liftdestructors.nim 41 KB

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