closureiters.nim 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2018 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This file implements closure iterator transformations.
  10. # The main idea is to split the closure iterator body to top level statements.
  11. # The body is split by yield statement.
  12. #
  13. # Example:
  14. # while a > 0:
  15. # echo "hi"
  16. # yield a
  17. # dec a
  18. #
  19. # Should be transformed to:
  20. # STATE0:
  21. # if a > 0:
  22. # echo "hi"
  23. # :state = 1 # Next state
  24. # return a # yield
  25. # else:
  26. # :state = 2 # Next state
  27. # break :stateLoop # Proceed to the next state
  28. # STATE1:
  29. # dec a
  30. # :state = 0 # Next state
  31. # break :stateLoop # Proceed to the next state
  32. # STATE2:
  33. # :state = -1 # End of execution
  34. # The transformation should play well with lambdalifting, however depending
  35. # on situation, it can be called either before or after lambdalifting
  36. # transformation. As such we behave slightly differently, when accessing
  37. # iterator state, or using temp variables. If lambdalifting did not happen,
  38. # we just create local variables, so that they will be lifted further on.
  39. # Otherwise, we utilize existing env, created by lambdalifting.
  40. # Lambdalifting treats :state variable specially, it should always end up
  41. # as the first field in env. Currently C codegen depends on this behavior.
  42. # One special subtransformation is nkStmtListExpr lowering.
  43. # Example:
  44. # template foo(): int =
  45. # yield 1
  46. # 2
  47. #
  48. # iterator it(): int {.closure.} =
  49. # if foo() == 2:
  50. # yield 3
  51. #
  52. # If a nkStmtListExpr has yield inside, it has first to be lowered to:
  53. # yield 1
  54. # :tmpSlLower = 2
  55. # if :tmpSlLower == 2:
  56. # yield 3
  57. # nkTryStmt Transformations:
  58. # If the iter has an nkTryStmt with a yield inside
  59. # - the closure iter is promoted to have exceptions (ctx.hasExceptions = true)
  60. # - exception table is created. This is a const array, where
  61. # `abs(exceptionTable[i])` is a state idx to which we should jump from state
  62. # `i` should exception be raised in state `i`. For all states in `try` block
  63. # the target state is `except` block. For all states in `except` block
  64. # the target state is `finally` block. For all other states there is no
  65. # target state (0, as the first block can never be neither except nor finally).
  66. # `exceptionTable[i]` is < 0 if `abs(exceptionTable[i])` is except block,
  67. # and > 0, for finally block.
  68. # - local variable :curExc is created
  69. # - the iter body is wrapped into a
  70. # try:
  71. # closureIterSetupExc(:curExc)
  72. # ...body...
  73. # catch:
  74. # :state = exceptionTable[:state]
  75. # if :state == 0: raise # No state that could handle exception
  76. # :unrollFinally = :state > 0 # Target state is finally
  77. # if :state < 0:
  78. # :state = -:state
  79. # :curExc = getCurrentException()
  80. #
  81. # nkReturnStmt within a try/except/finally now has to behave differently as we
  82. # want the nearest finally block to be executed before the return, thus it is
  83. # transformed to:
  84. # :tmpResult = returnValue (if return doesn't have a value, this is skipped)
  85. # :unrollFinally = true
  86. # goto nearestFinally (or -1 if not exists)
  87. #
  88. # Every finally block calls closureIterEndFinally() upon its successful
  89. # completion.
  90. #
  91. # Example:
  92. #
  93. # try:
  94. # yield 0
  95. # raise ...
  96. # except:
  97. # yield 1
  98. # return 3
  99. # finally:
  100. # yield 2
  101. #
  102. # Is transformed to (yields are left in place for example simplicity,
  103. # in reality the code is subdivided even more, as described above):
  104. #
  105. # STATE0: # Try
  106. # yield 0
  107. # raise ...
  108. # :state = 2 # What would happen should we not raise
  109. # break :stateLoop
  110. # STATE1: # Except
  111. # yield 1
  112. # :tmpResult = 3 # Return
  113. # :unrollFinally = true # Return
  114. # :state = 2 # Goto Finally
  115. # break :stateLoop
  116. # :state = 2 # What would happen should we not return
  117. # break :stateLoop
  118. # STATE2: # Finally
  119. # yield 2
  120. # if :unrollFinally: # This node is created by `newEndFinallyNode`
  121. # if :curExc.isNil:
  122. # return :tmpResult
  123. # else:
  124. # raise
  125. # state = -1 # Goto next state. In this case we just exit
  126. # break :stateLoop
  127. import
  128. intsets, strutils, options, ast, astalgo, trees, treetab, msgs, idents,
  129. renderer, types, magicsys, lowerings, lambdalifting, modulegraphs, lineinfos
  130. type
  131. Ctx = object
  132. g: ModuleGraph
  133. fn: PSym
  134. stateVarSym: PSym # :state variable. nil if env already introduced by lambdalifting
  135. tmpResultSym: PSym # Used when we return, but finally has to interfere
  136. unrollFinallySym: PSym # Indicates that we're unrolling finally states (either exception happened or premature return)
  137. curExcSym: PSym # Current exception
  138. states: seq[PNode] # The resulting states. Every state is an nkState node.
  139. blockLevel: int # Temp used to transform break and continue stmts
  140. stateLoopLabel: PSym # Label to break on, when jumping between states.
  141. exitStateIdx: int # index of the last state
  142. tempVarId: int # unique name counter
  143. tempVars: PNode # Temp var decls, nkVarSection
  144. exceptionTable: seq[int] # For state `i` jump to state `exceptionTable[i]` if exception is raised
  145. hasExceptions: bool # Does closure have yield in try?
  146. curExcHandlingState: int # Negative for except, positive for finally
  147. nearestFinally: int # Index of the nearest finally block. For try/except it
  148. # is their finally. For finally it is parent finally. Otherwise -1
  149. const
  150. nkSkip = { nkEmpty..nkNilLit, nkTemplateDef, nkTypeSection, nkStaticStmt,
  151. nkCommentStmt } + procDefs
  152. proc newStateAccess(ctx: var Ctx): PNode =
  153. if ctx.stateVarSym.isNil:
  154. result = rawIndirectAccess(newSymNode(getEnvParam(ctx.fn)),
  155. getStateField(ctx.g, ctx.fn), ctx.fn.info)
  156. else:
  157. result = newSymNode(ctx.stateVarSym)
  158. proc newStateAssgn(ctx: var Ctx, toValue: PNode): PNode =
  159. # Creates state assignment:
  160. # :state = toValue
  161. newTree(nkAsgn, ctx.newStateAccess(), toValue)
  162. proc newStateAssgn(ctx: var Ctx, stateNo: int = -2): PNode =
  163. # Creates state assignment:
  164. # :state = stateNo
  165. ctx.newStateAssgn(newIntTypeNode(nkIntLit, stateNo, ctx.g.getSysType(TLineInfo(), tyInt)))
  166. proc newEnvVar(ctx: var Ctx, name: string, typ: PType): PSym =
  167. result = newSym(skVar, getIdent(ctx.g.cache, name), ctx.fn, ctx.fn.info)
  168. result.typ = typ
  169. assert(not typ.isNil)
  170. if not ctx.stateVarSym.isNil:
  171. # We haven't gone through labmda lifting yet, so just create a local var,
  172. # it will be lifted later
  173. if ctx.tempVars.isNil:
  174. ctx.tempVars = newNodeI(nkVarSection, ctx.fn.info)
  175. addVar(ctx.tempVars, newSymNode(result))
  176. else:
  177. let envParam = getEnvParam(ctx.fn)
  178. # let obj = envParam.typ.lastSon
  179. result = addUniqueField(envParam.typ.lastSon, result, ctx.g.cache)
  180. proc newEnvVarAccess(ctx: Ctx, s: PSym): PNode =
  181. if ctx.stateVarSym.isNil:
  182. result = rawIndirectAccess(newSymNode(getEnvParam(ctx.fn)), s, ctx.fn.info)
  183. else:
  184. result = newSymNode(s)
  185. proc newTmpResultAccess(ctx: var Ctx): PNode =
  186. if ctx.tmpResultSym.isNil:
  187. ctx.tmpResultSym = ctx.newEnvVar(":tmpResult", ctx.fn.typ[0])
  188. ctx.newEnvVarAccess(ctx.tmpResultSym)
  189. proc newUnrollFinallyAccess(ctx: var Ctx, info: TLineInfo): PNode =
  190. if ctx.unrollFinallySym.isNil:
  191. ctx.unrollFinallySym = ctx.newEnvVar(":unrollFinally", ctx.g.getSysType(info, tyBool))
  192. ctx.newEnvVarAccess(ctx.unrollFinallySym)
  193. proc newCurExcAccess(ctx: var Ctx): PNode =
  194. if ctx.curExcSym.isNil:
  195. ctx.curExcSym = ctx.newEnvVar(":curExc", ctx.g.callCodegenProc("getCurrentException").typ)
  196. ctx.newEnvVarAccess(ctx.curExcSym)
  197. proc newState(ctx: var Ctx, n, gotoOut: PNode): int =
  198. # Creates a new state, adds it to the context fills out `gotoOut` so that it
  199. # will goto this state.
  200. # Returns index of the newly created state
  201. result = ctx.states.len
  202. let resLit = ctx.g.newIntLit(n.info, result)
  203. let s = newNodeI(nkState, n.info)
  204. s.add(resLit)
  205. s.add(n)
  206. ctx.states.add(s)
  207. ctx.exceptionTable.add(ctx.curExcHandlingState)
  208. if not gotoOut.isNil:
  209. assert(gotoOut.len == 0)
  210. gotoOut.add(ctx.g.newIntLit(gotoOut.info, result))
  211. proc toStmtList(n: PNode): PNode =
  212. result = n
  213. if result.kind notin {nkStmtList, nkStmtListExpr}:
  214. result = newNodeI(nkStmtList, n.info)
  215. result.add(n)
  216. proc addGotoOut(n: PNode, gotoOut: PNode): PNode =
  217. # Make sure `n` is a stmtlist, and ends with `gotoOut`
  218. result = toStmtList(n)
  219. if result.len == 0 or result.sons[^1].kind != nkGotoState:
  220. result.add(gotoOut)
  221. proc newTempVar(ctx: var Ctx, typ: PType): PSym =
  222. result = ctx.newEnvVar(":tmpSlLower" & $ctx.tempVarId, typ)
  223. inc ctx.tempVarId
  224. proc hasYields(n: PNode): bool =
  225. # TODO: This is very inefficient. It traverses the node, looking for nkYieldStmt.
  226. case n.kind
  227. of nkYieldStmt:
  228. result = true
  229. of nkSkip:
  230. discard
  231. else:
  232. for c in n:
  233. if c.hasYields:
  234. result = true
  235. break
  236. proc transformBreaksAndContinuesInWhile(ctx: var Ctx, n: PNode, before, after: PNode): PNode =
  237. result = n
  238. case n.kind
  239. of nkSkip:
  240. discard
  241. of nkWhileStmt: discard # Do not recurse into nested whiles
  242. of nkContinueStmt:
  243. result = before
  244. of nkBlockStmt:
  245. inc ctx.blockLevel
  246. result[1] = ctx.transformBreaksAndContinuesInWhile(result[1], before, after)
  247. dec ctx.blockLevel
  248. of nkBreakStmt:
  249. if ctx.blockLevel == 0:
  250. result = after
  251. else:
  252. for i in 0 ..< n.len:
  253. n[i] = ctx.transformBreaksAndContinuesInWhile(n[i], before, after)
  254. proc transformBreaksInBlock(ctx: var Ctx, n: PNode, label, after: PNode): PNode =
  255. result = n
  256. case n.kind
  257. of nkSkip:
  258. discard
  259. of nkBlockStmt, nkWhileStmt:
  260. inc ctx.blockLevel
  261. result[1] = ctx.transformBreaksInBlock(result[1], label, after)
  262. dec ctx.blockLevel
  263. of nkBreakStmt:
  264. if n[0].kind == nkEmpty:
  265. if ctx.blockLevel == 0:
  266. result = after
  267. else:
  268. if label.kind == nkSym and n[0].sym == label.sym:
  269. result = after
  270. else:
  271. for i in 0 ..< n.len:
  272. n[i] = ctx.transformBreaksInBlock(n[i], label, after)
  273. proc newNullifyCurExc(ctx: var Ctx, info: TLineInfo): PNode =
  274. # :curEcx = nil
  275. let curExc = ctx.newCurExcAccess()
  276. curExc.info = info
  277. let nilnode = newNode(nkNilLit)
  278. nilnode.typ = curExc.typ
  279. result = newTree(nkAsgn, curExc, nilnode)
  280. proc newOr(g: ModuleGraph, a, b: PNode): PNode {.inline.} =
  281. result = newTree(nkCall, newSymNode(g.getSysMagic(a.info, "or", mOr)), a, b)
  282. result.typ = g.getSysType(a.info, tyBool)
  283. result.info = a.info
  284. proc collectExceptState(ctx: var Ctx, n: PNode): PNode {.inline.} =
  285. var ifStmt = newNodeI(nkIfStmt, n.info)
  286. let g = ctx.g
  287. for c in n:
  288. if c.kind == nkExceptBranch:
  289. var ifBranch: PNode
  290. if c.len > 1:
  291. var cond: PNode
  292. for i in 0 .. c.len - 2:
  293. assert(c[i].kind == nkType)
  294. let nextCond = newTree(nkCall,
  295. newSymNode(g.getSysMagic(c.info, "of", mOf)),
  296. g.callCodegenProc("getCurrentException"),
  297. c[i])
  298. nextCond.typ = ctx.g.getSysType(c.info, tyBool)
  299. nextCond.info = c.info
  300. if cond.isNil:
  301. cond = nextCond
  302. else:
  303. cond = g.newOr(cond, nextCond)
  304. ifBranch = newNodeI(nkElifBranch, c.info)
  305. ifBranch.add(cond)
  306. else:
  307. if ifStmt.len == 0:
  308. ifStmt = newNodeI(nkStmtList, c.info)
  309. ifBranch = newNodeI(nkStmtList, c.info)
  310. else:
  311. ifBranch = newNodeI(nkElse, c.info)
  312. ifBranch.add(c[^1])
  313. ifStmt.add(ifBranch)
  314. if ifStmt.len != 0:
  315. result = newTree(nkStmtList, ctx.newNullifyCurExc(n.info), ifStmt)
  316. else:
  317. result = ctx.g.emptyNode
  318. proc addElseToExcept(ctx: var Ctx, n: PNode) =
  319. if n.kind == nkStmtList and n[1].kind == nkIfStmt and n[1][^1].kind != nkElse:
  320. # Not all cases are covered
  321. let branchBody = newNodeI(nkStmtList, n.info)
  322. block: # :unrollFinally = true
  323. branchBody.add(newTree(nkAsgn,
  324. ctx.newUnrollFinallyAccess(n.info),
  325. newIntTypeNode(nkIntLit, 1, ctx.g.getSysType(n.info, tyBool))))
  326. block: # :curExc = getCurrentException()
  327. branchBody.add(newTree(nkAsgn,
  328. ctx.newCurExcAccess(),
  329. ctx.g.callCodegenProc("getCurrentException")))
  330. block: # goto nearestFinally
  331. branchBody.add(newTree(nkGotoState, ctx.g.newIntLit(n.info, ctx.nearestFinally)))
  332. let elseBranch = newTree(nkElse, branchBody)
  333. n[1].add(elseBranch)
  334. proc getFinallyNode(ctx: var Ctx, n: PNode): PNode =
  335. result = n[^1]
  336. if result.kind == nkFinally:
  337. result = result[0]
  338. else:
  339. result = ctx.g.emptyNode
  340. proc hasYieldsInExpressions(n: PNode): bool =
  341. case n.kind
  342. of nkSkip:
  343. discard
  344. of nkStmtListExpr:
  345. if isEmptyType(n.typ):
  346. for c in n:
  347. if c.hasYieldsInExpressions:
  348. return true
  349. else:
  350. result = n.hasYields
  351. else:
  352. for c in n:
  353. if c.hasYieldsInExpressions:
  354. return true
  355. proc exprToStmtList(n: PNode): tuple[s, res: PNode] =
  356. assert(n.kind == nkStmtListExpr)
  357. result.s = newNodeI(nkStmtList, n.info)
  358. result.s.sons = @[]
  359. var n = n
  360. while n.kind == nkStmtListExpr:
  361. result.s.sons.add(n.sons)
  362. result.s.sons.setLen(result.s.sons.len - 1) # delete last son
  363. n = n[^1]
  364. result.res = n
  365. proc newEnvVarAsgn(ctx: Ctx, s: PSym, v: PNode): PNode =
  366. result = newTree(nkFastAsgn, ctx.newEnvVarAccess(s), v)
  367. result.info = v.info
  368. proc addExprAssgn(ctx: Ctx, output, input: PNode, sym: PSym) =
  369. if input.kind == nkStmtListExpr:
  370. let (st, res) = exprToStmtList(input)
  371. output.add(st)
  372. output.add(ctx.newEnvVarAsgn(sym, res))
  373. else:
  374. output.add(ctx.newEnvVarAsgn(sym, input))
  375. proc convertExprBodyToAsgn(ctx: Ctx, exprBody: PNode, res: PSym): PNode =
  376. result = newNodeI(nkStmtList, exprBody.info)
  377. ctx.addExprAssgn(result, exprBody, res)
  378. proc newNotCall(g: ModuleGraph; e: PNode): PNode =
  379. result = newTree(nkCall, newSymNode(g.getSysMagic(e.info, "not", mNot), e.info), e)
  380. result.typ = g.getSysType(e.info, tyBool)
  381. proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
  382. result = n
  383. case n.kind
  384. of nkSkip:
  385. discard
  386. of nkYieldStmt:
  387. var ns = false
  388. for i in 0 ..< n.len:
  389. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  390. if ns:
  391. result = newNodeI(nkStmtList, n.info)
  392. let (st, ex) = exprToStmtList(n[0])
  393. result.add(st)
  394. n[0] = ex
  395. result.add(n)
  396. needsSplit = true
  397. of nkPar, nkObjConstr, nkTupleConstr, nkBracket:
  398. var ns = false
  399. for i in 0 ..< n.len:
  400. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  401. if ns:
  402. needsSplit = true
  403. result = newNodeI(nkStmtListExpr, n.info)
  404. if n.typ.isNil: internalError(ctx.g.config, "lowerStmtListExprs: constr typ.isNil")
  405. result.typ = n.typ
  406. for i in 0 ..< n.len:
  407. case n[i].kind
  408. of nkExprColonExpr:
  409. if n[i][1].kind == nkStmtListExpr:
  410. let (st, ex) = exprToStmtList(n[i][1])
  411. result.add(st)
  412. n[i][1] = ex
  413. of nkStmtListExpr:
  414. let (st, ex) = exprToStmtList(n[i])
  415. result.add(st)
  416. n[i] = ex
  417. else: discard
  418. result.add(n)
  419. of nkIfStmt, nkIfExpr:
  420. var ns = false
  421. for i in 0 ..< n.len:
  422. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  423. if ns:
  424. needsSplit = true
  425. var tmp: PSym
  426. var s: PNode
  427. let isExpr = not isEmptyType(n.typ)
  428. if isExpr:
  429. tmp = ctx.newTempVar(n.typ)
  430. result = newNodeI(nkStmtListExpr, n.info)
  431. result.typ = n.typ
  432. else:
  433. result = newNodeI(nkStmtList, n.info)
  434. var curS = result
  435. for branch in n:
  436. case branch.kind
  437. of nkElseExpr, nkElse:
  438. if isExpr:
  439. let branchBody = newNodeI(nkStmtList, branch.info)
  440. ctx.addExprAssgn(branchBody, branch[0], tmp)
  441. let newBranch = newTree(nkElse, branchBody)
  442. curS.add(newBranch)
  443. else:
  444. curS.add(branch)
  445. of nkElifExpr, nkElifBranch:
  446. var newBranch: PNode
  447. if branch[0].kind == nkStmtListExpr:
  448. let (st, res) = exprToStmtList(branch[0])
  449. let elseBody = newTree(nkStmtList, st)
  450. newBranch = newTree(nkElifBranch, res, branch[1])
  451. let newIf = newTree(nkIfStmt, newBranch)
  452. elseBody.add(newIf)
  453. if curS.kind == nkIfStmt:
  454. let newElse = newNodeI(nkElse, branch.info)
  455. newElse.add(elseBody)
  456. curS.add(newElse)
  457. else:
  458. curS.add(elseBody)
  459. curS = newIf
  460. else:
  461. newBranch = branch
  462. if curS.kind == nkIfStmt:
  463. curS.add(newBranch)
  464. else:
  465. let newIf = newTree(nkIfStmt, newBranch)
  466. curS.add(newIf)
  467. curS = newIf
  468. if isExpr:
  469. let branchBody = newNodeI(nkStmtList, branch[1].info)
  470. ctx.addExprAssgn(branchBody, branch[1], tmp)
  471. newBranch[1] = branchBody
  472. else:
  473. internalError(ctx.g.config, "lowerStmtListExpr(nkIf): " & $branch.kind)
  474. if isExpr: result.add(ctx.newEnvVarAccess(tmp))
  475. of nkTryStmt:
  476. var ns = false
  477. for i in 0 ..< n.len:
  478. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  479. if ns:
  480. needsSplit = true
  481. let isExpr = not isEmptyType(n.typ)
  482. if isExpr:
  483. result = newNodeI(nkStmtListExpr, n.info)
  484. result.typ = n.typ
  485. let tmp = ctx.newTempVar(n.typ)
  486. n[0] = ctx.convertExprBodyToAsgn(n[0], tmp)
  487. for i in 1 ..< n.len:
  488. let branch = n[i]
  489. case branch.kind
  490. of nkExceptBranch:
  491. if branch[0].kind == nkType:
  492. branch[1] = ctx.convertExprBodyToAsgn(branch[1], tmp)
  493. else:
  494. branch[0] = ctx.convertExprBodyToAsgn(branch[0], tmp)
  495. of nkFinally:
  496. discard
  497. else:
  498. internalError(ctx.g.config, "lowerStmtListExpr(nkTryStmt): " & $branch.kind)
  499. result.add(n)
  500. result.add(ctx.newEnvVarAccess(tmp))
  501. of nkCaseStmt:
  502. var ns = false
  503. for i in 0 ..< n.len:
  504. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  505. if ns:
  506. needsSplit = true
  507. let isExpr = not isEmptyType(n.typ)
  508. if isExpr:
  509. let tmp = ctx.newTempVar(n.typ)
  510. result = newNodeI(nkStmtListExpr, n.info)
  511. result.typ = n.typ
  512. if n[0].kind == nkStmtListExpr:
  513. let (st, ex) = exprToStmtList(n[0])
  514. result.add(st)
  515. n[0] = ex
  516. for i in 1 ..< n.len:
  517. let branch = n[i]
  518. case branch.kind
  519. of nkOfBranch:
  520. branch[^1] = ctx.convertExprBodyToAsgn(branch[^1], tmp)
  521. of nkElse:
  522. branch[0] = ctx.convertExprBodyToAsgn(branch[0], tmp)
  523. else:
  524. internalError(ctx.g.config, "lowerStmtListExpr(nkCaseStmt): " & $branch.kind)
  525. result.add(n)
  526. result.add(ctx.newEnvVarAccess(tmp))
  527. of nkCallKinds:
  528. var ns = false
  529. for i in 0 ..< n.len:
  530. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  531. if ns:
  532. needsSplit = true
  533. let isExpr = not isEmptyType(n.typ)
  534. if isExpr:
  535. result = newNodeI(nkStmtListExpr, n.info)
  536. result.typ = n.typ
  537. else:
  538. result = newNodeI(nkStmtList, n.info)
  539. if n[0].kind == nkSym and n[0].sym.magic in {mAnd, mOr}: # `and`/`or` short cirquiting
  540. var cond = n[1]
  541. if cond.kind == nkStmtListExpr:
  542. let (st, ex) = exprToStmtList(cond)
  543. result.add(st)
  544. cond = ex
  545. let tmp = ctx.newTempVar(cond.typ)
  546. result.add(ctx.newEnvVarAsgn(tmp, cond))
  547. var check = ctx.newEnvVarAccess(tmp)
  548. if n[0].sym.magic == mOr:
  549. check = ctx.g.newNotCall(check)
  550. cond = n[2]
  551. let ifBody = newNodeI(nkStmtList, cond.info)
  552. if cond.kind == nkStmtListExpr:
  553. let (st, ex) = exprToStmtList(cond)
  554. ifBody.add(st)
  555. cond = ex
  556. ifBody.add(ctx.newEnvVarAsgn(tmp, cond))
  557. let ifBranch = newTree(nkElifBranch, check, ifBody)
  558. let ifNode = newTree(nkIfStmt, ifBranch)
  559. result.add(ifNode)
  560. result.add(ctx.newEnvVarAccess(tmp))
  561. else:
  562. for i in 0 ..< n.len:
  563. if n[i].kind == nkStmtListExpr:
  564. let (st, ex) = exprToStmtList(n[i])
  565. result.add(st)
  566. n[i] = ex
  567. if n[i].kind in nkCallKinds: # XXX: This should better be some sort of side effect tracking
  568. let tmp = ctx.newTempVar(n[i].typ)
  569. result.add(ctx.newEnvVarAsgn(tmp, n[i]))
  570. n[i] = ctx.newEnvVarAccess(tmp)
  571. result.add(n)
  572. of nkVarSection, nkLetSection:
  573. result = newNodeI(nkStmtList, n.info)
  574. for c in n:
  575. let varSect = newNodeI(n.kind, n.info)
  576. varSect.add(c)
  577. var ns = false
  578. c[^1] = ctx.lowerStmtListExprs(c[^1], ns)
  579. if ns:
  580. needsSplit = true
  581. let (st, ex) = exprToStmtList(c[^1])
  582. result.add(st)
  583. c[^1] = ex
  584. result.add(varSect)
  585. of nkDiscardStmt, nkReturnStmt, nkRaiseStmt:
  586. var ns = false
  587. for i in 0 ..< n.len:
  588. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  589. if ns:
  590. needsSplit = true
  591. result = newNodeI(nkStmtList, n.info)
  592. let (st, ex) = exprToStmtList(n[0])
  593. result.add(st)
  594. n[0] = ex
  595. result.add(n)
  596. of nkCast, nkHiddenStdConv, nkHiddenSubConv, nkConv, nkObjDownConv:
  597. var ns = false
  598. for i in 0 ..< n.len:
  599. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  600. if ns:
  601. needsSplit = true
  602. result = newNodeI(nkStmtListExpr, n.info)
  603. result.typ = n.typ
  604. let (st, ex) = exprToStmtList(n[^1])
  605. result.add(st)
  606. n[^1] = ex
  607. result.add(n)
  608. of nkAsgn, nkFastAsgn:
  609. var ns = false
  610. for i in 0 ..< n.len:
  611. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  612. if ns:
  613. needsSplit = true
  614. result = newNodeI(nkStmtList, n.info)
  615. if n[0].kind == nkStmtListExpr:
  616. let (st, ex) = exprToStmtList(n[0])
  617. result.add(st)
  618. n[0] = ex
  619. if n[1].kind == nkStmtListExpr:
  620. let (st, ex) = exprToStmtList(n[1])
  621. result.add(st)
  622. n[1] = ex
  623. result.add(n)
  624. of nkBracketExpr:
  625. var lhsNeedsSplit = false
  626. var rhsNeedsSplit = false
  627. n[0] = ctx.lowerStmtListExprs(n[0], lhsNeedsSplit)
  628. n[1] = ctx.lowerStmtListExprs(n[1], rhsNeedsSplit)
  629. if lhsNeedsSplit or rhsNeedsSplit:
  630. needsSplit = true
  631. result = newNodeI(nkStmtListExpr, n.info)
  632. if lhsNeedsSplit:
  633. let (st, ex) = exprToStmtList(n[0])
  634. result.add(st)
  635. n[0] = ex
  636. if rhsNeedsSplit:
  637. let (st, ex) = exprToStmtList(n[1])
  638. result.add(st)
  639. n[1] = ex
  640. result.add(n)
  641. of nkWhileStmt:
  642. var ns = false
  643. var condNeedsSplit = false
  644. n[0] = ctx.lowerStmtListExprs(n[0], condNeedsSplit)
  645. var bodyNeedsSplit = false
  646. n[1] = ctx.lowerStmtListExprs(n[1], bodyNeedsSplit)
  647. if condNeedsSplit or bodyNeedsSplit:
  648. needsSplit = true
  649. if condNeedsSplit:
  650. let (st, ex) = exprToStmtList(n[0])
  651. let brk = newTree(nkBreakStmt, ctx.g.emptyNode)
  652. let branch = newTree(nkElifBranch, ctx.g.newNotCall(ex), brk)
  653. let check = newTree(nkIfStmt, branch)
  654. let newBody = newTree(nkStmtList, st, check, n[1])
  655. n[0] = newSymNode(ctx.g.getSysSym(n[0].info, "true"))
  656. n[1] = newBody
  657. of nkDotExpr:
  658. var ns = false
  659. n[0] = ctx.lowerStmtListExprs(n[0], ns)
  660. if ns:
  661. needsSplit = true
  662. result = newNodeI(nkStmtListExpr, n.info)
  663. result.typ = n.typ
  664. let (st, ex) = exprToStmtList(n[0])
  665. result.add(st)
  666. n[0] = ex
  667. result.add(n)
  668. of nkBlockExpr:
  669. var ns = false
  670. n[1] = ctx.lowerStmtListExprs(n[1], ns)
  671. if ns:
  672. needsSplit = true
  673. result = newNodeI(nkStmtListExpr, n.info)
  674. result.typ = n.typ
  675. let (st, ex) = exprToStmtList(n[1])
  676. n.kind = nkBlockStmt
  677. n.typ = nil
  678. n[1] = st
  679. result.add(n)
  680. result.add(ex)
  681. else:
  682. for i in 0 ..< n.len:
  683. n[i] = ctx.lowerStmtListExprs(n[i], needsSplit)
  684. proc newEndFinallyNode(ctx: var Ctx, info: TLineInfo): PNode =
  685. # Generate the following code:
  686. # if :unrollFinally:
  687. # if :curExc.isNil:
  688. # return :tmpResult
  689. # else:
  690. # raise
  691. let curExc = ctx.newCurExcAccess()
  692. let nilnode = newNode(nkNilLit)
  693. nilnode.typ = curExc.typ
  694. let cmp = newTree(nkCall, newSymNode(ctx.g.getSysMagic(info, "==", mEqRef), info), curExc, nilnode)
  695. cmp.typ = ctx.g.getSysType(info, tyBool)
  696. let asgn = newTree(nkFastAsgn,
  697. newSymNode(getClosureIterResult(ctx.g, ctx.fn), info),
  698. ctx.newTmpResultAccess())
  699. let retStmt = newTree(nkReturnStmt, asgn)
  700. let branch = newTree(nkElifBranch, cmp, retStmt)
  701. # The C++ backend requires `getCurrentException` here.
  702. let raiseStmt = newTree(nkRaiseStmt, ctx.g.callCodegenProc("getCurrentException"))
  703. raiseStmt.info = info
  704. let elseBranch = newTree(nkElse, raiseStmt)
  705. let ifBody = newTree(nkIfStmt, branch, elseBranch)
  706. let elifBranch = newTree(nkElifBranch, ctx.newUnrollFinallyAccess(info), ifBody)
  707. elifBranch.info = info
  708. result = newTree(nkIfStmt, elifBranch)
  709. proc transformReturnsInTry(ctx: var Ctx, n: PNode): PNode =
  710. result = n
  711. # TODO: This is very inefficient. It traverses the node, looking for nkYieldStmt.
  712. case n.kind
  713. of nkReturnStmt:
  714. # We're somewhere in try, transform to finally unrolling
  715. assert(ctx.nearestFinally != 0)
  716. result = newNodeI(nkStmtList, n.info)
  717. block: # :unrollFinally = true
  718. let asgn = newNodeI(nkAsgn, n.info)
  719. asgn.add(ctx.newUnrollFinallyAccess(n.info))
  720. asgn.add(newIntTypeNode(nkIntLit, 1, ctx.g.getSysType(n.info, tyBool)))
  721. result.add(asgn)
  722. if n[0].kind != nkEmpty:
  723. let asgnTmpResult = newNodeI(nkAsgn, n.info)
  724. asgnTmpResult.add(ctx.newTmpResultAccess())
  725. asgnTmpResult.add(n[0])
  726. result.add(asgnTmpResult)
  727. result.add(ctx.newNullifyCurExc(n.info))
  728. let goto = newTree(nkGotoState, ctx.g.newIntLit(n.info, ctx.nearestFinally))
  729. result.add(goto)
  730. of nkSkip:
  731. discard
  732. else:
  733. for i in 0 ..< n.len:
  734. n[i] = ctx.transformReturnsInTry(n[i])
  735. proc transformClosureIteratorBody(ctx: var Ctx, n: PNode, gotoOut: PNode): PNode =
  736. result = n
  737. case n.kind:
  738. of nkSkip:
  739. discard
  740. of nkStmtList, nkStmtListExpr:
  741. result = addGotoOut(result, gotoOut)
  742. for i in 0 ..< n.len:
  743. if n[i].hasYields:
  744. # Create a new split
  745. let go = newNodeI(nkGotoState, n[i].info)
  746. n[i] = ctx.transformClosureIteratorBody(n[i], go)
  747. let s = newNodeI(nkStmtList, n[i + 1].info)
  748. for j in i + 1 ..< n.len:
  749. s.add(n[j])
  750. n.sons.setLen(i + 1)
  751. discard ctx.newState(s, go)
  752. if ctx.transformClosureIteratorBody(s, gotoOut) != s:
  753. internalError(ctx.g.config, "transformClosureIteratorBody != s")
  754. break
  755. of nkYieldStmt:
  756. result = newNodeI(nkStmtList, n.info)
  757. result.add(n)
  758. result.add(gotoOut)
  759. of nkElse, nkElseExpr:
  760. result[0] = addGotoOut(result[0], gotoOut)
  761. result[0] = ctx.transformClosureIteratorBody(result[0], gotoOut)
  762. of nkElifBranch, nkElifExpr, nkOfBranch:
  763. result[^1] = addGotoOut(result[^1], gotoOut)
  764. result[^1] = ctx.transformClosureIteratorBody(result[^1], gotoOut)
  765. of nkIfStmt, nkCaseStmt:
  766. for i in 0 ..< n.len:
  767. n[i] = ctx.transformClosureIteratorBody(n[i], gotoOut)
  768. if n[^1].kind != nkElse:
  769. # We don't have an else branch, but every possible branch has to end with
  770. # gotoOut, so add else here.
  771. let elseBranch = newTree(nkElse, gotoOut)
  772. n.add(elseBranch)
  773. of nkWhileStmt:
  774. # while e:
  775. # s
  776. # ->
  777. # BEGIN_STATE:
  778. # if e:
  779. # s
  780. # goto BEGIN_STATE
  781. # else:
  782. # goto OUT
  783. result = newNodeI(nkGotoState, n.info)
  784. let s = newNodeI(nkStmtList, n.info)
  785. discard ctx.newState(s, result)
  786. let ifNode = newNodeI(nkIfStmt, n.info)
  787. let elifBranch = newNodeI(nkElifBranch, n.info)
  788. elifBranch.add(n[0])
  789. var body = addGotoOut(n[1], result)
  790. body = ctx.transformBreaksAndContinuesInWhile(body, result, gotoOut)
  791. body = ctx.transformClosureIteratorBody(body, result)
  792. elifBranch.add(body)
  793. ifNode.add(elifBranch)
  794. let elseBranch = newTree(nkElse, gotoOut)
  795. ifNode.add(elseBranch)
  796. s.add(ifNode)
  797. of nkBlockStmt:
  798. result[1] = addGotoOut(result[1], gotoOut)
  799. result[1] = ctx.transformBreaksInBlock(result[1], result[0], gotoOut)
  800. result[1] = ctx.transformClosureIteratorBody(result[1], gotoOut)
  801. of nkTryStmt:
  802. # See explanation above about how this works
  803. ctx.hasExceptions = true
  804. result = newNodeI(nkGotoState, n.info)
  805. var tryBody = toStmtList(n[0])
  806. var exceptBody = ctx.collectExceptState(n)
  807. var finallyBody = newTree(nkStmtList, getFinallyNode(ctx, n))
  808. finallyBody = ctx.transformReturnsInTry(finallyBody)
  809. finallyBody.add(ctx.newEndFinallyNode(finallyBody.info))
  810. # The following index calculation is based on the knowledge how state
  811. # indexes are assigned
  812. let tryIdx = ctx.states.len
  813. var exceptIdx, finallyIdx: int
  814. if exceptBody.kind != nkEmpty:
  815. exceptIdx = -(tryIdx + 1)
  816. finallyIdx = tryIdx + 2
  817. else:
  818. exceptIdx = tryIdx + 1
  819. finallyIdx = tryIdx + 1
  820. let outToFinally = newNodeI(nkGotoState, finallyBody.info)
  821. block: # Create initial states.
  822. let oldExcHandlingState = ctx.curExcHandlingState
  823. ctx.curExcHandlingState = exceptIdx
  824. let realTryIdx = ctx.newState(tryBody, result)
  825. assert(realTryIdx == tryIdx)
  826. if exceptBody.kind != nkEmpty:
  827. ctx.curExcHandlingState = finallyIdx
  828. let realExceptIdx = ctx.newState(exceptBody, nil)
  829. assert(realExceptIdx == -exceptIdx)
  830. ctx.curExcHandlingState = oldExcHandlingState
  831. let realFinallyIdx = ctx.newState(finallyBody, outToFinally)
  832. assert(realFinallyIdx == finallyIdx)
  833. block: # Subdivide the states
  834. let oldNearestFinally = ctx.nearestFinally
  835. ctx.nearestFinally = finallyIdx
  836. let oldExcHandlingState = ctx.curExcHandlingState
  837. ctx.curExcHandlingState = exceptIdx
  838. if ctx.transformReturnsInTry(tryBody) != tryBody:
  839. internalError(ctx.g.config, "transformReturnsInTry != tryBody")
  840. if ctx.transformClosureIteratorBody(tryBody, outToFinally) != tryBody:
  841. internalError(ctx.g.config, "transformClosureIteratorBody != tryBody")
  842. ctx.curExcHandlingState = finallyIdx
  843. ctx.addElseToExcept(exceptBody)
  844. if ctx.transformReturnsInTry(exceptBody) != exceptBody:
  845. internalError(ctx.g.config, "transformReturnsInTry != exceptBody")
  846. if ctx.transformClosureIteratorBody(exceptBody, outToFinally) != exceptBody:
  847. internalError(ctx.g.config, "transformClosureIteratorBody != exceptBody")
  848. ctx.curExcHandlingState = oldExcHandlingState
  849. ctx.nearestFinally = oldNearestFinally
  850. if ctx.transformClosureIteratorBody(finallyBody, gotoOut) != finallyBody:
  851. internalError(ctx.g.config, "transformClosureIteratorBody != finallyBody")
  852. of nkGotoState, nkForStmt:
  853. internalError(ctx.g.config, "closure iter " & $n.kind)
  854. else:
  855. for i in 0 ..< n.len:
  856. n[i] = ctx.transformClosureIteratorBody(n[i], gotoOut)
  857. proc stateFromGotoState(n: PNode): int =
  858. assert(n.kind == nkGotoState)
  859. result = n[0].intVal.int
  860. proc transformStateAssignments(ctx: var Ctx, n: PNode): PNode =
  861. # This transforms 3 patterns:
  862. ########################## 1
  863. # yield e
  864. # goto STATE
  865. # ->
  866. # :state = STATE
  867. # return e
  868. ########################## 2
  869. # goto STATE
  870. # ->
  871. # :state = STATE
  872. # break :stateLoop
  873. ########################## 3
  874. # return e
  875. # ->
  876. # :state = -1
  877. # return e
  878. #
  879. result = n
  880. case n.kind
  881. of nkStmtList, nkStmtListExpr:
  882. if n.len != 0 and n[0].kind == nkYieldStmt:
  883. assert(n.len == 2)
  884. assert(n[1].kind == nkGotoState)
  885. result = newNodeI(nkStmtList, n.info)
  886. result.add(ctx.newStateAssgn(stateFromGotoState(n[1])))
  887. var retStmt = newNodeI(nkReturnStmt, n.info)
  888. if n[0].sons[0].kind != nkEmpty:
  889. var a = newNodeI(nkAsgn, n[0].sons[0].info)
  890. var retVal = n[0].sons[0] #liftCapturedVars(n.sons[0], owner, d, c)
  891. addSon(a, newSymNode(getClosureIterResult(ctx.g, ctx.fn)))
  892. addSon(a, retVal)
  893. retStmt.add(a)
  894. else:
  895. retStmt.add(ctx.g.emptyNode)
  896. result.add(retStmt)
  897. else:
  898. for i in 0 ..< n.len:
  899. n[i] = ctx.transformStateAssignments(n[i])
  900. of nkSkip:
  901. discard
  902. of nkReturnStmt:
  903. result = newNodeI(nkStmtList, n.info)
  904. result.add(ctx.newStateAssgn(-1))
  905. result.add(n)
  906. of nkGotoState:
  907. result = newNodeI(nkStmtList, n.info)
  908. result.add(ctx.newStateAssgn(stateFromGotoState(n)))
  909. let breakState = newNodeI(nkBreakStmt, n.info)
  910. breakState.add(newSymNode(ctx.stateLoopLabel))
  911. result.add(breakState)
  912. else:
  913. for i in 0 ..< n.len:
  914. n[i] = ctx.transformStateAssignments(n[i])
  915. proc skipStmtList(ctx: Ctx; n: PNode): PNode =
  916. result = n
  917. while result.kind in {nkStmtList}:
  918. if result.len == 0: return ctx.g.emptyNode
  919. result = result[0]
  920. proc skipEmptyStates(ctx: Ctx, stateIdx: int): int =
  921. # Returns first non-empty state idx for `stateIdx`. Returns `stateIdx` if
  922. # it is not empty
  923. var maxJumps = ctx.states.len # maxJumps used only for debugging purposes.
  924. var stateIdx = stateIdx
  925. while true:
  926. let label = stateIdx
  927. if label == ctx.exitStateIdx: break
  928. var newLabel = label
  929. if label == -1:
  930. newLabel = ctx.exitStateIdx
  931. else:
  932. let fs = skipStmtList(ctx, ctx.states[label][1])
  933. if fs.kind == nkGotoState:
  934. newLabel = fs[0].intVal.int
  935. if label == newLabel: break
  936. stateIdx = newLabel
  937. dec maxJumps
  938. if maxJumps == 0:
  939. assert(false, "Internal error")
  940. result = ctx.states[stateIdx][0].intVal.int
  941. proc skipThroughEmptyStates(ctx: var Ctx, n: PNode): PNode =
  942. result = n
  943. case n.kind
  944. of nkSkip:
  945. discard
  946. of nkGotoState:
  947. result = copyTree(n)
  948. result[0].intVal = ctx.skipEmptyStates(result[0].intVal.int)
  949. else:
  950. for i in 0 ..< n.len:
  951. n[i] = ctx.skipThroughEmptyStates(n[i])
  952. proc newArrayType(g: ModuleGraph; n: int, t: PType, owner: PSym): PType =
  953. result = newType(tyArray, owner)
  954. let rng = newType(tyRange, owner)
  955. rng.n = newTree(nkRange, g.newIntLit(owner.info, 0), g.newIntLit(owner.info, n))
  956. rng.rawAddSon(t)
  957. result.rawAddSon(rng)
  958. result.rawAddSon(t)
  959. proc createExceptionTable(ctx: var Ctx): PNode {.inline.} =
  960. result = newNodeI(nkBracket, ctx.fn.info)
  961. result.typ = ctx.g.newArrayType(ctx.exceptionTable.len, ctx.g.getSysType(ctx.fn.info, tyInt16), ctx.fn)
  962. for i in ctx.exceptionTable:
  963. let elem = newIntNode(nkIntLit, i)
  964. elem.typ = ctx.g.getSysType(ctx.fn.info, tyInt16)
  965. result.add(elem)
  966. proc newCatchBody(ctx: var Ctx, info: TLineInfo): PNode {.inline.} =
  967. # Generates the code:
  968. # :state = exceptionTable[:state]
  969. # if :state == 0: raise
  970. # :unrollFinally = :state > 0
  971. # if :state < 0:
  972. # :state = -:state
  973. # :curExc = getCurrentException()
  974. result = newNodeI(nkStmtList, info)
  975. let intTyp = ctx.g.getSysType(info, tyInt)
  976. let boolTyp = ctx.g.getSysType(info, tyBool)
  977. # :state = exceptionTable[:state]
  978. block:
  979. # exceptionTable[:state]
  980. let getNextState = newTree(nkBracketExpr,
  981. ctx.createExceptionTable(),
  982. ctx.newStateAccess())
  983. getNextState.typ = intTyp
  984. # :state = exceptionTable[:state]
  985. result.add(ctx.newStateAssgn(getNextState))
  986. # if :state == 0: raise
  987. block:
  988. let cond = newTree(nkCall,
  989. ctx.g.getSysMagic(info, "==", mEqI).newSymNode(),
  990. ctx.newStateAccess(),
  991. newIntTypeNode(nkIntLit, 0, intTyp))
  992. cond.typ = boolTyp
  993. let raiseStmt = newTree(nkRaiseStmt, ctx.g.emptyNode)
  994. let ifBranch = newTree(nkElifBranch, cond, raiseStmt)
  995. let ifStmt = newTree(nkIfStmt, ifBranch)
  996. result.add(ifStmt)
  997. # :unrollFinally = :state > 0
  998. block:
  999. let cond = newTree(nkCall,
  1000. ctx.g.getSysMagic(info, "<", mLtI).newSymNode,
  1001. newIntTypeNode(nkIntLit, 0, intTyp),
  1002. ctx.newStateAccess())
  1003. cond.typ = boolTyp
  1004. let asgn = newTree(nkAsgn, ctx.newUnrollFinallyAccess(info), cond)
  1005. result.add(asgn)
  1006. # if :state < 0: :state = -:state
  1007. block:
  1008. let cond = newTree(nkCall,
  1009. ctx.g.getSysMagic(info, "<", mLtI).newSymNode,
  1010. ctx.newStateAccess(),
  1011. newIntTypeNode(nkIntLit, 0, intTyp))
  1012. cond.typ = boolTyp
  1013. let negateState = newTree(nkCall,
  1014. ctx.g.getSysMagic(info, "-", mUnaryMinusI).newSymNode,
  1015. ctx.newStateAccess())
  1016. negateState.typ = intTyp
  1017. let ifBranch = newTree(nkElifBranch, cond, ctx.newStateAssgn(negateState))
  1018. let ifStmt = newTree(nkIfStmt, ifBranch)
  1019. result.add(ifStmt)
  1020. # :curExc = getCurrentException()
  1021. block:
  1022. result.add(newTree(nkAsgn,
  1023. ctx.newCurExcAccess(),
  1024. ctx.g.callCodegenProc("getCurrentException")))
  1025. proc wrapIntoTryExcept(ctx: var Ctx, n: PNode): PNode {.inline.} =
  1026. let setupExc = newTree(nkCall,
  1027. newSymNode(ctx.g.getCompilerProc("closureIterSetupExc")),
  1028. ctx.newCurExcAccess())
  1029. let tryBody = newTree(nkStmtList, setupExc, n)
  1030. let exceptBranch = newTree(nkExceptBranch, ctx.newCatchBody(ctx.fn.info))
  1031. result = newTree(nkTryStmt, tryBody, exceptBranch)
  1032. proc wrapIntoStateLoop(ctx: var Ctx, n: PNode): PNode =
  1033. # while true:
  1034. # block :stateLoop:
  1035. # gotoState :state
  1036. # local vars decl (if needed)
  1037. # body # Might get wrapped in try-except
  1038. let loopBody = newNodeI(nkStmtList, n.info)
  1039. result = newTree(nkWhileStmt, newSymNode(ctx.g.getSysSym(n.info, "true")), loopBody)
  1040. result.info = n.info
  1041. let localVars = newNodeI(nkStmtList, n.info)
  1042. if not ctx.stateVarSym.isNil:
  1043. let varSect = newNodeI(nkVarSection, n.info)
  1044. addVar(varSect, newSymNode(ctx.stateVarSym))
  1045. localVars.add(varSect)
  1046. if not ctx.tempVars.isNil:
  1047. localVars.add(ctx.tempVars)
  1048. let blockStmt = newNodeI(nkBlockStmt, n.info)
  1049. blockStmt.add(newSymNode(ctx.stateLoopLabel))
  1050. let gs = newNodeI(nkGotoState, n.info)
  1051. gs.add(ctx.newStateAccess())
  1052. gs.add(ctx.g.newIntLit(n.info, ctx.states.len - 1))
  1053. var blockBody = newTree(nkStmtList, gs, localVars, n)
  1054. if ctx.hasExceptions:
  1055. blockBody = ctx.wrapIntoTryExcept(blockBody)
  1056. blockStmt.add(blockBody)
  1057. loopBody.add(blockStmt)
  1058. proc deleteEmptyStates(ctx: var Ctx) =
  1059. let goOut = newTree(nkGotoState, ctx.g.newIntLit(TLineInfo(), -1))
  1060. ctx.exitStateIdx = ctx.newState(goOut, nil)
  1061. # Apply new state indexes and mark unused states with -1
  1062. var iValid = 0
  1063. for i, s in ctx.states:
  1064. let body = skipStmtList(ctx, s[1])
  1065. if body.kind == nkGotoState and i != ctx.states.len - 1 and i != 0:
  1066. # This is an empty state. Mark with -1.
  1067. s[0].intVal = -1
  1068. else:
  1069. s[0].intVal = iValid
  1070. inc iValid
  1071. for i, s in ctx.states:
  1072. let body = skipStmtList(ctx, s[1])
  1073. if body.kind != nkGotoState or i == 0:
  1074. discard ctx.skipThroughEmptyStates(s)
  1075. let excHandlState = ctx.exceptionTable[i]
  1076. if excHandlState < 0:
  1077. ctx.exceptionTable[i] = -ctx.skipEmptyStates(-excHandlState)
  1078. elif excHandlState != 0:
  1079. ctx.exceptionTable[i] = ctx.skipEmptyStates(excHandlState)
  1080. var i = 0
  1081. while i < ctx.states.len - 1:
  1082. let fs = skipStmtList(ctx, ctx.states[i][1])
  1083. if fs.kind == nkGotoState and i != 0:
  1084. ctx.states.delete(i)
  1085. ctx.exceptionTable.delete(i)
  1086. else:
  1087. inc i
  1088. proc transformClosureIterator*(g: ModuleGraph; fn: PSym, n: PNode): PNode =
  1089. var ctx: Ctx
  1090. ctx.g = g
  1091. ctx.fn = fn
  1092. if getEnvParam(fn).isNil:
  1093. # Lambda lifting was not done yet. Use temporary :state sym, which
  1094. # be handled specially by lambda lifting. Local temp vars (if needed)
  1095. # should folllow the same logic.
  1096. ctx.stateVarSym = newSym(skVar, getIdent(ctx.g.cache, ":state"), fn, fn.info)
  1097. ctx.stateVarSym.typ = g.createClosureIterStateType(fn)
  1098. ctx.stateLoopLabel = newSym(skLabel, getIdent(ctx.g.cache, ":stateLoop"), fn, fn.info)
  1099. var n = n.toStmtList
  1100. discard ctx.newState(n, nil)
  1101. let gotoOut = newTree(nkGotoState, g.newIntLit(n.info, -1))
  1102. var ns = false
  1103. n = ctx.lowerStmtListExprs(n, ns)
  1104. if n.hasYieldsInExpressions():
  1105. internalError(ctx.g.config, "yield in expr not lowered")
  1106. # Splitting transformation
  1107. discard ctx.transformClosureIteratorBody(n, gotoOut)
  1108. # Optimize empty states away
  1109. ctx.deleteEmptyStates()
  1110. # Make new body by concating the list of states
  1111. result = newNodeI(nkStmtList, n.info)
  1112. for s in ctx.states:
  1113. assert(s.len == 2)
  1114. let body = s[1]
  1115. s.sons.del(1)
  1116. result.add(s)
  1117. result.add(body)
  1118. result = ctx.transformStateAssignments(result)
  1119. result = ctx.wrapIntoStateLoop(result)
  1120. # echo "TRANSFORM TO STATES: "
  1121. # echo renderTree(result)
  1122. # echo "exception table:"
  1123. # for i, e in ctx.exceptionTable:
  1124. # echo i, " -> ", e