renderer.nim 56 KB

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