lambdalifting.nim 36 KB

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