main.nim 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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, ic]
  24. import ../dist/checksums/src/checksums/sha1
  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 = default(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: raiseAssert $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, graph.cachedFiles)
  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 = default(Lexer)
  174. tok: Token = default(Token)
  175. openLexer(L, f, stream, cache, config)
  176. while true:
  177. rawGetTok(L, tok)
  178. printTok(config, tok)
  179. if tok.tokType == tkEof: break
  180. closeLexer(L)
  181. else:
  182. rawMessage(config, errGenerated, "cannot open file: " & f.string)
  183. proc commandView(graph: ModuleGraph) =
  184. let f = toAbsolute(mainCommandArg(graph.config), AbsoluteDir getCurrentDir()).addFileExt(RodExt)
  185. rodViewer(f, graph.config, graph.cache)
  186. const
  187. PrintRopeCacheStats = false
  188. proc hashMainCompilationParams*(conf: ConfigRef): string =
  189. ## doesn't have to be complete; worst case is a cache hit and recompilation.
  190. var state = newSha1State()
  191. with state:
  192. update os.getAppFilename() # nim compiler
  193. update conf.commandLine # excludes `arguments`, as it should
  194. update $conf.projectFull # so that running `nim r main` from 2 directories caches differently
  195. result = $SecureHash(state.finalize())
  196. proc setOutFile*(conf: ConfigRef) =
  197. proc libNameTmpl(conf: ConfigRef): string {.inline.} =
  198. result = if conf.target.targetOS == osWindows: "$1.lib" else: "lib$1.a"
  199. if conf.outFile.isEmpty:
  200. var base = conf.projectName
  201. if optUseNimcache in conf.globalOptions:
  202. base.add "_" & hashMainCompilationParams(conf)
  203. let targetName =
  204. if conf.backend == backendJs: base & ".js"
  205. elif optGenDynLib in conf.globalOptions:
  206. platform.OS[conf.target.targetOS].dllFrmt % base
  207. elif optGenStaticLib in conf.globalOptions: libNameTmpl(conf) % base
  208. else: base & platform.OS[conf.target.targetOS].exeExt
  209. conf.outFile = RelativeFile targetName
  210. proc mainCommand*(graph: ModuleGraph) =
  211. let conf = graph.config
  212. let cache = graph.cache
  213. conf.lastCmdTime = epochTime()
  214. conf.searchPaths.add(conf.libpath)
  215. proc customizeForBackend(backend: TBackend) =
  216. ## Sets backend specific options but don't compile to backend yet in
  217. ## case command doesn't require it. This must be called by all commands.
  218. if conf.backend == backendInvalid:
  219. # only set if wasn't already set, to allow override via `nim c -b:cpp`
  220. conf.backend = backend
  221. defineSymbol(graph.config.symbols, $conf.backend)
  222. case conf.backend
  223. of backendC:
  224. if conf.exc == excNone: conf.exc = excSetjmp
  225. of backendCpp:
  226. if conf.exc == excNone: conf.exc = excCpp
  227. of backendObjc: discard
  228. of backendJs:
  229. if conf.hcrOn:
  230. # XXX: At the moment, system.nim cannot be compiled in JS mode
  231. # with "-d:useNimRtl". The HCR option has been processed earlier
  232. # and it has added this define implictly, so we must undo that here.
  233. # A better solution might be to fix system.nim
  234. undefSymbol(conf.symbols, "useNimRtl")
  235. of backendInvalid: raiseAssert "unreachable"
  236. proc compileToBackend() =
  237. customizeForBackend(conf.backend)
  238. setOutFile(conf)
  239. case conf.backend
  240. of backendC: commandCompileToC(graph)
  241. of backendCpp: commandCompileToC(graph)
  242. of backendObjc: commandCompileToC(graph)
  243. of backendJs: commandCompileToJS(graph)
  244. of backendInvalid: raiseAssert "unreachable"
  245. template docLikeCmd(body) =
  246. when defined(leanCompiler):
  247. conf.quitOrRaise "compiler wasn't built with documentation generator"
  248. else:
  249. wantMainModule(conf)
  250. let docConf = if conf.cmd == cmdDoc2tex: DocTexConfig else: DocConfig
  251. loadConfigs(docConf, cache, conf, graph.idgen)
  252. defineSymbol(conf.symbols, "nimdoc")
  253. body
  254. ## command prepass
  255. if conf.cmd == cmdCrun: conf.globalOptions.incl {optRun, optUseNimcache}
  256. if conf.cmd notin cmdBackends + {cmdTcc}: customizeForBackend(backendC)
  257. if conf.outDir.isEmpty:
  258. # doc like commands can generate a lot of files (especially with --project)
  259. # so by default should not end up in $PWD nor in $projectPath.
  260. var ret = if optUseNimcache in conf.globalOptions: getNimcacheDir(conf)
  261. else: conf.projectPath
  262. if not ret.string.isAbsolute: # `AbsoluteDir` is not a real guarantee
  263. rawMessage(conf, errCannotOpenFile, ret.string & "/")
  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:
  270. compileToBackend()
  271. when BenchIC:
  272. echoTimes graph.packed
  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 cmdM:
  363. graph.config.symbolFiles = v2Sf
  364. setUseIc(graph.config.symbolFiles != disabledSf)
  365. commandCheck(graph)
  366. of cmdParse:
  367. wantMainModule(conf)
  368. discard parseFile(conf.projectMainIdx, cache, conf)
  369. of cmdRod:
  370. wantMainModule(conf)
  371. commandView(graph)
  372. #msgWriteln(conf, "Beware: Indentation tokens depend on the parser's state!")
  373. of cmdInteractive: commandInteractive(graph)
  374. of cmdNimscript:
  375. if conf.projectIsCmd or conf.projectIsStdin: discard
  376. elif not fileExists(conf.projectFull):
  377. rawMessage(conf, errGenerated, "NimScript file does not exist: " & conf.projectFull.string)
  378. # main NimScript logic handled in `loadConfigs`.
  379. of cmdNop: discard
  380. of cmdJsonscript:
  381. setOutFile(graph.config)
  382. commandJsonScript(graph)
  383. of cmdUnknown, cmdNone, cmdIdeTools:
  384. rawMessage(conf, errGenerated, "invalid command: " & conf.command)
  385. if conf.errorCounter == 0 and conf.cmd notin {cmdTcc, cmdDump, cmdNop}:
  386. if optProfileVM in conf.globalOptions:
  387. echo conf.dump(conf.vmProfileData)
  388. genSuccessX(conf)
  389. when PrintRopeCacheStats:
  390. echo "rope cache stats: "
  391. echo " tries : ", gCacheTries
  392. echo " misses: ", gCacheMisses
  393. echo " int tries: ", gCacheIntTries
  394. echo " efficiency: ", formatFloat(1-(gCacheMisses.float/gCacheTries.float),
  395. ffDecimal, 3)