-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvm.go
803 lines (643 loc) · 11.9 KB
/
vm.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
package gates
import (
"context"
"errors"
"fmt"
"math"
"strings"
)
type valueStack struct {
l []Value
sp int
}
type stash struct {
values valueStack
names map[string]uint32
outer *stash
}
type ctx struct {
program *Program
stash *stash
pc, bp int
}
var (
ErrStackOverflow = errors.New("stack overflow")
ErrCyclesLimitExceeded = errors.New("cycles limit exceeded")
)
func (v *valueStack) init() {
v.l = v.l[:0]
v.sp = 0
}
func (v *valueStack) expand(idx int) {
l := len(v.l)
if idx < l {
return
}
if idx < cap(v.l) {
v.l = v.l[:idx+1]
} else {
n := make([]Value, idx+1, (idx+1)<<1)
copy(n, v.l)
v.l = n
}
for i := range v.l[l:] {
v.l[l+i] = Null
}
}
func (v *valueStack) Push(value Value) {
v.expand(v.sp)
v.l[v.sp] = value
v.sp++
}
func (v *valueStack) Peek() Value {
return v.l[v.sp-1]
}
func (v *valueStack) Pop() Value {
v.sp--
return v.l[v.sp]
}
func (v *valueStack) PopN(n int) []Value {
values := v.l[v.sp-n : v.sp]
v.sp -= n
return values
}
func (s *stash) putByName(name string, v Value) bool {
if idx, ok := s.names[name]; ok {
s.values.expand(int(idx))
s.values.l[idx] = v
return true
}
return false
}
func (s *stash) putByIdx(idx uint32, v Value) {
s.values.expand(int(idx))
s.values.l[idx] = v
}
func (s *stash) getByName(name string) (Value, bool) {
if idx, ok := s.names[name]; ok {
return s.values.l[idx], true
}
return nil, false
}
func (s *stash) getByIdx(idx uint32) Value {
if int(idx) < len(s.values.l) {
return s.values.l[idx]
}
return Null
}
type vm struct {
r *Runtime
ctx context.Context
halt bool
pc int
stack valueStack
stash *stash
callStack []ctx
bp int
program *Program
cyclesLimit int
}
func (vm *vm) newStash() {
vm.stash = &stash{
outer: vm.stash,
}
}
func (vm *vm) init() {
vm.stack.init()
vm.stash = nil
vm.callStack = nil
}
func (vm *vm) run() (err error) {
defer func() {
r := recover()
if r != nil {
if rErr, ok := r.(error); ok {
if rErr == ErrStackOverflow {
err = rErr
return
}
}
panic(r)
}
}()
vm.halt = false
ctx := vm.ctx
remainingCycles := vm.cyclesLimit
for !vm.halt {
select {
case <-ctx.Done():
return ctx.Err()
default:
if remainingCycles > 0 {
if remainingCycles--; remainingCycles == 0 {
return ErrCyclesLimitExceeded
}
}
}
vm.program.code[vm.pc].exec(vm)
}
return nil
}
func (vm *vm) pushCtx() {
if len(vm.callStack) > 1<<10 {
panic(ErrStackOverflow)
}
vm.callStack = append(vm.callStack, ctx{
program: vm.program,
stash: vm.stash,
pc: vm.pc,
bp: vm.bp,
})
}
func (vm *vm) popCtx() {
l := len(vm.callStack) - 1
vm.program = vm.callStack[l].program
vm.stash = vm.callStack[l].stash
vm.pc = vm.callStack[l].pc
vm.bp = vm.callStack[l].bp
vm.callStack = vm.callStack[:l]
}
type instruction interface {
exec(*vm)
}
type _halt struct{}
var halt _halt
func (_halt) exec(vm *vm) {
vm.halt = true
vm.pc++
}
type _noop struct{}
var noop _noop
func (_noop) exec(vm *vm) {
vm.pc++
}
type load uint
func (index load) exec(vm *vm) {
vm.stack.Push(vm.program.values[index])
vm.pc++
}
type _loadNull struct{}
var loadNull _loadNull
func (_loadNull) exec(vm *vm) {
vm.stack.Push(Null)
vm.pc++
}
type _loadGlobal struct{}
var loadGlobal _loadGlobal
func (_loadGlobal) exec(vm *vm) {
vm.stack.Push(vm.r.global.m)
vm.pc++
}
type loadStack int
func (l loadStack) exec(vm *vm) {
idx := int(l)
bp := vm.bp
if l < 0 {
argc := int(vm.stack.l[bp-1].ToInt())
argn := -idx - 1
if argn >= argc {
vm.stack.Push(Null)
} else {
vm.stack.Push(vm.stack.l[bp-1-argc+argn])
}
} else {
vm.stack.Push(vm.stack.l[bp+idx])
}
vm.pc++
}
type storeStack uint32
func (s storeStack) exec(vm *vm) {
idx := int(s)
bp := vm.bp
vm.stack.l[bp+idx] = vm.stack.Pop()
vm.pc++
}
type loadLocal uint32
func (l loadLocal) exec(vm *vm) {
level := l >> 24
idx := uint32(l & 0x00FFFFFF)
stash := vm.stash
for ; level > 0; level-- {
stash = stash.outer
}
vm.stack.Push(stash.getByIdx(idx))
vm.pc++
}
type storeLocal uint32
func (s storeLocal) exec(vm *vm) {
v := vm.stack.Pop()
level := s >> 24
idx := uint32(s & 0x00FFFFFF)
stash := vm.stash
for ; level > 0; level-- {
stash = stash.outer
}
stash.putByIdx(idx, v)
vm.pc++
}
type _pop struct{}
var pop _pop
func (_pop) exec(vm *vm) {
vm.stack.Pop()
vm.pc++
}
type newArray uint
func (l newArray) exec(vm *vm) {
values := make([]Value, l)
copy(values, vm.stack.PopN(int(l)))
vm.stack.Push(NewArray(values))
vm.pc++
}
var arrayPush _arrayPush
type _arrayPush struct{}
func (l _arrayPush) exec(vm *vm) {
value := vm.stack.Pop()
array := vm.stack.Pop().(Array)
array.push(value)
vm.stack.Push(array)
vm.pc++
}
var arrayConcat _arrayConcat
type _arrayConcat struct{}
func (l _arrayConcat) exec(vm *vm) {
array2 := vm.stack.Pop()
array := vm.stack.Pop().(Array)
iterable, ok := GetIterable(array2)
if !ok {
goto End
}
{
it := iterable.Iterator()
for {
value, ok := it.Next()
if !ok {
break
}
array.push(value)
}
}
End:
vm.stack.Push(array)
vm.pc++
}
type newMap uint
func (l newMap) exec(vm *vm) {
m := make(Map, l)
ll := int(l) * 2
kvs := vm.stack.PopN(ll)
for i := 0; i < ll; i += 2 {
key := kvs[i]
value := kvs[i+1]
m[key.ToString()] = value
}
vm.stack.Push(m)
vm.pc++
}
var mapSet _mapSet
type _mapSet struct{}
func (l _mapSet) exec(vm *vm) {
v := vm.stack.Pop()
k := vm.stack.Pop()
m := vm.stack.Pop().(Map)
m[k.ToString()] = v
vm.stack.Push(m)
vm.pc++
}
var mapConcat _mapConcat
type _mapConcat struct{}
func (l _mapConcat) exec(vm *vm) {
m2 := vm.stack.Pop()
m := vm.stack.Pop().(Map)
iterable, ok := GetIterable(m2)
if !ok {
goto End
}
{
it := iterable.Iterator()
for {
entry, ok := it.Next()
if !ok {
break
}
k := objectGet(vm.r, entry, String("key")).ToString()
v := objectGet(vm.r, entry, String("value"))
m[k] = v
}
}
End:
vm.stack.Push(m)
vm.pc++
}
type newFunc struct {
program *Program
stackSize int
}
func (l newFunc) exec(vm *vm) {
f := &literalFunction{
program: l.program,
stackSize: l.stackSize,
stash: vm.stash,
}
vm.stack.Push(f)
vm.pc++
}
type _newStash struct{}
var newStash _newStash
func (_newStash) exec(vm *vm) {
vm.newStash()
vm.pc++
}
type _popStash struct{}
var popStash _popStash
func (_popStash) exec(vm *vm) {
vm.stash = vm.stash.outer
vm.pc++
}
type _set struct{}
var set _set
func (_set) exec(vm *vm) {
base := vm.stack.Pop()
key := vm.stack.Pop()
value := vm.stack.Pop()
objectSet(vm.r, base, key, value)
vm.pc++
}
type _get struct{}
var get _get
func (_get) exec(vm *vm) {
base := vm.stack.Pop()
key := vm.stack.Pop()
vm.stack.Push(objectGet(vm.r, base, key))
vm.pc++
}
type jmp1 int64
func (j jmp1) exec(vm *vm) {
vm.pc += int(j)
}
type jne int32
func (j jne) exec(vm *vm) {
if !vm.stack.Pop().ToBool() {
vm.pc += int(j)
} else {
vm.pc++
}
}
type jeq1 int64
func (j jeq1) exec(vm *vm) {
if vm.stack.Peek().ToBool() {
vm.pc += int(j)
} else {
vm.pc++
}
}
type jneq1 int64
func (j jneq1) exec(vm *vm) {
if !vm.stack.Peek().ToBool() {
vm.pc += int(j)
} else {
vm.pc++
}
}
type _plus struct{}
var plus _plus
func (_plus) exec(vm *vm) {
vm.stack.Push(vm.stack.Pop().ToNumber())
vm.pc++
}
type _neg struct{}
var neg _neg
func (_neg) exec(vm *vm) {
n := vm.stack.Pop().ToNumber()
if n.IsInt() {
vm.stack.Push(intToValue(-n.ToInt()))
} else {
vm.stack.Push(Float(-n.ToFloat()))
}
vm.pc++
}
type _not struct{}
var not _not
func (_not) exec(vm *vm) {
v := vm.stack.Pop().ToBool()
vm.stack.Push(Bool(!v))
vm.pc++
}
type _add struct{}
var add _add
func (_add) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
switch {
case x.IsString() || y.IsString():
xStr, yStr := x.ToString(), y.ToString()
vm.stack.Push(String(xStr + yStr))
case x.IsInt() && y.IsInt():
vm.stack.Push(intToValue(x.ToInt() + y.ToInt()))
default:
vm.stack.Push(Float(x.ToFloat() + y.ToFloat()))
}
vm.pc++
}
type _sub struct{}
var sub _sub
func (_sub) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
switch {
case x.IsInt() && y.IsInt():
vm.stack.Push(intToValue(x.ToInt() - y.ToInt()))
default:
vm.stack.Push(Float(x.ToFloat() - y.ToFloat()))
}
vm.pc++
}
type _mul struct{}
var mul _mul
func (_mul) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
switch {
case x.IsInt() && y.IsInt():
xI, yI := x.ToInt(), y.ToInt()
res := xI * yI
// overflow
if xI != 0 && res/xI != yI {
vm.stack.Push(Float(x.ToFloat() * y.ToFloat()))
vm.pc++
return
}
vm.stack.Push(intToValue(x.ToInt() * y.ToInt()))
default:
vm.stack.Push(Float(x.ToFloat() * y.ToFloat()))
}
vm.pc++
}
type _div struct{}
var div _div
func (_div) exec(vm *vm) {
y := vm.stack.Pop().ToFloat()
x := vm.stack.Pop().ToFloat()
vm.stack.Push(Float(x / y))
vm.pc++
}
type _mod struct{}
var mod _mod
func (_mod) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
if x.IsInt() && y.IsInt() {
xI, yI := x.ToInt(), y.ToInt()
if yI != 0 {
vm.stack.Push(intToValue(xI % yI))
vm.pc++
return
}
}
vm.stack.Push(Float(math.Mod(x.ToFloat(), y.ToFloat())))
vm.pc++
}
type _xor struct{}
var xor _xor
func (_xor) exec(vm *vm) {
y := vm.stack.Pop().ToInt()
x := vm.stack.Pop().ToInt()
vm.stack.Push(intToValue(x ^ y))
vm.pc++
}
type _shl struct{}
var shl _shl
func (_shl) exec(vm *vm) {
y := vm.stack.Pop().ToInt()
x := vm.stack.Pop().ToInt()
vm.stack.Push(intToValue(x << uint64(y)))
vm.pc++
}
type _shr struct{}
var shr _shr
func (_shr) exec(vm *vm) {
y := vm.stack.Pop().ToInt()
x := vm.stack.Pop().ToInt()
vm.stack.Push(intToValue(x >> uint64(y)))
vm.pc++
}
type _eq struct{}
var eq _eq
func (_eq) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
vm.stack.Push(Bool(x.Equals(y)))
vm.pc++
}
type _neq struct{}
var neq _neq
func (_neq) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
vm.stack.Push(Bool(!x.Equals(y)))
vm.pc++
}
func less(x, y Value) Value {
switch {
case x.IsString() && y.IsString():
xs, ys := x.ToString(), y.ToString()
return Bool(strings.Compare(xs, ys) == -1)
case x.IsInt() && y.IsInt():
return Bool(x.ToInt() < y.ToInt())
}
nx := x.ToFloat()
ny := y.ToFloat()
if math.IsNaN(nx) || math.IsNaN(ny) {
return Null
}
return Bool(nx < ny)
}
type _lt struct{}
var lt _lt
func (_lt) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
ret := less(x, y)
if ret == Null {
vm.stack.Push(False)
} else {
vm.stack.Push(ret)
}
vm.pc++
}
type _lte struct{}
var lte _lte
func (_lte) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
ret := less(y, x)
if ret == Null || ret == True {
vm.stack.Push(False)
} else {
vm.stack.Push(True)
}
vm.pc++
}
type _gt struct{}
var gt _gt
func (_gt) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
ret := less(y, x)
if ret == Null {
vm.stack.Push(False)
} else {
vm.stack.Push(ret)
}
vm.pc++
}
type _gte struct{}
var gte _gte
func (_gte) exec(vm *vm) {
y := vm.stack.Pop()
x := vm.stack.Pop()
ret := less(x, y)
if ret == Null || ret == True {
vm.stack.Push(False)
} else {
vm.stack.Push(True)
}
vm.pc++
}
type _call struct{}
var call _call
func (_call) exec(vm *vm) {
fun := vm.stack.Pop().ToFunction()
switch f := fun.(type) {
case *nativeFunction:
argc := int(vm.stack.Pop().ToInt())
args := vm.stack.PopN(argc)
fc := &functionCall{vm: vm, args: args}
vm.stack.Push(f.fun(fc))
vm.pc++
case *literalFunction:
vm.pc++
vm.pushCtx()
vm.bp = vm.stack.sp
for i := 0; i < f.stackSize; i++ {
vm.stack.Push(Null)
}
vm.stash = f.stash
vm.program = f.program
vm.pc = 0
default:
panic(fmt.Errorf("unsupported function type: %T", fun))
}
}
type _ret struct{}
var ret _ret
func (_ret) exec(vm *vm) {
argc := int(vm.stack.l[vm.bp-1].ToInt())
returnValue := vm.stack.Pop()
vm.stack.sp = vm.bp - 1 - argc
vm.stack.l = vm.stack.l[:vm.stack.sp]
vm.stack.Push(returnValue)
vm.popCtx()
if vm.pc < 0 {
vm.halt = true
}
}