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