transf.nim 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements the transformator. It transforms the syntax tree
  10. # to ease the work of the code generators. Does some transformations:
  11. #
  12. # * inlines iterators
  13. # * inlines constants
  14. # * performs constant folding
  15. # * converts "continue" to "break"; disambiguates "break"
  16. # * introduces method dispatchers
  17. # * performs lambda lifting for closure support
  18. # * transforms 'defer' into a 'try finally' statement
  19. import std / tables
  20. import
  21. options, ast, astalgo, trees, msgs,
  22. idents, renderer, types, semfold, magicsys, cgmeth,
  23. lowerings, liftlocals,
  24. modulegraphs, lineinfos
  25. when defined(nimPreviewSlimSystem):
  26. import std/assertions
  27. type
  28. TransformFlag* = enum
  29. useCache, keepOpenArrayConversions, force
  30. TransformFlags* = set[TransformFlag]
  31. proc transformBody*(g: ModuleGraph; idgen: IdGenerator; prc: PSym; flags: TransformFlags): PNode
  32. import closureiters, lambdalifting
  33. type
  34. PTransCon = ref object # part of TContext; stackable
  35. mapping: Table[ItemId, PNode] # mapping from symbols to nodes
  36. owner: PSym # current owner
  37. forStmt: PNode # current for stmt
  38. forLoopBody: PNode # transformed for loop body
  39. yieldStmts: int # we count the number of yield statements,
  40. # because we need to introduce new variables
  41. # if we encounter the 2nd yield statement
  42. next: PTransCon # for stacking
  43. PTransf = ref object
  44. module: PSym
  45. transCon: PTransCon # top of a TransCon stack
  46. inlining: int # > 0 if we are in inlining context (copy vars)
  47. contSyms, breakSyms: seq[PSym] # to transform 'continue' and 'break'
  48. deferDetected, tooEarly: bool
  49. isIntroducingNewLocalVars: bool # true if we are in `introducingNewLocalVars` (don't transform yields)
  50. flags: TransformFlags
  51. graph: ModuleGraph
  52. idgen: IdGenerator
  53. proc newTransNode(a: PNode): PNode {.inline.} =
  54. result = shallowCopy(a)
  55. proc newTransNode(kind: TNodeKind, info: TLineInfo,
  56. sons: int): PNode {.inline.} =
  57. var x = newNodeI(kind, info)
  58. newSeq(x.sons, sons)
  59. result = x
  60. proc newTransNode(kind: TNodeKind, n: PNode,
  61. sons: int): PNode {.inline.} =
  62. var x = newNodeIT(kind, n.info, n.typ)
  63. newSeq(x.sons, sons)
  64. # x.flags = n.flags
  65. result = x
  66. proc newTransCon(owner: PSym): PTransCon =
  67. assert owner != nil
  68. result = PTransCon(mapping: initTable[ItemId, PNode](), owner: owner)
  69. proc pushTransCon(c: PTransf, t: PTransCon) =
  70. t.next = c.transCon
  71. c.transCon = t
  72. proc popTransCon(c: PTransf) =
  73. if (c.transCon == nil): internalError(c.graph.config, "popTransCon")
  74. c.transCon = c.transCon.next
  75. proc getCurrOwner(c: PTransf): PSym =
  76. if c.transCon != nil: result = c.transCon.owner
  77. else: result = c.module
  78. proc newTemp(c: PTransf, typ: PType, info: TLineInfo): PNode =
  79. let r = newSym(skTemp, getIdent(c.graph.cache, genPrefix), c.idgen, getCurrOwner(c), info)
  80. r.typ = typ #skipTypes(typ, {tyGenericInst, tyAlias, tySink})
  81. incl(r.flags, sfFromGeneric)
  82. let owner = getCurrOwner(c)
  83. if owner.isIterator and not c.tooEarly:
  84. result = freshVarForClosureIter(c.graph, r, c.idgen, owner)
  85. else:
  86. result = newSymNode(r)
  87. proc transform(c: PTransf, n: PNode): PNode
  88. proc transformSons(c: PTransf, n: PNode): PNode =
  89. result = newTransNode(n)
  90. for i in 0..<n.len:
  91. result[i] = transform(c, n[i])
  92. proc newAsgnStmt(c: PTransf, kind: TNodeKind, le: PNode, ri: PNode; isFirstWrite: bool): PNode =
  93. result = newTransNode(kind, ri.info, 2)
  94. result[0] = le
  95. if isFirstWrite:
  96. le.flags.incl nfFirstWrite
  97. result[1] = ri
  98. proc transformSymAux(c: PTransf, n: PNode): PNode =
  99. let s = n.sym
  100. if s.typ != nil and s.typ.callConv == ccClosure:
  101. if s.kind in routineKinds:
  102. discard transformBody(c.graph, c.idgen, s, {useCache}+c.flags)
  103. if s.kind == skIterator:
  104. if c.tooEarly: return n
  105. else: return liftIterSym(c.graph, n, c.idgen, getCurrOwner(c))
  106. elif s.kind in {skProc, skFunc, skConverter, skMethod} and not c.tooEarly:
  107. # top level .closure procs are still somewhat supported for 'Nake':
  108. return makeClosure(c.graph, c.idgen, s, nil, n.info)
  109. #elif n.sym.kind in {skVar, skLet} and n.sym.typ.callConv == ccClosure:
  110. # echo n.info, " come heer for ", c.tooEarly
  111. # if not c.tooEarly:
  112. var b: PNode
  113. var tc = c.transCon
  114. if sfBorrow in s.flags and s.kind in routineKinds:
  115. # simply exchange the symbol:
  116. var s = s
  117. while true:
  118. # Skips over all borrowed procs getting the last proc symbol without an implementation
  119. let body = getBody(c.graph, s)
  120. if body.kind == nkSym and sfBorrow in body.sym.flags and getBody(c.graph, body.sym).kind == nkSym:
  121. s = body.sym
  122. else:
  123. break
  124. b = getBody(c.graph, s)
  125. if b.kind != nkSym: internalError(c.graph.config, n.info, "wrong AST for borrowed symbol")
  126. b = newSymNode(b.sym, n.info)
  127. elif c.inlining > 0:
  128. # see bug #13596: we use ref-based equality in the DFA for destruction
  129. # injections so we need to ensure unique nodes after iterator inlining
  130. # which can lead to duplicated for loop bodies! Consider:
  131. #[
  132. while remaining > 0:
  133. if ending == nil:
  134. yield ms
  135. break
  136. ...
  137. yield ms
  138. ]#
  139. b = newSymNode(n.sym, n.info)
  140. else:
  141. b = n
  142. while tc != nil:
  143. result = getOrDefault(tc.mapping, b.sym.itemId)
  144. if result != nil:
  145. # this slightly convoluted way ensures the line info stays correct:
  146. if result.kind == nkSym:
  147. result = copyNode(result)
  148. result.info = n.info
  149. return
  150. tc = tc.next
  151. result = b
  152. proc transformSym(c: PTransf, n: PNode): PNode =
  153. result = transformSymAux(c, n)
  154. proc freshVar(c: PTransf; v: PSym): PNode =
  155. let owner = getCurrOwner(c)
  156. if owner.isIterator and not c.tooEarly:
  157. result = freshVarForClosureIter(c.graph, v, c.idgen, owner)
  158. else:
  159. var newVar = copySym(v, c.idgen)
  160. incl(newVar.flags, sfFromGeneric)
  161. newVar.owner = owner
  162. result = newSymNode(newVar)
  163. proc transformVarSection(c: PTransf, v: PNode): PNode =
  164. result = newTransNode(v)
  165. for i in 0..<v.len:
  166. var it = v[i]
  167. if it.kind == nkCommentStmt:
  168. result[i] = it
  169. elif it.kind == nkIdentDefs:
  170. var vn = it[0]
  171. if vn.kind == nkPragmaExpr: vn = vn[0]
  172. if vn.kind == nkSym:
  173. internalAssert(c.graph.config, it.len == 3)
  174. let x = freshVar(c, vn.sym)
  175. c.transCon.mapping[vn.sym.itemId] = x
  176. var defs = newTransNode(nkIdentDefs, it.info, 3)
  177. if importantComments(c.graph.config):
  178. # keep documentation information:
  179. defs.comment = it.comment
  180. defs[0] = x
  181. defs[1] = it[1]
  182. defs[2] = transform(c, it[2])
  183. if x.kind == nkSym: x.sym.ast = defs[2]
  184. result[i] = defs
  185. else:
  186. # has been transformed into 'param.x' for closure iterators, so just
  187. # transform it:
  188. result[i] = transform(c, it)
  189. else:
  190. if it.kind != nkVarTuple:
  191. internalError(c.graph.config, it.info, "transformVarSection: not nkVarTuple")
  192. var defs = newTransNode(it.kind, it.info, it.len)
  193. for j in 0..<it.len-2:
  194. if it[j].kind == nkSym:
  195. let x = freshVar(c, it[j].sym)
  196. c.transCon.mapping[it[j].sym.itemId] = x
  197. defs[j] = x
  198. else:
  199. defs[j] = transform(c, it[j])
  200. assert(it[^2].kind == nkEmpty)
  201. defs[^2] = newNodeI(nkEmpty, it.info)
  202. defs[^1] = transform(c, it[^1])
  203. result[i] = defs
  204. proc transformConstSection(c: PTransf, v: PNode): PNode =
  205. result = v
  206. when false:
  207. result = newTransNode(v)
  208. for i in 0..<v.len:
  209. var it = v[i]
  210. if it.kind == nkCommentStmt:
  211. result[i] = it
  212. else:
  213. if it.kind != nkConstDef: internalError(c.graph.config, it.info, "transformConstSection")
  214. if it[0].kind != nkSym:
  215. debug it[0]
  216. internalError(c.graph.config, it.info, "transformConstSection")
  217. result[i] = it
  218. proc hasContinue(n: PNode): bool =
  219. case n.kind
  220. of nkEmpty..nkNilLit, nkForStmt, nkParForStmt, nkWhileStmt: result = false
  221. of nkContinueStmt: result = true
  222. else:
  223. result = false
  224. for i in 0..<n.len:
  225. if hasContinue(n[i]): return true
  226. proc newLabel(c: PTransf, n: PNode): PSym =
  227. result = newSym(skLabel, getIdent(c.graph.cache, genPrefix), c.idgen, getCurrOwner(c), n.info)
  228. proc transformBlock(c: PTransf, n: PNode): PNode =
  229. var labl: PSym
  230. if c.inlining > 0:
  231. labl = newLabel(c, n[0])
  232. c.transCon.mapping[n[0].sym.itemId] = newSymNode(labl)
  233. else:
  234. labl =
  235. if n[0].kind != nkEmpty:
  236. n[0].sym # already named block? -> Push symbol on the stack
  237. else:
  238. newLabel(c, n)
  239. c.breakSyms.add(labl)
  240. result = transformSons(c, n)
  241. discard c.breakSyms.pop
  242. result[0] = newSymNode(labl)
  243. proc transformLoopBody(c: PTransf, n: PNode): PNode =
  244. # What if it contains "continue" and "break"? "break" needs
  245. # an explicit label too, but not the same!
  246. # We fix this here by making every 'break' belong to its enclosing loop
  247. # and changing all breaks that belong to a 'block' by annotating it with
  248. # a label (if it hasn't one already).
  249. if hasContinue(n):
  250. let labl = newLabel(c, n)
  251. c.contSyms.add(labl)
  252. result = newTransNode(nkBlockStmt, n.info, 2)
  253. result[0] = newSymNode(labl)
  254. result[1] = transform(c, n)
  255. discard c.contSyms.pop()
  256. else:
  257. result = transform(c, n)
  258. proc transformWhile(c: PTransf; n: PNode): PNode =
  259. if c.inlining > 0:
  260. result = transformSons(c, n)
  261. else:
  262. let labl = newLabel(c, n)
  263. c.breakSyms.add(labl)
  264. result = newTransNode(nkBlockStmt, n.info, 2)
  265. result[0] = newSymNode(labl)
  266. var body = newTransNode(n)
  267. for i in 0..<n.len-1:
  268. body[i] = transform(c, n[i])
  269. body[^1] = transformLoopBody(c, n[^1])
  270. result[1] = body
  271. discard c.breakSyms.pop
  272. proc transformBreak(c: PTransf, n: PNode): PNode =
  273. result = transformSons(c, n)
  274. if n[0].kind == nkEmpty and c.breakSyms.len > 0:
  275. let labl = c.breakSyms[c.breakSyms.high]
  276. result[0] = newSymNode(labl)
  277. proc introduceNewLocalVars(c: PTransf, n: PNode): PNode =
  278. case n.kind
  279. of nkSym:
  280. result = transformSym(c, n)
  281. of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit:
  282. # nothing to be done for leaves:
  283. result = n
  284. of nkVarSection, nkLetSection:
  285. result = transformVarSection(c, n)
  286. of nkClosure:
  287. # it can happen that for-loop-inlining produced a fresh
  288. # set of variables, including some computed environment
  289. # (bug #2604). We need to patch this environment here too:
  290. let a = n[1]
  291. if a.kind == nkSym:
  292. n[1] = transformSymAux(c, a)
  293. return n
  294. of nkProcDef: # todo optimize nosideeffects?
  295. result = newTransNode(n)
  296. let x = newSymNode(copySym(n[namePos].sym, c.idgen))
  297. c.transCon.mapping[n[namePos].sym.itemId] = x
  298. result[namePos] = x # we have to copy proc definitions for iters
  299. for i in 1..<n.len:
  300. result[i] = introduceNewLocalVars(c, n[i])
  301. result[namePos].sym.ast = result
  302. else:
  303. result = newTransNode(n)
  304. for i in 0..<n.len:
  305. result[i] = introduceNewLocalVars(c, n[i])
  306. proc transformAsgn(c: PTransf, n: PNode): PNode =
  307. let rhs = n[1]
  308. if rhs.kind != nkTupleConstr:
  309. return transformSons(c, n)
  310. # Unpack the tuple assignment into N temporary variables and then pack them
  311. # into a tuple: this allows us to get the correct results even when the rhs
  312. # depends on the value of the lhs
  313. let letSection = newTransNode(nkLetSection, n.info, rhs.len)
  314. let newTupleConstr = newTransNode(nkTupleConstr, n.info, rhs.len)
  315. for i, field in rhs:
  316. let val = if field.kind == nkExprColonExpr: field[1] else: field
  317. let def = newTransNode(nkIdentDefs, field.info, 3)
  318. def[0] = newTemp(c, val.typ, field.info)
  319. def[1] = newNodeI(nkEmpty, field.info)
  320. def[2] = transform(c, val)
  321. letSection[i] = def
  322. # NOTE: We assume the constructor fields are in the correct order for the
  323. # given tuple type
  324. newTupleConstr[i] = def[0]
  325. newTupleConstr.typ = rhs.typ
  326. let asgnNode = newTransNode(nkAsgn, n.info, 2)
  327. asgnNode[0] = transform(c, n[0])
  328. asgnNode[1] = newTupleConstr
  329. result = newTransNode(nkStmtList, n.info, 2)
  330. result[0] = letSection
  331. result[1] = asgnNode
  332. proc transformYield(c: PTransf, n: PNode): PNode =
  333. proc asgnTo(lhs: PNode, rhs: PNode): PNode =
  334. # Choose the right assignment instruction according to the given ``lhs``
  335. # node since it may not be a nkSym (a stack-allocated skForVar) but a
  336. # nkDotExpr (a heap-allocated slot into the envP block)
  337. case lhs.kind
  338. of nkSym:
  339. internalAssert c.graph.config, lhs.sym.kind == skForVar
  340. result = newAsgnStmt(c, nkFastAsgn, lhs, rhs, false)
  341. of nkDotExpr:
  342. result = newAsgnStmt(c, nkAsgn, lhs, rhs, false)
  343. else:
  344. result = nil
  345. internalAssert c.graph.config, false
  346. result = newTransNode(nkStmtList, n.info, 0)
  347. var e = n[0]
  348. # c.transCon.forStmt.len == 3 means that there is one for loop variable
  349. # and thus no tuple unpacking:
  350. if e.typ.isNil: return result # can happen in nimsuggest for unknown reasons
  351. if c.transCon.forStmt.len != 3:
  352. e = skipConv(e)
  353. if e.kind == nkTupleConstr:
  354. for i in 0..<e.len:
  355. var v = e[i]
  356. if v.kind == nkExprColonExpr: v = v[1]
  357. if c.transCon.forStmt[i].kind == nkVarTuple:
  358. for j in 0..<c.transCon.forStmt[i].len-1:
  359. let lhs = c.transCon.forStmt[i][j]
  360. let rhs = transform(c, newTupleAccess(c.graph, v, j))
  361. result.add(asgnTo(lhs, rhs))
  362. else:
  363. let lhs = c.transCon.forStmt[i]
  364. let rhs = transform(c, v)
  365. result.add(asgnTo(lhs, rhs))
  366. elif e.kind notin {nkAddr, nkHiddenAddr}: # no need to generate temp for address operation
  367. # TODO do not use temp for nodes which cannot have side-effects
  368. var tmp = newTemp(c, e.typ, e.info)
  369. let v = newNodeI(nkVarSection, e.info)
  370. v.addVar(tmp, e)
  371. result.add transform(c, v)
  372. for i in 0..<c.transCon.forStmt.len - 2:
  373. let lhs = c.transCon.forStmt[i]
  374. let rhs = transform(c, newTupleAccess(c.graph, tmp, i))
  375. result.add(asgnTo(lhs, rhs))
  376. else:
  377. for i in 0..<c.transCon.forStmt.len - 2:
  378. let lhs = c.transCon.forStmt[i]
  379. let rhs = transform(c, newTupleAccess(c.graph, e, i))
  380. result.add(asgnTo(lhs, rhs))
  381. else:
  382. if c.transCon.forStmt[0].kind == nkVarTuple:
  383. var notLiteralTuple = false # we don't generate temp for tuples with const value: (1, 2, 3)
  384. let ev = e.skipConv
  385. if ev.kind == nkTupleConstr:
  386. for i in ev:
  387. if not isConstExpr(i):
  388. notLiteralTuple = true
  389. break
  390. else:
  391. notLiteralTuple = true
  392. if e.kind notin {nkAddr, nkHiddenAddr} and notLiteralTuple:
  393. # TODO do not use temp for nodes which cannot have side-effects
  394. var tmp = newTemp(c, e.typ, e.info)
  395. let v = newNodeI(nkVarSection, e.info)
  396. v.addVar(tmp, e)
  397. result.add transform(c, v)
  398. for i in 0..<c.transCon.forStmt[0].len-1:
  399. let lhs = c.transCon.forStmt[0][i]
  400. let rhs = transform(c, newTupleAccess(c.graph, tmp, i))
  401. result.add(asgnTo(lhs, rhs))
  402. else:
  403. for i in 0..<c.transCon.forStmt[0].len-1:
  404. let lhs = c.transCon.forStmt[0][i]
  405. let rhs = transform(c, newTupleAccess(c.graph, e, i))
  406. result.add(asgnTo(lhs, rhs))
  407. else:
  408. let lhs = c.transCon.forStmt[0]
  409. let rhs = transform(c, e)
  410. result.add(asgnTo(lhs, rhs))
  411. # bug #23536; note that the info of forLoopBody should't change
  412. for idx in 0 ..< result.len:
  413. var changeNode = result[idx]
  414. changeNode.info = c.transCon.forStmt.info
  415. for i, child in changeNode:
  416. child.info = changeNode.info
  417. inc(c.transCon.yieldStmts)
  418. if c.transCon.yieldStmts <= 1:
  419. # common case
  420. result.add(c.transCon.forLoopBody)
  421. else:
  422. # we need to introduce new local variables:
  423. c.isIntroducingNewLocalVars = true # don't transform yields when introducing new local vars
  424. result.add(introduceNewLocalVars(c, c.transCon.forLoopBody))
  425. c.isIntroducingNewLocalVars = false
  426. proc transformAddrDeref(c: PTransf, n: PNode, kinds: TNodeKinds): PNode =
  427. result = transformSons(c, n)
  428. # inlining of 'var openarray' iterators; bug #19977
  429. if n.typ.kind != tyOpenArray and (c.graph.config.backend == backendCpp or sfCompileToCpp in c.module.flags): return
  430. var n = result
  431. case n[0].kind
  432. of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
  433. var m = n[0][0]
  434. if m.kind in kinds:
  435. # addr ( nkConv ( deref ( x ) ) ) --> nkConv(x)
  436. n[0][0] = m[0]
  437. result = n[0]
  438. if n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  439. result.typ = n.typ
  440. elif n.typ.skipTypes(abstractInst).kind in {tyVar}:
  441. result.typ = toVar(result.typ, n.typ.skipTypes(abstractInst).kind, c.idgen)
  442. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  443. var m = n[0][1]
  444. if m.kind in kinds:
  445. # addr ( nkConv ( deref ( x ) ) ) --> nkConv(x)
  446. n[0][1] = m[0]
  447. result = n[0]
  448. if n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  449. result.typ = n.typ
  450. elif n.typ.skipTypes(abstractInst).kind in {tyVar}:
  451. result.typ = toVar(result.typ, n.typ.skipTypes(abstractInst).kind, c.idgen)
  452. else:
  453. if n[0].kind in kinds:
  454. # addr ( deref ( x )) --> x
  455. result = n[0][0]
  456. if n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  457. result.typ = n.typ
  458. proc generateThunk(c: PTransf; prc: PNode, dest: PType): PNode =
  459. ## Converts 'prc' into '(thunk, nil)' so that it's compatible with
  460. ## a closure.
  461. # we cannot generate a proper thunk here for GC-safety reasons
  462. # (see internal documentation):
  463. if jsNoLambdaLifting in c.graph.config.legacyFeatures and c.graph.config.backend == backendJs: return prc
  464. result = newNodeIT(nkClosure, prc.info, dest)
  465. var conv = newNodeIT(nkHiddenSubConv, prc.info, dest)
  466. conv.add(newNodeI(nkEmpty, prc.info))
  467. conv.add(prc)
  468. if prc.kind == nkClosure:
  469. internalError(c.graph.config, prc.info, "closure to closure created")
  470. result.add(conv)
  471. result.add(newNodeIT(nkNilLit, prc.info, getSysType(c.graph, prc.info, tyNil)))
  472. proc transformConv(c: PTransf, n: PNode): PNode =
  473. # numeric types need range checks:
  474. var dest = skipTypes(n.typ, abstractVarRange)
  475. var source = skipTypes(n[1].typ, abstractVarRange)
  476. case dest.kind
  477. of tyInt..tyInt64, tyEnum, tyChar, tyUInt8..tyUInt32:
  478. # we don't include uint and uint64 here as these are no ordinal types ;-)
  479. if not isOrdinalType(source):
  480. # float -> int conversions. ugh.
  481. result = transformSons(c, n)
  482. elif firstOrd(c.graph.config, n.typ) <= firstOrd(c.graph.config, n[1].typ) and
  483. lastOrd(c.graph.config, n[1].typ) <= lastOrd(c.graph.config, n.typ):
  484. # BUGFIX: simply leave n as it is; we need a nkConv node,
  485. # but no range check:
  486. result = transformSons(c, n)
  487. else:
  488. # generate a range check:
  489. if dest.kind == tyInt64 or source.kind == tyInt64:
  490. result = newTransNode(nkChckRange64, n, 3)
  491. else:
  492. result = newTransNode(nkChckRange, n, 3)
  493. dest = skipTypes(n.typ, abstractVar)
  494. result[0] = transform(c, n[1])
  495. result[1] = newIntTypeNode(firstOrd(c.graph.config, dest), dest)
  496. result[2] = newIntTypeNode(lastOrd(c.graph.config, dest), dest)
  497. of tyFloat..tyFloat128:
  498. # XXX int64 -> float conversion?
  499. if skipTypes(n.typ, abstractVar).kind == tyRange:
  500. result = newTransNode(nkChckRangeF, n, 3)
  501. dest = skipTypes(n.typ, abstractVar)
  502. result[0] = transform(c, n[1])
  503. result[1] = copyTree(dest.n[0])
  504. result[2] = copyTree(dest.n[1])
  505. else:
  506. result = transformSons(c, n)
  507. of tyOpenArray, tyVarargs:
  508. if keepOpenArrayConversions in c.flags:
  509. result = transformSons(c, n)
  510. else:
  511. result = transform(c, n[1])
  512. #result = transformSons(c, n)
  513. result.typ = takeType(n.typ, n[1].typ, c.graph, c.idgen)
  514. #echo n.info, " came here and produced ", typeToString(result.typ),
  515. # " from ", typeToString(n.typ), " and ", typeToString(n[1].typ)
  516. of tyCstring:
  517. if source.kind == tyString:
  518. result = newTransNode(nkStringToCString, n, 1)
  519. result[0] = transform(c, n[1])
  520. else:
  521. result = transformSons(c, n)
  522. of tyString:
  523. if source.kind == tyCstring:
  524. result = newTransNode(nkCStringToString, n, 1)
  525. result[0] = transform(c, n[1])
  526. else:
  527. result = transformSons(c, n)
  528. of tyRef, tyPtr:
  529. dest = skipTypes(dest, abstractPtrs)
  530. source = skipTypes(source, abstractPtrs)
  531. if source.kind == tyObject:
  532. var diff = inheritanceDiff(dest, source)
  533. if diff < 0:
  534. result = newTransNode(nkObjUpConv, n, 1)
  535. result[0] = transform(c, n[1])
  536. elif diff > 0 and diff != high(int):
  537. result = newTransNode(nkObjDownConv, n, 1)
  538. result[0] = transform(c, n[1])
  539. else:
  540. result = transform(c, n[1])
  541. result.typ = n.typ
  542. else:
  543. result = transformSons(c, n)
  544. of tyObject:
  545. var diff = inheritanceDiff(dest, source)
  546. if diff < 0:
  547. result = newTransNode(nkObjUpConv, n, 1)
  548. result[0] = transform(c, n[1])
  549. elif diff > 0 and diff != high(int):
  550. result = newTransNode(nkObjDownConv, n, 1)
  551. result[0] = transform(c, n[1])
  552. else:
  553. result = transform(c, n[1])
  554. result.typ = n.typ
  555. of tyGenericParam, tyOrdinal:
  556. result = transform(c, n[1])
  557. # happens sometimes for generated assignments, etc.
  558. of tyProc:
  559. result = transformSons(c, n)
  560. if dest.callConv == ccClosure and source.callConv == ccNimCall:
  561. result = generateThunk(c, result[1], dest)
  562. else:
  563. result = transformSons(c, n)
  564. type
  565. TPutArgInto = enum
  566. paDirectMapping, paFastAsgn, paFastAsgnTakeTypeFromArg
  567. paVarAsgn, paComplexOpenarray, paViaIndirection
  568. proc putArgInto(arg: PNode, formal: PType): TPutArgInto =
  569. # This analyses how to treat the mapping "formal <-> arg" in an
  570. # inline context.
  571. if formal.kind == tyTypeDesc: return paDirectMapping
  572. if skipTypes(formal, abstractInst).kind in {tyOpenArray, tyVarargs}:
  573. case arg.kind
  574. of nkStmtListExpr:
  575. return paComplexOpenarray
  576. of nkBracket:
  577. return paFastAsgnTakeTypeFromArg
  578. else:
  579. # XXX incorrect, causes #13417 when `arg` has side effects.
  580. return paDirectMapping
  581. case arg.kind
  582. of nkEmpty..nkNilLit:
  583. result = paDirectMapping
  584. of nkDotExpr, nkDerefExpr, nkHiddenDeref, nkAddr, nkHiddenAddr:
  585. result = putArgInto(arg[0], formal)
  586. #if result == paViaIndirection: result = paFastAsgn
  587. of nkCurly, nkBracket:
  588. for i in 0..<arg.len:
  589. if putArgInto(arg[i], formal) != paDirectMapping:
  590. return paFastAsgn
  591. result = paDirectMapping
  592. of nkPar, nkTupleConstr, nkObjConstr:
  593. for i in 0..<arg.len:
  594. let a = if arg[i].kind == nkExprColonExpr: arg[i][1]
  595. else: arg[0]
  596. if putArgInto(a, formal) != paDirectMapping:
  597. return paFastAsgn
  598. result = paDirectMapping
  599. of nkBracketExpr:
  600. if skipTypes(formal, abstractInst).kind in {tyVar, tyLent}: result = paVarAsgn
  601. else: result = paViaIndirection
  602. else:
  603. if skipTypes(formal, abstractInst).kind in {tyVar, tyLent}: result = paVarAsgn
  604. else: result = paFastAsgn
  605. proc findWrongOwners(c: PTransf, n: PNode) =
  606. if n.kind == nkVarSection:
  607. let x = n[0][0]
  608. if x.kind == nkSym and x.sym.owner != getCurrOwner(c):
  609. internalError(c.graph.config, x.info, "bah " & x.sym.name.s & " " &
  610. x.sym.owner.name.s & " " & getCurrOwner(c).name.s)
  611. else:
  612. for i in 0..<n.safeLen: findWrongOwners(c, n[i])
  613. proc isSimpleIteratorVar(c: PTransf; iter: PSym; call: PNode; owner: PSym): bool =
  614. proc rec(n: PNode; owner: PSym; dangerousYields: var int) =
  615. case n.kind
  616. of nkEmpty..nkNilLit: discard
  617. of nkYieldStmt:
  618. if n[0].kind == nkSym and n[0].sym.owner == owner:
  619. discard "good: yield a single variable that we own"
  620. else:
  621. inc dangerousYields
  622. else:
  623. for c in n: rec(c, owner, dangerousYields)
  624. proc recSym(n: PNode; owner: PSym; sameOwner: var bool) =
  625. case n.kind
  626. of {nkEmpty..nkNilLit} - {nkSym}: discard
  627. of nkSym:
  628. if n.sym.owner != owner:
  629. sameOwner = false
  630. else:
  631. for c in n: recSym(c, owner, sameOwner)
  632. var dangerousYields = 0
  633. rec(getBody(c.graph, iter), iter, dangerousYields)
  634. result = dangerousYields == 0
  635. # the parameters should be owned by the owner
  636. # bug #22237
  637. for i in 1..<call.len:
  638. recSym(call[i], owner, result)
  639. template destructor(t: PType): PSym = getAttachedOp(c.graph, t, attachedDestructor)
  640. proc transformFor(c: PTransf, n: PNode): PNode =
  641. # generate access statements for the parameters (unless they are constant)
  642. # put mapping from formal parameters to actual parameters
  643. if n.kind != nkForStmt: internalError(c.graph.config, n.info, "transformFor")
  644. var call = n[^2]
  645. let labl = newLabel(c, n)
  646. result = newTransNode(nkBlockStmt, n.info, 2)
  647. result[0] = newSymNode(labl)
  648. if call.typ.isNil:
  649. # see bug #3051
  650. result[1] = newNode(nkEmpty)
  651. return result
  652. c.breakSyms.add(labl)
  653. if call.kind notin nkCallKinds or call[0].kind != nkSym or
  654. call[0].typ.skipTypes(abstractInst).callConv == ccClosure:
  655. result[1] = n
  656. result[1][^1] = transformLoopBody(c, n[^1])
  657. result[1][^2] = transform(c, n[^2])
  658. result[1] = lambdalifting.liftForLoop(c.graph, result[1], c.idgen, getCurrOwner(c))
  659. discard c.breakSyms.pop
  660. return result
  661. #echo "transforming: ", renderTree(n)
  662. var stmtList = newTransNode(nkStmtList, n.info, 0)
  663. result[1] = stmtList
  664. var loopBody = transformLoopBody(c, n[^1])
  665. discard c.breakSyms.pop
  666. let iter = call[0].sym
  667. var v = newNodeI(nkVarSection, n.info)
  668. for i in 0..<n.len - 2:
  669. if n[i].kind == nkVarTuple:
  670. for j in 0..<n[i].len-1:
  671. addVar(v, copyTree(n[i][j])) # declare new vars
  672. else:
  673. if n[i].kind == nkSym and isSimpleIteratorVar(c, iter, call, n[i].sym.owner):
  674. incl n[i].sym.flags, sfCursor
  675. addVar(v, copyTree(n[i])) # declare new vars
  676. stmtList.add(v)
  677. # Bugfix: inlined locals belong to the invoking routine, not to the invoked
  678. # iterator!
  679. var newC = newTransCon(getCurrOwner(c))
  680. newC.forStmt = n
  681. newC.forLoopBody = loopBody
  682. # this can fail for 'nimsuggest' and 'check':
  683. if iter.kind != skIterator: return result
  684. # generate access statements for the parameters (unless they are constant)
  685. pushTransCon(c, newC)
  686. for i in 1..<call.len:
  687. var arg = transform(c, call[i])
  688. let ff = skipTypes(iter.typ, abstractInst)
  689. # can happen for 'nim check':
  690. if i >= ff.n.len: return result
  691. var formal = ff.n[i].sym
  692. let pa = putArgInto(arg, formal.typ)
  693. case pa
  694. of paDirectMapping:
  695. newC.mapping[formal.itemId] = arg
  696. of paFastAsgn, paFastAsgnTakeTypeFromArg:
  697. var t = formal.typ
  698. if pa == paFastAsgnTakeTypeFromArg:
  699. t = arg.typ
  700. elif formal.ast != nil and formal.ast.typ.destructor != nil and t.destructor == nil:
  701. t = formal.ast.typ # better use the type that actually has a destructor.
  702. elif t.destructor == nil and arg.typ.destructor != nil:
  703. t = arg.typ
  704. # generate a temporary and produce an assignment statement:
  705. var temp = newTemp(c, t, formal.info)
  706. #incl(temp.sym.flags, sfCursor)
  707. addVar(v, temp)
  708. stmtList.add(newAsgnStmt(c, nkFastAsgn, temp, arg, true))
  709. newC.mapping[formal.itemId] = temp
  710. of paVarAsgn:
  711. assert(skipTypes(formal.typ, abstractInst).kind in {tyVar, tyLent})
  712. newC.mapping[formal.itemId] = arg
  713. # XXX BUG still not correct if the arg has a side effect!
  714. of paViaIndirection:
  715. let t = formal.typ
  716. let vt = makeVarType(t.owner, t, c.idgen)
  717. vt.flags.incl tfVarIsPtr
  718. var temp = newTemp(c, vt, formal.info)
  719. addVar(v, temp)
  720. var addrExp = newNodeIT(nkHiddenAddr, formal.info, makeVarType(t.owner, t, c.idgen, tyPtr))
  721. addrExp.add(arg)
  722. stmtList.add(newAsgnStmt(c, nkFastAsgn, temp, addrExp, true))
  723. newC.mapping[formal.itemId] = newDeref(temp)
  724. of paComplexOpenarray:
  725. # arrays will deep copy here (pretty bad).
  726. var temp = newTemp(c, arg.typ, formal.info)
  727. addVar(v, temp)
  728. stmtList.add(newAsgnStmt(c, nkFastAsgn, temp, arg, true))
  729. newC.mapping[formal.itemId] = temp
  730. let body = transformBody(c.graph, c.idgen, iter, {useCache}+c.flags)
  731. pushInfoContext(c.graph.config, n.info)
  732. inc(c.inlining)
  733. stmtList.add(transform(c, body))
  734. #findWrongOwners(c, stmtList.PNode)
  735. dec(c.inlining)
  736. popInfoContext(c.graph.config)
  737. popTransCon(c)
  738. # echo "transformed: ", stmtList.renderTree
  739. proc transformCase(c: PTransf, n: PNode): PNode =
  740. # removes `elif` branches of a case stmt
  741. # adds ``else: nil`` if needed for the code generator
  742. result = newTransNode(nkCaseStmt, n, 0)
  743. var ifs: PNode = nil
  744. for it in n:
  745. var e = transform(c, it)
  746. case it.kind
  747. of nkElifBranch:
  748. if ifs == nil:
  749. # Generate the right node depending on whether `n` is used as a stmt or
  750. # as an expr
  751. let kind = if n.typ != nil: nkIfExpr else: nkIfStmt
  752. ifs = newTransNode(kind, it.info, 0)
  753. ifs.typ = n.typ
  754. ifs.add(e)
  755. of nkElse:
  756. if ifs == nil: result.add(e)
  757. else: ifs.add(e)
  758. else:
  759. result.add(e)
  760. if ifs != nil:
  761. var elseBranch = newTransNode(nkElse, n.info, 1)
  762. elseBranch[0] = ifs
  763. result.add(elseBranch)
  764. elif result.lastSon.kind != nkElse and not (
  765. skipTypes(n[0].typ, abstractVarRange).kind in
  766. {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt64}):
  767. # fix a stupid code gen bug by normalizing:
  768. var elseBranch = newTransNode(nkElse, n.info, 1)
  769. elseBranch[0] = newTransNode(nkNilLit, n.info, 0)
  770. result.add(elseBranch)
  771. proc transformArrayAccess(c: PTransf, n: PNode): PNode =
  772. # XXX this is really bad; transf should use a proper AST visitor
  773. if n[0].kind == nkSym and n[0].sym.kind == skType:
  774. result = n
  775. else:
  776. result = newTransNode(n)
  777. for i in 0..<n.len:
  778. result[i] = transform(c, skipConv(n[i]))
  779. proc getMergeOp(n: PNode): PSym =
  780. case n.kind
  781. of nkCall, nkHiddenCallConv, nkCommand, nkInfix, nkPrefix, nkPostfix,
  782. nkCallStrLit:
  783. if n[0].kind == nkSym and n[0].sym.magic == mConStrStr:
  784. result = n[0].sym
  785. else:
  786. result = nil
  787. else: result = nil
  788. proc flattenTreeAux(d, a: PNode, op: PSym) =
  789. ## Optimizes away the `&` calls in the children nodes and
  790. ## lifts the leaf nodes to the same level as `op2`.
  791. let op2 = getMergeOp(a)
  792. if op2 != nil and
  793. (op2.id == op.id or op.magic != mNone and op2.magic == op.magic):
  794. for i in 1..<a.len: flattenTreeAux(d, a[i], op)
  795. else:
  796. d.add copyTree(a)
  797. proc flattenTree(root: PNode): PNode =
  798. let op = getMergeOp(root)
  799. if op != nil:
  800. result = copyNode(root)
  801. result.add copyTree(root[0])
  802. flattenTreeAux(result, root, op)
  803. else:
  804. result = root
  805. proc transformCall(c: PTransf, n: PNode): PNode =
  806. var n = flattenTree(n)
  807. let op = getMergeOp(n)
  808. let magic = getMagic(n)
  809. if op != nil and op.magic != mNone and n.len >= 3:
  810. result = newTransNode(nkCall, n, 0)
  811. result.add(transform(c, n[0]))
  812. var j = 1
  813. while j < n.len:
  814. var a = transform(c, n[j])
  815. inc(j)
  816. if isConstExpr(a):
  817. while (j < n.len):
  818. let b = transform(c, n[j])
  819. if not isConstExpr(b): break
  820. a = evalOp(op.magic, n, a, b, nil, c.idgen, c.graph)
  821. inc(j)
  822. result.add(a)
  823. if result.len == 2: result = result[1]
  824. elif magic in {mNBindSym, mTypeOf, mRunnableExamples}:
  825. # for bindSym(myconst) we MUST NOT perform constant folding:
  826. result = n
  827. elif magic == mProcCall:
  828. # but do not change to its dispatcher:
  829. result = transformSons(c, n[1])
  830. elif magic == mStrToStr:
  831. result = transform(c, n[1])
  832. else:
  833. let s = transformSons(c, n)
  834. # bugfix: check after 'transformSons' if it's still a method call:
  835. # use the dispatcher for the call:
  836. if s[0].kind == nkSym and s[0].sym.kind == skMethod:
  837. when false:
  838. let t = lastSon(s[0].sym.ast)
  839. if t.kind != nkSym or sfDispatcher notin t.sym.flags:
  840. methodDef(s[0].sym, false)
  841. result = methodCall(s, c.graph.config)
  842. else:
  843. result = s
  844. proc transformExceptBranch(c: PTransf, n: PNode): PNode =
  845. if n[0].isInfixAs() and not isImportedException(n[0][1].typ, c.graph.config):
  846. let excTypeNode = n[0][1]
  847. let actions = newTransNode(nkStmtListExpr, n[1], 2)
  848. # Generating `let exc = (excType)(getCurrentException())`
  849. # -> getCurrentException()
  850. let excCall = callCodegenProc(c.graph, "getCurrentException")
  851. # -> (excType)
  852. let convNode = newTransNode(nkHiddenSubConv, n[1].info, 2)
  853. convNode[0] = newNodeI(nkEmpty, n.info)
  854. convNode[1] = excCall
  855. convNode.typ = excTypeNode.typ.toRef(c.idgen)
  856. # -> let exc = ...
  857. let identDefs = newTransNode(nkIdentDefs, n[1].info, 3)
  858. identDefs[0] = n[0][2]
  859. identDefs[1] = newNodeI(nkEmpty, n.info)
  860. identDefs[2] = convNode
  861. let letSection = newTransNode(nkLetSection, n[1].info, 1)
  862. letSection[0] = identDefs
  863. # Place the let statement and body of the 'except' branch into new stmtList.
  864. actions[0] = letSection
  865. actions[1] = transform(c, n[1])
  866. # Overwrite 'except' branch body with our stmtList.
  867. result = newTransNode(nkExceptBranch, n[1].info, 2)
  868. # Replace the `Exception as foobar` with just `Exception`.
  869. result[0] = transform(c, n[0][1])
  870. result[1] = actions
  871. else:
  872. result = transformSons(c, n)
  873. proc commonOptimizations*(g: ModuleGraph; idgen: IdGenerator; c: PSym, n: PNode): PNode =
  874. ## Merges adjacent constant expressions of the children of the `&` call into
  875. ## a single constant expression. It also inlines constant expressions which are not
  876. ## complex.
  877. result = n
  878. for i in 0..<n.safeLen:
  879. result[i] = commonOptimizations(g, idgen, c, n[i])
  880. var op = getMergeOp(n)
  881. if (op != nil) and (op.magic != mNone) and (n.len >= 3):
  882. result = newNodeIT(nkCall, n.info, n.typ)
  883. result.add(n[0])
  884. var args = newNode(nkArgList)
  885. flattenTreeAux(args, n, op)
  886. var j = 0
  887. while j < args.len:
  888. var a = args[j]
  889. inc(j)
  890. if isConstExpr(a):
  891. while j < args.len:
  892. let b = args[j]
  893. if not isConstExpr(b): break
  894. a = evalOp(op.magic, result, a, b, nil, idgen, g)
  895. inc(j)
  896. result.add(a)
  897. if result.len == 2: result = result[1]
  898. else:
  899. var cnst = getConstExpr(c, n, idgen, g)
  900. # we inline constants if they are not complex constants:
  901. if cnst != nil and not dontInlineConstant(n, cnst):
  902. result = cnst
  903. else:
  904. result = n
  905. proc transformDerefBlock(c: PTransf, n: PNode): PNode =
  906. # We transform (block: x)[] to (block: x[])
  907. let e0 = n[0]
  908. result = shallowCopy(e0)
  909. result.typ = n.typ
  910. for i in 0 ..< e0.len - 1:
  911. result[i] = e0[i]
  912. result[e0.len-1] = newTreeIT(nkHiddenDeref, n.info, n.typ, e0[e0.len-1])
  913. proc transform(c: PTransf, n: PNode): PNode =
  914. when false:
  915. var oldDeferAnchor: PNode
  916. if n.kind in {nkElifBranch, nkOfBranch, nkExceptBranch, nkElifExpr,
  917. nkElseExpr, nkElse, nkForStmt, nkWhileStmt, nkFinally,
  918. nkBlockStmt, nkBlockExpr}:
  919. oldDeferAnchor = c.deferAnchor
  920. c.deferAnchor = n
  921. case n.kind
  922. of nkSym:
  923. result = transformSym(c, n)
  924. of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit, nkComesFrom:
  925. # nothing to be done for leaves:
  926. result = n
  927. of nkBracketExpr: result = transformArrayAccess(c, n)
  928. of procDefs:
  929. var s = n[namePos].sym
  930. if n.typ != nil and s.typ.callConv == ccClosure:
  931. result = transformSym(c, n[namePos])
  932. # use the same node as before if still a symbol:
  933. if result.kind == nkSym: result = n
  934. else:
  935. result = n
  936. of nkMacroDef:
  937. # XXX no proper closure support yet:
  938. when false:
  939. if n[genericParamsPos].kind == nkEmpty:
  940. var s = n[namePos].sym
  941. n[bodyPos] = transform(c, s.getBody)
  942. if n.kind == nkMethodDef: methodDef(s, false)
  943. result = n
  944. of nkForStmt:
  945. result = transformFor(c, n)
  946. of nkParForStmt:
  947. result = transformSons(c, n)
  948. of nkCaseStmt:
  949. result = transformCase(c, n)
  950. of nkWhileStmt: result = transformWhile(c, n)
  951. of nkBlockStmt, nkBlockExpr:
  952. result = transformBlock(c, n)
  953. of nkDefer:
  954. c.deferDetected = true
  955. result = transformSons(c, n)
  956. when false:
  957. let deferPart = newNodeI(nkFinally, n.info)
  958. deferPart.add n[0]
  959. let tryStmt = newNodeI(nkTryStmt, n.info)
  960. if c.deferAnchor.isNil:
  961. tryStmt.add c.root
  962. c.root = tryStmt
  963. result = tryStmt
  964. else:
  965. # modify the corresponding *action*, don't rely on nkStmtList:
  966. tryStmt.add c.deferAnchor[^1]
  967. c.deferAnchor[^1] = tryStmt
  968. result = newTransNode(nkCommentStmt, n.info, 0)
  969. tryStmt.add deferPart
  970. # disable the original 'defer' statement:
  971. n.kind = nkEmpty
  972. of nkContinueStmt:
  973. result = newNodeI(nkBreakStmt, n.info)
  974. var labl = c.contSyms[c.contSyms.high]
  975. result.add(newSymNode(labl))
  976. of nkBreakStmt: result = transformBreak(c, n)
  977. of nkCallKinds:
  978. result = transformCall(c, n)
  979. of nkHiddenAddr:
  980. result = transformAddrDeref(c, n, {nkHiddenDeref})
  981. of nkAddr:
  982. result = transformAddrDeref(c, n, {nkDerefExpr, nkHiddenDeref})
  983. of nkDerefExpr:
  984. result = transformAddrDeref(c, n, {nkAddr, nkHiddenAddr})
  985. of nkHiddenDeref:
  986. if n[0].kind in {nkBlockExpr, nkBlockStmt}:
  987. # bug #20107 bug #21540. Watch out to not deref the pointer too late.
  988. let e = transformDerefBlock(c, n)
  989. result = transformBlock(c, e)
  990. else:
  991. result = transformAddrDeref(c, n, {nkAddr, nkHiddenAddr})
  992. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  993. result = transformConv(c, n)
  994. of nkDiscardStmt:
  995. result = n
  996. if n[0].kind != nkEmpty:
  997. result = transformSons(c, n)
  998. if isConstExpr(result[0]):
  999. # ensure that e.g. discard "some comment" gets optimized away
  1000. # completely:
  1001. result = newNode(nkCommentStmt)
  1002. of nkCommentStmt, nkTemplateDef, nkImportStmt, nkStaticStmt,
  1003. nkExportStmt, nkExportExceptStmt:
  1004. return n
  1005. of nkConstSection:
  1006. # do not replace ``const c = 3`` with ``const 3 = 3``
  1007. return transformConstSection(c, n)
  1008. of nkTypeSection, nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  1009. # no need to transform type sections:
  1010. return n
  1011. of nkVarSection, nkLetSection:
  1012. if c.inlining > 0:
  1013. # we need to copy the variables for multiple yield statements:
  1014. result = transformVarSection(c, n)
  1015. else:
  1016. result = transformSons(c, n)
  1017. of nkYieldStmt:
  1018. if c.inlining > 0 and not c.isIntroducingNewLocalVars:
  1019. result = transformYield(c, n)
  1020. else:
  1021. result = transformSons(c, n)
  1022. of nkAsgn:
  1023. result = transformAsgn(c, n)
  1024. of nkIdentDefs, nkConstDef:
  1025. result = newTransNode(n)
  1026. result[0] = transform(c, skipPragmaExpr(n[0]))
  1027. # Skip the second son since it only contains an unsemanticized copy of the
  1028. # variable type used by docgen
  1029. let last = n.len-1
  1030. for i in 1..<last: result[i] = n[i]
  1031. result[last] = transform(c, n[last])
  1032. # XXX comment handling really sucks:
  1033. if importantComments(c.graph.config):
  1034. result.comment = n.comment
  1035. of nkClosure:
  1036. # it can happen that for-loop-inlining produced a fresh
  1037. # set of variables, including some computed environment
  1038. # (bug #2604). We need to patch this environment here too:
  1039. let a = n[1]
  1040. if a.kind == nkSym:
  1041. result = copyTree(n)
  1042. result[1] = transformSymAux(c, a)
  1043. else:
  1044. result = n
  1045. of nkExceptBranch:
  1046. result = transformExceptBranch(c, n)
  1047. of nkCheckedFieldExpr:
  1048. result = transformSons(c, n)
  1049. if result[0].kind != nkDotExpr:
  1050. # simplfied beyond a dot expression --> simplify further.
  1051. result = result[0]
  1052. else:
  1053. result = transformSons(c, n)
  1054. when false:
  1055. if oldDeferAnchor != nil: c.deferAnchor = oldDeferAnchor
  1056. # Constants can be inlined here, but only if they cannot result in a cast
  1057. # in the back-end (e.g. var p: pointer = someProc)
  1058. let exprIsPointerCast = n.kind in {nkCast, nkConv, nkHiddenStdConv} and
  1059. n.typ != nil and
  1060. n.typ.kind == tyPointer
  1061. if not exprIsPointerCast:
  1062. var cnst = getConstExpr(c.module, result, c.idgen, c.graph)
  1063. # we inline constants if they are not complex constants:
  1064. if cnst != nil and not dontInlineConstant(n, cnst):
  1065. result = cnst # do not miss an optimization
  1066. proc processTransf(c: PTransf, n: PNode, owner: PSym): PNode =
  1067. # Note: For interactive mode we cannot call 'passes.skipCodegen' and skip
  1068. # this step! We have to rely that the semantic pass transforms too errornous
  1069. # nodes into an empty node.
  1070. if nfTransf in n.flags: return n
  1071. pushTransCon(c, newTransCon(owner))
  1072. result = transform(c, n)
  1073. popTransCon(c)
  1074. incl(result.flags, nfTransf)
  1075. proc openTransf(g: ModuleGraph; module: PSym, filename: string; idgen: IdGenerator; flags: TransformFlags): PTransf =
  1076. result = PTransf(module: module, graph: g, idgen: idgen, flags: flags)
  1077. proc flattenStmts(n: PNode) =
  1078. var goOn = true
  1079. while goOn:
  1080. goOn = false
  1081. var i = 0
  1082. while i < n.len:
  1083. let it = n[i]
  1084. if it.kind in {nkStmtList, nkStmtListExpr}:
  1085. n.sons[i..i] = it.sons[0..<it.len]
  1086. goOn = true
  1087. inc i
  1088. proc liftDeferAux(n: PNode) =
  1089. if n.kind in {nkStmtList, nkStmtListExpr}:
  1090. flattenStmts(n)
  1091. var goOn = true
  1092. while goOn:
  1093. goOn = false
  1094. let last = n.len-1
  1095. for i in 0..last:
  1096. if n[i].kind == nkDefer:
  1097. let deferPart = newNodeI(nkFinally, n[i].info)
  1098. deferPart.add n[i][0]
  1099. var tryStmt = newNodeIT(nkTryStmt, n[i].info, n.typ)
  1100. var body = newNodeIT(n.kind, n[i].info, n.typ)
  1101. if i < last:
  1102. body.sons = n.sons[(i+1)..last]
  1103. tryStmt.add body
  1104. tryStmt.add deferPart
  1105. n[i] = tryStmt
  1106. n.sons.setLen(i+1)
  1107. n.typ = tryStmt.typ
  1108. goOn = true
  1109. break
  1110. for i in 0..n.safeLen-1:
  1111. liftDeferAux(n[i])
  1112. template liftDefer(c, root) =
  1113. if c.deferDetected:
  1114. liftDeferAux(root)
  1115. proc transformBody*(g: ModuleGraph; idgen: IdGenerator; prc: PSym; flags: TransformFlags): PNode =
  1116. assert prc.kind in routineKinds
  1117. if prc.transformedBody != nil:
  1118. result = prc.transformedBody
  1119. elif nfTransf in getBody(g, prc).flags or prc.kind in {skTemplate}:
  1120. result = getBody(g, prc)
  1121. else:
  1122. prc.transformedBody = newNode(nkEmpty) # protects from recursion
  1123. var c = openTransf(g, prc.getModule, "", idgen, flags)
  1124. result = liftLambdas(g, prc, getBody(g, prc), c.tooEarly, c.idgen, flags)
  1125. result = processTransf(c, result, prc)
  1126. liftDefer(c, result)
  1127. result = liftLocalsIfRequested(prc, result, g.cache, g.config, c.idgen)
  1128. if prc.isIterator:
  1129. result = g.transformClosureIterator(c.idgen, prc, result)
  1130. incl(result.flags, nfTransf)
  1131. if useCache in flags or prc.typ.callConv == ccInline:
  1132. # genProc for inline procs will be called multiple times from different modules,
  1133. # it is important to transform exactly once to get sym ids and locations right
  1134. prc.transformedBody = result
  1135. else:
  1136. prc.transformedBody = nil
  1137. # XXX Rodfile support for transformedBody!
  1138. #if prc.name.s == "main":
  1139. # echo "transformed into ", renderTree(result, {renderIds})
  1140. proc transformStmt*(g: ModuleGraph; idgen: IdGenerator; module: PSym, n: PNode; flags: TransformFlags = {}): PNode =
  1141. if nfTransf in n.flags:
  1142. result = n
  1143. else:
  1144. var c = openTransf(g, module, "", idgen, flags)
  1145. result = processTransf(c, n, module)
  1146. liftDefer(c, result)
  1147. #result = liftLambdasForTopLevel(module, result)
  1148. incl(result.flags, nfTransf)
  1149. proc transformExpr*(g: ModuleGraph; idgen: IdGenerator; module: PSym, n: PNode; flags: TransformFlags = {}): PNode =
  1150. if nfTransf in n.flags:
  1151. result = n
  1152. else:
  1153. var c = openTransf(g, module, "", idgen, flags)
  1154. result = processTransf(c, n, module)
  1155. liftDefer(c, result)
  1156. # expressions are not to be injected with destructor calls as that
  1157. # the list of top level statements needs to be collected before.
  1158. incl(result.flags, nfTransf)