main.nim 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. idents, extccomp,
  17. cgen, nversion,
  18. platform, nimconf, depends,
  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. import pipelines
  26. when not defined(leanCompiler):
  27. import docgen
  28. proc writeDepsFile(g: ModuleGraph) =
  29. let fname = g.config.nimcacheDir / RelativeFile(g.config.projectName & ".deps")
  30. let f = open(fname.string, fmWrite)
  31. for m in g.ifaces:
  32. if m.module != nil:
  33. f.writeLine(toFullPath(g.config, m.module.position.FileIndex))
  34. for k in g.inclToMod.keys:
  35. if g.getModule(k).isNil: # don't repeat includes which are also modules
  36. f.writeLine(toFullPath(g.config, k))
  37. f.close()
  38. proc writeCMakeDepsFile(conf: ConfigRef) =
  39. ## write a list of C files for build systems like CMake.
  40. ## only updated when the C file list changes.
  41. let fname = getNimcacheDir(conf) / conf.outFile.changeFileExt("cdeps")
  42. # generate output files list
  43. var cfiles: seq[string] = @[]
  44. for it in conf.toCompile: cfiles.add(it.cname.string)
  45. let fileset = cfiles.toCountTable()
  46. # read old cfiles list
  47. var fl: File
  48. var prevset = initCountTable[string]()
  49. if open(fl, fname.string, fmRead):
  50. for line in fl.lines: prevset.inc(line)
  51. fl.close()
  52. # write cfiles out
  53. if fileset != prevset:
  54. fl = open(fname.string, fmWrite)
  55. for line in cfiles: fl.writeLine(line)
  56. fl.close()
  57. proc commandGenDepend(graph: ModuleGraph) =
  58. setPipeLinePass(graph, GenDependPass)
  59. compilePipelineProject(graph)
  60. let project = graph.config.projectFull
  61. writeDepsFile(graph)
  62. generateDot(graph, project)
  63. # dot in graphivz tool kit is required
  64. let graphvizDotPath = findExe("dot")
  65. if graphvizDotPath.len == 0:
  66. quit("gendepend: Graphviz's tool dot is required," &
  67. "see https://graphviz.org/download for downloading")
  68. execExternalProgram(graph.config, "dot -Tpng -o" &
  69. changeFileExt(project, "png").string &
  70. ' ' & changeFileExt(project, "dot").string)
  71. proc commandCheck(graph: ModuleGraph) =
  72. let conf = graph.config
  73. conf.setErrorMaxHighMaybe
  74. defineSymbol(conf.symbols, "nimcheck")
  75. if optWasNimscript in conf.globalOptions:
  76. defineSymbol(conf.symbols, "nimscript")
  77. defineSymbol(conf.symbols, "nimconfig")
  78. elif conf.backend == backendJs:
  79. setTarget(conf.target, osJS, cpuJS)
  80. setPipeLinePass(graph, SemPass)
  81. compilePipelineProject(graph)
  82. if conf.symbolFiles != disabledSf:
  83. case conf.ideCmd
  84. of ideDef: navDefinition(graph)
  85. of ideUse: navUsages(graph)
  86. of ideDus: navDefusages(graph)
  87. else: discard
  88. writeRodFiles(graph)
  89. when not defined(leanCompiler):
  90. proc commandDoc2(graph: ModuleGraph; ext: string) =
  91. handleDocOutputOptions graph.config
  92. graph.config.setErrorMaxHighMaybe
  93. case ext:
  94. of TexExt:
  95. setPipeLinePass(graph, Docgen2TexPass)
  96. of JsonExt:
  97. setPipeLinePass(graph, Docgen2JsonPass)
  98. of HtmlExt:
  99. setPipeLinePass(graph, Docgen2Pass)
  100. else: doAssert false, $ext
  101. compilePipelineProject(graph)
  102. proc commandCompileToC(graph: ModuleGraph) =
  103. let conf = graph.config
  104. extccomp.initVars(conf)
  105. if conf.symbolFiles == disabledSf:
  106. if {optRun, optForceFullMake} * conf.globalOptions == {optRun} or isDefined(conf, "nimBetterRun"):
  107. if not changeDetectedViaJsonBuildInstructions(conf, conf.jsonBuildInstructionsFile):
  108. # nothing changed
  109. graph.config.notes = graph.config.mainPackageNotes
  110. return
  111. if not extccomp.ccHasSaneOverflow(conf):
  112. conf.symbols.defineSymbol("nimEmulateOverflowChecks")
  113. if conf.symbolFiles == disabledSf:
  114. setPipeLinePass(graph, CgenPass)
  115. else:
  116. setPipeLinePass(graph, SemPass)
  117. compilePipelineProject(graph)
  118. if graph.config.errorCounter > 0:
  119. return # issue #9933
  120. if conf.symbolFiles == disabledSf:
  121. cgenWriteModules(graph.backend, conf)
  122. else:
  123. if isDefined(conf, "nimIcIntegrityChecks"):
  124. checkIntegrity(graph)
  125. generateCode(graph)
  126. # graph.backend can be nil under IC when nothing changed at all:
  127. if graph.backend != nil:
  128. cgenWriteModules(graph.backend, conf)
  129. if conf.cmd != cmdTcc and graph.backend != nil:
  130. extccomp.callCCompiler(conf)
  131. # for now we do not support writing out a .json file with the build instructions when HCR is on
  132. if not conf.hcrOn:
  133. extccomp.writeJsonBuildInstructions(conf)
  134. if optGenScript in graph.config.globalOptions:
  135. writeDepsFile(graph)
  136. if optGenCDeps in graph.config.globalOptions:
  137. writeCMakeDepsFile(conf)
  138. proc commandJsonScript(graph: ModuleGraph) =
  139. extccomp.runJsonBuildInstructions(graph.config, graph.config.jsonBuildInstructionsFile)
  140. proc commandCompileToJS(graph: ModuleGraph) =
  141. let conf = graph.config
  142. when defined(leanCompiler):
  143. globalError(conf, unknownLineInfo, "compiler wasn't built with JS code generator")
  144. else:
  145. conf.exc = excCpp
  146. setTarget(conf.target, osJS, cpuJS)
  147. defineSymbol(conf.symbols, "ecmascript") # For backward compatibility
  148. setPipeLinePass(graph, JSgenPass)
  149. compilePipelineProject(graph)
  150. if optGenScript in conf.globalOptions:
  151. writeDepsFile(graph)
  152. proc commandInteractive(graph: ModuleGraph) =
  153. graph.config.setErrorMaxHighMaybe
  154. initDefines(graph.config.symbols)
  155. defineSymbol(graph.config.symbols, "nimscript")
  156. # note: seems redundant with -d:nimHasLibFFI
  157. when hasFFI: defineSymbol(graph.config.symbols, "nimffi")
  158. setPipeLinePass(graph, InterpreterPass)
  159. compilePipelineSystemModule(graph)
  160. if graph.config.commandArgs.len > 0:
  161. discard graph.compilePipelineModule(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. discard processPipelineModule(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. conf.lastCmdTime = epochTime()
  215. conf.searchPaths.add(conf.libpath)
  216. proc customizeForBackend(backend: TBackend) =
  217. ## Sets backend specific options but don't compile to backend yet in
  218. ## case command doesn't require it. This must be called by all commands.
  219. if conf.backend == backendInvalid:
  220. # only set if wasn't already set, to allow override via `nim c -b:cpp`
  221. conf.backend = backend
  222. defineSymbol(graph.config.symbols, $conf.backend)
  223. case conf.backend
  224. of backendC:
  225. if conf.exc == excNone: conf.exc = excSetjmp
  226. of backendCpp:
  227. if conf.exc == excNone: conf.exc = excCpp
  228. of backendObjc: discard
  229. of backendJs:
  230. if conf.hcrOn:
  231. # XXX: At the moment, system.nim cannot be compiled in JS mode
  232. # with "-d:useNimRtl". The HCR option has been processed earlier
  233. # and it has added this define implictly, so we must undo that here.
  234. # A better solution might be to fix system.nim
  235. undefSymbol(conf.symbols, "useNimRtl")
  236. of backendInvalid: doAssert false
  237. proc compileToBackend() =
  238. customizeForBackend(conf.backend)
  239. setOutFile(conf)
  240. case conf.backend
  241. of backendC: commandCompileToC(graph)
  242. of backendCpp: commandCompileToC(graph)
  243. of backendObjc: commandCompileToC(graph)
  244. of backendJs: commandCompileToJS(graph)
  245. of backendInvalid: doAssert false
  246. template docLikeCmd(body) =
  247. when defined(leanCompiler):
  248. conf.quitOrRaise "compiler wasn't built with documentation generator"
  249. else:
  250. wantMainModule(conf)
  251. let docConf = if conf.cmd == cmdDoc2tex: DocTexConfig else: DocConfig
  252. loadConfigs(docConf, cache, conf, graph.idgen)
  253. defineSymbol(conf.symbols, "nimdoc")
  254. body
  255. ## command prepass
  256. if conf.cmd == cmdCrun: conf.globalOptions.incl {optRun, optUseNimcache}
  257. if conf.cmd notin cmdBackends + {cmdTcc}: customizeForBackend(backendC)
  258. if conf.outDir.isEmpty:
  259. # doc like commands can generate a lot of files (especially with --project)
  260. # so by default should not end up in $PWD nor in $projectPath.
  261. var ret = if optUseNimcache in conf.globalOptions: getNimcacheDir(conf)
  262. else: conf.projectPath
  263. doAssert ret.string.isAbsolute # `AbsoluteDir` is not a real guarantee
  264. if conf.cmd in cmdDocLike + {cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex}:
  265. ret = ret / htmldocsDir
  266. conf.outDir = ret
  267. ## process all commands
  268. case conf.cmd
  269. of cmdBackends: compileToBackend()
  270. of cmdTcc:
  271. when hasTinyCBackend:
  272. extccomp.setCC(conf, "tcc", unknownLineInfo)
  273. if conf.backend != backendC:
  274. rawMessage(conf, errGenerated, "'run' requires c backend, got: '$1'" % $conf.backend)
  275. compileToBackend()
  276. else:
  277. rawMessage(conf, errGenerated, "'run' command not available; rebuild with -d:tinyc")
  278. of cmdDoc0: docLikeCmd commandDoc(cache, conf)
  279. of cmdDoc:
  280. docLikeCmd():
  281. conf.setNoteDefaults(warnRstRedefinitionOfLabel, false) # issue #13218
  282. # because currently generates lots of false positives due to conflation
  283. # of labels links in doc comments, e.g. for random.rand:
  284. # ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer
  285. # ## * `rand proc<#rand,Rand,range[]>`_ that returns a float
  286. commandDoc2(graph, HtmlExt)
  287. if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
  288. commandBuildIndex(conf, $conf.outDir)
  289. of cmdRst2html, cmdMd2html:
  290. # XXX: why are warnings disabled by default for rst2html and rst2tex?
  291. for warn in rstWarnings:
  292. conf.setNoteDefaults(warn, true)
  293. conf.setNoteDefaults(warnRstRedefinitionOfLabel, false) # similar to issue #13218
  294. when defined(leanCompiler):
  295. conf.quitOrRaise "compiler wasn't built with documentation generator"
  296. else:
  297. loadConfigs(DocConfig, cache, conf, graph.idgen)
  298. commandRst2Html(cache, conf, preferMarkdown = (conf.cmd == cmdMd2html))
  299. of cmdRst2tex, cmdMd2tex, cmdDoc2tex:
  300. for warn in rstWarnings:
  301. conf.setNoteDefaults(warn, true)
  302. when defined(leanCompiler):
  303. conf.quitOrRaise "compiler wasn't built with documentation generator"
  304. else:
  305. if conf.cmd in {cmdRst2tex, cmdMd2tex}:
  306. loadConfigs(DocTexConfig, cache, conf, graph.idgen)
  307. commandRst2TeX(cache, conf, preferMarkdown = (conf.cmd == cmdMd2tex))
  308. else:
  309. docLikeCmd commandDoc2(graph, TexExt)
  310. of cmdJsondoc0: docLikeCmd commandJson(cache, conf)
  311. of cmdJsondoc:
  312. docLikeCmd():
  313. commandDoc2(graph, JsonExt)
  314. if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
  315. commandBuildIndexJson(conf, $conf.outDir)
  316. of cmdCtags: docLikeCmd commandTags(cache, conf)
  317. of cmdBuildindex: docLikeCmd commandBuildIndex(conf, $conf.projectFull, conf.outFile)
  318. of cmdGendepend: commandGenDepend(graph)
  319. of cmdDump:
  320. if getConfigVar(conf, "dump.format") == "json":
  321. wantMainModule(conf)
  322. var definedSymbols = newJArray()
  323. for s in definedSymbolNames(conf.symbols): definedSymbols.elems.add(%s)
  324. var libpaths = newJArray()
  325. var lazyPaths = newJArray()
  326. for dir in conf.searchPaths: libpaths.elems.add(%dir.string)
  327. for dir in conf.lazyPaths: lazyPaths.elems.add(%dir.string)
  328. var hints = newJObject() # consider factoring with `listHints`
  329. for a in hintMin..hintMax:
  330. hints[$a] = %(a in conf.notes)
  331. var warnings = newJObject()
  332. for a in warnMin..warnMax:
  333. warnings[$a] = %(a in conf.notes)
  334. var dumpdata = %[
  335. (key: "version", val: %VersionAsString),
  336. (key: "nimExe", val: %(getAppFilename())),
  337. (key: "prefixdir", val: %conf.getPrefixDir().string),
  338. (key: "libpath", val: %conf.libpath.string),
  339. (key: "project_path", val: %conf.projectFull.string),
  340. (key: "defined_symbols", val: definedSymbols),
  341. (key: "lib_paths", val: %libpaths),
  342. (key: "lazyPaths", val: %lazyPaths),
  343. (key: "outdir", val: %conf.outDir.string),
  344. (key: "out", val: %conf.outFile.string),
  345. (key: "nimcache", val: %getNimcacheDir(conf).string),
  346. (key: "hints", val: hints),
  347. (key: "warnings", val: warnings),
  348. ]
  349. msgWriteln(conf, $dumpdata, {msgStdout, msgSkipHook, msgNoUnitSep})
  350. # `msgNoUnitSep` to avoid generating invalid json, refs bug #17853
  351. else:
  352. msgWriteln(conf, "-- list of currently defined symbols --",
  353. {msgStdout, msgSkipHook, msgNoUnitSep})
  354. for s in definedSymbolNames(conf.symbols): msgWriteln(conf, s, {msgStdout, msgSkipHook, msgNoUnitSep})
  355. msgWriteln(conf, "-- end of list --", {msgStdout, msgSkipHook})
  356. for it in conf.searchPaths: msgWriteln(conf, it.string)
  357. of cmdCheck:
  358. commandCheck(graph)
  359. of cmdParse:
  360. wantMainModule(conf)
  361. discard parseFile(conf.projectMainIdx, cache, conf)
  362. of cmdRod:
  363. wantMainModule(conf)
  364. commandView(graph)
  365. #msgWriteln(conf, "Beware: Indentation tokens depend on the parser's state!")
  366. of cmdInteractive: commandInteractive(graph)
  367. of cmdNimscript:
  368. if conf.projectIsCmd or conf.projectIsStdin: discard
  369. elif not fileExists(conf.projectFull):
  370. rawMessage(conf, errGenerated, "NimScript file does not exist: " & conf.projectFull.string)
  371. # main NimScript logic handled in `loadConfigs`.
  372. of cmdNop: discard
  373. of cmdJsonscript:
  374. setOutFile(graph.config)
  375. commandJsonScript(graph)
  376. of cmdUnknown, cmdNone, cmdIdeTools, cmdNimfix:
  377. rawMessage(conf, errGenerated, "invalid command: " & conf.command)
  378. if conf.errorCounter == 0 and conf.cmd notin {cmdTcc, cmdDump, cmdNop}:
  379. if optProfileVM in conf.globalOptions:
  380. echo conf.dump(conf.vmProfileData)
  381. genSuccessX(conf)
  382. when PrintRopeCacheStats:
  383. echo "rope cache stats: "
  384. echo " tries : ", gCacheTries
  385. echo " misses: ", gCacheMisses
  386. echo " int tries: ", gCacheIntTries
  387. echo " efficiency: ", formatFloat(1-(gCacheMisses.float/gCacheTries.float),
  388. ffDecimal, 3)