renderer.nim 57 KB

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