lambdalifting.nim 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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 file implements lambda lifting for the transformator.
  10. import
  11. options, ast, astalgo, msgs,
  12. idents, renderer, types, magicsys, lowerings, modulegraphs, lineinfos,
  13. transf, liftdestructors, typeallowed
  14. import std/[strutils, tables, intsets]
  15. when defined(nimPreviewSlimSystem):
  16. import std/assertions
  17. discard """
  18. The basic approach is that captured vars need to be put on the heap and
  19. that the calling chain needs to be explicitly modelled. Things to consider:
  20. proc a =
  21. var v = 0
  22. proc b =
  23. var w = 2
  24. for x in 0..3:
  25. proc c = capture v, w, x
  26. c()
  27. b()
  28. for x in 0..4:
  29. proc d = capture x
  30. d()
  31. Needs to be translated into:
  32. proc a =
  33. var cl: *
  34. new cl
  35. cl.v = 0
  36. proc b(cl) =
  37. var bcl: *
  38. new bcl
  39. bcl.w = 2
  40. bcl.up = cl
  41. for x in 0..3:
  42. var bcl2: *
  43. new bcl2
  44. bcl2.up = bcl
  45. bcl2.up2 = cl
  46. bcl2.x = x
  47. proc c(cl) = capture cl.up2.v, cl.up.w, cl.x
  48. c(bcl2)
  49. c(bcl)
  50. b(cl)
  51. for x in 0..4:
  52. var acl2: *
  53. new acl2
  54. acl2.x = x
  55. proc d(cl) = capture cl.x
  56. d(acl2)
  57. Closures as interfaces:
  58. proc outer: T =
  59. var captureMe: TObject # value type required for efficiency
  60. proc getter(): int = result = captureMe.x
  61. proc setter(x: int) = captureMe.x = x
  62. result = (getter, setter)
  63. Is translated to:
  64. proc outer: T =
  65. var cl: *
  66. new cl
  67. proc getter(cl): int = result = cl.captureMe.x
  68. proc setter(cl: *, x: int) = cl.captureMe.x = x
  69. result = ((cl, getter), (cl, setter))
  70. For 'byref' capture, the outer proc needs to access the captured var through
  71. the indirection too. For 'bycopy' capture, the outer proc accesses the var
  72. not through the indirection.
  73. Possible optimizations:
  74. 1) If the closure contains a single 'ref' and this
  75. reference is not re-assigned (check ``sfAddrTaken`` flag) make this the
  76. closure. This is an important optimization if closures are used as
  77. interfaces.
  78. 2) If the closure does not escape, put it onto the stack, not on the heap.
  79. 3) Dataflow analysis would help to eliminate the 'up' indirections.
  80. 4) If the captured var is not actually used in the outer proc (common?),
  81. put it into an inner proc.
  82. """
  83. # Important things to keep in mind:
  84. # * Don't base the analysis on nkProcDef et al. This doesn't work for
  85. # instantiated (formerly generic) procs. The analysis has to look at nkSym.
  86. # This also means we need to prevent the same proc is processed multiple
  87. # times via the 'processed' set.
  88. # * Keep in mind that the owner of some temporaries used to be unreliable.
  89. # * For closure iterators we merge the "real" potential closure with the
  90. # local storage requirements for efficiency. This means closure iterators
  91. # have slightly different semantics from ordinary closures.
  92. # ---------------- essential helpers -------------------------------------
  93. const
  94. upName* = ":up" # field name for the 'up' reference
  95. paramName* = ":envP"
  96. envName* = ":env"
  97. proc newCall(a: PSym, b: PNode): PNode =
  98. result = newNodeI(nkCall, a.info)
  99. result.add newSymNode(a)
  100. result.add b
  101. proc createClosureIterStateType*(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PType =
  102. var n = newNodeI(nkRange, iter.info)
  103. n.add newIntNode(nkIntLit, -1)
  104. n.add newIntNode(nkIntLit, 0)
  105. result = newType(tyRange, idgen, iter)
  106. result.n = n
  107. var intType = nilOrSysInt(g)
  108. if intType.isNil: intType = newType(tyInt, idgen, iter)
  109. rawAddSon(result, intType)
  110. proc createStateField(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PSym =
  111. result = newSym(skField, getIdent(g.cache, ":state"), idgen, iter, iter.info)
  112. result.typ = createClosureIterStateType(g, iter, idgen)
  113. proc createEnvObj(g: ModuleGraph; idgen: IdGenerator; owner: PSym; info: TLineInfo): PType =
  114. # YYY meh, just add the state field for every closure for now, it's too
  115. # hard to figure out if it comes from a closure iterator:
  116. result = createObj(g, idgen, owner, info, final=false)
  117. rawAddField(result, createStateField(g, owner, idgen))
  118. proc getClosureIterResult*(g: ModuleGraph; iter: PSym; idgen: IdGenerator): PSym =
  119. if resultPos < iter.ast.len:
  120. result = iter.ast[resultPos].sym
  121. else:
  122. # XXX a bit hacky:
  123. result = newSym(skResult, getIdent(g.cache, ":result"), idgen, iter, iter.info, {})
  124. result.typ = iter.typ.returnType
  125. incl(result.flags, sfUsed)
  126. iter.ast.add newSymNode(result)
  127. proc addHiddenParam(routine: PSym, param: PSym) =
  128. assert param.kind == skParam
  129. var params = routine.ast[paramsPos]
  130. # -1 is correct here as param.position is 0 based but we have at position 0
  131. # some nkEffect node:
  132. param.position = routine.typ.n.len-1
  133. params.add newSymNode(param)
  134. #incl(routine.typ.flags, tfCapturesEnv)
  135. assert sfFromGeneric in param.flags
  136. #echo "produced environment: ", param.id, " for ", routine.id
  137. proc getHiddenParam(g: ModuleGraph; routine: PSym): PSym =
  138. let params = routine.ast[paramsPos]
  139. let hidden = lastSon(params)
  140. if hidden.kind == nkSym and hidden.sym.kind == skParam and hidden.sym.name.s == paramName:
  141. result = hidden.sym
  142. assert sfFromGeneric in result.flags
  143. else:
  144. # writeStackTrace()
  145. localError(g.config, routine.info, "internal error: could not find env param for " & routine.name.s)
  146. result = routine
  147. proc getEnvParam*(routine: PSym): PSym =
  148. let params = routine.ast[paramsPos]
  149. let hidden = lastSon(params)
  150. if hidden.kind == nkSym and hidden.sym.name.s == paramName:
  151. result = hidden.sym
  152. assert sfFromGeneric in result.flags
  153. else:
  154. result = nil
  155. proc interestingVar(s: PSym): bool {.inline.} =
  156. result = s.kind in {skVar, skLet, skTemp, skForVar, skParam, skResult} and
  157. sfGlobal notin s.flags and
  158. s.typ.kind notin {tyStatic, tyTypeDesc}
  159. proc illegalCapture(s: PSym): bool {.inline.} =
  160. result = classifyViewType(s.typ) != noView or s.kind == skResult
  161. proc isInnerProc(s: PSym): bool =
  162. if s.kind in {skProc, skFunc, skMethod, skConverter, skIterator} and s.magic == mNone:
  163. result = s.skipGenericOwner.kind in routineKinds
  164. else:
  165. result = false
  166. proc newAsgnStmt(le, ri: PNode, info: TLineInfo): PNode =
  167. # Bugfix: unfortunately we cannot use 'nkFastAsgn' here as that would
  168. # mean to be able to capture string literals which have no GC header.
  169. # However this can only happen if the capture happens through a parameter,
  170. # which is however the only case when we generate an assignment in the first
  171. # place.
  172. result = newNodeI(nkAsgn, info, 2)
  173. result[0] = le
  174. result[1] = ri
  175. proc makeClosure*(g: ModuleGraph; idgen: IdGenerator; prc: PSym; env: PNode; info: TLineInfo): PNode =
  176. result = newNodeIT(nkClosure, info, prc.typ)
  177. result.add(newSymNode(prc))
  178. if env == nil:
  179. result.add(newNodeIT(nkNilLit, info, getSysType(g, info, tyNil)))
  180. else:
  181. if env.skipConv.kind == nkClosure:
  182. localError(g.config, info, "internal error: taking closure of closure")
  183. result.add(env)
  184. #if isClosureIterator(result.typ):
  185. createTypeBoundOps(g, nil, result.typ, info, idgen)
  186. if tfHasAsgn in result.typ.flags or optSeqDestructors in g.config.globalOptions:
  187. prc.flags.incl sfInjectDestructors
  188. proc interestingIterVar(s: PSym): bool {.inline.} =
  189. # XXX optimization: Only lift the variable if it lives across
  190. # yield/return boundaries! This can potentially speed up
  191. # closure iterators quite a bit.
  192. result = s.kind in {skResult, skVar, skLet, skTemp, skForVar} and sfGlobal notin s.flags
  193. template isIterator*(owner: PSym): bool =
  194. owner.kind == skIterator and owner.typ.callConv == ccClosure
  195. proc createTypeBoundOpsLL(g: ModuleGraph; refType: PType; info: TLineInfo; idgen: IdGenerator; owner: PSym) =
  196. if owner.kind != skMacro:
  197. createTypeBoundOps(g, nil, refType.elementType, info, idgen)
  198. createTypeBoundOps(g, nil, refType, info, idgen)
  199. if tfHasAsgn in refType.flags or optSeqDestructors in g.config.globalOptions:
  200. owner.flags.incl sfInjectDestructors
  201. proc genCreateEnv(env: PNode): PNode =
  202. var c = newNodeIT(nkObjConstr, env.info, env.typ)
  203. c.add newNodeIT(nkType, env.info, env.typ)
  204. let e = copyTree(env)
  205. e.flags.incl nfFirstWrite
  206. result = newAsgnStmt(e, c)
  207. proc liftIterSym*(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode =
  208. # transforms (iter) to (let env = newClosure[iter](); (iter, env))
  209. let iter = n.sym
  210. assert iter.isIterator
  211. result = newNodeIT(nkStmtListExpr, n.info, iter.typ)
  212. let hp = getHiddenParam(g, iter)
  213. var env: PNode
  214. if owner.isIterator:
  215. let it = getHiddenParam(g, owner)
  216. addUniqueField(it.typ.skipTypes({tyOwned})[0], hp, g.cache, idgen)
  217. env = indirectAccess(newSymNode(it), hp, hp.info)
  218. else:
  219. let e = newSym(skLet, iter.name, idgen, owner, n.info)
  220. e.typ = hp.typ
  221. e.flags = hp.flags
  222. env = newSymNode(e)
  223. var v = newNodeI(nkVarSection, n.info)
  224. addVar(v, env)
  225. result.add(v)
  226. # add 'new' statement:
  227. #result.add newCall(getSysSym(g, n.info, "internalNew"), env)
  228. result.add genCreateEnv(env)
  229. createTypeBoundOpsLL(g, env.typ, n.info, idgen, owner)
  230. result.add makeClosure(g, idgen, iter, env, n.info)
  231. proc freshVarForClosureIter*(g: ModuleGraph; s: PSym; idgen: IdGenerator; owner: PSym): PNode =
  232. let envParam = getHiddenParam(g, owner)
  233. let obj = envParam.typ.skipTypes({tyOwned, tyRef, tyPtr})
  234. let field = addField(obj, s, g.cache, idgen)
  235. var access = newSymNode(envParam)
  236. assert obj.kind == tyObject
  237. result = rawIndirectAccess(access, field, s.info)
  238. # ------------------ new stuff -------------------------------------------
  239. proc markAsClosure(g: ModuleGraph; owner: PSym; n: PNode) =
  240. let s = n.sym
  241. let isEnv = s.name.id == getIdent(g.cache, ":env").id
  242. if illegalCapture(s):
  243. localError(g.config, n.info,
  244. ("'$1' is of type <$2> which cannot be captured as it would violate memory" &
  245. " safety, declared here: $3; using '-d:nimNoLentIterators' helps in some cases." &
  246. " Consider using a <ref $2> which can be captured.") %
  247. [s.name.s, typeToString(s.typ), g.config$s.info])
  248. elif not (owner.typ.isClosure or owner.isNimcall and not owner.isExplicitCallConv or isEnv):
  249. localError(g.config, n.info, "illegal capture '$1' because '$2' has the calling convention: <$3>" %
  250. [s.name.s, owner.name.s, $owner.typ.callConv])
  251. incl(owner.typ.flags, tfCapturesEnv)
  252. if not isEnv:
  253. owner.typ.callConv = ccClosure
  254. type
  255. DetectionPass = object
  256. processed, capturedVars: IntSet
  257. ownerToType: Table[int, PType]
  258. somethingToDo: bool
  259. inTypeOf: bool
  260. graph: ModuleGraph
  261. idgen: IdGenerator
  262. proc initDetectionPass(g: ModuleGraph; fn: PSym; idgen: IdGenerator): DetectionPass =
  263. result = DetectionPass(processed: toIntSet([fn.id]),
  264. capturedVars: initIntSet(), ownerToType: initTable[int, PType](),
  265. graph: g, idgen: idgen
  266. )
  267. discard """
  268. proc outer =
  269. var a, b: int
  270. proc innerA = use(a)
  271. proc innerB = use(b); innerA()
  272. # --> innerA and innerB need to *share* the closure type!
  273. This is why need to store the 'ownerToType' table and use it
  274. during .closure'fication.
  275. """
  276. proc getEnvTypeForOwner(c: var DetectionPass; owner: PSym;
  277. info: TLineInfo): PType =
  278. result = c.ownerToType.getOrDefault(owner.id)
  279. if result.isNil:
  280. result = newType(tyRef, c.idgen, owner)
  281. let obj = createEnvObj(c.graph, c.idgen, owner, info)
  282. rawAddSon(result, obj)
  283. c.ownerToType[owner.id] = result
  284. proc asOwnedRef(c: var DetectionPass; t: PType): PType =
  285. if optOwnedRefs in c.graph.config.globalOptions:
  286. assert t.kind == tyRef
  287. result = newType(tyOwned, c.idgen, t.owner)
  288. result.flags.incl tfHasOwned
  289. result.rawAddSon t
  290. else:
  291. result = t
  292. proc getEnvTypeForOwnerUp(c: var DetectionPass; owner: PSym;
  293. info: TLineInfo): PType =
  294. var r = c.getEnvTypeForOwner(owner, info)
  295. result = newType(tyPtr, c.idgen, owner)
  296. rawAddSon(result, r.skipTypes({tyOwned, tyRef, tyPtr}))
  297. proc createUpField(c: var DetectionPass; dest, dep: PSym; info: TLineInfo) =
  298. let refObj = c.getEnvTypeForOwner(dest, info) # getHiddenParam(dest).typ
  299. let obj = refObj.skipTypes({tyOwned, tyRef, tyPtr})
  300. # The assumption here is that gcDestructors means we cannot deal
  301. # with cycles properly, so it's better to produce a weak ref (=ptr) here.
  302. # This seems to be generally correct but since it's a bit risky it's disabled
  303. # for now.
  304. # XXX This is wrong for the 'hamming' test, so remove this logic again.
  305. let fieldType = if isDefined(c.graph.config, "nimCycleBreaker"):
  306. c.getEnvTypeForOwnerUp(dep, info) #getHiddenParam(dep).typ
  307. else:
  308. c.getEnvTypeForOwner(dep, info)
  309. if refObj == fieldType:
  310. localError(c.graph.config, dep.info, "internal error: invalid up reference computed")
  311. let upIdent = getIdent(c.graph.cache, upName)
  312. let upField = lookupInRecord(obj.n, upIdent)
  313. if upField != nil:
  314. if upField.typ.skipTypes({tyOwned, tyRef, tyPtr}) != fieldType.skipTypes({tyOwned, tyRef, tyPtr}):
  315. localError(c.graph.config, dep.info, "internal error: up references do not agree")
  316. when false:
  317. if c.graph.config.selectedGC == gcDestructors and sfCursor notin upField.flags:
  318. localError(c.graph.config, dep.info, "internal error: up reference is not a .cursor")
  319. else:
  320. let result = newSym(skField, upIdent, c.idgen, obj.owner, obj.owner.info)
  321. result.typ = fieldType
  322. when false:
  323. if c.graph.config.selectedGC == gcDestructors:
  324. result.flags.incl sfCursor
  325. rawAddField(obj, result)
  326. discard """
  327. There are a couple of possibilities of how to implement closure
  328. iterators that capture outer variables in a traditional sense
  329. (aka closure closure iterators).
  330. 1. Transform iter() to iter(state, capturedEnv). So use 2 hidden
  331. parameters.
  332. 2. Add the captured vars directly to 'state'.
  333. 3. Make capturedEnv an up-reference of 'state'.
  334. We do (3) here because (2) is obviously wrong and (1) is wrong too.
  335. Consider:
  336. proc outer =
  337. var xx = 9
  338. iterator foo() =
  339. var someState = 3
  340. proc bar = echo someState
  341. proc baz = someState = 0
  342. baz()
  343. bar()
  344. """
  345. proc isTypeOf(n: PNode): bool =
  346. n.kind == nkSym and n.sym.magic in {mTypeOf, mType}
  347. proc addClosureParam(c: var DetectionPass; fn: PSym; info: TLineInfo) =
  348. var cp = getEnvParam(fn)
  349. let owner = if fn.kind == skIterator: fn else: fn.skipGenericOwner
  350. let t = c.getEnvTypeForOwner(owner, info)
  351. if cp == nil:
  352. cp = newSym(skParam, getIdent(c.graph.cache, paramName), c.idgen, fn, fn.info)
  353. incl(cp.flags, sfFromGeneric)
  354. cp.typ = t
  355. addHiddenParam(fn, cp)
  356. elif cp.typ != t and fn.kind != skIterator:
  357. localError(c.graph.config, fn.info, "internal error: inconsistent environment type")
  358. #echo "adding closure to ", fn.name.s
  359. proc detectCapturedVars(n: PNode; owner: PSym; c: var DetectionPass) =
  360. case n.kind
  361. of nkSym:
  362. let s = n.sym
  363. if s.kind in {skProc, skFunc, skMethod, skConverter, skIterator} and
  364. s.typ != nil and s.typ.callConv == ccClosure:
  365. # this handles the case that the inner proc was declared as
  366. # .closure but does not actually capture anything:
  367. addClosureParam(c, s, n.info)
  368. c.somethingToDo = true
  369. let innerProc = isInnerProc(s)
  370. if innerProc:
  371. if s.isIterator: c.somethingToDo = true
  372. if not c.processed.containsOrIncl(s.id):
  373. let body = transformBody(c.graph, c.idgen, s, {useCache})
  374. detectCapturedVars(body, s, c)
  375. let ow = s.skipGenericOwner
  376. let innerClosure = innerProc and s.typ.callConv == ccClosure and not s.isIterator
  377. let interested = interestingVar(s)
  378. if ow == owner:
  379. if owner.isIterator:
  380. c.somethingToDo = true
  381. addClosureParam(c, owner, n.info)
  382. if interestingIterVar(s):
  383. if not c.capturedVars.contains(s.id):
  384. if not c.inTypeOf: c.capturedVars.incl(s.id)
  385. let obj = getHiddenParam(c.graph, owner).typ.skipTypes({tyOwned, tyRef, tyPtr})
  386. #let obj = c.getEnvTypeForOwner(s.owner).skipTypes({tyOwned, tyRef, tyPtr})
  387. if s.name.id == getIdent(c.graph.cache, ":state").id:
  388. obj.n[0].sym.flags.incl sfNoInit
  389. obj.n[0].sym.itemId = ItemId(module: s.itemId.module, item: -s.itemId.item)
  390. else:
  391. discard addField(obj, s, c.graph.cache, c.idgen)
  392. # direct or indirect dependency:
  393. elif innerClosure or interested:
  394. discard """
  395. proc outer() =
  396. var x: int
  397. proc inner() =
  398. proc innerInner() =
  399. echo x
  400. innerInner()
  401. inner()
  402. # inner() takes a closure too!
  403. """
  404. # mark 'owner' as taking a closure:
  405. c.somethingToDo = true
  406. markAsClosure(c.graph, owner, n)
  407. addClosureParam(c, owner, n.info)
  408. #echo "capturing ", n.info
  409. # variable 's' is actually captured:
  410. if interestingVar(s):
  411. if not c.capturedVars.contains(s.id):
  412. if not c.inTypeOf: c.capturedVars.incl(s.id)
  413. let obj = c.getEnvTypeForOwner(ow, n.info).skipTypes({tyOwned, tyRef, tyPtr})
  414. #getHiddenParam(owner).typ.skipTypes({tyOwned, tyRef, tyPtr})
  415. discard addField(obj, s, c.graph.cache, c.idgen)
  416. # create required upFields:
  417. var w = owner.skipGenericOwner
  418. if isInnerProc(w) or owner.isIterator:
  419. if owner.isIterator: w = owner
  420. let last = if ow.isIterator: ow.skipGenericOwner else: ow
  421. while w != nil and w.kind != skModule and last != w:
  422. discard """
  423. proc outer =
  424. var a, b: int
  425. proc outerB =
  426. proc innerA = use(a)
  427. proc innerB = use(b); innerA()
  428. # --> make outerB of calling convention .closure and
  429. # give it the same env type that outer's env var gets:
  430. """
  431. let up = w.skipGenericOwner
  432. #echo "up for ", w.name.s, " up ", up.name.s
  433. markAsClosure(c.graph, w, n)
  434. addClosureParam(c, w, n.info) # , ow
  435. createUpField(c, w, up, n.info)
  436. w = up
  437. of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit,
  438. nkTemplateDef, nkTypeSection, nkProcDef, nkMethodDef,
  439. nkConverterDef, nkMacroDef, nkFuncDef, nkCommentStmt,
  440. nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  441. discard
  442. of nkLambdaKinds, nkIteratorDef:
  443. if n.typ != nil:
  444. detectCapturedVars(n[namePos], owner, c)
  445. of nkReturnStmt:
  446. detectCapturedVars(n[0], owner, c)
  447. of nkIdentDefs:
  448. detectCapturedVars(n[^1], owner, c)
  449. else:
  450. if n.isCallExpr and n[0].isTypeOf:
  451. c.inTypeOf = true
  452. for i in 0..<n.len:
  453. detectCapturedVars(n[i], owner, c)
  454. c.inTypeOf = false
  455. type
  456. LiftingPass = object
  457. processed: IntSet
  458. envVars: Table[int, PNode]
  459. inContainer: int
  460. unownedEnvVars: Table[int, PNode] # only required for --newruntime
  461. proc initLiftingPass(fn: PSym): LiftingPass =
  462. result = LiftingPass(processed: toIntSet([fn.id]),
  463. envVars: initTable[int, PNode]())
  464. proc accessViaEnvParam(g: ModuleGraph; n: PNode; owner: PSym): PNode =
  465. let s = n.sym
  466. # Type based expression construction for simplicity:
  467. let envParam = getHiddenParam(g, owner)
  468. if not envParam.isNil:
  469. var access = newSymNode(envParam)
  470. var obj = access.typ.elementType
  471. while true:
  472. assert obj.kind == tyObject
  473. let field = getFieldFromObj(obj, s)
  474. if field != nil:
  475. return rawIndirectAccess(access, field, n.info)
  476. let upField = lookupInRecord(obj.n, getIdent(g.cache, upName))
  477. if upField == nil: break
  478. access = rawIndirectAccess(access, upField, n.info)
  479. obj = access.typ.baseClass
  480. localError(g.config, n.info, "internal error: environment misses: " & s.name.s)
  481. result = n
  482. proc newEnvVar(cache: IdentCache; owner: PSym; typ: PType; info: TLineInfo; idgen: IdGenerator): PNode =
  483. var v = newSym(skVar, getIdent(cache, envName), idgen, owner, info)
  484. v.flags = {sfShadowed, sfGeneratedOp}
  485. v.typ = typ
  486. result = newSymNode(v)
  487. when false:
  488. if owner.kind == skIterator and owner.typ.callConv == ccClosure:
  489. let it = getHiddenParam(owner)
  490. addUniqueField(it.typ.elementType, v)
  491. result = indirectAccess(newSymNode(it), v, v.info)
  492. else:
  493. result = newSymNode(v)
  494. proc setupEnvVar(owner: PSym; d: var DetectionPass;
  495. c: var LiftingPass; info: TLineInfo): PNode =
  496. if owner.isIterator:
  497. return getHiddenParam(d.graph, owner).newSymNode
  498. result = c.envVars.getOrDefault(owner.id)
  499. if result.isNil:
  500. let envVarType = d.ownerToType.getOrDefault(owner.id)
  501. if envVarType.isNil:
  502. localError d.graph.config, owner.info, "internal error: could not determine closure type"
  503. result = newEnvVar(d.graph.cache, owner, asOwnedRef(d, envVarType), info, d.idgen)
  504. c.envVars[owner.id] = result
  505. if optOwnedRefs in d.graph.config.globalOptions:
  506. var v = newSym(skVar, getIdent(d.graph.cache, envName & "Alt"), d.idgen, owner, info)
  507. v.flags = {sfShadowed, sfGeneratedOp}
  508. v.typ = envVarType
  509. c.unownedEnvVars[owner.id] = newSymNode(v)
  510. proc getUpViaParam(g: ModuleGraph; owner: PSym): PNode =
  511. let p = getHiddenParam(g, owner)
  512. result = p.newSymNode
  513. if owner.isIterator:
  514. let upField = lookupInRecord(p.typ.skipTypes({tyOwned, tyRef, tyPtr}).n, getIdent(g.cache, upName))
  515. if upField == nil:
  516. localError(g.config, owner.info, "could not find up reference for closure iter")
  517. else:
  518. result = rawIndirectAccess(result, upField, p.info)
  519. proc rawClosureCreation(owner: PSym;
  520. d: var DetectionPass; c: var LiftingPass;
  521. info: TLineInfo): PNode =
  522. result = newNodeI(nkStmtList, owner.info)
  523. var env: PNode
  524. if owner.isIterator:
  525. env = getHiddenParam(d.graph, owner).newSymNode
  526. else:
  527. env = setupEnvVar(owner, d, c, info)
  528. if env.kind == nkSym:
  529. var v = newNodeI(nkVarSection, env.info)
  530. addVar(v, env)
  531. result.add(v)
  532. if optOwnedRefs in d.graph.config.globalOptions:
  533. let unowned = c.unownedEnvVars[owner.id]
  534. assert unowned != nil
  535. addVar(v, unowned)
  536. # add 'new' statement:
  537. result.add genCreateEnv(env)
  538. if optOwnedRefs in d.graph.config.globalOptions:
  539. let unowned = c.unownedEnvVars[owner.id]
  540. assert unowned != nil
  541. let env2 = copyTree(env)
  542. env2.typ = unowned.typ
  543. result.add newAsgnStmt(unowned, env2, env.info)
  544. createTypeBoundOpsLL(d.graph, unowned.typ, env.info, d.idgen, owner)
  545. # add assignment statements for captured parameters:
  546. for i in 1..<owner.typ.n.len:
  547. let local = owner.typ.n[i].sym
  548. if local.id in d.capturedVars:
  549. let fieldAccess = indirectAccess(env, local, env.info)
  550. # add ``env.param = param``
  551. result.add(newAsgnStmt(fieldAccess, newSymNode(local), env.info))
  552. if owner.kind != skMacro:
  553. createTypeBoundOps(d.graph, nil, fieldAccess.typ, env.info, d.idgen)
  554. if tfHasAsgn in fieldAccess.typ.flags or optSeqDestructors in d.graph.config.globalOptions:
  555. owner.flags.incl sfInjectDestructors
  556. let upField = lookupInRecord(env.typ.skipTypes({tyOwned, tyRef, tyPtr}).n, getIdent(d.graph.cache, upName))
  557. if upField != nil:
  558. let up = getUpViaParam(d.graph, owner)
  559. if up != nil and upField.typ.skipTypes({tyOwned, tyRef, tyPtr}) == up.typ.skipTypes({tyOwned, tyRef, tyPtr}):
  560. result.add(newAsgnStmt(rawIndirectAccess(env, upField, env.info),
  561. up, env.info))
  562. #elif oldenv != nil and oldenv.typ == upField.typ:
  563. # result.add(newAsgnStmt(rawIndirectAccess(env, upField, env.info),
  564. # oldenv, env.info))
  565. else:
  566. localError(d.graph.config, env.info, "internal error: cannot create up reference")
  567. # we are not in the sem'check phase anymore! so pass 'nil' for the PContext
  568. # and hope for the best:
  569. createTypeBoundOpsLL(d.graph, env.typ, owner.info, d.idgen, owner)
  570. proc finishClosureCreation(owner: PSym; d: var DetectionPass; c: LiftingPass;
  571. info: TLineInfo; res: PNode) =
  572. if optOwnedRefs in d.graph.config.globalOptions:
  573. let unowned = c.unownedEnvVars[owner.id]
  574. assert unowned != nil
  575. let nilLit = newNodeIT(nkNilLit, info, unowned.typ)
  576. res.add newAsgnStmt(unowned, nilLit, info)
  577. createTypeBoundOpsLL(d.graph, unowned.typ, info, d.idgen, owner)
  578. proc closureCreationForIter(iter: PNode;
  579. d: var DetectionPass; c: var LiftingPass): PNode =
  580. result = newNodeIT(nkStmtListExpr, iter.info, iter.sym.typ)
  581. let owner = iter.sym.skipGenericOwner
  582. var v = newSym(skVar, getIdent(d.graph.cache, envName), d.idgen, owner, iter.info)
  583. incl(v.flags, sfShadowed)
  584. v.typ = asOwnedRef(d, getHiddenParam(d.graph, iter.sym).typ)
  585. var vnode: PNode
  586. if owner.isIterator:
  587. let it = getHiddenParam(d.graph, owner)
  588. addUniqueField(it.typ.skipTypes({tyOwned, tyRef, tyPtr}), v, d.graph.cache, d.idgen)
  589. vnode = indirectAccess(newSymNode(it), v, v.info)
  590. else:
  591. vnode = v.newSymNode
  592. var vs = newNodeI(nkVarSection, iter.info)
  593. addVar(vs, vnode)
  594. result.add(vs)
  595. result.add genCreateEnv(vnode)
  596. createTypeBoundOpsLL(d.graph, vnode.typ, iter.info, d.idgen, owner)
  597. let upField = lookupInRecord(v.typ.skipTypes({tyOwned, tyRef, tyPtr}).n, getIdent(d.graph.cache, upName))
  598. if upField != nil:
  599. let u = setupEnvVar(owner, d, c, iter.info)
  600. if u.typ.skipTypes({tyOwned, tyRef, tyPtr}) == upField.typ.skipTypes({tyOwned, tyRef, tyPtr}):
  601. result.add(newAsgnStmt(rawIndirectAccess(vnode, upField, iter.info),
  602. u, iter.info))
  603. else:
  604. localError(d.graph.config, iter.info, "internal error: cannot create up reference for iter")
  605. result.add makeClosure(d.graph, d.idgen, iter.sym, vnode, iter.info)
  606. proc accessViaEnvVar(n: PNode; owner: PSym; d: var DetectionPass;
  607. c: var LiftingPass): PNode =
  608. var access = setupEnvVar(owner, d, c, n.info)
  609. if optOwnedRefs in d.graph.config.globalOptions:
  610. access = c.unownedEnvVars[owner.id]
  611. let obj = access.typ.skipTypes({tyOwned, tyRef, tyPtr})
  612. let field = getFieldFromObj(obj, n.sym)
  613. if field != nil:
  614. result = rawIndirectAccess(access, field, n.info)
  615. else:
  616. localError(d.graph.config, n.info, "internal error: not part of closure object type")
  617. result = n
  618. proc getStateField*(g: ModuleGraph; owner: PSym): PSym =
  619. getHiddenParam(g, owner).typ.skipTypes({tyOwned, tyRef, tyPtr}).n[0].sym
  620. proc liftCapturedVars(n: PNode; owner: PSym; d: var DetectionPass;
  621. c: var LiftingPass): PNode
  622. proc symToClosure(n: PNode; owner: PSym; d: var DetectionPass;
  623. c: var LiftingPass): PNode =
  624. let s = n.sym
  625. if s == owner:
  626. # recursive calls go through (lambda, hiddenParam):
  627. let available = getHiddenParam(d.graph, owner)
  628. result = makeClosure(d.graph, d.idgen, s, available.newSymNode, n.info)
  629. elif s.isIterator:
  630. result = closureCreationForIter(n, d, c)
  631. elif s.skipGenericOwner == owner:
  632. # direct dependency, so use the outer's env variable:
  633. result = makeClosure(d.graph, d.idgen, s, setupEnvVar(owner, d, c, n.info), n.info)
  634. else:
  635. result = nil
  636. let available = getHiddenParam(d.graph, owner)
  637. let wanted = getHiddenParam(d.graph, s).typ
  638. # ugh: call through some other inner proc;
  639. var access = newSymNode(available)
  640. while true:
  641. if access.typ == wanted:
  642. return makeClosure(d.graph, d.idgen, s, access, n.info)
  643. let obj = access.typ.skipTypes({tyOwned, tyRef, tyPtr})
  644. let upField = lookupInRecord(obj.n, getIdent(d.graph.cache, upName))
  645. if upField == nil:
  646. localError(d.graph.config, n.info, "internal error: no environment found")
  647. return n
  648. access = rawIndirectAccess(access, upField, n.info)
  649. proc liftCapturedVars(n: PNode; owner: PSym; d: var DetectionPass;
  650. c: var LiftingPass): PNode =
  651. result = n
  652. case n.kind
  653. of nkSym:
  654. let s = n.sym
  655. if isInnerProc(s):
  656. if not c.processed.containsOrIncl(s.id):
  657. #if s.name.s == "temp":
  658. # echo renderTree(s.getBody, {renderIds})
  659. let oldInContainer = c.inContainer
  660. c.inContainer = 0
  661. var body = transformBody(d.graph, d.idgen, s, {})
  662. body = liftCapturedVars(body, s, d, c)
  663. if c.envVars.getOrDefault(s.id).isNil:
  664. s.transformedBody = body
  665. else:
  666. s.transformedBody = newTree(nkStmtList, rawClosureCreation(s, d, c, n.info), body)
  667. finishClosureCreation(s, d, c, n.info, s.transformedBody)
  668. c.inContainer = oldInContainer
  669. if s.typ.callConv == ccClosure:
  670. result = symToClosure(n, owner, d, c)
  671. elif s.id in d.capturedVars:
  672. if s.owner != owner:
  673. result = accessViaEnvParam(d.graph, n, owner)
  674. elif owner.isIterator and interestingIterVar(s):
  675. result = accessViaEnvParam(d.graph, n, owner)
  676. else:
  677. result = accessViaEnvVar(n, owner, d, c)
  678. of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit, nkComesFrom,
  679. nkTemplateDef, nkTypeSection, nkProcDef, nkMethodDef, nkConverterDef,
  680. nkMacroDef, nkFuncDef, nkMixinStmt, nkBindStmt:
  681. discard
  682. of nkClosure:
  683. if n[1].kind == nkNilLit:
  684. n[0] = liftCapturedVars(n[0], owner, d, c)
  685. let x = n[0].skipConv
  686. if x.kind == nkClosure:
  687. #localError(n.info, "internal error: closure to closure created")
  688. # now we know better, so patch it:
  689. n[0] = x[0]
  690. n[1] = x[1]
  691. of nkLambdaKinds, nkIteratorDef:
  692. if n.typ != nil and n[namePos].kind == nkSym:
  693. let oldInContainer = c.inContainer
  694. c.inContainer = 0
  695. let m = newSymNode(n[namePos].sym)
  696. m.typ = n.typ
  697. result = liftCapturedVars(m, owner, d, c)
  698. c.inContainer = oldInContainer
  699. of nkHiddenStdConv:
  700. if n.len == 2:
  701. n[1] = liftCapturedVars(n[1], owner, d, c)
  702. if n[1].kind == nkClosure: result = n[1]
  703. of nkReturnStmt:
  704. if n[0].kind in {nkAsgn, nkFastAsgn, nkSinkAsgn}:
  705. # we have a `result = result` expression produced by the closure
  706. # transform, let's not touch the LHS in order to make the lifting pass
  707. # correct when `result` is lifted
  708. n[0][1] = liftCapturedVars(n[0][1], owner, d, c)
  709. else:
  710. n[0] = liftCapturedVars(n[0], owner, d, c)
  711. of nkTypeOfExpr:
  712. result = n
  713. else:
  714. if n.isCallExpr and n[0].isTypeOf:
  715. return
  716. if owner.isIterator:
  717. if nfLL in n.flags:
  718. # special case 'when nimVm' due to bug #3636:
  719. n[1] = liftCapturedVars(n[1], owner, d, c)
  720. return
  721. let inContainer = n.kind in {nkObjConstr, nkBracket}
  722. if inContainer: inc c.inContainer
  723. for i in 0..<n.len:
  724. n[i] = liftCapturedVars(n[i], owner, d, c)
  725. if inContainer: dec c.inContainer
  726. # ------------------ old stuff -------------------------------------------
  727. proc semCaptureSym*(s, owner: PSym) =
  728. discard """
  729. proc outer() =
  730. var x: int
  731. proc inner() =
  732. proc innerInner() =
  733. echo x
  734. innerInner()
  735. inner()
  736. # inner() takes a closure too!
  737. """
  738. proc propagateClosure(start, last: PSym) =
  739. var o = start
  740. while o != nil and o.kind != skModule:
  741. if o == last: break
  742. o.typ.callConv = ccClosure
  743. o = o.skipGenericOwner
  744. if interestingVar(s) and s.kind != skResult:
  745. if owner.typ != nil and not isGenericRoutine(owner):
  746. # XXX: is this really safe?
  747. # if we capture a var from another generic routine,
  748. # it won't be consider captured.
  749. var o = owner.skipGenericOwner
  750. while o != nil and o.kind != skModule:
  751. if s.owner == o:
  752. if owner.typ.callConv == ccClosure or owner.kind == skIterator or
  753. owner.typ.callConv == ccNimCall and tfExplicitCallConv notin owner.typ.flags:
  754. owner.typ.callConv = ccClosure
  755. propagateClosure(owner.skipGenericOwner, s.owner)
  756. else:
  757. discard "do not produce an error here, but later"
  758. #echo "computing .closure for ", owner.name.s, " because of ", s.name.s
  759. o = o.skipGenericOwner
  760. # since the analysis is not entirely correct, we don't set 'tfCapturesEnv'
  761. # here
  762. proc liftIterToProc*(g: ModuleGraph; fn: PSym; body: PNode; ptrType: PType;
  763. idgen: IdGenerator): PNode =
  764. var d = initDetectionPass(g, fn, idgen)
  765. var c = initLiftingPass(fn)
  766. # pretend 'fn' is a closure iterator for the analysis:
  767. let oldKind = fn.kind
  768. let oldCC = fn.typ.callConv
  769. fn.transitionRoutineSymKind(skIterator)
  770. fn.typ.callConv = ccClosure
  771. d.ownerToType[fn.id] = ptrType
  772. detectCapturedVars(body, fn, d)
  773. result = liftCapturedVars(body, fn, d, c)
  774. fn.transitionRoutineSymKind(oldKind)
  775. fn.typ.callConv = oldCC
  776. proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool;
  777. idgen: IdGenerator; flags: TransformFlags): PNode =
  778. let isCompileTime = sfCompileTime in fn.flags or fn.kind == skMacro
  779. if body.kind == nkEmpty or
  780. (fn.skipGenericOwner.kind != skModule and force notin flags):
  781. # ignore forward declaration:
  782. result = body
  783. tooEarly = true
  784. else:
  785. var d = initDetectionPass(g, fn, idgen)
  786. detectCapturedVars(body, fn, d)
  787. if not d.somethingToDo and fn.isIterator:
  788. addClosureParam(d, fn, body.info)
  789. d.somethingToDo = true
  790. if d.somethingToDo:
  791. var c = initLiftingPass(fn)
  792. result = liftCapturedVars(body, fn, d, c)
  793. # echo renderTree(result, {renderIds})
  794. if c.envVars.getOrDefault(fn.id) != nil:
  795. result = newTree(nkStmtList, rawClosureCreation(fn, d, c, body.info), result)
  796. finishClosureCreation(fn, d, c, body.info, result)
  797. else:
  798. result = body
  799. #if fn.name.s == "get2":
  800. # echo "had something to do ", d.somethingToDo
  801. # echo renderTree(result, {renderIds})
  802. proc liftLambdasForTopLevel*(module: PSym, body: PNode): PNode =
  803. # XXX implement it properly
  804. result = body
  805. # ------------------- iterator transformation --------------------------------
  806. proc liftForLoop*(g: ModuleGraph; body: PNode; idgen: IdGenerator; owner: PSym): PNode =
  807. # problem ahead: the iterator could be invoked indirectly, but then
  808. # we don't know what environment to create here:
  809. #
  810. # iterator count(): int =
  811. # yield 0
  812. #
  813. # iterator count2(): int =
  814. # var x = 3
  815. # yield x
  816. # inc x
  817. # yield x
  818. #
  819. # proc invoke(iter: iterator(): int) =
  820. # for x in iter(): echo x
  821. #
  822. # --> When to create the closure? --> for the (count) occurrence!
  823. discard """
  824. for i in foo(): ...
  825. Is transformed to:
  826. cl = createClosure()
  827. while true:
  828. let i = foo(cl)
  829. if (nkBreakState(cl.state)):
  830. break
  831. ...
  832. """
  833. if not (body.kind == nkForStmt and body[^2].kind in nkCallKinds):
  834. localError(g.config, body.info, "ignored invalid for loop")
  835. return body
  836. var call = body[^2]
  837. result = newNodeI(nkStmtList, body.info)
  838. # static binding?
  839. var env: PSym = nil
  840. let op = call[0]
  841. if op.kind == nkSym and op.sym.isIterator:
  842. # createClosure()
  843. let iter = op.sym
  844. let hp = getHiddenParam(g, iter)
  845. env = newSym(skLet, iter.name, idgen, owner, body.info)
  846. env.typ = hp.typ
  847. env.flags = hp.flags
  848. var v = newNodeI(nkVarSection, body.info)
  849. addVar(v, newSymNode(env))
  850. result.add(v)
  851. # add 'new' statement:
  852. result.add genCreateEnv(env.newSymNode)
  853. createTypeBoundOpsLL(g, env.typ, body.info, idgen, owner)
  854. elif op.kind == nkStmtListExpr:
  855. let closure = op.lastSon
  856. if closure.kind == nkClosure:
  857. call[0] = closure
  858. for i in 0..<op.len-1:
  859. result.add op[i]
  860. var loopBody = newNodeI(nkStmtList, body.info, 3)
  861. var whileLoop = newNodeI(nkWhileStmt, body.info, 2)
  862. whileLoop[0] = newIntTypeNode(1, getSysType(g, body.info, tyBool))
  863. whileLoop[1] = loopBody
  864. result.add whileLoop
  865. # setup loopBody:
  866. # gather vars in a tuple:
  867. var v2 = newNodeI(nkLetSection, body.info)
  868. var vpart = newNodeI(if body.len == 3: nkIdentDefs else: nkVarTuple, body.info)
  869. if body.len == 3 and body[0].kind == nkVarTuple:
  870. vpart = body[0] # fixes for (i,j) in walk() # bug #15924
  871. else:
  872. for i in 0..<body.len-2:
  873. if body[i].kind == nkSym:
  874. body[i].sym.transitionToLet()
  875. vpart.add body[i]
  876. vpart.add newNodeI(nkEmpty, body.info) # no explicit type
  877. if not env.isNil:
  878. call[0] = makeClosure(g, idgen, call[0].sym, env.newSymNode, body.info)
  879. vpart.add call
  880. v2.add vpart
  881. loopBody[0] = v2
  882. var bs = newNodeI(nkBreakState, body.info)
  883. bs.add call[0]
  884. let ibs = newNodeI(nkIfStmt, body.info)
  885. let elifBranch = newNodeI(nkElifBranch, body.info)
  886. elifBranch.add(bs)
  887. let br = newNodeI(nkBreakStmt, body.info)
  888. br.add(g.emptyNode)
  889. elifBranch.add(br)
  890. ibs.add(elifBranch)
  891. loopBody[1] = ibs
  892. loopBody[2] = body[^1]