-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvm.go
1732 lines (1545 loc) · 37.7 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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020-2023 Ozan Hacıbekiroğlu.
// Use of this source code is governed by a MIT License
// that can be found in the LICENSE file.
package ugo
import (
"errors"
"fmt"
"runtime"
"strconv"
"sync"
"sync/atomic"
"github.com/ozanh/ugo/parser"
"github.com/ozanh/ugo/token"
)
const (
stackSize = 2048
frameSize = 1024
)
// VM executes the instructions in Bytecode.
type VM struct {
abort int64
sp int
ip int
curInsts []byte
constants []Object
stack [stackSize]Object
frames [frameSize]frame
curFrame *frame
frameIndex int
bytecode *Bytecode
modulesCache []Object
globals Object
pool vmPool
mu sync.Mutex
err error
noPanic bool
}
// NewVM creates a VM object.
func NewVM(bc *Bytecode) *VM {
var constants []Object
if bc != nil {
constants = bc.Constants
}
vm := &VM{
bytecode: bc,
constants: constants,
}
vm.pool.root = vm
return vm
}
// SetRecover recovers panic when Run panics and returns panic as an error.
// If error handler is present `try-catch-finally`, VM continues to run from catch/finally.
func (vm *VM) SetRecover(v bool) *VM {
vm.mu.Lock()
defer vm.mu.Unlock()
vm.noPanic = v
return vm
}
// SetBytecode enables to set a new Bytecode.
func (vm *VM) SetBytecode(bc *Bytecode) *VM {
vm.mu.Lock()
defer vm.mu.Unlock()
vm.bytecode = bc
vm.constants = bc.Constants
vm.modulesCache = nil
return vm
}
// Clear clears stack by setting nil to stack indexes and removes modules cache.
func (vm *VM) Clear() *VM {
vm.mu.Lock()
defer vm.mu.Unlock()
for i := range vm.stack {
vm.stack[i] = nil
}
vm.pool.clear()
vm.modulesCache = nil
vm.globals = nil
return vm
}
// GetGlobals returns global variables.
func (vm *VM) GetGlobals() Object {
return vm.globals
}
// GetLocals returns variables from stack up to the NumLocals of given Bytecode.
// This must be called after Run() before Clear().
func (vm *VM) GetLocals(locals []Object) []Object {
vm.mu.Lock()
defer vm.mu.Unlock()
if locals != nil {
locals = locals[:0]
} else {
locals = make([]Object, 0, vm.bytecode.Main.NumLocals)
}
for i := range vm.stack[:vm.bytecode.Main.NumLocals] {
locals = append(locals, vm.stack[i])
}
return locals
}
// RunCompiledFunction runs given CompiledFunction as if it is Main function.
// Bytecode must be set before calling this method, because Fileset and Constants are copied.
func (vm *VM) RunCompiledFunction(
f *CompiledFunction,
globals Object,
args ...Object,
) (Object, error) {
vm.mu.Lock()
defer vm.mu.Unlock()
if vm.bytecode == nil {
return nil, errors.New("invalid Bytecode")
}
vm.bytecode = &Bytecode{
FileSet: vm.bytecode.FileSet,
Constants: vm.constants,
Main: f,
NumModules: vm.bytecode.NumModules,
}
for i := range vm.stack {
vm.stack[i] = nil
}
return vm.init(globals, args...)
}
// Abort aborts the VM execution. It is safe to call this method from another
// goroutine.
func (vm *VM) Abort() {
vm.pool.abort(vm)
atomic.StoreInt64(&vm.abort, 1)
}
// Aborted reports whether VM is aborted. It is safe to call this method from
// another goroutine.
func (vm *VM) Aborted() bool {
return atomic.LoadInt64(&vm.abort) == 1
}
// Run runs VM and executes the instructions until the OpReturn Opcode or Abort call.
func (vm *VM) Run(globals Object, args ...Object) (Object, error) {
vm.mu.Lock()
defer vm.mu.Unlock()
return vm.init(globals, args...)
}
func (vm *VM) init(globals Object, args ...Object) (Object, error) {
if vm.bytecode == nil || vm.bytecode.Main == nil {
return nil, errors.New("invalid Bytecode")
}
vm.err = nil
atomic.StoreInt64(&vm.abort, 0)
vm.initGlobals(globals)
vm.initLocals(args)
vm.initCurrentFrame()
vm.frameIndex = 1
vm.ip = -1
vm.sp = vm.curFrame.fn.NumLocals
// Resize modules cache or create it if not exists.
// Note that REPL can set module cache before running, don't recreate it add missing indexes.
if diff := vm.bytecode.NumModules - len(vm.modulesCache); diff > 0 {
for i := 0; i < diff; i++ {
vm.modulesCache = append(vm.modulesCache, nil)
}
}
for run := true; run; {
run = vm.run()
}
if vm.err != nil {
return nil, vm.err
}
if vm.sp < stackSize {
if vv, ok := vm.stack[vm.sp-1].(*ObjectPtr); ok {
return *vv.Value, nil
}
return vm.stack[vm.sp-1], nil
}
return nil, ErrStackOverflow
}
func (vm *VM) run() (rerun bool) {
defer func() {
if vm.noPanic {
if r := recover(); r != nil {
vm.handlePanic(r)
rerun = vm.err == nil
return
}
}
vm.clearCurrentFrame()
}()
vm.loop()
return
}
func (vm *VM) loop() {
VMLoop:
for atomic.LoadInt64(&vm.abort) == 0 {
vm.ip++
switch vm.curInsts[vm.ip] {
case OpConstant:
cidx := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
obj := vm.constants[cidx]
vm.stack[vm.sp] = obj
vm.sp++
vm.ip += 2
case OpGetLocal:
localIdx := int(vm.curInsts[vm.ip+1])
value := vm.stack[vm.curFrame.basePointer+localIdx]
if v, ok := value.(*ObjectPtr); ok {
value = *v.Value
}
vm.stack[vm.sp] = value
vm.sp++
vm.ip++
case OpSetLocal:
localIndex := int(vm.curInsts[vm.ip+1])
value := vm.stack[vm.sp-1]
index := vm.curFrame.basePointer + localIndex
if v, ok := vm.stack[index].(*ObjectPtr); ok {
*v.Value = value
} else {
vm.stack[index] = value
}
vm.sp--
vm.stack[vm.sp] = nil
vm.ip++
case OpBinaryOp:
tok := token.Token(vm.curInsts[vm.ip+1])
left, right := vm.stack[vm.sp-2], vm.stack[vm.sp-1]
var value Object
var err error
switch left := left.(type) {
case Int:
value, err = left.BinaryOp(tok, right)
case String:
value, err = left.BinaryOp(tok, right)
case Float:
value, err = left.BinaryOp(tok, right)
case Uint:
value, err = left.BinaryOp(tok, right)
case Char:
value, err = left.BinaryOp(tok, right)
case Bool:
value, err = left.BinaryOp(tok, right)
default:
value, err = left.BinaryOp(tok, right)
}
if err == nil {
vm.stack[vm.sp-2] = value
vm.sp--
vm.stack[vm.sp] = nil
vm.ip++
continue
}
if err == ErrInvalidOperator {
err = ErrInvalidOperator.NewError(tok.String())
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
case OpAndJump:
if vm.stack[vm.sp-1].IsFalsy() {
pos := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
vm.ip = pos - 1
continue
}
vm.stack[vm.sp-1] = nil
vm.sp--
vm.ip += 2
case OpOrJump:
if vm.stack[vm.sp-1].IsFalsy() {
vm.stack[vm.sp-1] = nil
vm.sp--
vm.ip += 2
continue
}
pos := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
vm.ip = pos - 1
case OpEqual:
left, right := vm.stack[vm.sp-2], vm.stack[vm.sp-1]
switch left := left.(type) {
case Int:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
case String:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
case Float:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
case Bool:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
case Uint:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
case Char:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
default:
vm.stack[vm.sp-2] = Bool(left.Equal(right))
}
vm.sp--
vm.stack[vm.sp] = nil
case OpNotEqual:
left, right := vm.stack[vm.sp-2], vm.stack[vm.sp-1]
switch left := left.(type) {
case Int:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
case String:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
case Float:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
case Bool:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
case Uint:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
case Char:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
default:
vm.stack[vm.sp-2] = Bool(!left.Equal(right))
}
vm.sp--
vm.stack[vm.sp] = nil
case OpTrue:
vm.stack[vm.sp] = True
vm.sp++
case OpFalse:
vm.stack[vm.sp] = False
vm.sp++
case OpCall:
err := vm.xOpCall()
if err == nil {
continue
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
case OpCallName:
err := vm.xOpCallName()
if err == nil {
continue
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
case OpReturn:
numRet := vm.curInsts[vm.ip+1]
bp := vm.curFrame.basePointer
if bp == 0 {
bp = vm.curFrame.fn.NumLocals + 1
}
if numRet == 1 {
vm.stack[bp-1] = vm.stack[vm.sp-1]
} else {
vm.stack[bp-1] = Undefined
}
for i := vm.sp - 1; i >= bp; i-- {
vm.stack[i] = nil
}
vm.sp = bp
if vm.frameIndex == 1 {
return
}
vm.clearCurrentFrame()
parent := &(vm.frames[vm.frameIndex-2])
vm.frameIndex--
vm.ip = parent.ip
vm.curFrame = parent
vm.curInsts = vm.curFrame.fn.Instructions
case OpGetBuiltin:
builtinIndex := BuiltinType(int(vm.curInsts[vm.ip+1]))
vm.stack[vm.sp] = BuiltinObjects[builtinIndex]
vm.sp++
vm.ip++
case OpClosure:
constIdx := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
fn := vm.constants[constIdx].(*CompiledFunction)
numFree := int(vm.curInsts[vm.ip+3])
free := make([]*ObjectPtr, numFree)
for i := 0; i < numFree; i++ {
switch freeVar := (vm.stack[vm.sp-numFree+i]).(type) {
case *ObjectPtr:
free[i] = freeVar
default:
temp := vm.stack[vm.sp-numFree+i]
free[i] = &ObjectPtr{
Value: &temp,
}
}
vm.stack[vm.sp-numFree+i] = nil
}
vm.sp -= numFree
newFn := &CompiledFunction{
Instructions: fn.Instructions,
NumParams: fn.NumParams,
NumLocals: fn.NumLocals,
Variadic: fn.Variadic,
SourceMap: fn.SourceMap,
Free: free,
}
vm.stack[vm.sp] = newFn
vm.sp++
vm.ip += 3
case OpJump:
vm.ip = (int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8) - 1
case OpJumpFalsy:
vm.sp--
obj := vm.stack[vm.sp]
vm.stack[vm.sp] = nil
var falsy bool
switch obj := obj.(type) {
case Bool:
falsy = obj.IsFalsy()
case Int:
falsy = obj.IsFalsy()
case Uint:
falsy = obj.IsFalsy()
case Float:
falsy = obj.IsFalsy()
case String:
falsy = obj.IsFalsy()
default:
falsy = obj.IsFalsy()
}
if falsy {
vm.ip = (int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8) - 1
continue
}
vm.ip += 2
case OpGetGlobal:
cidx := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
index := vm.constants[cidx]
var ret Object
var err error
ret, err = vm.globals.IndexGet(index)
if err != nil {
if err := vm.throwGenErr(err); err != nil {
vm.err = err
return
}
continue
}
if ret == nil {
vm.stack[vm.sp] = Undefined
} else {
vm.stack[vm.sp] = ret
}
vm.ip += 2
vm.sp++
case OpSetGlobal:
cidx := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
index := vm.constants[cidx]
value := vm.stack[vm.sp-1]
if v, ok := value.(*ObjectPtr); ok {
value = *v.Value
}
if err := vm.globals.IndexSet(index, value); err != nil {
if err := vm.throwGenErr(err); err != nil {
vm.err = err
return
}
continue
}
vm.ip += 2
vm.sp--
vm.stack[vm.sp] = nil
case OpArray:
numItems := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
arr := make(Array, numItems)
copy(arr, vm.stack[vm.sp-numItems:vm.sp])
vm.sp -= numItems
vm.stack[vm.sp] = arr
for i := vm.sp + 1; i < vm.sp+numItems+1; i++ {
vm.stack[i] = nil
}
vm.sp++
vm.ip += 2
case OpMap:
numItems := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
kv := make(Map)
for i := vm.sp - numItems; i < vm.sp; i += 2 {
key := vm.stack[i]
value := vm.stack[i+1]
kv[key.String()] = value
vm.stack[i] = nil
vm.stack[i+1] = nil
}
vm.sp -= numItems
vm.stack[vm.sp] = kv
vm.sp++
vm.ip += 2
case OpGetIndex:
numSel := int(vm.curInsts[vm.ip+1])
tp := vm.sp - 1 - numSel
target := vm.stack[tp]
value := Undefined
for ; numSel > 0; numSel-- {
ptr := vm.sp - numSel
index := vm.stack[ptr]
vm.stack[ptr] = nil
v, err := target.IndexGet(index)
if err != nil {
switch err {
case ErrNotIndexable:
err = ErrNotIndexable.NewError(target.TypeName())
case ErrIndexOutOfBounds:
err = ErrIndexOutOfBounds.NewError(index.String())
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
continue VMLoop
}
target = v
value = v
}
vm.stack[tp] = value
vm.sp = tp + 1
vm.ip++
case OpSetIndex:
value := vm.stack[vm.sp-3]
target := vm.stack[vm.sp-2]
index := vm.stack[vm.sp-1]
err := target.IndexSet(index, value)
if err != nil {
switch err {
case ErrNotIndexAssignable:
err = ErrNotIndexAssignable.NewError(target.TypeName())
case ErrIndexOutOfBounds:
err = ErrIndexOutOfBounds.NewError(index.String())
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
continue
}
vm.stack[vm.sp-3] = nil
vm.stack[vm.sp-2] = nil
vm.stack[vm.sp-1] = nil
vm.sp -= 3
case OpSliceIndex:
err := vm.xOpSliceIndex()
if err == nil {
continue
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
case OpGetFree:
freeIndex := int(vm.curInsts[vm.ip+1])
vm.stack[vm.sp] = *vm.curFrame.freeVars[freeIndex].Value
vm.sp++
vm.ip++
case OpSetFree:
freeIndex := int(vm.curInsts[vm.ip+1])
*vm.curFrame.freeVars[freeIndex].Value = vm.stack[vm.sp-1]
vm.sp--
vm.stack[vm.sp] = nil
vm.ip++
case OpGetLocalPtr:
localIndex := int(vm.curInsts[vm.ip+1])
var freeVar *ObjectPtr
value := vm.stack[vm.curFrame.basePointer+localIndex]
if obj, ok := value.(*ObjectPtr); ok {
freeVar = obj
} else {
freeVar = &ObjectPtr{Value: &value}
vm.stack[vm.curFrame.basePointer+localIndex] = freeVar
}
vm.stack[vm.sp] = freeVar
vm.sp++
vm.ip++
case OpGetFreePtr:
freeIndex := int(vm.curInsts[vm.ip+1])
value := vm.curFrame.freeVars[freeIndex]
vm.stack[vm.sp] = value
vm.sp++
vm.ip++
case OpDefineLocal:
localIndex := int(vm.curInsts[vm.ip+1])
vm.stack[vm.curFrame.basePointer+localIndex] = vm.stack[vm.sp-1]
vm.sp--
vm.stack[vm.sp] = nil
vm.ip++
case OpNull:
vm.stack[vm.sp] = Undefined
vm.sp++
case OpPop:
vm.sp--
vm.stack[vm.sp] = nil
case OpIterInit:
dst := vm.stack[vm.sp-1]
if dst.CanIterate() {
it := dst.Iterate()
vm.stack[vm.sp-1] = &iteratorObject{Iterator: it}
continue
}
var err error = ErrNotIterable.NewError(dst.TypeName())
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
case OpIterNext:
iterator := vm.stack[vm.sp-1]
hasMore := iterator.(Iterator).Next()
vm.stack[vm.sp-1] = Bool(hasMore)
case OpIterKey:
iterator := vm.stack[vm.sp-1]
val := iterator.(Iterator).Key()
vm.stack[vm.sp-1] = val
case OpIterValue:
iterator := vm.stack[vm.sp-1]
val := iterator.(Iterator).Value()
vm.stack[vm.sp-1] = val
case OpLoadModule:
cidx := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
midx := int(vm.curInsts[vm.ip+4]) | int(vm.curInsts[vm.ip+3])<<8
value := vm.modulesCache[midx]
if value == nil {
// module cache is empty, load the object from constants
vm.stack[vm.sp] = vm.constants[cidx]
vm.sp++
// load module by putting true for subsequent OpJumpFalsy
// if module is a compiledFunction it will be called and result will be stored in module cache
// if module is not a compiledFunction, copy of object will be stored in module cache
vm.stack[vm.sp] = True
vm.sp++
} else {
vm.stack[vm.sp] = value
vm.sp++
// no need to load the module, put false for subsequent OpJumpFalsy
vm.stack[vm.sp] = False
vm.sp++
}
vm.ip += 4
case OpStoreModule:
midx := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
value := vm.stack[vm.sp-1]
if v, ok := value.(Copier); ok {
// store deep copy of the module if supported
value = v.Copy()
vm.stack[vm.sp-1] = value
}
vm.modulesCache[midx] = value
vm.ip += 2
case OpSetupTry:
vm.xOpSetupTry()
case OpSetupCatch:
vm.xOpSetupCatch()
case OpSetupFinally:
vm.xOpSetupFinally()
case OpThrow:
err := vm.xOpThrow()
if err != nil {
vm.err = err
return
}
case OpFinalizer:
upto := int(vm.curInsts[vm.ip+1])
pos := vm.curFrame.errHandlers.findFinally(upto)
if pos <= 0 {
vm.ip++
continue
}
// go to finally if set
handler := vm.curFrame.errHandlers.last()
// save current ip to come back to same position
handler.returnTo = vm.ip
// save current sp to come back to same position
handler.sp = vm.sp
// remove current error if any
vm.curFrame.errHandlers.err = nil
// set ip to finally's position
vm.ip = pos - 1
case OpUnary:
err := vm.xOpUnary()
if err == nil {
continue
}
if err = vm.throwGenErr(err); err != nil {
vm.err = err
return
}
case OpNoOp:
default:
vm.err = fmt.Errorf("unknown opcode %d", vm.curInsts[vm.ip])
return
}
}
vm.err = ErrVMAborted
}
func (vm *VM) initGlobals(globals Object) {
if globals == nil {
globals = Map{}
}
vm.globals = globals
}
func (vm *VM) initLocals(args []Object) {
// init all params as undefined
numParams := vm.bytecode.Main.NumParams
locals := vm.stack[:vm.bytecode.Main.NumLocals]
// TODO (ozan): check why setting numParams fails some tests!
for i := 0; i < vm.bytecode.Main.NumLocals; i++ {
locals[i] = Undefined
}
if numParams <= 0 {
return
}
if len(args) < numParams {
if vm.bytecode.Main.Variadic {
locals[numParams-1] = Array{}
}
copy(locals, args)
return
}
if vm.bytecode.Main.Variadic {
vargs := args[numParams-1:]
arr := make(Array, 0, len(vargs))
locals[numParams-1] = append(arr, vargs...)
} else {
locals[numParams-1] = args[numParams-1]
}
copy(locals, args[:numParams-1])
}
func (vm *VM) initCurrentFrame() {
// initialize frame and pointers
vm.curInsts = vm.bytecode.Main.Instructions
vm.curFrame = &(vm.frames[0])
vm.curFrame.fn = vm.bytecode.Main
if vm.curFrame.fn.Free != nil {
// Assign free variables if exists in compiled function.
// This is required to run compiled functions returned from VM using RunCompiledFunction().
vm.curFrame.freeVars = vm.curFrame.fn.Free
}
vm.curFrame.errHandlers = nil
vm.curFrame.basePointer = 0
}
func (vm *VM) clearCurrentFrame() {
vm.curFrame.freeVars = nil
vm.curFrame.fn = nil
vm.curFrame.errHandlers = nil
}
func (vm *VM) handlePanic(r interface{}) {
if vm.sp < stackSize && vm.frameIndex <= frameSize && vm.err == nil {
if err := vm.throwGenErr(fmt.Errorf("%v", r)); err != nil {
vm.err = err
gostack := debugStack()
if vm.err != nil {
vm.err = fmt.Errorf("panic: %v %w\nGo Stack:\n%s",
r, vm.err, gostack)
}
}
return
}
gostack := debugStack()
if vm.err != nil {
vm.err = fmt.Errorf("panic: %v error: %w\nGo Stack:\n%s",
r, vm.err, gostack)
return
}
vm.err = fmt.Errorf("panic: %v\nGo Stack:\n%s", r, gostack)
}
func (vm *VM) xOpSetupTry() {
catch := int(vm.curInsts[vm.ip+2]) | int(vm.curInsts[vm.ip+1])<<8
finally := int(vm.curInsts[vm.ip+4]) | int(vm.curInsts[vm.ip+3])<<8
ptrs := errHandler{
sp: vm.sp,
catch: catch,
finally: finally,
}
if vm.curFrame.errHandlers == nil {
vm.curFrame.errHandlers = &errHandlers{
handlers: []errHandler{ptrs},
}
} else {
vm.curFrame.errHandlers.handlers = append(
vm.curFrame.errHandlers.handlers, ptrs)
}
vm.ip += 4
}
func (vm *VM) xOpSetupCatch() {
value := Undefined
errHandlers := vm.curFrame.errHandlers
if errHandlers.hasHandler() {
// set 0 to last catch position
hdl := errHandlers.last()
hdl.catch = 0
if errHandlers.err != nil {
value = errHandlers.err
errHandlers.err = nil
}
}
vm.stack[vm.sp] = value
vm.sp++
//Either OpSetLocal or OpPop is generated by compiler to handle error
}
func (vm *VM) xOpSetupFinally() {
errHandlers := vm.curFrame.errHandlers
if errHandlers.hasHandler() {
hdl := errHandlers.last()
hdl.catch = 0
hdl.finally = 0
}
}
func (vm *VM) xOpThrow() error {
op := vm.curInsts[vm.ip+1]
vm.ip++
switch op {
case 0: // system
errHandlers := vm.curFrame.errHandlers
if errHandlers.hasError() {
errHandlers.pop()
// do not put position info to error for re-throw after finally.
if err := vm.throw(errHandlers.err, true); err != nil {
return err
}
} else if pos := errHandlers.hasReturnTo(); pos > 0 {
// go to OpReturn if it is set
handler := errHandlers.last()
errHandlers.pop()
handler.returnTo = 0
if vm.sp >= handler.sp {
for i := vm.sp; i >= handler.sp; i-- {
vm.stack[i] = nil
}
}
vm.sp = handler.sp
vm.ip = pos - 1
}
case 1: // user
obj := vm.stack[vm.sp-1]
vm.stack[vm.sp-1] = nil
vm.sp--
if err := vm.throw(vm.newErrorFromObject(obj), false); err != nil {
return err
}
default:
return fmt.Errorf("wrong operand for OpThrow:%d", op)
}
return nil
}
func (vm *VM) throwGenErr(err error) error {
if e, ok := err.(*RuntimeError); ok {
if e.fileSet == nil {
e.fileSet = vm.bytecode.FileSet
}
return vm.throw(e, true)
} else if e, ok := err.(*Error); ok {
return vm.throw(vm.newError(e), false)
}
return vm.throw(vm.newErrorFromError(err), false)
}
func (vm *VM) throw(err *RuntimeError, noTrace bool) error {
if !noTrace {
err.addTrace(vm.getSourcePos())
}
// firstly check our frame has error handler
if vm.curFrame.errHandlers.hasHandler() {
return vm.handleThrownError(vm.curFrame, err)
}
// find previous frames having error handler
var frame *frame
index := vm.frameIndex - 2
for index >= 0 {
f := &(vm.frames[index])
err.addTrace(getFrameSourcePos(f))
if f.errHandlers.hasHandler() {
frame = f
break
}
f.freeVars = nil
f.fn = nil
index--
}
if frame == nil || index < 0 {
// not handled, exit
return err
}
vm.frameIndex = index + 1
if e := vm.handleThrownError(frame, err); e != nil {
return e
}
vm.curFrame = frame
vm.curFrame.fn = frame.fn
vm.curInsts = frame.fn.Instructions
return nil
}
func (vm *VM) handleThrownError(frame *frame, err *RuntimeError) error {
frame.errHandlers.err = err
handler := frame.errHandlers.last()
// if we have catch>0 goto catch else follow finally (one of them must be set)
if handler.catch > 0 {
vm.ip = handler.catch - 1
} else if handler.finally > 0 {
vm.ip = handler.finally - 1
} else {
frame.errHandlers.pop()
return vm.throw(err, false)
}
if vm.sp >= handler.sp {
for i := vm.sp; i >= handler.sp; i-- {
vm.stack[i] = nil
}
}
vm.sp = handler.sp
return nil