renderer.nim 47 KB

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