Skip to content

Commit b3fb3b9

Browse files
committed
Beautify program disassemble
1 parent 1a1138d commit b3fb3b9

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

vm/program.go

+16-10
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package vm
22

33
import (
4+
"bytes"
45
"fmt"
6+
"reflect"
57
"regexp"
68
"strings"
9+
"text/tabwriter"
710

811
"github.com/antonmedv/expr/ast"
912
"github.com/antonmedv/expr/builtin"
@@ -22,7 +25,8 @@ type Program struct {
2225
}
2326

2427
func (program *Program) Disassemble() string {
25-
out := ""
28+
var buf bytes.Buffer
29+
w := tabwriter.NewWriter(&buf, 0, 0, 2, ' ', 0)
2630
ip := 0
2731
for ip < len(program.Bytecode) {
2832
pp := ip
@@ -31,16 +35,16 @@ func (program *Program) Disassemble() string {
3135
ip += 1
3236

3337
code := func(label string) {
34-
out += fmt.Sprintf("%v\t%v\n", pp, label)
38+
_, _ = fmt.Fprintf(w, "%v\t%v\n", pp, label)
3539
}
3640
jump := func(label string) {
37-
out += fmt.Sprintf("%v\t%v\t%v\t(%v)\n", pp, label, arg, ip+arg)
41+
_, _ = fmt.Fprintf(w, "%v\t%v\t<%v>\t(%v)\n", pp, label, arg, ip+arg)
3842
}
3943
jumpBack := func(label string) {
40-
out += fmt.Sprintf("%v\t%v\t%v\t(%v)\n", pp, label, arg, ip-arg)
44+
_, _ = fmt.Fprintf(w, "%v\t%v\t<%v>\t(%v)\n", pp, label, arg, ip-arg)
4145
}
4246
argument := func(label string) {
43-
out += fmt.Sprintf("%v\t%v\t%v\n", pp, label, arg)
47+
_, _ = fmt.Fprintf(w, "%v\t%v\t<%v>\n", pp, label, arg)
4448
}
4549
constant := func(label string) {
4650
var c interface{}
@@ -58,14 +62,14 @@ func (program *Program) Disassemble() string {
5862
if method, ok := c.(*runtime.Method); ok {
5963
c = fmt.Sprintf("{%v %v}", method.Name, method.Index)
6064
}
61-
out += fmt.Sprintf("%v\t%v\t%v\t%v\n", pp, label, arg, c)
65+
_, _ = fmt.Fprintf(w, "%v\t%v\t<%v>\t%v\n", pp, label, arg, c)
6266
}
6367
builtIn := func(label string) {
6468
f, ok := builtin.Builtins[arg]
6569
if !ok {
6670
panic(fmt.Sprintf("unknown builtin %v", arg))
6771
}
68-
out += fmt.Sprintf("%v\t%v\t%v\n", pp, "OpBuiltin", f.Name)
72+
_, _ = fmt.Fprintf(w, "%v\t%v\t%v\n", pp, "OpBuiltin", f.Name)
6973
}
7074

7175
switch op {
@@ -223,7 +227,8 @@ func (program *Program) Disassemble() string {
223227
argument("OpCallFast")
224228

225229
case OpCallTyped:
226-
argument("OpCallTyped")
230+
signature := reflect.TypeOf(FuncTypes[arg]).Elem().String()
231+
_, _ = fmt.Fprintf(w, "%v\t%v\t<%v>\t%v\n", pp, "OpCallTyped", arg, signature)
227232

228233
case OpBuiltin:
229234
builtIn("OpBuiltin")
@@ -265,8 +270,9 @@ func (program *Program) Disassemble() string {
265270
code("OpEnd")
266271

267272
default:
268-
out += fmt.Sprintf("%v\t%#x\n", ip, op)
273+
_, _ = fmt.Fprintf(w, "%v\t%#x\n", ip, op)
269274
}
270275
}
271-
return out
276+
_ = w.Flush()
277+
return buf.String()
272278
}

0 commit comments

Comments
 (0)