transf.nim 41 KB

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