closureiters.nim 43 KB

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