renderer.nim 56 KB

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