transf.nim 44 KB

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