-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpycodegen.py
1939 lines (1646 loc) · 59.3 KB
/
pycodegen.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
from __future__ import print_function
import imp
import os
import marshal
import struct
import sys
from io import StringIO
import ast
from compiler import walk
from compiler import pyassem, misc, future, symbols
from compiler.consts import SC_LOCAL, SC_GLOBAL_IMPLICIT, SC_GLOBAL_EXPLICIT, \
SC_FREE, SC_CELL
from compiler.consts import (CO_VARARGS, CO_VARKEYWORDS, CO_NEWLOCALS,
CO_NESTED, CO_GENERATOR, CO_FUTURE_DIVISION,
CO_FUTURE_ABSIMPORT, CO_FUTURE_WITH_STATEMENT, CO_FUTURE_PRINT_FUNCTION)
from .visitor import ASTVisitor
from . import config
# XXX The version-specific code can go, since this code only works with 2.x.
# Do we have Python 1.x or Python 2.x?
try:
VERSION = sys.version_info[0]
except AttributeError:
VERSION = 1
callfunc_opcode_info = {
# (Have *args, Have **args) : opcode
(0,0) : "CALL_FUNCTION",
(1,0) : "CALL_FUNCTION_VAR",
(0,1) : "CALL_FUNCTION_KW",
(1,1) : "CALL_FUNCTION_VAR_KW",
}
LOOP = 1
EXCEPT = 2
TRY_FINALLY = 3
END_FINALLY = 4
def compileFile(filename, display=0):
f = open(filename, 'U')
buf = f.read()
f.close()
mod = Module(buf, filename)
try:
mod.compile(display)
except SyntaxError:
raise
else:
f = open(filename + "c", "wb")
mod.dump(f)
f.close()
def compile(source, filename, mode, flags=None, dont_inherit=None):
"""Replacement for builtin compile() function"""
if flags is not None or dont_inherit is not None:
raise RuntimeError("not implemented yet")
if mode == "single":
gen = Interactive(source, filename)
elif mode == "exec":
gen = Module(source, filename)
elif mode == "eval":
gen = Expression(source, filename)
else:
raise ValueError("compile() 3rd arg must be 'exec' or "
"'eval' or 'single'")
gen.compile()
return gen.code
class AbstractCompileMode:
mode = None # defined by subclass
def __init__(self, source, filename):
self.source = source
self.filename = filename
self.code = None
def _get_tree(self):
tree = ast.parse(self.source, self.filename, self.mode)
tree.filename = self.filename
return tree
def compile(self):
pass # implemented by subclass
def getCode(self):
return self.code
class Expression(AbstractCompileMode):
mode = "eval"
def compile(self):
tree = self._get_tree()
gen = ExpressionCodeGenerator(tree)
self.code = gen.getCode()
class Interactive(AbstractCompileMode):
mode = "single"
def compile(self):
tree = self._get_tree()
gen = InteractiveCodeGenerator(tree)
self.code = gen.getCode()
class Module(AbstractCompileMode):
mode = "exec"
def compile(self, display=0):
tree = self._get_tree()
gen = ModuleCodeGenerator(tree)
if display:
import pprint
pprint.pprint(tree)
self.code = gen.getCode()
def dump(self, f):
f.write(self.getPycHeader())
marshal.dump(self.code, f)
MAGIC = imp.get_magic()
def getPycHeader(self):
# compile.c uses marshal to write a long directly, with
# calling the interface that would also generate a 1-byte code
# to indicate the type of the value. simplest way to get the
# same effect is to call marshal and then skip the code.
mtime = os.path.getmtime(self.filename)
# TODO: Use size of original file
hdr = struct.pack('<II', int(mtime), len(self.source.encode()))
return self.MAGIC + hdr
def get_bool_const(node):
"""Return True if node represent constantly true value, False if
constantly false value, and None otherwise (non-constant)."""
if isinstance(node, ast.Num):
return bool(node.n)
if isinstance(node, ast.NameConstant):
return bool(node.value)
if isinstance(node, ast.Str):
return bool(node.s)
if isinstance(node, ast.Name):
if node.id == "__debug__":
return True
def is_constant_false(node):
if isinstance(node, ast.Num):
if not node.n:
return 1
return 0
def is_constant_true(node):
if isinstance(node, ast.Num):
if node.n:
return 1
return 0
class CodeGenerator:
"""Defines basic code generator for Python bytecode
This class is an abstract base class. Concrete subclasses must
define an __init__() that defines self.graph and then calls the
__init__() defined in this class.
The concrete class must also define the class attributes
FunctionGen, and ClassGen. These attributes can be
defined in the initClass() method, which is a hook for
initializing these methods after all the classes have been
defined.
"""
optimized = 0 # is namespace access optimized?
__initialized = None
class_name = None # provide default for instance variable
def __init__(self):
if self.__initialized is None:
self.initClass()
self.__class__.__initialized = 1
self.checkClass()
self.setups = misc.Stack()
self.last_lineno = None
self._setupGraphDelegation()
self._div_op = "BINARY_DIVIDE"
# XXX set flags based on future features
futures = self.get_module().futures
for feature in futures:
if feature == "division":
self.graph.setFlag(CO_FUTURE_DIVISION)
self._div_op = "BINARY_TRUE_DIVIDE"
elif feature == "absolute_import":
self.graph.setFlag(CO_FUTURE_ABSIMPORT)
elif feature == "with_statement":
self.graph.setFlag(CO_FUTURE_WITH_STATEMENT)
elif feature == "print_function":
self.graph.setFlag(CO_FUTURE_PRINT_FUNCTION)
def initClass(self):
"""This method is called once for each class"""
def checkClass(self):
"""Verify that class is constructed correctly"""
try:
assert hasattr(self, 'graph')
assert getattr(self, 'FunctionGen')
assert getattr(self, 'ClassGen')
except AssertionError:
intro = "Bad class construction for %s" % self.__class__.__name__
raise AssertionError(intro)
def _setupGraphDelegation(self):
self.emit = self.graph.emit
self.newBlock = self.graph.newBlock
self.startBlock = self.graph.startBlock
self.nextBlock = self.graph.nextBlock
self.setDocstring = self.graph.setDocstring
def getCode(self):
"""Return a code object"""
return self.graph.getCode()
def mangle(self, name):
if self.class_name is not None:
return misc.mangle(name, self.class_name)
else:
return name
def parseSymbols(self, tree):
s = symbols.SymbolVisitor()
walk(tree, s)
return s.scopes
def get_module(self):
raise RuntimeError("should be implemented by subclasses")
# Next five methods handle name access
def storeName(self, name):
self._nameOp('STORE', name)
def loadName(self, name):
self._nameOp('LOAD', name)
def delName(self, name):
self._nameOp('DELETE', name)
def _nameOp(self, prefix, name):
name = self.mangle(name)
scope = self.scope.check_name(name)
if scope == SC_LOCAL:
if not self.optimized:
self.emit(prefix + '_NAME', name)
else:
self.emit(prefix + '_FAST', name)
elif scope == SC_GLOBAL_EXPLICIT:
self.emit(prefix + '_GLOBAL', name)
elif scope == SC_GLOBAL_IMPLICIT:
if not self.optimized:
self.emit(prefix + '_NAME', name)
else:
self.emit(prefix + '_GLOBAL', name)
elif scope == SC_FREE or scope == SC_CELL:
if isinstance(self.scope, symbols.ClassScope):
if prefix == "STORE" and name not in self.scope.nonlocals:
self.emit(prefix + '_NAME', name)
return
if isinstance(self.scope, symbols.ClassScope) and prefix == "LOAD":
self.emit(prefix + '_CLASSDEREF', name)
else:
self.emit(prefix + '_DEREF', name)
else:
raise RuntimeError("unsupported scope for var %s: %d" % \
(name, scope))
def _implicitNameOp(self, prefix, name):
"""Emit name ops for names generated implicitly by for loops
The interpreter generates names that start with a period or
dollar sign. The symbol table ignores these names because
they aren't present in the program text.
"""
if self.optimized:
self.emit(prefix + '_FAST', name)
else:
self.emit(prefix + '_NAME', name)
def set_lineno(self, node):
if hasattr(node, "lineno"):
self.graph.lineno = node.lineno
self.graph.lineno_set = False
def update_lineno(self, node):
if hasattr(node, "lineno") and node.lineno > self.graph.lineno:
self.set_lineno(node)
def get_docstring(self, node):
if node.body and isinstance(node.body[0], ast.Expr) \
and isinstance(node.body[0].value, ast.Str):
return node.body[0].value.s
def skip_docstring(self, body):
"""Given list of statements, representing body of a function, class,
or module, skip docstring, if any.
"""
if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Str):
return body[1:]
return body
# The first few visitor methods handle nodes that generator new
# code objects. They use class attributes to determine what
# specialized code generators to use.
FunctionGen = None
ClassGen = None
def visitModule(self, node):
self.scopes = self.parseSymbols(node)
self.scope = self.scopes[node]
self.emit('SET_LINENO', 0)
doc = self.get_docstring(node)
if doc is not None:
self.set_lineno(node.body[0])
self.emit('LOAD_CONST', doc)
self.storeName('__doc__')
self.visit(self.skip_docstring(node.body))
# See if the was a live statement, to later set its line number as
# module first line. If not, fall back to first line of 1.
if not self.graph.first_inst_lineno:
self.graph.first_inst_lineno = 1
self.emit('LOAD_CONST', None)
self.emit('RETURN_VALUE')
def visitExpression(self, node):
self.scopes = self.parseSymbols(node)
self.scope = self.scopes[node]
self.visit(node.body)
self.emit('RETURN_VALUE')
def visitFunctionDef(self, node):
self.set_lineno(node)
self._visitFuncOrLambda(node, isLambda=0)
# Handled by AbstractFunctionCode?
#if node.doc:
# self.setDocstring(node.doc)
self.storeName(node.name)
visitAsyncFunctionDef = visitFunctionDef
def visitLambda(self, node):
self.update_lineno(node)
self._visitFuncOrLambda(node, isLambda=1)
def processBody(self, body, gen):
walker = ASTVisitor(gen)
if isinstance(body, list):
for stmt in body:
if isinstance(stmt, ast.Return):
gen.seen_toplevel_return = True
gen.visit(stmt)
else:
gen.visit(body)
def _visitFuncOrLambda(self, node, isLambda=0):
if not isLambda and node.decorator_list:
for decorator in node.decorator_list:
self.visit(decorator)
ndecorators = len(node.decorator_list)
else:
ndecorators = 0
gen = self.FunctionGen(node, self.scopes, isLambda,
self.class_name, self.get_module())
body = node.body
if not isLambda:
body = self.skip_docstring(body)
self.processBody(body, gen)
gen.finish()
for default in node.args.defaults:
self.visit(default)
kwdefaults_num = 0
for kwonly, default in zip(node.args.kwonlyargs, node.args.kw_defaults):
if default is not None:
self.emit('LOAD_CONST', self.mangle(kwonly.arg))
self.visit(default)
kwdefaults_num += 1
ann_args = []
ann_num = 0
for arg in node.args.args:
if arg.annotation:
self.visit(arg.annotation)
ann_args.append(self.mangle(arg.arg))
if node.args.vararg:
if node.args.vararg.annotation:
self.visit(node.args.vararg.annotation)
ann_args.append(self.mangle(node.args.vararg.arg))
for arg in node.args.kwonlyargs:
if arg.annotation:
self.visit(arg.annotation)
ann_args.append(self.mangle(arg.arg))
if node.args.kwarg:
if node.args.kwarg.annotation:
self.visit(node.args.kwarg.annotation)
ann_args.append(self.mangle(node.args.kwarg.arg))
# Cannot annotate return type for lambda
if isinstance(node, ast.FunctionDef) and node.returns:
self.visit(node.returns)
ann_args.append("return")
if ann_args:
self.emit('LOAD_CONST', tuple(ann_args))
ann_num = len(ann_args) + 1
self._makeClosure(gen, ann_num << 16 | kwdefaults_num << 8 | len(node.args.defaults))
for i in range(ndecorators):
self.emit('CALL_FUNCTION', 1)
def visitClassDef(self, node):
for decorator in node.decorator_list:
self.visit(decorator)
gen = self.ClassGen(node, self.scopes,
self.get_module())
walk(self.skip_docstring(node.body), gen)
gen.finish()
self.set_lineno(node)
self.emit('LOAD_BUILD_CLASS')
self._makeClosure(gen, 0)
self.emit('LOAD_CONST', node.name)
args = 2
for base in node.bases:
self.visit(base)
args += 1
kw = 0
for kwarg in node.keywords:
if kwarg.arg is None:
assert 0, "TODO: implement"
dstar_args = kwarg.value
self.visit(dstar_args)
else:
self.emit('LOAD_CONST', kwarg.arg)
self.visit(kwarg.value)
kw = kw + 1
self.emit('CALL_FUNCTION', kw << 8 | args)
for i in range(len(node.decorator_list)):
self.emit('CALL_FUNCTION', 1)
self.storeName(node.name)
# The rest are standard visitor methods
# The next few implement control-flow statements
def visitIf(self, node):
self.set_lineno(node)
test = node.test
test_const = get_bool_const(test)
end = self.newBlock("if_end")
orelse = None
if node.orelse:
orelse = self.newBlock("if_else")
if test_const is None:
self.visit(test)
self.emit('POP_JUMP_IF_FALSE', orelse or end)
if test_const != False:
self.nextBlock()
self.visit(node.body)
if node.orelse:
if test_const is None:
self.emit('JUMP_FORWARD', end)
if test_const != True:
self.startBlock(orelse)
self.visit(node.orelse)
self.nextBlock(end)
def visitWhile(self, node):
self.set_lineno(node)
test_const = get_bool_const(node.test)
if test_const == False:
if node.orelse:
self.visit(node.orelse)
return
loop = self.newBlock("while_loop")
else_ = self.newBlock("while_else")
after = self.newBlock("while_after")
self.emit('SETUP_LOOP', after)
self.nextBlock(loop)
self.setups.push((LOOP, loop))
if test_const != True:
self.visit(node.test)
self.emit('POP_JUMP_IF_FALSE', else_ or after)
self.nextBlock()
self.visit(node.body)
self.emit('JUMP_ABSOLUTE', loop)
if not is_constant_true(node.test): # TODO: Workaround for weird block linking implementation
self.startBlock(else_ or after) # or just the POPs if not else clause
self.emit('POP_BLOCK')
self.setups.pop()
if node.orelse:
self.visit(node.orelse)
self.nextBlock(after)
def visitFor(self, node):
start = self.newBlock()
anchor = self.newBlock()
after = self.newBlock()
self.setups.push((LOOP, start))
self.set_lineno(node)
self.emit('SETUP_LOOP', after)
self.visit(node.iter)
self.emit('GET_ITER')
self.nextBlock(start)
self.emit('FOR_ITER', anchor)
self.visit(node.target)
self.visit(node.body)
self.emit('JUMP_ABSOLUTE', start)
self.nextBlock(anchor)
self.emit('POP_BLOCK')
self.setups.pop()
if node.orelse:
self.visit(node.orelse)
self.nextBlock(after)
def visitAsyncFor(self, node):
start = self.newBlock()
anchor = self.newBlock()
or_else = self.newBlock()
jump_after = self.newBlock()
after = self.newBlock()
self.set_lineno(node)
self.setups.push((LOOP, start))
self.emit('SETUP_LOOP', jump_after)
self.visit(node.iter)
self.emit('GET_AITER')
self.emit('LOAD_CONST', None)
self.emit('YIELD_FROM')
try_body = self.newBlock()
handlers = self.newBlock()
loop_body = self.newBlock()
self.nextBlock(start)
self.emit('SETUP_EXCEPT', handlers)
self.nextBlock(try_body)
self.setups.push((EXCEPT, try_body))
self.emit('GET_ANEXT')
self.emit('LOAD_CONST', None)
self.emit('YIELD_FROM')
self.visit(node.target)
self.emit('POP_BLOCK')
self.setups.pop()
self.emit('JUMP_FORWARD', loop_body)
self.startBlock(handlers)
self.emit('DUP_TOP')
self.emit('LOAD_GLOBAL', 'StopAsyncIteration')
self.emit('COMPARE_OP', 'exception match')
next = self.newBlock()
self.emit('POP_JUMP_IF_FALSE', next)
self.nextBlock()
self.emit('POP_TOP')
self.emit('POP_TOP')
self.emit('POP_TOP')
self.emit('POP_EXCEPT')
self.emit('POP_BLOCK')
self.emit('JUMP_ABSOLUTE', or_else)
self.startBlock(next)
self.emit('END_FINALLY')
self.startBlock(loop_body)
self.visit(node.body)
self.emit('JUMP_ABSOLUTE', start)
self.nextBlock(anchor)
self.emit('POP_BLOCK')
self.setups.pop()
self.nextBlock(jump_after)
self.emit('JUMP_ABSOLUTE', after)
self.startBlock(or_else)
if node.orelse:
self.visit(node.orelse)
self.nextBlock(after)
def visitBreak(self, node):
if not self.setups:
raise SyntaxError("'break' outside loop (%s, %d)" % \
(node.filename, node.lineno))
self.set_lineno(node)
self.emit('BREAK_LOOP')
def visitContinue(self, node):
if not self.setups:
raise SyntaxError("'continue' outside loop (%s, %d)" % \
(node.filename, node.lineno))
self.set_lineno(node)
kind, block = self.setups.top()
if kind == LOOP:
self.emit('JUMP_ABSOLUTE', block)
self.nextBlock()
elif kind == EXCEPT or kind == TRY_FINALLY:
# find the block that starts the loop
top = len(self.setups)
while top > 0:
top = top - 1
kind, loop_block = self.setups[top]
if kind == LOOP:
break
if kind != LOOP:
raise SyntaxError("'continue' outside loop (%s, %d)" % \
(node.filename, node.lineno))
self.emit('CONTINUE_LOOP', loop_block)
self.nextBlock()
elif kind == END_FINALLY:
msg = "'continue' not allowed inside 'finally' clause (%s, %d)"
raise SyntaxError(msg % (node.filename, node.lineno))
def visitTest(self, node, jump):
end = self.newBlock()
for child in node.values[:-1]:
self.visit(child)
self.emit(jump, end)
self.nextBlock()
self.visit(node.values[-1])
self.nextBlock(end)
_boolop_opcode = {
ast.And: "JUMP_IF_FALSE_OR_POP",
ast.Or: "JUMP_IF_TRUE_OR_POP",
}
def visitBoolOp(self, node):
opcode = self._boolop_opcode[type(node.op)]
self.visitTest(node, opcode)
_cmp_opcode = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
ast.LtE: "<=",
ast.Gt: ">",
ast.GtE: ">=",
ast.Is: "is",
ast.IsNot: "is not",
ast.In: "in",
ast.NotIn: "not in",
}
def visitIfExp(self, node):
endblock = self.newBlock()
elseblock = self.newBlock()
self.visit(node.test)
self.emit('POP_JUMP_IF_FALSE', elseblock)
self.visit(node.body)
self.emit('JUMP_FORWARD', endblock)
self.nextBlock(elseblock)
self.visit(node.orelse)
self.nextBlock(endblock)
def visitCompare(self, node):
self.update_lineno(node)
self.visit(node.left)
cleanup = self.newBlock()
for op, code in zip(node.ops[:-1], node.comparators[:-1]):
self.visit(code)
self.emit('DUP_TOP')
self.emit('ROT_THREE')
self.emit('COMPARE_OP', self._cmp_opcode[type(op)])
self.emit('JUMP_IF_FALSE_OR_POP', cleanup)
self.nextBlock()
# now do the last comparison
if node.ops:
op = node.ops[-1]
code = node.comparators[-1]
self.visit(code)
self.emit('COMPARE_OP', self._cmp_opcode[type(op)])
if len(node.ops) > 1:
end = self.newBlock()
self.emit('JUMP_FORWARD', end)
self.startBlock(cleanup)
self.emit('ROT_TWO')
self.emit('POP_TOP')
self.nextBlock(end)
def get_qual_prefix(self, gen):
prefix = ""
if gen.scope.global_scope:
return prefix
# Construct qualname prefix
parent = gen.scope.parent
while not isinstance(parent, symbols.ModuleScope):
# Only real functions use "<locals>", nested scopes like
# comprehensions don't.
if type(parent) in (symbols.FunctionScope, symbols.LambdaScope):
prefix = parent.name + ".<locals>." + prefix
else:
prefix = parent.name + "." + prefix
if parent.global_scope:
break
parent = parent.parent
return prefix
def _makeClosure(self, gen, args):
prefix = ""
if not isinstance(gen, ClassCodeGenerator):
prefix = self.get_qual_prefix(gen)
frees = gen.scope.get_free_vars()
if frees:
for name in frees:
self.emit('LOAD_CLOSURE', name)
self.emit('BUILD_TUPLE', len(frees))
self.emit('LOAD_CONST', gen)
self.emit('LOAD_CONST', prefix + gen.name) # py3 qualname
self.emit('MAKE_CLOSURE', args)
else:
self.emit('LOAD_CONST', gen)
self.emit('LOAD_CONST', prefix + gen.name) # py3 qualname
self.emit('MAKE_FUNCTION', args)
def wrap_comprehension(self, node, nested_scope):
if isinstance(node, ast.GeneratorExp):
inner = CompInner(
node, nested_scope, None,
[node.elt], ["YIELD_VALUE", "POP_TOP"]
)
inner_name = "<genexpr>"
elif isinstance(node, ast.SetComp):
inner = CompInner(
node, nested_scope, ("BUILD_SET", 0),
[node.elt], [("SET_ADD", len(node.generators) + 1)]
)
inner_name = "<setcomp>"
elif isinstance(node, ast.ListComp):
inner = CompInner(
node, nested_scope, ("BUILD_LIST", 0),
[node.elt], [("LIST_APPEND", len(node.generators) + 1)]
)
inner_name = "<listcomp>"
elif isinstance(node, ast.DictComp):
inner = CompInner(
node, nested_scope, ("BUILD_MAP", 0),
[node.value, node.key], [("MAP_ADD", len(node.generators) + 1)]
)
inner_name = "<dictcomp>"
else:
assert 0
return inner, inner_name
def visitNestedComp(self, node):
# Make comprehension node to also look like function node
class Holder: pass
node.args = Holder()
arg1 = Holder()
arg1.arg = ".0"
node.args.args = (arg1,)
node.args.kwonlyargs = ()
node.args.vararg = None
node.args.kwarg = None
node.body = []
inner, inner_name = self.wrap_comprehension(node, nested_scope=True)
gen = GenExprCodeGenerator(node, self.scopes, self.class_name,
self.get_module(), inner_name)
walk(inner, gen)
gen.finish()
self.set_lineno(node)
self._makeClosure(gen, 0)
# precomputation of outmost iterable
self.visit(node.generators[0].iter)
self.emit('GET_ITER')
self.emit('CALL_FUNCTION', 1)
def visitInlineComp(self, node):
inner, _ = self.wrap_comprehension(node, nested_scope=False)
self.visit(inner)
def visitGenericComp(self, node):
if config.COMPREHENSION_SCOPE:
return self.visitNestedComp(node)
else:
return self.visitInlineComp(node)
# Genereator expression should be always compiled with nested scope
# to follow generator semantics.
visitGeneratorExp = visitNestedComp
# Other comprehensions can be configured inline or nested-scope.
visitSetComp = visitGenericComp
visitListComp = visitGenericComp
visitDictComp = visitGenericComp
def visitcomprehension(self, node, is_outmost):
start = self.newBlock("comp_start")
anchor = self.newBlock("comp_anchor")
# TODO: end is not used
end = self.newBlock("comp_end")
# SETUP_LOOP isn't needed because(?) break/continue are
# not supported in comprehensions
#self.setups.push((LOOP, start))
#self.emit('SETUP_LOOP', end)
if is_outmost:
self.loadName('.0')
else:
self.visit(node.iter)
self.emit('GET_ITER')
self.nextBlock(start)
self.set_lineno(node)
self.emit('FOR_ITER', anchor)
self.nextBlock()
self.visit(node.target)
return start, anchor, end
def visitCompInner(self, node):
self.set_lineno(node)
if node.init_inst:
self.emit(*node.init_inst)
stack = []
is_outmost = node.nested_scope
for for_ in node.generators:
start, anchor, end = self.visit(for_, is_outmost)
is_outmost = False
cont = None
for if_ in for_.ifs:
if cont is None:
cont = self.newBlock()
self._visitCompIf(if_, cont)
stack.insert(0, (start, cont, anchor, end))
#self.visit(node.elt)
for elt in node.elt_nodes:
self.visit(elt)
#self.emit('YIELD_VALUE')
#self.emit('POP_TOP')
for inst in node.elt_insts:
if isinstance(inst, str):
self.emit(inst)
else:
self.emit(*inst)
for start, cont, anchor, end in stack:
if cont:
self.nextBlock(cont)
self.emit('JUMP_ABSOLUTE', start)
self.startBlock(anchor)
if isinstance(node.obj, ast.GeneratorExp):
self.emit('LOAD_CONST', None)
def _visitCompIf(self, node, branch):
self.set_lineno(node)
self.visit(node)
self.emit('POP_JUMP_IF_FALSE', branch)
self.newBlock()
# exception related
def visitAssert(self, node):
# XXX would be interesting to implement this via a
# transformation of the AST before this stage
if __debug__:
end = self.newBlock()
self.set_lineno(node)
# XXX AssertionError appears to be special case -- it is always
# loaded as a global even if there is a local name. I guess this
# is a sort of renaming op.
self.nextBlock()
self.visit(node.test)
self.emit('POP_JUMP_IF_TRUE', end)
self.nextBlock()
self.emit('LOAD_GLOBAL', 'AssertionError')
if node.msg:
self.visit(node.msg)
self.emit('CALL_FUNCTION', 1)
self.emit('RAISE_VARARGS', 1)
else:
self.emit('RAISE_VARARGS', 1)
self.nextBlock(end)
def visitRaise(self, node):
self.set_lineno(node)
n = 0
if node.exc:
self.visit(node.exc)
n = n + 1
if node.cause:
self.visit(node.cause)
n = n + 1
self.emit('RAISE_VARARGS', n)
def visitTry(self, node):
self.set_lineno(node)
if node.finalbody and not node.handlers:
self.visitTryFinally(node)
return
if not node.finalbody and node.handlers:
self.visitTryExcept(node)
return
# Split into 2 statements, try-except wrapped with try-finally
try_ex = ast.Try(body=node.body, handlers=node.handlers, orelse=node.orelse, finalbody=[], lineno=node.lineno)
node.body = try_ex
node.handlers = []
node.orelse = []
self.visitTryFinally(node)
def visitTryExcept(self, node):
body = self.newBlock()
handlers = self.newBlock()
end = self.newBlock()
if node.orelse:
lElse = self.newBlock()
else:
lElse = end
self.set_lineno(node)
self.emit('SETUP_EXCEPT', handlers)
self.nextBlock(body)
self.setups.push((EXCEPT, body))
self.visit(node.body)
self.emit('POP_BLOCK')
self.setups.pop()
self.emit('JUMP_FORWARD', lElse)
self.startBlock(handlers)
last = len(node.handlers) - 1
for i in range(len(node.handlers)):
handler = node.handlers[i]
expr = handler.type
target = handler.name
body = handler.body
self.set_lineno(handler)
if expr:
self.emit('DUP_TOP')
self.visit(expr)
self.emit('COMPARE_OP', 'exception match')
next = self.newBlock()
self.emit('POP_JUMP_IF_FALSE', next)
self.nextBlock()
else:
self.set_lineno(handler)
self.emit('POP_TOP')
if target:
self.visit(ast.Name(id=target, ctx=ast.Store(), lineno=expr.lineno))
else:
self.emit('POP_TOP')
self.emit('POP_TOP')
if target:
protected = ast.Try(
body=body, handlers=[], orelse=[],
finalbody=[
ast.Assign(targets=[ast.Name(id=target, ctx=ast.Store())], value=ast.NameConstant(value=None)),
ast.Delete(ast.Name(id=target, ctx=ast.Del())),
]
)
self.visitTryFinally(protected, except_protect=True)
else: