lambdalifting.nim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. # direct or indirect dependency:
  342. elif (innerProc and s.typ.callConv == ccClosure) or interestingVar(s):
  343. discard """
  344. proc outer() =
  345. var x: int
  346. proc inner() =
  347. proc innerInner() =
  348. echo x
  349. innerInner()
  350. inner()
  351. # inner() takes a closure too!
  352. """
  353. # mark 'owner' as taking a closure:
  354. c.somethingToDo = true
  355. markAsClosure(c.graph, owner, n)
  356. addClosureParam(c, owner, n.info)
  357. #echo "capturing ", n.info
  358. # variable 's' is actually captured:
  359. if interestingVar(s) and not c.capturedVars.containsOrIncl(s.id):
  360. let obj = c.getEnvTypeForOwner(ow, n.info).lastSon
  361. #getHiddenParam(owner).typ.lastSon
  362. addField(obj, s, c.graph.cache)
  363. # create required upFields:
  364. var w = owner.skipGenericOwner
  365. if isInnerProc(w) or owner.isIterator:
  366. if owner.isIterator: w = owner
  367. let last = if ow.isIterator: ow.skipGenericOwner else: ow
  368. while w != nil and w.kind != skModule and last != w:
  369. discard """
  370. proc outer =
  371. var a, b: int
  372. proc outerB =
  373. proc innerA = use(a)
  374. proc innerB = use(b); innerA()
  375. # --> make outerB of calling convention .closure and
  376. # give it the same env type that outer's env var gets:
  377. """
  378. let up = w.skipGenericOwner
  379. #echo "up for ", w.name.s, " up ", up.name.s
  380. markAsClosure(c.graph, w, n)
  381. addClosureParam(c, w, n.info) # , ow
  382. createUpField(c, w, up, n.info)
  383. w = up
  384. of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit,
  385. nkTemplateDef, nkTypeSection, nkProcDef, nkMethodDef,
  386. nkConverterDef, nkMacroDef, nkFuncDef:
  387. discard
  388. of nkLambdaKinds, nkIteratorDef:
  389. if n.typ != nil:
  390. detectCapturedVars(n[namePos], owner, c)
  391. of nkReturnStmt:
  392. if n[0].kind in {nkAsgn, nkFastAsgn}:
  393. detectCapturedVars(n[0].sons[1], owner, c)
  394. else: assert n[0].kind == nkEmpty
  395. else:
  396. for i in 0..<n.len:
  397. detectCapturedVars(n[i], owner, c)
  398. type
  399. LiftingPass = object
  400. processed: IntSet
  401. envVars: Table[int, PNode]
  402. inContainer: int
  403. proc initLiftingPass(fn: PSym): LiftingPass =
  404. result.processed = initIntSet()
  405. result.processed.incl(fn.id)
  406. result.envVars = initTable[int, PNode]()
  407. proc accessViaEnvParam(g: ModuleGraph; n: PNode; owner: PSym): PNode =
  408. let s = n.sym
  409. # Type based expression construction for simplicity:
  410. let envParam = getHiddenParam(g, owner)
  411. if not envParam.isNil:
  412. var access = newSymNode(envParam)
  413. while true:
  414. let obj = access.typ.sons[0]
  415. assert obj.kind == tyObject
  416. let field = getFieldFromObj(obj, s)
  417. if field != nil:
  418. return rawIndirectAccess(access, field, n.info)
  419. let upField = lookupInRecord(obj.n, getIdent(g.cache, upName))
  420. if upField == nil: break
  421. access = rawIndirectAccess(access, upField, n.info)
  422. localError(g.config, n.info, "internal error: environment misses: " & s.name.s)
  423. result = n
  424. proc newEnvVar(cache: IdentCache; owner: PSym; typ: PType): PNode =
  425. var v = newSym(skVar, getIdent(cache, envName), owner, owner.info)
  426. incl(v.flags, sfShadowed)
  427. v.typ = typ
  428. result = newSymNode(v)
  429. when false:
  430. if owner.kind == skIterator and owner.typ.callConv == ccClosure:
  431. let it = getHiddenParam(owner)
  432. addUniqueField(it.typ.sons[0], v)
  433. result = indirectAccess(newSymNode(it), v, v.info)
  434. else:
  435. result = newSymNode(v)
  436. proc setupEnvVar(owner: PSym; d: DetectionPass;
  437. c: var LiftingPass): PNode =
  438. if owner.isIterator:
  439. return getHiddenParam(d.graph, owner).newSymNode
  440. result = c.envvars.getOrDefault(owner.id)
  441. if result.isNil:
  442. let envVarType = d.ownerToType.getOrDefault(owner.id)
  443. if envVarType.isNil:
  444. localError d.graph.config, owner.info, "internal error: could not determine closure type"
  445. result = newEnvVar(d.graph.cache, owner, envVarType)
  446. c.envVars[owner.id] = result
  447. proc getUpViaParam(g: ModuleGraph; owner: PSym): PNode =
  448. let p = getHiddenParam(g, owner)
  449. result = p.newSymNode
  450. if owner.isIterator:
  451. let upField = lookupInRecord(p.typ.lastSon.n, getIdent(g.cache, upName))
  452. if upField == nil:
  453. localError(g.config, owner.info, "could not find up reference for closure iter")
  454. else:
  455. result = rawIndirectAccess(result, upField, p.info)
  456. proc rawClosureCreation(owner: PSym;
  457. d: DetectionPass; c: var LiftingPass): PNode =
  458. result = newNodeI(nkStmtList, owner.info)
  459. var env: PNode
  460. if owner.isIterator:
  461. env = getHiddenParam(d.graph, owner).newSymNode
  462. else:
  463. env = setupEnvVar(owner, d, c)
  464. if env.kind == nkSym:
  465. var v = newNodeI(nkVarSection, env.info)
  466. addVar(v, env)
  467. result.add(v)
  468. # add 'new' statement:
  469. result.add(newCall(getSysSym(d.graph, env.info, "internalNew"), env))
  470. # add assignment statements for captured parameters:
  471. for i in 1..<owner.typ.n.len:
  472. let local = owner.typ.n[i].sym
  473. if local.id in d.capturedVars:
  474. let fieldAccess = indirectAccess(env, local, env.info)
  475. # add ``env.param = param``
  476. result.add(newAsgnStmt(fieldAccess, newSymNode(local), env.info))
  477. let upField = lookupInRecord(env.typ.lastSon.n, getIdent(d.graph.cache, upName))
  478. if upField != nil:
  479. let up = getUpViaParam(d.graph, owner)
  480. if up != nil and upField.typ == up.typ:
  481. result.add(newAsgnStmt(rawIndirectAccess(env, upField, env.info),
  482. up, env.info))
  483. #elif oldenv != nil and oldenv.typ == upField.typ:
  484. # result.add(newAsgnStmt(rawIndirectAccess(env, upField, env.info),
  485. # oldenv, env.info))
  486. else:
  487. localError(d.graph.config, env.info, "internal error: cannot create up reference")
  488. proc closureCreationForIter(iter: PNode;
  489. d: DetectionPass; c: var LiftingPass): PNode =
  490. result = newNodeIT(nkStmtListExpr, iter.info, iter.sym.typ)
  491. let owner = iter.sym.skipGenericOwner
  492. var v = newSym(skVar, getIdent(d.graph.cache, envName), owner, iter.info)
  493. incl(v.flags, sfShadowed)
  494. v.typ = getHiddenParam(d.graph, iter.sym).typ
  495. var vnode: PNode
  496. if owner.isIterator:
  497. let it = getHiddenParam(d.graph, owner)
  498. addUniqueField(it.typ.sons[0], v, d.graph.cache)
  499. vnode = indirectAccess(newSymNode(it), v, v.info)
  500. else:
  501. vnode = v.newSymNode
  502. var vs = newNodeI(nkVarSection, iter.info)
  503. addVar(vs, vnode)
  504. result.add(vs)
  505. result.add(newCall(getSysSym(d.graph, iter.info, "internalNew"), vnode))
  506. let upField = lookupInRecord(v.typ.lastSon.n, getIdent(d.graph.cache, upName))
  507. if upField != nil:
  508. let u = setupEnvVar(owner, d, c)
  509. if u.typ == upField.typ:
  510. result.add(newAsgnStmt(rawIndirectAccess(vnode, upField, iter.info),
  511. u, iter.info))
  512. else:
  513. localError(d.graph.config, iter.info, "internal error: cannot create up reference for iter")
  514. result.add makeClosure(d.graph, iter.sym, vnode, iter.info)
  515. proc accessViaEnvVar(n: PNode; owner: PSym; d: DetectionPass;
  516. c: var LiftingPass): PNode =
  517. let access = setupEnvVar(owner, d, c)
  518. let obj = access.typ.sons[0]
  519. let field = getFieldFromObj(obj, n.sym)
  520. if field != nil:
  521. result = rawIndirectAccess(access, field, n.info)
  522. else:
  523. localError(d.graph.config, n.info, "internal error: not part of closure object type")
  524. result = n
  525. proc getStateField*(g: ModuleGraph; owner: PSym): PSym =
  526. getHiddenParam(g, owner).typ.sons[0].n.sons[0].sym
  527. proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
  528. c: var LiftingPass): PNode
  529. proc symToClosure(n: PNode; owner: PSym; d: DetectionPass;
  530. c: var LiftingPass): PNode =
  531. let s = n.sym
  532. if s == owner:
  533. # recursive calls go through (lambda, hiddenParam):
  534. let available = getHiddenParam(d.graph, owner)
  535. result = makeClosure(d.graph, s, available.newSymNode, n.info)
  536. elif s.isIterator:
  537. result = closureCreationForIter(n, d, c)
  538. elif s.skipGenericOwner == owner:
  539. # direct dependency, so use the outer's env variable:
  540. result = makeClosure(d.graph, s, setupEnvVar(owner, d, c), n.info)
  541. else:
  542. let available = getHiddenParam(d.graph, owner)
  543. let wanted = getHiddenParam(d.graph, s).typ
  544. # ugh: call through some other inner proc;
  545. var access = newSymNode(available)
  546. while true:
  547. if access.typ == wanted:
  548. return makeClosure(d.graph, s, access, n.info)
  549. let obj = access.typ.sons[0]
  550. let upField = lookupInRecord(obj.n, getIdent(d.graph.cache, upName))
  551. if upField == nil:
  552. localError(d.graph.config, n.info, "internal error: no environment found")
  553. return n
  554. access = rawIndirectAccess(access, upField, n.info)
  555. proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
  556. c: var LiftingPass): PNode =
  557. result = n
  558. case n.kind
  559. of nkSym:
  560. let s = n.sym
  561. if isInnerProc(s):
  562. if not c.processed.containsOrIncl(s.id):
  563. #if s.name.s == "temp":
  564. # echo renderTree(s.getBody, {renderIds})
  565. let oldInContainer = c.inContainer
  566. c.inContainer = 0
  567. var body = transformBody(d.graph, s)
  568. body = liftCapturedVars(body, s, d, c)
  569. if c.envvars.getOrDefault(s.id).isNil:
  570. s.transformedBody = body
  571. else:
  572. s.transformedBody = newTree(nkStmtList, rawClosureCreation(s, d, c), body)
  573. c.inContainer = oldInContainer
  574. if s.typ.callConv == ccClosure:
  575. result = symToClosure(n, owner, d, c)
  576. elif s.id in d.capturedVars:
  577. if s.owner != owner:
  578. result = accessViaEnvParam(d.graph, n, owner)
  579. elif owner.isIterator and interestingIterVar(s):
  580. result = accessViaEnvParam(d.graph, n, owner)
  581. else:
  582. result = accessViaEnvVar(n, owner, d, c)
  583. of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit, nkComesFrom,
  584. nkTemplateDef, nkTypeSection, nkProcDef, nkMethodDef, nkConverterDef,
  585. nkMacroDef, nkFuncDef:
  586. discard
  587. of nkClosure:
  588. if n[1].kind == nkNilLit:
  589. n.sons[0] = liftCapturedVars(n[0], owner, d, c)
  590. let x = n.sons[0].skipConv
  591. if x.kind == nkClosure:
  592. #localError(n.info, "internal error: closure to closure created")
  593. # now we know better, so patch it:
  594. n.sons[0] = x.sons[0]
  595. n.sons[1] = x.sons[1]
  596. of nkLambdaKinds, nkIteratorDef:
  597. if n.typ != nil and n[namePos].kind == nkSym:
  598. let oldInContainer = c.inContainer
  599. c.inContainer = 0
  600. let m = newSymNode(n[namePos].sym)
  601. m.typ = n.typ
  602. result = liftCapturedVars(m, owner, d, c)
  603. c.inContainer = oldInContainer
  604. of nkHiddenStdConv:
  605. if n.len == 2:
  606. n.sons[1] = liftCapturedVars(n[1], owner, d, c)
  607. if n[1].kind == nkClosure: result = n[1]
  608. of nkReturnStmt:
  609. if n[0].kind in {nkAsgn, nkFastAsgn}:
  610. # we have a `result = result` expression produced by the closure
  611. # transform, let's not touch the LHS in order to make the lifting pass
  612. # correct when `result` is lifted
  613. n[0].sons[1] = liftCapturedVars(n[0].sons[1], owner, d, c)
  614. else: assert n[0].kind == nkEmpty
  615. else:
  616. if owner.isIterator:
  617. if nfLL in n.flags:
  618. # special case 'when nimVm' due to bug #3636:
  619. n.sons[1] = liftCapturedVars(n[1], owner, d, c)
  620. return
  621. let inContainer = n.kind in {nkObjConstr, nkBracket}
  622. if inContainer: inc c.inContainer
  623. for i in 0..<n.len:
  624. n.sons[i] = liftCapturedVars(n[i], owner, d, c)
  625. if inContainer: dec c.inContainer
  626. # ------------------ old stuff -------------------------------------------
  627. proc semCaptureSym*(s, owner: PSym) =
  628. discard """
  629. proc outer() =
  630. var x: int
  631. proc inner() =
  632. proc innerInner() =
  633. echo x
  634. innerInner()
  635. inner()
  636. # inner() takes a closure too!
  637. """
  638. proc propagateClosure(start, last: PSym) =
  639. var o = start
  640. while o != nil and o.kind != skModule:
  641. if o == last: break
  642. o.typ.callConv = ccClosure
  643. o = o.skipGenericOwner
  644. if interestingVar(s) and s.kind != skResult:
  645. if owner.typ != nil and not isGenericRoutine(owner):
  646. # XXX: is this really safe?
  647. # if we capture a var from another generic routine,
  648. # it won't be consider captured.
  649. var o = owner.skipGenericOwner
  650. while o != nil and o.kind != skModule:
  651. if s.owner == o:
  652. if owner.typ.callConv in {ccClosure, ccDefault} or owner.kind == skIterator:
  653. owner.typ.callConv = ccClosure
  654. propagateClosure(owner.skipGenericOwner, s.owner)
  655. else:
  656. discard "do not produce an error here, but later"
  657. #echo "computing .closure for ", owner.name.s, " because of ", s.name.s
  658. o = o.skipGenericOwner
  659. # since the analysis is not entirely correct, we don't set 'tfCapturesEnv'
  660. # here
  661. proc liftIterToProc*(g: ModuleGraph; fn: PSym; body: PNode; ptrType: PType): PNode =
  662. var d = initDetectionPass(g, fn)
  663. var c = initLiftingPass(fn)
  664. # pretend 'fn' is a closure iterator for the analysis:
  665. let oldKind = fn.kind
  666. let oldCC = fn.typ.callConv
  667. fn.kind = skIterator
  668. fn.typ.callConv = ccClosure
  669. d.ownerToType[fn.id] = ptrType
  670. detectCapturedVars(body, fn, d)
  671. result = liftCapturedVars(body, fn, d, c)
  672. fn.kind = oldKind
  673. fn.typ.callConv = oldCC
  674. proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool): PNode =
  675. # XXX gCmd == cmdCompileToJS does not suffice! The compiletime stuff needs
  676. # the transformation even when compiling to JS ...
  677. # However we can do lifting for the stuff which is *only* compiletime.
  678. let isCompileTime = sfCompileTime in fn.flags or fn.kind == skMacro
  679. if body.kind == nkEmpty or (
  680. g.config.cmd == cmdCompileToJS and not isCompileTime) or
  681. fn.skipGenericOwner.kind != skModule:
  682. # ignore forward declaration:
  683. result = body
  684. tooEarly = true
  685. else:
  686. var d = initDetectionPass(g, fn)
  687. detectCapturedVars(body, fn, d)
  688. if not d.somethingToDo and fn.isIterator:
  689. addClosureParam(d, fn, body.info)
  690. d.somethingToDo = true
  691. if d.somethingToDo:
  692. var c = initLiftingPass(fn)
  693. result = liftCapturedVars(body, fn, d, c)
  694. # echo renderTree(result, {renderIds})
  695. if c.envvars.getOrDefault(fn.id) != nil:
  696. result = newTree(nkStmtList, rawClosureCreation(fn, d, c), result)
  697. else:
  698. result = body
  699. #if fn.name.s == "get2":
  700. # echo "had something to do ", d.somethingToDo
  701. # echo renderTree(result, {renderIds})
  702. proc liftLambdasForTopLevel*(module: PSym, body: PNode): PNode =
  703. # XXX implement it properly
  704. result = body
  705. # ------------------- iterator transformation --------------------------------
  706. proc liftForLoop*(g: ModuleGraph; body: PNode; owner: PSym): PNode =
  707. # problem ahead: the iterator could be invoked indirectly, but then
  708. # we don't know what environment to create here:
  709. #
  710. # iterator count(): int =
  711. # yield 0
  712. #
  713. # iterator count2(): int =
  714. # var x = 3
  715. # yield x
  716. # inc x
  717. # yield x
  718. #
  719. # proc invoke(iter: iterator(): int) =
  720. # for x in iter(): echo x
  721. #
  722. # --> When to create the closure? --> for the (count) occurrence!
  723. discard """
  724. for i in foo(): ...
  725. Is transformed to:
  726. cl = createClosure()
  727. while true:
  728. let i = foo(cl)
  729. if (nkBreakState(cl.state)):
  730. break
  731. ...
  732. """
  733. if liftingHarmful(g.config, owner): return body
  734. var L = body.len
  735. if not (body.kind == nkForStmt and body[L-2].kind in nkCallKinds):
  736. localError(g.config, body.info, "ignored invalid for loop")
  737. return body
  738. var call = body[L-2]
  739. result = newNodeI(nkStmtList, body.info)
  740. # static binding?
  741. var env: PSym
  742. let op = call[0]
  743. if op.kind == nkSym and op.sym.isIterator:
  744. # createClosure()
  745. let iter = op.sym
  746. let hp = getHiddenParam(g, iter)
  747. env = newSym(skLet, iter.name, owner, body.info)
  748. env.typ = hp.typ
  749. env.flags = hp.flags
  750. var v = newNodeI(nkVarSection, body.info)
  751. addVar(v, newSymNode(env))
  752. result.add(v)
  753. # add 'new' statement:
  754. result.add(newCall(getSysSym(g, env.info, "internalNew"), env.newSymNode))
  755. elif op.kind == nkStmtListExpr:
  756. let closure = op.lastSon
  757. if closure.kind == nkClosure:
  758. call.sons[0] = closure
  759. for i in 0 .. op.len-2:
  760. result.add op[i]
  761. var loopBody = newNodeI(nkStmtList, body.info, 3)
  762. var whileLoop = newNodeI(nkWhileStmt, body.info, 2)
  763. whileLoop.sons[0] = newIntTypeNode(nkIntLit, 1, getSysType(g, body.info, tyBool))
  764. whileLoop.sons[1] = loopBody
  765. result.add whileLoop
  766. # setup loopBody:
  767. # gather vars in a tuple:
  768. var v2 = newNodeI(nkLetSection, body.info)
  769. var vpart = newNodeI(if L == 3: nkIdentDefs else: nkVarTuple, body.info)
  770. for i in 0 .. L-3:
  771. if body[i].kind == nkSym:
  772. body[i].sym.kind = skLet
  773. addSon(vpart, body[i])
  774. addSon(vpart, newNodeI(nkEmpty, body.info)) # no explicit type
  775. if not env.isNil:
  776. call.sons[0] = makeClosure(g, call.sons[0].sym, env.newSymNode, body.info)
  777. addSon(vpart, call)
  778. addSon(v2, vpart)
  779. loopBody.sons[0] = v2
  780. var bs = newNodeI(nkBreakState, body.info)
  781. bs.addSon(call.sons[0])
  782. let ibs = newNodeI(nkIfStmt, body.info)
  783. let elifBranch = newNodeI(nkElifBranch, body.info)
  784. elifBranch.add(bs)
  785. let br = newNodeI(nkBreakStmt, body.info)
  786. br.add(g.emptyNode)
  787. elifBranch.add(br)
  788. ibs.add(elifBranch)
  789. loopBody.sons[1] = ibs
  790. loopBody.sons[2] = body[L-1]