renderer.nim 46 KB

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