lambdalifting.nim 37 KB

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