modulegraphs.nim 25 KB

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