modulegraphs.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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, os, strutils, parseutils]
  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 someSymAmb*(g: ModuleGraph; m: PSym; name: PIdent; amb: var bool): PSym =
  240. let importHidden = optImportHidden in m.options
  241. if isCachedModule(g, m):
  242. result = nil
  243. for s in interfaceSymbols(g.config, g.cache, g.packed, FileIndex(m.position), name, importHidden):
  244. if result == nil:
  245. # set result to the first symbol
  246. result = s
  247. else:
  248. # another symbol found
  249. amb = true
  250. break
  251. else:
  252. var ti: TIdentIter = default(TIdentIter)
  253. result = initIdentIter(ti, g.ifaces[m.position].interfSelect(importHidden), name)
  254. if result != nil and nextIdentIter(ti, g.ifaces[m.position].interfSelect(importHidden)) != nil:
  255. # another symbol exists with same name
  256. amb = true
  257. proc systemModuleSym*(g: ModuleGraph; name: PIdent): PSym =
  258. result = someSym(g, g.systemModule, name)
  259. iterator systemModuleSyms*(g: ModuleGraph; name: PIdent): PSym =
  260. var mi: ModuleIter = default(ModuleIter)
  261. var r = initModuleIter(mi, g, g.systemModule, name)
  262. while r != nil:
  263. yield r
  264. r = nextModuleIter(mi, g)
  265. proc resolveType(g: ModuleGraph; t: var LazyType): PType =
  266. result = t.typ
  267. if result == nil and isCachedModule(g, t.id.module):
  268. result = loadTypeFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
  269. t.typ = result
  270. assert result != nil
  271. proc resolveSym(g: ModuleGraph; t: var LazySym): PSym =
  272. result = t.sym
  273. if result == nil and isCachedModule(g, t.id.module):
  274. result = loadSymFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
  275. t.sym = result
  276. assert result != nil
  277. proc resolveInst(g: ModuleGraph; t: var LazyInstantiation): PInstantiation =
  278. result = t.inst
  279. if result == nil and isCachedModule(g, t.module):
  280. result = PInstantiation(sym: loadSymFromId(g.config, g.cache, g.packed, t.sym.module, t.sym.packed))
  281. result.concreteTypes = newSeq[PType](t.concreteTypes.len)
  282. for i in 0..high(result.concreteTypes):
  283. result.concreteTypes[i] = loadTypeFromId(g.config, g.cache, g.packed,
  284. t.concreteTypes[i].module, t.concreteTypes[i].packed)
  285. t.inst = result
  286. assert result != nil
  287. proc resolveAttachedOp*(g: ModuleGraph; t: var LazySym): PSym =
  288. result = t.sym
  289. if result == nil:
  290. result = loadSymFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
  291. t.sym = result
  292. assert result != nil
  293. iterator typeInstCacheItems*(g: ModuleGraph; s: PSym): PType =
  294. if g.typeInstCache.contains(s.itemId):
  295. let x = addr(g.typeInstCache[s.itemId])
  296. for t in mitems(x[]):
  297. yield resolveType(g, t)
  298. iterator procInstCacheItems*(g: ModuleGraph; s: PSym): PInstantiation =
  299. if g.procInstCache.contains(s.itemId):
  300. let x = addr(g.procInstCache[s.itemId])
  301. for t in mitems(x[]):
  302. yield resolveInst(g, t)
  303. proc getAttachedOp*(g: ModuleGraph; t: PType; op: TTypeAttachedOp): PSym =
  304. ## returns the requested attached operation for type `t`. Can return nil
  305. ## if no such operation exists.
  306. if g.attachedOps[op].contains(t.itemId):
  307. result = resolveAttachedOp(g, g.attachedOps[op][t.itemId])
  308. else:
  309. result = nil
  310. proc setAttachedOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  311. ## we also need to record this to the packed module.
  312. g.attachedOps[op][t.itemId] = LazySym(sym: value)
  313. proc setAttachedOpPartial*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  314. ## we also need to record this to the packed module.
  315. g.attachedOps[op][t.itemId] = LazySym(sym: value)
  316. proc completePartialOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
  317. if g.config.symbolFiles != disabledSf:
  318. assert module < g.encoders.len
  319. assert isActive(g.encoders[module])
  320. toPackedGeneratedProcDef(value, g.encoders[module], g.packed[module].fromDisk)
  321. #storeAttachedProcDef(t, op, value, g.encoders[module], g.packed[module].fromDisk)
  322. iterator getDispatchers*(g: ModuleGraph): PSym =
  323. for i in g.dispatchers.mitems:
  324. yield resolveSym(g, i)
  325. proc addDispatchers*(g: ModuleGraph, value: PSym) =
  326. # TODO: add it for packed modules
  327. g.dispatchers.add LazySym(sym: value)
  328. iterator resolveLazySymSeq(g: ModuleGraph, list: var seq[LazySym]): PSym =
  329. for it in list.mitems:
  330. yield resolveSym(g, it)
  331. proc setMethodsPerType*(g: ModuleGraph; id: ItemId, methods: seq[LazySym]) =
  332. # TODO: add it for packed modules
  333. g.methodsPerType[id] = methods
  334. iterator getMethodsPerType*(g: ModuleGraph; t: PType): PSym =
  335. if g.methodsPerType.contains(t.itemId):
  336. for it in mitems g.methodsPerType[t.itemId]:
  337. yield resolveSym(g, it)
  338. proc getToStringProc*(g: ModuleGraph; t: PType): PSym =
  339. result = resolveSym(g, g.enumToStringProcs[t.itemId])
  340. assert result != nil
  341. proc setToStringProc*(g: ModuleGraph; t: PType; value: PSym) =
  342. g.enumToStringProcs[t.itemId] = LazySym(sym: value)
  343. iterator methodsForGeneric*(g: ModuleGraph; t: PType): (int, PSym) =
  344. if g.methodsPerGenericType.contains(t.itemId):
  345. for it in mitems g.methodsPerGenericType[t.itemId]:
  346. yield (it[0], resolveSym(g, it[1]))
  347. proc addMethodToGeneric*(g: ModuleGraph; module: int; t: PType; col: int; m: PSym) =
  348. g.methodsPerGenericType.mgetOrPut(t.itemId, @[]).add (col, LazySym(sym: m))
  349. proc hasDisabledAsgn*(g: ModuleGraph; t: PType): bool =
  350. let op = getAttachedOp(g, t, attachedAsgn)
  351. result = op != nil and sfError in op.flags
  352. proc copyTypeProps*(g: ModuleGraph; module: int; dest, src: PType) =
  353. for k in low(TTypeAttachedOp)..high(TTypeAttachedOp):
  354. let op = getAttachedOp(g, src, k)
  355. if op != nil:
  356. setAttachedOp(g, module, dest, k, op)
  357. proc loadCompilerProc*(g: ModuleGraph; name: string): PSym =
  358. result = nil
  359. if g.config.symbolFiles == disabledSf: return nil
  360. # slow, linear search, but the results are cached:
  361. for module in 0..<len(g.packed):
  362. #if isCachedModule(g, module):
  363. let x = searchForCompilerproc(g.packed[module], name)
  364. if x >= 0:
  365. result = loadSymFromId(g.config, g.cache, g.packed, module, toPackedItemId(x))
  366. if result != nil:
  367. strTableAdd(g.compilerprocs, result)
  368. return result
  369. proc loadPackedSym*(g: ModuleGraph; s: var LazySym) =
  370. if s.sym == nil:
  371. s.sym = loadSymFromId(g.config, g.cache, g.packed, s.id.module, s.id.packed)
  372. proc `$`*(u: SigHash): string =
  373. toBase64a(cast[cstring](unsafeAddr u), sizeof(u))
  374. proc `==`*(a, b: SigHash): bool =
  375. result = equalMem(unsafeAddr a, unsafeAddr b, sizeof(a))
  376. proc hash*(u: SigHash): Hash =
  377. result = 0
  378. for x in 0..3:
  379. result = (result shl 8) or u.MD5Digest[x].int
  380. proc hash*(x: FileIndex): Hash {.borrow.}
  381. template getPContext(): untyped =
  382. when c is PContext: c
  383. else: c.c
  384. when defined(nimsuggest):
  385. template onUse*(info: TLineInfo; s: PSym) = discard
  386. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  387. else:
  388. template onUse*(info: TLineInfo; s: PSym) = discard
  389. template onDef*(info: TLineInfo; s: PSym) = discard
  390. template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
  391. proc stopCompile*(g: ModuleGraph): bool {.inline.} =
  392. result = g.doStopCompile != nil and g.doStopCompile()
  393. proc createMagic*(g: ModuleGraph; idgen: IdGenerator; name: string, m: TMagic): PSym =
  394. result = newSym(skProc, getIdent(g.cache, name), idgen, nil, unknownLineInfo, {})
  395. result.magic = m
  396. result.flags = {sfNeverRaises}
  397. proc createMagic(g: ModuleGraph; name: string, m: TMagic): PSym =
  398. result = createMagic(g, g.idgen, name, m)
  399. proc uniqueModuleName*(conf: ConfigRef; m: PSym): string =
  400. ## The unique module name is guaranteed to only contain {'A'..'Z', 'a'..'z', '0'..'9', '_'}
  401. ## so that it is useful as a C identifier snippet.
  402. let fid = FileIndex(m.position)
  403. let path = AbsoluteFile toFullPath(conf, fid)
  404. var isLib = false
  405. var rel = ""
  406. if path.string.startsWith(conf.libpath.string):
  407. isLib = true
  408. rel = relativeTo(path, conf.libpath).string
  409. else:
  410. rel = relativeTo(path, conf.projectPath).string
  411. if not isLib and not belongsToProjectPackage(conf, m):
  412. # special handlings for nimble packages
  413. when DirSep == '\\':
  414. let rel2 = replace(rel, '\\', '/')
  415. else:
  416. let rel2 = rel
  417. const pkgs2 = "pkgs2/"
  418. var start = rel2.find(pkgs2)
  419. if start >= 0:
  420. start += pkgs2.len
  421. start += skipUntil(rel2, {'/'}, start)
  422. if start+1 < rel2.len:
  423. rel = "pkg/" & rel2[start+1..<rel.len] # strips paths
  424. let trunc = if rel.endsWith(".nim"): rel.len - len(".nim") else: rel.len
  425. result = newStringOfCap(trunc)
  426. for i in 0..<trunc:
  427. let c = rel[i]
  428. case c
  429. of 'a'..'z', '0'..'9':
  430. result.add c
  431. of {os.DirSep, os.AltSep}:
  432. result.add 'Z' # because it looks a bit like '/'
  433. of '.':
  434. result.add 'O' # a circle
  435. else:
  436. # We mangle upper letters too so that there cannot
  437. # be clashes with our special meanings of 'Z' and 'O'
  438. result.addInt ord(c)
  439. proc registerModule*(g: ModuleGraph; m: PSym) =
  440. assert m != nil
  441. assert m.kind == skModule
  442. if m.position >= g.ifaces.len:
  443. setLen(g.ifaces, m.position + 1)
  444. if m.position >= g.packed.len:
  445. setLen(g.packed.pm, m.position + 1)
  446. g.ifaces[m.position] = Iface(module: m, converters: @[], patterns: @[],
  447. uniqueName: rope(uniqueModuleName(g.config, m)))
  448. initStrTables(g, m)
  449. proc registerModuleById*(g: ModuleGraph; m: FileIndex) =
  450. registerModule(g, g.packed[int m].module)
  451. proc initOperators*(g: ModuleGraph): Operators =
  452. # These are safe for IC.
  453. # Public because it's used by DrNim.
  454. result = Operators(
  455. opLe: createMagic(g, "<=", mLeI),
  456. opLt: createMagic(g, "<", mLtI),
  457. opAnd: createMagic(g, "and", mAnd),
  458. opOr: createMagic(g, "or", mOr),
  459. opIsNil: createMagic(g, "isnil", mIsNil),
  460. opEq: createMagic(g, "==", mEqI),
  461. opAdd: createMagic(g, "+", mAddI),
  462. opSub: createMagic(g, "-", mSubI),
  463. opMul: createMagic(g, "*", mMulI),
  464. opDiv: createMagic(g, "div", mDivI),
  465. opLen: createMagic(g, "len", mLengthSeq),
  466. opNot: createMagic(g, "not", mNot),
  467. opContains: createMagic(g, "contains", mInSet)
  468. )
  469. proc initModuleGraphFields(result: ModuleGraph) =
  470. # A module ID of -1 means that the symbol is not attached to a module at all,
  471. # but to the module graph:
  472. result.idgen = IdGenerator(module: -1'i32, symId: 0'i32, typeId: 0'i32)
  473. result.packageSyms = initStrTable()
  474. result.deps = initIntSet()
  475. result.importDeps = initTable[FileIndex, seq[FileIndex]]()
  476. result.ifaces = @[]
  477. result.importStack = @[]
  478. result.inclToMod = initTable[FileIndex, FileIndex]()
  479. result.owners = @[]
  480. result.suggestSymbols = initTable[FileIndex, SuggestFileSymbolDatabase]()
  481. result.suggestErrors = initTable[FileIndex, seq[Suggest]]()
  482. result.methods = @[]
  483. result.compilerprocs = initStrTable()
  484. result.exposed = initStrTable()
  485. result.packageTypes = initStrTable()
  486. result.emptyNode = newNode(nkEmpty)
  487. result.cacheSeqs = initTable[string, PNode]()
  488. result.cacheCounters = initTable[string, BiggestInt]()
  489. result.cacheTables = initTable[string, BTree[string, PNode]]()
  490. result.canonTypes = initTable[SigHash, PType]()
  491. result.symBodyHashes = initTable[int, SigHash]()
  492. result.operators = initOperators(result)
  493. result.emittedTypeInfo = initTable[string, FileIndex]()
  494. result.cachedFiles = newStringTable()
  495. proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
  496. result = ModuleGraph()
  497. result.config = config
  498. result.cache = cache
  499. initModuleGraphFields(result)
  500. proc resetAllModules*(g: ModuleGraph) =
  501. g.packageSyms = initStrTable()
  502. g.deps = initIntSet()
  503. g.ifaces = @[]
  504. g.importStack = @[]
  505. g.inclToMod = initTable[FileIndex, FileIndex]()
  506. g.usageSym = nil
  507. g.owners = @[]
  508. g.methods = @[]
  509. g.compilerprocs = initStrTable()
  510. g.exposed = initStrTable()
  511. initModuleGraphFields(g)
  512. proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
  513. result = nil
  514. if fileIdx.int32 >= 0:
  515. if isCachedModule(g, fileIdx.int32):
  516. result = g.packed[fileIdx.int32].module
  517. elif fileIdx.int32 < g.ifaces.len:
  518. result = g.ifaces[fileIdx.int32].module
  519. proc moduleOpenForCodegen*(g: ModuleGraph; m: FileIndex): bool {.inline.} =
  520. if g.config.symbolFiles == disabledSf:
  521. result = true
  522. else:
  523. result = g.packed[m.int32].status notin {undefined, stored, loaded}
  524. proc rememberEmittedTypeInfo*(g: ModuleGraph; m: FileIndex; ti: string) =
  525. #assert(not isCachedModule(g, m.int32))
  526. if g.config.symbolFiles != disabledSf:
  527. #assert g.encoders[m.int32].isActive
  528. assert g.packed[m.int32].status != stored
  529. g.packed[m.int32].fromDisk.emittedTypeInfo.add ti
  530. #echo "added typeinfo ", m.int32, " ", ti, " suspicious ", not g.encoders[m.int32].isActive
  531. proc rememberFlag*(g: ModuleGraph; m: PSym; flag: ModuleBackendFlag) =
  532. if g.config.symbolFiles != disabledSf:
  533. #assert g.encoders[m.int32].isActive
  534. assert g.packed[m.position].status != stored
  535. g.packed[m.position].fromDisk.backendFlags.incl flag
  536. proc closeRodFile*(g: ModuleGraph; m: PSym) =
  537. if g.config.symbolFiles in {readOnlySf, v2Sf}:
  538. # For stress testing we seek to reload the symbols from memory. This
  539. # way much of the logic is tested but the test is reproducible as it does
  540. # not depend on the hard disk contents!
  541. let mint = m.position
  542. saveRodFile(toRodFile(g.config, AbsoluteFile toFullPath(g.config, FileIndex(mint))),
  543. g.encoders[mint], g.packed[mint].fromDisk)
  544. g.packed[mint].status = stored
  545. elif g.config.symbolFiles == stressTest:
  546. # debug code, but maybe a good idea for production? Could reduce the compiler's
  547. # memory consumption considerably at the cost of more loads from disk.
  548. let mint = m.position
  549. simulateCachedModule(g, m, g.packed[mint].fromDisk)
  550. g.packed[mint].status = loaded
  551. proc dependsOn(a, b: int): int {.inline.} = (a shl 15) + b
  552. proc addDep*(g: ModuleGraph; m: PSym, dep: FileIndex) =
  553. assert m.position == m.info.fileIndex.int32
  554. if g.suggestMode:
  555. g.deps.incl m.position.dependsOn(dep.int)
  556. # we compute the transitive closure later when querying the graph lazily.
  557. # this improves efficiency quite a lot:
  558. #invalidTransitiveClosure = true
  559. proc addIncludeDep*(g: ModuleGraph; module, includeFile: FileIndex) =
  560. discard hasKeyOrPut(g.inclToMod, includeFile, module)
  561. proc parentModule*(g: ModuleGraph; fileIdx: FileIndex): FileIndex =
  562. ## returns 'fileIdx' if the file belonging to this index is
  563. ## directly used as a module or else the module that first
  564. ## references this include file.
  565. if fileIdx.int32 >= 0 and fileIdx.int32 < g.ifaces.len and g.ifaces[fileIdx.int32].module != nil:
  566. result = fileIdx
  567. else:
  568. result = g.inclToMod.getOrDefault(fileIdx)
  569. proc transitiveClosure(g: var IntSet; n: int) =
  570. # warshall's algorithm
  571. for k in 0..<n:
  572. for i in 0..<n:
  573. for j in 0..<n:
  574. if i != j and not g.contains(i.dependsOn(j)):
  575. if g.contains(i.dependsOn(k)) and g.contains(k.dependsOn(j)):
  576. g.incl i.dependsOn(j)
  577. proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  578. let m = g.getModule fileIdx
  579. if m != nil:
  580. g.suggestSymbols.del(fileIdx)
  581. g.suggestErrors.del(fileIdx)
  582. incl m.flags, sfDirty
  583. proc unmarkAllDirty*(g: ModuleGraph) =
  584. for i in 0i32..<g.ifaces.len.int32:
  585. let m = g.ifaces[i].module
  586. if m != nil:
  587. m.flags.excl sfDirty
  588. proc isDirty*(g: ModuleGraph; m: PSym): bool =
  589. result = g.suggestMode and sfDirty in m.flags
  590. proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
  591. # we need to mark its dependent modules D as dirty right away because after
  592. # nimsuggest is done with this module, the module's dirty flag will be
  593. # cleared but D still needs to be remembered as 'dirty'.
  594. if g.invalidTransitiveClosure:
  595. g.invalidTransitiveClosure = false
  596. transitiveClosure(g.deps, g.ifaces.len)
  597. # every module that *depends* on this file is also dirty:
  598. for i in 0i32..<g.ifaces.len.int32:
  599. if g.deps.contains(i.dependsOn(fileIdx.int)):
  600. g.markDirty(FileIndex(i))
  601. proc needsCompilation*(g: ModuleGraph): bool =
  602. # every module that *depends* on this file is also dirty:
  603. result = false
  604. for i in 0i32..<g.ifaces.len.int32:
  605. let m = g.ifaces[i].module
  606. if m != nil:
  607. if sfDirty in m.flags:
  608. return true
  609. proc needsCompilation*(g: ModuleGraph, fileIdx: FileIndex): bool =
  610. result = false
  611. let module = g.getModule(fileIdx)
  612. if module != nil and g.isDirty(module):
  613. return true
  614. for i in 0i32..<g.ifaces.len.int32:
  615. let m = g.ifaces[i].module
  616. if m != nil and g.isDirty(m) and g.deps.contains(fileIdx.int32.dependsOn(i)):
  617. return true
  618. proc getBody*(g: ModuleGraph; s: PSym): PNode {.inline.} =
  619. result = s.ast[bodyPos]
  620. if result == nil and g.config.symbolFiles in {readOnlySf, v2Sf, stressTest}:
  621. result = loadProcBody(g.config, g.cache, g.packed, s)
  622. s.ast[bodyPos] = result
  623. assert result != nil
  624. proc moduleFromRodFile*(g: ModuleGraph; fileIdx: FileIndex;
  625. cachedModules: var seq[FileIndex]): PSym =
  626. ## Returns 'nil' if the module needs to be recompiled.
  627. if g.config.symbolFiles in {readOnlySf, v2Sf, stressTest}:
  628. result = moduleFromRodFile(g.packed, g.config, g.cache, fileIdx, cachedModules)
  629. else:
  630. result = nil
  631. proc configComplete*(g: ModuleGraph) =
  632. rememberStartupConfig(g.startupPackedConfig, g.config)
  633. proc onProcessing*(graph: ModuleGraph, fileIdx: FileIndex, moduleStatus: string, fromModule: PSym, ) =
  634. let conf = graph.config
  635. let isNimscript = conf.isDefined("nimscript")
  636. if (not isNimscript) or hintProcessing in conf.cmdlineNotes:
  637. let path = toFilenameOption(conf, fileIdx, conf.filenameOption)
  638. let indent = ">".repeat(graph.importStack.len)
  639. let fromModule2 = if fromModule != nil: $fromModule.name.s else: "(toplevel)"
  640. let mode = if isNimscript: "(nims) " else: ""
  641. rawMessage(conf, hintProcessing, "$#$# $#: $#: $#" % [mode, indent, fromModule2, moduleStatus, path])
  642. proc getPackage*(graph: ModuleGraph; fileIdx: FileIndex): PSym =
  643. ## Returns a package symbol for yet to be defined module for fileIdx.
  644. ## The package symbol is added to the graph if it doesn't exist.
  645. let pkgSym = getPackage(graph.config, graph.cache, fileIdx)
  646. # check if the package is already in the graph
  647. result = graph.packageSyms.strTableGet(pkgSym.name)
  648. if result == nil:
  649. # the package isn't in the graph, so create and add it
  650. result = pkgSym
  651. graph.packageSyms.strTableAdd(pkgSym)
  652. func belongsToStdlib*(graph: ModuleGraph, sym: PSym): bool =
  653. ## Check if symbol belongs to the 'stdlib' package.
  654. sym.getPackageSymbol.getPackageId == graph.systemModule.getPackageId
  655. proc fileSymbols*(graph: ModuleGraph, fileIdx: FileIndex): SuggestFileSymbolDatabase =
  656. result = graph.suggestSymbols.getOrDefault(fileIdx, newSuggestFileSymbolDatabase(fileIdx, optIdeExceptionInlayHints in graph.config.globalOptions))
  657. doAssert(result.fileIndex == fileIdx)
  658. iterator suggestSymbolsIter*(g: ModuleGraph): SymInfoPair =
  659. for xs in g.suggestSymbols.values:
  660. for i in xs.lineInfo.low..xs.lineInfo.high:
  661. yield xs.getSymInfoPair(i)
  662. iterator suggestErrorsIter*(g: ModuleGraph): Suggest =
  663. for xs in g.suggestErrors.values:
  664. for x in xs:
  665. yield x