rodimpl.nim 29 KB

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