semasgn.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. # included from sem.nim
  12. type
  13. TLiftCtx = object
  14. c: PContext
  15. info: TLineInfo # for construction
  16. kind: TTypeAttachedOp
  17. fn: PSym
  18. asgnForType: PType
  19. recurse: bool
  20. proc liftBodyAux(c: var TLiftCtx; t: PType; body, x, y: PNode)
  21. proc liftBody(c: PContext; typ: PType; kind: TTypeAttachedOp;
  22. info: TLineInfo): PSym {.discardable.}
  23. proc at(a, i: PNode, elemType: PType): PNode =
  24. result = newNodeI(nkBracketExpr, a.info, 2)
  25. result.sons[0] = a
  26. result.sons[1] = i
  27. result.typ = elemType
  28. proc liftBodyTup(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  29. for i in 0 ..< t.len:
  30. let lit = lowerings.newIntLit(c.c.graph, x.info, i)
  31. liftBodyAux(c, t.sons[i], body, x.at(lit, t.sons[i]), y.at(lit, t.sons[i]))
  32. proc dotField(x: PNode, f: PSym): PNode =
  33. result = newNodeI(nkDotExpr, x.info, 2)
  34. result.sons[0] = x
  35. result.sons[1] = newSymNode(f, x.info)
  36. result.typ = f.typ
  37. proc liftBodyObj(c: var TLiftCtx; n, body, x, y: PNode) =
  38. case n.kind
  39. of nkSym:
  40. let f = n.sym
  41. liftBodyAux(c, f.typ, body, x.dotField(f), y.dotField(f))
  42. of nkNilLit: discard
  43. of nkRecCase:
  44. # copy the selector:
  45. liftBodyObj(c, n[0], body, x, y)
  46. # we need to generate a case statement:
  47. var caseStmt = newNodeI(nkCaseStmt, c.info)
  48. # XXX generate 'if' that checks same branches
  49. # generate selector:
  50. var access = dotField(x, n[0].sym)
  51. caseStmt.add(access)
  52. # copy the branches over, but replace the fields with the for loop body:
  53. for i in 1 ..< n.len:
  54. var branch = copyTree(n[i])
  55. let L = branch.len
  56. branch.sons[L-1] = newNodeI(nkStmtList, c.info)
  57. liftBodyObj(c, n[i].lastSon, branch.sons[L-1], x, y)
  58. caseStmt.add(branch)
  59. body.add(caseStmt)
  60. localError(c.c.config, c.info, "cannot lift assignment operator to 'case' object")
  61. of nkRecList:
  62. for t in items(n): liftBodyObj(c, t, body, x, y)
  63. else:
  64. illFormedAstLocal(n, c.c.config)
  65. proc genAddr(c: PContext; x: PNode): PNode =
  66. if x.kind == nkHiddenDeref:
  67. checkSonsLen(x, 1, c.config)
  68. result = x.sons[0]
  69. else:
  70. result = newNodeIT(nkHiddenAddr, x.info, makeVarType(c, x.typ))
  71. addSon(result, x)
  72. proc newAsgnCall(c: PContext; op: PSym; x, y: PNode): PNode =
  73. #if sfError in op.flags:
  74. # localError(c.config, x.info, "usage of '$1' is a user-defined error" % op.name.s)
  75. result = newNodeI(nkCall, x.info)
  76. result.add newSymNode(op)
  77. result.add genAddr(c, x)
  78. result.add y
  79. proc newAsgnStmt(le, ri: PNode): PNode =
  80. result = newNodeI(nkAsgn, le.info, 2)
  81. result.sons[0] = le
  82. result.sons[1] = ri
  83. proc newOpCall(op: PSym; x: PNode): PNode =
  84. result = newNodeIT(nkCall, x.info, op.typ.sons[0])
  85. result.add(newSymNode(op))
  86. result.add x
  87. proc destructorCall(c: PContext; op: PSym; x: PNode): PNode =
  88. result = newNodeIT(nkCall, x.info, op.typ.sons[0])
  89. result.add(newSymNode(op))
  90. result.add genAddr(c, x)
  91. proc newDeepCopyCall(op: PSym; x, y: PNode): PNode =
  92. result = newAsgnStmt(x, newOpCall(op, y))
  93. proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode;
  94. field: PSym): bool =
  95. if tfHasAsgn in t.flags:
  96. var op: PSym
  97. if sameType(t, c.asgnForType):
  98. # generate recursive call:
  99. if c.recurse:
  100. op = c.fn
  101. else:
  102. c.recurse = true
  103. return false
  104. else:
  105. op = field
  106. if op == nil:
  107. op = liftBody(c.c, t, c.kind, c.info)
  108. if sfError in op.flags:
  109. incl c.fn.flags, sfError
  110. else:
  111. markUsed(c.c.config, c.info, op, c.c.graph.usageSym)
  112. onUse(c.info, op)
  113. body.add newAsgnCall(c.c, op, x, y)
  114. result = true
  115. proc considerOverloadedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  116. case c.kind
  117. of attachedDestructor:
  118. let op = t.destructor
  119. if op != nil:
  120. markUsed(c.c.config, c.info, op, c.c.graph.usageSym)
  121. onUse(c.info, op)
  122. body.add destructorCall(c.c, op, x)
  123. result = true
  124. of attachedAsgn:
  125. result = considerAsgnOrSink(c, t, body, x, y, t.assignment)
  126. of attachedSink:
  127. result = considerAsgnOrSink(c, t, body, x, y, t.sink)
  128. of attachedDeepCopy:
  129. let op = t.deepCopy
  130. if op != nil:
  131. markUsed(c.c.config, c.info, op, c.c.graph.usageSym)
  132. onUse(c.info, op)
  133. body.add newDeepCopyCall(op, x, y)
  134. result = true
  135. proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  136. if c.kind != attachedDestructor:
  137. body.add newAsgnStmt(x, y)
  138. proc addVar(father, v, value: PNode) =
  139. var vpart = newNodeI(nkIdentDefs, v.info, 3)
  140. vpart.sons[0] = v
  141. vpart.sons[1] = newNodeI(nkEmpty, v.info)
  142. vpart.sons[2] = value
  143. addSon(father, vpart)
  144. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  145. var temp = newSym(skTemp, getIdent(c.c.cache, lowerings.genPrefix), c.fn, c.info)
  146. temp.typ = getSysType(c.c.graph, body.info, tyInt)
  147. incl(temp.flags, sfFromGeneric)
  148. var v = newNodeI(nkVarSection, c.info)
  149. result = newSymNode(temp)
  150. v.addVar(result, lowerings.newIntLit(c.c.graph, body.info, first))
  151. body.add v
  152. proc genBuiltin(g: ModuleGraph; magic: TMagic; name: string; i: PNode): PNode =
  153. result = newNodeI(nkCall, i.info)
  154. result.add createMagic(g, name, magic).newSymNode
  155. result.add i
  156. proc genWhileLoop(c: var TLiftCtx; i, dest: PNode): PNode =
  157. result = newNodeI(nkWhileStmt, c.info, 2)
  158. let cmp = genBuiltin(c.c.graph, mLeI, "<=", i)
  159. cmp.add genHigh(c.c.graph, dest)
  160. cmp.typ = getSysType(c.c.graph, c.info, tyBool)
  161. result.sons[0] = cmp
  162. result.sons[1] = newNodeI(nkStmtList, c.info)
  163. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  164. let incCall = genBuiltin(c.c.graph, mInc, "inc", i)
  165. incCall.add lowerings.newIntLit(c.c.graph, c.info, 1)
  166. body.add incCall
  167. proc newSeqCall(c: PContext; x, y: PNode): PNode =
  168. # don't call genAddr(c, x) here:
  169. result = genBuiltin(c.graph, mNewSeq, "newSeq", x)
  170. let lenCall = genBuiltin(c.graph, mLengthSeq, "len", y)
  171. lenCall.typ = getSysType(c.graph, x.info, tyInt)
  172. result.add lenCall
  173. proc liftBodyAux(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  174. case t.kind
  175. of tyNone, tyEmpty, tyVoid: discard
  176. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCString,
  177. tyPtr, tyRef, tyOpt, tyUncheckedArray:
  178. defaultOp(c, t, body, x, y)
  179. of tyArray:
  180. if tfHasAsgn in t.flags:
  181. let i = declareCounter(c, body, firstOrd(c.c.config, t))
  182. let whileLoop = genWhileLoop(c, i, x)
  183. let elemType = t.lastSon
  184. liftBodyAux(c, elemType, whileLoop.sons[1], x.at(i, elemType),
  185. y.at(i, elemType))
  186. addIncStmt(c, whileLoop.sons[1], i)
  187. body.add whileLoop
  188. else:
  189. defaultOp(c, t, body, x, y)
  190. of tySequence:
  191. # note that tfHasAsgn is propagated so we need the check on
  192. # 'selectedGC' here to determine if we have the new runtime.
  193. if c.c.config.selectedGC == gcDestructors:
  194. discard considerOverloadedOp(c, t, body, x, y)
  195. elif tfHasAsgn in t.flags:
  196. if c.kind != attachedDestructor:
  197. body.add newSeqCall(c.c, x, y)
  198. let i = declareCounter(c, body, firstOrd(c.c.config, t))
  199. let whileLoop = genWhileLoop(c, i, x)
  200. let elemType = t.lastSon
  201. liftBodyAux(c, elemType, whileLoop.sons[1], x.at(i, elemType),
  202. y.at(i, elemType))
  203. addIncStmt(c, whileLoop.sons[1], i)
  204. body.add whileLoop
  205. else:
  206. defaultOp(c, t, body, x, y)
  207. of tyString:
  208. if tfHasAsgn in t.flags:
  209. discard considerOverloadedOp(c, t, body, x, y)
  210. else:
  211. defaultOp(c, t, body, x, y)
  212. of tyObject, tyDistinct:
  213. if not considerOverloadedOp(c, t, body, x, y):
  214. if t.sons[0] != nil:
  215. liftBodyAux(c, t.sons[0].skipTypes(skipPtrs), body, x, y)
  216. if t.kind == tyObject: liftBodyObj(c, t.n, body, x, y)
  217. of tyTuple:
  218. liftBodyTup(c, t, body, x, y)
  219. of tyProc:
  220. if t.callConv != ccClosure or c.kind != attachedDeepCopy:
  221. defaultOp(c, t, body, x, y)
  222. else:
  223. # a big problem is that we don't know the enviroment's type here, so we
  224. # have to go through some indirection; we delegate this to the codegen:
  225. let call = newNodeI(nkCall, c.info, 2)
  226. call.typ = t
  227. call.sons[0] = newSymNode(createMagic(c.c.graph, "deepCopy", mDeepCopy))
  228. call.sons[1] = y
  229. body.add newAsgnStmt(x, call)
  230. of tyVarargs, tyOpenArray:
  231. localError(c.c.config, c.info, "cannot copy openArray")
  232. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  233. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  234. tyGenericParam, tyGenericBody, tyNil, tyExpr, tyStmt,
  235. tyTypeDesc, tyGenericInvocation, tyForward:
  236. internalError(c.c.config, c.info, "assignment requested for type: " & typeToString(t))
  237. of tyOrdinal, tyRange, tyInferred,
  238. tyGenericInst, tyStatic, tyVar, tyLent, tyAlias, tySink:
  239. liftBodyAux(c, lastSon(t), body, x, y)
  240. of tyOptAsRef: internalError(c.c.config, "liftBodyAux")
  241. proc newProcType(info: TLineInfo; owner: PSym): PType =
  242. result = newType(tyProc, owner)
  243. result.n = newNodeI(nkFormalParams, info)
  244. rawAddSon(result, nil) # return type
  245. # result.n[0] used to be `nkType`, but now it's `nkEffectList` because
  246. # the effects are now stored in there too ... this is a bit hacky, but as
  247. # usual we desperately try to save memory:
  248. addSon(result.n, newNodeI(nkEffectList, info))
  249. proc addParam(procType: PType; param: PSym) =
  250. param.position = procType.len-1
  251. addSon(procType.n, newSymNode(param))
  252. rawAddSon(procType, param.typ)
  253. proc liftBody(c: PContext; typ: PType; kind: TTypeAttachedOp;
  254. info: TLineInfo): PSym =
  255. var a: TLiftCtx
  256. a.info = info
  257. a.c = c
  258. a.kind = kind
  259. let body = newNodeI(nkStmtList, info)
  260. let procname = case kind
  261. of attachedAsgn: getIdent(c.cache, "=")
  262. of attachedSink: getIdent(c.cache, "=sink")
  263. of attachedDeepCopy: getIdent(c.cache, "=deepcopy")
  264. of attachedDestructor: getIdent(c.cache, "=destroy")
  265. result = newSym(skProc, procname, typ.owner, info)
  266. a.fn = result
  267. a.asgnForType = typ
  268. let dest = newSym(skParam, getIdent(c.cache, "dest"), result, info)
  269. let src = newSym(skParam, getIdent(c.cache, "src"), result, info)
  270. dest.typ = makeVarType(c, typ)
  271. src.typ = typ
  272. result.typ = newProcType(info, typ.owner)
  273. result.typ.addParam dest
  274. if kind != attachedDestructor:
  275. result.typ.addParam src
  276. liftBodyAux(a, typ, body, newSymNode(dest).newDeref, newSymNode(src))
  277. # recursion is handled explicitly, do not register the type based operation
  278. # before 'liftBodyAux':
  279. if c.config.selectedGC == gcDestructors and
  280. typ.kind in {tySequence, tyString} and body.len == 0:
  281. discard "do not cache it yet"
  282. else:
  283. case kind
  284. of attachedAsgn: typ.assignment = result
  285. of attachedSink: typ.sink = result
  286. of attachedDeepCopy: typ.deepCopy = result
  287. of attachedDestructor: typ.destructor = result
  288. var n = newNodeI(nkProcDef, info, bodyPos+1)
  289. for i in 0 ..< n.len: n.sons[i] = newNodeI(nkEmpty, info)
  290. n.sons[namePos] = newSymNode(result)
  291. n.sons[paramsPos] = result.typ.n
  292. n.sons[bodyPos] = body
  293. result.ast = n
  294. incl result.flags, sfFromGeneric
  295. proc getAsgnOrLiftBody(c: PContext; typ: PType; info: TLineInfo): PSym =
  296. let t = typ.skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  297. result = t.assignment
  298. if result.isNil:
  299. result = liftBody(c, t, attachedAsgn, info)
  300. proc overloadedAsgn(c: PContext; dest, src: PNode): PNode =
  301. let a = getAsgnOrLiftBody(c, dest.typ, dest.info)
  302. result = newAsgnCall(c, a, dest, src)
  303. proc liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  304. ## In the semantic pass this is called in strategic places
  305. ## to ensure we lift assignment, destructors and moves properly.
  306. ## The later 'destroyer' pass depends on it.
  307. if not hasDestructor(typ): return
  308. when false:
  309. # do not produce wrong liftings while we're still instantiating generics:
  310. # now disabled; breaks topttree.nim!
  311. if c.typesWithOps.len > 0: return
  312. let typ = typ.skipTypes({tyGenericInst, tyAlias})
  313. # we generate the destructor first so that other operators can depend on it:
  314. if typ.destructor == nil:
  315. liftBody(c, typ, attachedDestructor, info)
  316. if typ.assignment == nil:
  317. liftBody(c, typ, attachedAsgn, info)
  318. if typ.sink == nil:
  319. liftBody(c, typ, attachedSink, info)
  320. #proc patchResolvedTypeBoundOp*(c: PContext; n: PNode): PNode =
  321. # if n.kind == nkCall and