renderer.nim 49 KB

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