transf.nim 41 KB

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