-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.go
331 lines (276 loc) · 6.3 KB
/
machine.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package bcl
import (
"fmt"
"io"
"strconv"
"strings"
)
type vmConfig struct{ trace bool }
func execute(p *Prog, cf vmConfig) ([]Block, execStats, error) {
vm := &vm{
output: p.output,
trace: cf.trace,
prog: p,
pc: 0,
}
err := vm.run()
vm.stats.pcFinal = vm.pc
return vm.result, vm.stats, err
}
type vm struct {
prog *Prog
pc int
stack [stackSize]value
tos int
output io.Writer
trace bool
blockStack [blockStackSize]Block
blockTos int
result []Block
stats execStats
}
const (
stackSize = 1024
blockStackSize = 16
)
type execStats struct {
tosMax int
blockTosMax int
opsRead int
pcFinal int
}
func (vm *vm) run() error {
readByte := func() (b byte) {
b = vm.prog.code[vm.pc]
vm.pc++
return b
}
readOp := func() (o opcode) {
o = opcode(readByte())
vm.stats.opsRead++
return o
}
readU16 := func() int {
x := u16FromBytes(vm.prog.code[vm.pc : vm.pc+2])
vm.pc += 2
return int(x)
}
readUvarint := func() int {
x, n := uvarintFromBytes(vm.prog.code[vm.pc:])
vm.pc += n
return int(x)
}
readConst := func() value {
return vm.prog.constants[readUvarint()]
}
push := func(v value) {
vm.stack[vm.tos] = v
vm.tos++
vm.stats.tosMax = max(vm.stats.tosMax, vm.tos)
}
pop := func() value {
vm.tos--
return vm.stack[vm.tos]
}
peek := func(distance int) value {
return vm.stack[vm.tos-1-distance]
}
set := func(v value) {
vm.stack[vm.tos-1] = v
}
blockGet := func(name string) (v value, ok bool) {
switch name {
case "TYPE":
return vm.blockStack[vm.blockTos-1].Type, true
case "NAME":
return vm.blockStack[vm.blockTos-1].Name, true
}
for i := vm.blockTos - 1; i >= 0; i-- {
v, ok = vm.blockStack[i].Fields[name]
if ok {
return v, ok
}
}
return
}
blockSet := func(name string, v value) {
vm.blockStack[vm.blockTos-1].Fields[name] = v
}
for {
if vm.trace {
printStack(vm.output, vm.stack[:vm.tos])
vm.prog.disasmInstr(vm.pc)
}
switch instr := readOp(); instr {
case opCONST:
// ( -- x )
push(readConst())
case opZERO:
// ( -- 0 )
push(0)
case opONE:
// ( -- 1 )
push(1)
case opTRUE:
// ( -- true )
push(true)
case opFALSE:
// ( -- false )
push(false)
case opNIL:
// ( -- nil )
push(nil)
case opEQ, opLT, opGT, opADD, opSUB, opMUL, opDIV:
// ( a b -- c )
switch {
case isNumber(peek(1)) && isNumber(peek(0)):
if b := peek(0); instr == opDIV && isInt(b) && b == 0 {
return vm.runtimeError("division by int zero")
}
b, a := pop(), pop()
push(binopNumeric(instr, a, b))
case (instr == opLT || instr == opGT || instr == opADD) &&
isString(peek(1)) && isString(peek(0)):
b, a := pop().(string), pop().(string)
push(binopString(instr, a, b))
case instr == opADD && isString(peek(1)) && isInt(peek(0)):
b, a := pop().(int), pop().(string)
push(a + strconv.Itoa(b))
case instr == opADD && isString(peek(1)) && isFloat(peek(0)):
b, a := pop().(float64), pop().(string)
push(a + strconv.FormatFloat(b, 'f', -1, 64))
case instr == opADD && isString(peek(1)) && peek(0) == nil:
pop()
case instr == opMUL && isString(peek(1)) && isInt(peek(0)):
b, a := pop().(int), pop().(string)
push(strings.Repeat(a, b))
case instr == opEQ:
b, a := pop(), pop()
push(a == b)
default:
return vm.runtimeError(
"%s: invalid types: %s, %s", instr, vtype(peek(1)), vtype(peek(0)),
)
}
case opNEG:
// ( a -- b )
if !isNumber(peek(0)) {
return vm.runtimeError("NEG: invalid type: %s, expected number", vtype(peek(0)))
}
set(unopNumeric(instr, peek(0)))
case opUNPLUS:
// ( a -- a )
if !isNumber(peek(0)) {
return vm.runtimeError("UNPLUS: invalid type: %s, expected number", vtype(peek(0)))
}
// do nothing
case opNOT:
// ( a -- b )
set(isFalsey(peek(0)))
case opJUMP:
// ( -- )
vm.pc += readU16()
case opLOOP:
// ( -- )
vm.pc -= readU16()
case opJFALSE:
// ( a -- a )
jump := readU16()
if isFalsey(peek(0)) {
vm.pc += jump
}
case opPOP:
// ( a -- )
vm.tos--
case opPOPN:
// ( a1 ..aN -- )
vm.tos -= int(readUvarint())
case opPRINT:
// ( a -- )
fmt.Fprintln(vm.output, pop())
case opGETLOCAL:
// ( -- x )
slot := readUvarint()
push(vm.stack[slot])
case opSETLOCAL:
// ( x -- x )
slot := readUvarint()
vm.stack[slot] = peek(0)
case opDEFBLOCK:
// ( -- )
blk := Block{
Type: readConst().(string),
Name: readConst().(string),
Fields: map[string]any{},
}
vm.blockStack[vm.blockTos] = blk
vm.blockTos++
vm.stats.blockTosMax = max(vm.stats.blockTosMax, vm.blockTos)
case opENDBLOCK:
// ( -- )
vm.blockTos--
i := vm.blockTos
if i > 0 {
var (
child = &vm.blockStack[i]
parent = &vm.blockStack[i-1]
k = child.key()
)
// note: good to have the following safety check, although
// with the current syntax and with the key=type.name,
// it is impossible to trigger it
if _, ok := parent.Fields[k]; ok {
return vm.runtimeError("child %s duplicate at parent", k)
}
parent.Fields[k] = *child
} else {
// todo: uniqueness check
vm.result = append(vm.result, vm.blockStack[0])
}
case opGETFIELD:
// ( -- x )
name := readConst().(string)
v, ok := blockGet(name)
if !ok {
return vm.runtimeError("identifier '%s' not resolved as var or field", name)
}
push(v)
case opSETFIELD:
// ( x -- x )
name := readConst().(string)
blockSet(name, peek(0))
case opRET:
// ( -- )
if vm.tos != 0 {
return fmt.Errorf("internal error: non-empty stack on prog end; tos=%d", vm.tos)
}
return nil
case opNOP:
// ( -- )
}
}
}
func (vm *vm) runtimeError(format string, a ...any) error {
b := new(strings.Builder)
pos := vm.prog.positions[vm.pc-1]
fmt.Fprintf(b, "runtime error: line %s: ", vm.prog.linePos.format(pos))
fmt.Fprintf(b, format, a...)
return &runtimeErr{b.String()}
}
func (b *Block) key() string {
if b.Name == "" {
return b.Type
}
return b.Type + "." + b.Name
}
func printStack(w io.Writer, vv []value) {
fmt.Fprintf(w, " %d: ", len(vv))
for _, v := range vv {
fmt.Fprintf(w, "[ %v ]", v)
}
fmt.Fprintln(w)
}
type runtimeErr struct {
msg string
}
func (e *runtimeErr) Error() string { return e.msg }