transf.nim 41 KB

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