lambdalifting.nim 36 KB

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