passes.nim 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the passes functionality. A pass must implement the
  10. ## `TPass` interface.
  11. import
  12. options, ast, llstream, msgs,
  13. idents,
  14. syntaxes, modulegraphs, reorder,
  15. lineinfos,
  16. pipelineutils,
  17. modules, pathutils, packages,
  18. sem, semdata
  19. import ic/replayer
  20. export skipCodegen, resolveMod, prepareConfigNotes
  21. when defined(nimsuggest):
  22. import ../dist/checksums/src/checksums/sha1
  23. when defined(nimPreviewSlimSystem):
  24. import std/[syncio, assertions]
  25. import std/tables
  26. type
  27. TPassData* = tuple[input: PNode, closeOutput: PNode]
  28. # a pass is a tuple of procedure vars ``TPass.close`` may produce additional
  29. # nodes. These are passed to the other close procedures.
  30. # This mechanism used to be used for the instantiation of generics.
  31. proc makePass*(open: TPassOpen = nil,
  32. process: TPassProcess = nil,
  33. close: TPassClose = nil,
  34. isFrontend = false): TPass =
  35. result.open = open
  36. result.close = close
  37. result.process = process
  38. result.isFrontend = isFrontend
  39. const
  40. maxPasses = 10
  41. type
  42. TPassContextArray = array[0..maxPasses - 1, PPassContext]
  43. proc clearPasses*(g: ModuleGraph) =
  44. g.passes.setLen(0)
  45. proc registerPass*(g: ModuleGraph; p: TPass) =
  46. internalAssert g.config, g.passes.len < maxPasses
  47. g.passes.add(p)
  48. proc openPasses(g: ModuleGraph; a: var TPassContextArray;
  49. module: PSym; idgen: IdGenerator) =
  50. for i in 0..<g.passes.len:
  51. if not isNil(g.passes[i].open):
  52. a[i] = g.passes[i].open(g, module, idgen)
  53. else: a[i] = nil
  54. proc closePasses(graph: ModuleGraph; a: var TPassContextArray) =
  55. var m: PNode = nil
  56. for i in 0..<graph.passes.len:
  57. if not isNil(graph.passes[i].close):
  58. m = graph.passes[i].close(graph, a[i], m)
  59. a[i] = nil # free the memory here
  60. proc processTopLevelStmt(graph: ModuleGraph, n: PNode, a: var TPassContextArray): bool =
  61. # this implements the code transformation pipeline
  62. var m = n
  63. for i in 0..<graph.passes.len:
  64. if not isNil(graph.passes[i].process):
  65. m = graph.passes[i].process(a[i], m)
  66. if isNil(m): return false
  67. result = true
  68. proc processImplicits(graph: ModuleGraph; implicits: seq[string], nodeKind: TNodeKind,
  69. a: var TPassContextArray; m: PSym) =
  70. # XXX fixme this should actually be relative to the config file!
  71. let relativeTo = toFullPath(graph.config, m.info)
  72. for module in items(implicits):
  73. # implicit imports should not lead to a module importing itself
  74. if m.position != resolveMod(graph.config, module, relativeTo).int32:
  75. var importStmt = newNodeI(nodeKind, m.info)
  76. var str = newStrNode(nkStrLit, module)
  77. str.info = m.info
  78. importStmt.add str
  79. if not processTopLevelStmt(graph, importStmt, a): break
  80. proc processModule*(graph: ModuleGraph; module: PSym; idgen: IdGenerator;
  81. stream: PLLStream): bool {.discardable.} =
  82. if graph.stopCompile(): return true
  83. var
  84. p: Parser
  85. a: TPassContextArray
  86. s: PLLStream
  87. fileIdx = module.fileIdx
  88. prepareConfigNotes(graph, module)
  89. openPasses(graph, a, module, idgen)
  90. if stream == nil:
  91. let filename = toFullPathConsiderDirty(graph.config, fileIdx)
  92. s = llStreamOpen(filename, fmRead)
  93. if s == nil:
  94. rawMessage(graph.config, errCannotOpenFile, filename.string)
  95. return false
  96. else:
  97. s = stream
  98. when defined(nimsuggest):
  99. let filename = toFullPathConsiderDirty(graph.config, fileIdx).string
  100. msgs.setHash(graph.config, fileIdx, $sha1.secureHashFile(filename))
  101. while true:
  102. openParser(p, fileIdx, s, graph.cache, graph.config)
  103. if (not belongsToStdlib(graph, module)) or module.name.s == "distros":
  104. # XXX what about caching? no processing then? what if I change the
  105. # modules to include between compilation runs? we'd need to track that
  106. # in ROD files. I think we should enable this feature only
  107. # for the interactive mode.
  108. if module.name.s != "nimscriptapi":
  109. processImplicits graph, graph.config.implicitImports, nkImportStmt, a, module
  110. processImplicits graph, graph.config.implicitIncludes, nkIncludeStmt, a, module
  111. checkFirstLineIndentation(p)
  112. block processCode:
  113. if graph.stopCompile(): break processCode
  114. var n = parseTopLevelStmt(p)
  115. if n.kind == nkEmpty: break processCode
  116. # read everything, no streaming possible
  117. var sl = newNodeI(nkStmtList, n.info)
  118. sl.add n
  119. while true:
  120. var n = parseTopLevelStmt(p)
  121. if n.kind == nkEmpty: break
  122. sl.add n
  123. if sfReorder in module.flags or codeReordering in graph.config.features:
  124. sl = reorder(graph, sl, module)
  125. discard processTopLevelStmt(graph, sl, a)
  126. closeParser(p)
  127. if s.kind != llsStdIn: break
  128. closePasses(graph, a)
  129. if graph.config.backend notin {backendC, backendCpp, backendObjc}:
  130. # We only write rod files here if no C-like backend is active.
  131. # The C-like backends have been patched to support the IC mechanism.
  132. # They are responsible for closing the rod files. See `cbackend.nim`.
  133. closeRodFile(graph, module)
  134. result = true
  135. proc compileModule*(graph: ModuleGraph; fileIdx: FileIndex; flags: TSymFlags, fromModule: PSym = nil): PSym =
  136. var flags = flags
  137. if fileIdx == graph.config.projectMainIdx2: flags.incl sfMainModule
  138. result = graph.getModule(fileIdx)
  139. template processModuleAux(moduleStatus) =
  140. onProcessing(graph, fileIdx, moduleStatus, fromModule = fromModule)
  141. var s: PLLStream
  142. if sfMainModule in flags:
  143. if graph.config.projectIsStdin: s = stdin.llStreamOpen
  144. elif graph.config.projectIsCmd: s = llStreamOpen(graph.config.cmdInput)
  145. discard processModule(graph, result, idGeneratorFromModule(result), s)
  146. if result == nil:
  147. var cachedModules: seq[FileIndex]
  148. result = moduleFromRodFile(graph, fileIdx, cachedModules)
  149. let filename = AbsoluteFile toFullPath(graph.config, fileIdx)
  150. if result == nil:
  151. result = newModule(graph, fileIdx)
  152. result.flags.incl flags
  153. registerModule(graph, result)
  154. processModuleAux("import")
  155. else:
  156. if sfSystemModule in flags:
  157. graph.systemModule = result
  158. partialInitModule(result, graph, fileIdx, filename)
  159. for m in cachedModules:
  160. registerModuleById(graph, m)
  161. replayStateChanges(graph.packed[m.int].module, graph)
  162. replayGenericCacheInformation(graph, m.int)
  163. elif graph.isDirty(result):
  164. result.flags.excl sfDirty
  165. # reset module fields:
  166. initStrTables(graph, result)
  167. result.ast = nil
  168. processModuleAux("import(dirty)")
  169. graph.markClientsDirty(fileIdx)
  170. proc importModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PSym =
  171. # this is called by the semantic checking phase
  172. assert graph.config != nil
  173. result = compileModule(graph, fileIdx, {}, s)
  174. graph.addDep(s, fileIdx)
  175. # keep track of import relationships
  176. if graph.config.hcrOn:
  177. graph.importDeps.mgetOrPut(FileIndex(s.position), @[]).add(fileIdx)
  178. #if sfSystemModule in result.flags:
  179. # localError(result.info, errAttemptToRedefine, result.name.s)
  180. # restore the notes for outer module:
  181. graph.config.notes =
  182. if graph.config.belongsToProjectPackage(s) or isDefined(graph.config, "booting"): graph.config.mainPackageNotes
  183. else: graph.config.foreignPackageNotes
  184. proc connectCallbacks*(graph: ModuleGraph) =
  185. graph.includeFileCallback = modules.includeModule
  186. graph.importModuleCallback = importModule
  187. proc compileSystemModule*(graph: ModuleGraph) =
  188. if graph.systemModule == nil:
  189. connectCallbacks(graph)
  190. graph.config.m.systemFileIdx = fileInfoIdx(graph.config,
  191. graph.config.libpath / RelativeFile"system.nim")
  192. discard graph.compileModule(graph.config.m.systemFileIdx, {sfSystemModule})
  193. proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) =
  194. connectCallbacks(graph)
  195. let conf = graph.config
  196. wantMainModule(conf)
  197. configComplete(graph)
  198. let systemFileIdx = fileInfoIdx(conf, conf.libpath / RelativeFile"system.nim")
  199. let projectFile = if projectFileIdx == InvalidFileIdx: conf.projectMainIdx else: projectFileIdx
  200. conf.projectMainIdx2 = projectFile
  201. let packSym = getPackage(graph, projectFile)
  202. graph.config.mainPackageId = packSym.getPackageId
  203. graph.importStack.add projectFile
  204. if projectFile == systemFileIdx:
  205. discard graph.compileModule(projectFile, {sfMainModule, sfSystemModule})
  206. else:
  207. graph.compileSystemModule()
  208. discard graph.compileModule(projectFile, {sfMainModule})
  209. proc mySemOpen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
  210. result = preparePContext(graph, module, idgen)
  211. proc mySemClose(graph: ModuleGraph; context: PPassContext, n: PNode): PNode =
  212. var c = PContext(context)
  213. closePContext(graph, c, n)
  214. proc mySemProcess(context: PPassContext, n: PNode): PNode =
  215. result = semWithPContext(PContext(context), n)
  216. const semPass* = makePass(mySemOpen, mySemProcess, mySemClose,
  217. isFrontend = true)