transf.nim 44 KB

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