passes.nim 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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, pathutils, std/sha1, packages
  16. when defined(nimPreviewSlimSystem):
  17. import std/syncio
  18. type
  19. TPassData* = tuple[input: PNode, closeOutput: PNode]
  20. # a pass is a tuple of procedure vars ``TPass.close`` may produce additional
  21. # nodes. These are passed to the other close procedures.
  22. # This mechanism used to be used for the instantiation of generics.
  23. proc makePass*(open: TPassOpen = nil,
  24. process: TPassProcess = nil,
  25. close: TPassClose = nil,
  26. isFrontend = false): TPass =
  27. result.open = open
  28. result.close = close
  29. result.process = process
  30. result.isFrontend = isFrontend
  31. proc skipCodegen*(config: ConfigRef; n: PNode): bool {.inline.} =
  32. # can be used by codegen passes to determine whether they should do
  33. # something with `n`. Currently, this ignores `n` and uses the global
  34. # error count instead.
  35. result = config.errorCounter > 0
  36. const
  37. maxPasses = 10
  38. type
  39. TPassContextArray = array[0..maxPasses - 1, PPassContext]
  40. proc clearPasses*(g: ModuleGraph) =
  41. g.passes.setLen(0)
  42. proc registerPass*(g: ModuleGraph; p: TPass) =
  43. internalAssert g.config, g.passes.len < maxPasses
  44. g.passes.add(p)
  45. proc openPasses(g: ModuleGraph; a: var TPassContextArray;
  46. module: PSym; idgen: IdGenerator) =
  47. for i in 0..<g.passes.len:
  48. if not isNil(g.passes[i].open):
  49. a[i] = g.passes[i].open(g, module, idgen)
  50. else: a[i] = nil
  51. proc closePasses(graph: ModuleGraph; a: var TPassContextArray) =
  52. var m: PNode = nil
  53. for i in 0..<graph.passes.len:
  54. if not isNil(graph.passes[i].close):
  55. m = graph.passes[i].close(graph, a[i], m)
  56. a[i] = nil # free the memory here
  57. proc processTopLevelStmt(graph: ModuleGraph, n: PNode, a: var TPassContextArray): bool =
  58. # this implements the code transformation pipeline
  59. var m = n
  60. for i in 0..<graph.passes.len:
  61. if not isNil(graph.passes[i].process):
  62. m = graph.passes[i].process(a[i], m)
  63. if isNil(m): return false
  64. result = true
  65. proc resolveMod(conf: ConfigRef; module, relativeTo: string): FileIndex =
  66. let fullPath = findModule(conf, module, relativeTo)
  67. if fullPath.isEmpty:
  68. result = InvalidFileIdx
  69. else:
  70. result = fileInfoIdx(conf, fullPath)
  71. proc processImplicits(graph: ModuleGraph; implicits: seq[string], nodeKind: TNodeKind,
  72. a: var TPassContextArray; m: PSym) =
  73. # XXX fixme this should actually be relative to the config file!
  74. let relativeTo = toFullPath(graph.config, m.info)
  75. for module in items(implicits):
  76. # implicit imports should not lead to a module importing itself
  77. if m.position != resolveMod(graph.config, module, relativeTo).int32:
  78. var importStmt = newNodeI(nodeKind, m.info)
  79. var str = newStrNode(nkStrLit, module)
  80. str.info = m.info
  81. importStmt.add str
  82. if not processTopLevelStmt(graph, importStmt, a): break
  83. const
  84. imperativeCode = {low(TNodeKind)..high(TNodeKind)} - {nkTemplateDef, nkProcDef, nkMethodDef,
  85. nkMacroDef, nkConverterDef, nkIteratorDef, nkFuncDef, nkPragma,
  86. nkExportStmt, nkExportExceptStmt, nkFromStmt, nkImportStmt, nkImportExceptStmt}
  87. proc prepareConfigNotes(graph: ModuleGraph; module: PSym) =
  88. # don't be verbose unless the module belongs to the main package:
  89. if graph.config.belongsToProjectPackage(module):
  90. graph.config.notes = graph.config.mainPackageNotes
  91. else:
  92. if graph.config.mainPackageNotes == {}: graph.config.mainPackageNotes = graph.config.notes
  93. graph.config.notes = graph.config.foreignPackageNotes
  94. proc moduleHasChanged*(graph: ModuleGraph; module: PSym): bool {.inline.} =
  95. result = true
  96. #module.id >= 0 or isDefined(graph.config, "nimBackendAssumesChange")
  97. proc processModule*(graph: ModuleGraph; module: PSym; idgen: IdGenerator;
  98. stream: PLLStream): bool {.discardable.} =
  99. if graph.stopCompile(): return true
  100. var
  101. p: Parser
  102. a: TPassContextArray
  103. s: PLLStream
  104. fileIdx = module.fileIdx
  105. prepareConfigNotes(graph, module)
  106. openPasses(graph, a, module, idgen)
  107. if stream == nil:
  108. let filename = toFullPathConsiderDirty(graph.config, fileIdx)
  109. s = llStreamOpen(filename, fmRead)
  110. if s == nil:
  111. rawMessage(graph.config, errCannotOpenFile, filename.string)
  112. return false
  113. else:
  114. s = stream
  115. when defined(nimsuggest):
  116. let filename = toFullPathConsiderDirty(graph.config, fileIdx).string
  117. msgs.setHash(graph.config, fileIdx, $sha1.secureHashFile(filename))
  118. while true:
  119. openParser(p, fileIdx, s, graph.cache, graph.config)
  120. if not belongsToStdlib(graph, module) or (belongsToStdlib(graph, module) and module.name.s == "distros"):
  121. # XXX what about caching? no processing then? what if I change the
  122. # modules to include between compilation runs? we'd need to track that
  123. # in ROD files. I think we should enable this feature only
  124. # for the interactive mode.
  125. if module.name.s != "nimscriptapi":
  126. processImplicits graph, graph.config.implicitImports, nkImportStmt, a, module
  127. processImplicits graph, graph.config.implicitIncludes, nkIncludeStmt, a, module
  128. checkFirstLineIndentation(p)
  129. while true:
  130. if graph.stopCompile(): break
  131. var n = parseTopLevelStmt(p)
  132. if n.kind == nkEmpty: break
  133. if (sfSystemModule notin module.flags and
  134. ({sfNoForward, sfReorder} * module.flags != {} or
  135. codeReordering in graph.config.features)):
  136. # read everything, no streaming possible
  137. var sl = newNodeI(nkStmtList, n.info)
  138. sl.add n
  139. while true:
  140. var n = parseTopLevelStmt(p)
  141. if n.kind == nkEmpty: break
  142. sl.add n
  143. if sfReorder in module.flags or codeReordering in graph.config.features:
  144. sl = reorder(graph, sl, module)
  145. discard processTopLevelStmt(graph, sl, a)
  146. break
  147. elif n.kind in imperativeCode:
  148. # read everything until the next proc declaration etc.
  149. var sl = newNodeI(nkStmtList, n.info)
  150. sl.add n
  151. var rest: PNode = nil
  152. while true:
  153. var n = parseTopLevelStmt(p)
  154. if n.kind == nkEmpty or n.kind notin imperativeCode:
  155. rest = n
  156. break
  157. sl.add n
  158. #echo "-----\n", sl
  159. if not processTopLevelStmt(graph, sl, a): break
  160. if rest != nil:
  161. #echo "-----\n", rest
  162. if not processTopLevelStmt(graph, rest, a): break
  163. else:
  164. #echo "----- single\n", n
  165. if not processTopLevelStmt(graph, n, a): break
  166. closeParser(p)
  167. if s.kind != llsStdIn: break
  168. closePasses(graph, a)
  169. if graph.config.backend notin {backendC, backendCpp, backendObjc}:
  170. # We only write rod files here if no C-like backend is active.
  171. # The C-like backends have been patched to support the IC mechanism.
  172. # They are responsible for closing the rod files. See `cbackend.nim`.
  173. closeRodFile(graph, module)
  174. result = true