modulegraphs.nim 25 KB

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