transf.nim 43 KB

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