modulegraphs.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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, sequtils
  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, PSym]] # 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. iterator typeInstCacheItems*(g: ModuleGraph; s: PSym): PType =
  249. if g.typeInstCache.contains(s.itemId):
  250. let x = addr(g.typeInstCache[s.itemId])
  251. for t in mitems(x[]):
  252. yield resolveType(g, t)
  253. iterator procInstCacheItems*(g: ModuleGraph; s: PSym): PInstantiation =
  254. if g.procInstCache.contains(s.itemId):
  255. let x = addr(g.procInstCache[s.itemId])
  256. for t in mitems(x[]):
  257. yield resolveInst(g, t)
  258. proc getAttachedOp*(g: ModuleGraph; t: PType; op: TTypeAttachedOp): PSym =
  259. ## returns the requested attached operation for type `t`. Can return nil
  260. ## if no such operation exists.
  261. result = g.attachedOps[op].getOrDefault(t.itemId)
  262. proc setAttachedOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  263. ## we also need to record this to the packed module.
  264. g.attachedOps[op][t.itemId] = value
  265. proc setAttachedOpPartial*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  266. ## we also need to record this to the packed module.
  267. g.attachedOps[op][t.itemId] = value
  268. # XXX Also add to the packed module!
  269. proc completePartialOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  270. if g.config.symbolFiles != disabledSf:
  271. assert module < g.encoders.len
  272. assert isActive(g.encoders[module])
  273. toPackedGeneratedProcDef(value, g.encoders[module], g.packed[module].fromDisk)
  274. proc getToStringProc*(g: ModuleGraph; t: PType): PSym =
  275. result = resolveSym(g, g.enumToStringProcs[t.itemId])
  276. assert result != nil
  277. proc setToStringProc*(g: ModuleGraph; t: PType; value: PSym) =
  278. g.enumToStringProcs[t.itemId] = LazySym(sym: value)
  279. iterator methodsForGeneric*(g: ModuleGraph; t: PType): (int, PSym) =
  280. if g.methodsPerType.contains(t.itemId):
  281. for it in mitems g.methodsPerType[t.itemId]:
  282. yield (it[0], resolveSym(g, it[1]))
  283. proc addMethodToGeneric*(g: ModuleGraph; module: int; t: PType; col: int; m: PSym) =
  284. g.methodsPerType.mgetOrPut(t.itemId, @[]).add (col, LazySym(sym: m))
  285. proc hasDisabledAsgn*(g: ModuleGraph; t: PType): bool =
  286. let op = getAttachedOp(g, t, attachedAsgn)
  287. result = op != nil and sfError in op.flags
  288. proc copyTypeProps*(g: ModuleGraph; module: int; dest, src: PType) =
  289. for k in low(TTypeAttachedOp)..high(TTypeAttachedOp):
  290. let op = getAttachedOp(g, src, k)
  291. if op != nil:
  292. setAttachedOp(g, module, dest, k, op)
  293. proc loadCompilerProc*(g: ModuleGraph; name: string): PSym =
  294. if g.config.symbolFiles == disabledSf: return nil
  295. # slow, linear search, but the results are cached:
  296. for module in 0..high(g.packed):
  297. #if isCachedModule(g, module):
  298. let x = searchForCompilerproc(g.packed[module], name)
  299. if x >= 0:
  300. result = loadSymFromId(g.config, g.cache, g.packed, module, toPackedItemId(x))
  301. if result != nil:
  302. strTableAdd(g.compilerprocs, result)
  303. return result
  304. proc loadPackedSym*(g: ModuleGraph; s: var LazySym) =
  305. if s.sym == nil:
  306. s.sym = loadSymFromId(g.config, g.cache, g.packed, s.id.module, s.id.packed)
  307. proc `$`*(u: SigHash): string =
  308. toBase64a(cast[cstring](unsafeAddr u), sizeof(u))
  309. proc `==`*(a, b: SigHash): bool =
  310. result = equalMem(unsafeAddr a, unsafeAddr b, sizeof(a))
  311. proc hash*(u: SigHash): Hash =
  312. result = 0
  313. for x in 0..3:
  314. result = (result shl 8) or u.MD5Digest[x].int
  315. proc hash*(x: FileIndex): Hash {.borrow.}
  316. template getPContext(): untyped =
  317. when c is PContext: c
  318. else: c.c
  319. when defined(nimsuggest):
  320. template onUse*(info: TLineInfo; s: PSym) = discard
  321. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  322. else:
  323. template onUse*(info: TLineInfo; s: PSym) = discard
  324. template onDef*(info: TLineInfo; s: PSym) = discard
  325. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  326. proc stopCompile*(g: ModuleGraph): bool {.inline.} =
  327. result = g.doStopCompile != nil and g.doStopCompile()
  328. proc createMagic*(g: ModuleGraph; idgen: IdGenerator; name: string, m: TMagic): PSym =
  329. result = newSym(skProc, getIdent(g.cache, name), nextSymId(idgen), nil, unknownLineInfo, {})
  330. result.magic = m
  331. result.flags = {sfNeverRaises}
  332. proc createMagic(g: ModuleGraph; name: string, m: TMagic): PSym =
  333. result = createMagic(g, g.idgen, name, m)
  334. proc registerModule*(g: ModuleGraph; m: PSym) =
  335. assert m != nil
  336. assert m.kind == skModule
  337. if m.position >= g.ifaces.len:
  338. setLen(g.ifaces, m.position + 1)
  339. if m.position >= g.packed.len:
  340. setLen(g.packed, m.position + 1)
  341. g.ifaces[m.position] = Iface(module: m, converters: @[], patterns: @[],
  342. uniqueName: rope(uniqueModuleName(g.config, FileIndex(m.position))))
  343. initStrTables(g, m)
  344. proc registerModuleById*(g: ModuleGraph; m: FileIndex) =
  345. registerModule(g, g.packed[int m].module)
  346. proc initOperators*(g: ModuleGraph): Operators =
  347. # These are safe for IC.
  348. # Public because it's used by DrNim.
  349. result.opLe = createMagic(g, "<=", mLeI)
  350. result.opLt = createMagic(g, "<", mLtI)
  351. result.opAnd = createMagic(g, "and", mAnd)
  352. result.opOr = createMagic(g, "or", mOr)
  353. result.opIsNil = createMagic(g, "isnil", mIsNil)
  354. result.opEq = createMagic(g, "==", mEqI)
  355. result.opAdd = createMagic(g, "+", mAddI)
  356. result.opSub = createMagic(g, "-", mSubI)
  357. result.opMul = createMagic(g, "*", mMulI)
  358. result.opDiv = createMagic(g, "div", mDivI)
  359. result.opLen = createMagic(g, "len", mLengthSeq)
  360. result.opNot = createMagic(g, "not", mNot)
  361. result.opContains = createMagic(g, "contains", mInSet)
  362. proc initModuleGraphFields(result: ModuleGraph) =
  363. # A module ID of -1 means that the symbol is not attached to a module at all,
  364. # but to the module graph:
  365. result.idgen = IdGenerator(module: -1'i32, symId: 0'i32, typeId: 0'i32)
  366. initStrTable(result.packageSyms)
  367. result.deps = initIntSet()
  368. result.importDeps = initTable[FileIndex, seq[FileIndex]]()
  369. result.ifaces = @[]
  370. result.importStack = @[]
  371. result.inclToMod = initTable[FileIndex, FileIndex]()
  372. result.owners = @[]
  373. result.suggestSymbols = initTable[FileIndex, seq[SymInfoPair]]()
  374. result.suggestErrors = initTable[FileIndex, seq[Suggest]]()
  375. result.methods = @[]
  376. initStrTable(result.compilerprocs)
  377. initStrTable(result.exposed)
  378. initStrTable(result.packageTypes)
  379. result.emptyNode = newNode(nkEmpty)
  380. result.cacheSeqs = initTable[string, PNode]()
  381. result.cacheCounters = initTable[string, BiggestInt]()
  382. result.cacheTables = initTable[string, BTree[string, PNode]]()
  383. result.canonTypes = initTable[SigHash, PType]()
  384. result.symBodyHashes = initTable[int, SigHash]()
  385. result.operators = initOperators(result)
  386. result.emittedTypeInfo = initTable[string, FileIndex]()
  387. proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
  388. result = ModuleGraph()
  389. result.config = config
  390. result.cache = cache
  391. initModuleGraphFields(result)
  392. proc resetAllModules*(g: ModuleGraph) =
  393. initStrTable(g.packageSyms)
  394. g.deps = initIntSet()
  395. g.ifaces = @[]
  396. g.importStack = @[]
  397. g.inclToMod = initTable[FileIndex, FileIndex]()
  398. g.usageSym = nil
  399. g.owners = @[]
  400. g.methods = @[]
  401. initStrTable(g.compilerprocs)
  402. initStrTable(g.exposed)
  403. initModuleGraphFields(g)
  404. proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
  405. if fileIdx.int32 >= 0:
  406. if isCachedModule(g, fileIdx.int32):
  407. result = g.packed[fileIdx.int32].module
  408. elif fileIdx.int32 < g.ifaces.len:
  409. result = g.ifaces[fileIdx.int32].module
  410. proc moduleOpenForCodegen*(g: ModuleGraph; m: FileIndex): bool {.inline.} =
  411. if g.config.symbolFiles == disabledSf:
  412. result = true
  413. else:
  414. result = g.packed[m.int32].status notin {undefined, stored, loaded}
  415. proc rememberEmittedTypeInfo*(g: ModuleGraph; m: FileIndex; ti: string) =
  416. #assert(not isCachedModule(g, m.int32))
  417. if g.config.symbolFiles != disabledSf:
  418. #assert g.encoders[m.int32].isActive
  419. assert g.packed[m.int32].status != stored
  420. g.packed[m.int32].fromDisk.emittedTypeInfo.add ti
  421. #echo "added typeinfo ", m.int32, " ", ti, " suspicious ", not g.encoders[m.int32].isActive
  422. proc rememberFlag*(g: ModuleGraph; m: PSym; flag: ModuleBackendFlag) =
  423. if g.config.symbolFiles != disabledSf:
  424. #assert g.encoders[m.int32].isActive
  425. assert g.packed[m.position].status != stored
  426. g.packed[m.position].fromDisk.backendFlags.incl flag
  427. proc closeRodFile*(g: ModuleGraph; m: PSym) =
  428. if g.config.symbolFiles in {readOnlySf, v2Sf}:
  429. # For stress testing we seek to reload the symbols from memory. This
  430. # way much of the logic is tested but the test is reproducible as it does
  431. # not depend on the hard disk contents!
  432. let mint = m.position
  433. saveRodFile(toRodFile(g.config, AbsoluteFile toFullPath(g.config, FileIndex(mint))),
  434. g.encoders[mint], g.packed[mint].fromDisk)
  435. g.packed[mint].status = stored
  436. elif g.config.symbolFiles == stressTest:
  437. # debug code, but maybe a good idea for production? Could reduce the compiler's
  438. # memory consumption considerably at the cost of more loads from disk.
  439. let mint = m.position
  440. simulateCachedModule(g, m, g.packed[mint].fromDisk)
  441. g.packed[mint].status = loaded
  442. proc dependsOn(a, b: int): int {.inline.} = (a shl 15) + b
  443. proc addDep*(g: ModuleGraph; m: PSym, dep: FileIndex) =
  444. assert m.position == m.info.fileIndex.int32
  445. if g.suggestMode:
  446. g.deps.incl m.position.dependsOn(dep.int)
  447. # we compute the transitive closure later when querying the graph lazily.
  448. # this improves efficiency quite a lot:
  449. #invalidTransitiveClosure = true
  450. proc addIncludeDep*(g: ModuleGraph; module, includeFile: FileIndex) =
  451. discard hasKeyOrPut(g.inclToMod, includeFile, module)
  452. proc parentModule*(g: ModuleGraph; fileIdx: FileIndex): FileIndex =
  453. ## returns 'fileIdx' if the file belonging to this index is
  454. ## directly used as a module or else the module that first
  455. ## references this include file.
  456. if fileIdx.int32 >= 0 and fileIdx.int32 < g.ifaces.len and g.ifaces[fileIdx.int32].module != nil:
  457. result = fileIdx
  458. else:
  459. result = g.inclToMod.getOrDefault(fileIdx)
  460. proc transitiveClosure(g: var IntSet; n: int) =
  461. # warshall's algorithm
  462. for k in 0..<n:
  463. for i in 0..<n:
  464. for j in 0..<n:
  465. if i != j and not g.contains(i.dependsOn(j)):
  466. if g.contains(i.dependsOn(k)) and g.contains(k.dependsOn(j)):
  467. g.incl i.dependsOn(j)
  468. proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  469. let m = g.getModule fileIdx
  470. if m != nil:
  471. g.suggestSymbols.del(fileIdx)
  472. g.suggestErrors.del(fileIdx)
  473. incl m.flags, sfDirty
  474. proc unmarkAllDirty*(g: ModuleGraph) =
  475. for i in 0i32..<g.ifaces.len.int32:
  476. let m = g.ifaces[i].module
  477. if m != nil:
  478. m.flags.excl sfDirty
  479. proc isDirty*(g: ModuleGraph; m: PSym): bool =
  480. result = g.suggestMode and sfDirty in m.flags
  481. proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  482. # we need to mark its dependent modules D as dirty right away because after
  483. # nimsuggest is done with this module, the module's dirty flag will be
  484. # cleared but D still needs to be remembered as 'dirty'.
  485. if g.invalidTransitiveClosure:
  486. g.invalidTransitiveClosure = false
  487. transitiveClosure(g.deps, g.ifaces.len)
  488. # every module that *depends* on this file is also dirty:
  489. for i in 0i32..<g.ifaces.len.int32:
  490. if g.deps.contains(i.dependsOn(fileIdx.int)):
  491. g.markDirty(FileIndex(i))
  492. proc needsCompilation*(g: ModuleGraph): bool =
  493. # every module that *depends* on this file is also dirty:
  494. for i in 0i32..<g.ifaces.len.int32:
  495. let m = g.ifaces[i].module
  496. if m != nil:
  497. if sfDirty in m.flags:
  498. return true
  499. proc needsCompilation*(g: ModuleGraph, fileIdx: FileIndex): bool =
  500. let module = g.getModule(fileIdx)
  501. if module != nil and g.isDirty(module):
  502. return true
  503. for i in 0i32..<g.ifaces.len.int32:
  504. let m = g.ifaces[i].module
  505. if m != nil and g.isDirty(m) and g.deps.contains(fileIdx.int32.dependsOn(i)):
  506. return true
  507. proc getBody*(g: ModuleGraph; s: PSym): PNode {.inline.} =
  508. result = s.ast[bodyPos]
  509. if result == nil and g.config.symbolFiles in {readOnlySf, v2Sf, stressTest}:
  510. result = loadProcBody(g.config, g.cache, g.packed, s)
  511. s.ast[bodyPos] = result
  512. assert result != nil
  513. proc moduleFromRodFile*(g: ModuleGraph; fileIdx: FileIndex;
  514. cachedModules: var seq[FileIndex]): PSym =
  515. ## Returns 'nil' if the module needs to be recompiled.
  516. if g.config.symbolFiles in {readOnlySf, v2Sf, stressTest}:
  517. result = moduleFromRodFile(g.packed, g.config, g.cache, fileIdx, cachedModules)
  518. proc configComplete*(g: ModuleGraph) =
  519. rememberStartupConfig(g.startupPackedConfig, g.config)
  520. from std/strutils import repeat, `%`
  521. proc onProcessing*(graph: ModuleGraph, fileIdx: FileIndex, moduleStatus: string, fromModule: PSym, ) =
  522. let conf = graph.config
  523. let isNimscript = conf.isDefined("nimscript")
  524. if (not isNimscript) or hintProcessing in conf.cmdlineNotes:
  525. let path = toFilenameOption(conf, fileIdx, conf.filenameOption)
  526. let indent = ">".repeat(graph.importStack.len)
  527. let fromModule2 = if fromModule != nil: $fromModule.name.s else: "(toplevel)"
  528. let mode = if isNimscript: "(nims) " else: ""
  529. rawMessage(conf, hintProcessing, "$#$# $#: $#: $#" % [mode, indent, fromModule2, moduleStatus, path])
  530. proc getPackage*(graph: ModuleGraph; fileIdx: FileIndex): PSym =
  531. ## Returns a package symbol for yet to be defined module for fileIdx.
  532. ## The package symbol is added to the graph if it doesn't exist.
  533. let pkgSym = getPackage(graph.config, graph.cache, fileIdx)
  534. # check if the package is already in the graph
  535. result = graph.packageSyms.strTableGet(pkgSym.name)
  536. if result == nil:
  537. # the package isn't in the graph, so create and add it
  538. result = pkgSym
  539. graph.packageSyms.strTableAdd(pkgSym)
  540. func belongsToStdlib*(graph: ModuleGraph, sym: PSym): bool =
  541. ## Check if symbol belongs to the 'stdlib' package.
  542. sym.getPackageSymbol.getPackageId == graph.systemModule.getPackageId
  543. proc `==`*(a, b: SymInfoPair): bool =
  544. result = a.sym == b.sym and a.info.exactEquals(b.info)
  545. proc fileSymbols*(graph: ModuleGraph, fileIdx: FileIndex): seq[SymInfoPair] =
  546. result = graph.suggestSymbols.getOrDefault(fileIdx, @[])
  547. iterator suggestSymbolsIter*(g: ModuleGraph): SymInfoPair =
  548. for xs in g.suggestSymbols.values:
  549. for x in xs:
  550. yield x
  551. iterator suggestErrorsIter*(g: ModuleGraph): Suggest =
  552. for xs in g.suggestErrors.values:
  553. for x in xs:
  554. yield x