-
Notifications
You must be signed in to change notification settings - Fork 0
/
AstPrinter.cs
55 lines (47 loc) · 1.28 KB
/
AstPrinter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cslox
{
class AstPrinter : IVisit<string>
{
public string Print(Expr expr)
{
return expr.Accept(this);
}
public string Visit(Expr.Binary expr)
{
return Parenthesize(expr.oper.lexeme, expr.left, expr.right);
}
public string Visit(Expr.Grouping expr)
{
return Parenthesize("group", expr.expr);
}
public string Visit(Expr.Literal expr)
{
if (expr.value != null)
{
return expr.value.ToString();
}
return "nil";
}
public string Visit(Expr.Unary expr)
{
return Parenthesize(expr.oper.lexeme, expr.right);
}
private string Parenthesize(string name, params Expr[] exprs)
{
StringBuilder builder = new StringBuilder();
builder.Append("(").Append(name);
foreach (Expr expr in exprs)
{
builder.Append(" ");
builder.Append(expr.Accept(this));
}
builder.Append(")");
return builder.ToString();
}
}
}