modulegraphs.nim 25 KB

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