-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAstPrinter.js
61 lines (51 loc) · 1.22 KB
/
AstPrinter.js
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
const {
Expr,
Binary,
Unary,
Literal,
Grouping,
} = require('./Expr.js');
const Token = require('./Token');
const TokenType = require('./TokenType');
class AstPrinter extends Expr {
print(expr) {
return expr.accept(this);
}
visitBinaryExpr(expr) {
return this.parenthesized(expr.operator.lexeme,
expr.left, expr.right);
}
visitGroupingExpr(expr) {
return this.parenthesized('group', expr.expression);
}
visitLiteralExpr(expr) {
if (expr.value === null) return 'nil';
return expr.value.toString();
}
visitUnaryExpr(expr) {
return this.parenthesized(expr.operator.lexeme, expr.right);
}
parenthesized(name, ...exprs) {
const builder = [];
builder.push('(');
builder.push(name);
for (let expr of exprs) {
builder.push(' ');
builder.push(expr.accept(this));
}
builder.push(')');
return builder.join('');
}
}
module.exports = AstPrinter;
if (!module.parent) {
const expression = new Binary(
new Unary(
new Token(TokenType.MINUS, '-', null, 1),
new Literal(123)
),
new Token(TokenType.STAR, '*', null, 1),
new Grouping(new Literal(45.67))
);
console.log(new AstPrinter().print(expression));
}