nimeval.nim 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2018 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## exposes the Nim VM to clients.
  10. import
  11. ast, astalgo, modules, passes, condsyms,
  12. options, sem, llstream, lineinfos, vm,
  13. vmdef, modulegraphs, idents, os, pathutils,
  14. passaux, scriptconfig, std/compilesettings
  15. type
  16. Interpreter* = ref object ## Use Nim as an interpreter with this object
  17. mainModule: PSym
  18. graph: ModuleGraph
  19. scriptName: string
  20. idgen: IdGenerator
  21. iterator exportedSymbols*(i: Interpreter): PSym =
  22. assert i != nil
  23. assert i.mainModule != nil, "no main module selected"
  24. for s in modulegraphs.allSyms(i.graph, i.mainModule):
  25. yield s
  26. proc selectUniqueSymbol*(i: Interpreter; name: string;
  27. symKinds: set[TSymKind] = {skLet, skVar}): PSym =
  28. ## Can be used to access a unique symbol of ``name`` and
  29. ## the given ``symKinds`` filter.
  30. assert i != nil
  31. assert i.mainModule != nil, "no main module selected"
  32. let n = getIdent(i.graph.cache, name)
  33. var it: ModuleIter
  34. var s = initModuleIter(it, i.graph, i.mainModule, n)
  35. result = nil
  36. while s != nil:
  37. if s.kind in symKinds:
  38. if result == nil: result = s
  39. else: return nil # ambiguous
  40. s = nextModuleIter(it, i.graph)
  41. proc selectRoutine*(i: Interpreter; name: string): PSym =
  42. ## Selects a declared routine (proc/func/etc) from the main module.
  43. ## The routine needs to have the export marker ``*``. The only matching
  44. ## routine is returned and ``nil`` if it is overloaded.
  45. result = selectUniqueSymbol(i, name, {skTemplate, skMacro, skFunc,
  46. skMethod, skProc, skConverter})
  47. proc callRoutine*(i: Interpreter; routine: PSym; args: openArray[PNode]): PNode =
  48. assert i != nil
  49. result = vm.execProc(PCtx i.graph.vm, routine, args)
  50. proc getGlobalValue*(i: Interpreter; letOrVar: PSym): PNode =
  51. result = vm.getGlobalValue(PCtx i.graph.vm, letOrVar)
  52. proc setGlobalValue*(i: Interpreter; letOrVar: PSym, val: PNode) =
  53. ## Sets a global value to a given PNode, does not do any type checking.
  54. vm.setGlobalValue(PCtx i.graph.vm, letOrVar, val)
  55. proc implementRoutine*(i: Interpreter; pkg, module, name: string;
  56. impl: proc (a: VmArgs) {.closure, gcsafe.}) =
  57. assert i != nil
  58. let vm = PCtx(i.graph.vm)
  59. vm.registerCallback(pkg & "." & module & "." & name, impl)
  60. proc evalScript*(i: Interpreter; scriptStream: PLLStream = nil) =
  61. ## This can also be used to *reload* the script.
  62. assert i != nil
  63. assert i.mainModule != nil, "no main module selected"
  64. initStrTables(i.graph, i.mainModule)
  65. i.mainModule.ast = nil
  66. let s = if scriptStream != nil: scriptStream
  67. else: llStreamOpen(findFile(i.graph.config, i.scriptName), fmRead)
  68. processModule(i.graph, i.mainModule, i.idgen, s)
  69. proc findNimStdLib*(): string =
  70. ## Tries to find a path to a valid "system.nim" file.
  71. ## Returns "" on failure.
  72. try:
  73. let nimexe = os.findExe("nim")
  74. # this can't work with choosenim shims, refs https://github.com/dom96/choosenim/issues/189
  75. # it'd need `nim dump --dump.format:json . | jq -r .libpath`
  76. # which we should simplify as `nim dump --key:libpath`
  77. if nimexe.len == 0: return ""
  78. result = nimexe.splitPath()[0] /../ "lib"
  79. if not fileExists(result / "system.nim"):
  80. when defined(unix):
  81. result = nimexe.expandSymlink.splitPath()[0] /../ "lib"
  82. if not fileExists(result / "system.nim"): return ""
  83. except OSError, ValueError:
  84. return ""
  85. proc findNimStdLibCompileTime*(): string =
  86. ## Same as `findNimStdLib` but uses source files used at compile time,
  87. ## and asserts on error.
  88. result = querySetting(libPath)
  89. doAssert fileExists(result / "system.nim"), "result:" & result
  90. proc createInterpreter*(scriptName: string;
  91. searchPaths: openArray[string];
  92. flags: TSandboxFlags = {},
  93. defines = @[("nimscript", "true")],
  94. registerOps = true): Interpreter =
  95. var conf = newConfigRef()
  96. var cache = newIdentCache()
  97. var graph = newModuleGraph(cache, conf)
  98. connectCallbacks(graph)
  99. initDefines(conf.symbols)
  100. for define in defines:
  101. defineSymbol(conf.symbols, define[0], define[1])
  102. registerPass(graph, semPass)
  103. registerPass(graph, evalPass)
  104. for p in searchPaths:
  105. conf.searchPaths.add(AbsoluteDir p)
  106. if conf.libpath.isEmpty: conf.libpath = AbsoluteDir p
  107. var m = graph.makeModule(scriptName)
  108. incl(m.flags, sfMainModule)
  109. var idgen = idGeneratorFromModule(m)
  110. var vm = newCtx(m, cache, graph, idgen)
  111. vm.mode = emRepl
  112. vm.features = flags
  113. if registerOps:
  114. vm.registerAdditionalOps() # Required to register parts of stdlib modules
  115. graph.vm = vm
  116. graph.compileSystemModule()
  117. result = Interpreter(mainModule: m, graph: graph, scriptName: scriptName, idgen: idgen)
  118. proc destroyInterpreter*(i: Interpreter) =
  119. ## destructor.
  120. discard "currently nothing to do."
  121. proc registerErrorHook*(i: Interpreter, hook:
  122. proc (config: ConfigRef; info: TLineInfo; msg: string;
  123. severity: Severity) {.gcsafe.}) =
  124. i.graph.config.structuredErrorHook = hook
  125. proc runRepl*(r: TLLRepl;
  126. searchPaths: openArray[string];
  127. supportNimscript: bool) =
  128. ## deadcode but please don't remove... might be revived
  129. var conf = newConfigRef()
  130. var cache = newIdentCache()
  131. var graph = newModuleGraph(cache, conf)
  132. for p in searchPaths:
  133. conf.searchPaths.add(AbsoluteDir p)
  134. if conf.libpath.isEmpty: conf.libpath = AbsoluteDir p
  135. conf.cmd = cmdInteractive # see also `setCmd`
  136. conf.setErrorMaxHighMaybe
  137. initDefines(conf.symbols)
  138. defineSymbol(conf.symbols, "nimscript")
  139. if supportNimscript: defineSymbol(conf.symbols, "nimconfig")
  140. when hasFFI: defineSymbol(graph.config.symbols, "nimffi")
  141. registerPass(graph, verbosePass)
  142. registerPass(graph, semPass)
  143. registerPass(graph, evalPass)
  144. var m = graph.makeStdinModule()
  145. incl(m.flags, sfMainModule)
  146. var idgen = idGeneratorFromModule(m)
  147. if supportNimscript: graph.vm = setupVM(m, cache, "stdin", graph, idgen)
  148. graph.compileSystemModule()
  149. processModule(graph, m, idgen, llStreamOpenStdIn(r))