modulegraphs.nim 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 rod-file.
  12. import intsets, tables, hashes
  13. import ../dist/checksums/src/checksums/md5
  14. import ast, astalgo, options, lineinfos,idents, btrees, ropes, msgs, pathutils, packages
  15. import ic / [packed_ast, ic]
  16. when defined(nimPreviewSlimSystem):
  17. import std/assertions
  18. type
  19. SigHash* = distinct MD5Digest
  20. LazySym* = object
  21. id*: FullId
  22. sym*: PSym
  23. Iface* = object ## data we don't want to store directly in the
  24. ## ast.PSym type for s.kind == skModule
  25. module*: PSym ## module this "Iface" belongs to
  26. converters*: seq[LazySym]
  27. patterns*: seq[LazySym]
  28. pureEnums*: seq[LazySym]
  29. interf: TStrTable
  30. interfHidden: TStrTable
  31. uniqueName*: Rope
  32. Operators* = object
  33. opNot*, opContains*, opLe*, opLt*, opAnd*, opOr*, opIsNil*, opEq*: PSym
  34. opAdd*, opSub*, opMul*, opDiv*, opLen*: PSym
  35. FullId* = object
  36. module*: int
  37. packed*: PackedItemId
  38. LazyType* = object
  39. id*: FullId
  40. typ*: PType
  41. LazyInstantiation* = object
  42. module*: int
  43. sym*: FullId
  44. concreteTypes*: seq[FullId]
  45. inst*: PInstantiation
  46. SymInfoPair* = object
  47. sym*: PSym
  48. info*: TLineInfo
  49. PipelinePass* = enum
  50. NonePass
  51. SemPass
  52. JSgenPass
  53. CgenPass
  54. EvalPass
  55. InterpreterPass
  56. GenDependPass
  57. Docgen2TexPass
  58. Docgen2JsonPass
  59. Docgen2Pass
  60. ModuleGraph* {.acyclic.} = ref object
  61. ifaces*: seq[Iface] ## indexed by int32 fileIdx
  62. packed*: PackedModuleGraph
  63. encoders*: seq[PackedEncoder]
  64. typeInstCache*: Table[ItemId, seq[LazyType]] # A symbol's ItemId.
  65. procInstCache*: Table[ItemId, seq[LazyInstantiation]] # A symbol's ItemId.
  66. attachedOps*: array[TTypeAttachedOp, Table[ItemId, LazySym]] # Type ID, destructors, etc.
  67. methodsPerType*: Table[ItemId, seq[(int, LazySym)]] # Type ID, attached methods
  68. memberProcsPerType*: Table[ItemId, seq[PSym]] # Type ID, attached member procs (only c++, virtual and ctor so far)
  69. enumToStringProcs*: Table[ItemId, LazySym]
  70. emittedTypeInfo*: Table[string, FileIndex]
  71. startupPackedConfig*: PackedConfig
  72. packageSyms*: TStrTable
  73. deps*: IntSet # the dependency graph or potentially its transitive closure.
  74. importDeps*: Table[FileIndex, seq[FileIndex]] # explicit import module dependencies
  75. suggestMode*: bool # whether we are in nimsuggest mode or not.
  76. invalidTransitiveClosure: bool
  77. inclToMod*: Table[FileIndex, FileIndex] # mapping of include file to the
  78. # first module that included it
  79. importStack*: seq[FileIndex] # The current import stack. Used for detecting recursive
  80. # module dependencies.
  81. backend*: RootRef # minor hack so that a backend can extend this easily
  82. config*: ConfigRef
  83. cache*: IdentCache
  84. vm*: RootRef # unfortunately the 'vm' state is shared project-wise, this will
  85. # be clarified in later compiler implementations.
  86. doStopCompile*: proc(): bool {.closure.}
  87. usageSym*: PSym # for nimsuggest
  88. owners*: seq[PSym]
  89. suggestSymbols*: Table[FileIndex, seq[SymInfoPair]]
  90. suggestErrors*: Table[FileIndex, seq[Suggest]]
  91. methods*: seq[tuple[methods: seq[PSym], dispatcher: PSym]] # needs serialization!
  92. systemModule*: PSym
  93. sysTypes*: array[TTypeKind, PType]
  94. compilerprocs*: TStrTable
  95. exposed*: TStrTable
  96. packageTypes*: TStrTable
  97. emptyNode*: PNode
  98. canonTypes*: Table[SigHash, PType]
  99. symBodyHashes*: Table[int, SigHash] # symId to digest mapping
  100. importModuleCallback*: proc (graph: ModuleGraph; m: PSym, fileIdx: FileIndex): PSym {.nimcall.}
  101. includeFileCallback*: proc (graph: ModuleGraph; m: PSym, fileIdx: FileIndex): PNode {.nimcall.}
  102. cacheSeqs*: Table[string, PNode] # state that is shared to support the 'macrocache' API; IC: implemented
  103. cacheCounters*: Table[string, BiggestInt] # IC: implemented
  104. cacheTables*: Table[string, BTree[string, PNode]] # IC: implemented
  105. passes*: seq[TPass]
  106. pipelinePass*: PipelinePass
  107. onDefinition*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  108. onDefinitionResolveForward*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  109. onUsage*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
  110. globalDestructors*: seq[PNode]
  111. strongSemCheck*: proc (graph: ModuleGraph; owner: PSym; body: PNode) {.nimcall.}
  112. compatibleProps*: proc (graph: ModuleGraph; formal, actual: PType): bool {.nimcall.}
  113. idgen*: IdGenerator
  114. operators*: Operators
  115. TPassContext* = object of RootObj # the pass's context
  116. idgen*: IdGenerator
  117. PPassContext* = ref TPassContext
  118. TPassOpen* = proc (graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.nimcall.}
  119. TPassClose* = proc (graph: ModuleGraph; p: PPassContext, n: PNode): PNode {.nimcall.}
  120. TPassProcess* = proc (p: PPassContext, topLevelStmt: PNode): PNode {.nimcall.}
  121. TPass* = tuple[open: TPassOpen,
  122. process: TPassProcess,
  123. close: TPassClose,
  124. isFrontend: bool]
  125. proc resetForBackend*(g: ModuleGraph) =
  126. g.compilerprocs = initStrTable()
  127. g.typeInstCache.clear()
  128. g.procInstCache.clear()
  129. for a in mitems(g.attachedOps):
  130. a.clear()
  131. g.methodsPerType.clear()
  132. g.enumToStringProcs.clear()
  133. const
  134. cb64 = [
  135. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
  136. "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
  137. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
  138. "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
  139. "0", "1", "2", "3", "4", "5", "6", "7", "8", "9a",
  140. "9b", "9c"]
  141. proc toBase64a(s: cstring, len: int): string =
  142. ## encodes `s` into base64 representation.
  143. result = newStringOfCap(((len + 2) div 3) * 4)
  144. result.add "__"
  145. var i = 0
  146. while i < len - 2:
  147. let a = ord(s[i])
  148. let b = ord(s[i+1])
  149. let c = ord(s[i+2])
  150. result.add cb64[a shr 2]
  151. result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
  152. result.add cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)]
  153. result.add cb64[c and 0x3F]
  154. inc(i, 3)
  155. if i < len-1:
  156. let a = ord(s[i])
  157. let b = ord(s[i+1])
  158. result.add cb64[a shr 2]
  159. result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
  160. result.add cb64[((b and 0x0F) shl 2)]
  161. elif i < len:
  162. let a = ord(s[i])
  163. result.add cb64[a shr 2]
  164. result.add cb64[(a and 3) shl 4]
  165. template interfSelect(iface: Iface, importHidden: bool): TStrTable =
  166. var ret = iface.interf.addr # without intermediate ptr, it creates a copy and compiler becomes 15x slower!
  167. if importHidden: ret = iface.interfHidden.addr
  168. ret[]
  169. template semtab(g: ModuleGraph, m: PSym): TStrTable =
  170. g.ifaces[m.position].interf
  171. template semtabAll*(g: ModuleGraph, m: PSym): TStrTable =
  172. g.ifaces[m.position].interfHidden
  173. proc initStrTables*(g: ModuleGraph, m: PSym) =
  174. semtab(g, m) = initStrTable()
  175. semtabAll(g, m) = initStrTable()
  176. proc strTableAdds*(g: ModuleGraph, m: PSym, s: PSym) =
  177. strTableAdd(semtab(g, m), s)
  178. strTableAdd(semtabAll(g, m), s)
  179. proc isCachedModule(g: ModuleGraph; module: int): bool {.inline.} =
  180. result = module < g.packed.len and g.packed[module].status == loaded
  181. proc isCachedModule(g: ModuleGraph; m: PSym): bool {.inline.} =
  182. isCachedModule(g, m.position)
  183. proc simulateCachedModule*(g: ModuleGraph; moduleSym: PSym; m: PackedModule) =
  184. when false:
  185. echo "simulating ", moduleSym.name.s, " ", moduleSym.position
  186. simulateLoadedModule(g.packed, g.config, g.cache, moduleSym, m)
  187. proc initEncoder*(g: ModuleGraph; module: PSym) =
  188. let id = module.position
  189. if id >= g.encoders.len:
  190. setLen g.encoders, id+1
  191. ic.initEncoder(g.encoders[id],
  192. g.packed[id].fromDisk, module, g.config, g.startupPackedConfig)
  193. type
  194. ModuleIter* = object
  195. fromRod: bool
  196. modIndex: int
  197. ti: TIdentIter
  198. rodIt: RodIter
  199. importHidden: bool
  200. proc initModuleIter*(mi: var ModuleIter; g: ModuleGraph; m: PSym; name: PIdent): PSym =
  201. assert m.kind == skModule
  202. mi.modIndex = m.position
  203. mi.fromRod = isCachedModule(g, mi.modIndex)
  204. mi.importHidden = optImportHidden in m.options
  205. if mi.fromRod:
  206. result = initRodIter(mi.rodIt, g.config, g.cache, g.packed, FileIndex mi.modIndex, name, mi.importHidden)
  207. else:
  208. result = initIdentIter(mi.ti, g.ifaces[mi.modIndex].interfSelect(mi.importHidden), name)
  209. proc nextModuleIter*(mi: var ModuleIter; g: ModuleGraph): PSym =
  210. if mi.fromRod:
  211. result = nextRodIter(mi.rodIt, g.packed)
  212. else:
  213. result = nextIdentIter(mi.ti, g.ifaces[mi.modIndex].interfSelect(mi.importHidden))
  214. iterator allSyms*(g: ModuleGraph; m: PSym): PSym =
  215. let importHidden = optImportHidden in m.options
  216. if isCachedModule(g, m):
  217. var rodIt: RodIter
  218. var r = initRodIterAllSyms(rodIt, g.config, g.cache, g.packed, FileIndex m.position, importHidden)
  219. while r != nil:
  220. yield r
  221. r = nextRodIter(rodIt, g.packed)
  222. else:
  223. for s in g.ifaces[m.position].interfSelect(importHidden).data:
  224. if s != nil:
  225. yield s
  226. proc someSym*(g: ModuleGraph; m: PSym; name: PIdent): PSym =
  227. let importHidden = optImportHidden in m.options
  228. if isCachedModule(g, m):
  229. result = interfaceSymbol(g.config, g.cache, g.packed, FileIndex(m.position), name, importHidden)
  230. else:
  231. result = strTableGet(g.ifaces[m.position].interfSelect(importHidden), name)
  232. proc systemModuleSym*(g: ModuleGraph; name: PIdent): PSym =
  233. result = someSym(g, g.systemModule, name)
  234. iterator systemModuleSyms*(g: ModuleGraph; name: PIdent): PSym =
  235. var mi: ModuleIter
  236. var r = initModuleIter(mi, g, g.systemModule, name)
  237. while r != nil:
  238. yield r
  239. r = nextModuleIter(mi, g)
  240. proc resolveType(g: ModuleGraph; t: var LazyType): PType =
  241. result = t.typ
  242. if result == nil and isCachedModule(g, t.id.module):
  243. result = loadTypeFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
  244. t.typ = result
  245. assert result != nil
  246. proc resolveSym(g: ModuleGraph; t: var LazySym): PSym =
  247. result = t.sym
  248. if result == nil and isCachedModule(g, t.id.module):
  249. result = loadSymFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
  250. t.sym = result
  251. assert result != nil
  252. proc resolveInst(g: ModuleGraph; t: var LazyInstantiation): PInstantiation =
  253. result = t.inst
  254. if result == nil and isCachedModule(g, t.module):
  255. result = PInstantiation(sym: loadSymFromId(g.config, g.cache, g.packed, t.sym.module, t.sym.packed))
  256. result.concreteTypes = newSeq[PType](t.concreteTypes.len)
  257. for i in 0..high(result.concreteTypes):
  258. result.concreteTypes[i] = loadTypeFromId(g.config, g.cache, g.packed,
  259. t.concreteTypes[i].module, t.concreteTypes[i].packed)
  260. t.inst = result
  261. assert result != nil
  262. proc resolveAttachedOp(g: ModuleGraph; t: var LazySym): PSym =
  263. result = t.sym
  264. if result == nil:
  265. result = loadSymFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
  266. t.sym = result
  267. assert result != nil
  268. iterator typeInstCacheItems*(g: ModuleGraph; s: PSym): PType =
  269. if g.typeInstCache.contains(s.itemId):
  270. let x = addr(g.typeInstCache[s.itemId])
  271. for t in mitems(x[]):
  272. yield resolveType(g, t)
  273. iterator procInstCacheItems*(g: ModuleGraph; s: PSym): PInstantiation =
  274. if g.procInstCache.contains(s.itemId):
  275. let x = addr(g.procInstCache[s.itemId])
  276. for t in mitems(x[]):
  277. yield resolveInst(g, t)
  278. proc getAttachedOp*(g: ModuleGraph; t: PType; op: TTypeAttachedOp): PSym =
  279. ## returns the requested attached operation for type `t`. Can return nil
  280. ## if no such operation exists.
  281. if g.attachedOps[op].contains(t.itemId):
  282. result = resolveAttachedOp(g, g.attachedOps[op][t.itemId])
  283. else:
  284. result = nil
  285. proc setAttachedOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  286. ## we also need to record this to the packed module.
  287. g.attachedOps[op][t.itemId] = LazySym(sym: value)
  288. proc setAttachedOpPartial*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  289. ## we also need to record this to the packed module.
  290. g.attachedOps[op][t.itemId] = LazySym(sym: value)
  291. proc completePartialOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  292. if g.config.symbolFiles != disabledSf:
  293. assert module < g.encoders.len
  294. assert isActive(g.encoders[module])
  295. toPackedGeneratedProcDef(value, g.encoders[module], g.packed[module].fromDisk)
  296. #storeAttachedProcDef(t, op, value, g.encoders[module], g.packed[module].fromDisk)
  297. proc getToStringProc*(g: ModuleGraph; t: PType): PSym =
  298. result = resolveSym(g, g.enumToStringProcs[t.itemId])
  299. assert result != nil
  300. proc setToStringProc*(g: ModuleGraph; t: PType; value: PSym) =
  301. g.enumToStringProcs[t.itemId] = LazySym(sym: value)
  302. iterator methodsForGeneric*(g: ModuleGraph; t: PType): (int, PSym) =
  303. if g.methodsPerType.contains(t.itemId):
  304. for it in mitems g.methodsPerType[t.itemId]:
  305. yield (it[0], resolveSym(g, it[1]))
  306. proc addMethodToGeneric*(g: ModuleGraph; module: int; t: PType; col: int; m: PSym) =
  307. g.methodsPerType.mgetOrPut(t.itemId, @[]).add (col, LazySym(sym: m))
  308. proc hasDisabledAsgn*(g: ModuleGraph; t: PType): bool =
  309. let op = getAttachedOp(g, t, attachedAsgn)
  310. result = op != nil and sfError in op.flags
  311. proc copyTypeProps*(g: ModuleGraph; module: int; dest, src: PType) =
  312. for k in low(TTypeAttachedOp)..high(TTypeAttachedOp):
  313. let op = getAttachedOp(g, src, k)
  314. if op != nil:
  315. setAttachedOp(g, module, dest, k, op)
  316. proc loadCompilerProc*(g: ModuleGraph; name: string): PSym =
  317. result = nil
  318. if g.config.symbolFiles == disabledSf: return nil
  319. # slow, linear search, but the results are cached:
  320. for module in 0..high(g.packed):
  321. #if isCachedModule(g, module):
  322. let x = searchForCompilerproc(g.packed[module], name)
  323. if x >= 0:
  324. result = loadSymFromId(g.config, g.cache, g.packed, module, toPackedItemId(x))
  325. if result != nil:
  326. strTableAdd(g.compilerprocs, result)
  327. return result
  328. proc loadPackedSym*(g: ModuleGraph; s: var LazySym) =
  329. if s.sym == nil:
  330. s.sym = loadSymFromId(g.config, g.cache, g.packed, s.id.module, s.id.packed)
  331. proc `$`*(u: SigHash): string =
  332. toBase64a(cast[cstring](unsafeAddr u), sizeof(u))
  333. proc `==`*(a, b: SigHash): bool =
  334. result = equalMem(unsafeAddr a, unsafeAddr b, sizeof(a))
  335. proc hash*(u: SigHash): Hash =
  336. result = 0
  337. for x in 0..3:
  338. result = (result shl 8) or u.MD5Digest[x].int
  339. proc hash*(x: FileIndex): Hash {.borrow.}
  340. template getPContext(): untyped =
  341. when c is PContext: c
  342. else: c.c
  343. when defined(nimsuggest):
  344. template onUse*(info: TLineInfo; s: PSym) = discard
  345. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  346. else:
  347. template onUse*(info: TLineInfo; s: PSym) = discard
  348. template onDef*(info: TLineInfo; s: PSym) = discard
  349. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  350. proc stopCompile*(g: ModuleGraph): bool {.inline.} =
  351. result = g.doStopCompile != nil and g.doStopCompile()
  352. proc createMagic*(g: ModuleGraph; idgen: IdGenerator; name: string, m: TMagic): PSym =
  353. result = newSym(skProc, getIdent(g.cache, name), idgen, nil, unknownLineInfo, {})
  354. result.magic = m
  355. result.flags = {sfNeverRaises}
  356. proc createMagic(g: ModuleGraph; name: string, m: TMagic): PSym =
  357. result = createMagic(g, g.idgen, name, m)
  358. proc registerModule*(g: ModuleGraph; m: PSym) =
  359. assert m != nil
  360. assert m.kind == skModule
  361. if m.position >= g.ifaces.len:
  362. setLen(g.ifaces, m.position + 1)
  363. if m.position >= g.packed.len:
  364. setLen(g.packed, m.position + 1)
  365. g.ifaces[m.position] = Iface(module: m, converters: @[], patterns: @[],
  366. uniqueName: rope(uniqueModuleName(g.config, FileIndex(m.position))))
  367. initStrTables(g, m)
  368. proc registerModuleById*(g: ModuleGraph; m: FileIndex) =
  369. registerModule(g, g.packed[int m].module)
  370. proc initOperators*(g: ModuleGraph): Operators =
  371. # These are safe for IC.
  372. # Public because it's used by DrNim.
  373. result.opLe = createMagic(g, "<=", mLeI)
  374. result.opLt = createMagic(g, "<", mLtI)
  375. result.opAnd = createMagic(g, "and", mAnd)
  376. result.opOr = createMagic(g, "or", mOr)
  377. result.opIsNil = createMagic(g, "isnil", mIsNil)
  378. result.opEq = createMagic(g, "==", mEqI)
  379. result.opAdd = createMagic(g, "+", mAddI)
  380. result.opSub = createMagic(g, "-", mSubI)
  381. result.opMul = createMagic(g, "*", mMulI)
  382. result.opDiv = createMagic(g, "div", mDivI)
  383. result.opLen = createMagic(g, "len", mLengthSeq)
  384. result.opNot = createMagic(g, "not", mNot)
  385. result.opContains = createMagic(g, "contains", mInSet)
  386. proc initModuleGraphFields(result: ModuleGraph) =
  387. # A module ID of -1 means that the symbol is not attached to a module at all,
  388. # but to the module graph:
  389. result.idgen = IdGenerator(module: -1'i32, symId: 0'i32, typeId: 0'i32)
  390. result.packageSyms = initStrTable()
  391. result.deps = initIntSet()
  392. result.importDeps = initTable[FileIndex, seq[FileIndex]]()
  393. result.ifaces = @[]
  394. result.importStack = @[]
  395. result.inclToMod = initTable[FileIndex, FileIndex]()
  396. result.owners = @[]
  397. result.suggestSymbols = initTable[FileIndex, seq[SymInfoPair]]()
  398. result.suggestErrors = initTable[FileIndex, seq[Suggest]]()
  399. result.methods = @[]
  400. result.compilerprocs = initStrTable()
  401. result.exposed = initStrTable()
  402. result.packageTypes = initStrTable()
  403. result.emptyNode = newNode(nkEmpty)
  404. result.cacheSeqs = initTable[string, PNode]()
  405. result.cacheCounters = initTable[string, BiggestInt]()
  406. result.cacheTables = initTable[string, BTree[string, PNode]]()
  407. result.canonTypes = initTable[SigHash, PType]()
  408. result.symBodyHashes = initTable[int, SigHash]()
  409. result.operators = initOperators(result)
  410. result.emittedTypeInfo = initTable[string, FileIndex]()
  411. proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
  412. result = ModuleGraph()
  413. result.config = config
  414. result.cache = cache
  415. initModuleGraphFields(result)
  416. proc resetAllModules*(g: ModuleGraph) =
  417. g.packageSyms = initStrTable()
  418. g.deps = initIntSet()
  419. g.ifaces = @[]
  420. g.importStack = @[]
  421. g.inclToMod = initTable[FileIndex, FileIndex]()
  422. g.usageSym = nil
  423. g.owners = @[]
  424. g.methods = @[]
  425. g.compilerprocs = initStrTable()
  426. g.exposed = initStrTable()
  427. initModuleGraphFields(g)
  428. proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
  429. result = nil
  430. if fileIdx.int32 >= 0:
  431. if isCachedModule(g, fileIdx.int32):
  432. result = g.packed[fileIdx.int32].module
  433. elif fileIdx.int32 < g.ifaces.len:
  434. result = g.ifaces[fileIdx.int32].module
  435. proc moduleOpenForCodegen*(g: ModuleGraph; m: FileIndex): bool {.inline.} =
  436. if g.config.symbolFiles == disabledSf:
  437. result = true
  438. else:
  439. result = g.packed[m.int32].status notin {undefined, stored, loaded}
  440. proc rememberEmittedTypeInfo*(g: ModuleGraph; m: FileIndex; ti: string) =
  441. #assert(not isCachedModule(g, m.int32))
  442. if g.config.symbolFiles != disabledSf:
  443. #assert g.encoders[m.int32].isActive
  444. assert g.packed[m.int32].status != stored
  445. g.packed[m.int32].fromDisk.emittedTypeInfo.add ti
  446. #echo "added typeinfo ", m.int32, " ", ti, " suspicious ", not g.encoders[m.int32].isActive
  447. proc rememberFlag*(g: ModuleGraph; m: PSym; flag: ModuleBackendFlag) =
  448. if g.config.symbolFiles != disabledSf:
  449. #assert g.encoders[m.int32].isActive
  450. assert g.packed[m.position].status != stored
  451. g.packed[m.position].fromDisk.backendFlags.incl flag
  452. proc closeRodFile*(g: ModuleGraph; m: PSym) =
  453. if g.config.symbolFiles in {readOnlySf, v2Sf}:
  454. # For stress testing we seek to reload the symbols from memory. This
  455. # way much of the logic is tested but the test is reproducible as it does
  456. # not depend on the hard disk contents!
  457. let mint = m.position
  458. saveRodFile(toRodFile(g.config, AbsoluteFile toFullPath(g.config, FileIndex(mint))),
  459. g.encoders[mint], g.packed[mint].fromDisk)
  460. g.packed[mint].status = stored
  461. elif g.config.symbolFiles == stressTest:
  462. # debug code, but maybe a good idea for production? Could reduce the compiler's
  463. # memory consumption considerably at the cost of more loads from disk.
  464. let mint = m.position
  465. simulateCachedModule(g, m, g.packed[mint].fromDisk)
  466. g.packed[mint].status = loaded
  467. proc dependsOn(a, b: int): int {.inline.} = (a shl 15) + b
  468. proc addDep*(g: ModuleGraph; m: PSym, dep: FileIndex) =
  469. assert m.position == m.info.fileIndex.int32
  470. if g.suggestMode:
  471. g.deps.incl m.position.dependsOn(dep.int)
  472. # we compute the transitive closure later when querying the graph lazily.
  473. # this improves efficiency quite a lot:
  474. #invalidTransitiveClosure = true
  475. proc addIncludeDep*(g: ModuleGraph; module, includeFile: FileIndex) =
  476. discard hasKeyOrPut(g.inclToMod, includeFile, module)
  477. proc parentModule*(g: ModuleGraph; fileIdx: FileIndex): FileIndex =
  478. ## returns 'fileIdx' if the file belonging to this index is
  479. ## directly used as a module or else the module that first
  480. ## references this include file.
  481. if fileIdx.int32 >= 0 and fileIdx.int32 < g.ifaces.len and g.ifaces[fileIdx.int32].module != nil:
  482. result = fileIdx
  483. else:
  484. result = g.inclToMod.getOrDefault(fileIdx)
  485. proc transitiveClosure(g: var IntSet; n: int) =
  486. # warshall's algorithm
  487. for k in 0..<n:
  488. for i in 0..<n:
  489. for j in 0..<n:
  490. if i != j and not g.contains(i.dependsOn(j)):
  491. if g.contains(i.dependsOn(k)) and g.contains(k.dependsOn(j)):
  492. g.incl i.dependsOn(j)
  493. proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  494. let m = g.getModule fileIdx
  495. if m != nil:
  496. g.suggestSymbols.del(fileIdx)
  497. g.suggestErrors.del(fileIdx)
  498. incl m.flags, sfDirty
  499. proc unmarkAllDirty*(g: ModuleGraph) =
  500. for i in 0i32..<g.ifaces.len.int32:
  501. let m = g.ifaces[i].module
  502. if m != nil:
  503. m.flags.excl sfDirty
  504. proc isDirty*(g: ModuleGraph; m: PSym): bool =
  505. result = g.suggestMode and sfDirty in m.flags
  506. proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  507. # we need to mark its dependent modules D as dirty right away because after
  508. # nimsuggest is done with this module, the module's dirty flag will be
  509. # cleared but D still needs to be remembered as 'dirty'.
  510. if g.invalidTransitiveClosure:
  511. g.invalidTransitiveClosure = false
  512. transitiveClosure(g.deps, g.ifaces.len)
  513. # every module that *depends* on this file is also dirty:
  514. for i in 0i32..<g.ifaces.len.int32:
  515. if g.deps.contains(i.dependsOn(fileIdx.int)):
  516. g.markDirty(FileIndex(i))
  517. proc needsCompilation*(g: ModuleGraph): bool =
  518. # every module that *depends* on this file is also dirty:
  519. result = false
  520. for i in 0i32..<g.ifaces.len.int32:
  521. let m = g.ifaces[i].module
  522. if m != nil:
  523. if sfDirty in m.flags:
  524. return true
  525. proc needsCompilation*(g: ModuleGraph, fileIdx: FileIndex): bool =
  526. result = false
  527. let module = g.getModule(fileIdx)
  528. if module != nil and g.isDirty(module):
  529. return true
  530. for i in 0i32..<g.ifaces.len.int32:
  531. let m = g.ifaces[i].module
  532. if m != nil and g.isDirty(m) and g.deps.contains(fileIdx.int32.dependsOn(i)):
  533. return true
  534. proc getBody*(g: ModuleGraph; s: PSym): PNode {.inline.} =
  535. result = s.ast[bodyPos]
  536. if result == nil and g.config.symbolFiles in {readOnlySf, v2Sf, stressTest}:
  537. result = loadProcBody(g.config, g.cache, g.packed, s)
  538. s.ast[bodyPos] = result
  539. assert result != nil
  540. proc moduleFromRodFile*(g: ModuleGraph; fileIdx: FileIndex;
  541. cachedModules: var seq[FileIndex]): PSym =
  542. ## Returns 'nil' if the module needs to be recompiled.
  543. if g.config.symbolFiles in {readOnlySf, v2Sf, stressTest}:
  544. result = moduleFromRodFile(g.packed, g.config, g.cache, fileIdx, cachedModules)
  545. else:
  546. result = nil
  547. proc configComplete*(g: ModuleGraph) =
  548. rememberStartupConfig(g.startupPackedConfig, g.config)
  549. from std/strutils import repeat, `%`
  550. proc onProcessing*(graph: ModuleGraph, fileIdx: FileIndex, moduleStatus: string, fromModule: PSym, ) =
  551. let conf = graph.config
  552. let isNimscript = conf.isDefined("nimscript")
  553. if (not isNimscript) or hintProcessing in conf.cmdlineNotes:
  554. let path = toFilenameOption(conf, fileIdx, conf.filenameOption)
  555. let indent = ">".repeat(graph.importStack.len)
  556. let fromModule2 = if fromModule != nil: $fromModule.name.s else: "(toplevel)"
  557. let mode = if isNimscript: "(nims) " else: ""
  558. rawMessage(conf, hintProcessing, "$#$# $#: $#: $#" % [mode, indent, fromModule2, moduleStatus, path])
  559. proc getPackage*(graph: ModuleGraph; fileIdx: FileIndex): PSym =
  560. ## Returns a package symbol for yet to be defined module for fileIdx.
  561. ## The package symbol is added to the graph if it doesn't exist.
  562. let pkgSym = getPackage(graph.config, graph.cache, fileIdx)
  563. # check if the package is already in the graph
  564. result = graph.packageSyms.strTableGet(pkgSym.name)
  565. if result == nil:
  566. # the package isn't in the graph, so create and add it
  567. result = pkgSym
  568. graph.packageSyms.strTableAdd(pkgSym)
  569. func belongsToStdlib*(graph: ModuleGraph, sym: PSym): bool =
  570. ## Check if symbol belongs to the 'stdlib' package.
  571. sym.getPackageSymbol.getPackageId == graph.systemModule.getPackageId
  572. proc `==`*(a, b: SymInfoPair): bool =
  573. result = a.sym == b.sym and a.info.exactEquals(b.info)
  574. proc fileSymbols*(graph: ModuleGraph, fileIdx: FileIndex): seq[SymInfoPair] =
  575. result = graph.suggestSymbols.getOrDefault(fileIdx, @[])
  576. iterator suggestSymbolsIter*(g: ModuleGraph): SymInfoPair =
  577. for xs in g.suggestSymbols.values:
  578. for x in xs:
  579. yield x
  580. iterator suggestErrorsIter*(g: ModuleGraph): Suggest =
  581. for xs in g.suggestErrors.values:
  582. for x in xs:
  583. yield x