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