closureiters.nim 43 KB

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