passes.nim 7.0 KB

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