semasgn.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. markUsed(c.c.config, c.info, op, c.c.graph.usageSym)
  109. styleCheckUse(c.info, op)
  110. body.add newAsgnCall(c.c, op, x, y)
  111. result = true
  112. proc considerOverloadedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  113. case c.kind
  114. of attachedDestructor:
  115. let op = t.destructor
  116. if op != nil:
  117. markUsed(c.c.config, c.info, op, c.c.graph.usageSym)
  118. styleCheckUse(c.info, op)
  119. body.add destructorCall(c.c, op, x)
  120. result = true
  121. of attachedAsgn:
  122. result = considerAsgnOrSink(c, t, body, x, y, t.assignment)
  123. of attachedSink:
  124. result = considerAsgnOrSink(c, t, body, x, y, t.sink)
  125. of attachedDeepCopy:
  126. let op = t.deepCopy
  127. if op != nil:
  128. markUsed(c.c.config, c.info, op, c.c.graph.usageSym)
  129. styleCheckUse(c.info, op)
  130. body.add newDeepCopyCall(op, x, y)
  131. result = true
  132. proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  133. if c.kind != attachedDestructor:
  134. body.add newAsgnStmt(x, y)
  135. proc addVar(father, v, value: PNode) =
  136. var vpart = newNodeI(nkIdentDefs, v.info, 3)
  137. vpart.sons[0] = v
  138. vpart.sons[1] = newNodeI(nkEmpty, v.info)
  139. vpart.sons[2] = value
  140. addSon(father, vpart)
  141. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  142. var temp = newSym(skTemp, getIdent(c.c.cache, lowerings.genPrefix), c.fn, c.info)
  143. temp.typ = getSysType(c.c.graph, body.info, tyInt)
  144. incl(temp.flags, sfFromGeneric)
  145. var v = newNodeI(nkVarSection, c.info)
  146. result = newSymNode(temp)
  147. v.addVar(result, lowerings.newIntLit(c.c.graph, body.info, first))
  148. body.add v
  149. proc genBuiltin(g: ModuleGraph; magic: TMagic; name: string; i: PNode): PNode =
  150. result = newNodeI(nkCall, i.info)
  151. result.add createMagic(g, name, magic).newSymNode
  152. result.add i
  153. proc genWhileLoop(c: var TLiftCtx; i, dest: PNode): PNode =
  154. result = newNodeI(nkWhileStmt, c.info, 2)
  155. let cmp = genBuiltin(c.c.graph, mLeI, "<=", i)
  156. cmp.add genHigh(c.c.graph, dest)
  157. cmp.typ = getSysType(c.c.graph, c.info, tyBool)
  158. result.sons[0] = cmp
  159. result.sons[1] = newNodeI(nkStmtList, c.info)
  160. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  161. let incCall = genBuiltin(c.c.graph, mInc, "inc", i)
  162. incCall.add lowerings.newIntLit(c.c.graph, c.info, 1)
  163. body.add incCall
  164. proc newSeqCall(c: PContext; x, y: PNode): PNode =
  165. # don't call genAddr(c, x) here:
  166. result = genBuiltin(c.graph, mNewSeq, "newSeq", x)
  167. let lenCall = genBuiltin(c.graph, mLengthSeq, "len", y)
  168. lenCall.typ = getSysType(c.graph, x.info, tyInt)
  169. result.add lenCall
  170. proc liftBodyAux(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  171. case t.kind
  172. of tyNone, tyEmpty, tyVoid: discard
  173. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCString,
  174. tyPtr, tyRef, tyOpt:
  175. defaultOp(c, t, body, x, y)
  176. of tyArray:
  177. if {tfHasAsgn, tfUncheckedArray} * t.flags == {tfHasAsgn}:
  178. let i = declareCounter(c, body, firstOrd(c.c.config, t))
  179. let whileLoop = genWhileLoop(c, i, x)
  180. let elemType = t.lastSon
  181. liftBodyAux(c, elemType, whileLoop.sons[1], x.at(i, elemType),
  182. y.at(i, elemType))
  183. addIncStmt(c, whileLoop.sons[1], i)
  184. body.add whileLoop
  185. else:
  186. defaultOp(c, t, body, x, y)
  187. of tySequence:
  188. # note that tfHasAsgn is propagated so we need the check on
  189. # 'selectedGC' here to determine if we have the new runtime.
  190. if c.c.config.selectedGC == gcDestructors:
  191. discard considerOverloadedOp(c, t, body, x, y)
  192. elif tfHasAsgn in t.flags:
  193. if c.kind != attachedDestructor:
  194. body.add newSeqCall(c.c, x, y)
  195. let i = declareCounter(c, body, firstOrd(c.c.config, t))
  196. let whileLoop = genWhileLoop(c, i, x)
  197. let elemType = t.lastSon
  198. liftBodyAux(c, elemType, whileLoop.sons[1], x.at(i, elemType),
  199. y.at(i, elemType))
  200. addIncStmt(c, whileLoop.sons[1], i)
  201. body.add whileLoop
  202. else:
  203. defaultOp(c, t, body, x, y)
  204. of tyString:
  205. if tfHasAsgn in t.flags:
  206. discard considerOverloadedOp(c, t, body, x, y)
  207. else:
  208. defaultOp(c, t, body, x, y)
  209. of tyObject, tyDistinct:
  210. if not considerOverloadedOp(c, t, body, x, y):
  211. if t.sons[0] != nil:
  212. liftBodyAux(c, t.sons[0].skipTypes(skipPtrs), body, x, y)
  213. if t.kind == tyObject: liftBodyObj(c, t.n, body, x, y)
  214. of tyTuple:
  215. liftBodyTup(c, t, body, x, y)
  216. of tyProc:
  217. if t.callConv != ccClosure or c.kind != attachedDeepCopy:
  218. defaultOp(c, t, body, x, y)
  219. else:
  220. # a big problem is that we don't know the enviroment's type here, so we
  221. # have to go through some indirection; we delegate this to the codegen:
  222. let call = newNodeI(nkCall, c.info, 2)
  223. call.typ = t
  224. call.sons[0] = newSymNode(createMagic(c.c.graph, "deepCopy", mDeepCopy))
  225. call.sons[1] = y
  226. body.add newAsgnStmt(x, call)
  227. of tyVarargs, tyOpenArray:
  228. localError(c.c.config, c.info, "cannot copy openArray")
  229. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  230. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  231. tyGenericParam, tyGenericBody, tyNil, tyExpr, tyStmt,
  232. tyTypeDesc, tyGenericInvocation, tyForward:
  233. internalError(c.c.config, c.info, "assignment requested for type: " & typeToString(t))
  234. of tyOrdinal, tyRange, tyInferred,
  235. tyGenericInst, tyStatic, tyVar, tyLent, tyAlias, tySink:
  236. liftBodyAux(c, lastSon(t), body, x, y)
  237. of tyUnused, tyOptAsRef: internalError(c.c.config, "liftBodyAux")
  238. proc newProcType(info: TLineInfo; owner: PSym): PType =
  239. result = newType(tyProc, owner)
  240. result.n = newNodeI(nkFormalParams, info)
  241. rawAddSon(result, nil) # return type
  242. # result.n[0] used to be `nkType`, but now it's `nkEffectList` because
  243. # the effects are now stored in there too ... this is a bit hacky, but as
  244. # usual we desperately try to save memory:
  245. addSon(result.n, newNodeI(nkEffectList, info))
  246. proc addParam(procType: PType; param: PSym) =
  247. param.position = procType.len-1
  248. addSon(procType.n, newSymNode(param))
  249. rawAddSon(procType, param.typ)
  250. proc liftBody(c: PContext; typ: PType; kind: TTypeAttachedOp;
  251. info: TLineInfo): PSym =
  252. var a: TLiftCtx
  253. a.info = info
  254. a.c = c
  255. a.kind = kind
  256. let body = newNodeI(nkStmtList, info)
  257. let procname = case kind
  258. of attachedAsgn: getIdent(c.cache, "=")
  259. of attachedSink: getIdent(c.cache, "=sink")
  260. of attachedDeepCopy: getIdent(c.cache, "=deepcopy")
  261. of attachedDestructor: getIdent(c.cache, "=destroy")
  262. result = newSym(skProc, procname, typ.owner, info)
  263. a.fn = result
  264. a.asgnForType = typ
  265. let dest = newSym(skParam, getIdent(c.cache, "dest"), result, info)
  266. let src = newSym(skParam, getIdent(c.cache, "src"), result, info)
  267. dest.typ = makeVarType(c, typ)
  268. src.typ = typ
  269. result.typ = newProcType(info, typ.owner)
  270. result.typ.addParam dest
  271. if kind != attachedDestructor:
  272. result.typ.addParam src
  273. liftBodyAux(a, typ, body, newSymNode(dest).newDeref, newSymNode(src))
  274. # recursion is handled explicitly, do not register the type based operation
  275. # before 'liftBodyAux':
  276. case kind
  277. of attachedAsgn: typ.assignment = result
  278. of attachedSink: typ.sink = result
  279. of attachedDeepCopy: typ.deepCopy = result
  280. of attachedDestructor: typ.destructor = result
  281. var n = newNodeI(nkProcDef, info, bodyPos+1)
  282. for i in 0 ..< n.len: n.sons[i] = newNodeI(nkEmpty, info)
  283. n.sons[namePos] = newSymNode(result)
  284. n.sons[paramsPos] = result.typ.n
  285. n.sons[bodyPos] = body
  286. result.ast = n
  287. incl result.flags, sfFromGeneric
  288. proc getAsgnOrLiftBody(c: PContext; typ: PType; info: TLineInfo): PSym =
  289. let t = typ.skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  290. result = t.assignment
  291. if result.isNil:
  292. result = liftBody(c, t, attachedAsgn, info)
  293. proc overloadedAsgn(c: PContext; dest, src: PNode): PNode =
  294. let a = getAsgnOrLiftBody(c, dest.typ, dest.info)
  295. result = newAsgnCall(c, a, dest, src)
  296. proc liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  297. ## In the semantic pass this is called in strategic places
  298. ## to ensure we lift assignment, destructors and moves properly.
  299. ## The later 'destroyer' pass depends on it.
  300. if not hasDestructor(typ): return
  301. when false:
  302. # do not produce wrong liftings while we're still instantiating generics:
  303. # now disabled; breaks topttree.nim!
  304. if c.typesWithOps.len > 0: return
  305. let typ = typ.skipTypes({tyGenericInst, tyAlias})
  306. # we generate the destructor first so that other operators can depend on it:
  307. if typ.destructor == nil:
  308. liftBody(c, typ, attachedDestructor, info)
  309. if typ.assignment == nil:
  310. liftBody(c, typ, attachedAsgn, info)
  311. if typ.sink == nil:
  312. liftBody(c, typ, attachedSink, info)
  313. #proc patchResolvedTypeBoundOp*(c: PContext; n: PNode): PNode =
  314. # if n.kind == nkCall and