-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast_printer.cr
91 lines (73 loc) · 1.9 KB
/
ast_printer.cr
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
require "./expr.cr"
require "./scanner.cr"
class AstPrinter
include Expr::Visitor(String)
def print(expr : Expr)
return expr.accept(self)
end
def visit_assign_expr(expr : Expr::Assign)
return "ASSIGN"
end
def visit_call_expr(expr : Expr::Call)
return "CLASS"
end
def visit_get_expr(expr : Expr::Get)
return "GET"
end
def visit_set_expr(expr : Expr::Set)
return "SET"
end
def visit_this_expr(expr : Expr::This)
return "THIS"
end
def visit_super_expr(expr : Expr::Super)
return "SUPER"
end
def visit_binary_expr(expr : Expr::Binary)
return parenthesize(expr.operator.lexeme, expr.left, expr.right)
end
def visit_grouping_expr(expr : Expr::Grouping)
return parenthesize("group", expr.expression)
end
def visit_literal_expr(expr : Expr::Literal)
return "nil" if expr.value.nil?
return expr.value.to_s
end
def visit_unary_expr(expr : Expr::Unary)
return parenthesize(expr.operator.lexeme, expr.right)
end
def visit_variable_expr(expr : Expr::Variable)
return "VAR"
end
def visit_logical_expr(expr : Expr::Logical)
return "LOGICAL"
end
def parenthesize(name : String, *exprs : Expr)
res = ""
res += "(#{name}"
exprs.each do |expr|
res += " #{expr.accept(self)}"
end
res += ")"
return res
end
end
def main()
expression : Expr = Expr::Binary.new(
Expr::Unary.new(
Token.new(
TokenType::Minus, "-", nil, 1
),
Expr::Literal.new(123)
),
Token.new(
TokenType::Star, "*", nil, 1
),
Expr::Grouping.new(
Expr::Literal.new(45.67)
)
)
ast_printer = AstPrinter.new
puts(ast_printer.print(expression))
end
# main()