lambdalifting.nim 35 KB

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