lambdalifting.nim 37 KB

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