closureiters.nim 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  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. when defined(nimPreviewSlimSystem):
  133. import std/assertions
  134. type
  135. Ctx = object
  136. g: ModuleGraph
  137. fn: PSym
  138. stateVarSym: PSym # :state variable. nil if env already introduced by lambdalifting
  139. tmpResultSym: PSym # Used when we return, but finally has to interfere
  140. unrollFinallySym: PSym # Indicates that we're unrolling finally states (either exception happened or premature return)
  141. curExcSym: PSym # Current exception
  142. states: seq[PNode] # The resulting states. Every state is an nkState node.
  143. blockLevel: int # Temp used to transform break and continue stmts
  144. stateLoopLabel: PSym # Label to break on, when jumping between states.
  145. exitStateIdx: int # index of the last state
  146. tempVarId: int # unique name counter
  147. tempVars: PNode # Temp var decls, nkVarSection
  148. exceptionTable: seq[int] # For state `i` jump to state `exceptionTable[i]` if exception is raised
  149. hasExceptions: bool # Does closure have yield in try?
  150. curExcHandlingState: int # Negative for except, positive for finally
  151. nearestFinally: int # Index of the nearest finally block. For try/except it
  152. # is their finally. For finally it is parent finally. Otherwise -1
  153. idgen: IdGenerator
  154. const
  155. nkSkip = {nkEmpty..nkNilLit, nkTemplateDef, nkTypeSection, nkStaticStmt,
  156. nkCommentStmt, nkMixinStmt, nkBindStmt} + procDefs
  157. proc newStateAccess(ctx: var Ctx): PNode =
  158. if ctx.stateVarSym.isNil:
  159. result = rawIndirectAccess(newSymNode(getEnvParam(ctx.fn)),
  160. getStateField(ctx.g, ctx.fn), ctx.fn.info)
  161. else:
  162. result = newSymNode(ctx.stateVarSym)
  163. proc newStateAssgn(ctx: var Ctx, toValue: PNode): PNode =
  164. # Creates state assignment:
  165. # :state = toValue
  166. newTree(nkAsgn, ctx.newStateAccess(), toValue)
  167. proc newStateAssgn(ctx: var Ctx, stateNo: int = -2): PNode =
  168. # Creates state assignment:
  169. # :state = stateNo
  170. ctx.newStateAssgn(newIntTypeNode(stateNo, ctx.g.getSysType(TLineInfo(), tyInt)))
  171. proc newEnvVar(ctx: var Ctx, name: string, typ: PType): PSym =
  172. result = newSym(skVar, getIdent(ctx.g.cache, name), nextSymId(ctx.idgen), ctx.fn, ctx.fn.info)
  173. result.typ = typ
  174. assert(not typ.isNil)
  175. if not ctx.stateVarSym.isNil:
  176. # We haven't gone through labmda lifting yet, so just create a local var,
  177. # it will be lifted later
  178. if ctx.tempVars.isNil:
  179. ctx.tempVars = newNodeI(nkVarSection, ctx.fn.info)
  180. addVar(ctx.tempVars, newSymNode(result))
  181. else:
  182. let envParam = getEnvParam(ctx.fn)
  183. # let obj = envParam.typ.lastSon
  184. result = addUniqueField(envParam.typ.lastSon, result, ctx.g.cache, ctx.idgen)
  185. proc newEnvVarAccess(ctx: Ctx, s: PSym): PNode =
  186. if ctx.stateVarSym.isNil:
  187. result = rawIndirectAccess(newSymNode(getEnvParam(ctx.fn)), s, ctx.fn.info)
  188. else:
  189. result = newSymNode(s)
  190. proc newTmpResultAccess(ctx: var Ctx): PNode =
  191. if ctx.tmpResultSym.isNil:
  192. ctx.tmpResultSym = ctx.newEnvVar(":tmpResult", ctx.fn.typ[0])
  193. ctx.newEnvVarAccess(ctx.tmpResultSym)
  194. proc newUnrollFinallyAccess(ctx: var Ctx, info: TLineInfo): PNode =
  195. if ctx.unrollFinallySym.isNil:
  196. ctx.unrollFinallySym = ctx.newEnvVar(":unrollFinally", ctx.g.getSysType(info, tyBool))
  197. ctx.newEnvVarAccess(ctx.unrollFinallySym)
  198. proc newCurExcAccess(ctx: var Ctx): PNode =
  199. if ctx.curExcSym.isNil:
  200. ctx.curExcSym = ctx.newEnvVar(":curExc", ctx.g.callCodegenProc("getCurrentException").typ)
  201. ctx.newEnvVarAccess(ctx.curExcSym)
  202. proc newState(ctx: var Ctx, n, gotoOut: PNode): int =
  203. # Creates a new state, adds it to the context fills out `gotoOut` so that it
  204. # will goto this state.
  205. # Returns index of the newly created state
  206. result = ctx.states.len
  207. let resLit = ctx.g.newIntLit(n.info, result)
  208. let s = newNodeI(nkState, n.info)
  209. s.add(resLit)
  210. s.add(n)
  211. ctx.states.add(s)
  212. ctx.exceptionTable.add(ctx.curExcHandlingState)
  213. if not gotoOut.isNil:
  214. assert(gotoOut.len == 0)
  215. gotoOut.add(ctx.g.newIntLit(gotoOut.info, result))
  216. proc toStmtList(n: PNode): PNode =
  217. result = n
  218. if result.kind notin {nkStmtList, nkStmtListExpr}:
  219. result = newNodeI(nkStmtList, n.info)
  220. result.add(n)
  221. proc addGotoOut(n: PNode, gotoOut: PNode): PNode =
  222. # Make sure `n` is a stmtlist, and ends with `gotoOut`
  223. result = toStmtList(n)
  224. if result.len == 0 or result[^1].kind != nkGotoState:
  225. result.add(gotoOut)
  226. proc newTempVar(ctx: var Ctx, typ: PType): PSym =
  227. result = ctx.newEnvVar(":tmpSlLower" & $ctx.tempVarId, typ)
  228. inc ctx.tempVarId
  229. proc hasYields(n: PNode): bool =
  230. # TODO: This is very inefficient. It traverses the node, looking for nkYieldStmt.
  231. case n.kind
  232. of nkYieldStmt:
  233. result = true
  234. of nkSkip:
  235. discard
  236. else:
  237. for c in n:
  238. if c.hasYields:
  239. result = true
  240. break
  241. proc transformBreaksAndContinuesInWhile(ctx: var Ctx, n: PNode, before, after: PNode): PNode =
  242. result = n
  243. case n.kind
  244. of nkSkip:
  245. discard
  246. of nkWhileStmt: discard # Do not recurse into nested whiles
  247. of nkContinueStmt:
  248. result = before
  249. of nkBlockStmt:
  250. inc ctx.blockLevel
  251. result[1] = ctx.transformBreaksAndContinuesInWhile(result[1], before, after)
  252. dec ctx.blockLevel
  253. of nkBreakStmt:
  254. if ctx.blockLevel == 0:
  255. result = after
  256. else:
  257. for i in 0..<n.len:
  258. n[i] = ctx.transformBreaksAndContinuesInWhile(n[i], before, after)
  259. proc transformBreaksInBlock(ctx: var Ctx, n: PNode, label, after: PNode): PNode =
  260. result = n
  261. case n.kind
  262. of nkSkip:
  263. discard
  264. of nkBlockStmt, nkWhileStmt:
  265. inc ctx.blockLevel
  266. result[1] = ctx.transformBreaksInBlock(result[1], label, after)
  267. dec ctx.blockLevel
  268. of nkBreakStmt:
  269. if n[0].kind == nkEmpty:
  270. if ctx.blockLevel == 0:
  271. result = after
  272. else:
  273. if label.kind == nkSym and n[0].sym == label.sym:
  274. result = after
  275. else:
  276. for i in 0..<n.len:
  277. n[i] = ctx.transformBreaksInBlock(n[i], label, after)
  278. proc newNullifyCurExc(ctx: var Ctx, info: TLineInfo): PNode =
  279. # :curEcx = nil
  280. let curExc = ctx.newCurExcAccess()
  281. curExc.info = info
  282. let nilnode = newNode(nkNilLit)
  283. nilnode.typ = curExc.typ
  284. result = newTree(nkAsgn, curExc, nilnode)
  285. proc newOr(g: ModuleGraph, a, b: PNode): PNode {.inline.} =
  286. result = newTree(nkCall, newSymNode(g.getSysMagic(a.info, "or", mOr)), a, b)
  287. result.typ = g.getSysType(a.info, tyBool)
  288. result.info = a.info
  289. proc collectExceptState(ctx: var Ctx, n: PNode): PNode {.inline.} =
  290. var ifStmt = newNodeI(nkIfStmt, n.info)
  291. let g = ctx.g
  292. for c in n:
  293. if c.kind == nkExceptBranch:
  294. var ifBranch: PNode
  295. if c.len > 1:
  296. var cond: PNode
  297. for i in 0..<c.len - 1:
  298. assert(c[i].kind == nkType)
  299. let nextCond = newTree(nkCall,
  300. newSymNode(g.getSysMagic(c.info, "of", mOf)),
  301. g.callCodegenProc("getCurrentException"),
  302. c[i])
  303. nextCond.typ = ctx.g.getSysType(c.info, tyBool)
  304. nextCond.info = c.info
  305. if cond.isNil:
  306. cond = nextCond
  307. else:
  308. cond = g.newOr(cond, nextCond)
  309. ifBranch = newNodeI(nkElifBranch, c.info)
  310. ifBranch.add(cond)
  311. else:
  312. if ifStmt.len == 0:
  313. ifStmt = newNodeI(nkStmtList, c.info)
  314. ifBranch = newNodeI(nkStmtList, c.info)
  315. else:
  316. ifBranch = newNodeI(nkElse, c.info)
  317. ifBranch.add(c[^1])
  318. ifStmt.add(ifBranch)
  319. if ifStmt.len != 0:
  320. result = newTree(nkStmtList, ctx.newNullifyCurExc(n.info), ifStmt)
  321. else:
  322. result = ctx.g.emptyNode
  323. proc addElseToExcept(ctx: var Ctx, n: PNode) =
  324. if n.kind == nkStmtList and n[1].kind == nkIfStmt and n[1][^1].kind != nkElse:
  325. # Not all cases are covered
  326. let branchBody = newNodeI(nkStmtList, n.info)
  327. block: # :unrollFinally = true
  328. branchBody.add(newTree(nkAsgn,
  329. ctx.newUnrollFinallyAccess(n.info),
  330. newIntTypeNode(1, ctx.g.getSysType(n.info, tyBool))))
  331. block: # :curExc = getCurrentException()
  332. branchBody.add(newTree(nkAsgn,
  333. ctx.newCurExcAccess(),
  334. ctx.g.callCodegenProc("getCurrentException")))
  335. block: # goto nearestFinally
  336. branchBody.add(newTree(nkGotoState, ctx.g.newIntLit(n.info, ctx.nearestFinally)))
  337. let elseBranch = newTree(nkElse, branchBody)
  338. n[1].add(elseBranch)
  339. proc getFinallyNode(ctx: var Ctx, n: PNode): PNode =
  340. result = n[^1]
  341. if result.kind == nkFinally:
  342. result = result[0]
  343. else:
  344. result = ctx.g.emptyNode
  345. proc hasYieldsInExpressions(n: PNode): bool =
  346. case n.kind
  347. of nkSkip:
  348. discard
  349. of nkStmtListExpr:
  350. if isEmptyType(n.typ):
  351. for c in n:
  352. if c.hasYieldsInExpressions:
  353. return true
  354. else:
  355. result = n.hasYields
  356. of nkCast:
  357. for i in 1..<n.len:
  358. if n[i].hasYieldsInExpressions:
  359. return true
  360. else:
  361. for c in n:
  362. if c.hasYieldsInExpressions:
  363. return true
  364. proc exprToStmtList(n: PNode): tuple[s, res: PNode] =
  365. assert(n.kind == nkStmtListExpr)
  366. result.s = newNodeI(nkStmtList, n.info)
  367. result.s.sons = @[]
  368. var n = n
  369. while n.kind == nkStmtListExpr:
  370. result.s.sons.add(n.sons)
  371. result.s.sons.setLen(result.s.len - 1) # delete last son
  372. n = n[^1]
  373. result.res = n
  374. proc newEnvVarAsgn(ctx: Ctx, s: PSym, v: PNode): PNode =
  375. if isEmptyType(v.typ):
  376. result = v
  377. else:
  378. result = newTree(nkFastAsgn, ctx.newEnvVarAccess(s), v)
  379. result.info = v.info
  380. proc addExprAssgn(ctx: Ctx, output, input: PNode, sym: PSym) =
  381. if input.kind == nkStmtListExpr:
  382. let (st, res) = exprToStmtList(input)
  383. output.add(st)
  384. output.add(ctx.newEnvVarAsgn(sym, res))
  385. else:
  386. output.add(ctx.newEnvVarAsgn(sym, input))
  387. proc convertExprBodyToAsgn(ctx: Ctx, exprBody: PNode, res: PSym): PNode =
  388. result = newNodeI(nkStmtList, exprBody.info)
  389. ctx.addExprAssgn(result, exprBody, res)
  390. proc newNotCall(g: ModuleGraph; e: PNode): PNode =
  391. result = newTree(nkCall, newSymNode(g.getSysMagic(e.info, "not", mNot), e.info), e)
  392. result.typ = g.getSysType(e.info, tyBool)
  393. proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
  394. result = n
  395. case n.kind
  396. of nkSkip:
  397. discard
  398. of nkYieldStmt:
  399. var ns = false
  400. for i in 0..<n.len:
  401. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  402. if ns:
  403. result = newNodeI(nkStmtList, n.info)
  404. let (st, ex) = exprToStmtList(n[0])
  405. result.add(st)
  406. n[0] = ex
  407. result.add(n)
  408. needsSplit = true
  409. of nkPar, nkObjConstr, nkTupleConstr, nkBracket:
  410. var ns = false
  411. for i in 0..<n.len:
  412. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  413. if ns:
  414. needsSplit = true
  415. result = newNodeI(nkStmtListExpr, n.info)
  416. if n.typ.isNil: internalError(ctx.g.config, "lowerStmtListExprs: constr typ.isNil")
  417. result.typ = n.typ
  418. for i in 0..<n.len:
  419. case n[i].kind
  420. of nkExprColonExpr:
  421. if n[i][1].kind == nkStmtListExpr:
  422. let (st, ex) = exprToStmtList(n[i][1])
  423. result.add(st)
  424. n[i][1] = ex
  425. of nkStmtListExpr:
  426. let (st, ex) = exprToStmtList(n[i])
  427. result.add(st)
  428. n[i] = ex
  429. else: discard
  430. result.add(n)
  431. of nkIfStmt, nkIfExpr:
  432. var ns = false
  433. for i in 0..<n.len:
  434. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  435. if ns:
  436. needsSplit = true
  437. var tmp: PSym
  438. let isExpr = not isEmptyType(n.typ)
  439. if isExpr:
  440. tmp = ctx.newTempVar(n.typ)
  441. result = newNodeI(nkStmtListExpr, n.info)
  442. result.typ = n.typ
  443. else:
  444. result = newNodeI(nkStmtList, n.info)
  445. var curS = result
  446. for branch in n:
  447. case branch.kind
  448. of nkElseExpr, nkElse:
  449. if isExpr:
  450. let branchBody = newNodeI(nkStmtList, branch.info)
  451. ctx.addExprAssgn(branchBody, branch[0], tmp)
  452. let newBranch = newTree(nkElse, branchBody)
  453. curS.add(newBranch)
  454. else:
  455. curS.add(branch)
  456. of nkElifExpr, nkElifBranch:
  457. var newBranch: PNode
  458. if branch[0].kind == nkStmtListExpr:
  459. let (st, res) = exprToStmtList(branch[0])
  460. let elseBody = newTree(nkStmtList, st)
  461. newBranch = newTree(nkElifBranch, res, branch[1])
  462. let newIf = newTree(nkIfStmt, newBranch)
  463. elseBody.add(newIf)
  464. if curS.kind == nkIfStmt:
  465. let newElse = newNodeI(nkElse, branch.info)
  466. newElse.add(elseBody)
  467. curS.add(newElse)
  468. else:
  469. curS.add(elseBody)
  470. curS = newIf
  471. else:
  472. newBranch = branch
  473. if curS.kind == nkIfStmt:
  474. curS.add(newBranch)
  475. else:
  476. let newIf = newTree(nkIfStmt, newBranch)
  477. curS.add(newIf)
  478. curS = newIf
  479. if isExpr:
  480. let branchBody = newNodeI(nkStmtList, branch[1].info)
  481. ctx.addExprAssgn(branchBody, branch[1], tmp)
  482. newBranch[1] = branchBody
  483. else:
  484. internalError(ctx.g.config, "lowerStmtListExpr(nkIf): " & $branch.kind)
  485. if isExpr: result.add(ctx.newEnvVarAccess(tmp))
  486. of nkTryStmt, nkHiddenTryStmt:
  487. var ns = false
  488. for i in 0..<n.len:
  489. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  490. if ns:
  491. needsSplit = true
  492. let isExpr = not isEmptyType(n.typ)
  493. if isExpr:
  494. result = newNodeI(nkStmtListExpr, n.info)
  495. result.typ = n.typ
  496. let tmp = ctx.newTempVar(n.typ)
  497. n[0] = ctx.convertExprBodyToAsgn(n[0], tmp)
  498. for i in 1..<n.len:
  499. let branch = n[i]
  500. case branch.kind
  501. of nkExceptBranch:
  502. if branch[0].kind == nkType:
  503. branch[1] = ctx.convertExprBodyToAsgn(branch[1], tmp)
  504. else:
  505. branch[0] = ctx.convertExprBodyToAsgn(branch[0], tmp)
  506. of nkFinally:
  507. discard
  508. else:
  509. internalError(ctx.g.config, "lowerStmtListExpr(nkTryStmt): " & $branch.kind)
  510. result.add(n)
  511. result.add(ctx.newEnvVarAccess(tmp))
  512. of nkCaseStmt:
  513. var ns = false
  514. for i in 0..<n.len:
  515. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  516. if ns:
  517. needsSplit = true
  518. let isExpr = not isEmptyType(n.typ)
  519. if isExpr:
  520. let tmp = ctx.newTempVar(n.typ)
  521. result = newNodeI(nkStmtListExpr, n.info)
  522. result.typ = n.typ
  523. if n[0].kind == nkStmtListExpr:
  524. let (st, ex) = exprToStmtList(n[0])
  525. result.add(st)
  526. n[0] = ex
  527. for i in 1..<n.len:
  528. let branch = n[i]
  529. case branch.kind
  530. of nkOfBranch:
  531. branch[^1] = ctx.convertExprBodyToAsgn(branch[^1], tmp)
  532. of nkElse:
  533. branch[0] = ctx.convertExprBodyToAsgn(branch[0], tmp)
  534. else:
  535. internalError(ctx.g.config, "lowerStmtListExpr(nkCaseStmt): " & $branch.kind)
  536. result.add(n)
  537. result.add(ctx.newEnvVarAccess(tmp))
  538. elif n[0].kind == nkStmtListExpr:
  539. result = newNodeI(nkStmtList, n.info)
  540. let (st, ex) = exprToStmtList(n[0])
  541. result.add(st)
  542. n[0] = ex
  543. result.add(n)
  544. of nkCallKinds, nkChckRange, nkChckRangeF, nkChckRange64:
  545. var ns = false
  546. for i in 0..<n.len:
  547. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  548. if ns:
  549. needsSplit = true
  550. let isExpr = not isEmptyType(n.typ)
  551. if isExpr:
  552. result = newNodeI(nkStmtListExpr, n.info)
  553. result.typ = n.typ
  554. else:
  555. result = newNodeI(nkStmtList, n.info)
  556. if n[0].kind == nkSym and n[0].sym.magic in {mAnd, mOr}: # `and`/`or` short cirquiting
  557. var cond = n[1]
  558. if cond.kind == nkStmtListExpr:
  559. let (st, ex) = exprToStmtList(cond)
  560. result.add(st)
  561. cond = ex
  562. let tmp = ctx.newTempVar(cond.typ)
  563. result.add(ctx.newEnvVarAsgn(tmp, cond))
  564. var check = ctx.newEnvVarAccess(tmp)
  565. if n[0].sym.magic == mOr:
  566. check = ctx.g.newNotCall(check)
  567. cond = n[2]
  568. let ifBody = newNodeI(nkStmtList, cond.info)
  569. if cond.kind == nkStmtListExpr:
  570. let (st, ex) = exprToStmtList(cond)
  571. ifBody.add(st)
  572. cond = ex
  573. ifBody.add(ctx.newEnvVarAsgn(tmp, cond))
  574. let ifBranch = newTree(nkElifBranch, check, ifBody)
  575. let ifNode = newTree(nkIfStmt, ifBranch)
  576. result.add(ifNode)
  577. result.add(ctx.newEnvVarAccess(tmp))
  578. else:
  579. for i in 0..<n.len:
  580. if n[i].kind == nkStmtListExpr:
  581. let (st, ex) = exprToStmtList(n[i])
  582. result.add(st)
  583. n[i] = ex
  584. if n[i].kind in nkCallKinds: # XXX: This should better be some sort of side effect tracking
  585. let tmp = ctx.newTempVar(n[i].typ)
  586. result.add(ctx.newEnvVarAsgn(tmp, n[i]))
  587. n[i] = ctx.newEnvVarAccess(tmp)
  588. result.add(n)
  589. of nkVarSection, nkLetSection:
  590. result = newNodeI(nkStmtList, n.info)
  591. for c in n:
  592. let varSect = newNodeI(n.kind, n.info)
  593. varSect.add(c)
  594. var ns = false
  595. c[^1] = ctx.lowerStmtListExprs(c[^1], ns)
  596. if ns:
  597. needsSplit = true
  598. let (st, ex) = exprToStmtList(c[^1])
  599. result.add(st)
  600. c[^1] = ex
  601. result.add(varSect)
  602. of nkDiscardStmt, nkReturnStmt, nkRaiseStmt:
  603. var ns = false
  604. for i in 0..<n.len:
  605. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  606. if ns:
  607. needsSplit = true
  608. result = newNodeI(nkStmtList, n.info)
  609. let (st, ex) = exprToStmtList(n[0])
  610. result.add(st)
  611. n[0] = ex
  612. result.add(n)
  613. of nkCast, nkHiddenStdConv, nkHiddenSubConv, nkConv, nkObjDownConv,
  614. nkDerefExpr, nkHiddenDeref:
  615. var ns = false
  616. for i in ord(n.kind == nkCast)..<n.len:
  617. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  618. if ns:
  619. needsSplit = true
  620. result = newNodeI(nkStmtListExpr, n.info)
  621. result.typ = n.typ
  622. let (st, ex) = exprToStmtList(n[^1])
  623. result.add(st)
  624. n[^1] = ex
  625. result.add(n)
  626. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  627. var ns = false
  628. for i in 0..<n.len:
  629. n[i] = ctx.lowerStmtListExprs(n[i], ns)
  630. if ns:
  631. needsSplit = true
  632. result = newNodeI(nkStmtList, n.info)
  633. if n[0].kind == nkStmtListExpr:
  634. let (st, ex) = exprToStmtList(n[0])
  635. result.add(st)
  636. n[0] = ex
  637. if n[1].kind == nkStmtListExpr:
  638. let (st, ex) = exprToStmtList(n[1])
  639. result.add(st)
  640. n[1] = ex
  641. result.add(n)
  642. of nkBracketExpr:
  643. var lhsNeedsSplit = false
  644. var rhsNeedsSplit = false
  645. n[0] = ctx.lowerStmtListExprs(n[0], lhsNeedsSplit)
  646. n[1] = ctx.lowerStmtListExprs(n[1], rhsNeedsSplit)
  647. if lhsNeedsSplit or rhsNeedsSplit:
  648. needsSplit = true
  649. result = newNodeI(nkStmtListExpr, n.info)
  650. if lhsNeedsSplit:
  651. let (st, ex) = exprToStmtList(n[0])
  652. result.add(st)
  653. n[0] = ex
  654. if rhsNeedsSplit:
  655. let (st, ex) = exprToStmtList(n[1])
  656. result.add(st)
  657. n[1] = ex
  658. result.add(n)
  659. of nkWhileStmt:
  660. var condNeedsSplit = false
  661. n[0] = ctx.lowerStmtListExprs(n[0], condNeedsSplit)
  662. var bodyNeedsSplit = false
  663. n[1] = ctx.lowerStmtListExprs(n[1], bodyNeedsSplit)
  664. if condNeedsSplit or bodyNeedsSplit:
  665. needsSplit = true
  666. if condNeedsSplit:
  667. let (st, ex) = exprToStmtList(n[0])
  668. let brk = newTree(nkBreakStmt, ctx.g.emptyNode)
  669. let branch = newTree(nkElifBranch, ctx.g.newNotCall(ex), brk)
  670. let check = newTree(nkIfStmt, branch)
  671. let newBody = newTree(nkStmtList, st, check, n[1])
  672. n[0] = newSymNode(ctx.g.getSysSym(n[0].info, "true"))
  673. n[1] = newBody
  674. of nkDotExpr, nkCheckedFieldExpr:
  675. var ns = false
  676. n[0] = ctx.lowerStmtListExprs(n[0], ns)
  677. if ns:
  678. needsSplit = true
  679. result = newNodeI(nkStmtListExpr, n.info)
  680. result.typ = n.typ
  681. let (st, ex) = exprToStmtList(n[0])
  682. result.add(st)
  683. n[0] = ex
  684. result.add(n)
  685. of nkBlockExpr:
  686. var ns = false
  687. n[1] = ctx.lowerStmtListExprs(n[1], ns)
  688. if ns:
  689. needsSplit = true
  690. result = newNodeI(nkStmtListExpr, n.info)
  691. result.typ = n.typ
  692. let (st, ex) = exprToStmtList(n[1])
  693. n.transitionSonsKind(nkBlockStmt)
  694. n.typ = nil
  695. n[1] = st
  696. result.add(n)
  697. result.add(ex)
  698. else:
  699. for i in 0..<n.len:
  700. n[i] = ctx.lowerStmtListExprs(n[i], needsSplit)
  701. proc newEndFinallyNode(ctx: var Ctx, info: TLineInfo): PNode =
  702. # Generate the following code:
  703. # if :unrollFinally:
  704. # if :curExc.isNil:
  705. # if nearestFinally == 0:
  706. # return :tmpResult
  707. # else:
  708. # :state = nearestFinally # bubble up
  709. # else:
  710. # raise
  711. let curExc = ctx.newCurExcAccess()
  712. let nilnode = newNode(nkNilLit)
  713. nilnode.typ = curExc.typ
  714. let cmp = newTree(nkCall, newSymNode(ctx.g.getSysMagic(info, "==", mEqRef), info), curExc, nilnode)
  715. cmp.typ = ctx.g.getSysType(info, tyBool)
  716. let retStmt =
  717. if ctx.nearestFinally == 0:
  718. # last finally, we can return
  719. let retValue = if ctx.fn.typ[0].isNil:
  720. ctx.g.emptyNode
  721. else:
  722. newTree(nkFastAsgn,
  723. newSymNode(getClosureIterResult(ctx.g, ctx.fn, ctx.idgen), info),
  724. ctx.newTmpResultAccess())
  725. newTree(nkReturnStmt, retValue)
  726. else:
  727. # bubble up to next finally
  728. newTree(nkGotoState, ctx.g.newIntLit(info, ctx.nearestFinally))
  729. let branch = newTree(nkElifBranch, cmp, retStmt)
  730. let nullifyExc = newTree(nkCall, newSymNode(ctx.g.getCompilerProc("closureIterSetupExc")), nilnode)
  731. nullifyExc.info = info
  732. let raiseStmt = newTree(nkRaiseStmt, curExc)
  733. raiseStmt.info = info
  734. let elseBranch = newTree(nkElse, newTree(nkStmtList, nullifyExc, raiseStmt))
  735. let ifBody = newTree(nkIfStmt, branch, elseBranch)
  736. let elifBranch = newTree(nkElifBranch, ctx.newUnrollFinallyAccess(info), ifBody)
  737. elifBranch.info = info
  738. result = newTree(nkIfStmt, elifBranch)
  739. proc transformReturnsInTry(ctx: var Ctx, n: PNode): PNode =
  740. result = n
  741. # TODO: This is very inefficient. It traverses the node, looking for nkYieldStmt.
  742. case n.kind
  743. of nkReturnStmt:
  744. # We're somewhere in try, transform to finally unrolling
  745. assert(ctx.nearestFinally != 0)
  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, nkSinkAsgn}: 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