transf.nim 43 KB

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