transf.nim 43 KB

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