-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy patheval.go
More file actions
2194 lines (2004 loc) · 59.4 KB
/
eval.go
File metadata and controls
2194 lines (2004 loc) · 59.4 KB
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 2018 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Evaluate opcodes
package vm
/*
FIXME
cpython keeps a zombie frame on each code object to speed up execution
of a code object so a frame doesn't have to be allocated and
deallocated each time which seems like a good idea. If we want to
work with go routines then it might have to be more sophisticated.
FIXME could make the stack be permanently allocated and just keep a
pointer into it rather than using append etc...
If we are caching the frames need to make sure we clear the stack
objects so they can be GCed
*/
import (
"fmt"
"os"
"runtime/debug"
"strings"
"github.com/go-python/gpython/py"
)
const (
nameErrorMsg = "name '%s' is not defined"
globalNameErrorMsg = "global name '%s' is not defined"
unboundLocalErrorMsg = "local variable '%s' referenced before assignment"
unboundFreeErrorMsg = "free variable '%s' referenced before assignment in enclosing scope"
cannotCatchMsg = "catching '%s' that does not inherit from BaseException is not allowed"
)
const debugging = false
// Debug print
func debugf(format string, a ...interface{}) {
fmt.Printf(format, a...)
}
// Stack operations
func (vm *Vm) STACK_LEVEL() int { return len(vm.frame.Stack) }
func (vm *Vm) TOP() py.Object { return vm.frame.Stack[len(vm.frame.Stack)-1] }
func (vm *Vm) SECOND() py.Object { return vm.frame.Stack[len(vm.frame.Stack)-2] }
func (vm *Vm) THIRD() py.Object { return vm.frame.Stack[len(vm.frame.Stack)-3] }
func (vm *Vm) FOURTH() py.Object { return vm.frame.Stack[len(vm.frame.Stack)-4] }
func (vm *Vm) PEEK(n int) py.Object { return vm.frame.Stack[len(vm.frame.Stack)-n] }
func (vm *Vm) SET_TOP(v py.Object) { vm.frame.Stack[len(vm.frame.Stack)-1] = v }
func (vm *Vm) SET_SECOND(v py.Object) { vm.frame.Stack[len(vm.frame.Stack)-2] = v }
func (vm *Vm) SET_THIRD(v py.Object) { vm.frame.Stack[len(vm.frame.Stack)-3] = v }
func (vm *Vm) SET_FOURTH(v py.Object) { vm.frame.Stack[len(vm.frame.Stack)-4] = v }
func (vm *Vm) SET_VALUE(n int, v py.Object) { vm.frame.Stack[len(vm.frame.Stack)-(n)] = (v) }
func (vm *Vm) DROP() { vm.frame.Stack = vm.frame.Stack[:len(vm.frame.Stack)-1] }
func (vm *Vm) DROPN(n int) { vm.frame.Stack = vm.frame.Stack[:len(vm.frame.Stack)-n] }
// Pop from top of vm stack
func (vm *Vm) POP() py.Object {
// FIXME what if empty?
out := vm.frame.Stack[len(vm.frame.Stack)-1]
vm.frame.Stack = vm.frame.Stack[:len(vm.frame.Stack)-1]
return out
}
// Push to top of vm stack
func (vm *Vm) PUSH(obj py.Object) {
vm.frame.Stack = append(vm.frame.Stack, obj)
}
// Push items to top of vm stack
func (vm *Vm) EXTEND(items py.Tuple) {
vm.frame.Stack = append(vm.frame.Stack, items...)
}
// Push items to top of vm stack in reverse order
func (vm *Vm) EXTEND_REVERSED(items py.Tuple) {
start := len(vm.frame.Stack)
vm.frame.Stack = append(vm.frame.Stack, items...)
py.Tuple(vm.frame.Stack[start:]).Reverse()
}
// Adds a traceback to the exc passed in for the current vm state
func (vm *Vm) AddTraceback(exc *py.ExceptionInfo) {
exc.Traceback = &py.Traceback{
Next: exc.Traceback,
Frame: vm.frame,
Lasti: vm.frame.Lasti,
Lineno: vm.frame.Code.Addr2Line(vm.frame.Lasti),
}
}
// Set an exception in the VM
//
// The exception must be a valid exception instance (eg as returned by
// py.MakeException)
//
// It sets vm.curexc.* and sets vm.why to whyException
func (vm *Vm) SetException(exception py.Object) {
vm.curexc.Value = exception
vm.curexc.Type = exception.Type()
vm.curexc.Traceback = nil
vm.AddTraceback(&vm.curexc)
vm.why = whyException
}
// Check for an exception (panic)
//
// Should be called with the result of recover
func (vm *Vm) CheckExceptionRecover(r interface{}) {
// If what was raised was an ExceptionInfo the stuff this into the current vm
if exc, ok := r.(py.ExceptionInfo); ok {
vm.curexc = exc
vm.AddTraceback(&vm.curexc)
vm.why = whyException
if debugging {
debugf("*** Propagating exception: %s\n", exc.Error())
}
} else {
// Coerce whatever was raised into a *Exception
vm.SetException(py.MakeException(r))
if debugging {
debugf("*** Exception raised %v\n", r)
debug.PrintStack()
}
}
}
// Check for an exception (panic)
//
// Must be called as a defer function
func (vm *Vm) CheckException() {
if r := recover(); r != nil {
if debugging {
debugf("*** Panic recovered %v\n", r)
}
vm.CheckExceptionRecover(r)
}
}
// Illegal instruction
func do_ILLEGAL(vm *Vm, arg int32) error {
return py.ExceptionNewf(py.SystemError, "Illegal opcode")
}
// Do nothing code. Used as a placeholder by the bytecode optimizer.
func do_NOP(vm *Vm, arg int32) error {
return nil
}
// Removes the top-of-stack (TOS) item.
func do_POP_TOP(vm *Vm, arg int32) error {
vm.DROPN(1)
return nil
}
// Swaps the two top-most stack items.
func do_ROT_TWO(vm *Vm, arg int32) error {
top := vm.TOP()
second := vm.SECOND()
vm.SET_TOP(second)
vm.SET_SECOND(top)
return nil
}
// Lifts second and third stack item one position up, moves top down
// to position three.
func do_ROT_THREE(vm *Vm, arg int32) error {
top := vm.TOP()
second := vm.SECOND()
third := vm.THIRD()
vm.SET_TOP(second)
vm.SET_SECOND(third)
vm.SET_THIRD(top)
return nil
}
// Duplicates the reference on top of the stack.
func do_DUP_TOP(vm *Vm, arg int32) error {
vm.PUSH(vm.TOP())
return nil
}
// Duplicates the top two reference on top of the stack.
func do_DUP_TOP_TWO(vm *Vm, arg int32) error {
top := vm.TOP()
second := vm.SECOND()
vm.PUSH(second)
vm.PUSH(top)
return nil
}
// Unary Operations take the top of the stack, apply the operation,
// and push the result back on the stack.
// Set the Top and return the error
func (vm *Vm) setTopAndCheckErr(obj py.Object, err error) error {
if err == nil {
vm.SET_TOP(obj)
}
return err
}
// Implements TOS = +TOS.
func do_UNARY_POSITIVE(vm *Vm, arg int32) error {
return vm.setTopAndCheckErr(py.Pos(vm.TOP()))
}
// Implements TOS = -TOS.
func do_UNARY_NEGATIVE(vm *Vm, arg int32) error {
return vm.setTopAndCheckErr(py.Neg(vm.TOP()))
}
// Implements TOS = not TOS.
func do_UNARY_NOT(vm *Vm, arg int32) error {
return vm.setTopAndCheckErr(py.Not(vm.TOP()))
}
// Implements TOS = ~TOS.
func do_UNARY_INVERT(vm *Vm, arg int32) error {
return vm.setTopAndCheckErr(py.Invert(vm.TOP()))
}
// Implements TOS = iter(TOS).
func do_GET_ITER(vm *Vm, arg int32) error {
return vm.setTopAndCheckErr(py.Iter(vm.TOP()))
}
// Binary operations remove the top of the stack (TOS) and the second
// top-most stack item (TOS1) from the stack. They perform the
// operation, and put the result back on the stack.
// Implements TOS = TOS1 ** TOS.
func do_BINARY_POWER(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Pow(a, b, py.None))
}
// Implements TOS = TOS1 * TOS.
func do_BINARY_MULTIPLY(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Mul(a, b))
}
// Implements TOS = TOS1 // TOS.
func do_BINARY_FLOOR_DIVIDE(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.FloorDiv(a, b))
}
// Implements TOS = TOS1 / TOS when from __future__ import division is
// in effect.
func do_BINARY_TRUE_DIVIDE(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.TrueDiv(a, b))
}
// Implements TOS = TOS1 % TOS.
func do_BINARY_MODULO(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Mod(a, b))
}
// Implements TOS = TOS1 + TOS.
func do_BINARY_ADD(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Add(a, b))
}
// Implements TOS = TOS1 - TOS.
func do_BINARY_SUBTRACT(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Sub(a, b))
}
// Implements TOS = TOS1[TOS].
func do_BINARY_SUBSCR(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.GetItem(a, b))
}
// Implements TOS = TOS1 << TOS.
func do_BINARY_LSHIFT(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Lshift(a, b))
}
// Implements TOS = TOS1 >> TOS.
func do_BINARY_RSHIFT(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Rshift(a, b))
}
// Implements TOS = TOS1 & TOS.
func do_BINARY_AND(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.And(a, b))
}
// Implements TOS = TOS1 ^ TOS.
func do_BINARY_XOR(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Xor(a, b))
}
// Implements TOS = TOS1 | TOS.
func do_BINARY_OR(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Or(a, b))
}
// In-place operations are like binary operations, in that they remove
// TOS and TOS1, and push the result back on the stack, but the
// operation is done in-place when TOS1 supports it, and the resulting
// TOS may be (but does not have to be) the original TOS1.
// Implements in-place TOS = TOS1 ** TOS.
func do_INPLACE_POWER(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IPow(a, b, py.None))
}
// Implements in-place TOS = TOS1 * TOS.
func do_INPLACE_MULTIPLY(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IMul(a, b))
}
// Implements in-place TOS = TOS1 // TOS.
func do_INPLACE_FLOOR_DIVIDE(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IFloorDiv(a, b))
}
// Implements in-place TOS = TOS1 / TOS when from __future__ import
// division is in effect.
func do_INPLACE_TRUE_DIVIDE(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.ITrueDiv(a, b))
}
// Implements in-place TOS = TOS1 % TOS.
func do_INPLACE_MODULO(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.Mod(a, b))
}
// Implements in-place TOS = TOS1 + TOS.
func do_INPLACE_ADD(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IAdd(a, b))
}
// Implements in-place TOS = TOS1 - TOS.
func do_INPLACE_SUBTRACT(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.ISub(a, b))
}
// Implements in-place TOS = TOS1 << TOS.
func do_INPLACE_LSHIFT(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.ILshift(a, b))
}
// Implements in-place TOS = TOS1 >> TOS.
func do_INPLACE_RSHIFT(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IRshift(a, b))
}
// Implements in-place TOS = TOS1 & TOS.
func do_INPLACE_AND(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IAnd(a, b))
}
// Implements in-place TOS = TOS1 ^ TOS.
func do_INPLACE_XOR(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IXor(a, b))
}
// Implements in-place TOS = TOS1 | TOS.
func do_INPLACE_OR(vm *Vm, arg int32) error {
b := vm.POP()
a := vm.TOP()
return vm.setTopAndCheckErr(py.IOr(a, b))
}
// Implements TOS1[TOS] = TOS2.
func do_STORE_SUBSCR(vm *Vm, arg int32) error {
w := vm.TOP()
v := vm.SECOND()
u := vm.THIRD()
vm.DROPN(3)
// v[w] = u
_, err := py.SetItem(v, w, u)
if err != nil {
return err
}
return nil
}
// Implements del TOS1[TOS].
func do_DELETE_SUBSCR(vm *Vm, arg int32) error {
sub := vm.TOP()
container := vm.SECOND()
vm.DROPN(2)
/* del v[w] */
_, err := py.DelItem(container, sub)
if err != nil {
return err
}
return nil
}
// Miscellaneous opcodes.
// PrintExpr controls where the output of PRINT_EXPR goes which is
// used in the REPL
var PrintExpr = func(out string) {
_, _ = os.Stdout.WriteString(out + "\n")
}
// Implements the expression statement for the interactive mode. TOS
// is removed from the stack and printed. In non-interactive mode, an
// expression statement is terminated with POP_STACK.
func do_PRINT_EXPR(vm *Vm, arg int32) error {
// FIXME this should be calling sys.displayhook
// Print value except if None
// After printing, also assign to '_'
// Before, set '_' to None to avoid recursion
value := vm.POP()
vm.frame.Globals["_"] = py.None
if value != py.None {
repr, err := py.Repr(value)
if err != nil {
return err
}
PrintExpr(fmt.Sprint(repr))
}
vm.frame.Globals["_"] = value
return nil
}
// Terminates a loop due to a break statement.
func do_BREAK_LOOP(vm *Vm, arg int32) error {
vm.why = whyBreak
return nil
}
// Continues a loop due to a continue statement. target is the address
// to jump to (which should be a FOR_ITER instruction).
func do_CONTINUE_LOOP(vm *Vm, target int32) error {
vm.retval = py.Int(target)
vm.why = whyContinue
return nil
}
// Iterate v argcnt times and store the results on the stack (via decreasing
// sp). Return 1 for success, 0 if error.
//
// If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
// with a variable target.
func unpack_iterable(vm *Vm, v py.Object, argcnt int, argcntafter int, sp int) error {
it, err := py.Iter(v)
if err != nil {
return err
}
i := 0
for i = 0; i < argcnt; i++ {
w, err := py.Next(it)
if err != nil {
/* Iterator done, via error or exhaustion. */
return py.ExceptionNewf(py.ValueError, "need more than %d value(s) to unpack", i)
}
sp--
vm.frame.Stack[sp] = w
}
if argcntafter == -1 {
/* We better have exhausted the iterator now. */
_, finished := py.Next(it)
if finished != nil {
return nil
}
return py.ExceptionNewf(py.ValueError, "too many values to unpack (expected %d)", argcnt)
}
l, err := py.SequenceList(it)
if err != nil {
return err
}
sp--
vm.frame.Stack[sp] = l
i++
ll := l.Len()
if ll < argcntafter {
return py.ExceptionNewf(py.ValueError, "need more than %d values to unpack", argcnt+ll)
}
/* Pop the "after-variable" args off the list. */
for j := argcntafter; j > 0; j-- {
sp--
vm.frame.Stack[sp], err = l.M__getitem__(py.Int(ll - j))
if err != nil {
return err
}
}
/* Resize the list. */
l.Resize(ll - argcntafter)
return nil
}
// Implements assignment with a starred target: Unpacks an iterable in
// TOS into individual values, where the total number of values can be
// smaller than the number of items in the iterable: one the new
// values will be a list of all leftover items.
//
// The low byte of counts is the number of values before the list
// value, the high byte of counts the number of values after it. The
// resulting values are put onto the stack right-to-left.
func do_UNPACK_EX(vm *Vm, counts int32) error {
before := int(counts & 0xFF)
after := int(counts >> 8)
totalargs := 1 + before + after
seq := vm.POP()
sp := vm.STACK_LEVEL()
vm.EXTEND(make([]py.Object, totalargs))
return unpack_iterable(vm, seq, before, after, sp+totalargs)
}
// Calls set.add(TOS1[-i], TOS). Used to implement set comprehensions.
func do_SET_ADD(vm *Vm, i int32) error {
w := vm.POP()
v := vm.PEEK(int(i))
v.(*py.Set).Add(w)
return nil
}
// Calls list.append(TOS[-i], TOS). Used to implement list
// comprehensions. While the appended value is popped off, the list
// object remains on the stack so that it is available for further
// iterations of the loop.
func do_LIST_APPEND(vm *Vm, i int32) error {
w := vm.POP()
v := vm.PEEK(int(i))
v.(*py.List).Append(w)
return nil
}
// Calls dict.setitem(TOS1[-i], TOS, TOS1). Used to implement dict comprehensions.
func do_MAP_ADD(vm *Vm, i int32) error {
key := vm.TOP()
value := vm.SECOND()
vm.DROPN(2)
dictObj := vm.PEEK(int(i))
dict, err := py.DictCheckExact(dictObj)
if err != nil {
return err
}
_, err = dict.M__setitem__(key, value)
return err
}
// Returns with TOS to the caller of the function.
func do_RETURN_VALUE(vm *Vm, arg int32) error {
vm.retval = vm.POP()
vm.frame.Yielded = false
vm.why = whyReturn
return nil
}
// Pops TOS and delegates to it as a subiterator from a generator.
func do_YIELD_FROM(vm *Vm, arg int32) error {
var retval py.Object
var err error
u := vm.POP()
x := vm.TOP()
// send u to x
if u == py.None {
retval, err = py.Next(x)
} else {
retval, err = py.Send(x, u)
}
if err != nil {
if !py.IsException(py.StopIteration, err) {
return err
}
return nil
}
// x remains on stack, retval is value to be yielded
// FIXME vm.frame.Stacktop = stack_pointer
//why = whyYield
// and repeat...
vm.frame.Lasti--
vm.retval = retval
vm.frame.Yielded = true
vm.why = whyYield
return nil
}
// Pops TOS and yields it from a generator.
func do_YIELD_VALUE(vm *Vm, arg int32) error {
vm.retval = vm.POP()
vm.frame.Yielded = true
vm.why = whyYield
return nil
}
// Loads all symbols not starting with '_' directly from the module
// TOS to the local namespace. The module is popped after loading all
// names. This opcode implements from module import *.
func do_IMPORT_STAR(vm *Vm, arg int32) error {
vm.frame.FastToLocals()
from := vm.POP()
module := from.(*py.Module)
if all, ok := module.Globals["__all__"]; ok {
var loopErr error
iterErr := py.Iterate(all, func(item py.Object) bool {
name, err := py.AttributeName(item)
if err != nil {
loopErr = err
return true
}
vm.frame.Locals[name], err = py.GetAttrString(module, name)
if err != nil {
loopErr = err
return true
}
return false
})
if iterErr != nil {
return iterErr
}
if loopErr != nil {
return loopErr
}
} else {
for name, value := range module.Globals {
if !strings.HasPrefix(name, "_") {
vm.frame.Locals[name] = value
}
}
}
vm.frame.LocalsToFast(false)
return nil
}
// Removes one block from the block stack. Per frame, there is a stack
// of blocks, denoting nested loops, try statements, and such.
func do_POP_BLOCK(vm *Vm, arg int32) error {
vm.frame.PopBlock()
return nil
}
// Removes one block from the block stack. The popped block must be an
// exception handler block, as implicitly created when entering an
// except handler. In addition to popping extraneous values from the
// frame stack, the last three popped values are used to restore the
// exception state.
func do_POP_EXCEPT(vm *Vm, arg int32) error {
frame := vm.frame
b := vm.frame.Block
frame.PopBlock()
if b.Type != py.TryBlockExceptHandler {
return py.ExceptionNewf(py.SystemError, "popped block is not an except handler")
} else {
vm.UnwindExceptHandler(frame, b)
}
return nil
}
// Terminates a finally clause. The interpreter recalls whether the
// exception has to be re-raised, or whether the function returns, and
// continues with the outer-next block.
func do_END_FINALLY(vm *Vm, arg int32) error {
v := vm.POP()
if debugging {
debugf("END_FINALLY v=%#v\n", v)
}
if v == py.None {
// None exception
if debugging {
debugf(" END_FINALLY: None\n")
}
} else if vInt, ok := v.(py.Int); ok {
vm.why = vmStatus(vInt)
if debugging {
debugf(" END_FINALLY: Int %v\n", vm.why)
}
switch vm.why {
case whyYield:
panic("vm: Unexpected whyYield in END_FINALLY")
case whyException:
panic("vm: Unexpected whyException in END_FINALLY")
case whyReturn, whyContinue:
vm.retval = vm.POP()
case whySilenced:
// An exception was silenced by 'with', we must
// manually unwind the EXCEPT_HANDLER block which was
// created when the exception was caught, otherwise
// the stack will be in an inconsistent state.
frame := vm.frame
b := vm.frame.Block
frame.PopBlock()
if b.Type != py.TryBlockExceptHandler {
panic("vm: Expecting EXCEPT_HANDLER in END_FINALLY")
}
vm.UnwindExceptHandler(frame, b)
vm.why = whyNot
}
} else if py.ExceptionClassCheck(v) {
w := vm.POP()
u := vm.POP()
if debugging {
debugf(" END_FINALLY: Exc %v, Type %v, Traceback %v\n", v, w, u)
}
// FIXME PyErr_Restore(v, w, u)
vm.curexc.Type, _ = v.(*py.Type)
vm.curexc.Value = w
vm.curexc.Traceback, _ = u.(*py.Traceback)
vm.why = whyException
} else {
return py.ExceptionNewf(py.SystemError, "'finally' pops bad exception %#v", v)
}
if debugging {
debugf("END_FINALLY: vm.why = %v\n", vm.why)
}
return nil
}
// Loads the __build_class__ helper function to the stack which
// creates a new class object.
func do_LOAD_BUILD_CLASS(vm *Vm, arg int32) error {
vm.PUSH(vm.context.Store().Builtins.Globals["__build_class__"])
return nil
}
// This opcode performs several operations before a with block
// starts. First, it loads __exit__( ) from the context manager and
// pushes it onto the stack for later use by WITH_CLEANUP. Then,
// __enter__( ) is called, and a finally block pointing to delta is
// pushed. Finally, the result of calling the enter method is pushed
// onto the stack. The next opcode will either ignore it (POP_TOP), or
// store it in (a) variable(s) (STORE_FAST, STORE_NAME, or
// UNPACK_SEQUENCE).
func do_SETUP_WITH(vm *Vm, delta int32) error {
mgr := vm.TOP()
// exit := py.ObjectLookupSpecial(mgr, "__exit__")
exit, err := py.GetAttrString(mgr, "__exit__")
if err != nil {
return err
}
vm.SET_TOP(exit)
// enter := py.ObjectLookupSpecial(mgr, "__enter__")
enter, err := py.GetAttrString(mgr, "__enter__")
if err != nil {
return err
}
res, err := py.Call(enter, nil, nil) // FIXME method for this?
if err != nil {
return err
}
// Setup the finally block before pushing the result of __enter__ on the stack.
vm.frame.PushBlock(py.TryBlockSetupFinally, vm.frame.Lasti+delta, vm.STACK_LEVEL())
vm.PUSH(res)
return nil
}
// Cleans up the stack when a with statement block exits. On top of
// the stack are 1–3 values indicating how/why the finally clause was
// entered:
//
// TOP = None
// (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
// TOP = WHY_*; no retval below it
// (TOP, SECOND, THIRD) = exc_info( )
// Under them is EXIT, the context manager’s __exit__( ) bound method.
//
// In the last case, EXIT(TOP, SECOND, THIRD) is called, otherwise
// EXIT(None, None, None).
//
// EXIT is removed from the stack, leaving the values above it in the
// same order. In addition, if the stack represents an exception, and
// the function call returns a ‘true’ value, this information is
// “zapped”, to prevent END_FINALLY from re-raising the
// exception. (But non-local gotos should still be resumed.)
func do_WITH_CLEANUP(vm *Vm, arg int32) error {
var exit_func py.Object
exc := vm.TOP()
var val py.Object = py.None
var tb py.Object = py.None
if exc == py.None {
vm.DROP()
exit_func = vm.TOP()
vm.SET_TOP(exc)
} else if excInt, ok := exc.(py.Int); ok {
vm.DROP()
switch vmStatus(excInt) {
case whyReturn, whyContinue:
/* Retval in TOP. */
exit_func = vm.SECOND()
vm.SET_SECOND(vm.TOP())
vm.SET_TOP(exc)
default:
exit_func = vm.TOP()
vm.SET_TOP(exc)
}
exc = py.None
} else {
val = vm.SECOND()
tb = vm.THIRD()
tp2 := vm.FOURTH()
exc2 := vm.PEEK(5)
tb2 := vm.PEEK(6)
exit_func = vm.PEEK(7)
vm.SET_VALUE(7, tb2)
vm.SET_VALUE(6, exc2)
vm.SET_VALUE(5, tp2)
/* UNWIND_EXCEPT_HANDLER will pop this off. */
vm.SET_FOURTH(nil)
/* We just shifted the stack down, so we have
to tell the except handler block that the
values are lower than it expects. */
block := vm.frame.Block
if block.Type != py.TryBlockExceptHandler {
panic("vm: WITH_CLEANUP expecting TryBlockExceptHandler")
}
block.Level--
}
/* XXX Not the fastest way to call it... */
res, err := py.Call(exit_func, []py.Object{exc, val, tb}, nil)
if err != nil {
return err
}
wasErr := false
if exc != py.None {
wasErr = res == py.True
}
if wasErr {
/* There was an exception and a True return */
vm.PUSH(py.Int(whySilenced))
}
return nil
}
// All of the following opcodes expect arguments. An argument is two bytes, with the more significant byte last.
// Implements name = TOS. namei is the index of name in the attribute
// co_names of the code object. The compiler tries to use STORE_FAST
// or STORE_GLOBAL if possible.
func do_STORE_NAME(vm *Vm, namei int32) error {
if debugging {
debugf("STORE_NAME %v\n", vm.frame.Code.Names[namei])
}
vm.frame.Locals[vm.frame.Code.Names[namei]] = vm.POP()
return nil
}
// Implements del name, where namei is the index into co_names
// attribute of the code object.
func do_DELETE_NAME(vm *Vm, namei int32) error {
name := vm.frame.Code.Names[namei]
if _, ok := vm.frame.Locals[name]; !ok {
return py.ExceptionNewf(py.NameError, nameErrorMsg, name)
} else {
delete(vm.frame.Locals, name)
}
return nil
}
// Unpacks TOS into count individual values, which are put onto the
// stack right-to-left.
func do_UNPACK_SEQUENCE(vm *Vm, count int32) error {
it := vm.POP()
args := int(count)
if tuple, ok := it.(py.Tuple); ok && len(tuple) == args {
vm.EXTEND_REVERSED(tuple)
} else if list, ok := it.(*py.List); ok && list.Len() == args {
vm.EXTEND_REVERSED(list.Items)
} else {
sp := vm.STACK_LEVEL()
vm.EXTEND(make([]py.Object, args))
return unpack_iterable(vm, it, args, -1, sp+args)
}
return nil
}
// Implements TOS.name = TOS1, where namei is the index of name in
// co_names.
func do_STORE_ATTR(vm *Vm, namei int32) error {
w := vm.frame.Code.Names[namei]
v := vm.TOP()
u := vm.SECOND()
vm.DROPN(2)
_, err := py.SetAttrString(v, w, u) /* v.w = u */
if err != nil {
return err
}
return nil
}
// Implements del TOS.name, using namei as index into co_names.
func do_DELETE_ATTR(vm *Vm, namei int32) error {
return py.DeleteAttrString(vm.POP(), vm.frame.Code.Names[namei])
}
// Works as STORE_NAME, but stores the name as a global.
func do_STORE_GLOBAL(vm *Vm, namei int32) error {
vm.frame.Globals[vm.frame.Code.Names[namei]] = vm.POP()
return nil
}
// Works as DELETE_NAME, but deletes a global name.
func do_DELETE_GLOBAL(vm *Vm, namei int32) error {
name := vm.frame.Code.Names[namei]
if _, ok := vm.frame.Globals[name]; !ok {
return py.ExceptionNewf(py.NameError, nameErrorMsg, name)
} else {
delete(vm.frame.Globals, name)
}
return nil
}
// Pushes co_consts[consti] onto the stack.
func do_LOAD_CONST(vm *Vm, consti int32) error {
vm.PUSH(vm.frame.Code.Consts[consti])
// if debugging { debugf("LOAD_CONST %v\n", vm.TOP()) }
return nil
}
// Pushes the value associated with co_names[namei] onto the stack.
func do_LOAD_NAME(vm *Vm, namei int32) error {
name := vm.frame.Code.Names[namei]
if debugging {
debugf("LOAD_NAME %v\n", name)
}
obj, ok := vm.frame.Lookup(name)
if !ok {
return py.ExceptionNewf(py.NameError, nameErrorMsg, name)
} else {
vm.PUSH(obj)
}
return nil
}
// Creates a tuple consuming count items from the stack, and pushes
// the resulting tuple onto the stack.
func do_BUILD_TUPLE(vm *Vm, count int32) error {
tuple := make(py.Tuple, count)
copy(tuple, vm.frame.Stack[len(vm.frame.Stack)-int(count):])
vm.DROPN(int(count))
vm.PUSH(tuple)
return nil
}
// Works as BUILD_TUPLE, but creates a set.
func do_BUILD_SET(vm *Vm, count int32) error {
set := py.NewSetFromItems(vm.frame.Stack[len(vm.frame.Stack)-int(count):])
vm.DROPN(int(count))
vm.PUSH(set)
return nil
}