lambdalifting.nim 30 KB

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