modulegraphs.nim 10 KB

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