main.nim 16 KB

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