closureiters.nim 43 KB

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