modulegraphs.nim 25 KB

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