-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
78 lines (62 loc) · 1.48 KB
/
ast.go
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
package main
import (
"fmt"
"strconv"
"strings"
)
type BoolLiteral bool
type IntLiteral int
type FloatLiteral float64
type StringLiteral string
func (b BoolLiteral) String() string {
if b {
return "true"
}
return "false"
}
func (f FloatLiteral) String() string {
return strconv.FormatFloat(float64(f), 'f', -1, 64)
}
func (i IntLiteral) String() string {
return strconv.FormatInt(int64(i), 10)
}
func (s StringLiteral) String() string {
return string(s)
}
type Visitor interface {
visitBinaryExpr(expr BinaryExpr) string
visitGroupingExpr(expr GroupingExpr) string
visitLiteralExpr(expr LiteralExpr) string
visitUnaryExpr(expr UnaryExpr) string
}
type AstPrinter struct {
}
func (p AstPrinter) Print(expr Expr) {
fmt.Println(expr.Accept(p))
}
func (p AstPrinter) parenthesize(name []byte, exprs ...Expr) string {
var b strings.Builder
b.WriteByte('(')
b.Write(name)
for _, expr := range exprs {
b.WriteByte(' ')
b.WriteString(expr.Accept(p))
}
b.WriteByte(')')
return b.String()
}
func (p AstPrinter) visitBinaryExpr(expr BinaryExpr) string {
return p.parenthesize(expr.op.lexeme, expr.lhs, expr.rhs)
}
func (p AstPrinter) visitGroupingExpr(expr GroupingExpr) string {
return p.parenthesize([]byte("group"), expr.expr)
}
func (p AstPrinter) visitLiteralExpr(expr LiteralExpr) string {
if expr.value == nil {
return "nil"
}
return expr.value.String()
}
func (p AstPrinter) visitUnaryExpr(expr UnaryExpr) string {
return p.parenthesize(expr.op.lexeme, expr.rhs)
}