closureiters.nim 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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. if n[i].kind == nkStmtListExpr:
  408. let (st, ex) = exprToStmtList(n[i])
  409. result.add(st)
  410. n[i] = ex
  411. result.add(n)
  412. of nkIfStmt, nkIfExpr:
  413. var ns = false
  414. for i in 0 ..< n.len:
  415. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  416. if ns:
  417. needsSplit = true
  418. var tmp: PSym
  419. var s: PNode
  420. let isExpr = not isEmptyType(n.typ)
  421. if isExpr:
  422. tmp = ctx.newTempVar(n.typ)
  423. result = newNodeI(nkStmtListExpr, n.info)
  424. result.typ = n.typ
  425. else:
  426. result = newNodeI(nkStmtList, n.info)
  427. var curS = result
  428. for branch in n:
  429. case branch.kind
  430. of nkElseExpr, nkElse:
  431. if isExpr:
  432. let branchBody = newNodeI(nkStmtList, branch.info)
  433. ctx.addExprAssgn(branchBody, branch[0], tmp)
  434. let newBranch = newTree(nkElse, branchBody)
  435. curS.add(newBranch)
  436. else:
  437. curS.add(branch)
  438. of nkElifExpr, nkElifBranch:
  439. var newBranch: PNode
  440. if branch[0].kind == nkStmtListExpr:
  441. let (st, res) = exprToStmtList(branch[0])
  442. let elseBody = newTree(nkStmtList, st)
  443. newBranch = newTree(nkElifBranch, res, branch[1])
  444. let newIf = newTree(nkIfStmt, newBranch)
  445. elseBody.add(newIf)
  446. if curS.kind == nkIfStmt:
  447. let newElse = newNodeI(nkElse, branch.info)
  448. newElse.add(elseBody)
  449. curS.add(newElse)
  450. else:
  451. curS.add(elseBody)
  452. curS = newIf
  453. else:
  454. newBranch = branch
  455. if curS.kind == nkIfStmt:
  456. curS.add(newBranch)
  457. else:
  458. let newIf = newTree(nkIfStmt, newBranch)
  459. curS.add(newIf)
  460. curS = newIf
  461. if isExpr:
  462. let branchBody = newNodeI(nkStmtList, branch[1].info)
  463. ctx.addExprAssgn(branchBody, branch[1], tmp)
  464. newBranch[1] = branchBody
  465. else:
  466. internalError(ctx.g.config, "lowerStmtListExpr(nkIf): " & $branch.kind)
  467. if isExpr: result.add(ctx.newEnvVarAccess(tmp))
  468. of nkTryStmt:
  469. var ns = false
  470. for i in 0 ..< n.len:
  471. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  472. if ns:
  473. needsSplit = true
  474. let isExpr = not isEmptyType(n.typ)
  475. if isExpr:
  476. result = newNodeI(nkStmtListExpr, n.info)
  477. result.typ = n.typ
  478. let tmp = ctx.newTempVar(n.typ)
  479. n[0] = ctx.convertExprBodyToAsgn(n[0], tmp)
  480. for i in 1 ..< n.len:
  481. let branch = n[i]
  482. case branch.kind
  483. of nkExceptBranch:
  484. if branch[0].kind == nkType:
  485. branch[1] = ctx.convertExprBodyToAsgn(branch[1], tmp)
  486. else:
  487. branch[0] = ctx.convertExprBodyToAsgn(branch[0], tmp)
  488. of nkFinally:
  489. discard
  490. else:
  491. internalError(ctx.g.config, "lowerStmtListExpr(nkTryStmt): " & $branch.kind)
  492. result.add(n)
  493. result.add(ctx.newEnvVarAccess(tmp))
  494. of nkCaseStmt:
  495. var ns = false
  496. for i in 0 ..< n.len:
  497. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  498. if ns:
  499. needsSplit = true
  500. let isExpr = not isEmptyType(n.typ)
  501. if isExpr:
  502. let tmp = ctx.newTempVar(n.typ)
  503. result = newNodeI(nkStmtListExpr, n.info)
  504. result.typ = n.typ
  505. if n[0].kind == nkStmtListExpr:
  506. let (st, ex) = exprToStmtList(n[0])
  507. result.add(st)
  508. n[0] = ex
  509. for i in 1 ..< n.len:
  510. let branch = n[i]
  511. case branch.kind
  512. of nkOfBranch:
  513. branch[^1] = ctx.convertExprBodyToAsgn(branch[^1], tmp)
  514. of nkElse:
  515. branch[0] = ctx.convertExprBodyToAsgn(branch[0], tmp)
  516. else:
  517. internalError(ctx.g.config, "lowerStmtListExpr(nkCaseStmt): " & $branch.kind)
  518. result.add(n)
  519. result.add(ctx.newEnvVarAccess(tmp))
  520. of nkCallKinds:
  521. var ns = false
  522. for i in 0 ..< n.len:
  523. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  524. if ns:
  525. needsSplit = true
  526. let isExpr = not isEmptyType(n.typ)
  527. if isExpr:
  528. result = newNodeI(nkStmtListExpr, n.info)
  529. result.typ = n.typ
  530. else:
  531. result = newNodeI(nkStmtList, n.info)
  532. if n[0].kind == nkSym and n[0].sym.magic in {mAnd, mOr}: # `and`/`or` short cirquiting
  533. var cond = n[1]
  534. if cond.kind == nkStmtListExpr:
  535. let (st, ex) = exprToStmtList(cond)
  536. result.add(st)
  537. cond = ex
  538. let tmp = ctx.newTempVar(cond.typ)
  539. result.add(ctx.newEnvVarAsgn(tmp, cond))
  540. var check = ctx.newEnvVarAccess(tmp)
  541. if n[0].sym.magic == mOr:
  542. check = ctx.g.newNotCall(check)
  543. cond = n[2]
  544. let ifBody = newNodeI(nkStmtList, cond.info)
  545. if cond.kind == nkStmtListExpr:
  546. let (st, ex) = exprToStmtList(cond)
  547. ifBody.add(st)
  548. cond = ex
  549. ifBody.add(ctx.newEnvVarAsgn(tmp, cond))
  550. let ifBranch = newTree(nkElifBranch, check, ifBody)
  551. let ifNode = newTree(nkIfStmt, ifBranch)
  552. result.add(ifNode)
  553. result.add(ctx.newEnvVarAccess(tmp))
  554. else:
  555. for i in 0 ..< n.len:
  556. if n[i].kind == nkStmtListExpr:
  557. let (st, ex) = exprToStmtList(n[i])
  558. result.add(st)
  559. n[i] = ex
  560. if n[i].kind in nkCallKinds: # XXX: This should better be some sort of side effect tracking
  561. let tmp = ctx.newTempVar(n[i].typ)
  562. result.add(ctx.newEnvVarAsgn(tmp, n[i]))
  563. n[i] = ctx.newEnvVarAccess(tmp)
  564. result.add(n)
  565. of nkVarSection, nkLetSection:
  566. result = newNodeI(nkStmtList, n.info)
  567. for c in n:
  568. let varSect = newNodeI(n.kind, n.info)
  569. varSect.add(c)
  570. var ns = false
  571. c[^1] = ctx.lowerStmtListExprs(c[^1], ns)
  572. if ns:
  573. needsSplit = true
  574. let (st, ex) = exprToStmtList(c[^1])
  575. result.add(st)
  576. c[^1] = ex
  577. result.add(varSect)
  578. of nkDiscardStmt, nkReturnStmt, nkRaiseStmt:
  579. var ns = false
  580. for i in 0 ..< n.len:
  581. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  582. if ns:
  583. needsSplit = true
  584. result = newNodeI(nkStmtList, n.info)
  585. let (st, ex) = exprToStmtList(n[0])
  586. result.add(st)
  587. n[0] = ex
  588. result.add(n)
  589. of nkCast, nkHiddenStdConv, nkHiddenSubConv, nkConv, nkObjDownConv:
  590. var ns = false
  591. for i in 0 ..< n.len:
  592. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  593. if ns:
  594. needsSplit = true
  595. result = newNodeI(nkStmtListExpr, n.info)
  596. result.typ = n.typ
  597. let (st, ex) = exprToStmtList(n[^1])
  598. result.add(st)
  599. n[^1] = ex
  600. result.add(n)
  601. of nkAsgn, nkFastAsgn:
  602. var ns = false
  603. for i in 0 ..< n.len:
  604. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  605. if ns:
  606. needsSplit = true
  607. result = newNodeI(nkStmtList, n.info)
  608. if n[0].kind == nkStmtListExpr:
  609. let (st, ex) = exprToStmtList(n[0])
  610. result.add(st)
  611. n[0] = ex
  612. if n[1].kind == nkStmtListExpr:
  613. let (st, ex) = exprToStmtList(n[1])
  614. result.add(st)
  615. n[1] = ex
  616. result.add(n)
  617. of nkBracketExpr:
  618. var lhsNeedsSplit = false
  619. var rhsNeedsSplit = false
  620. n[0] = ctx.lowerStmtListExprs(n[0], lhsNeedsSplit)
  621. n[1] = ctx.lowerStmtListExprs(n[1], rhsNeedsSplit)
  622. if lhsNeedsSplit or rhsNeedsSplit:
  623. needsSplit = true
  624. result = newNodeI(nkStmtListExpr, n.info)
  625. if lhsNeedsSplit:
  626. let (st, ex) = exprToStmtList(n[0])
  627. result.add(st)
  628. n[0] = ex
  629. if rhsNeedsSplit:
  630. let (st, ex) = exprToStmtList(n[1])
  631. result.add(st)
  632. n[1] = ex
  633. result.add(n)
  634. of nkWhileStmt:
  635. var ns = false
  636. var condNeedsSplit = false
  637. n[0] = ctx.lowerStmtListExprs(n[0], condNeedsSplit)
  638. var bodyNeedsSplit = false
  639. n[1] = ctx.lowerStmtListExprs(n[1], bodyNeedsSplit)
  640. if condNeedsSplit or bodyNeedsSplit:
  641. needsSplit = true
  642. if condNeedsSplit:
  643. let (st, ex) = exprToStmtList(n[0])
  644. let brk = newTree(nkBreakStmt, ctx.g.emptyNode)
  645. let branch = newTree(nkElifBranch, ctx.g.newNotCall(ex), brk)
  646. let check = newTree(nkIfStmt, branch)
  647. let newBody = newTree(nkStmtList, st, check, n[1])
  648. n[0] = newSymNode(ctx.g.getSysSym(n[0].info, "true"))
  649. n[1] = newBody
  650. of nkDotExpr:
  651. var ns = false
  652. n[0] = ctx.lowerStmtListExprs(n[0], ns)
  653. if ns:
  654. needsSplit = true
  655. result = newNodeI(nkStmtListExpr, n.info)
  656. result.typ = n.typ
  657. let (st, ex) = exprToStmtList(n[0])
  658. result.add(st)
  659. n[0] = ex
  660. result.add(n)
  661. of nkBlockExpr:
  662. var ns = false
  663. n[1] = ctx.lowerStmtListExprs(n[1], ns)
  664. if ns:
  665. needsSplit = true
  666. result = newNodeI(nkStmtListExpr, n.info)
  667. result.typ = n.typ
  668. let (st, ex) = exprToStmtList(n[1])
  669. n.kind = nkBlockStmt
  670. n.typ = nil
  671. n[1] = st
  672. result.add(n)
  673. result.add(ex)
  674. else:
  675. for i in 0 ..< n.len:
  676. n[i] = ctx.lowerStmtListExprs(n[i], needsSplit)
  677. proc newEndFinallyNode(ctx: var Ctx, info: TLineInfo): PNode =
  678. # Generate the following code:
  679. # if :unrollFinally:
  680. # if :curExc.isNil:
  681. # return :tmpResult
  682. # else:
  683. # raise
  684. let curExc = ctx.newCurExcAccess()
  685. let nilnode = newNode(nkNilLit)
  686. nilnode.typ = curExc.typ
  687. let cmp = newTree(nkCall, newSymNode(ctx.g.getSysMagic(info, "==", mEqRef), info), curExc, nilnode)
  688. cmp.typ = ctx.g.getSysType(info, tyBool)
  689. let asgn = newTree(nkFastAsgn,
  690. newSymNode(getClosureIterResult(ctx.g, ctx.fn), info),
  691. ctx.newTmpResultAccess())
  692. let retStmt = newTree(nkReturnStmt, asgn)
  693. let branch = newTree(nkElifBranch, cmp, retStmt)
  694. # The C++ backend requires `getCurrentException` here.
  695. let raiseStmt = newTree(nkRaiseStmt, ctx.g.callCodegenProc("getCurrentException"))
  696. raiseStmt.info = info
  697. let elseBranch = newTree(nkElse, raiseStmt)
  698. let ifBody = newTree(nkIfStmt, branch, elseBranch)
  699. let elifBranch = newTree(nkElifBranch, ctx.newUnrollFinallyAccess(info), ifBody)
  700. elifBranch.info = info
  701. result = newTree(nkIfStmt, elifBranch)
  702. proc transformReturnsInTry(ctx: var Ctx, n: PNode): PNode =
  703. result = n
  704. # TODO: This is very inefficient. It traverses the node, looking for nkYieldStmt.
  705. case n.kind
  706. of nkReturnStmt:
  707. # We're somewhere in try, transform to finally unrolling
  708. assert(ctx.nearestFinally != 0)
  709. result = newNodeI(nkStmtList, n.info)
  710. block: # :unrollFinally = true
  711. let asgn = newNodeI(nkAsgn, n.info)
  712. asgn.add(ctx.newUnrollFinallyAccess(n.info))
  713. asgn.add(newIntTypeNode(nkIntLit, 1, ctx.g.getSysType(n.info, tyBool)))
  714. result.add(asgn)
  715. if n[0].kind != nkEmpty:
  716. let asgnTmpResult = newNodeI(nkAsgn, n.info)
  717. asgnTmpResult.add(ctx.newTmpResultAccess())
  718. asgnTmpResult.add(n[0])
  719. result.add(asgnTmpResult)
  720. result.add(ctx.newNullifyCurExc(n.info))
  721. let goto = newTree(nkGotoState, ctx.g.newIntLit(n.info, ctx.nearestFinally))
  722. result.add(goto)
  723. of nkSkip:
  724. discard
  725. else:
  726. for i in 0 ..< n.len:
  727. n[i] = ctx.transformReturnsInTry(n[i])
  728. proc transformClosureIteratorBody(ctx: var Ctx, n: PNode, gotoOut: PNode): PNode =
  729. result = n
  730. case n.kind:
  731. of nkSkip:
  732. discard
  733. of nkStmtList, nkStmtListExpr:
  734. assert(isEmptyType(n.typ), "nkStmtListExpr not lowered")
  735. result = addGotoOut(result, gotoOut)
  736. for i in 0 ..< n.len:
  737. if n[i].hasYieldsInExpressions:
  738. # Lower nkStmtListExpr nodes inside `n[i]` first
  739. var ns = false
  740. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  741. if n[i].hasYields:
  742. # Create a new split
  743. let go = newNodeI(nkGotoState, n[i].info)
  744. n[i] = ctx.transformClosureIteratorBody(n[i], go)
  745. let s = newNodeI(nkStmtList, n[i + 1].info)
  746. for j in i + 1 ..< n.len:
  747. s.add(n[j])
  748. n.sons.setLen(i + 1)
  749. discard ctx.newState(s, go)
  750. if ctx.transformClosureIteratorBody(s, gotoOut) != s:
  751. internalError(ctx.g.config, "transformClosureIteratorBody != s")
  752. break
  753. of nkYieldStmt:
  754. result = newNodeI(nkStmtList, n.info)
  755. result.add(n)
  756. result.add(gotoOut)
  757. of nkElse, nkElseExpr:
  758. result[0] = addGotoOut(result[0], gotoOut)
  759. result[0] = ctx.transformClosureIteratorBody(result[0], gotoOut)
  760. of nkElifBranch, nkElifExpr, nkOfBranch:
  761. result[^1] = addGotoOut(result[^1], gotoOut)
  762. result[^1] = ctx.transformClosureIteratorBody(result[^1], gotoOut)
  763. of nkIfStmt, nkCaseStmt:
  764. for i in 0 ..< n.len:
  765. n[i] = ctx.transformClosureIteratorBody(n[i], gotoOut)
  766. if n[^1].kind != nkElse:
  767. # We don't have an else branch, but every possible branch has to end with
  768. # gotoOut, so add else here.
  769. let elseBranch = newTree(nkElse, gotoOut)
  770. n.add(elseBranch)
  771. of nkWhileStmt:
  772. # while e:
  773. # s
  774. # ->
  775. # BEGIN_STATE:
  776. # if e:
  777. # s
  778. # goto BEGIN_STATE
  779. # else:
  780. # goto OUT
  781. result = newNodeI(nkGotoState, n.info)
  782. let s = newNodeI(nkStmtList, n.info)
  783. discard ctx.newState(s, result)
  784. let ifNode = newNodeI(nkIfStmt, n.info)
  785. let elifBranch = newNodeI(nkElifBranch, n.info)
  786. elifBranch.add(n[0])
  787. var body = addGotoOut(n[1], result)
  788. body = ctx.transformBreaksAndContinuesInWhile(body, result, gotoOut)
  789. body = ctx.transformClosureIteratorBody(body, result)
  790. elifBranch.add(body)
  791. ifNode.add(elifBranch)
  792. let elseBranch = newTree(nkElse, gotoOut)
  793. ifNode.add(elseBranch)
  794. s.add(ifNode)
  795. of nkBlockStmt:
  796. result[1] = addGotoOut(result[1], gotoOut)
  797. result[1] = ctx.transformBreaksInBlock(result[1], result[0], gotoOut)
  798. result[1] = ctx.transformClosureIteratorBody(result[1], gotoOut)
  799. of nkTryStmt:
  800. # See explanation above about how this works
  801. ctx.hasExceptions = true
  802. result = newNodeI(nkGotoState, n.info)
  803. var tryBody = toStmtList(n[0])
  804. var exceptBody = ctx.collectExceptState(n)
  805. var finallyBody = newTree(nkStmtList, getFinallyNode(ctx, n))
  806. finallyBody = ctx.transformReturnsInTry(finallyBody)
  807. finallyBody.add(ctx.newEndFinallyNode(finallyBody.info))
  808. # The following index calculation is based on the knowledge how state
  809. # indexes are assigned
  810. let tryIdx = ctx.states.len
  811. var exceptIdx, finallyIdx: int
  812. if exceptBody.kind != nkEmpty:
  813. exceptIdx = -(tryIdx + 1)
  814. finallyIdx = tryIdx + 2
  815. else:
  816. exceptIdx = tryIdx + 1
  817. finallyIdx = tryIdx + 1
  818. let outToFinally = newNodeI(nkGotoState, finallyBody.info)
  819. block: # Create initial states.
  820. let oldExcHandlingState = ctx.curExcHandlingState
  821. ctx.curExcHandlingState = exceptIdx
  822. let realTryIdx = ctx.newState(tryBody, result)
  823. assert(realTryIdx == tryIdx)
  824. if exceptBody.kind != nkEmpty:
  825. ctx.curExcHandlingState = finallyIdx
  826. let realExceptIdx = ctx.newState(exceptBody, nil)
  827. assert(realExceptIdx == -exceptIdx)
  828. ctx.curExcHandlingState = oldExcHandlingState
  829. let realFinallyIdx = ctx.newState(finallyBody, outToFinally)
  830. assert(realFinallyIdx == finallyIdx)
  831. block: # Subdivide the states
  832. let oldNearestFinally = ctx.nearestFinally
  833. ctx.nearestFinally = finallyIdx
  834. let oldExcHandlingState = ctx.curExcHandlingState
  835. ctx.curExcHandlingState = exceptIdx
  836. if ctx.transformReturnsInTry(tryBody) != tryBody:
  837. internalError(ctx.g.config, "transformReturnsInTry != tryBody")
  838. if ctx.transformClosureIteratorBody(tryBody, outToFinally) != tryBody:
  839. internalError(ctx.g.config, "transformClosureIteratorBody != tryBody")
  840. ctx.curExcHandlingState = finallyIdx
  841. ctx.addElseToExcept(exceptBody)
  842. if ctx.transformReturnsInTry(exceptBody) != exceptBody:
  843. internalError(ctx.g.config, "transformReturnsInTry != exceptBody")
  844. if ctx.transformClosureIteratorBody(exceptBody, outToFinally) != exceptBody:
  845. internalError(ctx.g.config, "transformClosureIteratorBody != exceptBody")
  846. ctx.curExcHandlingState = oldExcHandlingState
  847. ctx.nearestFinally = oldNearestFinally
  848. if ctx.transformClosureIteratorBody(finallyBody, gotoOut) != finallyBody:
  849. internalError(ctx.g.config, "transformClosureIteratorBody != finallyBody")
  850. of nkGotoState, nkForStmt:
  851. internalError(ctx.g.config, "closure iter " & $n.kind)
  852. else:
  853. for i in 0 ..< n.len:
  854. n[i] = ctx.transformClosureIteratorBody(n[i], gotoOut)
  855. proc stateFromGotoState(n: PNode): int =
  856. assert(n.kind == nkGotoState)
  857. result = n[0].intVal.int
  858. proc tranformStateAssignments(ctx: var Ctx, n: PNode): PNode =
  859. # This transforms 3 patterns:
  860. ########################## 1
  861. # yield e
  862. # goto STATE
  863. # ->
  864. # :state = STATE
  865. # return e
  866. ########################## 2
  867. # goto STATE
  868. # ->
  869. # :state = STATE
  870. # break :stateLoop
  871. ########################## 3
  872. # return e
  873. # ->
  874. # :state = -1
  875. # return e
  876. #
  877. result = n
  878. case n.kind
  879. of nkStmtList, nkStmtListExpr:
  880. if n.len != 0 and n[0].kind == nkYieldStmt:
  881. assert(n.len == 2)
  882. assert(n[1].kind == nkGotoState)
  883. result = newNodeI(nkStmtList, n.info)
  884. result.add(ctx.newStateAssgn(stateFromGotoState(n[1])))
  885. var retStmt = newNodeI(nkReturnStmt, n.info)
  886. if n[0].sons[0].kind != nkEmpty:
  887. var a = newNodeI(nkAsgn, n[0].sons[0].info)
  888. var retVal = n[0].sons[0] #liftCapturedVars(n.sons[0], owner, d, c)
  889. addSon(a, newSymNode(getClosureIterResult(ctx.g, ctx.fn)))
  890. addSon(a, retVal)
  891. retStmt.add(a)
  892. else:
  893. retStmt.add(ctx.g.emptyNode)
  894. result.add(retStmt)
  895. else:
  896. for i in 0 ..< n.len:
  897. n[i] = ctx.tranformStateAssignments(n[i])
  898. of nkSkip:
  899. discard
  900. of nkReturnStmt:
  901. result = newNodeI(nkStmtList, n.info)
  902. result.add(ctx.newStateAssgn(-1))
  903. result.add(n)
  904. of nkGotoState:
  905. result = newNodeI(nkStmtList, n.info)
  906. result.add(ctx.newStateAssgn(stateFromGotoState(n)))
  907. let breakState = newNodeI(nkBreakStmt, n.info)
  908. breakState.add(newSymNode(ctx.stateLoopLabel))
  909. result.add(breakState)
  910. else:
  911. for i in 0 ..< n.len:
  912. n[i] = ctx.tranformStateAssignments(n[i])
  913. proc skipStmtList(ctx: Ctx; n: PNode): PNode =
  914. result = n
  915. while result.kind in {nkStmtList}:
  916. if result.len == 0: return ctx.g.emptyNode
  917. result = result[0]
  918. proc skipEmptyStates(ctx: Ctx, stateIdx: int): int =
  919. # Returns first non-empty state idx for `stateIdx`. Returns `stateIdx` if
  920. # it is not empty
  921. var maxJumps = ctx.states.len # maxJumps used only for debugging purposes.
  922. var stateIdx = stateIdx
  923. while true:
  924. let label = stateIdx
  925. if label == ctx.exitStateIdx: break
  926. var newLabel = label
  927. if label == -1:
  928. newLabel = ctx.exitStateIdx
  929. else:
  930. let fs = skipStmtList(ctx, ctx.states[label][1])
  931. if fs.kind == nkGotoState:
  932. newLabel = fs[0].intVal.int
  933. if label == newLabel: break
  934. stateIdx = newLabel
  935. dec maxJumps
  936. if maxJumps == 0:
  937. assert(false, "Internal error")
  938. result = ctx.states[stateIdx][0].intVal.int
  939. proc skipThroughEmptyStates(ctx: var Ctx, n: PNode): PNode =
  940. result = n
  941. case n.kind
  942. of nkSkip:
  943. discard
  944. of nkGotoState:
  945. result = copyTree(n)
  946. result[0].intVal = ctx.skipEmptyStates(result[0].intVal.int)
  947. else:
  948. for i in 0 ..< n.len:
  949. n[i] = ctx.skipThroughEmptyStates(n[i])
  950. proc newArrayType(g: ModuleGraph; n: int, t: PType, owner: PSym): PType =
  951. result = newType(tyArray, owner)
  952. let rng = newType(tyRange, owner)
  953. rng.n = newTree(nkRange, g.newIntLit(owner.info, 0), g.newIntLit(owner.info, n))
  954. rng.rawAddSon(t)
  955. result.rawAddSon(rng)
  956. result.rawAddSon(t)
  957. proc createExceptionTable(ctx: var Ctx): PNode {.inline.} =
  958. result = newNodeI(nkBracket, ctx.fn.info)
  959. result.typ = ctx.g.newArrayType(ctx.exceptionTable.len, ctx.g.getSysType(ctx.fn.info, tyInt16), ctx.fn)
  960. for i in ctx.exceptionTable:
  961. let elem = newIntNode(nkIntLit, i)
  962. elem.typ = ctx.g.getSysType(ctx.fn.info, tyInt16)
  963. result.add(elem)
  964. proc newCatchBody(ctx: var Ctx, info: TLineInfo): PNode {.inline.} =
  965. # Generates the code:
  966. # :state = exceptionTable[:state]
  967. # if :state == 0: raise
  968. # :unrollFinally = :state > 0
  969. # if :state < 0:
  970. # :state = -:state
  971. # :curExc = getCurrentException()
  972. result = newNodeI(nkStmtList, info)
  973. let intTyp = ctx.g.getSysType(info, tyInt)
  974. let boolTyp = ctx.g.getSysType(info, tyBool)
  975. # :state = exceptionTable[:state]
  976. block:
  977. # exceptionTable[:state]
  978. let getNextState = newTree(nkBracketExpr,
  979. ctx.createExceptionTable(),
  980. ctx.newStateAccess())
  981. getNextState.typ = intTyp
  982. # :state = exceptionTable[:state]
  983. result.add(ctx.newStateAssgn(getNextState))
  984. # if :state == 0: raise
  985. block:
  986. let cond = newTree(nkCall,
  987. ctx.g.getSysMagic(info, "==", mEqI).newSymNode(),
  988. ctx.newStateAccess(),
  989. newIntTypeNode(nkIntLit, 0, intTyp))
  990. cond.typ = boolTyp
  991. let raiseStmt = newTree(nkRaiseStmt, ctx.g.emptyNode)
  992. let ifBranch = newTree(nkElifBranch, cond, raiseStmt)
  993. let ifStmt = newTree(nkIfStmt, ifBranch)
  994. result.add(ifStmt)
  995. # :unrollFinally = :state > 0
  996. block:
  997. let cond = newTree(nkCall,
  998. ctx.g.getSysMagic(info, "<", mLtI).newSymNode,
  999. newIntTypeNode(nkIntLit, 0, intTyp),
  1000. ctx.newStateAccess())
  1001. cond.typ = boolTyp
  1002. let asgn = newTree(nkAsgn, ctx.newUnrollFinallyAccess(info), cond)
  1003. result.add(asgn)
  1004. # if :state < 0: :state = -:state
  1005. block:
  1006. let cond = newTree(nkCall,
  1007. ctx.g.getSysMagic(info, "<", mLtI).newSymNode,
  1008. ctx.newStateAccess(),
  1009. newIntTypeNode(nkIntLit, 0, intTyp))
  1010. cond.typ = boolTyp
  1011. let negateState = newTree(nkCall,
  1012. ctx.g.getSysMagic(info, "-", mUnaryMinusI).newSymNode,
  1013. ctx.newStateAccess())
  1014. negateState.typ = intTyp
  1015. let ifBranch = newTree(nkElifBranch, cond, ctx.newStateAssgn(negateState))
  1016. let ifStmt = newTree(nkIfStmt, ifBranch)
  1017. result.add(ifStmt)
  1018. # :curExc = getCurrentException()
  1019. block:
  1020. result.add(newTree(nkAsgn,
  1021. ctx.newCurExcAccess(),
  1022. ctx.g.callCodegenProc("getCurrentException")))
  1023. proc wrapIntoTryExcept(ctx: var Ctx, n: PNode): PNode {.inline.} =
  1024. let setupExc = newTree(nkCall,
  1025. newSymNode(ctx.g.getCompilerProc("closureIterSetupExc")),
  1026. ctx.newCurExcAccess())
  1027. let tryBody = newTree(nkStmtList, setupExc, n)
  1028. let exceptBranch = newTree(nkExceptBranch, ctx.newCatchBody(ctx.fn.info))
  1029. result = newTree(nkTryStmt, tryBody, exceptBranch)
  1030. proc wrapIntoStateLoop(ctx: var Ctx, n: PNode): PNode =
  1031. # while true:
  1032. # block :stateLoop:
  1033. # gotoState :state
  1034. # body # Might get wrapped in try-except
  1035. let loopBody = newNodeI(nkStmtList, n.info)
  1036. result = newTree(nkWhileStmt, newSymNode(ctx.g.getSysSym(n.info, "true")), loopBody)
  1037. result.info = n.info
  1038. if not ctx.stateVarSym.isNil:
  1039. let varSect = newNodeI(nkVarSection, n.info)
  1040. addVar(varSect, newSymNode(ctx.stateVarSym))
  1041. loopBody.add(varSect)
  1042. if not ctx.tempVars.isNil:
  1043. loopBody.add(ctx.tempVars)
  1044. let blockStmt = newNodeI(nkBlockStmt, n.info)
  1045. blockStmt.add(newSymNode(ctx.stateLoopLabel))
  1046. let gs = newNodeI(nkGotoState, n.info)
  1047. gs.add(ctx.newStateAccess())
  1048. gs.add(ctx.g.newIntLit(n.info, ctx.states.len - 1))
  1049. var blockBody = newTree(nkStmtList, gs, n)
  1050. if ctx.hasExceptions:
  1051. blockBody = ctx.wrapIntoTryExcept(blockBody)
  1052. blockStmt.add(blockBody)
  1053. loopBody.add(blockStmt)
  1054. proc deleteEmptyStates(ctx: var Ctx) =
  1055. let goOut = newTree(nkGotoState, ctx.g.newIntLit(TLineInfo(), -1))
  1056. ctx.exitStateIdx = ctx.newState(goOut, nil)
  1057. # Apply new state indexes and mark unused states with -1
  1058. var iValid = 0
  1059. for i, s in ctx.states:
  1060. let body = skipStmtList(ctx, s[1])
  1061. if body.kind == nkGotoState and i != ctx.states.len - 1 and i != 0:
  1062. # This is an empty state. Mark with -1.
  1063. s[0].intVal = -1
  1064. else:
  1065. s[0].intVal = iValid
  1066. inc iValid
  1067. for i, s in ctx.states:
  1068. let body = skipStmtList(ctx, s[1])
  1069. if body.kind != nkGotoState or i == 0:
  1070. discard ctx.skipThroughEmptyStates(s)
  1071. let excHandlState = ctx.exceptionTable[i]
  1072. if excHandlState < 0:
  1073. ctx.exceptionTable[i] = -ctx.skipEmptyStates(-excHandlState)
  1074. elif excHandlState != 0:
  1075. ctx.exceptionTable[i] = ctx.skipEmptyStates(excHandlState)
  1076. var i = 0
  1077. while i < ctx.states.len - 1:
  1078. let fs = skipStmtList(ctx, ctx.states[i][1])
  1079. if fs.kind == nkGotoState and i != 0:
  1080. ctx.states.delete(i)
  1081. ctx.exceptionTable.delete(i)
  1082. else:
  1083. inc i
  1084. proc transformClosureIterator*(g: ModuleGraph; fn: PSym, n: PNode): PNode =
  1085. var ctx: Ctx
  1086. ctx.g = g
  1087. ctx.fn = fn
  1088. if getEnvParam(fn).isNil:
  1089. # Lambda lifting was not done yet. Use temporary :state sym, which
  1090. # be handled specially by lambda lifting. Local temp vars (if needed)
  1091. # should folllow the same logic.
  1092. ctx.stateVarSym = newSym(skVar, getIdent(ctx.g.cache, ":state"), fn, fn.info)
  1093. ctx.stateVarSym.typ = g.createClosureIterStateType(fn)
  1094. ctx.stateLoopLabel = newSym(skLabel, getIdent(ctx.g.cache, ":stateLoop"), fn, fn.info)
  1095. let n = n.toStmtList
  1096. discard ctx.newState(n, nil)
  1097. let gotoOut = newTree(nkGotoState, g.newIntLit(n.info, -1))
  1098. # Splitting transformation
  1099. discard ctx.transformClosureIteratorBody(n, gotoOut)
  1100. # Optimize empty states away
  1101. ctx.deleteEmptyStates()
  1102. # Make new body by concating the list of states
  1103. result = newNodeI(nkStmtList, n.info)
  1104. for s in ctx.states:
  1105. assert(s.len == 2)
  1106. let body = s[1]
  1107. s.sons.del(1)
  1108. result.add(s)
  1109. result.add(body)
  1110. result = ctx.tranformStateAssignments(result)
  1111. result = ctx.wrapIntoStateLoop(result)
  1112. # echo "TRANSFORM TO STATES: "
  1113. # echo renderTree(result)
  1114. # echo "exception table:"
  1115. # for i, e in ctx.exceptionTable:
  1116. # echo i, " -> ", e