modulegraphs.nim 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 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 module graph data structure. The module graph
  10. ## represents a complete Nim project. Single modules can either be kept in RAM
  11. ## or stored in a Sqlite database.
  12. ##
  13. ## The caching of modules is critical for 'nimsuggest' and is tricky to get
  14. ## right. If module E is being edited, we need autocompletion (and type
  15. ## checking) for E but we don't want to recompile depending
  16. ## modules right away for faster turnaround times. Instead we mark the module's
  17. ## dependencies as 'dirty'. Let D be a dependency of E. If D is dirty, we
  18. ## need to recompile it and all of its dependencies that are marked as 'dirty'.
  19. ## 'nimsuggest sug' actually is invoked for the file being edited so we know
  20. ## its content changed and there is no need to compute any checksums.
  21. ## Instead of a recursive algorithm, we use an iterative algorithm:
  22. ##
  23. ## - If a module gets recompiled, its dependencies need to be updated.
  24. ## - Its dependent module stays the same.
  25. ##
  26. import ast, intsets, tables, options, lineinfos, hashes, idents,
  27. incremental, btrees
  28. type
  29. ModuleGraph* = ref object
  30. modules*: seq[PSym] ## indexed by int32 fileIdx
  31. packageSyms*: TStrTable
  32. deps*: IntSet # the dependency graph or potentially its transitive closure.
  33. suggestMode*: bool # whether we are in nimsuggest mode or not.
  34. invalidTransitiveClosure: bool
  35. inclToMod*: Table[FileIndex, FileIndex] # mapping of include file to the
  36. # first module that included it
  37. importStack*: seq[FileIndex] # The current import stack. Used for detecting recursive
  38. # module dependencies.
  39. backend*: RootRef # minor hack so that a backend can extend this easily
  40. config*: ConfigRef
  41. cache*: IdentCache
  42. vm*: RootRef # unfortunately the 'vm' state is shared project-wise, this will
  43. # be clarified in later compiler implementations.
  44. doStopCompile*: proc(): bool {.closure.}
  45. usageSym*: PSym # for nimsuggest
  46. owners*: seq[PSym]
  47. methods*: seq[tuple[methods: seq[PSym], dispatcher: PSym]] # needs serialization!
  48. systemModule*: PSym
  49. sysTypes*: array[TTypeKind, PType]
  50. compilerprocs*: TStrTable
  51. exposed*: TStrTable
  52. intTypeCache*: array[-5..64, PType]
  53. opContains*, opNot*: PSym
  54. emptyNode*: PNode
  55. incr*: IncrementalCtx
  56. importModuleCallback*: proc (graph: ModuleGraph; m: PSym, fileIdx: FileIndex): PSym {.nimcall.}
  57. includeFileCallback*: proc (graph: ModuleGraph; m: PSym, fileIdx: FileIndex): PNode {.nimcall.}
  58. recordStmt*: proc (graph: ModuleGraph; m: PSym; n: PNode) {.nimcall.}
  59. cacheSeqs*: Table[string, PNode] # state that is shared to suppor the 'macrocache' API
  60. cacheCounters*: Table[string, BiggestInt]
  61. cacheTables*: Table[string, BTree[string, PNode]]
  62. passes*: seq[TPass]
  63. onDefinition*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  64. onDefinitionResolveForward*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  65. onUsage*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  66. TPassContext* = object of RootObj # the pass's context
  67. PPassContext* = ref TPassContext
  68. TPassOpen* = proc (graph: ModuleGraph; module: PSym): PPassContext {.nimcall.}
  69. TPassClose* = proc (graph: ModuleGraph; p: PPassContext, n: PNode): PNode {.nimcall.}
  70. TPassProcess* = proc (p: PPassContext, topLevelStmt: PNode): PNode {.nimcall.}
  71. TPass* = tuple[open: TPassOpen,
  72. process: TPassProcess,
  73. close: TPassClose,
  74. isFrontend: bool]
  75. proc hash*(x: FileIndex): Hash {.borrow.}
  76. when defined(nimfind):
  77. template onUse*(info: TLineInfo; s: PSym) =
  78. when compiles(c.c.graph):
  79. if c.c.graph.onUsage != nil: c.c.graph.onUsage(c.c.graph, s, info)
  80. else:
  81. if c.graph.onUsage != nil: c.graph.onUsage(c.graph, s, info)
  82. template onDef*(info: TLineInfo; s: PSym) =
  83. when compiles(c.c.graph):
  84. if c.c.graph.onDefinition != nil: c.c.graph.onDefinition(c.c.graph, s, info)
  85. else:
  86. if c.graph.onDefinition != nil: c.graph.onDefinition(c.graph, s, info)
  87. template onDefResolveForward*(info: TLineInfo; s: PSym) =
  88. when compiles(c.c.graph):
  89. if c.c.graph.onDefinitionResolveForward != nil:
  90. c.c.graph.onDefinitionResolveForward(c.c.graph, s, info)
  91. else:
  92. if c.graph.onDefinitionResolveForward != nil:
  93. c.graph.onDefinitionResolveForward(c.graph, s, info)
  94. else:
  95. template onUse*(info: TLineInfo; s: PSym) = discard
  96. template onDef*(info: TLineInfo; s: PSym) = discard
  97. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  98. proc stopCompile*(g: ModuleGraph): bool {.inline.} =
  99. result = g.doStopCompile != nil and g.doStopCompile()
  100. proc createMagic*(g: ModuleGraph; name: string, m: TMagic): PSym =
  101. result = newSym(skProc, getIdent(g.cache, name), nil, unknownLineInfo(), {})
  102. result.magic = m
  103. proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
  104. result = ModuleGraph()
  105. initStrTable(result.packageSyms)
  106. result.deps = initIntSet()
  107. result.modules = @[]
  108. result.importStack = @[]
  109. result.inclToMod = initTable[FileIndex, FileIndex]()
  110. result.config = config
  111. result.cache = cache
  112. result.owners = @[]
  113. result.methods = @[]
  114. initStrTable(result.compilerprocs)
  115. initStrTable(result.exposed)
  116. result.opNot = createMagic(result, "not", mNot)
  117. result.opContains = createMagic(result, "contains", mInSet)
  118. result.emptyNode = newNode(nkEmpty)
  119. init(result.incr)
  120. result.recordStmt = proc (graph: ModuleGraph; m: PSym; n: PNode) {.nimcall.} =
  121. discard
  122. result.cacheSeqs = initTable[string, PNode]()
  123. result.cacheCounters = initTable[string, BiggestInt]()
  124. result.cacheTables = initTable[string, BTree[string, PNode]]()
  125. proc resetAllModules*(g: ModuleGraph) =
  126. initStrTable(g.packageSyms)
  127. g.deps = initIntSet()
  128. g.modules = @[]
  129. g.importStack = @[]
  130. g.inclToMod = initTable[FileIndex, FileIndex]()
  131. g.usageSym = nil
  132. g.owners = @[]
  133. g.methods = @[]
  134. initStrTable(g.compilerprocs)
  135. initStrTable(g.exposed)
  136. proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
  137. if fileIdx.int32 >= 0 and fileIdx.int32 < g.modules.len:
  138. result = g.modules[fileIdx.int32]
  139. proc dependsOn(a, b: int): int {.inline.} = (a shl 15) + b
  140. proc addDep*(g: ModuleGraph; m: PSym, dep: FileIndex) =
  141. assert m.position == m.info.fileIndex.int32
  142. addModuleDep(g.incr, g.config, m.info.fileIndex, dep, isIncludeFile = false)
  143. if g.suggestMode:
  144. g.deps.incl m.position.dependsOn(dep.int)
  145. # we compute the transitive closure later when quering the graph lazily.
  146. # this improves efficiency quite a lot:
  147. #invalidTransitiveClosure = true
  148. proc addIncludeDep*(g: ModuleGraph; module, includeFile: FileIndex) =
  149. addModuleDep(g.incr, g.config, module, includeFile, isIncludeFile = true)
  150. discard hasKeyOrPut(g.inclToMod, includeFile, module)
  151. proc parentModule*(g: ModuleGraph; fileIdx: FileIndex): FileIndex =
  152. ## returns 'fileIdx' if the file belonging to this index is
  153. ## directly used as a module or else the module that first
  154. ## references this include file.
  155. if fileIdx.int32 >= 0 and fileIdx.int32 < g.modules.len and g.modules[fileIdx.int32] != nil:
  156. result = fileIdx
  157. else:
  158. result = g.inclToMod.getOrDefault(fileIdx)
  159. proc transitiveClosure(g: var IntSet; n: int) =
  160. # warshall's algorithm
  161. for k in 0..<n:
  162. for i in 0..<n:
  163. for j in 0..<n:
  164. if i != j and not g.contains(i.dependsOn(j)):
  165. if g.contains(i.dependsOn(k)) and g.contains(k.dependsOn(j)):
  166. g.incl i.dependsOn(j)
  167. proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  168. let m = g.getModule fileIdx
  169. if m != nil: incl m.flags, sfDirty
  170. proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  171. # we need to mark its dependent modules D as dirty right away because after
  172. # nimsuggest is done with this module, the module's dirty flag will be
  173. # cleared but D still needs to be remembered as 'dirty'.
  174. if g.invalidTransitiveClosure:
  175. g.invalidTransitiveClosure = false
  176. transitiveClosure(g.deps, g.modules.len)
  177. # every module that *depends* on this file is also dirty:
  178. for i in 0i32..<g.modules.len.int32:
  179. let m = g.modules[i]
  180. if m != nil and g.deps.contains(i.dependsOn(fileIdx.int)):
  181. incl m.flags, sfDirty
  182. proc isDirty*(g: ModuleGraph; m: PSym): bool =
  183. result = g.suggestMode and sfDirty in m.flags