renderer.nim 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 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 renderer of the standard Nim representation.
  10. when defined(nimHasUsed):
  11. # 'import renderer' is so useful for debugging
  12. # that Nim shouldn't produce a warning for that:
  13. {.used.}
  14. import
  15. lexer, options, idents, strutils, ast, msgs, lineinfos
  16. when defined(nimPreviewSlimSystem):
  17. import std/[syncio, assertions, formatfloat]
  18. type
  19. TRenderFlag* = enum
  20. renderNone, renderNoBody, renderNoComments, renderDocComments,
  21. renderNoPragmas, renderIds, renderNoProcDefs, renderSyms, renderRunnableExamples,
  22. renderIr
  23. TRenderFlags* = set[TRenderFlag]
  24. TRenderTok* = object
  25. kind*: TokType
  26. length*: int16
  27. sym*: PSym
  28. TRenderTokSeq* = seq[TRenderTok]
  29. TSrcGen* = object
  30. indent*: int
  31. lineLen*: int
  32. col: int
  33. pos*: int # current position for iteration over the buffer
  34. idx*: int # current token index for iteration over the buffer
  35. tokens*: TRenderTokSeq
  36. buf*: string
  37. pendingNL*: int # negative if not active; else contains the
  38. # indentation value
  39. pendingWhitespace: int
  40. comStack*: seq[PNode] # comment stack
  41. flags*: TRenderFlags
  42. inGenericParams: bool
  43. checkAnon: bool # we're in a context that can contain sfAnon
  44. inPragma: int
  45. when defined(nimpretty):
  46. pendingNewlineCount: int
  47. fid*: FileIndex
  48. config*: ConfigRef
  49. mangler: seq[PSym]
  50. proc renderTree*(n: PNode, renderFlags: TRenderFlags = {}): string
  51. # We render the source code in a two phases: The first
  52. # determines how long the subtree will likely be, the second
  53. # phase appends to a buffer that will be the output.
  54. proc disamb(g: var TSrcGen; s: PSym): int =
  55. # we group by 's.name.s' to compute the stable name ID.
  56. result = 0
  57. for i in 0 ..< g.mangler.len:
  58. if s == g.mangler[i]: return result
  59. if s.name.s == g.mangler[i].name.s: inc result
  60. g.mangler.add s
  61. proc isKeyword*(i: PIdent): bool =
  62. if (i.id >= ord(tokKeywordLow) - ord(tkSymbol)) and
  63. (i.id <= ord(tokKeywordHigh) - ord(tkSymbol)):
  64. result = true
  65. proc renderDefinitionName*(s: PSym, noQuotes = false): string =
  66. ## Returns the definition name of the symbol.
  67. ##
  68. ## If noQuotes is false the symbol may be returned in backticks. This will
  69. ## happen if the name happens to be a keyword or the first character is not
  70. ## part of the SymStartChars set.
  71. let x = s.name.s
  72. if noQuotes or (x[0] in SymStartChars and not renderer.isKeyword(s.name)):
  73. result = x
  74. else:
  75. result = '`' & x & '`'
  76. const
  77. IndentWidth = 2
  78. longIndentWid = IndentWidth * 2
  79. when defined(nimpretty):
  80. proc minmaxLine(n: PNode): (int, int) =
  81. case n.kind
  82. of nkTripleStrLit:
  83. result = (n.info.line.int, n.info.line.int + countLines(n.strVal))
  84. of nkCommentStmt:
  85. result = (n.info.line.int, n.info.line.int + countLines(n.comment))
  86. else:
  87. result = (n.info.line.int, n.info.line.int)
  88. for i in 0..<n.safeLen:
  89. let (currMin, currMax) = minmaxLine(n[i])
  90. if currMin < result[0]: result[0] = currMin
  91. if currMax > result[1]: result[1] = currMax
  92. proc lineDiff(a, b: PNode): int =
  93. result = minmaxLine(b)[0] - minmaxLine(a)[1]
  94. const
  95. MaxLineLen = 80
  96. LineCommentColumn = 30
  97. proc initSrcGen(g: var TSrcGen, renderFlags: TRenderFlags; config: ConfigRef) =
  98. g.comStack = @[]
  99. g.tokens = @[]
  100. g.indent = 0
  101. g.lineLen = 0
  102. g.pos = 0
  103. g.idx = 0
  104. g.buf = ""
  105. g.flags = renderFlags
  106. g.pendingNL = -1
  107. g.pendingWhitespace = -1
  108. g.inGenericParams = false
  109. g.config = config
  110. proc addTok(g: var TSrcGen, kind: TokType, s: string; sym: PSym = nil) =
  111. g.tokens.add TRenderTok(kind: kind, length: int16(s.len), sym: sym)
  112. g.buf.add(s)
  113. if kind != tkSpaces:
  114. inc g.col, s.len
  115. proc addPendingNL(g: var TSrcGen) =
  116. if g.pendingNL >= 0:
  117. when defined(nimpretty):
  118. let newlines = repeat("\n", clamp(g.pendingNewlineCount, 1, 3))
  119. else:
  120. const newlines = "\n"
  121. addTok(g, tkSpaces, newlines & spaces(g.pendingNL))
  122. g.lineLen = g.pendingNL
  123. g.col = g.pendingNL
  124. g.pendingNL = - 1
  125. g.pendingWhitespace = -1
  126. elif g.pendingWhitespace >= 0:
  127. addTok(g, tkSpaces, spaces(g.pendingWhitespace))
  128. g.pendingWhitespace = -1
  129. proc putNL(g: var TSrcGen, indent: int) =
  130. if g.pendingNL >= 0: addPendingNL(g)
  131. else:
  132. addTok(g, tkSpaces, "\n")
  133. g.col = 0
  134. g.pendingNL = indent
  135. g.lineLen = indent
  136. g.pendingWhitespace = -1
  137. proc previousNL(g: TSrcGen): bool =
  138. result = g.pendingNL >= 0 or (g.tokens.len > 0 and
  139. g.tokens[^1].kind == tkSpaces)
  140. proc putNL(g: var TSrcGen) =
  141. putNL(g, g.indent)
  142. proc optNL(g: var TSrcGen, indent: int) =
  143. g.pendingNL = indent
  144. g.lineLen = indent
  145. g.col = g.indent
  146. when defined(nimpretty): g.pendingNewlineCount = 0
  147. proc optNL(g: var TSrcGen) =
  148. optNL(g, g.indent)
  149. proc optNL(g: var TSrcGen; a, b: PNode) =
  150. g.pendingNL = g.indent
  151. g.lineLen = g.indent
  152. g.col = g.indent
  153. when defined(nimpretty): g.pendingNewlineCount = lineDiff(a, b)
  154. proc indentNL(g: var TSrcGen) =
  155. inc(g.indent, IndentWidth)
  156. g.pendingNL = g.indent
  157. g.lineLen = g.indent
  158. proc dedent(g: var TSrcGen) =
  159. dec(g.indent, IndentWidth)
  160. assert(g.indent >= 0)
  161. if g.pendingNL > IndentWidth:
  162. dec(g.pendingNL, IndentWidth)
  163. dec(g.lineLen, IndentWidth)
  164. proc put(g: var TSrcGen, kind: TokType, s: string; sym: PSym = nil) =
  165. if kind != tkSpaces:
  166. addPendingNL(g)
  167. if s.len > 0 or kind in {tkHideableStart, tkHideableEnd}:
  168. addTok(g, kind, s, sym)
  169. else:
  170. g.pendingWhitespace = s.len
  171. inc g.col, s.len
  172. inc(g.lineLen, s.len)
  173. proc putComment(g: var TSrcGen, s: string) =
  174. if s.len == 0: return
  175. var i = 0
  176. let hi = s.len - 1
  177. let isCode = (s.len >= 2) and (s[1] != ' ')
  178. let ind = g.col
  179. var com = "## "
  180. while i <= hi:
  181. case s[i]
  182. of '\0':
  183. break
  184. of '\r':
  185. put(g, tkComment, com)
  186. com = "## "
  187. inc(i)
  188. if i <= hi and s[i] == '\n': inc(i)
  189. optNL(g, ind)
  190. of '\n':
  191. put(g, tkComment, com)
  192. com = "## "
  193. inc(i)
  194. optNL(g, ind)
  195. of ' ', '\t':
  196. com.add(s[i])
  197. inc(i)
  198. else:
  199. # we may break the comment into a multi-line comment if the line
  200. # gets too long:
  201. # compute length of the following word:
  202. var j = i
  203. while j <= hi and s[j] > ' ': inc(j)
  204. if not isCode and (g.col + (j - i) > MaxLineLen):
  205. put(g, tkComment, com)
  206. optNL(g, ind)
  207. com = "## "
  208. while i <= hi and s[i] > ' ':
  209. com.add(s[i])
  210. inc(i)
  211. put(g, tkComment, com)
  212. optNL(g)
  213. proc maxLineLength(s: string): int =
  214. if s.len == 0: return 0
  215. var i = 0
  216. let hi = s.len - 1
  217. var lineLen = 0
  218. while i <= hi:
  219. case s[i]
  220. of '\0':
  221. break
  222. of '\r':
  223. inc(i)
  224. if i <= hi and s[i] == '\n': inc(i)
  225. result = max(result, lineLen)
  226. lineLen = 0
  227. of '\n':
  228. inc(i)
  229. result = max(result, lineLen)
  230. lineLen = 0
  231. else:
  232. inc(lineLen)
  233. inc(i)
  234. proc putRawStr(g: var TSrcGen, kind: TokType, s: string) =
  235. var i = 0
  236. let hi = s.len - 1
  237. var str = ""
  238. while i <= hi:
  239. case s[i]
  240. of '\r':
  241. put(g, kind, str)
  242. str = ""
  243. inc(i)
  244. if i <= hi and s[i] == '\n': inc(i)
  245. optNL(g, 0)
  246. of '\n':
  247. put(g, kind, str)
  248. str = ""
  249. inc(i)
  250. optNL(g, 0)
  251. else:
  252. str.add(s[i])
  253. inc(i)
  254. put(g, kind, str)
  255. proc containsNL(s: string): bool =
  256. for i in 0..<s.len:
  257. case s[i]
  258. of '\r', '\n':
  259. return true
  260. else:
  261. discard
  262. result = false
  263. proc pushCom(g: var TSrcGen, n: PNode) =
  264. setLen(g.comStack, g.comStack.len + 1)
  265. g.comStack[^1] = n
  266. proc popAllComs(g: var TSrcGen) =
  267. setLen(g.comStack, 0)
  268. const
  269. Space = " "
  270. proc shouldRenderComment(g: TSrcGen): bool {.inline.} =
  271. (renderNoComments notin g.flags or renderDocComments in g.flags)
  272. proc shouldRenderComment(g: TSrcGen, n: PNode): bool {.inline.} =
  273. shouldRenderComment(g) and n.comment.len > 0
  274. proc gcom(g: var TSrcGen, n: PNode) =
  275. assert(n != nil)
  276. if shouldRenderComment(g, n):
  277. var oneSpaceAdded = 0
  278. if (g.pendingNL < 0) and (g.buf.len > 0) and (g.buf[^1] != ' '):
  279. put(g, tkSpaces, Space)
  280. oneSpaceAdded = 1
  281. # Before long comments we cannot make sure that a newline is generated,
  282. # because this might be wrong. But it is no problem in practice.
  283. if (g.pendingNL < 0) and (g.buf.len > 0) and
  284. (g.col < LineCommentColumn):
  285. var ml = maxLineLength(n.comment)
  286. if ml + LineCommentColumn <= MaxLineLen:
  287. put(g, tkSpaces, spaces(LineCommentColumn - g.col))
  288. dec g.col, oneSpaceAdded
  289. putComment(g, n.comment) #assert(g.comStack[high(g.comStack)] = n);
  290. proc gcoms(g: var TSrcGen) =
  291. for i in 0..high(g.comStack): gcom(g, g.comStack[i])
  292. popAllComs(g)
  293. proc lsub(g: TSrcGen; n: PNode): int
  294. proc litAux(g: TSrcGen; n: PNode, x: BiggestInt, size: int): string =
  295. proc skip(t: PType): PType =
  296. result = t
  297. while result != nil and result.kind in {tyGenericInst, tyRange, tyVar,
  298. tyLent, tyDistinct, tyOrdinal, tyAlias, tySink}:
  299. result = lastSon(result)
  300. let typ = n.typ.skip
  301. if typ != nil and typ.kind in {tyBool, tyEnum}:
  302. if sfPure in typ.sym.flags:
  303. result = typ.sym.name.s & '.'
  304. let enumfields = typ.n
  305. # we need a slow linear search because of enums with holes:
  306. for e in items(enumfields):
  307. if e.sym.position == x:
  308. result &= e.sym.name.s
  309. return
  310. if nfBase2 in n.flags: result = "0b" & toBin(x, size * 8)
  311. elif nfBase8 in n.flags:
  312. var y = if size < sizeof(BiggestInt): x and ((1.BiggestInt shl (size*8)) - 1)
  313. else: x
  314. result = "0o" & toOct(y, size * 3)
  315. elif nfBase16 in n.flags: result = "0x" & toHex(x, size * 2)
  316. else: result = $x
  317. proc ulitAux(g: TSrcGen; n: PNode, x: BiggestInt, size: int): string =
  318. if nfBase2 in n.flags: result = "0b" & toBin(x, size * 8)
  319. elif nfBase8 in n.flags: result = "0o" & toOct(x, size * 3)
  320. elif nfBase16 in n.flags: result = "0x" & toHex(x, size * 2)
  321. else: result = $cast[BiggestUInt](x)
  322. proc atom(g: TSrcGen; n: PNode): string =
  323. when defined(nimpretty):
  324. doAssert g.config != nil, "g.config not initialized!"
  325. let comment = if n.info.commentOffsetA < n.info.commentOffsetB:
  326. " " & fileSection(g.config, g.fid, n.info.commentOffsetA, n.info.commentOffsetB)
  327. else:
  328. ""
  329. if n.info.offsetA <= n.info.offsetB:
  330. # for some constructed tokens this can not be the case and we're better
  331. # off to not mess with the offset then.
  332. return fileSection(g.config, g.fid, n.info.offsetA, n.info.offsetB) & comment
  333. var f: float32
  334. case n.kind
  335. of nkEmpty: result = ""
  336. of nkIdent: result = n.ident.s
  337. of nkSym: result = n.sym.name.s
  338. of nkStrLit: result = ""; result.addQuoted(n.strVal)
  339. of nkRStrLit: result = "r\"" & replace(n.strVal, "\"", "\"\"") & '\"'
  340. of nkTripleStrLit: result = "\"\"\"" & n.strVal & "\"\"\""
  341. of nkCharLit:
  342. result = "\'"
  343. result.addEscapedChar(chr(int(n.intVal)));
  344. result.add '\''
  345. of nkIntLit: result = litAux(g, n, n.intVal, 4)
  346. of nkInt8Lit: result = litAux(g, n, n.intVal, 1) & "\'i8"
  347. of nkInt16Lit: result = litAux(g, n, n.intVal, 2) & "\'i16"
  348. of nkInt32Lit: result = litAux(g, n, n.intVal, 4) & "\'i32"
  349. of nkInt64Lit: result = litAux(g, n, n.intVal, 8) & "\'i64"
  350. of nkUIntLit: result = ulitAux(g, n, n.intVal, 4) & "\'u"
  351. of nkUInt8Lit: result = ulitAux(g, n, n.intVal, 1) & "\'u8"
  352. of nkUInt16Lit: result = ulitAux(g, n, n.intVal, 2) & "\'u16"
  353. of nkUInt32Lit: result = ulitAux(g, n, n.intVal, 4) & "\'u32"
  354. of nkUInt64Lit: result = ulitAux(g, n, n.intVal, 8) & "\'u64"
  355. of nkFloatLit:
  356. if n.flags * {nfBase2, nfBase8, nfBase16} == {}: result = $(n.floatVal)
  357. else: result = litAux(g, n, (cast[ptr int64](addr(n.floatVal)))[] , 8)
  358. of nkFloat32Lit:
  359. if n.flags * {nfBase2, nfBase8, nfBase16} == {}:
  360. result = $n.floatVal & "\'f32"
  361. else:
  362. f = n.floatVal.float32
  363. result = litAux(g, n, (cast[ptr int32](addr(f)))[], 4) & "\'f32"
  364. of nkFloat64Lit:
  365. if n.flags * {nfBase2, nfBase8, nfBase16} == {}:
  366. result = $n.floatVal & "\'f64"
  367. else:
  368. result = litAux(g, n, (cast[ptr int64](addr(n.floatVal)))[], 8) & "\'f64"
  369. of nkNilLit: result = "nil"
  370. of nkType:
  371. if (n.typ != nil) and (n.typ.sym != nil): result = n.typ.sym.name.s
  372. else: result = "[type node]"
  373. else:
  374. internalError(g.config, "renderer.atom " & $n.kind)
  375. result = ""
  376. proc lcomma(g: TSrcGen; n: PNode, start: int = 0, theEnd: int = - 1): int =
  377. assert(theEnd < 0)
  378. result = 0
  379. for i in start..n.len + theEnd:
  380. let param = n[i]
  381. if nfDefaultParam notin param.flags:
  382. inc(result, lsub(g, param))
  383. inc(result, 2) # for ``, ``
  384. if result > 0:
  385. dec(result, 2) # last does not get a comma!
  386. proc lsons(g: TSrcGen; n: PNode, start: int = 0, theEnd: int = - 1): int =
  387. assert(theEnd < 0)
  388. result = 0
  389. for i in start..n.len + theEnd: inc(result, lsub(g, n[i]))
  390. proc lsub(g: TSrcGen; n: PNode): int =
  391. # computes the length of a tree
  392. if isNil(n): return 0
  393. if shouldRenderComment(g, n): return MaxLineLen + 1
  394. case n.kind
  395. of nkEmpty: result = 0
  396. of nkTripleStrLit:
  397. if containsNL(n.strVal): result = MaxLineLen + 1
  398. else: result = atom(g, n).len
  399. of succ(nkEmpty)..pred(nkTripleStrLit), succ(nkTripleStrLit)..nkNilLit:
  400. result = atom(g, n).len
  401. of nkCall, nkBracketExpr, nkCurlyExpr, nkConv, nkPattern, nkObjConstr:
  402. result = lsub(g, n[0]) + lcomma(g, n, 1) + 2
  403. of nkHiddenStdConv, nkHiddenSubConv, nkHiddenCallConv: result = lsub(g, n[1])
  404. of nkCast: result = lsub(g, n[0]) + lsub(g, n[1]) + len("cast[]()")
  405. of nkAddr: result = (if n.len>0: lsub(g, n[0]) + len("addr()") else: 4)
  406. of nkStaticExpr: result = lsub(g, n[0]) + len("static_")
  407. of nkHiddenAddr, nkHiddenDeref, nkStringToCString, nkCStringToString: result = lsub(g, n[0])
  408. of nkCommand: result = lsub(g, n[0]) + lcomma(g, n, 1) + 1
  409. of nkExprEqExpr, nkAsgn, nkFastAsgn: result = lsons(g, n) + 3
  410. of nkPar, nkCurly, nkBracket, nkClosure: result = lcomma(g, n) + 2
  411. of nkTupleConstr:
  412. # assume the trailing comma:
  413. result = lcomma(g, n) + 3
  414. of nkArgList: result = lcomma(g, n)
  415. of nkTableConstr:
  416. result = if n.len > 0: lcomma(g, n) + 2 else: len("{:}")
  417. of nkClosedSymChoice, nkOpenSymChoice:
  418. if n.len > 0: result += lsub(g, n[0])
  419. of nkTupleTy: result = lcomma(g, n) + len("tuple[]")
  420. of nkTupleClassTy: result = len("tuple")
  421. of nkDotExpr: result = lsons(g, n) + 1
  422. of nkBind: result = lsons(g, n) + len("bind_")
  423. of nkBindStmt: result = lcomma(g, n) + len("bind_")
  424. of nkMixinStmt: result = lcomma(g, n) + len("mixin_")
  425. of nkCheckedFieldExpr: result = lsub(g, n[0])
  426. of nkLambda: result = lsons(g, n) + len("proc__=_")
  427. of nkDo: result = lsons(g, n) + len("do__:_")
  428. of nkConstDef, nkIdentDefs:
  429. result = lcomma(g, n, 0, - 3)
  430. if n[^2].kind != nkEmpty: result += lsub(g, n[^2]) + 2
  431. if n[^1].kind != nkEmpty: result += lsub(g, n[^1]) + 3
  432. of nkVarTuple:
  433. if n[^1].kind == nkEmpty:
  434. result = lcomma(g, n, 0, - 2) + len("()")
  435. else:
  436. result = lcomma(g, n, 0, - 3) + len("() = ") + lsub(g, lastSon(n))
  437. of nkChckRangeF: result = len("chckRangeF") + 2 + lcomma(g, n)
  438. of nkChckRange64: result = len("chckRange64") + 2 + lcomma(g, n)
  439. of nkChckRange: result = len("chckRange") + 2 + lcomma(g, n)
  440. of nkObjDownConv, nkObjUpConv:
  441. result = 2
  442. if n.len >= 1: result += lsub(g, n[0])
  443. result += lcomma(g, n, 1)
  444. of nkExprColonExpr: result = lsons(g, n) + 2
  445. of nkInfix: result = lsons(g, n) + 2
  446. of nkPrefix:
  447. result = lsons(g, n)+1+(if n.len > 0 and n[1].kind == nkInfix: 2 else: 0)
  448. of nkPostfix: result = lsons(g, n)
  449. of nkCallStrLit: result = lsons(g, n)
  450. of nkPragmaExpr: result = lsub(g, n[0]) + lcomma(g, n, 1)
  451. of nkRange: result = lsons(g, n) + 2
  452. of nkDerefExpr: result = lsub(g, n[0]) + 2
  453. of nkAccQuoted: result = lsons(g, n) + 2
  454. of nkIfExpr:
  455. result = lsub(g, n[0][0]) + lsub(g, n[0][1]) + lsons(g, n, 1) +
  456. len("if_:_")
  457. of nkElifExpr: result = lsons(g, n) + len("_elif_:_")
  458. of nkElseExpr: result = lsub(g, n[0]) + len("_else:_") # type descriptions
  459. of nkTypeOfExpr: result = (if n.len > 0: lsub(g, n[0]) else: 0)+len("typeof()")
  460. of nkRefTy: result = (if n.len > 0: lsub(g, n[0])+1 else: 0) + len("ref")
  461. of nkPtrTy: result = (if n.len > 0: lsub(g, n[0])+1 else: 0) + len("ptr")
  462. of nkVarTy, nkOutTy: result = (if n.len > 0: lsub(g, n[0])+1 else: 0) + len("var")
  463. of nkDistinctTy:
  464. result = len("distinct") + (if n.len > 0: lsub(g, n[0])+1 else: 0)
  465. if n.len > 1:
  466. result += (if n[1].kind == nkWith: len("_with_") else: len("_without_"))
  467. result += lcomma(g, n[1])
  468. of nkStaticTy: result = (if n.len > 0: lsub(g, n[0]) else: 0) +
  469. len("static[]")
  470. of nkTypeDef: result = lsons(g, n) + 3
  471. of nkOfInherit: result = lsub(g, n[0]) + len("of_")
  472. of nkProcTy: result = lsons(g, n) + len("proc_")
  473. of nkIteratorTy: result = lsons(g, n) + len("iterator_")
  474. of nkSinkAsgn: result = lsons(g, n) + len("`=sink`(, )")
  475. of nkEnumTy:
  476. if n.len > 0:
  477. result = lsub(g, n[0]) + lcomma(g, n, 1) + len("enum_")
  478. else:
  479. result = len("enum")
  480. of nkEnumFieldDef: result = lsons(g, n) + 3
  481. of nkVarSection, nkLetSection:
  482. if n.len > 1: result = MaxLineLen + 1
  483. else: result = lsons(g, n) + len("var_")
  484. of nkUsingStmt:
  485. if n.len > 1: result = MaxLineLen + 1
  486. else: result = lsons(g, n) + len("using_")
  487. of nkReturnStmt:
  488. if n.len > 0 and n[0].kind == nkAsgn:
  489. result = len("return_") + lsub(g, n[0][1])
  490. else:
  491. result = len("return_") + lsub(g, n[0])
  492. of nkRaiseStmt: result = lsub(g, n[0]) + len("raise_")
  493. of nkYieldStmt: result = lsub(g, n[0]) + len("yield_")
  494. of nkDiscardStmt: result = lsub(g, n[0]) + len("discard_")
  495. of nkBreakStmt: result = lsub(g, n[0]) + len("break_")
  496. of nkContinueStmt: result = lsub(g, n[0]) + len("continue_")
  497. of nkPragma: result = lcomma(g, n) + 4
  498. of nkCommentStmt: result = n.comment.len
  499. of nkOfBranch: result = lcomma(g, n, 0, - 2) + lsub(g, lastSon(n)) + len("of_:_")
  500. of nkImportAs: result = lsub(g, n[0]) + len("_as_") + lsub(g, n[1])
  501. of nkElifBranch: result = lsons(g, n) + len("elif_:_")
  502. of nkElse: result = lsub(g, n[0]) + len("else:_")
  503. of nkFinally: result = lsub(g, n[0]) + len("finally:_")
  504. of nkGenericParams: result = lcomma(g, n) + 2
  505. of nkFormalParams:
  506. result = lcomma(g, n, 1) + 2
  507. if n[0].kind != nkEmpty: result += lsub(g, n[0]) + 2
  508. of nkExceptBranch:
  509. result = lcomma(g, n, 0, -2) + lsub(g, lastSon(n)) + len("except_:_")
  510. of nkObjectTy:
  511. result = len("object_")
  512. else: result = MaxLineLen + 1
  513. proc fits(g: TSrcGen, x: int): bool =
  514. result = x <= MaxLineLen
  515. type
  516. TSubFlag = enum
  517. rfLongMode, rfInConstExpr
  518. TSubFlags = set[TSubFlag]
  519. TContext = tuple[spacing: int, flags: TSubFlags]
  520. const
  521. emptyContext: TContext = (spacing: 0, flags: {})
  522. proc initContext(c: var TContext) =
  523. c.spacing = 0
  524. c.flags = {}
  525. proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false)
  526. proc gsub(g: var TSrcGen, n: PNode, fromStmtList = false) =
  527. var c: TContext
  528. initContext(c)
  529. gsub(g, n, c, fromStmtList = fromStmtList)
  530. proc hasCom(n: PNode): bool =
  531. result = false
  532. if n.isNil: return false
  533. if n.comment.len > 0: return true
  534. case n.kind
  535. of nkEmpty..nkNilLit: discard
  536. else:
  537. for i in 0..<n.len:
  538. if hasCom(n[i]): return true
  539. proc putWithSpace(g: var TSrcGen, kind: TokType, s: string) =
  540. put(g, kind, s)
  541. put(g, tkSpaces, Space)
  542. proc isHideable(config: ConfigRef, n: PNode): bool =
  543. # xxx compare `ident` directly with `getIdent(cache, wRaises)`, but
  544. # this requires a `cache`.
  545. case n.kind
  546. of nkExprColonExpr: result = n[0].kind == nkIdent and n[0].ident.s in ["raises", "tags", "extern", "deprecated", "forbids"]
  547. of nkIdent: result = n.ident.s in ["gcsafe", "deprecated"]
  548. else: result = false
  549. proc gcommaAux(g: var TSrcGen, n: PNode, ind: int, start: int = 0,
  550. theEnd: int = - 1, separator = tkComma) =
  551. let inPragma = g.inPragma == 1 # just the top-level
  552. var inHideable = false
  553. for i in start..n.len + theEnd:
  554. let c = i < n.len + theEnd
  555. let sublen = lsub(g, n[i]) + ord(c)
  556. if not fits(g, g.lineLen + sublen) and (ind + sublen < MaxLineLen): optNL(g, ind)
  557. let oldLen = g.tokens.len
  558. if inPragma:
  559. if not inHideable and isHideable(g.config, n[i]):
  560. inHideable = true
  561. put(g, tkHideableStart, "")
  562. elif inHideable and not isHideable(g.config, n[i]):
  563. inHideable = false
  564. put(g, tkHideableEnd, "")
  565. gsub(g, n[i])
  566. if c:
  567. if g.tokens.len > oldLen:
  568. putWithSpace(g, separator, $separator)
  569. if shouldRenderComment(g) and hasCom(n[i]):
  570. gcoms(g)
  571. optNL(g, ind)
  572. if inHideable:
  573. put(g, tkHideableEnd, "")
  574. inHideable = false
  575. proc gcomma(g: var TSrcGen, n: PNode, c: TContext, start: int = 0,
  576. theEnd: int = - 1) =
  577. var ind: int
  578. if rfInConstExpr in c.flags:
  579. ind = g.indent + IndentWidth
  580. else:
  581. ind = g.lineLen
  582. if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
  583. gcommaAux(g, n, ind, start, theEnd)
  584. proc gcomma(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) =
  585. var ind = g.lineLen
  586. if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
  587. gcommaAux(g, n, ind, start, theEnd)
  588. proc gsemicolon(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) =
  589. var ind = g.lineLen
  590. if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
  591. gcommaAux(g, n, ind, start, theEnd, tkSemiColon)
  592. proc gsons(g: var TSrcGen, n: PNode, c: TContext, start: int = 0,
  593. theEnd: int = - 1) =
  594. for i in start..n.len + theEnd: gsub(g, n[i], c)
  595. proc gsection(g: var TSrcGen, n: PNode, c: TContext, kind: TokType,
  596. k: string) =
  597. if n.len == 0: return # empty var sections are possible
  598. putWithSpace(g, kind, k)
  599. gcoms(g)
  600. indentNL(g)
  601. for i in 0..<n.len:
  602. optNL(g)
  603. gsub(g, n[i], c)
  604. gcoms(g)
  605. dedent(g)
  606. proc longMode(g: TSrcGen; n: PNode, start: int = 0, theEnd: int = - 1): bool =
  607. result = shouldRenderComment(g, n)
  608. if not result:
  609. # check further
  610. for i in start..n.len + theEnd:
  611. if (lsub(g, n[i]) > MaxLineLen):
  612. result = true
  613. break
  614. proc gstmts(g: var TSrcGen, n: PNode, c: TContext, doIndent=true) =
  615. if n.kind == nkEmpty: return
  616. if n.kind in {nkStmtList, nkStmtListExpr, nkStmtListType}:
  617. if doIndent: indentNL(g)
  618. for i in 0..<n.len:
  619. if i > 0:
  620. optNL(g, n[i-1], n[i])
  621. else:
  622. optNL(g)
  623. if n[i].kind in {nkStmtList, nkStmtListExpr, nkStmtListType}:
  624. gstmts(g, n[i], c, doIndent=false)
  625. else:
  626. gsub(g, n[i], fromStmtList = true)
  627. gcoms(g)
  628. if doIndent: dedent(g)
  629. else:
  630. indentNL(g)
  631. gsub(g, n)
  632. gcoms(g)
  633. dedent(g)
  634. optNL(g)
  635. proc gcond(g: var TSrcGen, n: PNode) =
  636. if n.kind == nkStmtListExpr:
  637. put(g, tkParLe, "(")
  638. gsub(g, n)
  639. if n.kind == nkStmtListExpr:
  640. put(g, tkParRi, ")")
  641. proc gif(g: var TSrcGen, n: PNode) =
  642. var c: TContext
  643. gcond(g, n[0][0])
  644. initContext(c)
  645. putWithSpace(g, tkColon, ":")
  646. if longMode(g, n) or (lsub(g, n[0][1]) + g.lineLen > MaxLineLen):
  647. incl(c.flags, rfLongMode)
  648. gcoms(g) # a good place for comments
  649. gstmts(g, n[0][1], c)
  650. for i in 1..<n.len:
  651. optNL(g)
  652. gsub(g, n[i], c)
  653. proc gwhile(g: var TSrcGen, n: PNode) =
  654. var c: TContext
  655. putWithSpace(g, tkWhile, "while")
  656. gcond(g, n[0])
  657. putWithSpace(g, tkColon, ":")
  658. initContext(c)
  659. if longMode(g, n) or (lsub(g, n[1]) + g.lineLen > MaxLineLen):
  660. incl(c.flags, rfLongMode)
  661. gcoms(g) # a good place for comments
  662. gstmts(g, n[1], c)
  663. proc gpattern(g: var TSrcGen, n: PNode) =
  664. var c: TContext
  665. put(g, tkCurlyLe, "{")
  666. initContext(c)
  667. if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen):
  668. incl(c.flags, rfLongMode)
  669. gcoms(g) # a good place for comments
  670. gstmts(g, n, c)
  671. put(g, tkCurlyRi, "}")
  672. proc gpragmaBlock(g: var TSrcGen, n: PNode) =
  673. var c: TContext
  674. gsub(g, n[0])
  675. putWithSpace(g, tkColon, ":")
  676. initContext(c)
  677. if longMode(g, n) or (lsub(g, n[1]) + g.lineLen > MaxLineLen):
  678. incl(c.flags, rfLongMode)
  679. gcoms(g) # a good place for comments
  680. gstmts(g, n[1], c)
  681. proc gtry(g: var TSrcGen, n: PNode) =
  682. var c: TContext
  683. put(g, tkTry, "try")
  684. putWithSpace(g, tkColon, ":")
  685. initContext(c)
  686. if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen):
  687. incl(c.flags, rfLongMode)
  688. gcoms(g) # a good place for comments
  689. gstmts(g, n[0], c)
  690. gsons(g, n, c, 1)
  691. proc gfor(g: var TSrcGen, n: PNode) =
  692. var c: TContext
  693. putWithSpace(g, tkFor, "for")
  694. initContext(c)
  695. if longMode(g, n) or
  696. (lsub(g, n[^1]) + lsub(g, n[^2]) + 6 + g.lineLen > MaxLineLen):
  697. incl(c.flags, rfLongMode)
  698. gcomma(g, n, c, 0, - 3)
  699. put(g, tkSpaces, Space)
  700. putWithSpace(g, tkIn, "in")
  701. gsub(g, n[^2], c)
  702. putWithSpace(g, tkColon, ":")
  703. gcoms(g)
  704. gstmts(g, n[^1], c)
  705. proc gcase(g: var TSrcGen, n: PNode) =
  706. var c: TContext
  707. initContext(c)
  708. if n.len == 0: return
  709. var last = if n[^1].kind == nkElse: -2 else: -1
  710. if longMode(g, n, 0, last): incl(c.flags, rfLongMode)
  711. putWithSpace(g, tkCase, "case")
  712. gcond(g, n[0])
  713. gcoms(g)
  714. optNL(g)
  715. gsons(g, n, c, 1, last)
  716. if last == - 2:
  717. initContext(c)
  718. if longMode(g, n[^1]): incl(c.flags, rfLongMode)
  719. gsub(g, n[^1], c)
  720. proc genSymSuffix(result: var string, s: PSym) {.inline.} =
  721. if sfGenSym in s.flags:
  722. result.add '_'
  723. result.addInt s.id
  724. proc gproc(g: var TSrcGen, n: PNode) =
  725. var c: TContext
  726. if n[namePos].kind == nkSym:
  727. let s = n[namePos].sym
  728. var ret = renderDefinitionName(s)
  729. ret.genSymSuffix(s)
  730. put(g, tkSymbol, ret)
  731. else:
  732. gsub(g, n[namePos])
  733. if n[patternPos].kind != nkEmpty:
  734. gpattern(g, n[patternPos])
  735. let oldInGenericParams = g.inGenericParams
  736. g.inGenericParams = true
  737. if renderNoBody in g.flags and n[miscPos].kind != nkEmpty and
  738. n[miscPos][1].kind != nkEmpty:
  739. gsub(g, n[miscPos][1])
  740. else:
  741. gsub(g, n[genericParamsPos])
  742. g.inGenericParams = oldInGenericParams
  743. gsub(g, n[paramsPos])
  744. if renderNoPragmas notin g.flags:
  745. gsub(g, n[pragmasPos])
  746. if renderNoBody notin g.flags:
  747. if n[bodyPos].kind != nkEmpty:
  748. put(g, tkSpaces, Space)
  749. putWithSpace(g, tkEquals, "=")
  750. indentNL(g)
  751. gcoms(g)
  752. dedent(g)
  753. initContext(c)
  754. gstmts(g, n[bodyPos], c)
  755. putNL(g)
  756. else:
  757. indentNL(g)
  758. gcoms(g)
  759. dedent(g)
  760. proc gTypeClassTy(g: var TSrcGen, n: PNode) =
  761. var c: TContext
  762. initContext(c)
  763. putWithSpace(g, tkConcept, "concept")
  764. gsons(g, n[0], c) # arglist
  765. gsub(g, n[1]) # pragmas
  766. gsub(g, n[2]) # of
  767. gcoms(g)
  768. indentNL(g)
  769. gcoms(g)
  770. gstmts(g, n[3], c)
  771. dedent(g)
  772. proc gblock(g: var TSrcGen, n: PNode) =
  773. # you shouldn't simplify it to `n.len < 2`
  774. # because the following codes should be executed
  775. # even when block stmt has only one child for getting
  776. # better error messages.
  777. if n.len == 0:
  778. return
  779. var c: TContext
  780. initContext(c)
  781. if n[0].kind != nkEmpty:
  782. putWithSpace(g, tkBlock, "block")
  783. gsub(g, n[0])
  784. else:
  785. put(g, tkBlock, "block")
  786. # block stmt should have two children
  787. if n.len == 1:
  788. return
  789. putWithSpace(g, tkColon, ":")
  790. if longMode(g, n) or (lsub(g, n[1]) + g.lineLen > MaxLineLen):
  791. incl(c.flags, rfLongMode)
  792. gcoms(g)
  793. gstmts(g, n[1], c)
  794. proc gstaticStmt(g: var TSrcGen, n: PNode) =
  795. var c: TContext
  796. putWithSpace(g, tkStatic, "static")
  797. putWithSpace(g, tkColon, ":")
  798. initContext(c)
  799. if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen):
  800. incl(c.flags, rfLongMode)
  801. gcoms(g) # a good place for comments
  802. gstmts(g, n[0], c)
  803. proc gasm(g: var TSrcGen, n: PNode) =
  804. putWithSpace(g, tkAsm, "asm")
  805. gsub(g, n[0])
  806. gcoms(g)
  807. if n.len > 1:
  808. gsub(g, n[1])
  809. proc gident(g: var TSrcGen, n: PNode) =
  810. if g.inGenericParams and n.kind == nkSym:
  811. if sfAnon in n.sym.flags or
  812. (n.typ != nil and tfImplicitTypeParam in n.typ.flags): return
  813. var t: TokType
  814. var s = atom(g, n)
  815. if s.len > 0 and s[0] in lexer.SymChars:
  816. if n.kind == nkIdent:
  817. if (n.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
  818. (n.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
  819. t = tkSymbol
  820. else:
  821. t = TokType(n.ident.id + ord(tkSymbol))
  822. else:
  823. t = tkSymbol
  824. else:
  825. t = tkOpr
  826. if renderIr in g.flags and n.kind == nkSym:
  827. let localId = disamb(g, n.sym)
  828. if localId != 0 and n.sym.magic == mNone:
  829. s.add '_'
  830. s.addInt localId
  831. if sfCursor in n.sym.flags:
  832. s.add "_cursor"
  833. elif n.kind == nkSym and (renderIds in g.flags or sfGenSym in n.sym.flags or n.sym.kind == skTemp):
  834. s.add '_'
  835. s.addInt n.sym.id
  836. when defined(debugMagics):
  837. s.add '_'
  838. s.add $n.sym.magic
  839. put(g, t, s, if n.kind == nkSym and renderSyms in g.flags: n.sym else: nil)
  840. proc doParamsAux(g: var TSrcGen, params: PNode) =
  841. if params.len > 1:
  842. put(g, tkParLe, "(")
  843. gsemicolon(g, params, 1)
  844. put(g, tkParRi, ")")
  845. if params.len > 0 and params[0].kind != nkEmpty:
  846. put(g, tkSpaces, Space)
  847. putWithSpace(g, tkOpr, "->")
  848. gsub(g, params[0])
  849. proc gsub(g: var TSrcGen; n: PNode; i: int) =
  850. if i < n.len:
  851. gsub(g, n[i])
  852. else:
  853. put(g, tkOpr, "<<" & $i & "th child missing for " & $n.kind & " >>")
  854. type
  855. BracketKind = enum
  856. bkNone, bkBracket, bkBracketAsgn, bkCurly, bkCurlyAsgn
  857. proc bracketKind*(g: TSrcGen, n: PNode): BracketKind =
  858. if renderIds notin g.flags:
  859. case n.kind
  860. of nkClosedSymChoice, nkOpenSymChoice:
  861. if n.len > 0: result = bracketKind(g, n[0])
  862. of nkSym:
  863. result = case n.sym.name.s
  864. of "[]": bkBracket
  865. of "[]=": bkBracketAsgn
  866. of "{}": bkCurly
  867. of "{}=": bkCurlyAsgn
  868. else: bkNone
  869. else: result = bkNone
  870. proc skipHiddenNodes(n: PNode): PNode =
  871. result = n
  872. while result != nil:
  873. if result.kind in {nkHiddenStdConv, nkHiddenSubConv, nkHiddenCallConv} and result.len > 1:
  874. result = result[1]
  875. elif result.kind in {nkCheckedFieldExpr, nkHiddenAddr, nkHiddenDeref, nkStringToCString, nkCStringToString} and
  876. result.len > 0:
  877. result = result[0]
  878. else: break
  879. proc accentedName(g: var TSrcGen, n: PNode) =
  880. # This is for cases where ident should've really been a `nkAccQuoted`, e.g. `:tmp`
  881. # or if user writes a macro with `ident":foo"`. It's unclear whether these should be legal.
  882. const backticksNeeded = OpChars + {'[', '{', '\''}
  883. if n == nil: return
  884. let ident = n.getPIdent
  885. if ident != nil and ident.s[0] in backticksNeeded:
  886. put(g, tkAccent, "`")
  887. gident(g, n)
  888. put(g, tkAccent, "`")
  889. else:
  890. gsub(g, n)
  891. proc infixArgument(g: var TSrcGen, n: PNode, i: int) =
  892. if i < 1 and i > 2: return
  893. var needsParenthesis = false
  894. let nNext = n[i].skipHiddenNodes
  895. if nNext.kind == nkInfix:
  896. if nNext[0].kind in {nkSym, nkIdent} and n[0].kind in {nkSym, nkIdent}:
  897. let nextId = if nNext[0].kind == nkSym: nNext[0].sym.name else: nNext[0].ident
  898. let nnId = if n[0].kind == nkSym: n[0].sym.name else: n[0].ident
  899. if i == 1:
  900. if getPrecedence(nextId) < getPrecedence(nnId):
  901. needsParenthesis = true
  902. elif i == 2:
  903. if getPrecedence(nextId) <= getPrecedence(nnId):
  904. needsParenthesis = true
  905. if needsParenthesis:
  906. put(g, tkParLe, "(")
  907. gsub(g, n, i)
  908. if needsParenthesis:
  909. put(g, tkParRi, ")")
  910. const postExprBlocks = {nkStmtList, nkStmtListExpr,
  911. nkOfBranch, nkElifBranch, nkElse,
  912. nkExceptBranch, nkFinally, nkDo}
  913. proc postStatements(g: var TSrcGen, n: PNode, i: int, fromStmtList: bool) =
  914. var i = i
  915. if n[i].kind in {nkStmtList, nkStmtListExpr}:
  916. if fromStmtList:
  917. put(g, tkColon, ":")
  918. else:
  919. put(g, tkSpaces, Space)
  920. put(g, tkDo, "do")
  921. put(g, tkColon, ":")
  922. gsub(g, n, i)
  923. i.inc
  924. for j in i ..< n.len:
  925. if n[j].kind == nkDo:
  926. optNL(g)
  927. elif n[j].kind in {nkStmtList, nkStmtListExpr}:
  928. optNL(g)
  929. put(g, tkDo, "do")
  930. put(g, tkColon, ":")
  931. gsub(g, n, j)
  932. proc isCustomLit(n: PNode): bool =
  933. if n.len == 2 and n[0].kind == nkRStrLit:
  934. let ident = n[1].getPIdent
  935. result = ident != nil and ident.s.startsWith('\'')
  936. proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) =
  937. if isNil(n): return
  938. var
  939. a: TContext
  940. if shouldRenderComment(g, n): pushCom(g, n)
  941. case n.kind # atoms:
  942. of nkTripleStrLit: put(g, tkTripleStrLit, atom(g, n))
  943. of nkEmpty: discard
  944. of nkType: put(g, tkInvalid, atom(g, n))
  945. of nkSym, nkIdent: gident(g, n)
  946. of nkIntLit: put(g, tkIntLit, atom(g, n))
  947. of nkInt8Lit: put(g, tkInt8Lit, atom(g, n))
  948. of nkInt16Lit: put(g, tkInt16Lit, atom(g, n))
  949. of nkInt32Lit: put(g, tkInt32Lit, atom(g, n))
  950. of nkInt64Lit: put(g, tkInt64Lit, atom(g, n))
  951. of nkUIntLit: put(g, tkUIntLit, atom(g, n))
  952. of nkUInt8Lit: put(g, tkUInt8Lit, atom(g, n))
  953. of nkUInt16Lit: put(g, tkUInt16Lit, atom(g, n))
  954. of nkUInt32Lit: put(g, tkUInt32Lit, atom(g, n))
  955. of nkUInt64Lit: put(g, tkUInt64Lit, atom(g, n))
  956. of nkFloatLit: put(g, tkFloatLit, atom(g, n))
  957. of nkFloat32Lit: put(g, tkFloat32Lit, atom(g, n))
  958. of nkFloat64Lit: put(g, tkFloat64Lit, atom(g, n))
  959. of nkFloat128Lit: put(g, tkFloat128Lit, atom(g, n))
  960. of nkStrLit: put(g, tkStrLit, atom(g, n))
  961. of nkRStrLit: put(g, tkRStrLit, atom(g, n))
  962. of nkCharLit: put(g, tkCharLit, atom(g, n))
  963. of nkNilLit: put(g, tkNil, atom(g, n)) # complex expressions
  964. of nkCall, nkConv, nkDotCall, nkPattern, nkObjConstr:
  965. if n.len > 1 and n.lastSon.kind in postExprBlocks:
  966. accentedName(g, n[0])
  967. var i = 1
  968. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  969. if i > 1:
  970. put(g, tkParLe, "(")
  971. gcomma(g, n, 1, i - 1 - n.len)
  972. put(g, tkParRi, ")")
  973. postStatements(g, n, i, fromStmtList)
  974. elif n.len >= 1:
  975. case bracketKind(g, n[0])
  976. of bkBracket:
  977. gsub(g, n, 1)
  978. put(g, tkBracketLe, "[")
  979. gcomma(g, n, 2)
  980. put(g, tkBracketRi, "]")
  981. of bkBracketAsgn:
  982. gsub(g, n, 1)
  983. put(g, tkBracketLe, "[")
  984. gcomma(g, n, 2, -2)
  985. put(g, tkBracketRi, "]")
  986. put(g, tkSpaces, Space)
  987. putWithSpace(g, tkEquals, "=")
  988. gsub(g, n, n.len - 1)
  989. of bkCurly:
  990. gsub(g, n, 1)
  991. put(g, tkCurlyLe, "{")
  992. gcomma(g, n, 2)
  993. put(g, tkCurlyRi, "}")
  994. of bkCurlyAsgn:
  995. gsub(g, n, 1)
  996. put(g, tkCurlyLe, "{")
  997. gcomma(g, n, 2, -2)
  998. put(g, tkCurlyRi, "}")
  999. put(g, tkSpaces, Space)
  1000. putWithSpace(g, tkEquals, "=")
  1001. gsub(g, n, n.len - 1)
  1002. of bkNone:
  1003. accentedName(g, n[0])
  1004. put(g, tkParLe, "(")
  1005. gcomma(g, n, 1)
  1006. put(g, tkParRi, ")")
  1007. else:
  1008. put(g, tkParLe, "(")
  1009. put(g, tkParRi, ")")
  1010. of nkCallStrLit:
  1011. if n.len > 0: accentedName(g, n[0])
  1012. if n.len > 1 and n[1].kind == nkRStrLit:
  1013. put(g, tkRStrLit, '\"' & replace(n[1].strVal, "\"", "\"\"") & '\"')
  1014. else:
  1015. gsub(g, n, 1)
  1016. of nkHiddenStdConv, nkHiddenSubConv:
  1017. if n.len >= 2:
  1018. when false:
  1019. # if {renderIds, renderIr} * g.flags != {}:
  1020. put(g, tkSymbol, "(conv)")
  1021. put(g, tkParLe, "(")
  1022. gsub(g, n[1])
  1023. put(g, tkParRi, ")")
  1024. else:
  1025. gsub(g, n[1])
  1026. else:
  1027. put(g, tkSymbol, "(wrong conv)")
  1028. of nkHiddenCallConv:
  1029. if {renderIds, renderIr} * g.flags != {}:
  1030. accentedName(g, n[0])
  1031. put(g, tkParLe, "(")
  1032. gcomma(g, n, 1)
  1033. put(g, tkParRi, ")")
  1034. elif n.len >= 2:
  1035. gsub(g, n[1])
  1036. else:
  1037. put(g, tkSymbol, "(wrong conv)")
  1038. of nkCast:
  1039. put(g, tkCast, "cast")
  1040. if n.len > 0 and n[0].kind != nkEmpty:
  1041. put(g, tkBracketLe, "[")
  1042. gsub(g, n, 0)
  1043. put(g, tkBracketRi, "]")
  1044. put(g, tkParLe, "(")
  1045. gsub(g, n, 1)
  1046. put(g, tkParRi, ")")
  1047. of nkAddr:
  1048. put(g, tkAddr, "addr")
  1049. if n.len > 0:
  1050. put(g, tkParLe, "(")
  1051. gsub(g, n[0])
  1052. put(g, tkParRi, ")")
  1053. of nkStaticExpr:
  1054. put(g, tkStatic, "static")
  1055. put(g, tkSpaces, Space)
  1056. gsub(g, n, 0)
  1057. of nkBracketExpr:
  1058. gsub(g, n, 0)
  1059. put(g, tkBracketLe, "[")
  1060. gcomma(g, n, 1)
  1061. put(g, tkBracketRi, "]")
  1062. of nkCurlyExpr:
  1063. gsub(g, n, 0)
  1064. put(g, tkCurlyLe, "{")
  1065. gcomma(g, n, 1)
  1066. put(g, tkCurlyRi, "}")
  1067. of nkPragmaExpr:
  1068. gsub(g, n, 0)
  1069. gcomma(g, n, 1)
  1070. of nkCommand:
  1071. accentedName(g, n[0])
  1072. put(g, tkSpaces, Space)
  1073. if n.len > 1 and n.lastSon.kind in postExprBlocks:
  1074. var i = 1
  1075. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1076. if i > 1:
  1077. gcomma(g, n, 1, i - 1 - n.len)
  1078. postStatements(g, n, i, fromStmtList)
  1079. else:
  1080. gcomma(g, n, 1)
  1081. of nkExprEqExpr, nkAsgn, nkFastAsgn:
  1082. gsub(g, n, 0)
  1083. put(g, tkSpaces, Space)
  1084. putWithSpace(g, tkEquals, "=")
  1085. gsub(g, n, 1)
  1086. of nkSinkAsgn:
  1087. put(g, tkSymbol, "`=sink`")
  1088. put(g, tkParLe, "(")
  1089. gcomma(g, n)
  1090. put(g, tkParRi, ")")
  1091. of nkChckRangeF:
  1092. put(g, tkSymbol, "chckRangeF")
  1093. put(g, tkParLe, "(")
  1094. gcomma(g, n)
  1095. put(g, tkParRi, ")")
  1096. of nkChckRange64:
  1097. put(g, tkSymbol, "chckRange64")
  1098. put(g, tkParLe, "(")
  1099. gcomma(g, n)
  1100. put(g, tkParRi, ")")
  1101. of nkChckRange:
  1102. put(g, tkSymbol, "chckRange")
  1103. put(g, tkParLe, "(")
  1104. gcomma(g, n)
  1105. put(g, tkParRi, ")")
  1106. of nkObjDownConv, nkObjUpConv:
  1107. let typ = if (n.typ != nil) and (n.typ.sym != nil): n.typ.sym.name.s else: ""
  1108. put(g, tkParLe, typ & "(")
  1109. if n.len >= 1: gsub(g, n[0])
  1110. put(g, tkParRi, ")")
  1111. of nkClosedSymChoice, nkOpenSymChoice:
  1112. if renderIds in g.flags:
  1113. put(g, tkParLe, "(")
  1114. for i in 0..<n.len:
  1115. if i > 0: put(g, tkOpr, "|")
  1116. if n[i].kind == nkSym:
  1117. let s = n[i].sym
  1118. if s.owner != nil:
  1119. put g, tkSymbol, n[i].sym.owner.name.s
  1120. put g, tkOpr, "."
  1121. put g, tkSymbol, n[i].sym.name.s
  1122. else:
  1123. gsub(g, n[i], c)
  1124. put(g, tkParRi, if n.kind == nkOpenSymChoice: "|...)" else: ")")
  1125. else:
  1126. gsub(g, n, 0)
  1127. of nkPar, nkClosure:
  1128. put(g, tkParLe, "(")
  1129. gcomma(g, n, c)
  1130. put(g, tkParRi, ")")
  1131. of nkTupleConstr:
  1132. put(g, tkParLe, "(")
  1133. gcomma(g, n, c)
  1134. if n.len == 1 and n[0].kind != nkExprColonExpr: put(g, tkComma, ",")
  1135. put(g, tkParRi, ")")
  1136. of nkCurly:
  1137. put(g, tkCurlyLe, "{")
  1138. gcomma(g, n, c)
  1139. put(g, tkCurlyRi, "}")
  1140. of nkArgList:
  1141. gcomma(g, n, c)
  1142. of nkTableConstr:
  1143. put(g, tkCurlyLe, "{")
  1144. if n.len > 0: gcomma(g, n, c)
  1145. else: put(g, tkColon, ":")
  1146. put(g, tkCurlyRi, "}")
  1147. of nkBracket:
  1148. put(g, tkBracketLe, "[")
  1149. gcomma(g, n, c)
  1150. put(g, tkBracketRi, "]")
  1151. of nkDotExpr:
  1152. if isCustomLit(n):
  1153. put(g, tkCustomLit, n[0].strVal)
  1154. gsub(g, n, 1)
  1155. else:
  1156. gsub(g, n, 0)
  1157. put(g, tkDot, ".")
  1158. assert n.len == 2, $n.len
  1159. accentedName(g, n[1])
  1160. of nkBind:
  1161. putWithSpace(g, tkBind, "bind")
  1162. gsub(g, n, 0)
  1163. of nkCheckedFieldExpr, nkHiddenAddr, nkHiddenDeref, nkStringToCString, nkCStringToString:
  1164. if renderIds in g.flags:
  1165. putWithSpace(g, tkAddr, $n.kind)
  1166. gsub(g, n, 0)
  1167. of nkLambda:
  1168. putWithSpace(g, tkProc, "proc")
  1169. gsub(g, n, paramsPos)
  1170. gsub(g, n, pragmasPos)
  1171. put(g, tkSpaces, Space)
  1172. putWithSpace(g, tkEquals, "=")
  1173. gsub(g, n, bodyPos)
  1174. of nkDo:
  1175. putWithSpace(g, tkDo, "do")
  1176. if paramsPos < n.len:
  1177. doParamsAux(g, n[paramsPos])
  1178. gsub(g, n, pragmasPos)
  1179. put(g, tkColon, ":")
  1180. gsub(g, n, bodyPos)
  1181. of nkConstDef, nkIdentDefs:
  1182. gcomma(g, n, 0, -3)
  1183. if n.len >= 2 and n[^2].kind != nkEmpty:
  1184. putWithSpace(g, tkColon, ":")
  1185. gsub(g, n, n.len - 2)
  1186. if n.len >= 1 and n[^1].kind != nkEmpty:
  1187. put(g, tkSpaces, Space)
  1188. putWithSpace(g, tkEquals, "=")
  1189. gsub(g, n[^1], c)
  1190. of nkVarTuple:
  1191. if n[^1].kind == nkEmpty:
  1192. put(g, tkParLe, "(")
  1193. gcomma(g, n, 0, -2)
  1194. put(g, tkParRi, ")")
  1195. else:
  1196. put(g, tkParLe, "(")
  1197. gcomma(g, n, 0, -3)
  1198. put(g, tkParRi, ")")
  1199. put(g, tkSpaces, Space)
  1200. putWithSpace(g, tkEquals, "=")
  1201. gsub(g, lastSon(n), c)
  1202. of nkExprColonExpr:
  1203. gsub(g, n, 0)
  1204. putWithSpace(g, tkColon, ":")
  1205. gsub(g, n, 1)
  1206. of nkInfix:
  1207. let oldLineLen = g.lineLen # we cache this because lineLen gets updated below
  1208. infixArgument(g, n, 1)
  1209. put(g, tkSpaces, Space)
  1210. gsub(g, n, 0) # binary operator
  1211. # e.g.: `n1 == n2` decompses as following sum:
  1212. if n.len == 3 and not fits(g, oldLineLen + lsub(g, n[1]) + lsub(g, n[2]) + lsub(g, n[0]) + len(" ")):
  1213. optNL(g, g.indent + longIndentWid)
  1214. else:
  1215. put(g, tkSpaces, Space)
  1216. infixArgument(g, n, 2)
  1217. if n.len > 3 and n.lastSon.kind in postExprBlocks:
  1218. var i = 3
  1219. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1220. postStatements(g, n, i, fromStmtList)
  1221. of nkPrefix:
  1222. gsub(g, n, 0)
  1223. if n.len > 1:
  1224. let opr = if n[0].kind == nkIdent: n[0].ident
  1225. elif n[0].kind == nkSym: n[0].sym.name
  1226. elif n[0].kind in {nkOpenSymChoice, nkClosedSymChoice}: n[0][0].sym.name
  1227. else: nil
  1228. let nNext = skipHiddenNodes(n[1])
  1229. if nNext.kind == nkPrefix or (opr != nil and renderer.isKeyword(opr)):
  1230. put(g, tkSpaces, Space)
  1231. if nNext.kind == nkInfix:
  1232. put(g, tkParLe, "(")
  1233. gsub(g, n[1])
  1234. put(g, tkParRi, ")")
  1235. else:
  1236. gsub(g, n[1])
  1237. if n.len > 2 and n.lastSon.kind in postExprBlocks:
  1238. var i = 2
  1239. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1240. postStatements(g, n, i, fromStmtList)
  1241. of nkPostfix:
  1242. gsub(g, n, 1)
  1243. gsub(g, n, 0)
  1244. of nkRange:
  1245. gsub(g, n, 0)
  1246. put(g, tkDotDot, "..")
  1247. gsub(g, n, 1)
  1248. of nkDerefExpr:
  1249. gsub(g, n, 0)
  1250. put(g, tkOpr, "[]")
  1251. of nkAccQuoted:
  1252. put(g, tkAccent, "`")
  1253. for i in 0..<n.len:
  1254. proc getStrVal(n: PNode): string =
  1255. # pending https://github.com/nim-lang/Nim/pull/17540, use `getStrVal`
  1256. case n.kind
  1257. of nkIdent: n.ident.s
  1258. of nkSym: n.sym.name.s
  1259. else: ""
  1260. proc isAlpha(n: PNode): bool =
  1261. if n.kind in {nkIdent, nkSym}:
  1262. let tmp = n.getStrVal
  1263. result = tmp.len > 0 and tmp[0] in {'a'..'z', 'A'..'Z'}
  1264. var useSpace = false
  1265. if i == 1 and n[0].kind == nkIdent and n[0].ident.s in ["=", "'"]:
  1266. if not n[1].isAlpha: # handle `=destroy`, `'big'
  1267. useSpace = true
  1268. elif i == 1 and n[1].kind == nkIdent and n[1].ident.s == "=":
  1269. if not n[0].isAlpha: # handle setters, e.g. `foo=`
  1270. useSpace = true
  1271. elif i > 0: useSpace = true
  1272. if useSpace: put(g, tkSpaces, Space)
  1273. gsub(g, n[i])
  1274. put(g, tkAccent, "`")
  1275. of nkIfExpr:
  1276. putWithSpace(g, tkIf, "if")
  1277. if n.len > 0: gcond(g, n[0][0])
  1278. putWithSpace(g, tkColon, ":")
  1279. if n.len > 0: gsub(g, n[0], 1)
  1280. gsons(g, n, emptyContext, 1)
  1281. of nkElifExpr:
  1282. putWithSpace(g, tkElif, " elif")
  1283. gcond(g, n[0])
  1284. putWithSpace(g, tkColon, ":")
  1285. gsub(g, n, 1)
  1286. of nkElseExpr:
  1287. put(g, tkElse, " else")
  1288. putWithSpace(g, tkColon, ":")
  1289. gsub(g, n, 0)
  1290. of nkTypeOfExpr:
  1291. put(g, tkType, "typeof")
  1292. put(g, tkParLe, "(")
  1293. if n.len > 0: gsub(g, n[0])
  1294. put(g, tkParRi, ")")
  1295. of nkRefTy:
  1296. if n.len > 0:
  1297. putWithSpace(g, tkRef, "ref")
  1298. gsub(g, n[0])
  1299. else:
  1300. put(g, tkRef, "ref")
  1301. of nkPtrTy:
  1302. if n.len > 0:
  1303. putWithSpace(g, tkPtr, "ptr")
  1304. gsub(g, n[0])
  1305. else:
  1306. put(g, tkPtr, "ptr")
  1307. of nkVarTy:
  1308. if n.len > 0:
  1309. putWithSpace(g, tkVar, "var")
  1310. gsub(g, n[0])
  1311. else:
  1312. put(g, tkVar, "var")
  1313. of nkOutTy:
  1314. if n.len > 0:
  1315. putWithSpace(g, tkOut, "out")
  1316. gsub(g, n[0])
  1317. else:
  1318. put(g, tkOut, "out")
  1319. of nkDistinctTy:
  1320. if n.len > 0:
  1321. putWithSpace(g, tkDistinct, "distinct")
  1322. gsub(g, n[0])
  1323. if n.len > 1:
  1324. if n[1].kind == nkWith:
  1325. putWithSpace(g, tkSymbol, " with")
  1326. else:
  1327. putWithSpace(g, tkSymbol, " without")
  1328. gcomma(g, n[1])
  1329. else:
  1330. put(g, tkDistinct, "distinct")
  1331. of nkTypeDef:
  1332. if n[0].kind == nkPragmaExpr:
  1333. # generate pragma after generic
  1334. gsub(g, n[0], 0)
  1335. gsub(g, n, 1)
  1336. gsub(g, n[0], 1)
  1337. else:
  1338. gsub(g, n, 0)
  1339. gsub(g, n, 1)
  1340. put(g, tkSpaces, Space)
  1341. if n.len > 2 and n[2].kind != nkEmpty:
  1342. putWithSpace(g, tkEquals, "=")
  1343. gsub(g, n[2])
  1344. of nkObjectTy:
  1345. if n.len > 0:
  1346. putWithSpace(g, tkObject, "object")
  1347. gsub(g, n[0])
  1348. gsub(g, n[1])
  1349. gcoms(g)
  1350. gsub(g, n[2])
  1351. else:
  1352. put(g, tkObject, "object")
  1353. of nkRecList:
  1354. indentNL(g)
  1355. for i in 0..<n.len:
  1356. optNL(g)
  1357. gsub(g, n[i], c)
  1358. gcoms(g)
  1359. dedent(g)
  1360. putNL(g)
  1361. of nkOfInherit:
  1362. putWithSpace(g, tkOf, "of")
  1363. gsub(g, n, 0)
  1364. of nkProcTy:
  1365. if n.len > 0:
  1366. putWithSpace(g, tkProc, "proc")
  1367. gsub(g, n, 0)
  1368. gsub(g, n, 1)
  1369. else:
  1370. put(g, tkProc, "proc")
  1371. of nkIteratorTy:
  1372. if n.len > 0:
  1373. putWithSpace(g, tkIterator, "iterator")
  1374. gsub(g, n, 0)
  1375. gsub(g, n, 1)
  1376. else:
  1377. put(g, tkIterator, "iterator")
  1378. of nkStaticTy:
  1379. put(g, tkStatic, "static")
  1380. put(g, tkBracketLe, "[")
  1381. if n.len > 0:
  1382. gsub(g, n[0])
  1383. put(g, tkBracketRi, "]")
  1384. of nkEnumTy:
  1385. if n.len > 0:
  1386. putWithSpace(g, tkEnum, "enum")
  1387. gsub(g, n[0])
  1388. gcoms(g)
  1389. indentNL(g)
  1390. gcommaAux(g, n, g.indent, 1)
  1391. gcoms(g) # BUGFIX: comment for the last enum field
  1392. dedent(g)
  1393. else:
  1394. put(g, tkEnum, "enum")
  1395. of nkEnumFieldDef:
  1396. gsub(g, n, 0)
  1397. put(g, tkSpaces, Space)
  1398. putWithSpace(g, tkEquals, "=")
  1399. gsub(g, n, 1)
  1400. of nkStmtList, nkStmtListExpr, nkStmtListType:
  1401. if n.len == 1 and n[0].kind == nkDiscardStmt:
  1402. put(g, tkParLe, "(")
  1403. gsub(g, n[0])
  1404. put(g, tkParRi, ")")
  1405. else:
  1406. gstmts(g, n, emptyContext)
  1407. of nkIfStmt:
  1408. putWithSpace(g, tkIf, "if")
  1409. gif(g, n)
  1410. of nkWhen, nkRecWhen:
  1411. putWithSpace(g, tkWhen, "when")
  1412. gif(g, n)
  1413. of nkWhileStmt: gwhile(g, n)
  1414. of nkPragmaBlock: gpragmaBlock(g, n)
  1415. of nkCaseStmt, nkRecCase: gcase(g, n)
  1416. of nkTryStmt, nkHiddenTryStmt: gtry(g, n)
  1417. of nkForStmt, nkParForStmt: gfor(g, n)
  1418. of nkBlockStmt, nkBlockExpr: gblock(g, n)
  1419. of nkStaticStmt: gstaticStmt(g, n)
  1420. of nkAsmStmt: gasm(g, n)
  1421. of nkProcDef:
  1422. if renderNoProcDefs notin g.flags: putWithSpace(g, tkProc, "proc")
  1423. gproc(g, n)
  1424. of nkFuncDef:
  1425. if renderNoProcDefs notin g.flags: putWithSpace(g, tkFunc, "func")
  1426. gproc(g, n)
  1427. of nkConverterDef:
  1428. if renderNoProcDefs notin g.flags: putWithSpace(g, tkConverter, "converter")
  1429. gproc(g, n)
  1430. of nkMethodDef:
  1431. if renderNoProcDefs notin g.flags: putWithSpace(g, tkMethod, "method")
  1432. gproc(g, n)
  1433. of nkIteratorDef:
  1434. if renderNoProcDefs notin g.flags: putWithSpace(g, tkIterator, "iterator")
  1435. gproc(g, n)
  1436. of nkMacroDef:
  1437. if renderNoProcDefs notin g.flags: putWithSpace(g, tkMacro, "macro")
  1438. gproc(g, n)
  1439. of nkTemplateDef:
  1440. if renderNoProcDefs notin g.flags: putWithSpace(g, tkTemplate, "template")
  1441. gproc(g, n)
  1442. of nkTypeSection:
  1443. gsection(g, n, emptyContext, tkType, "type")
  1444. of nkConstSection:
  1445. initContext(a)
  1446. incl(a.flags, rfInConstExpr)
  1447. gsection(g, n, a, tkConst, "const")
  1448. of nkVarSection, nkLetSection, nkUsingStmt:
  1449. if n.len == 0: return
  1450. if n.kind == nkVarSection: putWithSpace(g, tkVar, "var")
  1451. elif n.kind == nkLetSection: putWithSpace(g, tkLet, "let")
  1452. else: putWithSpace(g, tkUsing, "using")
  1453. if n.len > 1:
  1454. gcoms(g)
  1455. indentNL(g)
  1456. for i in 0..<n.len:
  1457. optNL(g)
  1458. gsub(g, n[i])
  1459. gcoms(g)
  1460. dedent(g)
  1461. else:
  1462. gsub(g, n[0])
  1463. of nkReturnStmt:
  1464. putWithSpace(g, tkReturn, "return")
  1465. if n.len > 0 and n[0].kind == nkAsgn:
  1466. gsub(g, n[0], 1)
  1467. else:
  1468. gsub(g, n, 0)
  1469. of nkRaiseStmt:
  1470. putWithSpace(g, tkRaise, "raise")
  1471. gsub(g, n, 0)
  1472. of nkYieldStmt:
  1473. putWithSpace(g, tkYield, "yield")
  1474. gsub(g, n, 0)
  1475. of nkDiscardStmt:
  1476. putWithSpace(g, tkDiscard, "discard")
  1477. gsub(g, n, 0)
  1478. of nkBreakStmt:
  1479. putWithSpace(g, tkBreak, "break")
  1480. gsub(g, n, 0)
  1481. of nkContinueStmt:
  1482. putWithSpace(g, tkContinue, "continue")
  1483. gsub(g, n, 0)
  1484. of nkPragma:
  1485. if g.inPragma <= 0:
  1486. inc g.inPragma
  1487. #if not previousNL(g):
  1488. put(g, tkSpaces, Space)
  1489. put(g, tkCurlyDotLe, "{.")
  1490. gcomma(g, n, emptyContext)
  1491. put(g, tkCurlyDotRi, ".}")
  1492. dec g.inPragma
  1493. else:
  1494. gcomma(g, n, emptyContext)
  1495. of nkImportStmt, nkExportStmt:
  1496. if n.kind == nkImportStmt:
  1497. putWithSpace(g, tkImport, "import")
  1498. else:
  1499. putWithSpace(g, tkExport, "export")
  1500. gcoms(g)
  1501. indentNL(g)
  1502. gcommaAux(g, n, g.indent)
  1503. dedent(g)
  1504. putNL(g)
  1505. of nkImportExceptStmt, nkExportExceptStmt:
  1506. if n.kind == nkImportExceptStmt:
  1507. putWithSpace(g, tkImport, "import")
  1508. else:
  1509. putWithSpace(g, tkExport, "export")
  1510. gsub(g, n, 0)
  1511. put(g, tkSpaces, Space)
  1512. putWithSpace(g, tkExcept, "except")
  1513. gcommaAux(g, n, g.indent, 1)
  1514. gcoms(g)
  1515. putNL(g)
  1516. of nkFromStmt:
  1517. putWithSpace(g, tkFrom, "from")
  1518. gsub(g, n, 0)
  1519. put(g, tkSpaces, Space)
  1520. putWithSpace(g, tkImport, "import")
  1521. gcomma(g, n, emptyContext, 1)
  1522. putNL(g)
  1523. of nkIncludeStmt:
  1524. putWithSpace(g, tkInclude, "include")
  1525. gcoms(g)
  1526. indentNL(g)
  1527. gcommaAux(g, n, g.indent)
  1528. dedent(g)
  1529. putNL(g)
  1530. of nkCommentStmt:
  1531. gcoms(g)
  1532. optNL(g)
  1533. of nkOfBranch:
  1534. optNL(g)
  1535. putWithSpace(g, tkOf, "of")
  1536. gcomma(g, n, c, 0, - 2)
  1537. putWithSpace(g, tkColon, ":")
  1538. gcoms(g)
  1539. gstmts(g, lastSon(n), c)
  1540. of nkImportAs:
  1541. gsub(g, n, 0)
  1542. put(g, tkSpaces, Space)
  1543. putWithSpace(g, tkAs, "as")
  1544. gsub(g, n, 1)
  1545. of nkBindStmt:
  1546. putWithSpace(g, tkBind, "bind")
  1547. gcomma(g, n, c)
  1548. of nkMixinStmt:
  1549. putWithSpace(g, tkMixin, "mixin")
  1550. gcomma(g, n, c)
  1551. of nkElifBranch:
  1552. optNL(g)
  1553. putWithSpace(g, tkElif, "elif")
  1554. gsub(g, n, 0)
  1555. putWithSpace(g, tkColon, ":")
  1556. gcoms(g)
  1557. gstmts(g, n[1], c)
  1558. of nkElse:
  1559. optNL(g)
  1560. put(g, tkElse, "else")
  1561. putWithSpace(g, tkColon, ":")
  1562. gcoms(g)
  1563. gstmts(g, n[0], c)
  1564. of nkFinally, nkDefer:
  1565. optNL(g)
  1566. if n.kind == nkFinally:
  1567. put(g, tkFinally, "finally")
  1568. else:
  1569. put(g, tkDefer, "defer")
  1570. putWithSpace(g, tkColon, ":")
  1571. gcoms(g)
  1572. gstmts(g, n[0], c)
  1573. of nkExceptBranch:
  1574. optNL(g)
  1575. if n.len != 1:
  1576. putWithSpace(g, tkExcept, "except")
  1577. else:
  1578. put(g, tkExcept, "except")
  1579. gcomma(g, n, 0, -2)
  1580. putWithSpace(g, tkColon, ":")
  1581. gcoms(g)
  1582. gstmts(g, lastSon(n), c)
  1583. of nkGenericParams:
  1584. proc hasExplicitParams(gp: PNode): bool =
  1585. for p in gp:
  1586. if p.typ == nil or tfImplicitTypeParam notin p.typ.flags:
  1587. return true
  1588. return false
  1589. if n.hasExplicitParams:
  1590. put(g, tkBracketLe, "[")
  1591. gsemicolon(g, n)
  1592. put(g, tkBracketRi, "]")
  1593. of nkFormalParams:
  1594. put(g, tkParLe, "(")
  1595. gsemicolon(g, n, 1)
  1596. put(g, tkParRi, ")")
  1597. if n.len > 0 and n[0].kind != nkEmpty:
  1598. putWithSpace(g, tkColon, ":")
  1599. gsub(g, n[0])
  1600. of nkTupleTy:
  1601. put(g, tkTuple, "tuple")
  1602. put(g, tkBracketLe, "[")
  1603. gcomma(g, n)
  1604. put(g, tkBracketRi, "]")
  1605. of nkTupleClassTy:
  1606. put(g, tkTuple, "tuple")
  1607. of nkComesFrom:
  1608. put(g, tkParLe, "(ComesFrom|")
  1609. gsub(g, n, 0)
  1610. put(g, tkParRi, ")")
  1611. of nkGotoState:
  1612. var c: TContext
  1613. initContext c
  1614. putWithSpace g, tkSymbol, "goto"
  1615. gsons(g, n, c)
  1616. of nkState:
  1617. var c: TContext
  1618. initContext c
  1619. putWithSpace g, tkSymbol, "state"
  1620. gsub(g, n[0], c)
  1621. putWithSpace(g, tkColon, ":")
  1622. indentNL(g)
  1623. gsons(g, n, c, 1)
  1624. dedent(g)
  1625. of nkBreakState:
  1626. put(g, tkTuple, "breakstate")
  1627. if renderIds in g.flags:
  1628. gsons(g, n, c, 0)
  1629. of nkTypeClassTy:
  1630. gTypeClassTy(g, n)
  1631. of nkError:
  1632. putWithSpace(g, tkSymbol, "error")
  1633. #gcomma(g, n, c)
  1634. gsub(g, n[0], c)
  1635. else:
  1636. #nkNone, nkExplicitTypeListCall:
  1637. internalError(g.config, n.info, "renderer.gsub(" & $n.kind & ')')
  1638. proc renderTree*(n: PNode, renderFlags: TRenderFlags = {}): string =
  1639. if n == nil: return "<nil tree>"
  1640. var g: TSrcGen
  1641. initSrcGen(g, renderFlags, newPartialConfigRef())
  1642. # do not indent the initial statement list so that
  1643. # writeFile("file.nim", repr n)
  1644. # produces working Nim code:
  1645. if n.kind in {nkStmtList, nkStmtListExpr, nkStmtListType}:
  1646. gstmts(g, n, emptyContext, doIndent = false)
  1647. else:
  1648. gsub(g, n)
  1649. result = g.buf
  1650. proc `$`*(n: PNode): string = n.renderTree
  1651. proc renderModule*(n: PNode, outfile: string,
  1652. renderFlags: TRenderFlags = {};
  1653. fid = FileIndex(-1);
  1654. conf: ConfigRef = nil) =
  1655. var
  1656. f: File
  1657. g: TSrcGen
  1658. initSrcGen(g, renderFlags, conf)
  1659. g.fid = fid
  1660. for i in 0..<n.len:
  1661. gsub(g, n[i])
  1662. optNL(g)
  1663. case n[i].kind
  1664. of nkTypeSection, nkConstSection, nkVarSection, nkLetSection,
  1665. nkCommentStmt: putNL(g)
  1666. else: discard
  1667. gcoms(g)
  1668. if open(f, outfile, fmWrite):
  1669. write(f, g.buf)
  1670. close(f)
  1671. else:
  1672. rawMessage(g.config, errGenerated, "cannot open file: " & outfile)
  1673. proc initTokRender*(r: var TSrcGen, n: PNode, renderFlags: TRenderFlags = {}) =
  1674. initSrcGen(r, renderFlags, newPartialConfigRef())
  1675. gsub(r, n)
  1676. proc getNextTok*(r: var TSrcGen, kind: var TokType, literal: var string) =
  1677. if r.idx < r.tokens.len:
  1678. kind = r.tokens[r.idx].kind
  1679. let length = r.tokens[r.idx].length.int
  1680. literal = substr(r.buf, r.pos, r.pos + length - 1)
  1681. inc(r.pos, length)
  1682. inc(r.idx)
  1683. else:
  1684. kind = tkEof
  1685. proc getTokSym*(r: TSrcGen): PSym =
  1686. if r.idx > 0 and r.idx <= r.tokens.len:
  1687. result = r.tokens[r.idx-1].sym
  1688. else:
  1689. result = nil