modulegraphs.nim 27 KB

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