-
Notifications
You must be signed in to change notification settings - Fork 0
/
AstPrinter.cs
57 lines (48 loc) · 1.41 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
56
57
using ExprNamespace;
/*
class AstPrinter : Expr.Visitor<string>
{
public string print(Expr expr)
{
return expr.accept(this);
}
public string visitBinaryExpr(Expr.Binary expr)
{
return parenthesize(expr.op.lexeme, new Expr[] { expr.left, expr.right });
}
public string visitGroupingExpr(Expr.Grouping expr)
{
return parenthesize("group", new Expr[] { expr.expression });
}
public string visitLiteralExpr(Expr.Literal expr)
{
if (expr.value == null) return "nil";
return expr.value.ToString();
}
public string visitUnaryExpr(Expr.Unary expr)
{
return parenthesize(expr.op.lexeme, new Expr[] { expr.right });
}
private string parenthesize(string name, Expr[] exprs)
{
string returned = $"({name}";
foreach (Expr expr in exprs)
{
returned += $" {expr.accept(this)}";
}
returned += ")";
return returned;
}
public static void Test()
{
Expr expression = new Expr.Binary(
new Expr.Unary(
new LoxSharp.Token(LoxSharp.TokenType.MINUS, "-", null, 1),
new Expr.Literal(123)
),
new LoxSharp.Token(LoxSharp.TokenType.STAR, "*", null, 1),
new Expr.Grouping(new Expr.Literal(45.67))
);
System.Console.WriteLine(new AstPrinter().print(expression));
}
}*/