main.nim 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # implements the command dispatcher and several commands
  10. when not defined(nimcore):
  11. {.error: "nimcore MUST be defined for Nim's core tooling".}
  12. import
  13. std/[strutils, os, times, tables, sha1, with, json],
  14. llstream, ast, lexer, syntaxes, options, msgs,
  15. condsyms,
  16. sem, idents, passes, extccomp,
  17. cgen, nversion,
  18. platform, nimconf, passaux, depends, vm,
  19. modules,
  20. modulegraphs, lineinfos, pathutils, vmprofiler
  21. when defined(nimPreviewSlimSystem):
  22. import std/[syncio, assertions]
  23. import ic / [cbackend, integrity, navigator]
  24. from ic / ic import rodViewer
  25. when not defined(leanCompiler):
  26. import jsgen, docgen, docgen2
  27. proc semanticPasses(g: ModuleGraph) =
  28. registerPass g, verbosePass
  29. registerPass g, semPass
  30. proc writeDepsFile(g: ModuleGraph) =
  31. let fname = g.config.nimcacheDir / RelativeFile(g.config.projectName & ".deps")
  32. let f = open(fname.string, fmWrite)
  33. for m in g.ifaces:
  34. if m.module != nil:
  35. f.writeLine(toFullPath(g.config, m.module.position.FileIndex))
  36. for k in g.inclToMod.keys:
  37. if g.getModule(k).isNil: # don't repeat includes which are also modules
  38. f.writeLine(toFullPath(g.config, k))
  39. f.close()
  40. proc commandGenDepend(graph: ModuleGraph) =
  41. semanticPasses(graph)
  42. registerPass(graph, gendependPass)
  43. compileProject(graph)
  44. let project = graph.config.projectFull
  45. writeDepsFile(graph)
  46. generateDot(graph, project)
  47. execExternalProgram(graph.config, "dot -Tpng -o" &
  48. changeFileExt(project, "png").string &
  49. ' ' & changeFileExt(project, "dot").string)
  50. proc commandCheck(graph: ModuleGraph) =
  51. let conf = graph.config
  52. conf.setErrorMaxHighMaybe
  53. defineSymbol(conf.symbols, "nimcheck")
  54. if optWasNimscript in conf.globalOptions:
  55. defineSymbol(conf.symbols, "nimscript")
  56. defineSymbol(conf.symbols, "nimconfig")
  57. elif conf.backend == backendJs:
  58. setTarget(conf.target, osJS, cpuJS)
  59. semanticPasses(graph) # use an empty backend for semantic checking only
  60. compileProject(graph)
  61. if conf.symbolFiles != disabledSf:
  62. case conf.ideCmd
  63. of ideDef: navDefinition(graph)
  64. of ideUse: navUsages(graph)
  65. of ideDus: navDefusages(graph)
  66. else: discard
  67. writeRodFiles(graph)
  68. when not defined(leanCompiler):
  69. proc commandDoc2(graph: ModuleGraph; ext: string) =
  70. handleDocOutputOptions graph.config
  71. graph.config.setErrorMaxHighMaybe
  72. semanticPasses(graph)
  73. case ext:
  74. of TexExt: registerPass(graph, docgen2TexPass)
  75. of JsonExt: registerPass(graph, docgen2JsonPass)
  76. of HtmlExt: registerPass(graph, docgen2Pass)
  77. else: doAssert false, $ext
  78. compileProject(graph)
  79. finishDoc2Pass(graph.config.projectName)
  80. proc commandCompileToC(graph: ModuleGraph) =
  81. let conf = graph.config
  82. extccomp.initVars(conf)
  83. semanticPasses(graph)
  84. if conf.symbolFiles == disabledSf:
  85. registerPass(graph, cgenPass)
  86. if {optRun, optForceFullMake} * conf.globalOptions == {optRun} or isDefined(conf, "nimBetterRun"):
  87. if not changeDetectedViaJsonBuildInstructions(conf, conf.jsonBuildInstructionsFile):
  88. # nothing changed
  89. graph.config.notes = graph.config.mainPackageNotes
  90. return
  91. if not extccomp.ccHasSaneOverflow(conf):
  92. conf.symbols.defineSymbol("nimEmulateOverflowChecks")
  93. compileProject(graph)
  94. if graph.config.errorCounter > 0:
  95. return # issue #9933
  96. if conf.symbolFiles == disabledSf:
  97. cgenWriteModules(graph.backend, conf)
  98. else:
  99. if isDefined(conf, "nimIcIntegrityChecks"):
  100. checkIntegrity(graph)
  101. generateCode(graph)
  102. # graph.backend can be nil under IC when nothing changed at all:
  103. if graph.backend != nil:
  104. cgenWriteModules(graph.backend, conf)
  105. if conf.cmd != cmdTcc and graph.backend != nil:
  106. extccomp.callCCompiler(conf)
  107. # for now we do not support writing out a .json file with the build instructions when HCR is on
  108. if not conf.hcrOn:
  109. extccomp.writeJsonBuildInstructions(conf)
  110. if optGenScript in graph.config.globalOptions:
  111. writeDepsFile(graph)
  112. proc commandJsonScript(graph: ModuleGraph) =
  113. extccomp.runJsonBuildInstructions(graph.config, graph.config.jsonBuildInstructionsFile)
  114. proc commandCompileToJS(graph: ModuleGraph) =
  115. let conf = graph.config
  116. when defined(leanCompiler):
  117. globalError(conf, unknownLineInfo, "compiler wasn't built with JS code generator")
  118. else:
  119. conf.exc = excCpp
  120. setTarget(conf.target, osJS, cpuJS)
  121. defineSymbol(conf.symbols, "ecmascript") # For backward compatibility
  122. semanticPasses(graph)
  123. registerPass(graph, JSgenPass)
  124. compileProject(graph)
  125. if optGenScript in conf.globalOptions:
  126. writeDepsFile(graph)
  127. proc interactivePasses(graph: ModuleGraph) =
  128. initDefines(graph.config.symbols)
  129. defineSymbol(graph.config.symbols, "nimscript")
  130. # note: seems redundant with -d:nimHasLibFFI
  131. when hasFFI: defineSymbol(graph.config.symbols, "nimffi")
  132. registerPass(graph, verbosePass)
  133. registerPass(graph, semPass)
  134. registerPass(graph, evalPass)
  135. proc commandInteractive(graph: ModuleGraph) =
  136. graph.config.setErrorMaxHighMaybe
  137. interactivePasses(graph)
  138. compileSystemModule(graph)
  139. if graph.config.commandArgs.len > 0:
  140. discard graph.compileModule(fileInfoIdx(graph.config, graph.config.projectFull), {})
  141. else:
  142. var m = graph.makeStdinModule()
  143. incl(m.flags, sfMainModule)
  144. var idgen = IdGenerator(module: m.itemId.module, symId: m.itemId.item, typeId: 0)
  145. let s = llStreamOpenStdIn(onPrompt = proc() = flushDot(graph.config))
  146. processModule(graph, m, idgen, s)
  147. proc commandScan(cache: IdentCache, config: ConfigRef) =
  148. var f = addFileExt(AbsoluteFile mainCommandArg(config), NimExt)
  149. var stream = llStreamOpen(f, fmRead)
  150. if stream != nil:
  151. var
  152. L: Lexer
  153. tok: Token
  154. initToken(tok)
  155. openLexer(L, f, stream, cache, config)
  156. while true:
  157. rawGetTok(L, tok)
  158. printTok(config, tok)
  159. if tok.tokType == tkEof: break
  160. closeLexer(L)
  161. else:
  162. rawMessage(config, errGenerated, "cannot open file: " & f.string)
  163. proc commandView(graph: ModuleGraph) =
  164. let f = toAbsolute(mainCommandArg(graph.config), AbsoluteDir getCurrentDir()).addFileExt(RodExt)
  165. rodViewer(f, graph.config, graph.cache)
  166. const
  167. PrintRopeCacheStats = false
  168. proc hashMainCompilationParams*(conf: ConfigRef): string =
  169. ## doesn't have to be complete; worst case is a cache hit and recompilation.
  170. var state = newSha1State()
  171. with state:
  172. update os.getAppFilename() # nim compiler
  173. update conf.commandLine # excludes `arguments`, as it should
  174. update $conf.projectFull # so that running `nim r main` from 2 directories caches differently
  175. result = $SecureHash(state.finalize())
  176. proc setOutFile*(conf: ConfigRef) =
  177. proc libNameTmpl(conf: ConfigRef): string {.inline.} =
  178. result = if conf.target.targetOS == osWindows: "$1.lib" else: "lib$1.a"
  179. if conf.outFile.isEmpty:
  180. var base = conf.projectName
  181. if optUseNimcache in conf.globalOptions:
  182. base.add "_" & hashMainCompilationParams(conf)
  183. let targetName =
  184. if conf.backend == backendJs: base & ".js"
  185. elif optGenDynLib in conf.globalOptions:
  186. platform.OS[conf.target.targetOS].dllFrmt % base
  187. elif optGenStaticLib in conf.globalOptions: libNameTmpl(conf) % base
  188. else: base & platform.OS[conf.target.targetOS].exeExt
  189. conf.outFile = RelativeFile targetName
  190. proc mainCommand*(graph: ModuleGraph) =
  191. let conf = graph.config
  192. let cache = graph.cache
  193. # In "nim serve" scenario, each command must reset the registered passes
  194. clearPasses(graph)
  195. conf.lastCmdTime = epochTime()
  196. conf.searchPaths.add(conf.libpath)
  197. proc customizeForBackend(backend: TBackend) =
  198. ## Sets backend specific options but don't compile to backend yet in
  199. ## case command doesn't require it. This must be called by all commands.
  200. if conf.backend == backendInvalid:
  201. # only set if wasn't already set, to allow override via `nim c -b:cpp`
  202. conf.backend = backend
  203. defineSymbol(graph.config.symbols, $conf.backend)
  204. case conf.backend
  205. of backendC:
  206. if conf.exc == excNone: conf.exc = excSetjmp
  207. of backendCpp:
  208. if conf.exc == excNone: conf.exc = excCpp
  209. of backendObjc: discard
  210. of backendJs:
  211. if conf.hcrOn:
  212. # XXX: At the moment, system.nim cannot be compiled in JS mode
  213. # with "-d:useNimRtl". The HCR option has been processed earlier
  214. # and it has added this define implictly, so we must undo that here.
  215. # A better solution might be to fix system.nim
  216. undefSymbol(conf.symbols, "useNimRtl")
  217. of backendInvalid: doAssert false
  218. proc compileToBackend() =
  219. customizeForBackend(conf.backend)
  220. setOutFile(conf)
  221. case conf.backend
  222. of backendC: commandCompileToC(graph)
  223. of backendCpp: commandCompileToC(graph)
  224. of backendObjc: commandCompileToC(graph)
  225. of backendJs: commandCompileToJS(graph)
  226. of backendInvalid: doAssert false
  227. template docLikeCmd(body) =
  228. when defined(leanCompiler):
  229. conf.quitOrRaise "compiler wasn't built with documentation generator"
  230. else:
  231. wantMainModule(conf)
  232. let docConf = if conf.cmd == cmdDoc2tex: DocTexConfig else: DocConfig
  233. loadConfigs(docConf, cache, conf, graph.idgen)
  234. defineSymbol(conf.symbols, "nimdoc")
  235. body
  236. ## command prepass
  237. if conf.cmd == cmdCrun: conf.globalOptions.incl {optRun, optUseNimcache}
  238. if conf.cmd notin cmdBackends + {cmdTcc}: customizeForBackend(backendC)
  239. if conf.outDir.isEmpty:
  240. # doc like commands can generate a lot of files (especially with --project)
  241. # so by default should not end up in $PWD nor in $projectPath.
  242. var ret = if optUseNimcache in conf.globalOptions: getNimcacheDir(conf)
  243. else: conf.projectPath
  244. doAssert ret.string.isAbsolute # `AbsoluteDir` is not a real guarantee
  245. if conf.cmd in cmdDocLike + {cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex}:
  246. ret = ret / htmldocsDir
  247. conf.outDir = ret
  248. ## process all commands
  249. case conf.cmd
  250. of cmdBackends: compileToBackend()
  251. of cmdTcc:
  252. when hasTinyCBackend:
  253. extccomp.setCC(conf, "tcc", unknownLineInfo)
  254. if conf.backend != backendC:
  255. rawMessage(conf, errGenerated, "'run' requires c backend, got: '$1'" % $conf.backend)
  256. compileToBackend()
  257. else:
  258. rawMessage(conf, errGenerated, "'run' command not available; rebuild with -d:tinyc")
  259. of cmdDoc0: docLikeCmd commandDoc(cache, conf)
  260. of cmdDoc:
  261. docLikeCmd():
  262. conf.setNoteDefaults(warnRstRedefinitionOfLabel, false) # issue #13218
  263. # because currently generates lots of false positives due to conflation
  264. # of labels links in doc comments, e.g. for random.rand:
  265. # ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer
  266. # ## * `rand proc<#rand,Rand,range[]>`_ that returns a float
  267. commandDoc2(graph, HtmlExt)
  268. if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
  269. commandBuildIndex(conf, $conf.outDir)
  270. of cmdRst2html, cmdMd2html:
  271. # XXX: why are warnings disabled by default for rst2html and rst2tex?
  272. for warn in rstWarnings:
  273. conf.setNoteDefaults(warn, true)
  274. conf.setNoteDefaults(warnRstRedefinitionOfLabel, false) # similar to issue #13218
  275. when defined(leanCompiler):
  276. conf.quitOrRaise "compiler wasn't built with documentation generator"
  277. else:
  278. loadConfigs(DocConfig, cache, conf, graph.idgen)
  279. commandRst2Html(cache, conf, preferMarkdown = (conf.cmd == cmdMd2html))
  280. of cmdRst2tex, cmdMd2tex, cmdDoc2tex:
  281. for warn in rstWarnings:
  282. conf.setNoteDefaults(warn, true)
  283. when defined(leanCompiler):
  284. conf.quitOrRaise "compiler wasn't built with documentation generator"
  285. else:
  286. if conf.cmd in {cmdRst2tex, cmdMd2tex}:
  287. loadConfigs(DocTexConfig, cache, conf, graph.idgen)
  288. commandRst2TeX(cache, conf, preferMarkdown = (conf.cmd == cmdMd2tex))
  289. else:
  290. docLikeCmd commandDoc2(graph, TexExt)
  291. of cmdJsondoc0: docLikeCmd commandJson(cache, conf)
  292. of cmdJsondoc:
  293. docLikeCmd():
  294. commandDoc2(graph, JsonExt)
  295. if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
  296. commandBuildIndexJson(conf, $conf.outDir)
  297. of cmdCtags: docLikeCmd commandTags(cache, conf)
  298. of cmdBuildindex: docLikeCmd commandBuildIndex(conf, $conf.projectFull, conf.outFile)
  299. of cmdGendepend: commandGenDepend(graph)
  300. of cmdDump:
  301. if getConfigVar(conf, "dump.format") == "json":
  302. wantMainModule(conf)
  303. var definedSymbols = newJArray()
  304. for s in definedSymbolNames(conf.symbols): definedSymbols.elems.add(%s)
  305. var libpaths = newJArray()
  306. var lazyPaths = newJArray()
  307. for dir in conf.searchPaths: libpaths.elems.add(%dir.string)
  308. for dir in conf.lazyPaths: lazyPaths.elems.add(%dir.string)
  309. var hints = newJObject() # consider factoring with `listHints`
  310. for a in hintMin..hintMax:
  311. hints[$a] = %(a in conf.notes)
  312. var warnings = newJObject()
  313. for a in warnMin..warnMax:
  314. warnings[$a] = %(a in conf.notes)
  315. var dumpdata = %[
  316. (key: "version", val: %VersionAsString),
  317. (key: "nimExe", val: %(getAppFilename())),
  318. (key: "prefixdir", val: %conf.getPrefixDir().string),
  319. (key: "libpath", val: %conf.libpath.string),
  320. (key: "project_path", val: %conf.projectFull.string),
  321. (key: "defined_symbols", val: definedSymbols),
  322. (key: "lib_paths", val: %libpaths),
  323. (key: "lazyPaths", val: %lazyPaths),
  324. (key: "outdir", val: %conf.outDir.string),
  325. (key: "out", val: %conf.outFile.string),
  326. (key: "nimcache", val: %getNimcacheDir(conf).string),
  327. (key: "hints", val: hints),
  328. (key: "warnings", val: warnings),
  329. ]
  330. msgWriteln(conf, $dumpdata, {msgStdout, msgSkipHook, msgNoUnitSep})
  331. # `msgNoUnitSep` to avoid generating invalid json, refs bug #17853
  332. else:
  333. msgWriteln(conf, "-- list of currently defined symbols --",
  334. {msgStdout, msgSkipHook, msgNoUnitSep})
  335. for s in definedSymbolNames(conf.symbols): msgWriteln(conf, s, {msgStdout, msgSkipHook, msgNoUnitSep})
  336. msgWriteln(conf, "-- end of list --", {msgStdout, msgSkipHook})
  337. for it in conf.searchPaths: msgWriteln(conf, it.string)
  338. of cmdCheck:
  339. commandCheck(graph)
  340. of cmdParse:
  341. wantMainModule(conf)
  342. discard parseFile(conf.projectMainIdx, cache, conf)
  343. of cmdRod:
  344. wantMainModule(conf)
  345. commandView(graph)
  346. #msgWriteln(conf, "Beware: Indentation tokens depend on the parser's state!")
  347. of cmdInteractive: commandInteractive(graph)
  348. of cmdNimscript:
  349. if conf.projectIsCmd or conf.projectIsStdin: discard
  350. elif not fileExists(conf.projectFull):
  351. rawMessage(conf, errGenerated, "NimScript file does not exist: " & conf.projectFull.string)
  352. # main NimScript logic handled in `loadConfigs`.
  353. of cmdNop: discard
  354. of cmdJsonscript:
  355. setOutFile(graph.config)
  356. commandJsonScript(graph)
  357. of cmdUnknown, cmdNone, cmdIdeTools, cmdNimfix:
  358. rawMessage(conf, errGenerated, "invalid command: " & conf.command)
  359. if conf.errorCounter == 0 and conf.cmd notin {cmdTcc, cmdDump, cmdNop}:
  360. if optProfileVM in conf.globalOptions:
  361. echo conf.dump(conf.vmProfileData)
  362. genSuccessX(conf)
  363. when PrintRopeCacheStats:
  364. echo "rope cache stats: "
  365. echo " tries : ", gCacheTries
  366. echo " misses: ", gCacheMisses
  367. echo " int tries: ", gCacheIntTries
  368. echo " efficiency: ", formatFloat(1-(gCacheMisses.float/gCacheTries.float),
  369. ffDecimal, 3)