-
Notifications
You must be signed in to change notification settings - Fork 6
/
vm.py
1227 lines (965 loc) · 31.9 KB
/
vm.py
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
# -*- coding: utf-8 -*-
import dis, inspect, types, operator
import sys, re
import logging
import six
import collections
CATCH = True
LOGGING_LEVEL=logging.INFO
LOGGING_LEVEL=logging.ERROR
logging.basicConfig(stream=sys.stderr, level=LOGGING_LEVEL, format='%(message)s')
class VirtualMachineError(Exception):
pass
class Frame(object):
def __init__(self, f_code, f_globals, f_locals, f_back):
self.f_code = f_code
self.f_globals = f_globals
self.f_locals = f_locals
self.f_back = f_back
if hasattr(__builtins__, '__dict__'):
self.f_builtins = __builtins__.__dict__
else:
self.f_builtins = __builtins__
self.stack = []
self.last_instr = 0
self.running = True
#refactor
self.f_lasti = 0
self.generator = None
self.block_stack = []
if f_code.co_cellvars:
self.cells = {}
for var in f_code.co_cellvars:
cell = self.f_locals.get(var)
self.cells[var] = cell
else:
self.cells = None
if f_code.co_freevars:
if not self.cells:
self.cells = {}
for var in f_code.co_freevars:
self.cells[var] = self.f_locals.get(var)
def update_env(self, env):
self.f_locals.update(env)
Block = collections.namedtuple("Block", "type, handler, level")
def make_cell(value):
fn = (lambda x: lambda: x)(value)
return fn.func_closure[0]
class Function(object):
def __init__(self, code, defaults, closure, vm):
self.func_code = code
self.func_name = self.__name__ = code.co_name
self.func_defaults = defaults
self.func_closure = closure
self._vm = vm
if closure:
closure = tuple(make_cell(i) for i in closure)
self._func = types.FunctionType(code, vm.frame.f_globals,
argdefs=tuple(defaults),
closure=closure)
def __call__(self, *args, **kwargs):
if self.func_name in ["<setcomp>", "<dictcomp>", "<genexpr>"]:
# http://bugs.python.org/issue19611
assert len(args) == 1 and not kwargs, "Surprising comprehension!"
callargs = {".0": args[0]}
else:
callargs = inspect.getcallargs(self._func, *args, **kwargs)
for i, x in enumerate(self.func_code.co_freevars):
callargs[x] = self.func_closure[i]
frame = self._vm.make_frame(self.func_code,callargs)
CO_GENERATOR = 32
if self.func_code.co_flags & CO_GENERATOR:
gen = Generator(frame, self._vm)
frame.generator = gen
r = gen
else:
r = self._vm.run_frame(frame)
return r
def __get__(self, instance, owner):
if instance is not None:
return Method(instance, owner, self)
return Method(None, owner, self)
class Method(object):
def __init__(self, obj, _class, func):
self.im_self = obj
self.im_class = _class
self.im_func = func
def __repr__(self):
name = "%s.%s" % (self.im_class.__name__, self.im_func.func_name)
if self.im_self is not None:
return '<Bound Method %s of %s>' % (name, self.im_self)
else:
return '<Unbound Method %s>' % (name,)
def __call__(self, *args, **kwargs):
if self.im_self is not None:
return self.im_func(self.im_self, *args, **kwargs)
else:
return self.im_func(*args, **kwargs)
class Generator(object):
def __init__(self, g_frame, vm):
self.gi_frame = g_frame
self.vm = vm
self.started = False
self.finished = False
def __iter__(self):
return self
def next(self):
return self.send(None)
def send(self, value=None):
if not self.started and value is not None:
raise TypeError("Can't send non-None value to a just-started generator")
self.gi_frame.stack.append(value)
self.started = True
val = self.vm.resume_frame(self.gi_frame)
if self.finished:
raise StopIteration(val)
return val
#nil = object()
class nil(object):
pass
class VirtualMachine(object):
HAVE_ARGUMENT = 90
def __init__(self):
self._reset()
self.table = lambda x : x
def _reset(self):
self.jump = False
self.result = None
self.frames = []
self.frame = None
#refactor
self.return_value = None
self.last_exception = None
def run_code(self, code):
frame = self.make_frame(code)
val = self.run_frame(frame)
if self.frames:
raise VirtualMachineError("Frames left over!")
if self.frame and self.frame.stack:
raise VirtualMachineError("Data left on stack! %r" % self.frame.stack)
return val
def resume_frame(self, frame):
frame.f_back = self.frame
val = self.run_frame(frame)
frame.f_back = None
return val
def run_frame(self, frame):
self.push_frame(frame)
while True:
logging.info(str(frame.stack))
logging.info(str(frame.block_stack))
byteName, arguments, opoffset = self.parse_byte()
why = self.dispatch(byteName, arguments)
if why == 'return':
break
if why == 'reraise':
why = 'exception'
if why != 'yield':
if why and frame.block_stack:
why = self.manage_block_stack(why)
if why:
break
self.pop_frame()
if why == 'exception':
# print>>sys.stderr, self.last_exception
# 交给上层frame处理异常
six.reraise(*self.last_exception)
return self.return_value
def push_block(self, type, handler=None, level=None):
if level is None:
level = len(self.frame.stack)
self.frame.block_stack.append(Block(type, handler, level))
def pop_block(self):
return self.frame.block_stack.pop()
def manage_block_stack(self, why):
logging.info("enter manager")
block = self.frame.block_stack[-1]
if block.type == 'loop' and why == 'continue':
self.frame.f_lasti = self.return_value
why = None
return why
block = self.pop_block()
if block.type == 'loop' and why == 'break':
logging.info("for loop break")
why = None
self.frame.f_lasti = block.handler
return why
if block.type == 'except':
if why == 'exception':
logging.info("for excepting")
exctype, value, tb = self.last_exception
self.push(tb, value, exctype)
why = None
self.frame.f_lasti = block.handler
return why
if why == 'continue':
self.frame.f_lasti = self.return_value
why = None
return why
if block.type == 'finally':
if why == 'exception':
exctype, value, tb = self.last_exception
self.push(tb, value, exctype)
if why == 'continue':
self.push(self.return_value)
self.push(why)
why = None
self.frame.f_lasti = block.handler
return why
def parse_byte(self):
f = self.frame
opoffset = f.f_lasti
byteCode = ord(f.f_code.co_code[opoffset])
f.f_lasti += 1
byteName = dis.opname[byteCode]
arg = None
arguments = []
if byteCode >= dis.HAVE_ARGUMENT:
arg = f.f_code.co_code[f.f_lasti:f.f_lasti+2]
f.f_lasti += 2
intArg = ord(arg[0]) + (ord(arg[1]) << 8)
if byteCode in dis.hasconst:
arg = f.f_code.co_consts[intArg]
elif byteCode in dis.hasfree:
if intArg < len(f.f_code.co_cellvars):
arg = f.f_code.co_cellvars[intArg]
else:
var_idx = intArg - len(f.f_code.co_cellvars)
arg = f.f_code.co_freevars[var_idx]
elif byteCode in dis.hasname:
arg = f.f_code.co_names[intArg]
elif byteCode in dis.hasjrel:
arg = f.f_lasti + intArg
elif byteCode in dis.hasjabs:
arg = intArg
elif byteCode in dis.haslocal:
arg = f.f_code.co_varnames[intArg]
else:
arg = intArg
arguments = [arg]
return byteName, arguments, opoffset
def dispatch(self, byteName, arguments):
logging.info(byteName + " " + str(arguments) + '\n')
byteName = byteName.replace('+','')
why = None
if CATCH:
try:
bytecode_fn = getattr(self, byteName, None)
if not bytecode_fn:
raise VirtualMachineError(
"unknown bytecode type: %s" % byteName
)
why = bytecode_fn(*arguments)
except:
self.last_exception = sys.exc_info()[:2] + (None,)
why = 'exception'
else:
bytecode_fn = getattr(self, byteName, None)
if not bytecode_fn:
raise VirtualMachineError(
"unknown bytecode type: %s" % byteName
)
why = bytecode_fn(*arguments)
return why
def _get_exec(self, code):
self.frame.byte_to_instr = {}
what_to_exec = {
"instructions":[],
"constants": code.co_consts,
"names": code.co_names,
}
byte_codes = [ord(c) for c in code.co_code]
i = j = 0
while i < len(byte_codes):
self.frame.byte_to_instr[i] = j
byte_code = byte_codes[i]
name = dis.opname[byte_code]
if byte_code >= self.HAVE_ARGUMENT:
arg = (byte_codes[i+2] << 8) + byte_codes[i+1]
i += 2
else:
arg = None
what_to_exec["instructions"].append((dis.opname[byte_code], arg))
i += 1
j += 1
self.frame.instr_to_byte = dict(zip(self.frame.byte_to_instr.values(),
self.frame.byte_to_instr.keys()))
return what_to_exec
def _parse_argument(self, instr, arg, what_to_exec):
if arg is None:
return nil
byte_code = dis.opmap[instr]
if byte_code in dis.hasconst:
return what_to_exec['constants'][arg]
elif byte_code in dis.hasname:
return what_to_exec['names'][arg]
else:
return arg
def make_frame(self, code, callargs={}, f_globals=None, f_locals=None):
if f_globals is not None:
f_globals = f_globals
if f_locals is None:
f_locals = f_globals
elif self.frames:
f_globals = self.frame.f_globals
self.local_env = f_locals = {}
else:
self.env = f_globals = f_locals = {
'__builtins__': __builtins__,
'__name__': '__main__',
'__doc__': None,
'__package__': None,
}
f_locals.update(callargs)
frame = Frame(code, f_globals, f_locals, self.frame)
return frame
def push_frame(self, frame):
logging.debug('push frame')
self.frames.append(self.frame)
self.frame = frame
def pop_frame(self):
logging.debug('pop frame')
self.frame = self.frames.pop()
def pop(self, i=0):
"""Pop a value from the stack.
Default to the top of the stack, but `i` can be a count from the top
instead.
"""
return self.frame.stack.pop(-1-i)
def push(self, *vals):
"""Push values onto the value stack."""
self.frame.stack.extend(vals)
def popn(self, n):
"""Pop a number of values from the value stack.
A list of `n` values is returned, the deepest value first.
"""
if n:
ret = self.frame.stack[-n:]
self.frame.stack[-n:] = []
return ret
else:
return []
def peek(self, n):
"""Get a value `n` entries down in the stack, without changing the stack."""
return self.frame.stack[-n]
### byte instructions
def LOAD_CONST(self, const):
self.push(const)
def LOAD_NAME(self, name):
frame = self.frame
if name in frame.f_locals:
val = frame.f_locals[name]
elif name in frame.f_globals:
val = frame.f_globals[name]
elif name in frame.f_builtins:
val = frame.f_builtins[name]
else:
raise NameError("name '%s' is not defined" % name)
self.push(val)
def STORE_NAME(self, name):
self.frame.f_locals[name] = self.pop()
def LOAD_FAST(self, name):
#name = self.frame.f_code.co_varnames[name]
if name in self.frame.f_locals:
val = self.frame.f_locals[name]
else:
raise UnboundLocalError(
"local variable '%s' referenced before assignment" % name
)
self.push(val)
def STORE_FAST(self, name):
self.frame.f_locals[name] = self.pop()
def DELETE_FAST(self, name):
del self.frame.f_locals[name]
def LOAD_GLOBAL(self, name):
f = self.frame
if name in f.f_globals:
val = f.f_globals[name]
elif name in f.f_builtins:
val = f.f_builtins[name]
else:
raise NameError("global name '%s' is not defined" % name)
self.push(val)
def STORE_GLOBAL(self, name):
self.frame.f_globals[name] = self.pop()
def DELETE_GLOBAL(self, name):
del self.frame.f_globals[name]
def LOAD_CLOSURE(self, name):
self.push(self.frame.cells[name])
def LOAD_DEREF(self, name):
self.push(self.frame.cells[name])
def STORE_DEREF(self, name):
self.frame.cells[name] = self.pop()
def LOAD_ATTR(self, name):
target = self.pop()
val = getattr(target, name)
self.push(val)
def STORE_ATTR(self, name):
val, target = self.popn(2)
setattr(target, name, val)
def DELETE_ATTR(self, name):
target = self.pop()
delattr(target, name)
def LOAD_LOCALS(self):
self.push(self.frame.f_locals)
def UNARY_POSITIVE(self):
self.push(+self.pop())
def UNARY_NEGATIVE(self):
self.push(-self.pop())
def UNARY_INVERT(self):
self.push(~self.pop())
def UNARY_NOT(self):
self.push(not self.pop())
def UNARY_CONVERT(self):
self.push(repr(self.pop()))
def BINARY_ADD(self):
v1 = self.pop()
v2 = self.pop()
self.push(v2 + v1)
def BINARY_SUBTRACT(self):
a, b = self.popn(2)
self.push(a - b)
def BINARY_MULTIPLY(self):
v1, v2 = self.popn(2)
self.push(v2 * v1)
def BINARY_DIVIDE(self):
v1, v2 = self.popn(2)
self.push(v1/v2)
def BINARY_POWER(self):
v1, v2 = self.popn(2)
self.push(v2 ** v1)
def BINARY_MODULO(self):
v1, v2 = self.popn(2)
self.push(v1 % v2)
def BINARY_SUBSCR(self):
v, s = self.popn(2)
self.push(v[s])
def BINARY_LSHIFT(self):
v, s = self.popn(2)
self.push(s << v)
def BINARY_RSHIFT(self):
v, s = self.popn(2)
self.push(s >> v)
def BINARY_AND(self):
v1, v2 = self.popn(2)
self.push(v1 & v2)
def BINARY_XOR(self):
v1, v2 = self.popn(2)
self.push(v1 ^ v2)
def BINARY_OR(self):
v1, v2 = self.popn(2)
self.push(v1 | v2)
def PRINT_EXPR(self):
print self.pop()
def PRINT_ITEM(self):
print self.pop(),
def PRINT_ITEM_TO(self):
to = self.pop()
item = self.pop()
print>>to, item,
def PRINT_NEWLINE(self):
print
def PRINT_NEWLINE_TO(self):
to = self.pop()
print>>to
def RETURN_VALUE(self):
self.return_value = self.pop()
if self.frame.generator:
self.frame.generator.finished = True
return 'return'
def YIELD_VALUE(self):
self.return_value = self.pop()
return "yield"
COMPARE_OPERATORS = [
operator.lt,
operator.le,
operator.eq,
operator.ne,
operator.gt,
operator.ge,
lambda x, y: x in y,
lambda x, y: x not in y,
lambda x, y: x is y,
lambda x, y: x is not y,
lambda x, y: issubclass(x, Exception) and issubclass(x, y),
]
def COMPARE_OP(self, opnum):
x, y = self.popn(2)
self.push(self.COMPARE_OPERATORS[opnum](x, y))
def POP_JUMP_IF_TRUE(self, target):
v = self.pop()
if v:
self.frame.f_lasti = target
def POP_JUMP_IF_FALSE(self, target):
v = self.pop()
if not v:
self.frame.f_lasti = target
def JUMP_FORWARD(self, step):
self.frame.f_lasti = step
def JUMP_ABSOLUTE(self, target):
self.frame.f_lasti = target
def JUMP_IF_TRUE_OR_POP(self, jump):
val = self.peek(1)
if val:
self.frame.f_lasti = jump
else:
self.pop()
def JUMP_IF_FALSE_OR_POP(self, jump):
val = self.peek(1)
if not val:
self.frame.f_lasti = jump
else:
self.pop()
def GET_ITER(self):
v = self.pop()
self.push(iter(v))
def FOR_ITER(self, step):
v = self.frame.stack[-1]
try:
self.push(v.next())
except StopIteration:
self.pop()
self.frame.f_lasti = step
def SETUP_LOOP(self, dest):
self.push_block('loop', dest)
def SETUP_EXCEPT(self, dest):
self.push_block('except', dest)
def SETUP_FINALLY(self, dest):
self.push_block('finally', dest)
def END_FINALLY(self):
v = self.pop()
if isinstance(v, str):
why = v
if why == 'continue':
self.return_value = self.pop()
elif v is None:
why = None
elif issubclass(v, BaseException):
exctype = v
val = self.pop()
tb = self.pop()
self.last_exception = (exctype, val, tb)
why = 'reraise'
return why
def SETUP_WITH(self, dest):
ctxmgr = self.pop()
self.push(ctxmgr.__exit__)
ctxmgr_obj = ctxmgr.__enter__()
self.push(ctxmgr_obj)
self.push_block('with', dest)
def WITH_CLEANUP(self):
v = w = None
u = self.peek(1)
if u is None:
exit_func = self.pop(1)
exit_ret = exit_func(w, v, u)
def POP_BLOCK(self):
self.pop_block()
def BREAK_LOOP(self):
return 'break'
def CONTINUE_LOOP(self, dest):
self.return_value = dest
return 'continue'
def BUILD_LIST(self, num):
r = []
for i in range(num):
r.insert(0, self.pop())
self.push(r)
def BUILD_TUPLE(self, num):
t = self.popn(num)
self.push(tuple(t))
def BUILD_MAP(self, size):
# 忽略size
self.push({})
def BUILD_SET(self,count):
elts = self.popn(count)
self.push(set(elts))
def BUILD_CLASS(self):
name, bases, methods = self.popn(3)
self.push(type(name, bases, methods))
def SET_ADD(self, count):
val = self.pop()
the_set = self.peek(count)
the_set.add(val)
def MAP_ADD(self, count):
val, key = self.popn(2)
the_map = self.peek(count)
the_map[key] = val
def STORE_MAP(self):
val, key = self.popn(2)
m = self.peek(1)
m[key] = val
def LIST_APPEND(self, count):
val = self.pop()
l = self.peek(count)
l.append(val)
def MAKE_FUNCTION(self, arg):
code_obj = self.pop()
defaults = self.popn(arg)
fn = Function(code_obj, defaults, None, self)
self.push(fn)
def MAKE_CLOSURE(self, argc):
closure, code = self.popn(2)
defaults = self.popn(argc)
fn = Function(code, defaults, closure, self)
self.push(fn)
def CALL_FUNCTION(self, argc):
return self.call_function(argc, [], {})
def CALL_FUNCTION_VAR(self, argc):
args = self.pop()
return self.call_function(argc, args, {})
def CALL_FUNCTION_KW(self, argc):
kwargs = self.pop()
return self.call_function(argc, [], kwargs)
def CALL_FUNCTION_VAR_KW(self, argc):
args, kwargs = self.popn(2)
return self.call_function(argc, args, kwargs)
def call_function(self, argc, args, kwargs):
kwlen, poslen = divmod(argc, 256)
logging.debug("poslen {}, kwlen {}".format(poslen, kwlen))
namedargs = {}
for i in range(kwlen):
key, val = self.popn(2)
namedargs[key] = val
namedargs.update(kwargs)
posargs = self.popn(poslen)
posargs.extend(args)
func = self.pop()
if hasattr(func, 'im_func'):
if func.im_self:
posargs.insert(0, func.im_self)
if not isinstance(posargs[0], func.im_class):
raise TypeError(
'unbound method %s() must be called with %s instance '
'as first argument (got %s instance instead)' % (
func.im_func.func_name,
func.im_class.__name__,
type(posargs[0]).__name__,
)
)
func = func.im_func
r = func(*posargs, **namedargs)
self.push(r)
def EXEC_STMT(self):
stmt, globs, locs = self.popn(3)
exec(stmt, globs, locs)
## Importing
def IMPORT_NAME(self, name):
level, fromlist = self.popn(2)
frame = self.frame
self.push(
__import__(name, frame.f_globals, frame.f_locals, fromlist, level)
)
def IMPORT_STAR(self):
mod = self.pop()
for attr in dir(mod):
if attr[0] != '_':
self.frame.f_locals[attr] = getattr(mod, attr)
def IMPORT_FROM(self, name):
mod = self.peek(1)
self.push(getattr(mod, name))
def POP_TOP(self):
self.pop()
def DUP_TOP(self):
self.push(self.peek(1))
def DUP_TOPX(self, count):
items = self.popn(count)
for i in [1, 2]:
self.push(*items)
def ROT_TWO(self):
a, b = self.popn(2)
self.push(b, a)
def ROT_THREE(self):
a, b, c = self.popn(3)
self.push(c, a, b)
def ROT_FOUR(self):
a, b, c, d = self.popn(4)
self.push(d, a, b, c)
def DELETE_NAME(self, name):
del self.frame.f_locals[name]
#refactor
def UNPACK_SEQUENCE(self, count):
seq = self.pop()
for val in reversed(seq):
self.push(val)
#inplace operation
def INPLACE_POWER(self):
v1, v = self.popn(2)
self.push(v1 ** v)
def INPLACE_ADD(self):
v1, v = self.popn(2)
self.push(v1 + v)
def INPLACE_MULTIPLY(self):
v1, v = self.popn(2)
self.push(v1 * v)
def INPLACE_DIVIDE(self):
v1, v = self.popn(2)
self.push(v1 / v)
def INPLACE_FLOOR_DIVIDE(self):
v1, v = self.popn(2)
self.push(v1 // v)
def INPLACE_MODULO(self):
v1, v = self.popn(2)
self.push(v1 % v)
def INPLACE_SUBTRACT(self):
v1, v = self.popn(2)
self.push(v1 - v)
def INPLACE_LSHIFT(self):
v1, v = self.popn(2)
self.push(v1 << v)
def INPLACE_RSHIFT(self):
v1, v = self.popn(2)
self.push(v1 >> v)
def INPLACE_AND(self):
v1, v = self.popn(2)
self.push(v1 & v)
def INPLACE_XOR(self):
v1, v = self.popn(2)
self.push(v1 ^ v)
def INPLACE_OR(self):
v1, v = self.popn(2)
self.push(v1 | v)
#slice operation
def SLICE3(self):
l, r = self.popn(2)
v = self.pop()
self.push(v[l:r])
def SLICE2(self):
end = self.pop()
v = self.pop()
self.push(v[:end])
def SLICE1(self):
start = self.pop()
v = self.pop()
self.push(v[start:])
def SLICE0(self):
v = self.pop()
self.push(v[:])
def STORE_SLICE3(self):
start, end = self.popn(2)
l = self.pop()
v = self.pop()
l[start:end] = v
def STORE_SLICE2(self):
end = self.pop()
l = self.pop()
v = self.pop()
l[:end] = v
def STORE_SLICE1(self):
start = self.pop()
l = self.pop()
v = self.pop()
l[start:] = v
def STORE_SLICE0(self):
l = self.pop()
v = self.pop()
l[:] = v
def DELETE_SLICE3(self):
start, end = self.popn(2)
l = self.pop()
del l[start:end]
def DELETE_SLICE2(self):
end = self.pop()
l = self.pop()
del l[:end]
def DELETE_SLICE1(self):
start = self.pop()
l = self.pop()
del l[start:]
def DELETE_SLICE0(self):
l = self.pop()
del l[:]
def BUILD_SLICE(self, argc):
step = None
if argc == 2:
start, stop = self.popn(2)
else:
start, stop, step = self.popn(3)
self.push(slice(start, stop, step))
def STORE_SUBSCR(self):
v, s = self.popn(2)
v[s] = self.pop()
def DELETE_SUBSCR(self):
v, s = self.popn(2)
del v[s]
def RAISE_VARARGS(self, argc):
exctype = val = tb = None
if argc == 0:
exctype, val, tb = self.last_exception
elif argc == 1: