transf.nim 38 KB

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