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