modulegraphs.nim 27 KB

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