modulegraphs.nim 26 KB

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