rodimpl.nim 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2018 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 new compilation cache.
  10. import strutils, os, intsets, tables, ropes, db_sqlite, msgs, options, types,
  11. renderer, rodutils, idents, astalgo, btrees, magicsys, cgmeth, extccomp,
  12. btrees, trees, condsyms, nversion, pathutils
  13. ## Todo:
  14. ## - Dependency computation should use *signature* hashes in order to
  15. ## avoid recompiling dependent modules.
  16. ## - Patch the rest of the compiler to do lazy loading of proc bodies.
  17. ## - Patch the C codegen to cache proc bodies and maybe types.
  18. template db(): DbConn = g.incr.db
  19. proc encodeConfig(g: ModuleGraph): string =
  20. result = newStringOfCap(100)
  21. result.add RodFileVersion
  22. for d in definedSymbolNames(g.config.symbols):
  23. result.add ' '
  24. result.add d
  25. template serialize(field) =
  26. result.add ' '
  27. result.add($g.config.field)
  28. depConfigFields(serialize)
  29. proc needsRecompile(g: ModuleGraph; fileIdx: FileIndex; fullpath: AbsoluteFile;
  30. cycleCheck: var IntSet): bool =
  31. let root = db.getRow(sql"select id, fullhash from filenames where fullpath = ?",
  32. fullpath.string)
  33. if root[0].len == 0: return true
  34. if root[1] != hashFileCached(g.config, fileIdx, fullpath):
  35. return true
  36. # cycle detection: assume "not changed" is correct.
  37. if cycleCheck.containsOrIncl(int fileIdx):
  38. return false
  39. # check dependencies (recursively):
  40. for row in db.fastRows(sql"select fullpath from filenames where id in (select dependency from deps where module = ?)",
  41. root[0]):
  42. let dep = AbsoluteFile row[0]
  43. if needsRecompile(g, g.config.fileInfoIdx(dep), dep, cycleCheck):
  44. return true
  45. return false
  46. proc getModuleId(g: ModuleGraph; fileIdx: FileIndex; fullpath: AbsoluteFile): int =
  47. ## Analyse the known dependency graph.
  48. if g.config.symbolFiles == disabledSf: return getID()
  49. when false:
  50. if g.config.symbolFiles in {disabledSf, writeOnlySf} or
  51. g.incr.configChanged:
  52. return getID()
  53. let module = g.incr.db.getRow(
  54. sql"select id, fullHash, nimid from modules where fullpath = ?", string fullpath)
  55. let currentFullhash = hashFileCached(g.config, fileIdx, fullpath)
  56. if module[0].len == 0:
  57. result = getID()
  58. db.exec(sql"insert into modules(fullpath, interfHash, fullHash, nimid) values (?, ?, ?, ?)",
  59. string fullpath, "", currentFullhash, result)
  60. else:
  61. result = parseInt(module[2])
  62. if currentFullhash == module[1]:
  63. # not changed, so use the cached AST:
  64. doAssert(result != 0)
  65. var cycleCheck = initIntSet()
  66. if not needsRecompile(g, fileIdx, fullpath, cycleCheck) and not g.incr.configChanged:
  67. echo "cached successfully! ", string fullpath
  68. return -result
  69. db.exec(sql"update modules set fullHash = ? where id = ?", currentFullhash, module[0])
  70. db.exec(sql"delete from deps where module = ?", module[0])
  71. db.exec(sql"delete from types where module = ?", module[0])
  72. db.exec(sql"delete from syms where module = ?", module[0])
  73. db.exec(sql"delete from toplevelstmts where module = ?", module[0])
  74. db.exec(sql"delete from statics where module = ?", module[0])
  75. proc loadModuleSym*(g: ModuleGraph; fileIdx: FileIndex; fullpath: AbsoluteFile): (PSym, int) =
  76. let id = getModuleId(g, fileIdx, fullpath)
  77. result = (g.incr.r.syms.getOrDefault(abs id), id)
  78. proc pushType(w: var Writer, t: PType) =
  79. if not containsOrIncl(w.tmarks, t.uniqueId):
  80. w.tstack.add(t)
  81. proc pushSym(w: var Writer, s: PSym) =
  82. if not containsOrIncl(w.smarks, s.id):
  83. w.sstack.add(s)
  84. template w: untyped = g.incr.w
  85. proc encodeNode(g: ModuleGraph; fInfo: TLineInfo, n: PNode,
  86. result: var string) =
  87. if n == nil:
  88. # nil nodes have to be stored too:
  89. result.add("()")
  90. return
  91. result.add('(')
  92. encodeVInt(ord(n.kind), result)
  93. # we do not write comments for now
  94. # Line information takes easily 20% or more of the filesize! Therefore we
  95. # omit line information if it is the same as the parent's line information:
  96. if fInfo.fileIndex != n.info.fileIndex:
  97. result.add('?')
  98. encodeVInt(n.info.col, result)
  99. result.add(',')
  100. encodeVInt(int n.info.line, result)
  101. result.add(',')
  102. #encodeVInt(toDbFileId(g.incr, g.config, n.info.fileIndex), result)
  103. encodeVInt(n.info.fileIndex.int, result)
  104. elif fInfo.line != n.info.line:
  105. result.add('?')
  106. encodeVInt(n.info.col, result)
  107. result.add(',')
  108. encodeVInt(int n.info.line, result)
  109. elif fInfo.col != n.info.col:
  110. result.add('?')
  111. encodeVInt(n.info.col, result)
  112. # No need to output the file index, as this is the serialization of one
  113. # file.
  114. let f = n.flags * PersistentNodeFlags
  115. if f != {}:
  116. result.add('$')
  117. encodeVInt(cast[int32](f), result)
  118. if n.typ != nil:
  119. result.add('^')
  120. encodeVInt(n.typ.uniqueId, result)
  121. pushType(w, n.typ)
  122. case n.kind
  123. of nkCharLit..nkUInt64Lit:
  124. if n.intVal != 0:
  125. result.add('!')
  126. encodeVBiggestInt(n.intVal, result)
  127. of nkFloatLit..nkFloat64Lit:
  128. if n.floatVal != 0.0:
  129. result.add('!')
  130. encodeStr($n.floatVal, result)
  131. of nkStrLit..nkTripleStrLit:
  132. if n.strVal != "":
  133. result.add('!')
  134. encodeStr(n.strVal, result)
  135. of nkIdent:
  136. result.add('!')
  137. encodeStr(n.ident.s, result)
  138. of nkSym:
  139. result.add('!')
  140. encodeVInt(n.sym.id, result)
  141. pushSym(w, n.sym)
  142. else:
  143. for i in countup(0, sonsLen(n) - 1):
  144. encodeNode(g, n.info, n.sons[i], result)
  145. add(result, ')')
  146. proc encodeLoc(g: ModuleGraph; loc: TLoc, result: var string) =
  147. var oldLen = result.len
  148. result.add('<')
  149. if loc.k != low(loc.k): encodeVInt(ord(loc.k), result)
  150. if loc.storage != low(loc.storage):
  151. add(result, '*')
  152. encodeVInt(ord(loc.storage), result)
  153. if loc.flags != {}:
  154. add(result, '$')
  155. encodeVInt(cast[int32](loc.flags), result)
  156. if loc.lode != nil:
  157. add(result, '^')
  158. encodeNode(g, unknownLineInfo(), loc.lode, result)
  159. if loc.r != nil:
  160. add(result, '!')
  161. encodeStr($loc.r, result)
  162. if oldLen + 1 == result.len:
  163. # no data was necessary, so remove the '<' again:
  164. setLen(result, oldLen)
  165. else:
  166. add(result, '>')
  167. proc encodeType(g: ModuleGraph, t: PType, result: var string) =
  168. if t == nil:
  169. # nil nodes have to be stored too:
  170. result.add("[]")
  171. return
  172. # we need no surrounding [] here because the type is in a line of its own
  173. if t.kind == tyForward: internalError(g.config, "encodeType: tyForward")
  174. # for the new rodfile viewer we use a preceding [ so that the data section
  175. # can easily be disambiguated:
  176. add(result, '[')
  177. encodeVInt(ord(t.kind), result)
  178. add(result, '+')
  179. encodeVInt(t.uniqueId, result)
  180. if t.id != t.uniqueId:
  181. add(result, '+')
  182. encodeVInt(t.id, result)
  183. if t.n != nil:
  184. encodeNode(g, unknownLineInfo(), t.n, result)
  185. if t.flags != {}:
  186. add(result, '$')
  187. encodeVInt(cast[int32](t.flags), result)
  188. if t.callConv != low(t.callConv):
  189. add(result, '?')
  190. encodeVInt(ord(t.callConv), result)
  191. if t.owner != nil:
  192. add(result, '*')
  193. encodeVInt(t.owner.id, result)
  194. pushSym(w, t.owner)
  195. if t.sym != nil:
  196. add(result, '&')
  197. encodeVInt(t.sym.id, result)
  198. pushSym(w, t.sym)
  199. if t.size != - 1:
  200. add(result, '/')
  201. encodeVBiggestInt(t.size, result)
  202. if t.align != 2:
  203. add(result, '=')
  204. encodeVInt(t.align, result)
  205. if t.lockLevel.ord != UnspecifiedLockLevel.ord:
  206. add(result, '\14')
  207. encodeVInt(t.lockLevel.int16, result)
  208. if t.destructor != nil and t.destructor.id != 0:
  209. add(result, '\15')
  210. encodeVInt(t.destructor.id, result)
  211. pushSym(w, t.destructor)
  212. if t.deepCopy != nil:
  213. add(result, '\16')
  214. encodeVInt(t.deepcopy.id, result)
  215. pushSym(w, t.deepcopy)
  216. if t.assignment != nil:
  217. add(result, '\17')
  218. encodeVInt(t.assignment.id, result)
  219. pushSym(w, t.assignment)
  220. if t.sink != nil:
  221. add(result, '\18')
  222. encodeVInt(t.sink.id, result)
  223. pushSym(w, t.sink)
  224. for i, s in items(t.methods):
  225. add(result, '\19')
  226. encodeVInt(i, result)
  227. add(result, '\20')
  228. encodeVInt(s.id, result)
  229. pushSym(w, s)
  230. encodeLoc(g, t.loc, result)
  231. if t.typeInst != nil:
  232. add(result, '\21')
  233. encodeVInt(t.typeInst.uniqueId, result)
  234. pushType(w, t.typeInst)
  235. for i in countup(0, sonsLen(t) - 1):
  236. if t.sons[i] == nil:
  237. add(result, "^()")
  238. else:
  239. add(result, '^')
  240. encodeVInt(t.sons[i].uniqueId, result)
  241. pushType(w, t.sons[i])
  242. proc encodeLib(g: ModuleGraph, lib: PLib, info: TLineInfo, result: var string) =
  243. add(result, '|')
  244. encodeVInt(ord(lib.kind), result)
  245. add(result, '|')
  246. encodeStr($lib.name, result)
  247. add(result, '|')
  248. encodeNode(g, info, lib.path, result)
  249. proc encodeInstantiations(g: ModuleGraph; s: seq[PInstantiation];
  250. result: var string) =
  251. for t in s:
  252. result.add('\15')
  253. encodeVInt(t.sym.id, result)
  254. pushSym(w, t.sym)
  255. for tt in t.concreteTypes:
  256. result.add('\17')
  257. encodeVInt(tt.uniqueId, result)
  258. pushType(w, tt)
  259. result.add('\20')
  260. encodeVInt(t.compilesId, result)
  261. proc encodeSym(g: ModuleGraph, s: PSym, result: var string) =
  262. if s == nil:
  263. # nil nodes have to be stored too:
  264. result.add("{}")
  265. return
  266. # we need no surrounding {} here because the symbol is in a line of its own
  267. encodeVInt(ord(s.kind), result)
  268. result.add('+')
  269. encodeVInt(s.id, result)
  270. result.add('&')
  271. encodeStr(s.name.s, result)
  272. if s.typ != nil:
  273. result.add('^')
  274. encodeVInt(s.typ.uniqueId, result)
  275. pushType(w, s.typ)
  276. result.add('?')
  277. if s.info.col != -1'i16: encodeVInt(s.info.col, result)
  278. result.add(',')
  279. encodeVInt(int s.info.line, result)
  280. result.add(',')
  281. #encodeVInt(toDbFileId(g.incr, g.config, s.info.fileIndex), result)
  282. encodeVInt(s.info.fileIndex.int, result)
  283. if s.owner != nil:
  284. result.add('*')
  285. encodeVInt(s.owner.id, result)
  286. pushSym(w, s.owner)
  287. if s.flags != {}:
  288. result.add('$')
  289. encodeVInt(cast[int32](s.flags), result)
  290. if s.magic != mNone:
  291. result.add('@')
  292. encodeVInt(ord(s.magic), result)
  293. result.add('!')
  294. encodeVInt(cast[int32](s.options), result)
  295. if s.position != 0:
  296. result.add('%')
  297. encodeVInt(s.position, result)
  298. if s.offset != - 1:
  299. result.add('`')
  300. encodeVInt(s.offset, result)
  301. encodeLoc(g, s.loc, result)
  302. if s.annex != nil: encodeLib(g, s.annex, s.info, result)
  303. if s.constraint != nil:
  304. add(result, '#')
  305. encodeNode(g, unknownLineInfo(), s.constraint, result)
  306. case s.kind
  307. of skType, skGenericParam:
  308. for t in s.typeInstCache:
  309. result.add('\14')
  310. encodeVInt(t.uniqueId, result)
  311. pushType(w, t)
  312. of routineKinds:
  313. encodeInstantiations(g, s.procInstCache, result)
  314. if s.gcUnsafetyReason != nil:
  315. result.add('\16')
  316. encodeVInt(s.gcUnsafetyReason.id, result)
  317. pushSym(w, s.gcUnsafetyReason)
  318. if s.transformedBody != nil:
  319. result.add('\24')
  320. encodeNode(g, s.info, s.transformedBody, result)
  321. of skModule, skPackage:
  322. encodeInstantiations(g, s.usedGenerics, result)
  323. # we don't serialize:
  324. #tab*: TStrTable # interface table for modules
  325. of skLet, skVar, skField, skForVar:
  326. if s.guard != nil:
  327. result.add('\18')
  328. encodeVInt(s.guard.id, result)
  329. pushSym(w, s.guard)
  330. if s.bitsize != 0:
  331. result.add('\19')
  332. encodeVInt(s.bitsize, result)
  333. else: discard
  334. # lazy loading will soon reload the ast lazily, so the ast needs to be
  335. # the last entry of a symbol:
  336. if s.ast != nil:
  337. # we used to attempt to save space here by only storing a dummy AST if
  338. # it is not necessary, but Nim's heavy compile-time evaluation features
  339. # make that unfeasible nowadays:
  340. encodeNode(g, s.info, s.ast, result)
  341. proc storeSym(g: ModuleGraph; s: PSym) =
  342. if sfForward in s.flags and s.kind != skModule:
  343. w.forwardedSyms.add s
  344. return
  345. var buf = newStringOfCap(160)
  346. encodeSym(g, s, buf)
  347. # XXX only store the name for exported symbols in order to speed up lookup
  348. # times once we enable the skStub logic.
  349. let m = getModule(s)
  350. let mid = if m == nil: 0 else: abs(m.id)
  351. db.exec(sql"insert into syms(nimid, module, name, data, exported) values (?, ?, ?, ?, ?)",
  352. s.id, mid, s.name.s, buf, ord(sfExported in s.flags))
  353. proc storeType(g: ModuleGraph; t: PType) =
  354. var buf = newStringOfCap(160)
  355. encodeType(g, t, buf)
  356. let m = if t.owner != nil: getModule(t.owner) else: nil
  357. let mid = if m == nil: 0 else: abs(m.id)
  358. db.exec(sql"insert into types(nimid, module, data) values (?, ?, ?)",
  359. t.uniqueId, mid, buf)
  360. proc transitiveClosure(g: ModuleGraph) =
  361. var i = 0
  362. while true:
  363. if i > 100_000:
  364. doAssert false, "loop never ends!"
  365. if w.sstack.len > 0:
  366. let s = w.sstack.pop()
  367. when false:
  368. echo "popped ", s.name.s, " ", s.id
  369. storeSym(g, s)
  370. elif w.tstack.len > 0:
  371. let t = w.tstack.pop()
  372. storeType(g, t)
  373. when false:
  374. echo "popped type ", typeToString(t), " ", t.uniqueId
  375. else:
  376. break
  377. inc i
  378. proc storeNode*(g: ModuleGraph; module: PSym; n: PNode) =
  379. if g.config.symbolFiles == disabledSf: return
  380. var buf = newStringOfCap(160)
  381. encodeNode(g, module.info, n, buf)
  382. db.exec(sql"insert into toplevelstmts(module, position, data) values (?, ?, ?)",
  383. abs(module.id), module.offset, buf)
  384. inc module.offset
  385. transitiveClosure(g)
  386. proc recordStmt*(g: ModuleGraph; module: PSym; n: PNode) =
  387. storeNode(g, module, n)
  388. proc storeFilename(g: ModuleGraph; fullpath: AbsoluteFile; fileIdx: FileIndex) =
  389. let id = db.getValue(sql"select id from filenames where fullpath = ?", fullpath.string)
  390. if id.len == 0:
  391. let fullhash = hashFileCached(g.config, fileIdx, fullpath)
  392. db.exec(sql"insert into filenames(nimid, fullpath, fullhash) values (?, ?, ?)",
  393. int(fileIdx), fullpath.string, fullhash)
  394. proc storeRemaining*(g: ModuleGraph; module: PSym) =
  395. if g.config.symbolFiles == disabledSf: return
  396. var stillForwarded: seq[PSym] = @[]
  397. for s in w.forwardedSyms:
  398. if sfForward notin s.flags:
  399. storeSym(g, s)
  400. else:
  401. stillForwarded.add s
  402. swap w.forwardedSyms, stillForwarded
  403. transitiveClosure(g)
  404. var nimid = 0
  405. for x in items(g.config.m.fileInfos):
  406. # don't store the "command line" entry:
  407. if nimid != 0:
  408. storeFilename(g, x.fullPath, FileIndex(nimid))
  409. inc nimid
  410. # ---------------- decoder -----------------------------------
  411. type
  412. BlobReader = object
  413. s: string
  414. pos: int
  415. using
  416. b: var BlobReader
  417. g: ModuleGraph
  418. proc loadSym(g; id: int, info: TLineInfo): PSym
  419. proc loadType(g; id: int, info: TLineInfo): PType
  420. proc decodeLineInfo(g; b; info: var TLineInfo) =
  421. if b.s[b.pos] == '?':
  422. inc(b.pos)
  423. if b.s[b.pos] == ',': info.col = -1'i16
  424. else: info.col = int16(decodeVInt(b.s, b.pos))
  425. if b.s[b.pos] == ',':
  426. inc(b.pos)
  427. if b.s[b.pos] == ',': info.line = 0'u16
  428. else: info.line = uint16(decodeVInt(b.s, b.pos))
  429. if b.s[b.pos] == ',':
  430. inc(b.pos)
  431. #info.fileIndex = fromDbFileId(g.incr, g.config, decodeVInt(b.s, b.pos))
  432. info.fileIndex = FileIndex decodeVInt(b.s, b.pos)
  433. proc skipNode(b) =
  434. # ')' itself cannot be part of a string literal so that this is correct.
  435. assert b.s[b.pos] == '('
  436. var par = 0
  437. var pos = b.pos+1
  438. while true:
  439. case b.s[pos]
  440. of ')':
  441. if par == 0: break
  442. dec par
  443. of '(': inc par
  444. else: discard
  445. inc pos
  446. b.pos = pos+1 # skip ')'
  447. proc decodeNodeLazyBody(g; b; fInfo: TLineInfo,
  448. belongsTo: PSym): PNode =
  449. result = nil
  450. if b.s[b.pos] == '(':
  451. inc(b.pos)
  452. if b.s[b.pos] == ')':
  453. inc(b.pos)
  454. return # nil node
  455. result = newNodeI(TNodeKind(decodeVInt(b.s, b.pos)), fInfo)
  456. decodeLineInfo(g, b, result.info)
  457. if b.s[b.pos] == '$':
  458. inc(b.pos)
  459. result.flags = cast[TNodeFlags](int32(decodeVInt(b.s, b.pos)))
  460. if b.s[b.pos] == '^':
  461. inc(b.pos)
  462. var id = decodeVInt(b.s, b.pos)
  463. result.typ = loadType(g, id, result.info)
  464. case result.kind
  465. of nkCharLit..nkUInt64Lit:
  466. if b.s[b.pos] == '!':
  467. inc(b.pos)
  468. result.intVal = decodeVBiggestInt(b.s, b.pos)
  469. of nkFloatLit..nkFloat64Lit:
  470. if b.s[b.pos] == '!':
  471. inc(b.pos)
  472. var fl = decodeStr(b.s, b.pos)
  473. result.floatVal = parseFloat(fl)
  474. of nkStrLit..nkTripleStrLit:
  475. if b.s[b.pos] == '!':
  476. inc(b.pos)
  477. result.strVal = decodeStr(b.s, b.pos)
  478. else:
  479. result.strVal = ""
  480. of nkIdent:
  481. if b.s[b.pos] == '!':
  482. inc(b.pos)
  483. var fl = decodeStr(b.s, b.pos)
  484. result.ident = g.cache.getIdent(fl)
  485. else:
  486. internalError(g.config, result.info, "decodeNode: nkIdent")
  487. of nkSym:
  488. if b.s[b.pos] == '!':
  489. inc(b.pos)
  490. var id = decodeVInt(b.s, b.pos)
  491. result.sym = loadSym(g, id, result.info)
  492. else:
  493. internalError(g.config, result.info, "decodeNode: nkSym")
  494. else:
  495. var i = 0
  496. while b.s[b.pos] != ')':
  497. when false:
  498. if belongsTo != nil and i == bodyPos:
  499. addSonNilAllowed(result, nil)
  500. belongsTo.offset = b.pos
  501. skipNode(b)
  502. else:
  503. discard
  504. addSonNilAllowed(result, decodeNodeLazyBody(g, b, result.info, nil))
  505. inc i
  506. if b.s[b.pos] == ')': inc(b.pos)
  507. else: internalError(g.config, result.info, "decodeNode: ')' missing")
  508. else:
  509. internalError(g.config, fInfo, "decodeNode: '(' missing " & $b.pos)
  510. proc decodeNode(g; b; fInfo: TLineInfo): PNode =
  511. result = decodeNodeLazyBody(g, b, fInfo, nil)
  512. proc decodeLoc(g; b; loc: var TLoc, info: TLineInfo) =
  513. if b.s[b.pos] == '<':
  514. inc(b.pos)
  515. if b.s[b.pos] in {'0'..'9', 'a'..'z', 'A'..'Z'}:
  516. loc.k = TLocKind(decodeVInt(b.s, b.pos))
  517. else:
  518. loc.k = low(loc.k)
  519. if b.s[b.pos] == '*':
  520. inc(b.pos)
  521. loc.storage = TStorageLoc(decodeVInt(b.s, b.pos))
  522. else:
  523. loc.storage = low(loc.storage)
  524. if b.s[b.pos] == '$':
  525. inc(b.pos)
  526. loc.flags = cast[TLocFlags](int32(decodeVInt(b.s, b.pos)))
  527. else:
  528. loc.flags = {}
  529. if b.s[b.pos] == '^':
  530. inc(b.pos)
  531. loc.lode = decodeNode(g, b, info)
  532. # rrGetType(b, decodeVInt(b.s, b.pos), info)
  533. else:
  534. loc.lode = nil
  535. if b.s[b.pos] == '!':
  536. inc(b.pos)
  537. loc.r = rope(decodeStr(b.s, b.pos))
  538. else:
  539. loc.r = nil
  540. if b.s[b.pos] == '>': inc(b.pos)
  541. else: internalError(g.config, info, "decodeLoc " & b.s[b.pos])
  542. proc loadBlob(g; query: SqlQuery; id: int): BlobReader =
  543. let blob = db.getValue(query, id)
  544. if blob.len == 0:
  545. internalError(g.config, "symbolfiles: cannot find ID " & $ id)
  546. result = BlobReader(pos: 0)
  547. shallowCopy(result.s, blob)
  548. # ensure we can read without index checks:
  549. result.s.add '\0'
  550. proc loadType(g; id: int; info: TLineInfo): PType =
  551. result = g.incr.r.types.getOrDefault(id)
  552. if result != nil: return result
  553. var b = loadBlob(g, sql"select data from types where nimid = ?", id)
  554. if b.s[b.pos] == '[':
  555. inc(b.pos)
  556. if b.s[b.pos] == ']':
  557. inc(b.pos)
  558. return # nil type
  559. new(result)
  560. result.kind = TTypeKind(decodeVInt(b.s, b.pos))
  561. if b.s[b.pos] == '+':
  562. inc(b.pos)
  563. result.uniqueId = decodeVInt(b.s, b.pos)
  564. setId(result.uniqueId)
  565. #if debugIds: registerID(result)
  566. else:
  567. internalError(g.config, info, "decodeType: no id")
  568. if b.s[b.pos] == '+':
  569. inc(b.pos)
  570. result.id = decodeVInt(b.s, b.pos)
  571. else:
  572. result.id = result.uniqueId
  573. # here this also avoids endless recursion for recursive type
  574. g.incr.r.types.add(result.uniqueId, result)
  575. if b.s[b.pos] == '(': result.n = decodeNode(g, b, unknownLineInfo())
  576. if b.s[b.pos] == '$':
  577. inc(b.pos)
  578. result.flags = cast[TTypeFlags](int32(decodeVInt(b.s, b.pos)))
  579. if b.s[b.pos] == '?':
  580. inc(b.pos)
  581. result.callConv = TCallingConvention(decodeVInt(b.s, b.pos))
  582. if b.s[b.pos] == '*':
  583. inc(b.pos)
  584. result.owner = loadSym(g, decodeVInt(b.s, b.pos), info)
  585. if b.s[b.pos] == '&':
  586. inc(b.pos)
  587. result.sym = loadSym(g, decodeVInt(b.s, b.pos), info)
  588. if b.s[b.pos] == '/':
  589. inc(b.pos)
  590. result.size = decodeVInt(b.s, b.pos)
  591. else:
  592. result.size = -1
  593. if b.s[b.pos] == '=':
  594. inc(b.pos)
  595. result.align = decodeVInt(b.s, b.pos).int16
  596. else:
  597. result.align = 2
  598. if b.s[b.pos] == '\14':
  599. inc(b.pos)
  600. result.lockLevel = decodeVInt(b.s, b.pos).TLockLevel
  601. else:
  602. result.lockLevel = UnspecifiedLockLevel
  603. if b.s[b.pos] == '\15':
  604. inc(b.pos)
  605. result.destructor = loadSym(g, decodeVInt(b.s, b.pos), info)
  606. if b.s[b.pos] == '\16':
  607. inc(b.pos)
  608. result.deepCopy = loadSym(g, decodeVInt(b.s, b.pos), info)
  609. if b.s[b.pos] == '\17':
  610. inc(b.pos)
  611. result.assignment = loadSym(g, decodeVInt(b.s, b.pos), info)
  612. if b.s[b.pos] == '\18':
  613. inc(b.pos)
  614. result.sink = loadSym(g, decodeVInt(b.s, b.pos), info)
  615. while b.s[b.pos] == '\19':
  616. inc(b.pos)
  617. let x = decodeVInt(b.s, b.pos)
  618. doAssert b.s[b.pos] == '\20'
  619. inc(b.pos)
  620. let y = loadSym(g, decodeVInt(b.s, b.pos), info)
  621. result.methods.add((x, y))
  622. decodeLoc(g, b, result.loc, info)
  623. if b.s[b.pos] == '\21':
  624. inc(b.pos)
  625. let d = decodeVInt(b.s, b.pos)
  626. result.typeInst = loadType(g, d, info)
  627. while b.s[b.pos] == '^':
  628. inc(b.pos)
  629. if b.s[b.pos] == '(':
  630. inc(b.pos)
  631. if b.s[b.pos] == ')': inc(b.pos)
  632. else: internalError(g.config, info, "decodeType ^(" & b.s[b.pos])
  633. rawAddSon(result, nil)
  634. else:
  635. let d = decodeVInt(b.s, b.pos)
  636. rawAddSon(result, loadType(g, d, info))
  637. proc decodeLib(g; b; info: TLineInfo): PLib =
  638. result = nil
  639. if b.s[b.pos] == '|':
  640. new(result)
  641. inc(b.pos)
  642. result.kind = TLibKind(decodeVInt(b.s, b.pos))
  643. if b.s[b.pos] != '|': internalError(g.config, "decodeLib: 1")
  644. inc(b.pos)
  645. result.name = rope(decodeStr(b.s, b.pos))
  646. if b.s[b.pos] != '|': internalError(g.config, "decodeLib: 2")
  647. inc(b.pos)
  648. result.path = decodeNode(g, b, info)
  649. proc decodeInstantiations(g; b; info: TLineInfo;
  650. s: var seq[PInstantiation]) =
  651. while b.s[b.pos] == '\15':
  652. inc(b.pos)
  653. var ii: PInstantiation
  654. new ii
  655. ii.sym = loadSym(g, decodeVInt(b.s, b.pos), info)
  656. ii.concreteTypes = @[]
  657. while b.s[b.pos] == '\17':
  658. inc(b.pos)
  659. ii.concreteTypes.add loadType(g, decodeVInt(b.s, b.pos), info)
  660. if b.s[b.pos] == '\20':
  661. inc(b.pos)
  662. ii.compilesId = decodeVInt(b.s, b.pos)
  663. s.add ii
  664. proc loadSymFromBlob(g; b; info: TLineInfo): PSym =
  665. if b.s[b.pos] == '{':
  666. inc(b.pos)
  667. if b.s[b.pos] == '}':
  668. inc(b.pos)
  669. return # nil sym
  670. var k = TSymKind(decodeVInt(b.s, b.pos))
  671. var id: int
  672. if b.s[b.pos] == '+':
  673. inc(b.pos)
  674. id = decodeVInt(b.s, b.pos)
  675. setId(id)
  676. else:
  677. internalError(g.config, info, "decodeSym: no id")
  678. var ident: PIdent
  679. if b.s[b.pos] == '&':
  680. inc(b.pos)
  681. ident = g.cache.getIdent(decodeStr(b.s, b.pos))
  682. else:
  683. internalError(g.config, info, "decodeSym: no ident")
  684. #echo "decoding: {", ident.s
  685. new(result)
  686. result.id = id
  687. result.kind = k
  688. result.name = ident # read the rest of the symbol description:
  689. g.incr.r.syms.add(result.id, result)
  690. if b.s[b.pos] == '^':
  691. inc(b.pos)
  692. result.typ = loadType(g, decodeVInt(b.s, b.pos), info)
  693. decodeLineInfo(g, b, result.info)
  694. if b.s[b.pos] == '*':
  695. inc(b.pos)
  696. result.owner = loadSym(g, decodeVInt(b.s, b.pos), result.info)
  697. if b.s[b.pos] == '$':
  698. inc(b.pos)
  699. result.flags = cast[TSymFlags](int32(decodeVInt(b.s, b.pos)))
  700. if b.s[b.pos] == '@':
  701. inc(b.pos)
  702. result.magic = TMagic(decodeVInt(b.s, b.pos))
  703. if b.s[b.pos] == '!':
  704. inc(b.pos)
  705. result.options = cast[TOptions](int32(decodeVInt(b.s, b.pos)))
  706. if b.s[b.pos] == '%':
  707. inc(b.pos)
  708. result.position = decodeVInt(b.s, b.pos)
  709. if b.s[b.pos] == '`':
  710. inc(b.pos)
  711. result.offset = decodeVInt(b.s, b.pos)
  712. else:
  713. result.offset = -1
  714. decodeLoc(g, b, result.loc, result.info)
  715. result.annex = decodeLib(g, b, info)
  716. if b.s[b.pos] == '#':
  717. inc(b.pos)
  718. result.constraint = decodeNode(g, b, unknownLineInfo())
  719. case result.kind
  720. of skType, skGenericParam:
  721. while b.s[b.pos] == '\14':
  722. inc(b.pos)
  723. result.typeInstCache.add loadType(g, decodeVInt(b.s, b.pos), result.info)
  724. of routineKinds:
  725. decodeInstantiations(g, b, result.info, result.procInstCache)
  726. if b.s[b.pos] == '\16':
  727. inc(b.pos)
  728. result.gcUnsafetyReason = loadSym(g, decodeVInt(b.s, b.pos), result.info)
  729. if b.s[b.pos] == '\24':
  730. inc b.pos
  731. result.transformedBody = decodeNode(g, b, result.info)
  732. of skModule, skPackage:
  733. decodeInstantiations(g, b, result.info, result.usedGenerics)
  734. of skLet, skVar, skField, skForVar:
  735. if b.s[b.pos] == '\18':
  736. inc(b.pos)
  737. result.guard = loadSym(g, decodeVInt(b.s, b.pos), result.info)
  738. if b.s[b.pos] == '\19':
  739. inc(b.pos)
  740. result.bitsize = decodeVInt(b.s, b.pos).int16
  741. else: discard
  742. if b.s[b.pos] == '(':
  743. #if result.kind in routineKinds:
  744. # result.ast = decodeNodeLazyBody(b, result.info, result)
  745. #else:
  746. result.ast = decodeNode(g, b, result.info)
  747. if sfCompilerProc in result.flags:
  748. registerCompilerProc(g, result)
  749. #echo "loading ", result.name.s
  750. proc loadSym(g; id: int; info: TLineInfo): PSym =
  751. result = g.incr.r.syms.getOrDefault(id)
  752. if result != nil: return result
  753. var b = loadBlob(g, sql"select data from syms where nimid = ?", id)
  754. result = loadSymFromBlob(g, b, info)
  755. doAssert id == result.id, "symbol ID is not consistent!"
  756. proc registerModule*(g; module: PSym) =
  757. g.incr.r.syms.add(abs module.id, module)
  758. proc loadModuleSymTab(g; module: PSym) =
  759. ## goal: fill module.tab
  760. g.incr.r.syms.add(module.id, module)
  761. for row in db.fastRows(sql"select nimid, data from syms where module = ? and exported = 1", abs(module.id)):
  762. let id = parseInt(row[0])
  763. var s = g.incr.r.syms.getOrDefault(id)
  764. if s == nil:
  765. var b = BlobReader(pos: 0)
  766. shallowCopy(b.s, row[1])
  767. # ensure we can read without index checks:
  768. b.s.add '\0'
  769. s = loadSymFromBlob(g, b, module.info)
  770. assert s != nil
  771. if s.kind != skField:
  772. strTableAdd(module.tab, s)
  773. if sfSystemModule in module.flags:
  774. g.systemModule = module
  775. proc replay(g: ModuleGraph; module: PSym; n: PNode) =
  776. # XXX check if we need to replay nkStaticStmt here.
  777. case n.kind
  778. #of nkStaticStmt:
  779. #evalStaticStmt(module, g, n[0], module)
  780. #of nkVarSection, nkLetSection:
  781. # nkVarSections are already covered by the vmgen which produces nkStaticStmt
  782. of nkMethodDef:
  783. methodDef(g, n[namePos].sym, fromCache=true)
  784. of nkCommentStmt:
  785. # pragmas are complex and can be user-overriden via templates. So
  786. # instead of using the original ``nkPragma`` nodes, we rely on the
  787. # fact that pragmas.nim was patched to produce specialized recorded
  788. # statements for us in the form of ``nkCommentStmt`` with (key, value)
  789. # pairs. Ordinary nkCommentStmt nodes never have children so this is
  790. # not ambiguous.
  791. # Fortunately only a tiny subset of the available pragmas need to
  792. # be replayed here. This is always a subset of ``pragmas.stmtPragmas``.
  793. if n.len >= 2:
  794. internalAssert g.config, n[0].kind == nkStrLit and n[1].kind == nkStrLit
  795. case n[0].strVal
  796. of "hint": message(g.config, n.info, hintUser, n[1].strVal)
  797. of "warning": message(g.config, n.info, warnUser, n[1].strVal)
  798. of "error": localError(g.config, n.info, errUser, n[1].strVal)
  799. of "compile":
  800. internalAssert g.config, n.len == 3 and n[2].kind == nkStrLit
  801. var cf = Cfile(cname: AbsoluteFile n[1].strVal, obj: AbsoluteFile n[2].strVal,
  802. flags: {CfileFlag.External})
  803. extccomp.addExternalFileToCompile(g.config, cf)
  804. of "link":
  805. extccomp.addExternalFileToLink(g.config, AbsoluteFile n[1].strVal)
  806. of "passl":
  807. extccomp.addLinkOption(g.config, n[1].strVal)
  808. of "passc":
  809. extccomp.addCompileOption(g.config, n[1].strVal)
  810. of "cppdefine":
  811. options.cppDefine(g.config, n[1].strVal)
  812. of "inc":
  813. let destKey = n[1].strVal
  814. let by = n[2].intVal
  815. let v = getOrDefault(g.cacheCounters, destKey)
  816. g.cacheCounters[destKey] = v+by
  817. of "put":
  818. let destKey = n[1].strVal
  819. let key = n[2].strVal
  820. let val = n[3]
  821. if not contains(g.cacheTables, destKey):
  822. g.cacheTables[destKey] = initBTree[string, PNode]()
  823. if not contains(g.cacheTables[destKey], key):
  824. g.cacheTables[destKey].add(key, val)
  825. else:
  826. internalError(g.config, n.info, "key already exists: " & key)
  827. of "incl":
  828. let destKey = n[1].strVal
  829. let val = n[2]
  830. if not contains(g.cacheSeqs, destKey):
  831. g.cacheSeqs[destKey] = newTree(nkStmtList, val)
  832. else:
  833. block search:
  834. for existing in g.cacheSeqs[destKey]:
  835. if exprStructuralEquivalent(existing, val, strictSymEquality=true):
  836. break search
  837. g.cacheSeqs[destKey].add val
  838. of "add":
  839. let destKey = n[1].strVal
  840. let val = n[2]
  841. if not contains(g.cacheSeqs, destKey):
  842. g.cacheSeqs[destKey] = newTree(nkStmtList, val)
  843. else:
  844. g.cacheSeqs[destKey].add val
  845. else:
  846. internalAssert g.config, false
  847. of nkImportStmt:
  848. for x in n:
  849. internalAssert g.config, x.kind == nkSym
  850. let modpath = AbsoluteFile toFullPath(g.config, x.sym.info)
  851. let imported = g.importModuleCallback(g, module, fileInfoIdx(g.config, modpath))
  852. internalAssert g.config, imported.id < 0
  853. of nkStmtList, nkStmtListExpr:
  854. for x in n: replay(g, module, x)
  855. else: discard "nothing to do for this node"
  856. proc loadNode*(g: ModuleGraph; module: PSym): PNode =
  857. loadModuleSymTab(g, module)
  858. result = newNodeI(nkStmtList, module.info)
  859. for row in db.rows(sql"select data from toplevelstmts where module = ? order by position asc",
  860. abs module.id):
  861. var b = BlobReader(pos: 0)
  862. # ensure we can read without index checks:
  863. b.s = row[0] & '\0'
  864. result.add decodeNode(g, b, module.info)
  865. db.exec(sql"insert into controlblock(idgen) values (?)", gFrontEndId)
  866. replay(g, module, result)
  867. proc setupModuleCache*(g: ModuleGraph) =
  868. if g.config.symbolFiles == disabledSf: return
  869. g.recordStmt = recordStmt
  870. let dbfile = getNimcacheDir(g.config) / RelativeFile"rodfiles.db"
  871. if g.config.symbolFiles == writeOnlySf:
  872. removeFile(dbfile)
  873. createDir getNimcacheDir(g.config)
  874. let ec = encodeConfig(g)
  875. if not fileExists(dbfile):
  876. db = open(connection=string dbfile, user="nim", password="",
  877. database="nim")
  878. createDb(db)
  879. db.exec(sql"insert into config(config) values (?)", ec)
  880. else:
  881. db = open(connection=string dbfile, user="nim", password="",
  882. database="nim")
  883. let oldConfig = db.getValue(sql"select config from config")
  884. g.incr.configChanged = oldConfig != ec
  885. # ensure the filename IDs stay consistent:
  886. for row in db.rows(sql"select fullpath, nimid from filenames order by nimid"):
  887. let id = fileInfoIdx(g.config, AbsoluteFile row[0])
  888. doAssert id.int == parseInt(row[1])
  889. db.exec(sql"update config set config = ?", ec)
  890. db.exec(sql"pragma journal_mode=off")
  891. # This MUST be turned off, otherwise it's way too slow even for testing purposes:
  892. db.exec(sql"pragma SYNCHRONOUS=off")
  893. db.exec(sql"pragma LOCKING_MODE=exclusive")
  894. let lastId = db.getValue(sql"select max(idgen) from controlblock")
  895. if lastId.len > 0:
  896. idgen.setId(parseInt lastId)