-
Notifications
You must be signed in to change notification settings - Fork 0
/
print.go
49 lines (41 loc) · 814 Bytes
/
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
package eval
import (
"bytes"
"fmt"
)
// Format formats an expression as a string.
// It does not attempt to remove unnecessary parens.
func Format(e Expr) string {
var buf bytes.Buffer
write(&buf, e)
return buf.String()
}
func write(buf *bytes.Buffer, e Expr) {
switch e := e.(type) {
case literal:
fmt.Fprintf(buf, "%g", e)
case Var:
fmt.Fprintf(buf, "%s", e)
case unary:
fmt.Fprintf(buf, "(%c", e.op)
write(buf, e.x)
buf.WriteByte(')')
case binary:
buf.WriteByte('(')
write(buf, e.x)
fmt.Fprintf(buf, " %c ", e.op)
write(buf, e.y)
buf.WriteByte(')')
case call:
fmt.Fprintf(buf, "%s(", e.fn)
for i, arg := range e.args {
if i > 0 {
buf.WriteString(", ")
}
write(buf, arg)
}
buf.WriteByte(')')
default:
panic(fmt.Sprintf("unknown Expr: %T", e))
}
}