-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
64 lines (48 loc) · 1.52 KB
/
printer.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
package expr
import (
"fmt"
"strings"
)
type AstPrinter struct{}
var _ ExprVisitorStr = (*AstPrinter)(nil)
func (p *AstPrinter) Print(expr Expr) string {
return expr.AcceptStr(p)
}
func (p *AstPrinter) VisitExprBinaryStr(expr *ExprBinary) string {
return p.block(expr.operator.lexeme, "(", ")", expr.left, expr.right)
}
func (p *AstPrinter) VisitExprGroupingStr(expr *ExprGrouping) string {
return p.block("group", "(", ")", expr.expression)
}
func (p *AstPrinter) VisitExprLiteralStr(expr *ExprLiteral) string {
if expr.value == nil {
return "nil"
}
return fmt.Sprint(expr.value)
}
func (p *AstPrinter) VisitExprUnaryStr(expr *ExprUnary) string {
return p.block(expr.operator.lexeme, "(", ")", expr.right)
}
func (p *AstPrinter) VisitExprCallStr(expr *ExprCall) string {
return p.block(expr.callee.AcceptStr(p), "(", ")", expr.arguments...)
}
func (p *AstPrinter) VisitExprLogicalStr(expr *ExprLogical) string {
return p.block(expr.operator.lexeme, "(", ")", expr.left, expr.right)
}
func (p *AstPrinter) VisitExprVariableStr(expr *ExprVariable) string {
return expr.name.lexeme
}
func (p *AstPrinter) VisitExprArrayStr(expr *ExprArray) string {
return p.block(expr.bracket.lexeme, "[", "]", expr.items...)
}
func (p *AstPrinter) block(name, start, end string, exprs ...Expr) string {
var builder strings.Builder
builder.WriteString(start)
builder.WriteString(name)
for _, expr := range exprs {
builder.WriteString(" ")
builder.WriteString(expr.AcceptStr(p))
}
builder.WriteString(end)
return builder.String()
}