modulegraphs.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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, md5
  28. type
  29. SigHash* = distinct MD5Digest
  30. ModuleGraph* = ref object
  31. modules*: seq[PSym] ## indexed by int32 fileIdx
  32. packageSyms*: TStrTable
  33. deps*: IntSet # the dependency graph or potentially its transitive closure.
  34. importDeps*: Table[FileIndex, seq[FileIndex]] # explicit import module dependencies
  35. suggestMode*: bool # whether we are in nimsuggest mode or not.
  36. invalidTransitiveClosure: bool
  37. inclToMod*: Table[FileIndex, FileIndex] # mapping of include file to the
  38. # first module that included it
  39. importStack*: seq[FileIndex] # The current import stack. Used for detecting recursive
  40. # module dependencies.
  41. backend*: RootRef # minor hack so that a backend can extend this easily
  42. config*: ConfigRef
  43. cache*: IdentCache
  44. vm*: RootRef # unfortunately the 'vm' state is shared project-wise, this will
  45. # be clarified in later compiler implementations.
  46. doStopCompile*: proc(): bool {.closure.}
  47. usageSym*: PSym # for nimsuggest
  48. owners*: seq[PSym]
  49. methods*: seq[tuple[methods: seq[PSym], dispatcher: PSym]] # needs serialization!
  50. systemModule*: PSym
  51. sysTypes*: array[TTypeKind, PType]
  52. compilerprocs*: TStrTable
  53. exposed*: TStrTable
  54. intTypeCache*: array[-5..64, PType]
  55. opContains*, opNot*: PSym
  56. emptyNode*: PNode
  57. incr*: IncrementalCtx
  58. canonTypes*: Table[SigHash, PType]
  59. symBodyHashes*: Table[int, SigHash] # symId to digest mapping
  60. importModuleCallback*: proc (graph: ModuleGraph; m: PSym, fileIdx: FileIndex): PSym {.nimcall.}
  61. includeFileCallback*: proc (graph: ModuleGraph; m: PSym, fileIdx: FileIndex): PNode {.nimcall.}
  62. recordStmt*: proc (graph: ModuleGraph; m: PSym; n: PNode) {.nimcall.}
  63. cacheSeqs*: Table[string, PNode] # state that is shared to support the 'macrocache' API
  64. cacheCounters*: Table[string, BiggestInt]
  65. cacheTables*: Table[string, BTree[string, PNode]]
  66. passes*: seq[TPass]
  67. onDefinition*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  68. onDefinitionResolveForward*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  69. onUsage*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  70. globalDestructors*: seq[PNode]
  71. strongSemCheck*: proc (graph: ModuleGraph; owner: PSym; body: PNode) {.nimcall.}
  72. compatibleProps*: proc (graph: ModuleGraph; formal, actual: PType): bool {.nimcall.}
  73. TPassContext* = object of RootObj # the pass's context
  74. PPassContext* = ref TPassContext
  75. TPassOpen* = proc (graph: ModuleGraph; module: PSym): PPassContext {.nimcall.}
  76. TPassClose* = proc (graph: ModuleGraph; p: PPassContext, n: PNode): PNode {.nimcall.}
  77. TPassProcess* = proc (p: PPassContext, topLevelStmt: PNode): PNode {.nimcall.}
  78. TPass* = tuple[open: TPassOpen,
  79. process: TPassProcess,
  80. close: TPassClose,
  81. isFrontend: bool]
  82. const
  83. cb64 = [
  84. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
  85. "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
  86. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
  87. "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
  88. "0", "1", "2", "3", "4", "5", "6", "7", "8", "9a",
  89. "9b", "9c"]
  90. proc toBase64a(s: cstring, len: int): string =
  91. ## encodes `s` into base64 representation.
  92. result = newStringOfCap(((len + 2) div 3) * 4)
  93. result.add "__"
  94. var i = 0
  95. while i < len - 2:
  96. let a = ord(s[i])
  97. let b = ord(s[i+1])
  98. let c = ord(s[i+2])
  99. result.add cb64[a shr 2]
  100. result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
  101. result.add cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)]
  102. result.add cb64[c and 0x3F]
  103. inc(i, 3)
  104. if i < len-1:
  105. let a = ord(s[i])
  106. let b = ord(s[i+1])
  107. result.add cb64[a shr 2]
  108. result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
  109. result.add cb64[((b and 0x0F) shl 2)]
  110. elif i < len:
  111. let a = ord(s[i])
  112. result.add cb64[a shr 2]
  113. result.add cb64[(a and 3) shl 4]
  114. proc `$`*(u: SigHash): string =
  115. toBase64a(cast[cstring](unsafeAddr u), sizeof(u))
  116. proc `==`*(a, b: SigHash): bool =
  117. result = equalMem(unsafeAddr a, unsafeAddr b, sizeof(a))
  118. proc hash*(u: SigHash): Hash =
  119. result = 0
  120. for x in 0..3:
  121. result = (result shl 8) or u.MD5Digest[x].int
  122. proc hash*(x: FileIndex): Hash {.borrow.}
  123. when defined(nimfind):
  124. template onUse*(info: TLineInfo; s: PSym) =
  125. when compiles(c.c.graph):
  126. if c.c.graph.onUsage != nil: c.c.graph.onUsage(c.c.graph, s, info)
  127. else:
  128. if c.graph.onUsage != nil: c.graph.onUsage(c.graph, s, info)
  129. template onDef*(info: TLineInfo; s: PSym) =
  130. when compiles(c.c.graph):
  131. if c.c.graph.onDefinition != nil: c.c.graph.onDefinition(c.c.graph, s, info)
  132. else:
  133. if c.graph.onDefinition != nil: c.graph.onDefinition(c.graph, s, info)
  134. template onDefResolveForward*(info: TLineInfo; s: PSym) =
  135. when compiles(c.c.graph):
  136. if c.c.graph.onDefinitionResolveForward != nil:
  137. c.c.graph.onDefinitionResolveForward(c.c.graph, s, info)
  138. else:
  139. if c.graph.onDefinitionResolveForward != nil:
  140. c.graph.onDefinitionResolveForward(c.graph, s, info)
  141. else:
  142. template onUse*(info: TLineInfo; s: PSym) = discard
  143. template onDef*(info: TLineInfo; s: PSym) = discard
  144. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  145. proc stopCompile*(g: ModuleGraph): bool {.inline.} =
  146. result = g.doStopCompile != nil and g.doStopCompile()
  147. proc createMagic*(g: ModuleGraph; name: string, m: TMagic): PSym =
  148. result = newSym(skProc, getIdent(g.cache, name), nil, unknownLineInfo, {})
  149. result.magic = m
  150. result.flags = {sfNeverRaises}
  151. proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
  152. result = ModuleGraph()
  153. initStrTable(result.packageSyms)
  154. result.deps = initIntSet()
  155. result.importDeps = initTable[FileIndex, seq[FileIndex]]()
  156. result.modules = @[]
  157. result.importStack = @[]
  158. result.inclToMod = initTable[FileIndex, FileIndex]()
  159. result.config = config
  160. result.cache = cache
  161. result.owners = @[]
  162. result.methods = @[]
  163. initStrTable(result.compilerprocs)
  164. initStrTable(result.exposed)
  165. result.opNot = createMagic(result, "not", mNot)
  166. result.opContains = createMagic(result, "contains", mInSet)
  167. result.emptyNode = newNode(nkEmpty)
  168. init(result.incr)
  169. result.recordStmt = proc (graph: ModuleGraph; m: PSym; n: PNode) {.nimcall.} =
  170. discard
  171. result.cacheSeqs = initTable[string, PNode]()
  172. result.cacheCounters = initTable[string, BiggestInt]()
  173. result.cacheTables = initTable[string, BTree[string, PNode]]()
  174. result.canonTypes = initTable[SigHash, PType]()
  175. result.symBodyHashes = initTable[int, SigHash]()
  176. proc resetAllModules*(g: ModuleGraph) =
  177. initStrTable(g.packageSyms)
  178. g.deps = initIntSet()
  179. g.modules = @[]
  180. g.importStack = @[]
  181. g.inclToMod = initTable[FileIndex, FileIndex]()
  182. g.usageSym = nil
  183. g.owners = @[]
  184. g.methods = @[]
  185. initStrTable(g.compilerprocs)
  186. initStrTable(g.exposed)
  187. proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
  188. if fileIdx.int32 >= 0 and fileIdx.int32 < g.modules.len:
  189. result = g.modules[fileIdx.int32]
  190. proc dependsOn(a, b: int): int {.inline.} = (a shl 15) + b
  191. proc addDep*(g: ModuleGraph; m: PSym, dep: FileIndex) =
  192. assert m.position == m.info.fileIndex.int32
  193. addModuleDep(g.incr, g.config, m.info.fileIndex, dep, isIncludeFile = false)
  194. if g.suggestMode:
  195. g.deps.incl m.position.dependsOn(dep.int)
  196. # we compute the transitive closure later when querying the graph lazily.
  197. # this improves efficiency quite a lot:
  198. #invalidTransitiveClosure = true
  199. proc addIncludeDep*(g: ModuleGraph; module, includeFile: FileIndex) =
  200. addModuleDep(g.incr, g.config, module, includeFile, isIncludeFile = true)
  201. discard hasKeyOrPut(g.inclToMod, includeFile, module)
  202. proc parentModule*(g: ModuleGraph; fileIdx: FileIndex): FileIndex =
  203. ## returns 'fileIdx' if the file belonging to this index is
  204. ## directly used as a module or else the module that first
  205. ## references this include file.
  206. if fileIdx.int32 >= 0 and fileIdx.int32 < g.modules.len and g.modules[fileIdx.int32] != nil:
  207. result = fileIdx
  208. else:
  209. result = g.inclToMod.getOrDefault(fileIdx)
  210. proc transitiveClosure(g: var IntSet; n: int) =
  211. # warshall's algorithm
  212. for k in 0..<n:
  213. for i in 0..<n:
  214. for j in 0..<n:
  215. if i != j and not g.contains(i.dependsOn(j)):
  216. if g.contains(i.dependsOn(k)) and g.contains(k.dependsOn(j)):
  217. g.incl i.dependsOn(j)
  218. proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  219. let m = g.getModule fileIdx
  220. if m != nil: incl m.flags, sfDirty
  221. proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  222. # we need to mark its dependent modules D as dirty right away because after
  223. # nimsuggest is done with this module, the module's dirty flag will be
  224. # cleared but D still needs to be remembered as 'dirty'.
  225. if g.invalidTransitiveClosure:
  226. g.invalidTransitiveClosure = false
  227. transitiveClosure(g.deps, g.modules.len)
  228. # every module that *depends* on this file is also dirty:
  229. for i in 0i32..<g.modules.len.int32:
  230. let m = g.modules[i]
  231. if m != nil and g.deps.contains(i.dependsOn(fileIdx.int)):
  232. incl m.flags, sfDirty
  233. proc isDirty*(g: ModuleGraph; m: PSym): bool =
  234. result = g.suggestMode and sfDirty in m.flags