liftdestructors.nim 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements lifting for type-bound operations
  10. ## (``=sink``, ``=``, ``=destroy``, ``=deepCopy``).
  11. import modulegraphs, lineinfos, idents, ast, renderer, semdata,
  12. sighashes, lowerings, options, types, msgs, magicsys, tables
  13. from trees import isCaseObj
  14. type
  15. TLiftCtx = object
  16. g: ModuleGraph
  17. info: TLineInfo # for construction
  18. kind: TTypeAttachedOp
  19. fn: PSym
  20. asgnForType: PType
  21. recurse: bool
  22. addMemReset: bool # add wasMoved() call after destructor call
  23. canRaise: bool
  24. filterDiscriminator: PSym # we generating destructor for case branch
  25. c: PContext # c can be nil, then we are called from lambdalifting!
  26. idgen: IdGenerator
  27. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode)
  28. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  29. info: TLineInfo; idgen: IdGenerator): PSym
  30. proc createTypeBoundOps*(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  31. idgen: IdGenerator)
  32. proc at(a, i: PNode, elemType: PType): PNode =
  33. result = newNodeI(nkBracketExpr, a.info, 2)
  34. result[0] = a
  35. result[1] = i
  36. result.typ = elemType
  37. proc destructorOverriden(t: PType): bool =
  38. t.attachedOps[attachedDestructor] != nil and sfOverriden in t.attachedOps[attachedDestructor].flags
  39. proc fillBodyTup(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  40. for i in 0..<t.len:
  41. let lit = lowerings.newIntLit(c.g, x.info, i)
  42. let b = if c.kind == attachedTrace: y else: y.at(lit, t[i])
  43. fillBody(c, t[i], body, x.at(lit, t[i]), b)
  44. proc dotField(x: PNode, f: PSym): PNode =
  45. result = newNodeI(nkDotExpr, x.info, 2)
  46. if x.typ.skipTypes(abstractInst).kind == tyVar:
  47. result[0] = x.newDeref
  48. else:
  49. result[0] = x
  50. result[1] = newSymNode(f, x.info)
  51. result.typ = f.typ
  52. proc newAsgnStmt(le, ri: PNode): PNode =
  53. result = newNodeI(nkAsgn, le.info, 2)
  54. result[0] = le
  55. result[1] = ri
  56. proc genBuiltin*(g: ModuleGraph; magic: TMagic; name: string; i: PNode): PNode =
  57. result = newNodeI(nkCall, i.info)
  58. result.add createMagic(g, name, magic).newSymNode
  59. result.add i
  60. proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  61. if c.kind in {attachedAsgn, attachedDeepCopy, attachedSink}:
  62. body.add newAsgnStmt(x, y)
  63. elif c.kind == attachedDestructor and c.addMemReset:
  64. let call = genBuiltin(c.g, mDefault, "default", x)
  65. call.typ = t
  66. body.add newAsgnStmt(x, call)
  67. proc genAddr(c: var TLiftCtx; x: PNode): PNode =
  68. if x.kind == nkHiddenDeref:
  69. checkSonsLen(x, 1, c.g.config)
  70. result = x[0]
  71. else:
  72. result = newNodeIT(nkHiddenAddr, x.info, makeVarType(x.typ.owner, x.typ, c.idgen))
  73. result.add x
  74. proc genWhileLoop(c: var TLiftCtx; i, dest: PNode): PNode =
  75. result = newNodeI(nkWhileStmt, c.info, 2)
  76. let cmp = genBuiltin(c.g, mLtI, "<", i)
  77. cmp.add genLen(c.g, dest)
  78. cmp.typ = getSysType(c.g, c.info, tyBool)
  79. result[0] = cmp
  80. result[1] = newNodeI(nkStmtList, c.info)
  81. proc genIf(c: var TLiftCtx; cond, action: PNode): PNode =
  82. result = newTree(nkIfStmt, newTree(nkElifBranch, cond, action))
  83. proc genContainerOf(c: var TLiftCtx; objType: PType, field, x: PSym): PNode =
  84. # generate: cast[ptr ObjType](cast[int](addr(x)) - offsetOf(objType.field))
  85. let intType = getSysType(c.g, unknownLineInfo, tyInt)
  86. let addrOf = newNodeIT(nkAddr, c.info, makePtrType(x.owner, x.typ, c.idgen))
  87. addrOf.add newDeref(newSymNode(x))
  88. let castExpr1 = newNodeIT(nkCast, c.info, intType)
  89. castExpr1.add newNodeIT(nkType, c.info, intType)
  90. castExpr1.add addrOf
  91. let dotExpr = newNodeIT(nkDotExpr, c.info, x.typ)
  92. dotExpr.add newNodeIT(nkType, c.info, objType)
  93. dotExpr.add newSymNode(field)
  94. let offsetOf = genBuiltin(c.g, mOffsetOf, "offsetof", dotExpr)
  95. offsetOf.typ = intType
  96. let minusExpr = genBuiltin(c.g, mSubI, "-", castExpr1)
  97. minusExpr.typ = intType
  98. minusExpr.add offsetOf
  99. let objPtr = makePtrType(objType.owner, objType, c.idgen)
  100. result = newNodeIT(nkCast, c.info, objPtr)
  101. result.add newNodeIT(nkType, c.info, objPtr)
  102. result.add minusExpr
  103. proc destructorCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  104. var destroy = newNodeIT(nkCall, x.info, op.typ[0])
  105. destroy.add(newSymNode(op))
  106. destroy.add genAddr(c, x)
  107. if sfNeverRaises notin op.flags:
  108. c.canRaise = true
  109. if c.addMemReset:
  110. result = newTree(nkStmtList, destroy, genBuiltin(c.g, mWasMoved, "wasMoved", x))
  111. else:
  112. result = destroy
  113. proc fillBodyObj(c: var TLiftCtx; n, body, x, y: PNode; enforceDefaultOp: bool) =
  114. case n.kind
  115. of nkSym:
  116. if c.filterDiscriminator != nil: return
  117. let f = n.sym
  118. let b = if c.kind == attachedTrace: y else: y.dotField(f)
  119. if (sfCursor in f.flags and f.typ.skipTypes(abstractInst).kind in {tyRef, tyProc} and
  120. c.g.config.selectedGC in {gcArc, gcOrc, gcHooks}) or
  121. enforceDefaultOp:
  122. defaultOp(c, f.typ, body, x.dotField(f), b)
  123. else:
  124. fillBody(c, f.typ, body, x.dotField(f), b)
  125. of nkNilLit: discard
  126. of nkRecCase:
  127. # XXX This is only correct for 'attachedSink'!
  128. var localEnforceDefaultOp = enforceDefaultOp
  129. if c.kind == attachedSink:
  130. # the value needs to be destroyed before we assign the selector
  131. # or the value is lost
  132. let prevKind = c.kind
  133. c.kind = attachedDestructor
  134. fillBodyObj(c, n, body, x, y, enforceDefaultOp = false)
  135. c.kind = prevKind
  136. localEnforceDefaultOp = true
  137. if c.kind != attachedDestructor:
  138. # copy the selector before case stmt, but destroy after case stmt
  139. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  140. let oldfilterDiscriminator = c.filterDiscriminator
  141. if c.filterDiscriminator == n[0].sym:
  142. c.filterDiscriminator = nil # we have found the case part, proceed as normal
  143. # we need to generate a case statement:
  144. var caseStmt = newNodeI(nkCaseStmt, c.info)
  145. # XXX generate 'if' that checks same branches
  146. # generate selector:
  147. var access = dotField(x, n[0].sym)
  148. caseStmt.add(access)
  149. var emptyBranches = 0
  150. # copy the branches over, but replace the fields with the for loop body:
  151. for i in 1..<n.len:
  152. var branch = copyTree(n[i])
  153. branch[^1] = newNodeI(nkStmtList, c.info)
  154. fillBodyObj(c, n[i].lastSon, branch[^1], x, y,
  155. enforceDefaultOp = localEnforceDefaultOp)
  156. if branch[^1].len == 0: inc emptyBranches
  157. caseStmt.add(branch)
  158. if emptyBranches != n.len-1:
  159. body.add(caseStmt)
  160. if c.kind == attachedDestructor:
  161. # destructor for selector is done after case stmt
  162. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  163. c.filterDiscriminator = oldfilterDiscriminator
  164. of nkRecList:
  165. for t in items(n): fillBodyObj(c, t, body, x, y, enforceDefaultOp)
  166. else:
  167. illFormedAstLocal(n, c.g.config)
  168. proc fillBodyObjTImpl(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  169. if t.len > 0 and t[0] != nil:
  170. fillBody(c, skipTypes(t[0], abstractPtrs), body, x, y)
  171. fillBodyObj(c, t.n, body, x, y, enforceDefaultOp = false)
  172. proc fillBodyObjT(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  173. var hasCase = isCaseObj(t.n)
  174. var obj = t
  175. while obj.len > 0 and obj[0] != nil:
  176. obj = skipTypes(obj[0], abstractPtrs)
  177. hasCase = hasCase or isCaseObj(obj.n)
  178. if hasCase and c.kind in {attachedAsgn, attachedDeepCopy}:
  179. # assignment for case objects is complex, we do:
  180. # =destroy(dest)
  181. # wasMoved(dest)
  182. # for every field:
  183. # `=` dest.field, src.field
  184. # ^ this is what we used to do, but for 'result = result.sons[0]' it
  185. # destroys 'result' too early.
  186. # So this is what we really need to do:
  187. # let blob {.cursor.} = dest # remembers the old dest.kind
  188. # wasMoved(dest)
  189. # dest.kind = src.kind
  190. # for every field (dependent on dest.kind):
  191. # `=` dest.field, src.field
  192. # =destroy(blob)
  193. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), nextId c.idgen, c.fn, c.info)
  194. temp.typ = x.typ
  195. incl(temp.flags, sfFromGeneric)
  196. var v = newNodeI(nkVarSection, c.info)
  197. let blob = newSymNode(temp)
  198. v.addVar(blob, x)
  199. body.add v
  200. #body.add newAsgnStmt(blob, x)
  201. var wasMovedCall = newNodeI(nkCall, c.info)
  202. wasMovedCall.add(newSymNode(createMagic(c.g, "wasMoved", mWasMoved)))
  203. wasMovedCall.add x # mWasMoved does not take the address
  204. body.add wasMovedCall
  205. fillBodyObjTImpl(c, t, body, x, y)
  206. when false:
  207. # does not work yet due to phase-ordering problems:
  208. assert t.destructor != nil
  209. body.add destructorCall(c.g, t.destructor, blob)
  210. let prevKind = c.kind
  211. c.kind = attachedDestructor
  212. fillBodyObjTImpl(c, t, body, blob, y)
  213. c.kind = prevKind
  214. else:
  215. fillBodyObjTImpl(c, t, body, x, y)
  216. proc boolLit*(g: ModuleGraph; info: TLineInfo; value: bool): PNode =
  217. result = newIntLit(g, info, ord value)
  218. result.typ = getSysType(g, info, tyBool)
  219. proc getCycleParam(c: TLiftCtx): PNode =
  220. assert c.kind == attachedAsgn
  221. if c.fn.typ.len == 4:
  222. result = c.fn.typ.n.lastSon
  223. assert result.kind == nkSym
  224. assert result.sym.name.s == "cyclic"
  225. else:
  226. result = boolLit(c.g, c.info, true)
  227. proc newHookCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  228. #if sfError in op.flags:
  229. # localError(c.config, x.info, "usage of '$1' is a user-defined error" % op.name.s)
  230. result = newNodeI(nkCall, x.info)
  231. result.add newSymNode(op)
  232. if sfNeverRaises notin op.flags:
  233. c.canRaise = true
  234. if op.typ.sons[1].kind == tyVar:
  235. result.add genAddr(c, x)
  236. else:
  237. result.add x
  238. if y != nil:
  239. result.add y
  240. if op.typ.len == 4:
  241. assert y != nil
  242. if c.fn.typ.len == 4:
  243. result.add getCycleParam(c)
  244. else:
  245. # assume the worst: A cycle is created:
  246. result.add boolLit(c.g, y.info, true)
  247. proc newOpCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  248. result = newNodeIT(nkCall, x.info, op.typ[0])
  249. result.add(newSymNode(op))
  250. result.add x
  251. if sfNeverRaises notin op.flags:
  252. c.canRaise = true
  253. proc newDeepCopyCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  254. result = newAsgnStmt(x, newOpCall(c, op, y))
  255. proc usesBuiltinArc(t: PType): bool =
  256. proc wrap(t: PType): bool {.nimcall.} = ast.isGCedMem(t)
  257. result = types.searchTypeFor(t, wrap)
  258. proc useNoGc(c: TLiftCtx; t: PType): bool {.inline.} =
  259. result = optSeqDestructors in c.g.config.globalOptions and
  260. ({tfHasGCedMem, tfHasOwned} * t.flags != {} or usesBuiltinArc(t))
  261. proc requiresDestructor(c: TLiftCtx; t: PType): bool {.inline.} =
  262. result = optSeqDestructors in c.g.config.globalOptions and
  263. containsGarbageCollectedRef(t)
  264. proc instantiateGeneric(c: var TLiftCtx; op: PSym; t, typeInst: PType): PSym =
  265. if c.c != nil and typeInst != nil:
  266. result = c.c.instTypeBoundOp(c.c, op, typeInst, c.info, attachedAsgn, 1)
  267. else:
  268. localError(c.g.config, c.info,
  269. "cannot generate destructor for generic type: " & typeToString(t))
  270. result = nil
  271. proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode;
  272. field: var PSym): bool =
  273. if optSeqDestructors in c.g.config.globalOptions:
  274. var op = field
  275. let destructorOverriden = destructorOverriden(t)
  276. if op != nil and op != c.fn and
  277. (sfOverriden in op.flags or destructorOverriden):
  278. if sfError in op.flags:
  279. incl c.fn.flags, sfError
  280. #else:
  281. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  282. onUse(c.info, op)
  283. body.add newHookCall(c, op, x, y)
  284. result = true
  285. elif op == nil and destructorOverriden:
  286. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  287. body.add newHookCall(c, op, x, y)
  288. result = true
  289. elif tfHasAsgn in t.flags:
  290. var op: PSym
  291. if sameType(t, c.asgnForType):
  292. # generate recursive call:
  293. if c.recurse:
  294. op = c.fn
  295. else:
  296. c.recurse = true
  297. return false
  298. else:
  299. op = field
  300. if op == nil:
  301. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  302. if sfError in op.flags:
  303. incl c.fn.flags, sfError
  304. #else:
  305. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  306. onUse(c.info, op)
  307. # We also now do generic instantiations in the destructor lifting pass:
  308. if op.ast[genericParamsPos].kind != nkEmpty:
  309. op = instantiateGeneric(c, op, t, t.typeInst)
  310. field = op
  311. #echo "trying to use ", op.ast
  312. #echo "for ", op.name.s, " "
  313. #debug(t)
  314. #return false
  315. assert op.ast[genericParamsPos].kind == nkEmpty
  316. body.add newHookCall(c, op, x, y)
  317. result = true
  318. proc addDestructorCall(c: var TLiftCtx; orig: PType; body, x: PNode) =
  319. let t = orig.skipTypes(abstractInst)
  320. var op = t.destructor
  321. if op != nil and sfOverriden in op.flags:
  322. if op.ast[genericParamsPos].kind != nkEmpty:
  323. # patch generic destructor:
  324. op = instantiateGeneric(c, op, t, t.typeInst)
  325. t.attachedOps[attachedDestructor] = op
  326. if op == nil and (useNoGc(c, t) or requiresDestructor(c, t)):
  327. op = produceSym(c.g, c.c, t, attachedDestructor, c.info, c.idgen)
  328. doAssert op != nil
  329. doAssert op == t.destructor
  330. if op != nil:
  331. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  332. onUse(c.info, op)
  333. body.add destructorCall(c, op, x)
  334. elif useNoGc(c, t):
  335. internalError(c.g.config, c.info,
  336. "type-bound operator could not be resolved")
  337. proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  338. case c.kind
  339. of attachedDestructor:
  340. var op = t.destructor
  341. if op != nil and sfOverriden in op.flags:
  342. if op.ast[genericParamsPos].kind != nkEmpty:
  343. # patch generic destructor:
  344. op = instantiateGeneric(c, op, t, t.typeInst)
  345. t.attachedOps[attachedDestructor] = op
  346. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  347. onUse(c.info, op)
  348. body.add destructorCall(c, op, x)
  349. result = true
  350. #result = addDestructorCall(c, t, body, x)
  351. of attachedAsgn, attachedSink, attachedTrace:
  352. result = considerAsgnOrSink(c, t, body, x, y, t.attachedOps[c.kind])
  353. of attachedDispose:
  354. result = considerAsgnOrSink(c, t, body, x, nil, t.attachedOps[c.kind])
  355. of attachedDeepCopy:
  356. let op = t.attachedOps[attachedDeepCopy]
  357. if op != nil:
  358. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  359. onUse(c.info, op)
  360. body.add newDeepCopyCall(c, op, x, y)
  361. result = true
  362. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  363. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), nextId(c.idgen), c.fn, c.info)
  364. temp.typ = getSysType(c.g, body.info, tyInt)
  365. incl(temp.flags, sfFromGeneric)
  366. var v = newNodeI(nkVarSection, c.info)
  367. result = newSymNode(temp)
  368. v.addVar(result, lowerings.newIntLit(c.g, body.info, first))
  369. body.add v
  370. proc declareTempOf(c: var TLiftCtx; body: PNode; value: PNode): PNode =
  371. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), nextId(c.idgen), c.fn, c.info)
  372. temp.typ = value.typ
  373. incl(temp.flags, sfFromGeneric)
  374. var v = newNodeI(nkVarSection, c.info)
  375. result = newSymNode(temp)
  376. v.addVar(result, value)
  377. body.add v
  378. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  379. let incCall = genBuiltin(c.g, mInc, "inc", i)
  380. incCall.add lowerings.newIntLit(c.g, c.info, 1)
  381. body.add incCall
  382. proc newSeqCall(g: ModuleGraph; x, y: PNode): PNode =
  383. # don't call genAddr(c, x) here:
  384. result = genBuiltin(g, mNewSeq, "newSeq", x)
  385. let lenCall = genBuiltin(g, mLengthSeq, "len", y)
  386. lenCall.typ = getSysType(g, x.info, tyInt)
  387. result.add lenCall
  388. proc setLenStrCall(g: ModuleGraph; x, y: PNode): PNode =
  389. let lenCall = genBuiltin(g, mLengthStr, "len", y)
  390. lenCall.typ = getSysType(g, x.info, tyInt)
  391. result = genBuiltin(g, mSetLengthStr, "setLen", x) # genAddr(g, x))
  392. result.add lenCall
  393. proc setLenSeqCall(c: var TLiftCtx; t: PType; x, y: PNode): PNode =
  394. let lenCall = genBuiltin(c.g, mLengthSeq, "len", y)
  395. lenCall.typ = getSysType(c.g, x.info, tyInt)
  396. var op = getSysMagic(c.g, x.info, "setLen", mSetLengthSeq)
  397. op = instantiateGeneric(c, op, t, t)
  398. result = newTree(nkCall, newSymNode(op, x.info), x, lenCall)
  399. proc forallElements(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  400. let i = declareCounter(c, body, toInt64(firstOrd(c.g.config, t)))
  401. let whileLoop = genWhileLoop(c, i, x)
  402. let elemType = t.lastSon
  403. let b = if c.kind == attachedTrace: y else: y.at(i, elemType)
  404. fillBody(c, elemType, whileLoop[1], x.at(i, elemType), b)
  405. addIncStmt(c, whileLoop[1], i)
  406. body.add whileLoop
  407. proc fillSeqOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  408. case c.kind
  409. of attachedAsgn, attachedDeepCopy:
  410. # we generate:
  411. # setLen(dest, y.len)
  412. # var i = 0
  413. # while i < y.len: dest[i] = y[i]; inc(i)
  414. # This is usually more efficient than a destroy/create pair.
  415. body.add setLenSeqCall(c, t, x, y)
  416. forallElements(c, t, body, x, y)
  417. of attachedSink:
  418. let moveCall = genBuiltin(c.g, mMove, "move", x)
  419. moveCall.add y
  420. doAssert t.destructor != nil
  421. moveCall.add destructorCall(c, t.destructor, x)
  422. body.add moveCall
  423. of attachedDestructor:
  424. # destroy all elements:
  425. forallElements(c, t, body, x, y)
  426. body.add genBuiltin(c.g, mDestroy, "destroy", x)
  427. of attachedTrace:
  428. # follow all elements:
  429. forallElements(c, t, body, x, y)
  430. of attachedDispose:
  431. forallElements(c, t, body, x, y)
  432. body.add genBuiltin(c.g, mDestroy, "destroy", x)
  433. proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  434. createTypeBoundOps(c.g, c.c, t, body.info, c.idgen)
  435. # recursions are tricky, so we might need to forward the generated
  436. # operation here:
  437. var t = t
  438. if t.assignment == nil or t.destructor == nil:
  439. let h = sighashes.hashType(t, {CoType, CoConsiderOwned, CoDistinct})
  440. let canon = c.g.canonTypes.getOrDefault(h)
  441. if canon != nil: t = canon
  442. case c.kind
  443. of attachedAsgn, attachedDeepCopy:
  444. # XXX: replace these with assertions.
  445. if t.assignment == nil:
  446. return # protect from recursion
  447. body.add newHookCall(c, t.assignment, x, y)
  448. of attachedSink:
  449. # we always inline the move for better performance:
  450. let moveCall = genBuiltin(c.g, mMove, "move", x)
  451. moveCall.add y
  452. doAssert t.destructor != nil
  453. moveCall.add destructorCall(c, t.destructor, x)
  454. body.add moveCall
  455. # alternatively we could do this:
  456. when false:
  457. doAssert t.asink != nil
  458. body.add newHookCall(c, t.asink, x, y)
  459. of attachedDestructor:
  460. doAssert t.destructor != nil
  461. body.add destructorCall(c, t.destructor, x)
  462. of attachedTrace:
  463. if t.attachedOps[c.kind] == nil:
  464. return # protect from recursion
  465. body.add newHookCall(c, t.attachedOps[c.kind], x, y)
  466. of attachedDispose:
  467. if t.attachedOps[c.kind] == nil:
  468. return # protect from recursion
  469. body.add newHookCall(c, t.attachedOps[c.kind], x, nil)
  470. proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  471. case c.kind
  472. of attachedAsgn, attachedDeepCopy:
  473. body.add callCodegenProc(c.g, "nimAsgnStrV2", c.info, genAddr(c, x), y)
  474. of attachedSink:
  475. let moveCall = genBuiltin(c.g, mMove, "move", x)
  476. moveCall.add y
  477. doAssert t.destructor != nil
  478. moveCall.add destructorCall(c, t.destructor, x)
  479. body.add moveCall
  480. of attachedDestructor, attachedDispose:
  481. body.add genBuiltin(c.g, mDestroy, "destroy", x)
  482. of attachedTrace:
  483. discard "strings are atomic and have no inner elements that are to trace"
  484. proc cyclicType*(t: PType): bool =
  485. case t.kind
  486. of tyRef: result = types.canFormAcycle(t.lastSon)
  487. of tyProc: result = t.callConv == ccClosure
  488. else: result = false
  489. proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  490. #[ bug #15753 is really subtle. Usually the classical write barrier for reference
  491. counting looks like this::
  492. incRef source # increment first; this takes care of self-assignments1
  493. decRef dest
  494. dest[] = source
  495. However, 'decRef dest' might trigger a cycle collection and then the collector
  496. traverses the graph. It is crucial that when it follows the pointers the assignment
  497. 'dest[] = source' already happened so that we don't do trial deletion on a wrong
  498. graph -- this causes premature freeing of objects! The correct barrier looks like
  499. this::
  500. let tmp = dest
  501. incRef source
  502. dest[] = source
  503. decRef tmp
  504. ]#
  505. var actions = newNodeI(nkStmtList, c.info)
  506. let elemType = t.lastSon
  507. createTypeBoundOps(c.g, c.c, elemType, c.info, c.idgen)
  508. let isCyclic = c.g.config.selectedGC == gcOrc and types.canFormAcycle(elemType)
  509. let tmp =
  510. if isCyclic and c.kind in {attachedAsgn, attachedSink}:
  511. declareTempOf(c, body, x)
  512. else:
  513. x
  514. if isFinal(elemType):
  515. addDestructorCall(c, elemType, actions, genDeref(tmp, nkDerefExpr))
  516. var alignOf = genBuiltin(c.g, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  517. alignOf.typ = getSysType(c.g, c.info, tyInt)
  518. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, tmp, alignOf)
  519. else:
  520. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(tmp, nkDerefExpr))
  521. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  522. var cond: PNode
  523. if isCyclic:
  524. if isFinal(elemType):
  525. let typInfo = genBuiltin(c.g, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  526. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  527. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, tmp, typInfo)
  528. else:
  529. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, tmp)
  530. else:
  531. cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
  532. cond.typ = getSysType(c.g, x.info, tyBool)
  533. case c.kind
  534. of attachedSink:
  535. if isCyclic:
  536. body.add newAsgnStmt(x, y)
  537. body.add genIf(c, cond, actions)
  538. else:
  539. body.add genIf(c, cond, actions)
  540. body.add newAsgnStmt(x, y)
  541. of attachedAsgn:
  542. if isCyclic:
  543. body.add genIf(c, y, callCodegenProc(c.g,
  544. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  545. body.add newAsgnStmt(x, y)
  546. body.add genIf(c, cond, actions)
  547. else:
  548. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  549. body.add genIf(c, cond, actions)
  550. body.add newAsgnStmt(x, y)
  551. of attachedDestructor:
  552. body.add genIf(c, cond, actions)
  553. of attachedDeepCopy: assert(false, "cannot happen")
  554. of attachedTrace:
  555. if isFinal(elemType):
  556. let typInfo = genBuiltin(c.g, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  557. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  558. body.add callCodegenProc(c.g, "nimTraceRef", c.info, genAddrOf(x, c.idgen), typInfo, y)
  559. else:
  560. # If the ref is polymorphic we have to account for this
  561. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x, c.idgen), y)
  562. of attachedDispose:
  563. # this is crucial! dispose is like =destroy but we don't follow refs
  564. # as that is dealt within the cycle collector.
  565. when false:
  566. let cond = copyTree(x)
  567. cond.typ = getSysType(c.g, x.info, tyBool)
  568. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x)
  569. body.add genIf(c, cond, actions)
  570. proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  571. ## Closures are really like refs except they always use a virtual destructor
  572. ## and we need to do the refcounting only on the ref field which we call 'xenv':
  573. let xenv = genBuiltin(c.g, mAccessEnv, "accessEnv", x)
  574. xenv.typ = getSysType(c.g, c.info, tyPointer)
  575. let isCyclic = c.g.config.selectedGC == gcOrc
  576. let tmp =
  577. if isCyclic and c.kind in {attachedAsgn, attachedSink}:
  578. declareTempOf(c, body, xenv)
  579. else:
  580. xenv
  581. var actions = newNodeI(nkStmtList, c.info)
  582. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  583. let decRefProc =
  584. if isCyclic: "nimDecRefIsLastCyclicDyn"
  585. else: "nimDecRefIsLast"
  586. let cond = callCodegenProc(c.g, decRefProc, c.info, tmp)
  587. cond.typ = getSysType(c.g, x.info, tyBool)
  588. case c.kind
  589. of attachedSink:
  590. if isCyclic:
  591. body.add newAsgnStmt(x, y)
  592. body.add genIf(c, cond, actions)
  593. else:
  594. body.add genIf(c, cond, actions)
  595. body.add newAsgnStmt(x, y)
  596. of attachedAsgn:
  597. let yenv = genBuiltin(c.g, mAccessEnv, "accessEnv", y)
  598. yenv.typ = getSysType(c.g, c.info, tyPointer)
  599. if isCyclic:
  600. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  601. body.add newAsgnStmt(x, y)
  602. body.add genIf(c, cond, actions)
  603. else:
  604. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  605. body.add genIf(c, cond, actions)
  606. body.add newAsgnStmt(x, y)
  607. of attachedDestructor:
  608. body.add genIf(c, cond, actions)
  609. of attachedDeepCopy: assert(false, "cannot happen")
  610. of attachedTrace:
  611. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv, c.idgen), y)
  612. of attachedDispose:
  613. # this is crucial! dispose is like =destroy but we don't follow refs
  614. # as that is dealt within the cycle collector.
  615. when false:
  616. let cond = copyTree(xenv)
  617. cond.typ = getSysType(c.g, xenv.info, tyBool)
  618. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, xenv)
  619. body.add genIf(c, cond, actions)
  620. proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  621. case c.kind
  622. of attachedSink:
  623. # we 'nil' y out afterwards so we *need* to take over its reference
  624. # count value:
  625. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  626. body.add newAsgnStmt(x, y)
  627. of attachedAsgn:
  628. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  629. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  630. body.add newAsgnStmt(x, y)
  631. of attachedDestructor:
  632. # it's better to prepend the destruction of weak refs in order to
  633. # prevent wrong "dangling refs exist" problems:
  634. var actions = newNodeI(nkStmtList, c.info)
  635. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, x)
  636. let des = genIf(c, x, actions)
  637. if body.len == 0:
  638. body.add des
  639. else:
  640. body.sons.insert(des, 0)
  641. of attachedDeepCopy: assert(false, "cannot happen")
  642. of attachedTrace, attachedDispose: discard
  643. proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  644. var actions = newNodeI(nkStmtList, c.info)
  645. let elemType = t.lastSon
  646. #fillBody(c, elemType, actions, genDeref(x), genDeref(y))
  647. #var disposeCall = genBuiltin(c.g, mDispose, "dispose", x)
  648. if isFinal(elemType):
  649. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  650. var alignOf = genBuiltin(c.g, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  651. alignOf.typ = getSysType(c.g, c.info, tyInt)
  652. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x, alignOf)
  653. else:
  654. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  655. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  656. case c.kind
  657. of attachedSink, attachedAsgn:
  658. body.add genIf(c, x, actions)
  659. body.add newAsgnStmt(x, y)
  660. of attachedDestructor:
  661. body.add genIf(c, x, actions)
  662. of attachedDeepCopy: assert(false, "cannot happen")
  663. of attachedTrace, attachedDispose: discard
  664. proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  665. if c.kind == attachedDeepCopy:
  666. # a big problem is that we don't know the environment's type here, so we
  667. # have to go through some indirection; we delegate this to the codegen:
  668. let call = newNodeI(nkCall, c.info, 2)
  669. call.typ = t
  670. call[0] = newSymNode(createMagic(c.g, "deepCopy", mDeepCopy))
  671. call[1] = y
  672. body.add newAsgnStmt(x, call)
  673. elif (optOwnedRefs in c.g.config.globalOptions and
  674. optRefCheck in c.g.config.options) or c.g.config.selectedGC in {gcArc, gcOrc}:
  675. let xx = genBuiltin(c.g, mAccessEnv, "accessEnv", x)
  676. xx.typ = getSysType(c.g, c.info, tyPointer)
  677. case c.kind
  678. of attachedSink:
  679. # we 'nil' y out afterwards so we *need* to take over its reference
  680. # count value:
  681. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  682. body.add newAsgnStmt(x, y)
  683. of attachedAsgn:
  684. let yy = genBuiltin(c.g, mAccessEnv, "accessEnv", y)
  685. yy.typ = getSysType(c.g, c.info, tyPointer)
  686. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  687. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  688. body.add newAsgnStmt(x, y)
  689. of attachedDestructor:
  690. let des = genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  691. if body.len == 0:
  692. body.add des
  693. else:
  694. body.sons.insert(des, 0)
  695. of attachedDeepCopy: assert(false, "cannot happen")
  696. of attachedTrace, attachedDispose: discard
  697. proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  698. let xx = genBuiltin(c.g, mAccessEnv, "accessEnv", x)
  699. xx.typ = getSysType(c.g, c.info, tyPointer)
  700. var actions = newNodeI(nkStmtList, c.info)
  701. #discard addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(xx))
  702. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xx)
  703. case c.kind
  704. of attachedSink, attachedAsgn:
  705. body.add genIf(c, xx, actions)
  706. body.add newAsgnStmt(x, y)
  707. of attachedDestructor:
  708. body.add genIf(c, xx, actions)
  709. of attachedDeepCopy: assert(false, "cannot happen")
  710. of attachedTrace, attachedDispose: discard
  711. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  712. case t.kind
  713. of tyNone, tyEmpty, tyVoid: discard
  714. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCString,
  715. tyPtr, tyUncheckedArray, tyVar, tyLent:
  716. defaultOp(c, t, body, x, y)
  717. of tyRef:
  718. if c.g.config.selectedGC in {gcArc, gcOrc}:
  719. atomicRefOp(c, t, body, x, y)
  720. elif (optOwnedRefs in c.g.config.globalOptions and
  721. optRefCheck in c.g.config.options):
  722. weakrefOp(c, t, body, x, y)
  723. else:
  724. defaultOp(c, t, body, x, y)
  725. of tyProc:
  726. if t.callConv == ccClosure:
  727. if c.g.config.selectedGC in {gcArc, gcOrc}:
  728. atomicClosureOp(c, t, body, x, y)
  729. else:
  730. closureOp(c, t, body, x, y)
  731. else:
  732. defaultOp(c, t, body, x, y)
  733. of tyOwned:
  734. let base = t.skipTypes(abstractInstOwned)
  735. if optOwnedRefs in c.g.config.globalOptions:
  736. case base.kind
  737. of tyRef:
  738. ownedRefOp(c, base, body, x, y)
  739. return
  740. of tyProc:
  741. if base.callConv == ccClosure:
  742. ownedClosureOp(c, base, body, x, y)
  743. return
  744. else: discard
  745. defaultOp(c, base, body, x, y)
  746. of tyArray:
  747. if tfHasAsgn in t.flags or useNoGc(c, t):
  748. forallElements(c, t, body, x, y)
  749. else:
  750. defaultOp(c, t, body, x, y)
  751. of tySequence:
  752. if useNoGc(c, t):
  753. useSeqOrStrOp(c, t, body, x, y)
  754. elif optSeqDestructors in c.g.config.globalOptions:
  755. # note that tfHasAsgn is propagated so we need the check on
  756. # 'selectedGC' here to determine if we have the new runtime.
  757. discard considerUserDefinedOp(c, t, body, x, y)
  758. elif tfHasAsgn in t.flags:
  759. if c.kind in {attachedAsgn, attachedSink, attachedDeepCopy}:
  760. body.add newSeqCall(c.g, x, y)
  761. forallElements(c, t, body, x, y)
  762. else:
  763. defaultOp(c, t, body, x, y)
  764. of tyString:
  765. if useNoGc(c, t):
  766. useSeqOrStrOp(c, t, body, x, y)
  767. elif tfHasAsgn in t.flags:
  768. discard considerUserDefinedOp(c, t, body, x, y)
  769. else:
  770. defaultOp(c, t, body, x, y)
  771. of tyObject:
  772. if not considerUserDefinedOp(c, t, body, x, y):
  773. if c.kind in {attachedAsgn, attachedSink} and t.sym != nil and sfImportc in t.sym.flags:
  774. body.add newAsgnStmt(x, y)
  775. else:
  776. fillBodyObjT(c, t, body, x, y)
  777. of tyDistinct:
  778. if not considerUserDefinedOp(c, t, body, x, y):
  779. fillBody(c, t[0], body, x, y)
  780. of tyTuple:
  781. fillBodyTup(c, t, body, x, y)
  782. of tyVarargs, tyOpenArray:
  783. if c.kind == attachedDestructor and (tfHasAsgn in t.flags or useNoGc(c, t)):
  784. forallElements(c, t, body, x, y)
  785. else:
  786. discard "cannot copy openArray"
  787. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  788. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  789. tyGenericParam, tyGenericBody, tyNil, tyUntyped, tyTyped,
  790. tyTypeDesc, tyGenericInvocation, tyForward, tyStatic:
  791. #internalError(c.g.config, c.info, "assignment requested for type: " & typeToString(t))
  792. discard
  793. of tyOrdinal, tyRange, tyInferred,
  794. tyGenericInst, tyAlias, tySink:
  795. fillBody(c, lastSon(t), body, x, y)
  796. of tyOptDeprecated: doAssert false
  797. proc produceSymDistinctType(g: ModuleGraph; c: PContext; typ: PType;
  798. kind: TTypeAttachedOp; info: TLineInfo;
  799. idgen: IdGenerator): PSym =
  800. assert typ.kind == tyDistinct
  801. let baseType = typ[0]
  802. if baseType.attachedOps[kind] == nil:
  803. discard produceSym(g, c, baseType, kind, info, idgen)
  804. typ.attachedOps[kind] = baseType.attachedOps[kind]
  805. result = typ.attachedOps[kind]
  806. proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  807. info: TLineInfo; idgen: IdGenerator): PSym =
  808. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  809. result = newSym(skProc, procname, nextId(idgen), owner, info)
  810. let dest = newSym(skParam, getIdent(g.cache, "dest"), nextId(idgen), result, info)
  811. let src = newSym(skParam, getIdent(g.cache, if kind == attachedTrace: "env" else: "src"),
  812. nextId(idgen), result, info)
  813. dest.typ = makeVarType(typ.owner, typ, idgen)
  814. if kind == attachedTrace:
  815. src.typ = getSysType(g, info, tyPointer)
  816. else:
  817. src.typ = typ
  818. result.typ = newProcType(info, nextId(idgen), owner)
  819. result.typ.addParam dest
  820. if kind notin {attachedDestructor, attachedDispose}:
  821. result.typ.addParam src
  822. if kind == attachedAsgn and g.config.selectedGC == gcOrc and
  823. cyclicType(typ.skipTypes(abstractInst)):
  824. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  825. nextId(idgen), result, info)
  826. cycleParam.typ = getSysType(g, info, tyBool)
  827. result.typ.addParam cycleParam
  828. var n = newNodeI(nkProcDef, info, bodyPos+1)
  829. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  830. n[namePos] = newSymNode(result)
  831. n[paramsPos] = result.typ.n
  832. n[bodyPos] = newNodeI(nkStmtList, info)
  833. result.ast = n
  834. incl result.flags, sfFromGeneric
  835. incl result.flags, sfGeneratedOp
  836. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  837. info: TLineInfo; idgen: IdGenerator): PSym =
  838. if typ.kind == tyDistinct:
  839. return produceSymDistinctType(g, c, typ, kind, info, idgen)
  840. result = typ.attachedOps[kind]
  841. if result == nil:
  842. result = symPrototype(g, typ, typ.owner, kind, info, idgen)
  843. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, asgnForType: typ, idgen: idgen,
  844. fn: result)
  845. let dest = result.typ.n[1].sym
  846. let d = newDeref(newSymNode(dest))
  847. let src = if kind in {attachedDestructor, attachedDispose}: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  848. else: newSymNode(result.typ.n[2].sym)
  849. # register this operation already:
  850. typ.attachedOps[kind] = result
  851. if kind == attachedSink and destructorOverriden(typ):
  852. ## compiler can use a combination of `=destroy` and memCopy for sink op
  853. dest.flags.incl sfCursor
  854. result.ast[bodyPos].add newOpCall(a, typ.attachedOps[attachedDestructor], d[0])
  855. result.ast[bodyPos].add newAsgnStmt(d, src)
  856. else:
  857. var tk: TTypeKind
  858. if g.config.selectedGC in {gcArc, gcOrc, gcHooks}:
  859. tk = skipTypes(typ, {tyOrdinal, tyRange, tyInferred, tyGenericInst, tyStatic, tyAlias, tySink}).kind
  860. else:
  861. tk = tyNone # no special casing for strings and seqs
  862. case tk
  863. of tySequence:
  864. fillSeqOp(a, typ, result.ast[bodyPos], d, src)
  865. of tyString:
  866. fillStrOp(a, typ, result.ast[bodyPos], d, src)
  867. else:
  868. fillBody(a, typ, result.ast[bodyPos], d, src)
  869. if not a.canRaise: incl result.flags, sfNeverRaises
  870. proc produceDestructorForDiscriminator*(g: ModuleGraph; typ: PType; field: PSym,
  871. info: TLineInfo; idgen: IdGenerator): PSym =
  872. assert(typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject)
  873. result = symPrototype(g, field.typ, typ.owner, attachedDestructor, info, idgen)
  874. var a = TLiftCtx(info: info, g: g, kind: attachedDestructor, asgnForType: typ, idgen: idgen,
  875. fn: result)
  876. a.asgnForType = typ
  877. a.filterDiscriminator = field
  878. a.addMemReset = true
  879. let discrimantDest = result.typ.n[1].sym
  880. let dst = newSym(skVar, getIdent(g.cache, "dest"), nextId(idgen), result, info)
  881. dst.typ = makePtrType(typ.owner, typ, idgen)
  882. let dstSym = newSymNode(dst)
  883. let d = newDeref(dstSym)
  884. let v = newNodeI(nkVarSection, info)
  885. v.addVar(dstSym, genContainerOf(a, typ, field, discrimantDest))
  886. result.ast[bodyPos].add v
  887. let placeHolder = newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  888. fillBody(a, typ, result.ast[bodyPos], d, placeHolder)
  889. if not a.canRaise: incl result.flags, sfNeverRaises
  890. template liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  891. discard "now a nop"
  892. proc patchBody(g: ModuleGraph; c: PContext; n: PNode; info: TLineInfo; idgen: IdGenerator) =
  893. if n.kind in nkCallKinds:
  894. if n[0].kind == nkSym and n[0].sym.magic == mDestroy:
  895. let t = n[1].typ.skipTypes(abstractVar)
  896. if t.destructor == nil:
  897. discard produceSym(g, c, t, attachedDestructor, info, idgen)
  898. if t.destructor != nil:
  899. if t.destructor.ast[genericParamsPos].kind != nkEmpty:
  900. internalError(g.config, info, "resolved destructor is generic")
  901. if t.destructor.magic == mDestroy:
  902. internalError(g.config, info, "patching mDestroy with mDestroy?")
  903. n[0] = newSymNode(t.destructor)
  904. for x in n: patchBody(g, c, x, info, idgen)
  905. template inst(field, t, idgen) =
  906. if field.ast != nil and field.ast[genericParamsPos].kind != nkEmpty:
  907. if t.typeInst != nil:
  908. var a: TLiftCtx
  909. a.info = info
  910. a.g = g
  911. a.kind = k
  912. a.c = c
  913. a.idgen = idgen
  914. field = instantiateGeneric(a, field, t, t.typeInst)
  915. if field.ast != nil:
  916. patchBody(g, c, field.ast, info, a.idgen)
  917. else:
  918. localError(g.config, info, "unresolved generic parameter")
  919. proc isTrival(s: PSym): bool {.inline.} =
  920. s == nil or (s.ast != nil and s.ast[bodyPos].len == 0)
  921. proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  922. idgen: IdGenerator) =
  923. ## In the semantic pass this is called in strategic places
  924. ## to ensure we lift assignment, destructors and moves properly.
  925. ## The later 'injectdestructors' pass depends on it.
  926. if orig == nil or {tfCheckedForDestructor, tfHasMeta} * orig.flags != {}: return
  927. incl orig.flags, tfCheckedForDestructor
  928. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  929. if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
  930. let h = sighashes.hashType(skipped, {CoType, CoConsiderOwned, CoDistinct})
  931. var canon = g.canonTypes.getOrDefault(h)
  932. if canon == nil:
  933. g.canonTypes[h] = skipped
  934. canon = skipped
  935. # multiple cases are to distinguish here:
  936. # 1. we don't know yet if 'typ' has a nontrival destructor.
  937. # 2. we have a nop destructor. --> mDestroy
  938. # 3. we have a lifted destructor.
  939. # 4. We have a custom destructor.
  940. # 5. We have a (custom) generic destructor.
  941. # we do not generate '=trace' nor '=dispose' procs if we
  942. # have the cycle detection disabled, saves code size.
  943. let lastAttached = if g.config.selectedGC == gcOrc: attachedDispose
  944. else: attachedSink
  945. # bug #15122: We need to produce all prototypes before entering the
  946. # mind boggling recursion. Hacks like these imply we shoule rewrite
  947. # this module.
  948. var generics: array[attachedDestructor..attachedDispose, bool]
  949. for k in attachedDestructor..lastAttached:
  950. generics[k] = canon.attachedOps[k] != nil
  951. if not generics[k]:
  952. canon.attachedOps[k] = symPrototype(g, canon, canon.owner, k, info, idgen)
  953. # we generate the destructor first so that other operators can depend on it:
  954. for k in attachedDestructor..lastAttached:
  955. if not generics[k]:
  956. discard produceSym(g, c, canon, k, info, idgen)
  957. else:
  958. inst(canon.attachedOps[k], canon, idgen)
  959. if canon != orig:
  960. orig.attachedOps[k] = canon.attachedOps[k]
  961. if not isTrival(orig.destructor):
  962. #or not isTrival(orig.assignment) or
  963. # not isTrival(orig.sink):
  964. orig.flags.incl tfHasAsgn