renderer.nim 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  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: 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: result = lsons(g, n) + len("_elif_:_")
  515. of nkElseExpr: result = lsub(g, n[0]) + len("_else:_") # type descriptions
  516. of nkTypeOfExpr: result = (if n.len > 0: lsub(g, n[0]) else: 0)+len("typeof()")
  517. of nkRefTy: result = (if n.len > 0: lsub(g, n[0])+1 else: 0) + len("ref")
  518. of nkPtrTy: result = (if n.len > 0: lsub(g, n[0])+1 else: 0) + len("ptr")
  519. of nkVarTy, nkOutTy: result = (if n.len > 0: lsub(g, n[0])+1 else: 0) + len("var")
  520. of nkDistinctTy:
  521. result = len("distinct") + (if n.len > 0: lsub(g, n[0])+1 else: 0)
  522. if n.len > 1:
  523. result += (if n[1].kind == nkWith: len("_with_") else: len("_without_"))
  524. result += lcomma(g, n[1])
  525. of nkStaticTy: result = (if n.len > 0: lsub(g, n[0]) else: 0) +
  526. len("static[]")
  527. of nkTypeDef: result = lsons(g, n) + 3
  528. of nkOfInherit: result = lsub(g, n[0]) + len("of_")
  529. of nkProcTy: result = lsons(g, n) + len("proc_")
  530. of nkIteratorTy: result = lsons(g, n) + len("iterator_")
  531. of nkSinkAsgn: result = lsons(g, n) + len("`=sink`(, )")
  532. of nkEnumTy:
  533. if n.len > 0:
  534. result = lsub(g, n[0]) + lcomma(g, n, 1) + len("enum_")
  535. else:
  536. result = len("enum")
  537. of nkEnumFieldDef: result = lsons(g, n) + 3
  538. of nkVarSection, nkLetSection:
  539. if n.len > 1: result = MaxLineLen + 1
  540. else: result = lsons(g, n) + len("var_")
  541. of nkUsingStmt:
  542. if n.len > 1: result = MaxLineLen + 1
  543. else: result = lsons(g, n) + len("using_")
  544. of nkReturnStmt:
  545. if n.len > 0 and n[0].kind == nkAsgn and renderIr notin g.flags:
  546. result = len("return_") + lsub(g, n[0][1])
  547. else:
  548. result = len("return_") + lsub(g, n[0])
  549. of nkRaiseStmt: result = lsub(g, n[0]) + len("raise_")
  550. of nkYieldStmt: result = lsub(g, n[0]) + len("yield_")
  551. of nkDiscardStmt: result = lsub(g, n[0]) + len("discard_")
  552. of nkBreakStmt: result = lsub(g, n[0]) + len("break_")
  553. of nkContinueStmt: result = lsub(g, n[0]) + len("continue_")
  554. of nkPragma: result = lcomma(g, n) + 4
  555. of nkCommentStmt: result = n.comment.len
  556. of nkOfBranch: result = lcomma(g, n, 0, - 2) + lsub(g, lastSon(n)) + len("of_:_")
  557. of nkImportAs: result = lsub(g, n[0]) + len("_as_") + lsub(g, n[1])
  558. of nkElifBranch: result = lsons(g, n) + len("elif_:_")
  559. of nkElse: result = lsub(g, n[0]) + len("else:_")
  560. of nkFinally: result = lsub(g, n[0]) + len("finally:_")
  561. of nkGenericParams: result = lcomma(g, n) + 2
  562. of nkFormalParams:
  563. result = lcomma(g, n, 1) + 2
  564. if n[0].kind != nkEmpty: result += lsub(g, n[0]) + 2
  565. of nkExceptBranch:
  566. result = lcomma(g, n, 0, -2) + lsub(g, lastSon(n)) + len("except_:_")
  567. of nkObjectTy:
  568. result = len("object_")
  569. else: result = MaxLineLen + 1
  570. proc fits(g: TSrcGen, x: int): bool =
  571. result = x <= MaxLineLen
  572. type
  573. TSubFlag = enum
  574. rfLongMode, rfInConstExpr
  575. TSubFlags = set[TSubFlag]
  576. TContext = tuple[spacing: int, flags: TSubFlags]
  577. const
  578. emptyContext: TContext = (spacing: 0, flags: {})
  579. proc initContext(): TContext =
  580. result = (spacing: 0, flags: {})
  581. proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false)
  582. proc gsub(g: var TSrcGen, n: PNode, fromStmtList = false) =
  583. var c: TContext = initContext()
  584. gsub(g, n, c, fromStmtList = fromStmtList)
  585. proc hasCom(n: PNode): bool =
  586. result = false
  587. if n.isNil: return false
  588. if n.comment.len > 0: return true
  589. case n.kind
  590. of nkEmpty..nkNilLit: discard
  591. else:
  592. for i in 0..<n.len:
  593. if hasCom(n[i]): return true
  594. proc putWithSpace(g: var TSrcGen, kind: TokType, s: string) =
  595. put(g, kind, s)
  596. put(g, tkSpaces, Space)
  597. proc isHideable(config: ConfigRef, n: PNode): bool =
  598. # xxx compare `ident` directly with `getIdent(cache, wRaises)`, but
  599. # this requires a `cache`.
  600. case n.kind
  601. of nkExprColonExpr:
  602. result = n[0].kind == nkIdent and
  603. n[0].ident.s.nimIdentNormalize in ["raises", "tags", "extern", "deprecated", "forbids", "stacktrace"]
  604. of nkIdent: result = n.ident.s in ["gcsafe", "deprecated"]
  605. else: result = false
  606. proc gcommaAux(g: var TSrcGen, n: PNode, ind: int, start: int = 0,
  607. theEnd: int = - 1, separator = tkComma) =
  608. let inPragma = g.inPragma == 1 # just the top-level
  609. var inHideable = false
  610. for i in start..n.len + theEnd:
  611. let c = i < n.len + theEnd
  612. let sublen = lsub(g, n[i]) + ord(c)
  613. if not fits(g, g.lineLen + sublen) and (ind + sublen < MaxLineLen): optNL(g, ind)
  614. let oldLen = g.tokens.len
  615. if inPragma:
  616. if not inHideable and isHideable(g.config, n[i]):
  617. inHideable = true
  618. put(g, tkHideableStart, "")
  619. elif inHideable and not isHideable(g.config, n[i]):
  620. inHideable = false
  621. put(g, tkHideableEnd, "")
  622. gsub(g, n[i])
  623. if c:
  624. if g.tokens.len > oldLen:
  625. putWithSpace(g, separator, $separator)
  626. if shouldRenderComment(g) and hasCom(n[i]):
  627. gcoms(g)
  628. optNL(g, ind)
  629. if inHideable:
  630. put(g, tkHideableEnd, "")
  631. inHideable = false
  632. proc gcomma(g: var TSrcGen, n: PNode, c: TContext, start: int = 0,
  633. theEnd: int = -1) =
  634. var ind: int
  635. if rfInConstExpr in c.flags:
  636. ind = g.indent + IndentWidth
  637. else:
  638. ind = g.lineLen
  639. if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
  640. gcommaAux(g, n, ind, start, theEnd)
  641. proc gcomma(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) =
  642. var ind = g.lineLen
  643. if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
  644. gcommaAux(g, n, ind, start, theEnd)
  645. proc gsemicolon(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) =
  646. var ind = g.lineLen
  647. if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
  648. gcommaAux(g, n, ind, start, theEnd, tkSemiColon)
  649. proc gsons(g: var TSrcGen, n: PNode, c: TContext, start: int = 0,
  650. theEnd: int = - 1) =
  651. for i in start..n.len + theEnd: gsub(g, n[i], c)
  652. proc gsection(g: var TSrcGen, n: PNode, c: TContext, kind: TokType,
  653. k: string) =
  654. if n.len == 0: return # empty var sections are possible
  655. putWithSpace(g, kind, k)
  656. gcoms(g)
  657. indentNL(g)
  658. for i in 0..<n.len:
  659. optNL(g)
  660. gsub(g, n[i], c)
  661. gcoms(g)
  662. dedent(g)
  663. proc longMode(g: TSrcGen; n: PNode, start: int = 0, theEnd: int = - 1): bool =
  664. result = shouldRenderComment(g, n)
  665. if not result:
  666. # check further
  667. for i in start..n.len + theEnd:
  668. if (lsub(g, n[i]) > MaxLineLen):
  669. result = true
  670. break
  671. proc gstmts(g: var TSrcGen, n: PNode, c: TContext, doIndent=true) =
  672. if n.kind == nkEmpty: return
  673. if n.kind in {nkStmtList, nkStmtListExpr, nkStmtListType}:
  674. if doIndent: indentNL(g)
  675. for i in 0..<n.len:
  676. if i > 0:
  677. optNL(g, n[i-1], n[i])
  678. else:
  679. optNL(g)
  680. if n[i].kind in {nkStmtList, nkStmtListExpr, nkStmtListType}:
  681. gstmts(g, n[i], c, doIndent=false)
  682. else:
  683. gsub(g, n[i], fromStmtList = true)
  684. gcoms(g)
  685. if doIndent: dedent(g)
  686. else:
  687. indentNL(g)
  688. gsub(g, n)
  689. gcoms(g)
  690. dedent(g)
  691. optNL(g)
  692. proc gcond(g: var TSrcGen, n: PNode) =
  693. if n.kind == nkStmtListExpr:
  694. put(g, tkParLe, "(")
  695. gsub(g, n)
  696. if n.kind == nkStmtListExpr:
  697. put(g, tkParRi, ")")
  698. proc gif(g: var TSrcGen, n: PNode) =
  699. var c: TContext = initContext()
  700. gcond(g, n[0][0])
  701. putWithSpace(g, tkColon, ":")
  702. if longMode(g, n) or (lsub(g, n[0][1]) + g.lineLen > MaxLineLen):
  703. incl(c.flags, rfLongMode)
  704. gcoms(g) # a good place for comments
  705. gstmts(g, n[0][1], c)
  706. for i in 1..<n.len:
  707. optNL(g)
  708. gsub(g, n[i], c)
  709. proc gwhile(g: var TSrcGen, n: PNode) =
  710. var c: TContext = initContext()
  711. putWithSpace(g, tkWhile, "while")
  712. gcond(g, n[0])
  713. putWithSpace(g, tkColon, ":")
  714. if longMode(g, n) or (lsub(g, n[1]) + g.lineLen > MaxLineLen):
  715. incl(c.flags, rfLongMode)
  716. gcoms(g) # a good place for comments
  717. gstmts(g, n[1], c)
  718. proc gpattern(g: var TSrcGen, n: PNode) =
  719. var c: TContext = initContext()
  720. put(g, tkCurlyLe, "{")
  721. if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen):
  722. incl(c.flags, rfLongMode)
  723. gcoms(g) # a good place for comments
  724. gstmts(g, n, c)
  725. put(g, tkCurlyRi, "}")
  726. proc gpragmaBlock(g: var TSrcGen, n: PNode) =
  727. var c: TContext = initContext()
  728. gsub(g, n[0])
  729. putWithSpace(g, tkColon, ":")
  730. if longMode(g, n) or (lsub(g, n[1]) + g.lineLen > MaxLineLen):
  731. incl(c.flags, rfLongMode)
  732. gcoms(g) # a good place for comments
  733. gstmts(g, n[1], c)
  734. proc gtry(g: var TSrcGen, n: PNode) =
  735. var c: TContext = initContext()
  736. put(g, tkTry, "try")
  737. putWithSpace(g, tkColon, ":")
  738. if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen):
  739. incl(c.flags, rfLongMode)
  740. gcoms(g) # a good place for comments
  741. gstmts(g, n[0], c)
  742. gsons(g, n, c, 1)
  743. proc gfor(g: var TSrcGen, n: PNode) =
  744. var c: TContext = initContext()
  745. putWithSpace(g, tkFor, "for")
  746. if longMode(g, n) or
  747. (lsub(g, n[^1]) + lsub(g, n[^2]) + 6 + g.lineLen > MaxLineLen):
  748. incl(c.flags, rfLongMode)
  749. gcomma(g, n, c, 0, - 3)
  750. put(g, tkSpaces, Space)
  751. putWithSpace(g, tkIn, "in")
  752. gsub(g, n[^2], c)
  753. putWithSpace(g, tkColon, ":")
  754. gcoms(g)
  755. gstmts(g, n[^1], c)
  756. proc gcase(g: var TSrcGen, n: PNode) =
  757. var c: TContext = initContext()
  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. c = initContext()
  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 and s.name.id != ord(wUnderscore):
  772. result.add '_'
  773. result.addInt s.id
  774. proc gproc(g: var TSrcGen, n: PNode) =
  775. var c: TContext = initContext()
  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.len > bodyPos and n[bodyPos].kind != nkEmpty:
  796. put(g, tkSpaces, Space)
  797. putWithSpace(g, tkEquals, "=")
  798. indentNL(g)
  799. gcoms(g)
  800. dedent(g)
  801. c = initContext()
  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 = initContext()
  810. putWithSpace(g, tkConcept, "concept")
  811. gsons(g, n[0], c) # arglist
  812. gsub(g, n[1]) # pragmas
  813. gsub(g, n[2]) # of
  814. gcoms(g)
  815. indentNL(g)
  816. gcoms(g)
  817. gstmts(g, n[3], c)
  818. dedent(g)
  819. proc gblock(g: var TSrcGen, n: PNode) =
  820. # you shouldn't simplify it to `n.len < 2`
  821. # because the following codes should be executed
  822. # even when block stmt has only one child for getting
  823. # better error messages.
  824. if n.len == 0:
  825. return
  826. var c: TContext = initContext()
  827. if n[0].kind != nkEmpty:
  828. putWithSpace(g, tkBlock, "block")
  829. gsub(g, n[0])
  830. else:
  831. put(g, tkBlock, "block")
  832. # block stmt should have two children
  833. if n.len == 1:
  834. return
  835. putWithSpace(g, tkColon, ":")
  836. if longMode(g, n) or (lsub(g, n[1]) + g.lineLen > MaxLineLen):
  837. incl(c.flags, rfLongMode)
  838. gcoms(g)
  839. gstmts(g, n[1], c)
  840. proc gstaticStmt(g: var TSrcGen, n: PNode) =
  841. var c: TContext = initContext()
  842. putWithSpace(g, tkStatic, "static")
  843. putWithSpace(g, tkColon, ":")
  844. if longMode(g, n) or (lsub(g, n[0]) + g.lineLen > MaxLineLen):
  845. incl(c.flags, rfLongMode)
  846. gcoms(g) # a good place for comments
  847. gstmts(g, n[0], c)
  848. proc gasm(g: var TSrcGen, n: PNode) =
  849. putWithSpace(g, tkAsm, "asm")
  850. gsub(g, n[0])
  851. gcoms(g)
  852. if n.len > 1:
  853. gsub(g, n[1])
  854. proc gident(g: var TSrcGen, n: PNode) =
  855. if GenericParams in g.inside and n.kind == nkSym:
  856. if sfAnon in n.sym.flags or
  857. (n.typ != nil and tfImplicitTypeParam in n.typ.flags): return
  858. var t: TokType
  859. var s = atom(g, n)
  860. if s.len > 0 and s[0] in lexer.SymChars:
  861. if n.kind == nkIdent:
  862. if (n.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
  863. (n.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
  864. t = tkSymbol
  865. else:
  866. t = TokType(n.ident.id + ord(tkSymbol))
  867. else:
  868. t = tkSymbol
  869. else:
  870. t = tkOpr
  871. if renderIr in g.flags and n.kind == nkSym:
  872. let localId = disamb(g, n.sym)
  873. if localId != 0 and n.sym.magic == mNone:
  874. s.add '_'
  875. s.addInt localId
  876. if sfCursor in n.sym.flags:
  877. s.add "_cursor"
  878. elif n.kind == nkSym and (renderIds in g.flags or
  879. (sfGenSym in n.sym.flags and n.sym.name.id != ord(wUnderscore)) or
  880. n.sym.kind == skTemp):
  881. s.add '_'
  882. s.addInt n.sym.id
  883. when defined(debugMagics):
  884. s.add '_'
  885. s.add $n.sym.magic
  886. put(g, t, s, if n.kind == nkSym and renderSyms in g.flags: n.sym else: nil)
  887. proc doParamsAux(g: var TSrcGen, params: PNode) =
  888. if params.len > 1:
  889. put(g, tkParLe, "(")
  890. gsemicolon(g, params, 1)
  891. put(g, tkParRi, ")")
  892. if params.len > 0 and params[0].kind != nkEmpty:
  893. put(g, tkSpaces, Space)
  894. putWithSpace(g, tkOpr, "->")
  895. gsub(g, params[0])
  896. proc gsub(g: var TSrcGen; n: PNode; i: int) =
  897. if i < n.len:
  898. gsub(g, n[i])
  899. else:
  900. put(g, tkOpr, "<<" & $i & "th child missing for " & $n.kind & " >>")
  901. type
  902. BracketKind = enum
  903. bkNone, bkBracket, bkBracketAsgn, bkCurly, bkCurlyAsgn
  904. proc bracketKind*(g: TSrcGen, n: PNode): BracketKind =
  905. if renderIds notin g.flags:
  906. case n.kind
  907. of nkClosedSymChoice, nkOpenSymChoice:
  908. if n.len > 0: result = bracketKind(g, n[0])
  909. else: result = bkNone
  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. else:
  919. result = bkNone
  920. proc skipHiddenNodes(n: PNode): PNode =
  921. result = n
  922. while result != nil:
  923. if result.kind in {nkHiddenStdConv, nkHiddenSubConv, nkHiddenCallConv, nkOpenSym} and result.len > 1:
  924. result = result[1]
  925. elif result.kind in {nkCheckedFieldExpr, nkHiddenAddr, nkHiddenDeref, nkStringToCString, nkCStringToString} and
  926. result.len > 0:
  927. result = result[0]
  928. else: break
  929. proc accentedName(g: var TSrcGen, n: PNode) =
  930. # This is for cases where ident should've really been a `nkAccQuoted`, e.g. `:tmp`
  931. # or if user writes a macro with `ident":foo"`. It's unclear whether these should be legal.
  932. const backticksNeeded = OpChars + {'[', '{', '\''}
  933. if n == nil: return
  934. let ident = n.getPIdent
  935. if ident != nil and ident.s[0] in backticksNeeded:
  936. put(g, tkAccent, "`")
  937. gident(g, n)
  938. put(g, tkAccent, "`")
  939. else:
  940. gsub(g, n)
  941. proc infixArgument(g: var TSrcGen, n: PNode, i: int) =
  942. if i < 1 or i > 2: return
  943. var needsParenthesis = false
  944. let nNext = n[i].skipHiddenNodes
  945. if nNext.kind == nkInfix:
  946. if nNext[0].kind in {nkSym, nkIdent} and n[0].kind in {nkSym, nkIdent}:
  947. let nextId = if nNext[0].kind == nkSym: nNext[0].sym.name else: nNext[0].ident
  948. let nnId = if n[0].kind == nkSym: n[0].sym.name else: n[0].ident
  949. if i == 1:
  950. if getPrecedence(nextId) < getPrecedence(nnId):
  951. needsParenthesis = true
  952. elif i == 2:
  953. if getPrecedence(nextId) <= getPrecedence(nnId):
  954. needsParenthesis = true
  955. if needsParenthesis:
  956. put(g, tkParLe, "(")
  957. gsub(g, n, i)
  958. if needsParenthesis:
  959. put(g, tkParRi, ")")
  960. const postExprBlocks = {nkStmtList, nkStmtListExpr,
  961. nkOfBranch, nkElifBranch, nkElse,
  962. nkExceptBranch, nkFinally, nkDo}
  963. proc postStatements(g: var TSrcGen, n: PNode, i: int, fromStmtList: bool) =
  964. var i = i
  965. if n[i].kind in {nkStmtList, nkStmtListExpr}:
  966. if fromStmtList:
  967. put(g, tkColon, ":")
  968. else:
  969. put(g, tkSpaces, Space)
  970. put(g, tkDo, "do")
  971. put(g, tkColon, ":")
  972. gsub(g, n, i)
  973. i.inc
  974. for j in i ..< n.len:
  975. if n[j].kind == nkDo:
  976. optNL(g)
  977. elif n[j].kind in {nkStmtList, nkStmtListExpr}:
  978. optNL(g)
  979. put(g, tkDo, "do")
  980. put(g, tkColon, ":")
  981. gsub(g, n, j)
  982. proc isCustomLit(n: PNode): bool =
  983. if n.len == 2 and n[0].kind == nkRStrLit:
  984. let ident = n[1].getPIdent
  985. result = ident != nil and ident.s.startsWith('\'')
  986. else:
  987. result = false
  988. proc gsub(g: var TSrcGen, n: PNode, c: TContext, fromStmtList = false) =
  989. if isNil(n): return
  990. var
  991. a: TContext = default(TContext)
  992. if shouldRenderComment(g, n): pushCom(g, n)
  993. case n.kind # atoms:
  994. of nkTripleStrLit: put(g, tkTripleStrLit, atom(g, n))
  995. of nkEmpty: discard
  996. of nkType: put(g, tkInvalid, atom(g, n))
  997. of nkSym, nkIdent: gident(g, n)
  998. of nkIntLit: put(g, tkIntLit, atom(g, n))
  999. of nkInt8Lit: put(g, tkInt8Lit, atom(g, n))
  1000. of nkInt16Lit: put(g, tkInt16Lit, atom(g, n))
  1001. of nkInt32Lit: put(g, tkInt32Lit, atom(g, n))
  1002. of nkInt64Lit: put(g, tkInt64Lit, atom(g, n))
  1003. of nkUIntLit: put(g, tkUIntLit, atom(g, n))
  1004. of nkUInt8Lit: put(g, tkUInt8Lit, atom(g, n))
  1005. of nkUInt16Lit: put(g, tkUInt16Lit, atom(g, n))
  1006. of nkUInt32Lit: put(g, tkUInt32Lit, atom(g, n))
  1007. of nkUInt64Lit: put(g, tkUInt64Lit, atom(g, n))
  1008. of nkFloatLit: put(g, tkFloatLit, atom(g, n))
  1009. of nkFloat32Lit: put(g, tkFloat32Lit, atom(g, n))
  1010. of nkFloat64Lit: put(g, tkFloat64Lit, atom(g, n))
  1011. of nkFloat128Lit: put(g, tkFloat128Lit, atom(g, n))
  1012. of nkStrLit: put(g, tkStrLit, atom(g, n))
  1013. of nkRStrLit: put(g, tkRStrLit, atom(g, n))
  1014. of nkCharLit: put(g, tkCharLit, atom(g, n))
  1015. of nkNilLit: put(g, tkNil, atom(g, n)) # complex expressions
  1016. of nkCall, nkConv, nkDotCall, nkPattern, nkObjConstr:
  1017. if n.len > 1 and n.lastSon.kind in postExprBlocks:
  1018. accentedName(g, n[0])
  1019. var i = 1
  1020. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1021. if i > 1:
  1022. put(g, tkParLe, "(")
  1023. gcomma(g, n, 1, i - 1 - n.len)
  1024. put(g, tkParRi, ")")
  1025. postStatements(g, n, i, fromStmtList)
  1026. elif n.len >= 1:
  1027. case bracketKind(g, n[0])
  1028. of bkBracket:
  1029. gsub(g, n, 1)
  1030. put(g, tkBracketLe, "[")
  1031. gcomma(g, n, 2)
  1032. put(g, tkBracketRi, "]")
  1033. of bkBracketAsgn:
  1034. gsub(g, n, 1)
  1035. put(g, tkBracketLe, "[")
  1036. gcomma(g, n, 2, -2)
  1037. put(g, tkBracketRi, "]")
  1038. put(g, tkSpaces, Space)
  1039. putWithSpace(g, tkEquals, "=")
  1040. gsub(g, n, n.len - 1)
  1041. of bkCurly:
  1042. gsub(g, n, 1)
  1043. put(g, tkCurlyLe, "{")
  1044. gcomma(g, n, 2)
  1045. put(g, tkCurlyRi, "}")
  1046. of bkCurlyAsgn:
  1047. gsub(g, n, 1)
  1048. put(g, tkCurlyLe, "{")
  1049. gcomma(g, n, 2, -2)
  1050. put(g, tkCurlyRi, "}")
  1051. put(g, tkSpaces, Space)
  1052. putWithSpace(g, tkEquals, "=")
  1053. gsub(g, n, n.len - 1)
  1054. of bkNone:
  1055. accentedName(g, n[0])
  1056. put(g, tkParLe, "(")
  1057. gcomma(g, n, 1)
  1058. put(g, tkParRi, ")")
  1059. else:
  1060. put(g, tkParLe, "(")
  1061. put(g, tkParRi, ")")
  1062. of nkCallStrLit:
  1063. if n.len > 0: accentedName(g, n[0])
  1064. if n.len > 1 and n[1].kind == nkRStrLit:
  1065. put(g, tkRStrLit, '\"' & replace(n[1].strVal, "\"", "\"\"") & '\"')
  1066. else:
  1067. gsub(g, n, 1)
  1068. of nkHiddenStdConv, nkHiddenSubConv:
  1069. if n.len >= 2:
  1070. when false:
  1071. # if {renderIds, renderIr} * g.flags != {}:
  1072. put(g, tkSymbol, "(conv)")
  1073. put(g, tkParLe, "(")
  1074. gsub(g, n[1])
  1075. put(g, tkParRi, ")")
  1076. else:
  1077. gsub(g, n[1])
  1078. else:
  1079. put(g, tkSymbol, "(wrong conv)")
  1080. of nkHiddenCallConv:
  1081. if {renderIds, renderIr} * g.flags != {}:
  1082. accentedName(g, n[0])
  1083. put(g, tkParLe, "(")
  1084. gcomma(g, n, 1)
  1085. put(g, tkParRi, ")")
  1086. elif n.len >= 2:
  1087. gsub(g, n[1])
  1088. else:
  1089. put(g, tkSymbol, "(wrong conv)")
  1090. of nkCast:
  1091. put(g, tkCast, "cast")
  1092. if n.len > 0 and n[0].kind != nkEmpty:
  1093. put(g, tkBracketLe, "[")
  1094. gsub(g, n, 0)
  1095. put(g, tkBracketRi, "]")
  1096. put(g, tkParLe, "(")
  1097. gsub(g, n, 1)
  1098. put(g, tkParRi, ")")
  1099. of nkAddr:
  1100. put(g, tkAddr, "addr")
  1101. if n.len > 0:
  1102. put(g, tkParLe, "(")
  1103. gsub(g, n[0])
  1104. put(g, tkParRi, ")")
  1105. of nkStaticExpr:
  1106. put(g, tkStatic, "static")
  1107. put(g, tkSpaces, Space)
  1108. gsub(g, n, 0)
  1109. of nkBracketExpr:
  1110. gsub(g, n, 0)
  1111. put(g, tkBracketLe, "[")
  1112. gcomma(g, n, 1)
  1113. put(g, tkBracketRi, "]")
  1114. of nkCurlyExpr:
  1115. gsub(g, n, 0)
  1116. put(g, tkCurlyLe, "{")
  1117. gcomma(g, n, 1)
  1118. put(g, tkCurlyRi, "}")
  1119. of nkPragmaExpr:
  1120. gsub(g, n, 0)
  1121. gcomma(g, n, 1)
  1122. of nkCommand:
  1123. accentedName(g, n[0])
  1124. put(g, tkSpaces, Space)
  1125. if n.len > 1 and n.lastSon.kind in postExprBlocks:
  1126. var i = 1
  1127. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1128. if i > 1:
  1129. gcomma(g, n, 1, i - 1 - n.len)
  1130. postStatements(g, n, i, fromStmtList)
  1131. else:
  1132. gcomma(g, n, 1)
  1133. of nkExprEqExpr, nkAsgn, nkFastAsgn:
  1134. gsub(g, n, 0)
  1135. put(g, tkSpaces, Space)
  1136. putWithSpace(g, tkEquals, "=")
  1137. gsub(g, n, 1)
  1138. of nkSinkAsgn:
  1139. put(g, tkSymbol, "`=sink`")
  1140. put(g, tkParLe, "(")
  1141. gcomma(g, n)
  1142. put(g, tkParRi, ")")
  1143. of nkChckRangeF:
  1144. put(g, tkSymbol, "chckRangeF")
  1145. put(g, tkParLe, "(")
  1146. gcomma(g, n)
  1147. put(g, tkParRi, ")")
  1148. of nkChckRange64:
  1149. put(g, tkSymbol, "chckRange64")
  1150. put(g, tkParLe, "(")
  1151. gcomma(g, n)
  1152. put(g, tkParRi, ")")
  1153. of nkChckRange:
  1154. put(g, tkSymbol, "chckRange")
  1155. put(g, tkParLe, "(")
  1156. gcomma(g, n)
  1157. put(g, tkParRi, ")")
  1158. of nkObjDownConv, nkObjUpConv:
  1159. let typ = if (n.typ != nil) and (n.typ.sym != nil): n.typ.sym.name.s else: ""
  1160. put(g, tkParLe, typ & "(")
  1161. if n.len >= 1: gsub(g, n[0])
  1162. put(g, tkParRi, ")")
  1163. of nkClosedSymChoice, nkOpenSymChoice:
  1164. if renderIds in g.flags:
  1165. put(g, tkParLe, "(")
  1166. for i in 0..<n.len:
  1167. if i > 0: put(g, tkOpr, "|")
  1168. if n[i].kind == nkSym:
  1169. let s = n[i].sym
  1170. if s.owner != nil:
  1171. put g, tkSymbol, n[i].sym.owner.name.s
  1172. put g, tkOpr, "."
  1173. put g, tkSymbol, n[i].sym.name.s
  1174. else:
  1175. gsub(g, n[i], c)
  1176. put(g, tkParRi, if n.kind == nkOpenSymChoice: "|...)" else: ")")
  1177. else:
  1178. gsub(g, n, 0)
  1179. of nkOpenSym: gsub(g, n, 0)
  1180. of nkPar, nkClosure:
  1181. put(g, tkParLe, "(")
  1182. gcomma(g, n, c)
  1183. put(g, tkParRi, ")")
  1184. of nkTupleConstr:
  1185. put(g, tkParLe, "(")
  1186. gcomma(g, n, c)
  1187. if n.len == 1 and n[0].kind != nkExprColonExpr: put(g, tkComma, ",")
  1188. put(g, tkParRi, ")")
  1189. of nkCurly:
  1190. put(g, tkCurlyLe, "{")
  1191. gcomma(g, n, c)
  1192. put(g, tkCurlyRi, "}")
  1193. of nkArgList:
  1194. gcomma(g, n, c)
  1195. of nkTableConstr:
  1196. put(g, tkCurlyLe, "{")
  1197. if n.len > 0: gcomma(g, n, c)
  1198. else: put(g, tkColon, ":")
  1199. put(g, tkCurlyRi, "}")
  1200. of nkBracket:
  1201. put(g, tkBracketLe, "[")
  1202. gcomma(g, n, c)
  1203. put(g, tkBracketRi, "]")
  1204. of nkDotExpr:
  1205. if isCustomLit(n):
  1206. put(g, tkCustomLit, n[0].strVal)
  1207. gsub(g, n, 1)
  1208. else:
  1209. for i in 0..<n.len-1:
  1210. gsub(g, n, i)
  1211. put(g, tkDot, ".")
  1212. if n.len > 1:
  1213. accentedName(g, n[^1])
  1214. of nkBind:
  1215. putWithSpace(g, tkBind, "bind")
  1216. gsub(g, n, 0)
  1217. of nkCheckedFieldExpr, nkHiddenAddr, nkHiddenDeref, nkStringToCString, nkCStringToString:
  1218. if renderIds in g.flags:
  1219. put(g, tkAddr, $n.kind)
  1220. put(g, tkParLe, "(")
  1221. gsub(g, n, 0)
  1222. if renderIds in g.flags:
  1223. put(g, tkParRi, ")")
  1224. of nkLambda:
  1225. putWithSpace(g, tkProc, "proc")
  1226. gsub(g, n, paramsPos)
  1227. gsub(g, n, pragmasPos)
  1228. put(g, tkSpaces, Space)
  1229. putWithSpace(g, tkEquals, "=")
  1230. gsub(g, n, bodyPos)
  1231. of nkDo:
  1232. putWithSpace(g, tkDo, "do")
  1233. if paramsPos < n.len:
  1234. doParamsAux(g, n[paramsPos])
  1235. gsub(g, n, pragmasPos)
  1236. put(g, tkColon, ":")
  1237. gsub(g, n, bodyPos)
  1238. of nkIdentDefs:
  1239. var exclFlags: TRenderFlags = {}
  1240. if ObjectDef in g.inside:
  1241. if not n[0].isExported() and renderNonExportedFields notin g.flags:
  1242. # Skip if this is a property in a type and its not exported
  1243. # (While also not allowing rendering of non exported fields)
  1244. return
  1245. # render postfix for object fields:
  1246. exclFlags = g.flags * {renderNoPostfix}
  1247. # We render the identDef without being inside the section incase we render something like
  1248. # y: proc (x: string) # (We wouldn't want to check if x is exported)
  1249. g.outside(ObjectDef):
  1250. g.flags.excl(exclFlags)
  1251. gcomma(g, n, 0, -3)
  1252. g.flags.incl(exclFlags)
  1253. if n.len >= 2 and n[^2].kind != nkEmpty:
  1254. putWithSpace(g, tkColon, ":")
  1255. gsub(g, n[^2], c)
  1256. elif n.referencesUsing and renderExpandUsing in g.flags:
  1257. putWithSpace(g, tkColon, ":")
  1258. gsub(g, newSymNode(n.origUsingType), c)
  1259. if n.len >= 1 and n[^1].kind != nkEmpty:
  1260. put(g, tkSpaces, Space)
  1261. putWithSpace(g, tkEquals, "=")
  1262. gsub(g, n[^1], c)
  1263. of nkConstDef:
  1264. gcomma(g, n, 0, -3)
  1265. if n.len >= 2 and n[^2].kind != nkEmpty:
  1266. putWithSpace(g, tkColon, ":")
  1267. gsub(g, n[^2], c)
  1268. if n.len >= 1 and n[^1].kind != nkEmpty:
  1269. put(g, tkSpaces, Space)
  1270. putWithSpace(g, tkEquals, "=")
  1271. gsub(g, n[^1], c)
  1272. of nkVarTuple:
  1273. if n[^1].kind == nkEmpty:
  1274. put(g, tkParLe, "(")
  1275. gcomma(g, n, 0, -2)
  1276. put(g, tkParRi, ")")
  1277. else:
  1278. put(g, tkParLe, "(")
  1279. gcomma(g, n, 0, -3)
  1280. put(g, tkParRi, ")")
  1281. put(g, tkSpaces, Space)
  1282. putWithSpace(g, tkEquals, "=")
  1283. gsub(g, lastSon(n), c)
  1284. of nkExprColonExpr:
  1285. gsub(g, n, 0)
  1286. putWithSpace(g, tkColon, ":")
  1287. gsub(g, n, 1)
  1288. of nkInfix:
  1289. if n.len < 3:
  1290. var i = 0
  1291. put(g, tkOpr, "Too few children for nkInfix")
  1292. return
  1293. let oldLineLen = g.lineLen # we cache this because lineLen gets updated below
  1294. infixArgument(g, n, 1)
  1295. put(g, tkSpaces, Space)
  1296. gsub(g, n, 0) # binary operator
  1297. # e.g.: `n1 == n2` decompses as following sum:
  1298. if n.len == 3 and not fits(g, oldLineLen + lsub(g, n[1]) + lsub(g, n[2]) + lsub(g, n[0]) + len(" ")):
  1299. optNL(g, g.indent + longIndentWid)
  1300. else:
  1301. put(g, tkSpaces, Space)
  1302. infixArgument(g, n, 2)
  1303. if n.len > 3 and n.lastSon.kind in postExprBlocks:
  1304. var i = 3
  1305. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1306. postStatements(g, n, i, fromStmtList)
  1307. of nkPrefix:
  1308. gsub(g, n, 0)
  1309. if n.len > 1:
  1310. let opr = if n[0].kind == nkIdent: n[0].ident
  1311. elif n[0].kind == nkSym: n[0].sym.name
  1312. elif n[0].kind in {nkOpenSymChoice, nkClosedSymChoice}: n[0][0].sym.name
  1313. else: nil
  1314. let nNext = skipHiddenNodes(n[1])
  1315. if nNext.kind == nkPrefix or (opr != nil and renderer.isKeyword(opr)):
  1316. put(g, tkSpaces, Space)
  1317. if nNext.kind == nkInfix:
  1318. put(g, tkParLe, "(")
  1319. gsub(g, n[1])
  1320. put(g, tkParRi, ")")
  1321. else:
  1322. gsub(g, n[1])
  1323. if n.len > 2 and n.lastSon.kind in postExprBlocks:
  1324. var i = 2
  1325. while i < n.len and n[i].kind notin postExprBlocks: i.inc
  1326. postStatements(g, n, i, fromStmtList)
  1327. of nkPostfix:
  1328. gsub(g, n, 1)
  1329. if renderNoPostfix notin g.flags:
  1330. gsub(g, n, 0)
  1331. of nkRange:
  1332. gsub(g, n, 0)
  1333. put(g, tkDotDot, "..")
  1334. gsub(g, n, 1)
  1335. of nkDerefExpr:
  1336. gsub(g, n, 0)
  1337. put(g, tkOpr, "[]")
  1338. of nkAccQuoted:
  1339. put(g, tkAccent, "`")
  1340. for i in 0..<n.len:
  1341. proc isAlpha(n: PNode): bool =
  1342. if n.kind in {nkIdent, nkSym}:
  1343. let tmp = n.getPIdent.s
  1344. result = tmp.len > 0 and tmp[0] in {'a'..'z', 'A'..'Z'}
  1345. else:
  1346. result = false
  1347. var useSpace = false
  1348. if i == 1 and n[0].kind == nkIdent and n[0].ident.s in ["=", "'"]:
  1349. if not n[1].isAlpha: # handle `=destroy`, `'big'
  1350. useSpace = true
  1351. elif i == 1 and n[1].kind == nkIdent and n[1].ident.s == "=":
  1352. if not n[0].isAlpha: # handle setters, e.g. `foo=`
  1353. useSpace = true
  1354. elif i > 0: useSpace = true
  1355. if useSpace: put(g, tkSpaces, Space)
  1356. gsub(g, n[i])
  1357. put(g, tkAccent, "`")
  1358. of nkIfExpr:
  1359. putWithSpace(g, tkIf, "if")
  1360. if n.len > 0: gcond(g, n[0][0])
  1361. putWithSpace(g, tkColon, ":")
  1362. if n.len > 0: gsub(g, n[0], 1)
  1363. gsons(g, n, emptyContext, 1)
  1364. of nkElifExpr:
  1365. putWithSpace(g, tkElif, " elif")
  1366. gcond(g, n[0])
  1367. putWithSpace(g, tkColon, ":")
  1368. gsub(g, n, 1)
  1369. of nkElseExpr:
  1370. put(g, tkElse, " else")
  1371. putWithSpace(g, tkColon, ":")
  1372. gsub(g, n, 0)
  1373. of nkTypeOfExpr:
  1374. put(g, tkType, "typeof")
  1375. put(g, tkParLe, "(")
  1376. if n.len > 0: gsub(g, n[0])
  1377. put(g, tkParRi, ")")
  1378. of nkRefTy:
  1379. if n.len > 0:
  1380. putWithSpace(g, tkRef, "ref")
  1381. gsub(g, n[0])
  1382. else:
  1383. put(g, tkRef, "ref")
  1384. of nkPtrTy:
  1385. if n.len > 0:
  1386. putWithSpace(g, tkPtr, "ptr")
  1387. gsub(g, n[0])
  1388. else:
  1389. put(g, tkPtr, "ptr")
  1390. of nkVarTy:
  1391. if n.len > 0:
  1392. putWithSpace(g, tkVar, "var")
  1393. gsub(g, n[0])
  1394. else:
  1395. put(g, tkVar, "var")
  1396. of nkOutTy:
  1397. if n.len > 0:
  1398. putWithSpace(g, tkOut, "out")
  1399. gsub(g, n[0])
  1400. else:
  1401. put(g, tkOut, "out")
  1402. of nkDistinctTy:
  1403. if n.len > 0:
  1404. putWithSpace(g, tkDistinct, "distinct")
  1405. gsub(g, n[0])
  1406. if n.len > 1:
  1407. if n[1].kind == nkWith:
  1408. putWithSpace(g, tkSymbol, " with")
  1409. else:
  1410. putWithSpace(g, tkSymbol, " without")
  1411. gcomma(g, n[1])
  1412. else:
  1413. put(g, tkDistinct, "distinct")
  1414. of nkTypeDef:
  1415. if n[0].kind == nkPragmaExpr:
  1416. # generate pragma after generic
  1417. gsub(g, n[0], 0)
  1418. gsub(g, n, 1)
  1419. gsub(g, n[0], 1)
  1420. else:
  1421. gsub(g, n, 0)
  1422. gsub(g, n, 1)
  1423. put(g, tkSpaces, Space)
  1424. if n.len > 2 and n[2].kind != nkEmpty:
  1425. putWithSpace(g, tkEquals, "=")
  1426. gsub(g, n[2])
  1427. of nkObjectTy:
  1428. if n.len > 0:
  1429. putWithSpace(g, tkObject, "object")
  1430. g.inside(ObjectDef):
  1431. gsub(g, n[0])
  1432. gsub(g, n[1])
  1433. gcoms(g)
  1434. indentNL(g)
  1435. gsub(g, n[2])
  1436. dedent(g)
  1437. else:
  1438. put(g, tkObject, "object")
  1439. of nkRecList:
  1440. for i in 0..<n.len:
  1441. optNL(g)
  1442. gsub(g, n[i], c)
  1443. gcoms(g)
  1444. of nkOfInherit:
  1445. putWithSpace(g, tkOf, "of")
  1446. gsub(g, n, 0)
  1447. of nkProcTy:
  1448. if n.len > 0:
  1449. putWithSpace(g, tkProc, "proc")
  1450. gsub(g, n, 0)
  1451. gsub(g, n, 1)
  1452. else:
  1453. put(g, tkProc, "proc")
  1454. of nkIteratorTy:
  1455. if n.len > 0:
  1456. putWithSpace(g, tkIterator, "iterator")
  1457. gsub(g, n, 0)
  1458. gsub(g, n, 1)
  1459. else:
  1460. put(g, tkIterator, "iterator")
  1461. of nkStaticTy:
  1462. put(g, tkStatic, "static")
  1463. put(g, tkBracketLe, "[")
  1464. if n.len > 0:
  1465. gsub(g, n[0])
  1466. put(g, tkBracketRi, "]")
  1467. of nkEnumTy:
  1468. if n.len > 0:
  1469. putWithSpace(g, tkEnum, "enum")
  1470. gsub(g, n[0])
  1471. gcoms(g)
  1472. indentNL(g)
  1473. gcommaAux(g, n, g.indent, 1)
  1474. gcoms(g) # BUGFIX: comment for the last enum field
  1475. dedent(g)
  1476. else:
  1477. put(g, tkEnum, "enum")
  1478. of nkEnumFieldDef:
  1479. gsub(g, n, 0)
  1480. put(g, tkSpaces, Space)
  1481. putWithSpace(g, tkEquals, "=")
  1482. gsub(g, n, 1)
  1483. of nkStmtList, nkStmtListExpr, nkStmtListType:
  1484. if n.len == 1 and n[0].kind == nkDiscardStmt:
  1485. put(g, tkParLe, "(")
  1486. gsub(g, n[0])
  1487. put(g, tkParRi, ")")
  1488. else:
  1489. gstmts(g, n, emptyContext)
  1490. of nkIfStmt:
  1491. putWithSpace(g, tkIf, "if")
  1492. gif(g, n)
  1493. of nkWhen, nkRecWhen:
  1494. putWithSpace(g, tkWhen, "when")
  1495. gif(g, n)
  1496. of nkWhileStmt: gwhile(g, n)
  1497. of nkPragmaBlock: gpragmaBlock(g, n)
  1498. of nkCaseStmt, nkRecCase: gcase(g, n)
  1499. of nkTryStmt, nkHiddenTryStmt: gtry(g, n)
  1500. of nkForStmt, nkParForStmt: gfor(g, n)
  1501. of nkBlockStmt, nkBlockExpr: gblock(g, n)
  1502. of nkStaticStmt: gstaticStmt(g, n)
  1503. of nkAsmStmt: gasm(g, n)
  1504. of nkProcDef:
  1505. if renderNoProcDefs notin g.flags: putWithSpace(g, tkProc, "proc")
  1506. gproc(g, n)
  1507. of nkFuncDef:
  1508. if renderNoProcDefs notin g.flags: putWithSpace(g, tkFunc, "func")
  1509. gproc(g, n)
  1510. of nkConverterDef:
  1511. if renderNoProcDefs notin g.flags: putWithSpace(g, tkConverter, "converter")
  1512. gproc(g, n)
  1513. of nkMethodDef:
  1514. if renderNoProcDefs notin g.flags: putWithSpace(g, tkMethod, "method")
  1515. gproc(g, n)
  1516. of nkIteratorDef:
  1517. if renderNoProcDefs notin g.flags: putWithSpace(g, tkIterator, "iterator")
  1518. gproc(g, n)
  1519. of nkMacroDef:
  1520. if renderNoProcDefs notin g.flags: putWithSpace(g, tkMacro, "macro")
  1521. gproc(g, n)
  1522. of nkTemplateDef:
  1523. if renderNoProcDefs notin g.flags: putWithSpace(g, tkTemplate, "template")
  1524. gproc(g, n)
  1525. of nkTypeSection:
  1526. gsection(g, n, emptyContext, tkType, "type")
  1527. of nkConstSection:
  1528. a = initContext()
  1529. incl(a.flags, rfInConstExpr)
  1530. gsection(g, n, a, tkConst, "const")
  1531. of nkVarSection, nkLetSection, nkUsingStmt:
  1532. if n.len == 0: return
  1533. if n.kind == nkVarSection: putWithSpace(g, tkVar, "var")
  1534. elif n.kind == nkLetSection: putWithSpace(g, tkLet, "let")
  1535. else: putWithSpace(g, tkUsing, "using")
  1536. if n.len > 1:
  1537. gcoms(g)
  1538. indentNL(g)
  1539. for i in 0..<n.len:
  1540. optNL(g)
  1541. gsub(g, n[i])
  1542. gcoms(g)
  1543. dedent(g)
  1544. else:
  1545. gsub(g, n[0])
  1546. of nkReturnStmt:
  1547. putWithSpace(g, tkReturn, "return")
  1548. if n.len > 0 and n[0].kind == nkAsgn and renderIr notin g.flags:
  1549. gsub(g, n[0], 1)
  1550. else:
  1551. gsub(g, n, 0)
  1552. of nkRaiseStmt:
  1553. putWithSpace(g, tkRaise, "raise")
  1554. gsub(g, n, 0)
  1555. of nkYieldStmt:
  1556. putWithSpace(g, tkYield, "yield")
  1557. gsub(g, n, 0)
  1558. of nkDiscardStmt:
  1559. putWithSpace(g, tkDiscard, "discard")
  1560. gsub(g, n, 0)
  1561. of nkBreakStmt:
  1562. putWithSpace(g, tkBreak, "break")
  1563. gsub(g, n, 0)
  1564. of nkContinueStmt:
  1565. putWithSpace(g, tkContinue, "continue")
  1566. gsub(g, n, 0)
  1567. of nkPragma:
  1568. if g.inPragma <= 0:
  1569. inc g.inPragma
  1570. #if not previousNL(g):
  1571. put(g, tkSpaces, Space)
  1572. put(g, tkCurlyDotLe, "{.")
  1573. gcomma(g, n, emptyContext)
  1574. put(g, tkCurlyDotRi, ".}")
  1575. dec g.inPragma
  1576. else:
  1577. gcomma(g, n, emptyContext)
  1578. of nkImportStmt, nkExportStmt:
  1579. if n.kind == nkImportStmt:
  1580. putWithSpace(g, tkImport, "import")
  1581. else:
  1582. putWithSpace(g, tkExport, "export")
  1583. gcoms(g)
  1584. indentNL(g)
  1585. gcommaAux(g, n, g.indent)
  1586. dedent(g)
  1587. putNL(g)
  1588. of nkImportExceptStmt, nkExportExceptStmt:
  1589. if n.kind == nkImportExceptStmt:
  1590. putWithSpace(g, tkImport, "import")
  1591. else:
  1592. putWithSpace(g, tkExport, "export")
  1593. gsub(g, n, 0)
  1594. put(g, tkSpaces, Space)
  1595. putWithSpace(g, tkExcept, "except")
  1596. gcommaAux(g, n, g.indent, 1)
  1597. gcoms(g)
  1598. putNL(g)
  1599. of nkFromStmt:
  1600. putWithSpace(g, tkFrom, "from")
  1601. gsub(g, n, 0)
  1602. put(g, tkSpaces, Space)
  1603. putWithSpace(g, tkImport, "import")
  1604. gcomma(g, n, emptyContext, 1)
  1605. putNL(g)
  1606. of nkIncludeStmt:
  1607. putWithSpace(g, tkInclude, "include")
  1608. gcoms(g)
  1609. indentNL(g)
  1610. gcommaAux(g, n, g.indent)
  1611. dedent(g)
  1612. putNL(g)
  1613. of nkCommentStmt:
  1614. gcoms(g)
  1615. optNL(g)
  1616. of nkOfBranch:
  1617. optNL(g)
  1618. putWithSpace(g, tkOf, "of")
  1619. gcomma(g, n, c, 0, - 2)
  1620. putWithSpace(g, tkColon, ":")
  1621. gcoms(g)
  1622. gstmts(g, lastSon(n), c)
  1623. of nkImportAs:
  1624. gsub(g, n, 0)
  1625. put(g, tkSpaces, Space)
  1626. putWithSpace(g, tkAs, "as")
  1627. gsub(g, n, 1)
  1628. of nkBindStmt:
  1629. putWithSpace(g, tkBind, "bind")
  1630. gcomma(g, n, c)
  1631. of nkMixinStmt:
  1632. putWithSpace(g, tkMixin, "mixin")
  1633. gcomma(g, n, c)
  1634. of nkElifBranch:
  1635. optNL(g)
  1636. putWithSpace(g, tkElif, "elif")
  1637. gsub(g, n, 0)
  1638. putWithSpace(g, tkColon, ":")
  1639. gcoms(g)
  1640. gstmts(g, n[1], c)
  1641. of nkElse:
  1642. optNL(g)
  1643. put(g, tkElse, "else")
  1644. putWithSpace(g, tkColon, ":")
  1645. gcoms(g)
  1646. gstmts(g, n[0], c)
  1647. of nkFinally, nkDefer:
  1648. optNL(g)
  1649. if n.kind == nkFinally:
  1650. put(g, tkFinally, "finally")
  1651. else:
  1652. put(g, tkDefer, "defer")
  1653. putWithSpace(g, tkColon, ":")
  1654. gcoms(g)
  1655. gstmts(g, n[0], c)
  1656. of nkExceptBranch:
  1657. optNL(g)
  1658. if n.len != 1:
  1659. putWithSpace(g, tkExcept, "except")
  1660. else:
  1661. put(g, tkExcept, "except")
  1662. gcomma(g, n, 0, -2)
  1663. putWithSpace(g, tkColon, ":")
  1664. gcoms(g)
  1665. gstmts(g, lastSon(n), c)
  1666. of nkGenericParams:
  1667. proc hasExplicitParams(gp: PNode): bool =
  1668. for p in gp:
  1669. if p.typ == nil or tfImplicitTypeParam notin p.typ.flags:
  1670. return true
  1671. return false
  1672. if n.hasExplicitParams:
  1673. put(g, tkBracketLe, "[")
  1674. gsemicolon(g, n)
  1675. put(g, tkBracketRi, "]")
  1676. of nkFormalParams:
  1677. put(g, tkParLe, "(")
  1678. gsemicolon(g, n, 1)
  1679. put(g, tkParRi, ")")
  1680. if n.len > 0 and n[0].kind != nkEmpty:
  1681. putWithSpace(g, tkColon, ":")
  1682. gsub(g, n[0])
  1683. of nkTupleTy:
  1684. put(g, tkTuple, "tuple")
  1685. put(g, tkBracketLe, "[")
  1686. gcomma(g, n)
  1687. put(g, tkBracketRi, "]")
  1688. of nkTupleClassTy:
  1689. put(g, tkTuple, "tuple")
  1690. of nkComesFrom:
  1691. put(g, tkParLe, "(ComesFrom|")
  1692. gsub(g, n, 0)
  1693. put(g, tkParRi, ")")
  1694. of nkGotoState:
  1695. var c: TContext = initContext()
  1696. putWithSpace g, tkSymbol, "goto"
  1697. gsons(g, n, c)
  1698. of nkState:
  1699. var c: TContext = initContext()
  1700. putWithSpace g, tkSymbol, "state"
  1701. gsub(g, n[0], c)
  1702. putWithSpace(g, tkColon, ":")
  1703. indentNL(g)
  1704. gsons(g, n, c, 1)
  1705. dedent(g)
  1706. of nkBreakState:
  1707. put(g, tkTuple, "breakstate")
  1708. if renderIds in g.flags:
  1709. gsons(g, n, c, 0)
  1710. of nkTypeClassTy:
  1711. gTypeClassTy(g, n)
  1712. of nkError:
  1713. putWithSpace(g, tkSymbol, "error")
  1714. #gcomma(g, n, c)
  1715. gsub(g, n[0], c)
  1716. else:
  1717. #nkNone, nkExplicitTypeListCall:
  1718. internalError(g.config, n.info, "renderer.gsub(" & $n.kind & ')')
  1719. proc renderTree*(n: PNode, renderFlags: TRenderFlags = {}): string =
  1720. if n == nil: return "<nil tree>"
  1721. var g: TSrcGen = initSrcGen(renderFlags, newPartialConfigRef())
  1722. # do not indent the initial statement list so that
  1723. # writeFile("file.nim", repr n)
  1724. # produces working Nim code:
  1725. if n.kind in {nkStmtList, nkStmtListExpr, nkStmtListType}:
  1726. gstmts(g, n, emptyContext, doIndent = false)
  1727. else:
  1728. gsub(g, n)
  1729. result = g.buf
  1730. proc `$`*(n: PNode): string = n.renderTree
  1731. proc renderModule*(n: PNode, outfile: string,
  1732. renderFlags: TRenderFlags = {};
  1733. fid = FileIndex(-1);
  1734. conf: ConfigRef = nil) =
  1735. var
  1736. f: File = default(File)
  1737. g: TSrcGen = initSrcGen(renderFlags, conf)
  1738. g.fid = fid
  1739. for i in 0..<n.len:
  1740. gsub(g, n[i])
  1741. optNL(g)
  1742. case n[i].kind
  1743. of nkTypeSection, nkConstSection, nkVarSection, nkLetSection,
  1744. nkCommentStmt: putNL(g)
  1745. else: discard
  1746. gcoms(g)
  1747. if open(f, outfile, fmWrite):
  1748. write(f, g.buf)
  1749. close(f)
  1750. else:
  1751. rawMessage(g.config, errGenerated, "cannot open file: " & outfile)
  1752. proc initTokRender*(n: PNode, renderFlags: TRenderFlags = {}): TSrcGen =
  1753. result = initSrcGen(renderFlags, newPartialConfigRef())
  1754. gsub(result, n)
  1755. proc getNextTok*(r: var TSrcGen, kind: var TokType, literal: var string) =
  1756. if r.idx < r.tokens.len:
  1757. kind = r.tokens[r.idx].kind
  1758. let length = r.tokens[r.idx].length.int
  1759. literal = substr(r.buf, r.pos, r.pos + length - 1)
  1760. inc(r.pos, length)
  1761. inc(r.idx)
  1762. else:
  1763. kind = tkEof
  1764. proc getTokSym*(r: TSrcGen): PSym =
  1765. if r.idx > 0 and r.idx <= r.tokens.len:
  1766. result = r.tokens[r.idx-1].sym
  1767. else:
  1768. result = nil