modulegraphs.nim 27 KB

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