liftdestructors.nim 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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 isInheritableAcyclicRef = c.g.config.selectedGC == gcOrc and
  536. (not isPureObject(elemType)) and
  537. tfAcyclic in skipTypes(elemType, abstractInst+{tyOwned}-{tyTypeDesc}).flags
  538. # dynamic Acyclic refs need to use dyn decRef
  539. let tmp =
  540. if isCyclic and c.kind in {attachedAsgn, attachedSink}:
  541. declareTempOf(c, body, x)
  542. else:
  543. x
  544. if isFinal(elemType):
  545. addDestructorCall(c, elemType, actions, genDeref(tmp, nkDerefExpr))
  546. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  547. alignOf.typ = getSysType(c.g, c.info, tyInt)
  548. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, tmp, alignOf)
  549. else:
  550. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(tmp, nkDerefExpr))
  551. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  552. var cond: PNode
  553. if isCyclic:
  554. if isFinal(elemType):
  555. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  556. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  557. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, tmp, typInfo)
  558. else:
  559. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, tmp)
  560. elif isInheritableAcyclicRef:
  561. cond = callCodegenProc(c.g, "nimDecRefIsLastDyn", c.info, x)
  562. else:
  563. cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
  564. cond.typ = getSysType(c.g, x.info, tyBool)
  565. case c.kind
  566. of attachedSink:
  567. if isCyclic:
  568. body.add newAsgnStmt(x, y)
  569. body.add genIf(c, cond, actions)
  570. else:
  571. body.add genIf(c, cond, actions)
  572. body.add newAsgnStmt(x, y)
  573. of attachedAsgn:
  574. if isCyclic:
  575. body.add genIf(c, y, callCodegenProc(c.g,
  576. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  577. body.add newAsgnStmt(x, y)
  578. body.add genIf(c, cond, actions)
  579. else:
  580. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  581. body.add genIf(c, cond, actions)
  582. body.add newAsgnStmt(x, y)
  583. of attachedDestructor:
  584. body.add genIf(c, cond, actions)
  585. of attachedDeepCopy: assert(false, "cannot happen")
  586. of attachedTrace:
  587. if isCyclic:
  588. if isFinal(elemType):
  589. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  590. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  591. body.add callCodegenProc(c.g, "nimTraceRef", c.info, genAddrOf(x, c.idgen), typInfo, y)
  592. else:
  593. # If the ref is polymorphic we have to account for this
  594. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x, c.idgen), y)
  595. #echo "can follow ", elemType, " static ", isFinal(elemType)
  596. proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  597. ## Closures are really like refs except they always use a virtual destructor
  598. ## and we need to do the refcounting only on the ref field which we call 'xenv':
  599. let xenv = genBuiltin(c, mAccessEnv, "accessEnv", x)
  600. xenv.typ = getSysType(c.g, c.info, tyPointer)
  601. let isCyclic = c.g.config.selectedGC == gcOrc
  602. let tmp =
  603. if isCyclic and c.kind in {attachedAsgn, attachedSink}:
  604. declareTempOf(c, body, xenv)
  605. else:
  606. xenv
  607. var actions = newNodeI(nkStmtList, c.info)
  608. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  609. let decRefProc =
  610. if isCyclic: "nimDecRefIsLastCyclicDyn"
  611. else: "nimDecRefIsLast"
  612. let cond = callCodegenProc(c.g, decRefProc, c.info, tmp)
  613. cond.typ = getSysType(c.g, x.info, tyBool)
  614. case c.kind
  615. of attachedSink:
  616. if isCyclic:
  617. body.add newAsgnStmt(x, y)
  618. body.add genIf(c, cond, actions)
  619. else:
  620. body.add genIf(c, cond, actions)
  621. body.add newAsgnStmt(x, y)
  622. of attachedAsgn:
  623. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  624. yenv.typ = getSysType(c.g, c.info, tyPointer)
  625. if isCyclic:
  626. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  627. body.add newAsgnStmt(x, y)
  628. body.add genIf(c, cond, actions)
  629. else:
  630. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  631. body.add genIf(c, cond, actions)
  632. body.add newAsgnStmt(x, y)
  633. of attachedDestructor:
  634. body.add genIf(c, cond, actions)
  635. of attachedDeepCopy: assert(false, "cannot happen")
  636. of attachedTrace:
  637. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv, c.idgen), y)
  638. proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  639. case c.kind
  640. of attachedSink:
  641. # we 'nil' y out afterwards so we *need* to take over its reference
  642. # count value:
  643. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  644. body.add newAsgnStmt(x, y)
  645. of attachedAsgn:
  646. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  647. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  648. body.add newAsgnStmt(x, y)
  649. of attachedDestructor:
  650. # it's better to prepend the destruction of weak refs in order to
  651. # prevent wrong "dangling refs exist" problems:
  652. var actions = newNodeI(nkStmtList, c.info)
  653. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, x)
  654. let des = genIf(c, x, actions)
  655. if body.len == 0:
  656. body.add des
  657. else:
  658. body.sons.insert(des, 0)
  659. of attachedDeepCopy: assert(false, "cannot happen")
  660. of attachedTrace: discard
  661. proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  662. var actions = newNodeI(nkStmtList, c.info)
  663. let elemType = t.lastSon
  664. #fillBody(c, elemType, actions, genDeref(x), genDeref(y))
  665. #var disposeCall = genBuiltin(c, mDispose, "dispose", x)
  666. if isFinal(elemType):
  667. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  668. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  669. alignOf.typ = getSysType(c.g, c.info, tyInt)
  670. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x, alignOf)
  671. else:
  672. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  673. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  674. case c.kind
  675. of attachedSink, attachedAsgn:
  676. body.add genIf(c, x, actions)
  677. body.add newAsgnStmt(x, y)
  678. of attachedDestructor:
  679. body.add genIf(c, x, actions)
  680. of attachedDeepCopy: assert(false, "cannot happen")
  681. of attachedTrace: discard
  682. proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  683. if c.kind == attachedDeepCopy:
  684. # a big problem is that we don't know the environment's type here, so we
  685. # have to go through some indirection; we delegate this to the codegen:
  686. let call = newNodeI(nkCall, c.info, 2)
  687. call.typ = t
  688. call[0] = newSymNode(createMagic(c.g, c.idgen, "deepCopy", mDeepCopy))
  689. call[1] = y
  690. body.add newAsgnStmt(x, call)
  691. elif (optOwnedRefs in c.g.config.globalOptions and
  692. optRefCheck in c.g.config.options) or c.g.config.selectedGC in {gcArc, gcOrc}:
  693. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  694. xx.typ = getSysType(c.g, c.info, tyPointer)
  695. case c.kind
  696. of attachedSink:
  697. # we 'nil' y out afterwards so we *need* to take over its reference
  698. # count value:
  699. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  700. body.add newAsgnStmt(x, y)
  701. of attachedAsgn:
  702. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  703. yy.typ = getSysType(c.g, c.info, tyPointer)
  704. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  705. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  706. body.add newAsgnStmt(x, y)
  707. of attachedDestructor:
  708. let des = genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  709. if body.len == 0:
  710. body.add des
  711. else:
  712. body.sons.insert(des, 0)
  713. of attachedDeepCopy: assert(false, "cannot happen")
  714. of attachedTrace: discard
  715. proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  716. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  717. xx.typ = getSysType(c.g, c.info, tyPointer)
  718. var actions = newNodeI(nkStmtList, c.info)
  719. #discard addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(xx))
  720. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xx)
  721. case c.kind
  722. of attachedSink, attachedAsgn:
  723. body.add genIf(c, xx, actions)
  724. body.add newAsgnStmt(x, y)
  725. of attachedDestructor:
  726. body.add genIf(c, xx, actions)
  727. of attachedDeepCopy: assert(false, "cannot happen")
  728. of attachedTrace: discard
  729. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  730. case t.kind
  731. of tyNone, tyEmpty, tyVoid: discard
  732. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCstring,
  733. tyPtr, tyUncheckedArray, tyVar, tyLent:
  734. defaultOp(c, t, body, x, y)
  735. of tyRef:
  736. if c.g.config.selectedGC in {gcArc, gcOrc}:
  737. atomicRefOp(c, t, body, x, y)
  738. elif (optOwnedRefs in c.g.config.globalOptions and
  739. optRefCheck in c.g.config.options):
  740. weakrefOp(c, t, body, x, y)
  741. else:
  742. defaultOp(c, t, body, x, y)
  743. of tyProc:
  744. if t.callConv == ccClosure:
  745. if c.g.config.selectedGC in {gcArc, gcOrc}:
  746. atomicClosureOp(c, t, body, x, y)
  747. else:
  748. closureOp(c, t, body, x, y)
  749. else:
  750. defaultOp(c, t, body, x, y)
  751. of tyOwned:
  752. let base = t.skipTypes(abstractInstOwned)
  753. if optOwnedRefs in c.g.config.globalOptions:
  754. case base.kind
  755. of tyRef:
  756. ownedRefOp(c, base, body, x, y)
  757. return
  758. of tyProc:
  759. if base.callConv == ccClosure:
  760. ownedClosureOp(c, base, body, x, y)
  761. return
  762. else: discard
  763. defaultOp(c, base, body, x, y)
  764. of tyArray:
  765. if tfHasAsgn in t.flags or useNoGc(c, t):
  766. forallElements(c, t, body, x, y)
  767. else:
  768. defaultOp(c, t, body, x, y)
  769. of tySequence:
  770. if useNoGc(c, t):
  771. useSeqOrStrOp(c, t, body, x, y)
  772. elif optSeqDestructors in c.g.config.globalOptions:
  773. # note that tfHasAsgn is propagated so we need the check on
  774. # 'selectedGC' here to determine if we have the new runtime.
  775. discard considerUserDefinedOp(c, t, body, x, y)
  776. elif tfHasAsgn in t.flags:
  777. if c.kind in {attachedAsgn, attachedSink, attachedDeepCopy}:
  778. body.add newSeqCall(c, x, y)
  779. forallElements(c, t, body, x, y)
  780. else:
  781. defaultOp(c, t, body, x, y)
  782. of tyString:
  783. if useNoGc(c, t):
  784. useSeqOrStrOp(c, t, body, x, y)
  785. elif tfHasAsgn in t.flags:
  786. discard considerUserDefinedOp(c, t, body, x, y)
  787. else:
  788. defaultOp(c, t, body, x, y)
  789. of tyObject:
  790. if not considerUserDefinedOp(c, t, body, x, y):
  791. if c.kind in {attachedAsgn, attachedSink} and t.sym != nil and sfImportc in t.sym.flags:
  792. body.add newAsgnStmt(x, y)
  793. else:
  794. fillBodyObjT(c, t, body, x, y)
  795. of tyDistinct:
  796. if not considerUserDefinedOp(c, t, body, x, y):
  797. fillBody(c, t[0], body, x, y)
  798. of tyTuple:
  799. fillBodyTup(c, t, body, x, y)
  800. of tyVarargs, tyOpenArray:
  801. if c.kind == attachedDestructor and (tfHasAsgn in t.flags or useNoGc(c, t)):
  802. forallElements(c, t, body, x, y)
  803. else:
  804. discard "cannot copy openArray"
  805. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  806. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  807. tyGenericParam, tyGenericBody, tyNil, tyUntyped, tyTyped,
  808. tyTypeDesc, tyGenericInvocation, tyForward, tyStatic:
  809. #internalError(c.g.config, c.info, "assignment requested for type: " & typeToString(t))
  810. discard
  811. of tyOrdinal, tyRange, tyInferred,
  812. tyGenericInst, tyAlias, tySink:
  813. fillBody(c, lastSon(t), body, x, y)
  814. of tyConcept, tyIterable: doAssert false
  815. proc produceSymDistinctType(g: ModuleGraph; c: PContext; typ: PType;
  816. kind: TTypeAttachedOp; info: TLineInfo;
  817. idgen: IdGenerator): PSym =
  818. assert typ.kind == tyDistinct
  819. let baseType = typ[0]
  820. if getAttachedOp(g, baseType, kind) == nil:
  821. discard produceSym(g, c, baseType, kind, info, idgen)
  822. result = getAttachedOp(g, baseType, kind)
  823. setAttachedOp(g, idgen.module, typ, kind, result)
  824. proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  825. info: TLineInfo; idgen: IdGenerator): PSym =
  826. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  827. result = newSym(skProc, procname, nextSymId(idgen), owner, info)
  828. let dest = newSym(skParam, getIdent(g.cache, "dest"), nextSymId(idgen), result, info)
  829. let src = newSym(skParam, getIdent(g.cache, if kind == attachedTrace: "env" else: "src"),
  830. nextSymId(idgen), result, info)
  831. dest.typ = makeVarType(typ.owner, typ, idgen)
  832. if kind == attachedTrace:
  833. src.typ = getSysType(g, info, tyPointer)
  834. else:
  835. src.typ = typ
  836. result.typ = newProcType(info, nextTypeId(idgen), owner)
  837. result.typ.addParam dest
  838. if kind != attachedDestructor:
  839. result.typ.addParam src
  840. if kind == attachedAsgn and g.config.selectedGC == gcOrc and
  841. cyclicType(typ.skipTypes(abstractInst)):
  842. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  843. nextSymId(idgen), result, info)
  844. cycleParam.typ = getSysType(g, info, tyBool)
  845. result.typ.addParam cycleParam
  846. var n = newNodeI(nkProcDef, info, bodyPos+1)
  847. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  848. n[namePos] = newSymNode(result)
  849. n[paramsPos] = result.typ.n
  850. n[bodyPos] = newNodeI(nkStmtList, info)
  851. result.ast = n
  852. incl result.flags, sfFromGeneric
  853. incl result.flags, sfGeneratedOp
  854. proc genTypeFieldCopy(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  855. let xx = genBuiltin(c, mAccessTypeField, "accessTypeField", x)
  856. let yy = genBuiltin(c, mAccessTypeField, "accessTypeField", y)
  857. xx.typ = getSysType(c.g, c.info, tyPointer)
  858. yy.typ = xx.typ
  859. body.add newAsgnStmt(xx, yy)
  860. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  861. info: TLineInfo; idgen: IdGenerator): PSym =
  862. if typ.kind == tyDistinct:
  863. return produceSymDistinctType(g, c, typ, kind, info, idgen)
  864. result = getAttachedOp(g, typ, kind)
  865. if result == nil:
  866. result = symPrototype(g, typ, typ.owner, kind, info, idgen)
  867. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, asgnForType: typ, idgen: idgen,
  868. fn: result)
  869. let dest = result.typ.n[1].sym
  870. let d = newDeref(newSymNode(dest))
  871. let src = if kind == attachedDestructor: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  872. else: newSymNode(result.typ.n[2].sym)
  873. # register this operation already:
  874. setAttachedOpPartial(g, idgen.module, typ, kind, result)
  875. if kind == attachedSink and destructorOverriden(g, typ):
  876. ## compiler can use a combination of `=destroy` and memCopy for sink op
  877. dest.flags.incl sfCursor
  878. result.ast[bodyPos].add newOpCall(a, getAttachedOp(g, typ, attachedDestructor), d[0])
  879. result.ast[bodyPos].add newAsgnStmt(d, src)
  880. else:
  881. var tk: TTypeKind
  882. if g.config.selectedGC in {gcArc, gcOrc, gcHooks}:
  883. tk = skipTypes(typ, {tyOrdinal, tyRange, tyInferred, tyGenericInst, tyStatic, tyAlias, tySink}).kind
  884. else:
  885. tk = tyNone # no special casing for strings and seqs
  886. case tk
  887. of tySequence:
  888. fillSeqOp(a, typ, result.ast[bodyPos], d, src)
  889. of tyString:
  890. fillStrOp(a, typ, result.ast[bodyPos], d, src)
  891. else:
  892. fillBody(a, typ, result.ast[bodyPos], d, src)
  893. if tk == tyObject and a.kind in {attachedAsgn, attachedSink, attachedDeepCopy} and not lacksMTypeField(typ):
  894. # bug #19205: Do not forget to also copy the hidden type field:
  895. genTypeFieldCopy(a, typ, result.ast[bodyPos], d, src)
  896. if not a.canRaise: incl result.flags, sfNeverRaises
  897. completePartialOp(g, idgen.module, typ, kind, result)
  898. proc produceDestructorForDiscriminator*(g: ModuleGraph; typ: PType; field: PSym,
  899. info: TLineInfo; idgen: IdGenerator): PSym =
  900. assert(typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject)
  901. result = symPrototype(g, field.typ, typ.owner, attachedDestructor, info, idgen)
  902. var a = TLiftCtx(info: info, g: g, kind: attachedDestructor, asgnForType: typ, idgen: idgen,
  903. fn: result)
  904. a.asgnForType = typ
  905. a.filterDiscriminator = field
  906. a.addMemReset = true
  907. let discrimantDest = result.typ.n[1].sym
  908. let dst = newSym(skVar, getIdent(g.cache, "dest"), nextSymId(idgen), result, info)
  909. dst.typ = makePtrType(typ.owner, typ, idgen)
  910. let dstSym = newSymNode(dst)
  911. let d = newDeref(dstSym)
  912. let v = newNodeI(nkVarSection, info)
  913. v.addVar(dstSym, genContainerOf(a, typ, field, discrimantDest))
  914. result.ast[bodyPos].add v
  915. let placeHolder = newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  916. fillBody(a, typ, result.ast[bodyPos], d, placeHolder)
  917. if not a.canRaise: incl result.flags, sfNeverRaises
  918. template liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  919. discard "now a nop"
  920. proc patchBody(g: ModuleGraph; c: PContext; n: PNode; info: TLineInfo; idgen: IdGenerator) =
  921. if n.kind in nkCallKinds:
  922. if n[0].kind == nkSym and n[0].sym.magic == mDestroy:
  923. let t = n[1].typ.skipTypes(abstractVar)
  924. if getAttachedOp(g, t, attachedDestructor) == nil:
  925. discard produceSym(g, c, t, attachedDestructor, info, idgen)
  926. let op = getAttachedOp(g, t, attachedDestructor)
  927. if op != nil:
  928. if op.ast.isGenericRoutine:
  929. internalError(g.config, info, "resolved destructor is generic")
  930. if op.magic == mDestroy:
  931. internalError(g.config, info, "patching mDestroy with mDestroy?")
  932. n[0] = newSymNode(op)
  933. for x in n: patchBody(g, c, x, info, idgen)
  934. proc inst(g: ModuleGraph; c: PContext; t: PType; kind: TTypeAttachedOp; idgen: IdGenerator;
  935. info: TLineInfo) =
  936. let op = getAttachedOp(g, t, kind)
  937. if op != nil and op.ast != nil and op.ast.isGenericRoutine:
  938. if t.typeInst != nil:
  939. var a: TLiftCtx
  940. a.info = info
  941. a.g = g
  942. a.kind = kind
  943. a.c = c
  944. a.idgen = idgen
  945. let opInst = instantiateGeneric(a, op, t, t.typeInst)
  946. if opInst.ast != nil:
  947. patchBody(g, c, opInst.ast, info, a.idgen)
  948. setAttachedOp(g, idgen.module, t, kind, opInst)
  949. else:
  950. localError(g.config, info, "unresolved generic parameter")
  951. proc isTrival(s: PSym): bool {.inline.} =
  952. s == nil or (s.ast != nil and s.ast[bodyPos].len == 0)
  953. proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  954. idgen: IdGenerator) =
  955. ## In the semantic pass this is called in strategic places
  956. ## to ensure we lift assignment, destructors and moves properly.
  957. ## The later 'injectdestructors' pass depends on it.
  958. if orig == nil or {tfCheckedForDestructor, tfHasMeta} * orig.flags != {}: return
  959. incl orig.flags, tfCheckedForDestructor
  960. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  961. if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
  962. let h = sighashes.hashType(skipped, {CoType, CoConsiderOwned, CoDistinct})
  963. var canon = g.canonTypes.getOrDefault(h)
  964. if canon == nil:
  965. g.canonTypes[h] = skipped
  966. canon = skipped
  967. # multiple cases are to distinguish here:
  968. # 1. we don't know yet if 'typ' has a nontrival destructor.
  969. # 2. we have a nop destructor. --> mDestroy
  970. # 3. we have a lifted destructor.
  971. # 4. We have a custom destructor.
  972. # 5. We have a (custom) generic destructor.
  973. # we do not generate '=trace' procs if we
  974. # have the cycle detection disabled, saves code size.
  975. let lastAttached = if g.config.selectedGC == gcOrc: attachedTrace
  976. else: attachedSink
  977. # bug #15122: We need to produce all prototypes before entering the
  978. # mind boggling recursion. Hacks like these imply we should rewrite
  979. # this module.
  980. var generics: array[attachedDestructor..attachedTrace, bool]
  981. for k in attachedDestructor..lastAttached:
  982. generics[k] = getAttachedOp(g, canon, k) != nil
  983. if not generics[k]:
  984. setAttachedOp(g, idgen.module, canon, k,
  985. symPrototype(g, canon, canon.owner, k, info, idgen))
  986. # we generate the destructor first so that other operators can depend on it:
  987. for k in attachedDestructor..lastAttached:
  988. if not generics[k]:
  989. discard produceSym(g, c, canon, k, info, idgen)
  990. else:
  991. inst(g, c, canon, k, idgen, info)
  992. if canon != orig:
  993. setAttachedOp(g, idgen.module, orig, k, getAttachedOp(g, canon, k))
  994. if not isTrival(getAttachedOp(g, orig, attachedDestructor)):
  995. #or not isTrival(orig.assignment) or
  996. # not isTrival(orig.sink):
  997. orig.flags.incl tfHasAsgn
  998. # ^ XXX Breaks IC!