closureiters.nim 44 KB

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