-
Notifications
You must be signed in to change notification settings - Fork 14
/
print.go
101 lines (88 loc) · 1.58 KB
/
print.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package ast
import (
"io"
"os"
"github.com/mmcloughlin/addchain/internal/errutil"
"github.com/mmcloughlin/addchain/internal/print"
)
// Print an AST node to standard out.
func Print(n interface{}) error {
return Fprint(os.Stdout, n)
}
// Fprint writes the AST node n to w.
func Fprint(w io.Writer, n interface{}) error {
p := newprinter(w)
p.node(n)
return p.Error()
}
type printer struct {
print.Printer
}
func newprinter(w io.Writer) *printer {
p := &printer{
Printer: print.New(w),
}
p.SetIndentString(". ")
return p
}
func (p *printer) node(n interface{}) {
switch n := n.(type) {
case *Chain:
p.enter("chain")
for _, stmt := range n.Statements {
p.statement(stmt)
}
p.leave()
case Statement:
p.statement(n)
case Operand:
p.Linef("operand(%d)", n)
case Identifier:
p.Linef("identifier(%q)", n)
case Add:
p.add(n)
case Double:
p.double(n)
case Shift:
p.shift(n)
default:
p.SetError(errutil.UnexpectedType(n))
}
}
func (p *printer) statement(stmt Statement) {
p.enter("statement")
p.Printf("name = ")
p.node(stmt.Name)
p.Printf("expr = ")
p.node(stmt.Expr)
p.leave()
}
func (p *printer) add(a Add) {
p.enter("add")
p.Printf("x = ")
p.node(a.X)
p.Printf("y = ")
p.node(a.Y)
p.leave()
}
func (p *printer) double(d Double) {
p.enter("double")
p.Printf("x = ")
p.node(d.X)
p.leave()
}
func (p *printer) shift(s Shift) {
p.enter("shift")
p.Linef("s = %d", s.S)
p.Printf("x = ")
p.node(s.X)
p.leave()
}
func (p *printer) enter(name string) {
p.Linef("%s {", name)
p.Indent()
}
func (p *printer) leave() {
p.Dedent()
p.Linef("}")
}