main.nim 16 KB

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