-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAstPrinter.cs
101 lines (85 loc) · 2.81 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Lox
{
internal class AstPrinter : Expr.IVisitor<string>
{
internal string print(Expr expr)
{
return expr.Accept(this);
}
string Expr.IVisitor<string>.VisitBinaryExpr(Expr.Binary expr)
{
return parenthesize(expr.lox_operator.lexeme, expr.left, expr.right);
}
string Expr.IVisitor<string>.VisitGroupingExpr(Expr.Grouping expr)
{
return parenthesize("group", expr.expression);
}
string Expr.IVisitor<string>.VisitLiteralExpr(Expr.Literal expr)
{
if (expr.value == null) return "nil";
return expr.value.ToString();
}
string Expr.IVisitor<string>.VisitUnaryExpr(Expr.Unary expr)
{
return parenthesize(expr.lox_operator.lexeme, expr.right);
}
private string parenthesize(string name, params Expr[] exprs)
{
StringBuilder builder = new StringBuilder();
builder.Append("(").Append(name);
foreach (var expression in exprs)
{
builder.Append(" ");
builder.Append(expression.Accept(this));
}
builder.Append(")");
return builder.ToString();
}
internal static void AstTest()
{
var unary = new Expr.Unary(new Token(TokenType.MINUS, "-", null, 1), new Expr.Literal(123));
var token = new Token(TokenType.STAR, "*", null, 1);
var expression = new Expr.Grouping(new Expr.Literal(45.67));
var binary = new Expr.Binary(unary, token, expression);
Console.WriteLine(new AstPrinter().print(binary));
}
public string VisitVariableExpr(Expr.Variable expr)
{
throw new NotImplementedException();
}
public string VisitAssignExpr(Expr.Assign expr)
{
throw new NotImplementedException();
}
public string VisitLogicalExpr(Expr.Logical expr)
{
throw new NotImplementedException();
}
public string VisitCallExpr(Expr.Call expr)
{
throw new NotImplementedException();
}
public string VisitGetExpr(Expr.Get expr)
{
throw new NotImplementedException();
}
public string VisitSetExpr(Expr.Set expr)
{
throw new NotImplementedException();
}
public string VisitThisExpr(Expr.This expr)
{
throw new NotImplementedException();
}
public string VisitSuperExpr(Expr.Super expr)
{
throw new NotImplementedException();
}
}
}