transf.nim 43 KB

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