modulegraphs.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. proofEngine*: proc (graph: ModuleGraph; assumptions: seq[PNode]; toProve: PNode): (bool, string) {.nimcall.}
  72. requirementsCheck*: proc (graph: ModuleGraph; assumptions: seq[PNode];
  73. call, requirement: PNode): (bool, string) {.nimcall.}
  74. compatibleProps*: proc (graph: ModuleGraph; formal, actual: PType): bool {.nimcall.}
  75. TPassContext* = object of RootObj # the pass's context
  76. PPassContext* = ref TPassContext
  77. TPassOpen* = proc (graph: ModuleGraph; module: PSym): PPassContext {.nimcall.}
  78. TPassClose* = proc (graph: ModuleGraph; p: PPassContext, n: PNode): PNode {.nimcall.}
  79. TPassProcess* = proc (p: PPassContext, topLevelStmt: PNode): PNode {.nimcall.}
  80. TPass* = tuple[open: TPassOpen,
  81. process: TPassProcess,
  82. close: TPassClose,
  83. isFrontend: bool]
  84. const
  85. cb64 = [
  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. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
  89. "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
  90. "0", "1", "2", "3", "4", "5", "6", "7", "8", "9a",
  91. "9b", "9c"]
  92. proc toBase64a(s: cstring, len: int): string =
  93. ## encodes `s` into base64 representation.
  94. result = newStringOfCap(((len + 2) div 3) * 4)
  95. result.add "__"
  96. var i = 0
  97. while i < len - 2:
  98. let a = ord(s[i])
  99. let b = ord(s[i+1])
  100. let c = ord(s[i+2])
  101. result.add cb64[a shr 2]
  102. result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
  103. result.add cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)]
  104. result.add cb64[c and 0x3F]
  105. inc(i, 3)
  106. if i < len-1:
  107. let a = ord(s[i])
  108. let b = ord(s[i+1])
  109. result.add cb64[a shr 2]
  110. result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
  111. result.add cb64[((b and 0x0F) shl 2)]
  112. elif i < len:
  113. let a = ord(s[i])
  114. result.add cb64[a shr 2]
  115. result.add cb64[(a and 3) shl 4]
  116. proc `$`*(u: SigHash): string =
  117. toBase64a(cast[cstring](unsafeAddr u), sizeof(u))
  118. proc `==`*(a, b: SigHash): bool =
  119. result = equalMem(unsafeAddr a, unsafeAddr b, sizeof(a))
  120. proc hash*(u: SigHash): Hash =
  121. result = 0
  122. for x in 0..3:
  123. result = (result shl 8) or u.MD5Digest[x].int
  124. proc hash*(x: FileIndex): Hash {.borrow.}
  125. when defined(nimfind):
  126. template onUse*(info: TLineInfo; s: PSym) =
  127. when compiles(c.c.graph):
  128. if c.c.graph.onUsage != nil: c.c.graph.onUsage(c.c.graph, s, info)
  129. else:
  130. if c.graph.onUsage != nil: c.graph.onUsage(c.graph, s, info)
  131. template onDef*(info: TLineInfo; s: PSym) =
  132. when compiles(c.c.graph):
  133. if c.c.graph.onDefinition != nil: c.c.graph.onDefinition(c.c.graph, s, info)
  134. else:
  135. if c.graph.onDefinition != nil: c.graph.onDefinition(c.graph, s, info)
  136. template onDefResolveForward*(info: TLineInfo; s: PSym) =
  137. when compiles(c.c.graph):
  138. if c.c.graph.onDefinitionResolveForward != nil:
  139. c.c.graph.onDefinitionResolveForward(c.c.graph, s, info)
  140. else:
  141. if c.graph.onDefinitionResolveForward != nil:
  142. c.graph.onDefinitionResolveForward(c.graph, s, info)
  143. else:
  144. template onUse*(info: TLineInfo; s: PSym) = discard
  145. template onDef*(info: TLineInfo; s: PSym) = discard
  146. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  147. proc stopCompile*(g: ModuleGraph): bool {.inline.} =
  148. result = g.doStopCompile != nil and g.doStopCompile()
  149. proc createMagic*(g: ModuleGraph; name: string, m: TMagic): PSym =
  150. result = newSym(skProc, getIdent(g.cache, name), nil, unknownLineInfo, {})
  151. result.magic = m
  152. result.flags = {sfNeverRaises}
  153. proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
  154. result = ModuleGraph()
  155. initStrTable(result.packageSyms)
  156. result.deps = initIntSet()
  157. result.importDeps = initTable[FileIndex, seq[FileIndex]]()
  158. result.modules = @[]
  159. result.importStack = @[]
  160. result.inclToMod = initTable[FileIndex, FileIndex]()
  161. result.config = config
  162. result.cache = cache
  163. result.owners = @[]
  164. result.methods = @[]
  165. initStrTable(result.compilerprocs)
  166. initStrTable(result.exposed)
  167. result.opNot = createMagic(result, "not", mNot)
  168. result.opContains = createMagic(result, "contains", mInSet)
  169. result.emptyNode = newNode(nkEmpty)
  170. init(result.incr)
  171. result.recordStmt = proc (graph: ModuleGraph; m: PSym; n: PNode) {.nimcall.} =
  172. discard
  173. result.cacheSeqs = initTable[string, PNode]()
  174. result.cacheCounters = initTable[string, BiggestInt]()
  175. result.cacheTables = initTable[string, BTree[string, PNode]]()
  176. result.canonTypes = initTable[SigHash, PType]()
  177. result.symBodyHashes = initTable[int, SigHash]()
  178. proc resetAllModules*(g: ModuleGraph) =
  179. initStrTable(g.packageSyms)
  180. g.deps = initIntSet()
  181. g.modules = @[]
  182. g.importStack = @[]
  183. g.inclToMod = initTable[FileIndex, FileIndex]()
  184. g.usageSym = nil
  185. g.owners = @[]
  186. g.methods = @[]
  187. initStrTable(g.compilerprocs)
  188. initStrTable(g.exposed)
  189. proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
  190. if fileIdx.int32 >= 0 and fileIdx.int32 < g.modules.len:
  191. result = g.modules[fileIdx.int32]
  192. proc dependsOn(a, b: int): int {.inline.} = (a shl 15) + b
  193. proc addDep*(g: ModuleGraph; m: PSym, dep: FileIndex) =
  194. assert m.position == m.info.fileIndex.int32
  195. addModuleDep(g.incr, g.config, m.info.fileIndex, dep, isIncludeFile = false)
  196. if g.suggestMode:
  197. g.deps.incl m.position.dependsOn(dep.int)
  198. # we compute the transitive closure later when querying the graph lazily.
  199. # this improves efficiency quite a lot:
  200. #invalidTransitiveClosure = true
  201. proc addIncludeDep*(g: ModuleGraph; module, includeFile: FileIndex) =
  202. addModuleDep(g.incr, g.config, module, includeFile, isIncludeFile = true)
  203. discard hasKeyOrPut(g.inclToMod, includeFile, module)
  204. proc parentModule*(g: ModuleGraph; fileIdx: FileIndex): FileIndex =
  205. ## returns 'fileIdx' if the file belonging to this index is
  206. ## directly used as a module or else the module that first
  207. ## references this include file.
  208. if fileIdx.int32 >= 0 and fileIdx.int32 < g.modules.len and g.modules[fileIdx.int32] != nil:
  209. result = fileIdx
  210. else:
  211. result = g.inclToMod.getOrDefault(fileIdx)
  212. proc transitiveClosure(g: var IntSet; n: int) =
  213. # warshall's algorithm
  214. for k in 0..<n:
  215. for i in 0..<n:
  216. for j in 0..<n:
  217. if i != j and not g.contains(i.dependsOn(j)):
  218. if g.contains(i.dependsOn(k)) and g.contains(k.dependsOn(j)):
  219. g.incl i.dependsOn(j)
  220. proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  221. let m = g.getModule fileIdx
  222. if m != nil: incl m.flags, sfDirty
  223. proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  224. # we need to mark its dependent modules D as dirty right away because after
  225. # nimsuggest is done with this module, the module's dirty flag will be
  226. # cleared but D still needs to be remembered as 'dirty'.
  227. if g.invalidTransitiveClosure:
  228. g.invalidTransitiveClosure = false
  229. transitiveClosure(g.deps, g.modules.len)
  230. # every module that *depends* on this file is also dirty:
  231. for i in 0i32..<g.modules.len.int32:
  232. let m = g.modules[i]
  233. if m != nil and g.deps.contains(i.dependsOn(fileIdx.int)):
  234. incl m.flags, sfDirty
  235. proc isDirty*(g: ModuleGraph; m: PSym): bool =
  236. result = g.suggestMode and sfDirty in m.flags