Debian Codegraph @

pypy/interpreter/astcompiler/codegen.py

raw symbols SCIP
1 """
2 Generate Python bytecode from a Abstract Syntax Tree.
3 """
4
5 # NOTE TO READERS: All the ugly and "obvious" isinstance assertions here are to
6 # help the annotator. To it, unfortunately, everything is not so obvious. If
7 # you figure out a way to remove them, great, but try a translation first,
8 # please.
9 import struct
10
11 from rpython.rlib.objectmodel import specialize, we_are_translated
12 from pypy.interpreter.astcompiler import ast, assemble, symtable, consts, misc
13 from pypy.interpreter.astcompiler.assemble import _SETUP_FINALLY, _SETUP_CLEANUP, _SETUP_WITH, _POP_BLOCK
14 from pypy.interpreter.astcompiler import optimize # For side effects
15 from pypy.interpreter.pyparser.error import SyntaxError
16 from pypy.tool import stdlib_opcode as ops
17
18 C_INT_MAX = (2 ** (struct.calcsize('i') * 8)) / 2 - 1
19
20 def compile_ast(space, module, info, set_debug_flag=False):
21 """Generate a code object from AST."""
22 symbols = symtable.SymtableBuilder(space, module, info)
23 return TopLevelCodeGenerator(space, module, symbols, info, set_debug_flag).assemble()
24
25 MAX_STACKDEPTH_CONTAINERS = 100
26
27 name_ops_default = misc.dict_to_switch({
28 ast.Load: ops.LOAD_NAME,
29 ast.Store: ops.STORE_NAME,
30 ast.Del: ops.DELETE_NAME
31 })
32
33 name_ops_fast = misc.dict_to_switch({
34 ast.Load: ops.LOAD_FAST,
35 ast.Store: ops.STORE_FAST,
36 ast.Del: ops.DELETE_FAST
37 })
38
39 name_ops_deref = misc.dict_to_switch({
40 ast.Load: ops.LOAD_DEREF,
41 ast.Store: ops.STORE_DEREF,
42 ast.Del: ops.DELETE_DEREF,
43 })
44
45 name_ops_global = misc.dict_to_switch({
46 ast.Load: ops.LOAD_GLOBAL,
47 ast.Store: ops.STORE_GLOBAL,
48 ast.Del: ops.DELETE_GLOBAL
49 })
50
51
52 unary_operations = misc.dict_to_switch({
53 ast.Invert: ops.UNARY_INVERT,
54 ast.Not: ops.UNARY_NOT,
55 ast.UAdd: ops.UNARY_POSITIVE,
56 ast.USub: ops.UNARY_NEGATIVE
57 })
58
59 binary_operations = misc.dict_to_switch({
60 ast.Add: ops.BINARY_ADD,
61 ast.Sub: ops.BINARY_SUBTRACT,
62 ast.Mult: ops.BINARY_MULTIPLY,
63 ast.Div: ops.BINARY_TRUE_DIVIDE,
64 ast.Mod: ops.BINARY_MODULO,
65 ast.Pow: ops.BINARY_POWER,
66 ast.LShift: ops.BINARY_LSHIFT,
67 ast.RShift: ops.BINARY_RSHIFT,
68 ast.BitOr: ops.BINARY_OR,
69 ast.BitAnd: ops.BINARY_AND,
70 ast.BitXor: ops.BINARY_XOR,
71 ast.FloorDiv: ops.BINARY_FLOOR_DIVIDE,
72 ast.MatMult: ops.BINARY_MATRIX_MULTIPLY
73 })
74
75 inplace_operations = misc.dict_to_switch({
76 ast.Add: ops.INPLACE_ADD,
77 ast.Sub: ops.INPLACE_SUBTRACT,
78 ast.Mult: ops.INPLACE_MULTIPLY,
79 ast.Div: ops.INPLACE_TRUE_DIVIDE,
80 ast.Mod: ops.INPLACE_MODULO,
81 ast.Pow: ops.INPLACE_POWER,
82 ast.LShift: ops.INPLACE_LSHIFT,
83 ast.RShift: ops.INPLACE_RSHIFT,
84 ast.BitOr: ops.INPLACE_OR,
85 ast.BitAnd: ops.INPLACE_AND,
86 ast.BitXor: ops.INPLACE_XOR,
87 ast.FloorDiv: ops.INPLACE_FLOOR_DIVIDE,
88 ast.MatMult: ops.INPLACE_MATRIX_MULTIPLY
89 })
90
91 compare_operations = misc.dict_to_switch({
92 ast.Eq: (ops.COMPARE_OP, 2),
93 ast.NotEq: (ops.COMPARE_OP, 3),
94 ast.Lt: (ops.COMPARE_OP, 0),
95 ast.LtE: (ops.COMPARE_OP, 1),
96 ast.Gt: (ops.COMPARE_OP, 4),
97 ast.GtE: (ops.COMPARE_OP, 5),
98 ast.In: (ops.CONTAINS_OP, 0),
99 ast.NotIn: (ops.CONTAINS_OP, 1),
100 ast.Is: (ops.IS_OP, 0),
101 ast.IsNot: (ops.IS_OP, 1)
102 })
103
104
105 class __extend__(ast.AST):
106 _literal_type = False
107
108 class __extend__(
109 ast.Constant,
110 ast.Tuple,
111 ast.List,
112 ast.ListComp,
113 ast.Dict,
114 ast.DictComp,
115 ast.Set,
116 ast.SetComp,
117 ast.GeneratorExp,
118 ast.JoinedStr,
119 ast.FormattedValue
120 ):
121 _literal_type = True
122
123 class __extend__(ast.GeneratorExp):
124
125 def build_container_and_load_iter(self, codegen):
126 codegen.comprehension_load_iter()
127
128 def get_generators(self):
129 return self.generators
130
131 def accept_comp_iteration(self, codegen, index):
132 self.elt.walkabout(codegen)
133 codegen.emit_op(ops.YIELD_VALUE)
134 codegen.emit_op(ops.POP_TOP)
135
136
137 class __extend__(ast.ListComp):
138
139 def build_container_and_load_iter(self, codegen):
140 single = False
141 if len(self.generators) == 1:
142 gen, = self.generators
143 assert isinstance(gen, ast.comprehension)
144 if not gen.ifs:
145 single = True
146 if single:
147 codegen.comprehension_load_iter()
148 codegen.emit_op(ops.BUILD_LIST_FROM_ARG)
149 else:
150 codegen.emit_op_arg(ops.BUILD_LIST, 0)
151 codegen.comprehension_load_iter()
152
153 def get_generators(self):
154 return self.generators
155
156 def accept_comp_iteration(self, codegen, index):
157 self.elt.walkabout(codegen)
158 codegen.emit_op_arg(ops.LIST_APPEND, index + 1)
159
160
161 class __extend__(ast.SetComp):
162
163 def build_container_and_load_iter(self, codegen):
164 codegen.emit_op_arg(ops.BUILD_SET, 0)
165 codegen.comprehension_load_iter()
166
167 def get_generators(self):
168 return self.generators
169
170 def accept_comp_iteration(self, codegen, index):
171 self.elt.walkabout(codegen)
172 codegen.emit_op_arg(ops.SET_ADD, index + 1)
173
174
175 class __extend__(ast.DictComp):
176
177 def build_container_and_load_iter(self, codegen):
178 codegen.emit_op_arg(ops.BUILD_MAP, 0)
179 codegen.comprehension_load_iter()
180
181 def get_generators(self):
182 return self.generators
183
184 def accept_comp_iteration(self, codegen, index):
185 self.key.walkabout(codegen)
186 self.value.walkabout(codegen)
187 codegen.emit_op_arg(ops.MAP_ADD, index + 1)
188
189
190 # These are frame blocks.
191 fblock_kind_to_str = []
192 for i, name in enumerate("F_WHILE_LOOP F_FOR_LOOP F_TRY_EXCEPT F_FINALLY_TRY F_FINALLY_END F_WITH F_ASYNC_WITH F_HANDLER_CLEANUP F_POP_VALUE F_EXCEPTION_HANDLER F_EXCEPTION_GROUP_HANDLER".split()):
193 globals()[name] = i
194 fblock_kind_to_str.append(name)
195 del name, i
196
197
198 class FrameBlockInfo(object):
199 def __init__(self, kind, block, end, datum):
200 self.kind = kind
201 self.block = block
202 self.end = end
203 self.datum = datum # an ast node needed for specific kinds of blocks
204 # For F_WITH/F_ASYNC_WITH: the block at which body-proper ends when
205 # the body unwinds via break/continue/return. unwind_fblock sets
206 # this the first time it fires so that handle_withitem's body
207 # exception-table entry ends before the inline unwind code (which
208 # must not be covered by this with's cleanup, else __exit__ would
209 # run twice when it raises during call_exit_with_nones).
210 self.body_segment_end = None
211
212 def __repr__(self):
213 # for debugging
214 return "<FrameBlockInfo kind=%s block=%s end=%s>" % (fblock_kind_to_str[self.kind], self.block, self.end)
215
216
217 def _get_positions_for_expr(node):
218 return (
219 node.lineno,
220 node.end_lineno,
221 node.col_offset,
222 node.end_col_offset,
223 )
224
225 def update_pos_expr(func):
226 def updater(self, expr):
227 assert isinstance(expr, ast.expr)
228 if expr.lineno > 0:
229 new_position_info = _get_positions_for_expr(expr)
230 else:
231 new_position_info = (-1,) * 4
232 old_position_info = self.position_info
233 self.position_info = new_position_info
234 try:
235 return func(self, expr)
236 finally:
237 self.position_info = old_position_info
238 updater.func_name = func.func_name + "_pos_updater"
239 return updater
240
241
242 class PythonCodeGenerator(assemble.PythonCodeMaker):
243 """Base code generator.
244
245 A subclass of this is created for every scope to be compiled. It walks
246 across the AST tree generating bytecode as needed.
247 """
248
249 def __init__(self, space, name, tree, lineno, symbols, compile_info,
250 qualname):
251 self.scope = symbols.find_scope(tree)
252 assemble.PythonCodeMaker.__init__(self, space, name, lineno,
253 self.scope, compile_info)
254 self.symbols = symbols
255 self.frame_blocks = []
256 self.interactive = False
257 self.temporary_name_counter = 1
258 self.qualname = qualname
259 self._allow_top_level_await = compile_info.flags & consts.PyCF_ALLOW_TOP_LEVEL_AWAIT
260 self._compile(tree)
261
262 def _compile(self, tree):
263 """Override in subclasses to compile a scope."""
264 raise NotImplementedError
265
266 def sub_scope(self, kind, name, node, lineno):
267 """Convenience function for compiling a sub scope."""
268 if self.scope.lookup(name) == symtable.SCOPE_GLOBAL_EXPLICIT:
269 qualname = name
270 elif self.qualname:
271 if isinstance(self.scope, symtable.FunctionScope):
272 qualname = '%s.<locals>.%s' % (self.qualname, name)
273 else:
274 qualname = '%s.%s' % (self.qualname, name)
275 else:
276 qualname = name
277 generator = kind(self.space, name, node, lineno, self.symbols,
278 self.compile_info, qualname)
279 return generator.assemble(), qualname
280
281 def push_frame_block(self, kind, block, end=None, datum=None):
282 self.frame_blocks.append(FrameBlockInfo(kind, block, end, datum))
283
284 def pop_frame_block(self, kind, block):
285 fblock = self.frame_blocks.pop()
286 assert fblock.kind == kind and fblock.block is block, \
287 "mismatched frame blocks"
288
289 def unwind_fblock(self, fblock, preserve_tos):
290 """ Unwind a frame block. If preserve_tos is true, the TOS before
291 popping the blocks will be restored afterwards, unless another return,
292 break or continue is found. In which case, the TOS will be popped."""
293
294 kind = fblock.kind
295 if kind == F_FOR_LOOP:
296 if preserve_tos:
297 self.emit_op(ops.ROT_TWO)
298 self.emit_op(ops.POP_TOP) # pop iterator
299 elif kind == F_WHILE_LOOP or kind == F_EXCEPTION_HANDLER or kind == F_EXCEPTION_GROUP_HANDLER:
300 pass
301 elif kind == F_TRY_EXCEPT:
302 self.emit_op(_POP_BLOCK)
303 elif kind == F_FINALLY_TRY:
304 self.emit_op(_POP_BLOCK)
305 if preserve_tos:
306 self.push_frame_block(F_POP_VALUE, None)
307 # emit the finally block, restoring the line number when done
308 finallyblock = fblock.datum
309 assert isinstance(finallyblock, ast.Try)
310 assert finallyblock.finalbody
311 self._visit_body(finallyblock.finalbody)
312 if preserve_tos:
313 self.pop_frame_block(F_POP_VALUE, None)
314 self.no_position_info() # make the unwind be artificial
315 elif kind == F_FINALLY_END:
316 # new-mode stack: [..., prev_exc, exc] (placed by PUSH_EXC_INFO).
317 # POP_EXCEPT pops prev_exc from value stack (-1 effect).
318 if preserve_tos:
319 self.emit_op(ops.ROT_THREE) # [..., prev_exc, exc, tos] -> [..., tos, prev_exc, exc]
320 self.emit_op(ops.POP_TOP) # pop exc
321 self.emit_op(ops.POP_EXCEPT) # pop prev_exc, restore sys.exc_info
322
323 elif kind == F_WITH or kind == F_ASYNC_WITH:
324 node = fblock.datum
325 assert isinstance(node, ast.withitem)
326 # Switch to a new block before call_exit_with_nones so that the
327 # with-body scope (opened by _SETUP_WITH) ends here.
328 # POP_BLOCK below closes that scope; the inline unwind code that
329 # follows is NOT covered by the with's cleanup handler, preventing
330 # __exit__ from being called twice if it raises. Only the first
331 # unwind site records the boundary; later early-exit paths that merge
332 # here keep the (coarser) earlier POP_BLOCK position.
333 inline_unwind = self.new_block()
334 self.use_next_block(inline_unwind)
335 if fblock.body_segment_end is None:
336 fblock.body_segment_end = inline_unwind
337 self.emit_op(_POP_BLOCK) # end with-body scope on early exit
338 self.update_position(node.context_expr)
339 if preserve_tos:
340 self.emit_op(ops.ROT_TWO)
341 self.call_exit_with_nones()
342 if kind == F_ASYNC_WITH:
343 self.emit_op_arg(ops.GET_AWAITABLE, 2)
344 self.load_const(self.space.w_None)
345 self.emit_op(ops.YIELD_FROM)
346 self.emit_op(ops.POP_TOP)
347 self.no_position_info()
348 elif kind == F_HANDLER_CLEANUP:
349 if fblock.datum:
350 self.emit_op(_POP_BLOCK) # end inner cleanup scope (SETUP_CLEANUP cleanup_end)
351 # new-mode: prev_exc is on value stack below tos (if preserve_tos)
352 if preserve_tos:
353 self.emit_op(ops.ROT_TWO) # bring prev_exc to TOS
354 self.emit_op(ops.POP_EXCEPT) # pop prev_exc, restore sys.exc_info
355 if fblock.datum:
356 self.load_const(self.space.w_None)
357 excepthandler = fblock.datum
358 assert isinstance(excepthandler, ast.ExceptHandler)
359 self.name_op(excepthandler.name, ast.Store, excepthandler)
360 self.name_op(excepthandler.name, ast.Del, excepthandler)
361 elif kind == F_POP_VALUE:
362 if preserve_tos:
363 self.emit_op(ops.ROT_TWO)
364 self.emit_op(ops.POP_TOP)
365 else:
366 assert 0, "unreachable"
367
368 def unwind_fblock_stack(self, preserve_tos, cause, find_loop_block=False):
369 """ Unwind block stack. If find_loop_block is True, return the first
370 loop block, otherwise return None. """
371 # XXX This is a bit ridiculous, but we really need to remove the
372 # blocks and then re-add them for the benefit of unwinding a try with
373 # a finally block, which will emit the code of the finally block in
374 # situ, which might then do more unwinding!
375 if not self.frame_blocks:
376 return None
377 fblock_top = self.frame_blocks[-1]
378 if find_loop_block and (fblock_top.kind == F_WHILE_LOOP
379 or fblock_top.kind == F_FOR_LOOP):
380 return fblock_top
381 fblock = self.frame_blocks.pop()
382 if fblock.kind == F_EXCEPTION_GROUP_HANDLER:
383 if isinstance(cause, ast.Return):
384 self.error("'return' cannot appear in an except* block", cause)
385 elif isinstance(cause, ast.Break):
386 self.error("'break' cannot appear in an except* block", cause)
387 else:
388 assert isinstance(cause, ast.Continue)
389 self.error("'continue' cannot appear in an except* block", cause)
390 self.unwind_fblock(fblock, preserve_tos)
391 res = self.unwind_fblock_stack(preserve_tos, cause, find_loop_block)
392 self.frame_blocks.append(fblock)
393 return res
394
395 def error(self, msg, node):
396 # NB: SyntaxError's offset is 1-based!
397 raise SyntaxError.fromast(msg, node, filename=self.compile_info.filename)
398
399 def name_op(self, identifier, ctx, node):
400 """Generate an operation appropriate for the scope of the identifier."""
401 # node is used only for the possible syntax error
402 self.check_forbidden_name(identifier, node, ctx)
403
404 scope = self.scope.lookup(identifier)
405 op = ops.NOP
406 container = self.names
407 if scope == symtable.SCOPE_LOCAL:
408 if self.scope.can_be_optimized:
409 container = self.var_names
410 op = name_ops_fast(ctx)
411 elif scope == symtable.SCOPE_FREE:
412 op = name_ops_deref(ctx)
413 if op == ops.LOAD_DEREF and isinstance(self, ClassCodeGenerator):
414 op = ops.LOAD_CLASSDEREF
415 container = self.free_vars
416 elif scope == symtable.SCOPE_CELL:
417 op = name_ops_deref(ctx)
418 container = self.cell_vars
419 elif scope == symtable.SCOPE_GLOBAL_IMPLICIT:
420 if self.scope.optimized:
421 op = name_ops_global(ctx)
422 elif scope == symtable.SCOPE_GLOBAL_EXPLICIT:
423 op = name_ops_global(ctx)
424 if op == ops.NOP:
425 op = name_ops_default(ctx)
426 self.emit_op_arg(op, self.add_name(container, identifier))
427
428 def possible_docstring(self, node):
429 if isinstance(node, ast.Expr) and self.compile_info.optimize < 2:
430 expr_value = node.value
431 if isinstance(expr_value, ast.Constant) and self.space.isinstance_w(expr_value.value, self.space.w_unicode):
432 return expr_value
433 return None
434
435 def ensure_docstring_constant(self, body):
436 # If there's a docstring, store it as the first constant.
437 if body:
438 doc_expr = self.possible_docstring(body[0])
439 else:
440 doc_expr = None
441 if doc_expr is not None:
442 self.add_const(doc_expr.value)
443 self.scope.doc_removable = True
444 return True
445 else:
446 self.add_const(self.space.w_None)
447 return False
448
449 def _get_code_flags(self):
450 return 0
451
452 def _check_async_function(self):
453 """Returns true if 'await' is allowed."""
454 return False
455
456 def _handle_body(self, body):
457 """Compile a list of statements, handling doc strings if needed."""
458 if body:
459 start = 0
460 doc_expr = self.possible_docstring(body[0])
461 if doc_expr is not None:
462 start = 1
463 doc_expr.walkabout(self)
464 if doc_expr.lineno > 0:
465 self.update_position(doc_expr)
466 self.name_op("__doc__", ast.Store, doc_expr)
467 self.scope.doc_removable = True
468 self._visit_body(body, start)
469 return True
470 else:
471 return False
472
473 def _maybe_setup_annotations(self):
474 # if the scope contained an annotated variable assignment,
475 # this will emit the requisite SETUP_ANNOTATIONS
476 if self.scope.contains_annotated and not isinstance(self, AbstractFunctionCodeGenerator):
477 return self.emit_op(ops.SETUP_ANNOTATIONS)
478
479 def call_exit_with_nones(self):
480 self.load_const(self.space.w_None)
481 self.emit_op(ops.DUP_TOP)
482 self.emit_op(ops.DUP_TOP)
483 self.emit_op_arg(ops.CALL_FUNCTION, 3)
484
485 def visit_Module(self, mod):
486 self._handle_body(mod.body)
487
488 def visit_Interactive(self, mod):
489 self.interactive = True
490 self._visit_body(mod.body)
491
492 def visit_Expression(self, mod):
493 self.add_none_to_final_return = False
494 mod.body.walkabout(self)
495
496 def _visit_body(self, body, start=0):
497 if body is None:
498 return
499 for i in range(start, len(body)):
500 stmt = body[i]
501 if stmt is not None:
502 assert isinstance(stmt, ast.stmt)
503 if stmt.lineno > 0:
504 self.update_position(stmt)
505 stmt.walkabout(self)
506
507 def _make_function(self, code, oparg=0, qualname=None):
508 """Emit the opcodes to turn a code object into a function."""
509 w_qualname = self.space.newtext(qualname or code.co_name)
510 if code.co_freevars:
511 oparg = oparg | 0x08
512 # Load cell and free vars to pass on.
513 for free in code.co_freevars:
514 free_scope = self.scope.lookup(free)
515 if free_scope in (symtable.SCOPE_CELL,
516 symtable.SCOPE_CELL_CLASS):
517 index = self.cell_vars[free]
518 else:
519 index = self.free_vars[free]
520 self.emit_op_arg(ops.LOAD_CLOSURE, index)
521 self.emit_op_arg(ops.BUILD_TUPLE, len(code.co_freevars))
522 self.load_const(code)
523 self.emit_op_arg(ops.MAKE_FUNCTION, oparg)
524
525 def _visit_kwonlydefaults(self, args):
526 defaults = 0
527 keys_w = []
528 for i, default in enumerate(args.kw_defaults):
529 if default:
530 kwonly = args.kwonlyargs[i]
531 assert isinstance(kwonly, ast.arg)
532 mangled = self.scope.mangle(kwonly.arg)
533 keys_w.append(self.space.newtext(mangled))
534 default.walkabout(self)
535 defaults += 1
536 if keys_w:
537 w_tup = self.space.newtuple(keys_w)
538 self.load_const(w_tup)
539 self.emit_op_arg(ops.BUILD_CONST_KEY_MAP, len(keys_w))
540 return defaults
541
542 def _visit_arg_annotation(self, name, ann, names, can_be_starred=False):
543 if ann:
544 if can_be_starred and isinstance(ann, ast.Starred):
545 ann.value.walkabout(self)
546 self.emit_op_arg(ops.UNPACK_SEQUENCE, 1)
547 else:
548 ann.walkabout(self)
549 names.append(self.scope.mangle(name))
550
551 def _visit_arg_annotations(self, args, names):
552 if args:
553 for arg in args:
554 assert isinstance(arg, ast.arg)
555 self._visit_arg_annotation(arg.arg, arg.annotation, names)
556
557 @specialize.argtype(1)
558 def _visit_annotations(self, func, args, returns):
559 space = self.space
560 names = []
561 self._visit_arg_annotations(args.posonlyargs, names)
562 self._visit_arg_annotations(args.args, names)
563 vararg = args.vararg
564 if vararg:
565 self._visit_arg_annotation(vararg.arg, vararg.annotation,
566 names, can_be_starred=True)
567 self._visit_arg_annotations(args.kwonlyargs, names)
568 kwarg = args.kwarg
569 if kwarg:
570 self._visit_arg_annotation(kwarg.arg, kwarg.annotation,
571 names)
572 self._visit_arg_annotation("return", returns, names)
573 l = len(names)
574 if l:
575 if l > 65534:
576 self.error("too many annotations", func)
577 w_tup = space.newtuple([space.newtext(name) for name in names])
578 self.load_const(w_tup)
579 self.emit_op_arg(ops.BUILD_CONST_KEY_MAP, l)
580 return l
581
582 def _visit_defaults(self, defaults):
583 assert len(defaults) > 0
584 w_tup = self._tuple_of_consts(defaults)
585 if w_tup:
586 self.update_position(defaults[-1])
587 self.load_const(w_tup)
588 else:
589 self.visit_sequence(defaults)
590 self.emit_op_arg(ops.BUILD_TUPLE, len(defaults))
591
592 @specialize.arg(2)
593 def _visit_function(self, func, function_code_generator):
594 # Load decorators first, but apply them after the function is created.
595 if func.decorator_list:
596 for dec in func.decorator_list:
597 if dec.lineno > 0:
598 self.update_position(dec)
599 dec.walkabout(self)
600
601 if func.lineno > 0:
602 self.update_position(func)
603
604 args = func.args
605
606 assert isinstance(args, ast.arguments)
607
608 oparg = 0
609
610 if args.defaults is not None and len(args.defaults):
611 oparg = oparg | 0x01
612 self._visit_defaults(args.defaults)
613
614 if args.kwonlyargs:
615 kw_default_count = self._visit_kwonlydefaults(args)
616 if kw_default_count:
617 oparg = oparg | 0x02
618
619 num_annotations = self._visit_annotations(func, args, func.returns)
620 if num_annotations:
621 oparg = oparg | 0x04
622
623 code, qualname = self.sub_scope(function_code_generator, func.name,
624 func, func.lineno)
625 self._make_function(code, oparg, qualname=qualname)
626 # Apply decorators.
627 if func.decorator_list:
628 n = len(func.decorator_list)
629 for i in range(n):
630 self.update_position(func.decorator_list[n - 1 - i])
631 self.emit_op_arg(ops.CALL_FUNCTION, 1)
632 self.update_position(func)
633 self.name_op(func.name, ast.Store, func)
634
635 def visit_FunctionDef(self, func):
636 self._visit_function(func, FunctionCodeGenerator)
637
638 def visit_AsyncFunctionDef(self, func):
639 self._visit_function(func, AsyncFunctionCodeGenerator)
640
641 @update_pos_expr
642 def visit_Lambda(self, lam):
643 args = lam.args
644 assert isinstance(args, ast.arguments)
645
646 oparg = 0
647 if args.defaults is not None and len(args.defaults):
648 oparg = oparg | 0x01
649 self._visit_defaults(args.defaults)
650
651 if args.kwonlyargs:
652 kw_default_count = self._visit_kwonlydefaults(args)
653 if kw_default_count:
654 oparg = oparg | 0x02
655 code, qualname = self.sub_scope(
656 LambdaCodeGenerator, "<lambda>", lam, lam.lineno)
657 self._make_function(code, oparg, qualname=qualname)
658
659 def visit_ClassDef(self, cls):
660 self.visit_sequence(cls.decorator_list)
661 # 1. compile the class body into a code object
662 code, qualname = self.sub_scope(
663 ClassCodeGenerator, cls.name, cls, cls.lineno)
664 # 2. load the 'build_class' function
665 self.emit_op(ops.LOAD_BUILD_CLASS)
666 # 3. load a function (or closure) made from the code object
667 self._make_function(code, qualname=qualname)
668 # 4. load class name
669 self.load_const(self.space.newtext(cls.name))
670 # 5. generate the rest of the code for the call
671 self._make_call(2, cls.bases, cls.keywords)
672 # 6. apply decorators
673 if cls.decorator_list:
674 n = len(cls.decorator_list)
675 for i in range(n):
676 self.update_position(cls.decorator_list[n - 1 - i])
677 self.emit_op_arg(ops.CALL_FUNCTION, 1)
678 self.update_position(cls)
679 # 7. store into <name>
680 self.name_op(cls.name, ast.Store, cls)
681
682 def visit_AugAssign(self, assign):
683 target = assign.target
684 if isinstance(target, ast.Attribute):
685 self.check_forbidden_name(target.attr, target)
686 target.value.walkabout(self)
687 self.emit_op(ops.DUP_TOP)
688 attr_col = target.end_col_offset - len(target.attr)
689 attr_position = (target.end_lineno, target.end_lineno, attr_col, target.end_col_offset)
690 self.update_position(attr_position)
691 self.emit_op_name(ops.LOAD_ATTR, self.names, target.attr)
692 assign.value.walkabout(self)
693 self.emit_op(inplace_operations(assign.op))
694 self.emit_op(ops.ROT_TWO)
695 self.emit_op_name(ops.STORE_ATTR, self.names, target.attr)
696 elif isinstance(target, ast.Subscript):
697 target.value.walkabout(self)
698 target.slice.walkabout(self)
699 self.emit_op(ops.DUP_TOP_TWO)
700 self.emit_op(ops.BINARY_SUBSCR)
701 assign.value.walkabout(self)
702 self.emit_op(inplace_operations(assign.op))
703 self.emit_op(ops.ROT_THREE)
704 self.emit_op(ops.STORE_SUBSCR)
705 elif isinstance(target, ast.Name):
706 self.name_op(target.id, ast.Load, target)
707 assign.value.walkabout(self)
708 self.emit_op(inplace_operations(assign.op))
709 self.name_op(target.id, ast.Store, target)
710 else:
711 self.error("illegal expression for augmented assignment", assign)
712
713 def _assert_test_always_true(self, test):
714 if isinstance(test, ast.Tuple):
715 return len(test.elts) > 0
716 if (isinstance(test, ast.Constant) and
717 self.space.isinstance_w(test.value, self.space.w_tuple)):
718 return self.space.len_w(test.value) > 0
719 return False
720
721 def visit_Assert(self, asrt):
722 if self._assert_test_always_true(asrt.test):
723 misc.syntax_warning(
724 self.space,
725 "assertion is always true, perhaps remove parentheses?",
726 self.compile_info.filename,
727 asrt.lineno,
728 asrt.col_offset
729 )
730 if self.compile_info.optimize >= 1:
731 return
732 assert self.compile_info.optimize == 0
733 test_constant = asrt.test.as_constant_truth(
734 self.space, self.compile_info)
735 if test_constant == optimize.CONST_FALSE:
736 self.emit_line_tracing_nop()
737 end = None
738 else:
739 end = self.new_block()
740 asrt.test.accept_jump_if(self, True, end)
741 self.emit_op(ops.LOAD_ASSERTION_ERROR)
742 if asrt.msg:
743 asrt.msg.walkabout(self)
744 self.emit_op_arg(ops.CALL_FUNCTION, 1)
745 self.emit_op_arg(ops.RAISE_VARARGS, 1)
746 if end is not None:
747 self.use_next_block(end)
748
749 def _binop(self, op):
750 return binary_operations(op)
751
752 @update_pos_expr
753 def visit_BinOp(self, binop):
754 binop.left.walkabout(self)
755 binop.right.walkabout(self)
756 self.emit_op(self._binop(binop.op))
757
758 def visit_Return(self, ret):
759 if ret.value is not None and self.scope.is_coroutine and self.scope.is_generator:
760 self.error("'return' with value in async generator", ret)
761 preserve_tos = ret.value is not None and not isinstance(ret.value, ast.Constant)
762 if preserve_tos:
763 ret.value.walkabout(self)
764 elif ret.value:
765 self.emit_line_tracing_nop(ret.value)
766 self.emit_line_tracing_nop(ret)
767 self.unwind_fblock_stack(preserve_tos, ret)
768 if ret.value is None:
769 self.load_const(self.space.w_None)
770 elif not preserve_tos:
771 value = ret.value
772 assert isinstance(value, ast.Constant)
773 # not using walkabout here because that might mess up line numbers
774 # if there is a finally block
775 self.load_const(value.value)
776 if not isinstance(self, AbstractFunctionCodeGenerator):
777 self.error("return outside function", ret)
778 self.emit_op(ops.RETURN_VALUE)
779
780 def visit_Delete(self, delete):
781 self.visit_sequence(delete.targets)
782
783 def visit_If(self, if_):
784 end = self.new_block()
785 saved_depth = self._stack_depth # break/return/continue in body can corrupt
786 test_constant = if_.test.as_constant_truth(
787 self.space, self.compile_info)
788 if test_constant == optimize.CONST_FALSE:
789 self.emit_line_tracing_nop()
790 with self.all_dead_code():
791 self._visit_body(if_.body)
792 self._visit_body(if_.orelse)
793 elif test_constant == optimize.CONST_TRUE:
794 self.emit_line_tracing_nop()
795 self._visit_body(if_.body)
796 with self.all_dead_code():
797 self._visit_body(if_.orelse)
798 else:
799 if if_.orelse:
800 otherwise = self.new_block()
801 else:
802 otherwise = end
803 if_.test.accept_jump_if(self, False, otherwise)
804 self._visit_body(if_.body)
805 if if_.orelse:
806 self.emit_jump_noline(ops.JUMP_FORWARD, end)
807 self.use_next_block(otherwise)
808 self._stack_depth = saved_depth
809 self._visit_body(if_.orelse)
810 self.use_next_block(end)
811 self._stack_depth = saved_depth
812
813 def visit_Break(self, br):
814 self.emit_line_tracing_nop()
815 loop_fblock = self.unwind_fblock_stack(False, br, find_loop_block=True)
816 if loop_fblock is None:
817 self.error("'break' not properly in loop", br)
818 self.unwind_fblock(loop_fblock, False)
819 assert loop_fblock.end is not None
820 self.emit_jump(ops.JUMP_ABSOLUTE, loop_fblock.end)
821
822 def visit_Continue(self, cont):
823 self.emit_line_tracing_nop()
824 loop_fblock = self.unwind_fblock_stack(False, cont, find_loop_block=True)
825 if loop_fblock is None:
826 self.error("'continue' not properly in loop", cont)
827 self.emit_jump(ops.JUMP_ABSOLUTE, loop_fblock.block)
828
829 def visit_For(self, fr):
830 start = self.new_block()
831 cleanup = self.new_block()
832 end = self.new_block()
833 # self.emit_jump(ops.SETUP_LOOP, end)
834 self.push_frame_block(F_FOR_LOOP, start, end)
835 saved_depth = self._stack_depth
836 fr.iter.walkabout(self)
837 self.emit_op(ops.GET_ITER)
838 self.use_next_block(start)
839 self.emit_jump(ops.FOR_ITER, cleanup)
840 fr.target.walkabout(self)
841 self._visit_body(fr.body)
842 self.no_position_info()
843 self.emit_jump(ops.JUMP_ABSOLUTE, start)
844 self.use_next_block(cleanup)
845 # Restore: FOR_ITER exhaustion pops the iterator; depth is back to pre-loop.
846 self._stack_depth = saved_depth
847 self.pop_frame_block(F_FOR_LOOP, start)
848 self._visit_body(fr.orelse)
849 self.use_next_block(end)
850
851 def visit_AsyncFor(self, fr):
852 if not self._check_async_function():
853 self.error("'async for' outside async function", fr)
854 b_start = self.new_block()
855 b_except = self.new_block()
856 b_reraise = self.new_block()
857 b_end = self.new_block()
858
859 fr.iter.walkabout(self)
860 self.emit_op(ops.GET_AITER)
861
862 self.use_next_block(b_start)
863 self.push_frame_block(F_FOR_LOOP, b_start, b_end)
864
865 b_anext = self.use_next_block()
866 b_after_yield = self.new_block()
867 # Narrow SETUP_FINALLY/POP_BLOCK pair covering only GET_ANEXT/YIELD_FROM.
868 # The inner scope overrides any enclosing SETUP_WITH/SETUP_ASYNC_WITH for
869 # these two instructions, routing StopAsyncIteration to b_except.
870 self.emit_jump(_SETUP_FINALLY, b_except)
871 self.emit_op(ops.GET_ANEXT)
872 self.load_const(self.space.w_None)
873 self.emit_op(ops.YIELD_FROM)
874 self.emit_op(_POP_BLOCK)
875 self.use_next_block(b_after_yield)
876 fr.target.walkabout(self)
877 self._visit_body(fr.body)
878 self.no_position_info()
879 self.emit_jump(ops.JUMP_ABSOLUTE, b_start)
880 self.pop_frame_block(F_FOR_LOOP, b_start)
881
882 self._emit_async_for_handler(b_except, b_reraise, b_end,
883 position_node=fr.iter, orelse=fr.orelse)
884
885 def _emit_async_for_handler(self, b_except, b_reraise, b_end,
886 position_node=None, orelse=None):
887 """Emit the StopAsyncIteration-checking exception handler block shared
888 by visit_AsyncFor and _comp_async_generator.
889
890 Covers: use_next_block(b_except) ... use_next_block(b_end).
891 position_node: if given, update source position before PUSH_EXC_INFO.
892 orelse: if given, visit those nodes before jumping to b_end."""
893 # Exception table handler for GET_ANEXT / YIELD_FROM.
894 # Entry stack (from table dispatch): [..., aiter, w_exc].
895 self.use_next_block(b_except)
896 if position_node is not None:
897 self.update_position(position_node)
898 self.emit_op(ops.PUSH_EXC_INFO)
899 # Stack: [..., aiter, w_prev, w_exc]
900 # StopAsyncIteration is a builtin; emit LOAD_GLOBAL directly because
901 # this name is not in the scope table (user code never wrote it).
902 self.emit_op_arg(ops.LOAD_GLOBAL, self.add_name(self.names, "StopAsyncIteration"))
903 self.emit_op(ops.CHECK_EXC_MATCH)
904 self.emit_jump(ops.POP_JUMP_IF_FALSE, b_reraise)
905 # StopAsyncIteration: normal end of iteration.
906 self.emit_op(ops.POP_TOP) # pop w_exc
907 self.emit_op(ops.POP_EXCEPT) # pop w_prev, restore sys.exc_info
908 self.emit_op(ops.POP_TOP) # pop aiter
909 if orelse is not None:
910 self._visit_body(orelse)
911 self.emit_jump(ops.JUMP_ABSOLUTE, b_end)
912
913 # Non-StopAsyncIteration: re-raise into the enclosing handler.
914 # Stack: [..., aiter, prev, exc]. Restore sys.exc_info (POP_EXCEPT
915 # on prev), drop aiter, then RERAISE 0 with just exc on top. Use
916 # ROT_THREE to move exc below aiter+prev, POP_EXCEPT prev, POP_TOP
917 # aiter, RERAISE 0 exc.
918 self.use_next_block(b_reraise)
919 self.emit_op(ops.ROT_THREE) # [aiter, prev, exc] -> [exc, aiter, prev]
920 self.emit_op(ops.POP_EXCEPT) # pop prev, restore sys.exc_info
921 self.emit_op(ops.POP_TOP) # pop aiter
922 self.emit_op_arg(ops.RERAISE, 0)
923
924 self.use_next_block(b_end)
925
926 def visit_While(self, wh):
927 test_constant = wh.test.as_constant_truth(self.space, self.compile_info)
928 if test_constant == optimize.CONST_FALSE:
929 self.emit_line_tracing_nop()
930 with self.all_dead_code():
931 end = self.new_block()
932 loop = self.new_block()
933 self.push_frame_block(F_WHILE_LOOP, loop, end)
934 self._visit_body(wh.body)
935 self.pop_frame_block(F_WHILE_LOOP, loop)
936 self._visit_body(wh.orelse)
937 else:
938 end = self.new_block()
939 anchor = None
940 if test_constant == optimize.CONST_NOT_CONST:
941 anchor = self.new_block()
942 loop = self.new_block()
943 self.push_frame_block(F_WHILE_LOOP, loop, end)
944 self.use_next_block(loop)
945 if test_constant == optimize.CONST_NOT_CONST:
946 wh.test.accept_jump_if(self, False, anchor)
947 else:
948 self.emit_line_tracing_nop()
949 self._visit_body(wh.body)
950 self.no_position_info()
951 self.emit_jump(ops.JUMP_ABSOLUTE, loop)
952 if test_constant == optimize.CONST_NOT_CONST:
953 self.use_next_block(anchor)
954 self.pop_frame_block(F_WHILE_LOOP, loop)
955 self._visit_body(wh.orelse)
956 self.use_next_block(end)
957
958 def _visit_try_except(self, tr):
959 # copies CPython compiler_try_except (compile.c)
960 #
961 # try_body ; table: body -> exc (lasti=False)
962 # [orelse]
963 # JUMP_FORWARD end ; skip handlers
964 # <exc handler entry>
965 # SETUP_CLEANUP outer_cleanup
966 # PUSH_EXC_INFO ; stack: [prev, exc]
967 # (for each handler i:)
968 # check_i ; table entry i: check + STORE -> outer_cleanup (lasti=True)
969 # body_i ; table: body_i -> inner_cleanup_i (lasti=True)
970 # POP_EXCEPT; LOAD None; STORE name; DEL name; JUMP end
971 # inner_cleanup_i: ; stack [prev, lasti, exc]
972 # LOAD None; STORE name; DEL name
973 # RERAISE 1
974 # no_match:
975 # RERAISE 0 ; caught by outer_cleanup
976 # outer_cleanup: ; stack [prev, lasti, exc]
977 # COPY 3; POP_EXCEPT; RERAISE 1
978 # end:
979 body = self.new_block()
980 exc = self.new_block()
981 end = self.new_block()
982 outer_cleanup = self.new_block()
983 saved_depth = self._stack_depth
984 body = self.use_next_block(body)
985 self.emit_jump(_SETUP_FINALLY, exc) # open try-body scope; seeds exc.forced_initial_depth
986 self.push_frame_block(F_TRY_EXCEPT, body)
987 self._visit_body(tr.body)
988 self.pop_frame_block(F_TRY_EXCEPT, body)
989 self.no_position_info()
990 self.emit_op(_POP_BLOCK) # close try-body scope
991 self._visit_body(tr.orelse)
992 self.emit_jump_noline(ops.JUMP_FORWARD, end)
993 self.use_next_block(exc)
994 # stack: [..., prev_exc, exc] (after PUSH_EXC_INFO executed at handler entry)
995 self.emit_jump(_SETUP_CLEANUP, outer_cleanup) # open outer scope; seeds forced_initial_depth
996 self.emit_op(ops.PUSH_EXC_INFO)
997 self.push_frame_block(F_EXCEPTION_HANDLER, None)
998 handler = None
999 for i, handler in enumerate(tr.handlers):
1000 assert isinstance(handler, ast.ExceptHandler)
1001 self.update_position(handler)
1002 next_except = self.new_block()
1003 if handler.type:
1004 handler.type.walkabout(self)
1005 self.emit_op(ops.CHECK_EXC_MATCH)
1006 self.emit_jump(ops.POP_JUMP_IF_FALSE, next_except)
1007 else:
1008 if i != len(tr.handlers) - 1:
1009 self.error(
1010 "bare 'except:' must be the last except block", handler)
1011 cleanup_end = self.new_block()
1012 if handler.name:
1013 self.name_op(handler.name, ast.Store, handler)
1014 else:
1015 self.emit_op(ops.POP_TOP) # pop exc, stack: [prev_exc]
1016 cleanup_body = self.use_next_block()
1017 # Open inner cleanup scope for the handler body; seeds cleanup_end.forced_initial_depth.
1018 # The outer_cleanup scope (opened above PUSH_EXC_INFO) covers the check region.
1019 self.emit_jump(_SETUP_CLEANUP, cleanup_end)
1020 if handler.name:
1021 self.push_frame_block(F_HANDLER_CLEANUP, cleanup_body, None, handler)
1022 else:
1023 self.push_frame_block(F_HANDLER_CLEANUP, cleanup_body)
1024 self._visit_body(handler.body)
1025 self.pop_frame_block(F_HANDLER_CLEANUP, cleanup_body)
1026 self.no_position_info()
1027 self.emit_op(_POP_BLOCK) # close inner cleanup scope
1028 self.emit_op(_POP_BLOCK) # close outer_cleanup scope
1029 self.emit_op(ops.POP_EXCEPT)
1030 if handler.name:
1031 self.load_const(self.space.w_None)
1032 self.name_op(handler.name, ast.Store, handler)
1033 self.name_op(handler.name, ast.Del, handler)
1034 self.emit_jump(ops.JUMP_FORWARD, end)
1035
1036 # cleanup_end (inner cleanup): reached by exception table when the
1037 # handler body raises. Stack [prev, lasti, exc]. Clear the name,
1038 # then RERAISE 1 reads lasti, pops exc, reraises. The reraise is
1039 # caught by the next outer_cleanup table entry (added on the next
1040 # loop iteration, or after the loop for the last handler).
1041 self.use_next_block(cleanup_end)
1042 self.no_position_info()
1043 if handler.name:
1044 self.load_const(self.space.w_None)
1045 self.name_op(handler.name, ast.Store, handler)
1046 self.name_op(handler.name, ast.Del, handler)
1047 self.emit_op_arg(ops.RERAISE, 1)
1048 self.use_next_block(next_except)
1049 if handler is not None:
1050 self.update_position(handler)
1051 self.pop_frame_block(F_EXCEPTION_HANDLER, None)
1052 # no_match: fallthrough from the last POP_JUMP_IF_FALSE. Stack
1053 # [prev, lasti, exc]. RERAISE 0 pops exc and reraises; caught by
1054 # the outer_cleanup scope opened above PUSH_EXC_INFO.
1055 self.emit_op_arg(ops.RERAISE, 0)
1056 self.emit_op(_POP_BLOCK) # close outer_cleanup scope
1057
1058 # outer_cleanup: reached when a handler's code or the no-match path
1059 # raises. Stack [prev, lasti, exc]. COPY 3 duplicates prev,
1060 # POP_EXCEPT pops the duplicate and restores sys.exc_info to prev,
1061 # RERAISE 1 reads lasti and reraises exc upward. Any enclosing
1062 # with-statement's SETUP_WITH scope naturally covers this block.
1063 self.use_next_block(outer_cleanup)
1064 self.no_position_info()
1065 self.emit_op_arg(ops.COPY, 3)
1066 self.emit_op(ops.POP_EXCEPT)
1067 self.emit_op_arg(ops.RERAISE, 1)
1068 self.use_next_block(end)
1069 # Restore: try/except is stack-neutral.
1070 self._stack_depth = saved_depth
1071
1072 def _visit_try_finally(self, tr, has_handlers, trybody, finalbody):
1073 body = self.new_block()
1074 end = self.new_block()
1075 exit = self.new_block()
1076 # CPython 3.11-parity layout: body -> end (depth=0, no lasti), handler
1077 # does PUSH_EXC_INFO + finally body + RERAISE 0. An outer_cleanup
1078 # covering the PUSH_EXC_INFO...RERAISE 0 range catches reraises from
1079 # it and emits COPY 3; POP_EXCEPT; RERAISE 1 -- restoring sys.exc_info
1080 # and propagating with the original raise site preserved in lasti.
1081 outer_cleanup = self.new_block()
1082
1083 saved_depth = self._stack_depth
1084 body = self.use_next_block(body)
1085 self.emit_jump(_SETUP_FINALLY, end) # open try-body scope; seeds end.forced_initial_depth
1086 self.push_frame_block(F_FINALLY_TRY, body, end, tr)
1087 if has_handlers:
1088 if isinstance(tr, ast.Try):
1089 self._visit_try_except(tr)
1090 else:
1091 assert isinstance(tr, ast.TryStar)
1092 self._visit_try_except_star(tr)
1093 else:
1094 self._visit_body(trybody)
1095 self.no_position_info()
1096 self.emit_op(_POP_BLOCK) # close try-body scope
1097
1098 # finally block, unexceptional case: inline (CPython: VISIT_SEQ finalbody then JUMP exit)
1099 self.pop_frame_block(F_FINALLY_TRY, body)
1100 self._visit_body(finalbody)
1101 self.emit_jump_noline(ops.JUMP_FORWARD, exit)
1102
1103 # finally block, exceptional case: stack at entry is [exc] (depth 1).
1104 self.no_position_info() # SETUP_CLEANUP/PUSH_EXC_INFO are artificial; line event must
1105 self.use_next_block(end) # fire at the first real statement of the finally body so that
1106 self.emit_jump(_SETUP_CLEANUP, outer_cleanup) # open outer scope; seeds forced_initial_depth
1107 self.emit_op(ops.PUSH_EXC_INFO)
1108 self.push_frame_block(F_FINALLY_END, end)
1109 self._visit_body(finalbody)
1110 self.pop_frame_block(F_FINALLY_END, end)
1111 # RERAISE 0 pops exc and reraises; caught by outer_cleanup scope.
1112 # Keep current line (last line of finally body) -- matches CPython.
1113 self.emit_op_arg(ops.RERAISE, 0)
1114 self.emit_op(_POP_BLOCK) # close outer_cleanup scope
1115
1116 # outer_cleanup: re-entry with [prev, lasti, exc]; COPY 3 duplicates prev,
1117 # POP_EXCEPT restores sys.exc_info, RERAISE 1 reads lasti and reraises.
1118 # Any enclosing with-statement's SETUP_WITH scope naturally covers this.
1119 # Keep current line so _marklines finds the finally-body end line here,
1120 # allowing fset_f_lineno to detect this as an exception-handler target.
1121 self.use_next_block(outer_cleanup)
1122 self.emit_op_arg(ops.COPY, 3)
1123 self.emit_op(ops.POP_EXCEPT)
1124 self.emit_op_arg(ops.RERAISE, 1)
1125 self.use_next_block(exit)
1126 # Restore depth counter: try/finally is stack-neutral.
1127 self._stack_depth = saved_depth
1128
1129
1130 def visit_Try(self, tr):
1131 self.update_position(tr)
1132 self.emit_op(ops.NOP)
1133 if tr.finalbody:
1134 return self._visit_try_finally(
1135 tr, bool(tr.handlers), tr.body, tr.finalbody)
1136 else:
1137 return self._visit_try_except(tr)
1138
1139 def visit_TryStar(self, tr):
1140 self.update_position(tr)
1141 self.emit_op(ops.NOP)
1142 if tr.finalbody:
1143 return self._visit_try_finally(
1144 tr, bool(tr.handlers), tr.body, tr.finalbody)
1145 else:
1146 return self._visit_try_except_star(tr)
1147
1148 def _visit_try_except_star(self, tr):
1149 # copies cpython compiler_try_star_except
1150 """
1151 Code generated for "try: S except* E1 as V1: S1 except* E2 as V2: S2 ...":
1152 (The contents of the value stack is shown in [], with the top
1153 at the right; 'tb' is trace-back info, 'val' the exception instance,
1154 and 'typ' the exception's type.)
1155
1156 Value stack Label Instruction Argument
1157 [] SETUP_FINALLY L1 TODO: is SETUP_EXCEPT
1158 [] <code for S>
1159 [] POP_BLOCK
1160 [] JUMP L0
1161
1162 [exc] L1: COPY 1 ) save copy of the original exception
1163 [orig, exc] BUILD_LIST ) list for raised/reraised excs ("result")
1164 [orig, exc, res] SWAP 2 TODO: can use ROT_TWO?
1165
1166 [orig, res, exc] <evaluate E1>
1167 [orig, res, exc, E1] CHECK_EG_MATCH: # TODO: new bytecode
1168 [orig, res, rest/exc, match?] COPY 1 # TODO: DUP
1169 [orig, res, rest/exc, match?, match?] POP_JUMP_IF_NONE C1 # TODO: use LOAD_CONST(None), IS_OP, POP_JUMP_IF_TRUE
1170
1171 [orig, res, rest, match] <assign to V1> (or POP if no V1) # TODO: also delete after block!
1172
1173 [orig, res, rest] SETUP_FINALLY R1: TODO: is SETUP_EXCEPT?
1174 [orig, res, rest] <code for S1>
1175 [orig, res, rest] JUMP L2 TODO: missing POP_BLOCK before the jump?
1176
1177 [orig, res, rest, i, v] R1: LIST_APPEND 3 ) exc raised in except* body - add to res
1178 [orig, res, rest, i] POP
1179 [orig, res, rest] JUMP LE2
1180
1181 [orig, res, rest] L2: NOP ) for lineno
1182 [orig, res, rest] JUMP LE2
1183
1184 [orig, res, rest/exc, None] C1: POP
1185
1186 [orig, res, rest] LE2: <evaluate E2>
1187 .............................etc.......................
1188
1189 [orig, res, rest] Ln+1: LIST_APPEND 1 ) add unhandled exc to res (could be None)
1190
1191 [orig, res] PREP_RERAISE_STAR: TODO: implement me
1192 [exc] COPY 1
1193 [exc, exc] POP_JUMP_IF_NOT_NONE RER: TODO: don't have POP_JUMP_IF_NOT_NONE
1194 [exc] POP_TOP
1195 TODO: missing in cpython comment: POP_EXCEPT
1196 [] JUMP L0
1197
1198 [exc] RER: SWAP 2
1199 [exc, prev_exc_info] POP_EXCEPT
1200 [exc] RERAISE 0
1201
1202 [] L0: <next statement>
1203 """
1204 body = self.new_block()
1205 exc = self.new_block()
1206 orelse = self.new_block()
1207 end = self.new_block()
1208 cleanup = self.new_block()
1209 reraise_star = self.new_block()
1210
1211 saved_depth = self._stack_depth
1212 body = self.use_next_block(body)
1213 self.emit_jump(_SETUP_FINALLY, exc)
1214 self.push_frame_block(F_TRY_EXCEPT, body)
1215 self._visit_body(tr.body)
1216 self.pop_frame_block(F_TRY_EXCEPT, body)
1217 self.no_position_info()
1218 self.emit_op(_POP_BLOCK)
1219 self.emit_jump(ops.JUMP_FORWARD, orelse)
1220
1221 self.use_next_block(exc)
1222 self.no_position_info()
1223 self.emit_jump(_SETUP_CLEANUP, cleanup)
1224 self.emit_op(ops.PUSH_EXC_INFO)
1225 self.push_frame_block(F_EXCEPTION_GROUP_HANDLER, None)
1226
1227 n = len(tr.handlers)
1228 for i, handler in enumerate(tr.handlers):
1229 assert isinstance(handler, ast.ExceptHandler)
1230 self.update_position(handler)
1231
1232 except_block = self.new_block() # NOP block (holds propagated lineno)
1233 except_with_error = self.new_block() # merge point
1234 no_match = self.new_block()
1235
1236 assert handler.type is not None
1237 if i == 0:
1238 self.emit_op_arg(ops.COPY, 1)
1239 self.emit_op(ops.BUILD_LIST)
1240 self.emit_op_arg(ops.SWAP, 2)
1241
1242 handler.type.walkabout(self)
1243 self.emit_op(ops.CHECK_EG_MATCH)
1244 self.emit_op_arg(ops.COPY, 1)
1245 self.emit_jump(ops.POP_JUMP_FORWARD_IF_NONE, no_match)
1246
1247 cleanup_end = self.new_block()
1248 cleanup_body = self.new_block()
1249
1250 if handler.name is not None:
1251 self.name_op(handler.name, ast.Store, handler)
1252 else:
1253 self.emit_op(ops.POP_TOP)
1254
1255 cleanup_body = self.use_next_block(cleanup_body)
1256 self.emit_jump(_SETUP_CLEANUP, cleanup_end)
1257 if handler.name:
1258 self.push_frame_block(F_HANDLER_CLEANUP, cleanup_body, None, handler)
1259 else:
1260 self.push_frame_block(F_HANDLER_CLEANUP, cleanup_body)
1261 self._visit_body(handler.body)
1262 self.pop_frame_block(F_HANDLER_CLEANUP, cleanup_body)
1263 self.no_position_info()
1264 self.emit_op(_POP_BLOCK)
1265 if handler.name:
1266 self.load_const(self.space.w_None)
1267 self.name_op(handler.name, ast.Store, handler)
1268 self.name_op(handler.name, ast.Del, handler)
1269 self.emit_jump(ops.JUMP_FORWARD, except_block)
1270
1271 self.use_next_block(cleanup_end)
1272 self.no_position_info()
1273 if handler.name:
1274 self.load_const(self.space.w_None)
1275 self.name_op(handler.name, ast.Store, handler)
1276 self.name_op(handler.name, ast.Del, handler)
1277 self.emit_op_arg(ops.LIST_APPEND, 3)
1278 self.emit_op(ops.POP_TOP) # lasti
1279 self.emit_jump(ops.JUMP_FORWARD, except_with_error)
1280
1281 self.use_next_block(except_block)
1282 self.emit_op(ops.NOP)
1283 self.emit_jump(ops.JUMP_FORWARD, except_with_error)
1284
1285 self.use_next_block(no_match)
1286 self.emit_op(ops.POP_TOP) # match (None)
1287
1288 self.use_next_block(except_with_error)
1289
1290 if i == n - 1:
1291 self.emit_op_arg(ops.LIST_APPEND, 1)
1292 self.emit_jump(ops.JUMP_FORWARD, reraise_star)
1293
1294 self.no_position_info()
1295 self.pop_frame_block(F_EXCEPTION_GROUP_HANDLER, None)
1296
1297 reraise = self.new_block()
1298
1299 self.use_next_block(reraise_star)
1300 self.emit_op(ops.PREP_RERAISE_STAR)
1301 self.emit_op_arg(ops.COPY, 1)
1302 self.emit_jump(ops.POP_JUMP_FORWARD_IF_NOT_NONE, reraise)
1303
1304 self.emit_op(ops.POP_TOP)
1305 self.emit_op(_POP_BLOCK)
1306 self.emit_op(ops.POP_EXCEPT)
1307 self.emit_jump(ops.JUMP_FORWARD, end)
1308
1309 self.use_next_block(reraise)
1310 self.emit_op(_POP_BLOCK)
1311 self.emit_op_arg(ops.SWAP, 2)
1312 self.emit_op(ops.POP_EXCEPT)
1313 self.emit_op(ops.RERAISE)
1314
1315 self.use_next_block(cleanup)
1316 self.no_position_info()
1317 self.emit_op_arg(ops.COPY, 3)
1318 self.emit_op(ops.POP_EXCEPT)
1319 self.emit_op_arg(ops.RERAISE, 1)
1320
1321 self.use_next_block(orelse)
1322 self._stack_depth = saved_depth
1323 self._visit_body(tr.orelse)
1324 self.use_next_block(end)
1325 self._stack_depth = saved_depth
1326
1327 def _import_as(self, alias, imp):
1328 # in CPython this is roughly compile_import_as
1329 # The IMPORT_NAME opcode was already generated. This function
1330 # merely needs to bind the result to a name.
1331
1332 # If there is a dot in name, we need to split it and emit a
1333 # IMPORT_FROM for each name.
1334 source_name = alias.name
1335 dot = source_name.find(".")
1336 if dot > 0:
1337 # Consume the base module name to get the first attribute
1338 while True:
1339 start = dot + 1
1340 dot = source_name.find(".", start)
1341 if dot < 0:
1342 end = len(source_name)
1343 else:
1344 end = dot
1345 attr = source_name[start:end]
1346 self.emit_op_name(ops.IMPORT_FROM, self.names, attr)
1347 if dot < 0:
1348 break
1349 self.emit_op(ops.ROT_TWO)
1350 self.emit_op(ops.POP_TOP)
1351 self.name_op(alias.asname, ast.Store, imp)
1352 self.emit_op(ops.POP_TOP)
1353 return
1354 self.name_op(alias.asname, ast.Store, imp)
1355
1356 def visit_Import(self, imp):
1357 for alias in imp.names:
1358 assert isinstance(alias, ast.alias)
1359 level = 0
1360 self.load_const(self.space.newint(level))
1361 self.load_const(self.space.w_None)
1362 self.emit_op_name(ops.IMPORT_NAME, self.names, alias.name)
1363 # If there's no asname then we store the root module. If there is
1364 # an asname, _import_as stores the last module of the chain into it.
1365 if alias.asname:
1366 self._import_as(alias, imp)
1367 else:
1368 dot = alias.name.find(".")
1369 if dot < 0:
1370 store_name = alias.name
1371 else:
1372 store_name = alias.name[:dot]
1373 self.name_op(store_name, ast.Store, imp)
1374
1375 def visit_ImportFrom(self, imp):
1376 space = self.space
1377 first = imp.names[0]
1378 assert isinstance(first, ast.alias)
1379 star_import = len(imp.names) == 1 and first.name == "*"
1380 # Various error checking for future imports.
1381 if imp.module == "__future__":
1382 last_line, last_offset = self.compile_info.last_future_import
1383 if imp.lineno > last_line or \
1384 imp.lineno == last_line and imp.col_offset > last_offset:
1385 self.error("__future__ statements must appear at beginning "
1386 "of file", imp)
1387 if star_import:
1388 self.error("* not valid in __future__ imports", imp)
1389 compiler = space.createcompiler()
1390 for alias in imp.names:
1391 assert isinstance(alias, ast.alias)
1392 if alias.name not in compiler.future_flags.compiler_features:
1393 if alias.name == "braces":
1394 self.error("not a chance", imp)
1395 self.error("future feature %s is not defined" %
1396 (alias.name,), imp)
1397 self.load_const(space.newint(imp.level))
1398 names_w = [None]*len(imp.names)
1399 for i in range(len(imp.names)):
1400 alias = imp.names[i]
1401 assert isinstance(alias, ast.alias)
1402 names_w[i] = space.newtext(alias.name)
1403 self.load_const(space.newtuple(names_w))
1404 if imp.module:
1405 mod_name = imp.module
1406 else:
1407 # In the case of a relative import.
1408 mod_name = ""
1409 self.emit_op_name(ops.IMPORT_NAME, self.names, mod_name)
1410 if star_import:
1411 self.emit_op(ops.IMPORT_STAR)
1412 else:
1413 for alias in imp.names:
1414 assert isinstance(alias, ast.alias)
1415 self.emit_op_name(ops.IMPORT_FROM, self.names, alias.name)
1416 if alias.asname:
1417 store_name = alias.asname
1418 else:
1419 store_name = alias.name
1420 self.name_op(store_name, ast.Store, imp)
1421 self.emit_op(ops.POP_TOP)
1422
1423 def visit_Assign(self, assign):
1424 if self._optimize_unpacking(assign):
1425 return
1426 assign.value.walkabout(self)
1427 duplications = len(assign.targets) - 1
1428 for i in range(len(assign.targets)):
1429 if i < duplications:
1430 self.emit_op(ops.DUP_TOP)
1431 assign.targets[i].walkabout(self)
1432
1433 def _optimize_unpacking(self, assign):
1434 """Try to optimize out BUILD_TUPLE and UNPACK_SEQUENCE opcodes."""
1435 if len(assign.targets) != 1:
1436 return False
1437 targets = assign.targets[0].as_node_list(self.space)
1438 if targets is None:
1439 return False
1440 values = assign.value.as_node_list(self.space)
1441 if values is None:
1442 return False
1443 targets_count = len(targets)
1444 values_count = len(values)
1445 if targets_count != values_count:
1446 return False
1447 for value in values:
1448 if isinstance(value, ast.Starred):
1449 return False # more complicated
1450 for target in targets:
1451 if not isinstance(target, ast.Name):
1452 if isinstance(target, ast.Starred):
1453 # these require extra checks
1454 return False
1455 break
1456 else:
1457 self.visit_sequence(values)
1458 seen_names = {}
1459 for i in range(targets_count - 1, -1, -1):
1460 target = targets[i]
1461 assert isinstance(target, ast.Name)
1462 if target.id not in seen_names:
1463 seen_names[target.id] = True
1464 self.name_op(target.id, ast.Store, target)
1465 else:
1466 self.emit_op(ops.POP_TOP)
1467 return True
1468 if values_count > 3:
1469 return False
1470 self.visit_sequence(values)
1471 if values_count == 2:
1472 self.emit_op(ops.ROT_TWO)
1473 elif values_count == 3:
1474 self.emit_op(ops.ROT_THREE)
1475 self.emit_op(ops.ROT_TWO)
1476 self.visit_sequence(targets)
1477 return True
1478
1479 def _annotation_evaluate(self, item):
1480 # PEP 526 requires that some things be evaluated, to avoid bugs
1481 # where a non-assigning variable annotation references invalid items
1482 # this is effectively a NOP, but will fail if e.g. item is an
1483 # Attribute and one of the chained names does not exist
1484 item.walkabout(self)
1485 self.emit_op(ops.POP_TOP)
1486
1487 def _annotation_eval_slice(self, target):
1488 if isinstance(target, ast.Slice):
1489 for val in [target.lower, target.upper, target.step]:
1490 if val:
1491 self._annotation_evaluate(val)
1492 elif isinstance(target, ast.Tuple):
1493 for val in target.elts:
1494 self._annotation_eval_slice(val)
1495 else:
1496 self._annotation_evaluate(target)
1497
1498 def visit_AnnAssign(self, assign):
1499 target = assign.target
1500 # if there's an assignment to be done, do it
1501 if assign.value:
1502 assign.value.walkabout(self)
1503 target.walkabout(self)
1504 # the PEP requires that certain parts of the target be evaluated at runtime
1505 # to avoid silent annotation-related errors
1506 if isinstance(target, ast.Name):
1507 self.check_forbidden_name(target.id, assign)
1508 # if it's just a simple name and we're not in a function, store
1509 # the annotation in __annotations__
1510 if assign.simple and not isinstance(self.scope, symtable.FunctionScope):
1511 assign.annotation.walkabout(self)
1512 self.emit_op_arg(ops.LOAD_NAME, self.add_name(self.names, '__annotations__'))
1513 name = target.id
1514 w_name = self.space.newtext(self.scope.mangle(name))
1515 self.load_const(misc.intern_if_common_string(self.space, w_name))
1516 self.emit_op(ops.STORE_SUBSCR)
1517 elif isinstance(target, ast.Attribute):
1518 # the spec requires that `a.b: int` evaluates `a`
1519 # and in a non-function scope, also evaluates `int`
1520 # (N.B.: if the target is of the form `a.b.c`, `a.b` will be evaluated)
1521 self.check_forbidden_name(target.attr, assign)
1522 if not assign.value:
1523 attr = target.value
1524 self._annotation_evaluate(attr)
1525 elif isinstance(target, ast.Subscript):
1526 if not assign.value:
1527 # similar to the above, `a[0:5]: int` evaluates the name and the slice argument
1528 # and if not in a function, also evaluates the annotation
1529 sl = target.slice
1530 self._annotation_evaluate(target.value)
1531 self._annotation_eval_slice(sl)
1532 else:
1533 self.error("can't handle annotation with %s" % (target,), target)
1534 # if this is not in a function, evaluate the annotation
1535 if not (assign.simple or isinstance(self.scope, symtable.FunctionScope)):
1536 self._annotation_evaluate(assign.annotation)
1537
1538
1539 def visit_With(self, wih):
1540 self.handle_withitem(wih, 0, is_async=False)
1541
1542 @specialize.argtype(1)
1543 def handle_withitem(self, wih, pos, is_async):
1544 body_block = self.new_block()
1545 cleanup = self.new_block()
1546 witem = wih.items[pos]
1547 assert isinstance(witem, ast.withitem)
1548 witem.context_expr.walkabout(self)
1549 if not is_async:
1550 self.emit_op(ops.BEFORE_WITH)
1551 self.emit_jump(_SETUP_WITH, cleanup)
1552 fblock_kind = F_WITH
1553 else:
1554 self.emit_op(ops.BEFORE_ASYNC_WITH)
1555 self.emit_op_arg(ops.GET_AWAITABLE, 1)
1556 self.load_const(self.space.w_None)
1557 self.emit_op(ops.YIELD_FROM)
1558 self.emit_jump(_SETUP_WITH, cleanup)
1559 fblock_kind = F_ASYNC_WITH
1560
1561 normal_exit = self.new_block()
1562 body_block = self.use_next_block(body_block)
1563 self.push_frame_block(fblock_kind, body_block, cleanup, witem)
1564 if witem.optional_vars:
1565 witem.optional_vars.walkabout(self)
1566 else:
1567 self.emit_op(ops.POP_TOP)
1568 if pos == len(wih.items) - 1:
1569 self._visit_body(wih.body)
1570 else:
1571 self.handle_withitem(wih, pos + 1, is_async=is_async)
1572
1573 self.no_position_info()
1574 self.pop_frame_block(fblock_kind, body_block)
1575 # Always emit _POP_BLOCK to close the _SETUP_WITH scope on the
1576 # fall-through (normal exit) path. When the body contains an early
1577 # return/break/continue, unwind_fblock already emitted _POP_BLOCK on
1578 # that code path; this _POP_BLOCK closes the scope on the fall-through
1579 # path. The two _POP_BLOCKs are on separate control-flow paths, so
1580 # they do not double-close. If the fall-through is dead code (every
1581 # body path exits early), emit_op is a no-op on a dead block, and
1582 # use_next_block below creates an unreachable block that is removed.
1583 self.emit_op(_POP_BLOCK)
1584 self.use_next_block(normal_exit)
1585
1586 self.update_position(wih)
1587 # end of body, successful outcome, start cleanup
1588 self.call_exit_with_nones()
1589 if is_async:
1590 self.emit_op_arg(ops.GET_AWAITABLE, 2)
1591 self.load_const(self.space.w_None)
1592 self.emit_op(ops.YIELD_FROM)
1593 self.emit_op(ops.POP_TOP)
1594 exit = self.new_block()
1595 self.emit_jump(ops.JUMP_ABSOLUTE, exit)
1596
1597 # exceptional outcome: _SETUP_WITH opened lasti=True scope, so on
1598 # exception the stack on entry to `cleanup` is [..., __exit__, lasti, exc].
1599 # After PUSH_EXC_INFO: [..., __exit__, lasti, prev_exc, exc].
1600 # WITH_EXCEPT_START peeks __exit__ at depth 3 and pushes __exit__'s
1601 # return value. If truthy: consume exc/prev/lasti/__exit__ and restore
1602 # exc_info. If falsy: RERAISE 2 propagates.
1603 with_cleanup = self.new_block()
1604 self.use_next_block(cleanup) # resets _stack_depth to cleanup.forced_initial_depth
1605 self.update_position(wih)
1606 # Open inner scope for PUSH_EXC_INFO..RERAISE 2; seeds with_cleanup.forced_initial_depth.
1607 self.emit_jump(_SETUP_CLEANUP, with_cleanup)
1608 self.emit_op(ops.PUSH_EXC_INFO)
1609 self.emit_op(ops.WITH_EXCEPT_START)
1610 if is_async:
1611 self.emit_op_arg(ops.GET_AWAITABLE, 2)
1612 self.load_const(self.space.w_None)
1613 self.emit_op(ops.YIELD_FROM)
1614 rest_of_handler = self.new_block()
1615 self.use_next_block(rest_of_handler)
1616 exit2 = self.new_block()
1617 self.emit_jump(ops.POP_JUMP_IF_TRUE, exit2)
1618 # __exit__ returned false: propagate original exception.
1619 self.emit_op_arg(ops.RERAISE, 2)
1620 self.emit_op(_POP_BLOCK) # close SETUP_CLEANUP scope
1621 # with_cleanup: [__exit__, lasti, prev, lasti_new, exc_new]; COPY 3
1622 # duplicates prev, POP_EXCEPT restores sys.exc_info, RERAISE 1 reraises.
1623 # Any enclosing SETUP_WITH scope naturally covers this block.
1624 self.use_next_block(with_cleanup)
1625 self.emit_op_arg(ops.COPY, 3)
1626 self.emit_op(ops.POP_EXCEPT)
1627 self.emit_op_arg(ops.RERAISE, 1)
1628 self.use_next_block(exit2)
1629 self.emit_op(ops.POP_TOP) # pop exc
1630 self.emit_op(_POP_BLOCK) # close SETUP_CLEANUP scope (matches CPython POP_BLOCK)
1631 exit2_rest = self.new_block()
1632 self.use_next_block(exit2_rest)
1633 self.emit_op(ops.POP_EXCEPT) # pop prev_exc, restore sys.exc_info
1634 self.emit_op(ops.POP_TOP) # pop lasti
1635 self.emit_op(ops.POP_TOP) # pop __exit__
1636 self.use_next_block(exit)
1637
1638 def visit_AsyncWith(self, wih):
1639 if not self._check_async_function():
1640 self.error("'async with' outside async function", wih)
1641 self.handle_withitem(wih, 0, is_async=True)
1642
1643 def visit_Raise(self, rais):
1644 arg = 0
1645 if rais.exc:
1646 rais.exc.walkabout(self)
1647 arg += 1
1648 if rais.cause:
1649 rais.cause.walkabout(self)
1650 arg += 1
1651 self.emit_op_arg(ops.RAISE_VARARGS, arg)
1652
1653 def visit_Global(self, glob):
1654 # Handled in symbol table building.
1655 pass
1656
1657 def visit_Nonlocal(self, glob):
1658 # Handled in symbol table building.
1659 pass
1660
1661 def visit_Pass(self, pas):
1662 self.emit_line_tracing_nop()
1663
1664 def visit_Expr(self, expr):
1665 if self.interactive:
1666 expr.value.walkabout(self)
1667 self.emit_op(ops.PRINT_EXPR)
1668 elif not isinstance(expr.value, ast.Constant):
1669 self.no_position_info()
1670 expr.value.walkabout(self)
1671 self.emit_op(ops.POP_TOP)
1672 else:
1673 self.emit_line_tracing_nop()
1674
1675 @update_pos_expr
1676 def visit_Yield(self, yie):
1677 if yie.value:
1678 yie.value.walkabout(self)
1679 else:
1680 self.load_const(self.space.w_None)
1681 self.emit_op(ops.YIELD_VALUE)
1682
1683 @update_pos_expr
1684 def visit_YieldFrom(self, yfr):
1685 yfr.value.walkabout(self)
1686 self.emit_op(ops.GET_YIELD_FROM_ITER)
1687 self.load_const(self.space.w_None)
1688 self.emit_op(ops.YIELD_FROM)
1689
1690 @update_pos_expr
1691 def visit_Await(self, aw):
1692 if not self._check_async_function():
1693 self.error("'await' outside async function", aw)
1694 aw.value.walkabout(self)
1695 self.emit_op(ops.GET_AWAITABLE)
1696 self.load_const(self.space.w_None)
1697 self.emit_op(ops.YIELD_FROM)
1698
1699 @update_pos_expr
1700 def visit_Constant(self, const):
1701 self.load_const(const.value)
1702
1703 @update_pos_expr
1704 def visit_UnaryOp(self, op):
1705 op.operand.walkabout(self)
1706 self.emit_op(unary_operations(op.op))
1707
1708 @update_pos_expr
1709 def visit_BoolOp(self, op):
1710 if op.op == ast.And:
1711 instr = ops.JUMP_IF_FALSE_OR_POP
1712 else:
1713 instr = ops.JUMP_IF_TRUE_OR_POP
1714 end = self.new_block()
1715 we_are_and = op.op == ast.And
1716 last = len(op.values) - 1
1717 for index in range(last):
1718 value = op.values[index]
1719 truth = value.as_constant_truth(
1720 self.space, self.compile_info)
1721 if truth == optimize.CONST_NOT_CONST:
1722 value.walkabout(self)
1723 self.emit_jump(instr, end)
1724 continue
1725 if (truth != optimize.CONST_TRUE) == we_are_and:
1726 last = index
1727 with self.all_dead_code(): # error checking
1728 for i in range(index + 1, len(op.values)):
1729 op.values[i].walkabout(self)
1730 break
1731 else:
1732 with self.all_dead_code(): # error checking
1733 value.walkabout(self)
1734 op.values[last].walkabout(self)
1735 self.use_next_block(end)
1736
1737 @update_pos_expr
1738 def visit_Compare(self, comp):
1739 self._check_compare(comp)
1740 comp.left.walkabout(self)
1741 ops_count = len(comp.ops)
1742 cleanup = None
1743 if ops_count > 1:
1744 cleanup = self.new_block()
1745 comp.comparators[0].walkabout(self)
1746 for i in range(1, ops_count):
1747 self.emit_op(ops.DUP_TOP)
1748 self.emit_op(ops.ROT_THREE)
1749 self.emit_compare(comp.ops[i - 1])
1750 self.emit_jump(ops.JUMP_IF_FALSE_OR_POP, cleanup)
1751 if i < (ops_count - 1):
1752 comp.comparators[i].walkabout(self)
1753 last_op, last_comparator = comp.ops[-1], comp.comparators[-1]
1754 if not self._optimize_comparator(last_op, last_comparator):
1755 last_comparator.walkabout(self)
1756 self.emit_compare(last_op)
1757 if ops_count > 1:
1758 end = self.new_block()
1759 saved_depth = self._stack_depth # result at D+1; cleanup path also leaves D+1
1760 self.emit_jump(ops.JUMP_FORWARD, end)
1761 self.use_next_block(cleanup)
1762 self.emit_op(ops.ROT_TWO)
1763 self.emit_op(ops.POP_TOP)
1764 self.use_next_block(end)
1765 self._stack_depth = saved_depth # restore: result is on stack
1766
1767 def _is_literal(self, node):
1768 # to-do(isidentical): maybe include list, dict, sets?
1769 if not isinstance(node, ast.Constant):
1770 return False
1771
1772 for singleton in [
1773 self.space.w_None,
1774 self.space.w_True,
1775 self.space.w_False,
1776 self.space.w_Ellipsis
1777 ]:
1778 if self.space.is_w(node.value, singleton):
1779 return False
1780
1781 return True
1782
1783 def _check_compare(self, node):
1784 left = node.left
1785 for i in range(min(len(node.ops), len(node.comparators))):
1786 op = node.ops[i]
1787 right = node.comparators[i]
1788 if op in (ast.Is, ast.IsNot) and (self._is_literal(left) or self._is_literal(right)):
1789 if op is ast.Is:
1790 operator, replacement = "is", "=="
1791 else:
1792 operator, replacement = "is not", "!="
1793 misc.syntax_warning(
1794 self.space,
1795 '"%s" with a literal. Did you mean "%s"?'
1796 % (operator, replacement),
1797 self.compile_info.filename,
1798 node.lineno,
1799 node.col_offset
1800 )
1801 left = right
1802
1803 def _optimize_comparator(self, op, node):
1804 """Fold lists/sets of constants in the context of "in"/"not in".
1805
1806 lists are folded into tuples, sets into frozensets, otherwise
1807 returns False
1808 """
1809 if op in (ast.In, ast.NotIn):
1810 is_list = isinstance(node, ast.List)
1811 if is_list or isinstance(node, ast.Set):
1812 w_const = self._tuple_of_consts(node.elts)
1813 if w_const is not None:
1814 if not is_list:
1815 from pypy.objspace.std.setobject import (
1816 W_FrozensetObject)
1817 w_const = W_FrozensetObject(self.space, w_const)
1818 self.load_const(w_const)
1819 return True
1820 return False
1821
1822 def _tuple_of_consts(self, elts):
1823 """Return a tuple of consts from elts if possible, or None"""
1824 count = len(elts) if elts is not None else 0
1825 consts_w = [None] * count
1826 for i in range(count):
1827 w_value = elts[i].as_constant(self.space, self.compile_info)
1828 if w_value is None:
1829 # Not all constants
1830 return None
1831 consts_w[i] = w_value
1832 return self.space.newtuple(consts_w)
1833
1834 @update_pos_expr
1835 def visit_IfExp(self, ifexp):
1836 end = self.new_block()
1837 otherwise = self.new_block()
1838 ifexp.test.accept_jump_if(self, False, otherwise)
1839 saved_depth = self._stack_depth
1840 ifexp.body.walkabout(self)
1841 self.emit_jump_noline(ops.JUMP_FORWARD, end)
1842 self.use_next_block(otherwise)
1843 self._stack_depth = saved_depth # restore: otherwise entered before then-branch
1844 ifexp.orelse.walkabout(self)
1845 self.use_next_block(end)
1846
1847 def _visit_starunpack(self, node, elts, build_op, add_op, extend_op, is_tuple=False):
1848 elt_count = len(elts) if elts else 0
1849 contains_starred = False
1850 for i in range(elt_count):
1851 elt = elts[i]
1852 if isinstance(elt, ast.Starred):
1853 contains_starred = True
1854 break
1855 if not contains_starred:
1856 if elt_count > MAX_STACKDEPTH_CONTAINERS:
1857 if is_tuple:
1858 self.emit_op_arg(ops.BUILD_LIST, 0)
1859 add_op = ops.LIST_APPEND
1860 else:
1861 self.emit_op_arg(build_op, 0)
1862 for elt in elts:
1863 elt.walkabout(self)
1864 self.emit_op_arg(add_op, 1)
1865 if is_tuple:
1866 self.emit_op(ops.LIST_TO_TUPLE)
1867 else:
1868 for i in range(elt_count):
1869 elt = elts[i]
1870 elt.walkabout(self)
1871 if is_tuple:
1872 self.emit_op_arg(ops.BUILD_TUPLE, elt_count)
1873 else:
1874 self.emit_op_arg(build_op, elt_count)
1875 return
1876
1877 seen_star = False
1878 for i in range(elt_count):
1879 elt = elts[i]
1880 if isinstance(elt, ast.Starred):
1881 if not seen_star:
1882 self.emit_op_arg(build_op, i)
1883 seen_star = True
1884 elt.value.walkabout(self)
1885 self.emit_op_arg(extend_op, 1)
1886 else:
1887 elt.walkabout(self)
1888 if seen_star:
1889 self.emit_op_arg(add_op, 1)
1890 assert seen_star
1891 if is_tuple:
1892 self.emit_op(ops.LIST_TO_TUPLE)
1893
1894 def _visit_assignment(self, node, elts, ctx):
1895 elt_count = len(elts) if elts else 0
1896 if ctx == ast.Store:
1897 seen_star = False
1898 for i in range(elt_count):
1899 elt = elts[i]
1900 is_starred = isinstance(elt, ast.Starred)
1901 if is_starred and not seen_star:
1902 if i >= 1 << 8 or elt_count - i - 1 >= (C_INT_MAX >> 8):
1903 self.error("too many expressions in star-unpacking "
1904 "assignment", node)
1905 self.emit_op_arg(ops.UNPACK_EX,
1906 i + ((elt_count - i - 1) << 8))
1907 seen_star = True
1908 elts[i] = elt.value
1909 elif is_starred:
1910 self.error("multiple starred expressions in assignment", elt)
1911 if not seen_star:
1912 self.emit_op_arg(ops.UNPACK_SEQUENCE, elt_count)
1913 self.visit_sequence(elts)
1914
1915 def visit_Starred(self, star):
1916 if star.ctx != ast.Store:
1917 self.error("can't use starred expression here",
1918 star)
1919 self.error("starred assignment target must be in a list or tuple", star)
1920
1921 @update_pos_expr
1922 def visit_Tuple(self, tup):
1923 if tup.ctx == ast.Store:
1924 self._visit_assignment(tup, tup.elts, tup.ctx)
1925 elif tup.ctx == ast.Load:
1926 self._visit_starunpack(tup, tup.elts, ops.BUILD_LIST, ops.LIST_APPEND, ops.LIST_EXTEND, is_tuple=True)
1927 else:
1928 self.visit_sequence(tup.elts)
1929
1930 @update_pos_expr
1931 def visit_List(self, l):
1932 if l.ctx == ast.Store:
1933 self._visit_assignment(l, l.elts, l.ctx)
1934 elif l.ctx == ast.Load:
1935 self._visit_starunpack(l, l.elts, ops.BUILD_LIST, ops.LIST_APPEND, ops.LIST_EXTEND)
1936 else:
1937 self.visit_sequence(l.elts)
1938
1939 @update_pos_expr
1940 def visit_Dict(self, d):
1941 containers = 0
1942 elements = 0
1943 is_unpacking = False
1944 all_constant_keys_w = None
1945 if d.values:
1946 unpacking_anywhere = False
1947 for key in d.keys:
1948 if key is None:
1949 unpacking_anywhere = True
1950 break
1951 if not unpacking_anywhere and len(d.keys) > MAX_STACKDEPTH_CONTAINERS:
1952 # do it in a small amount of stack
1953 self.emit_op_arg(ops.BUILD_MAP, 0)
1954 for i in range(len(d.values)):
1955 key = d.keys[i]
1956 assert key is not None
1957 key.walkabout(self)
1958 d.values[i].walkabout(self)
1959 self.emit_op_arg(ops.MAP_ADD, 1)
1960 return
1961 assert len(d.keys) < 0xffff
1962 all_constant_keys_w = []
1963 for key in d.keys:
1964 if key is None:
1965 constant_key = None
1966 else:
1967 constant_key = key.as_constant(
1968 self.space, self.compile_info)
1969 if constant_key is None:
1970 all_constant_keys_w = None
1971 break
1972 else:
1973 all_constant_keys_w.append(constant_key)
1974 for i in range(len(d.values)):
1975 key = d.keys[i]
1976 is_unpacking = key is None
1977 if elements == 0xFFFF or (elements and is_unpacking):
1978 assert all_constant_keys_w is None
1979 self.emit_op_arg(ops.BUILD_MAP, elements)
1980 if containers > 0:
1981 self.emit_op(ops.DICT_UPDATE)
1982 else:
1983 containers = 1
1984 elements = 0
1985 if is_unpacking:
1986 if containers == 0:
1987 self.emit_op_arg(ops.BUILD_MAP, 0)
1988 containers = 1
1989 assert all_constant_keys_w is None
1990 d.values[i].walkabout(self)
1991 self.emit_op(ops.DICT_UPDATE)
1992 else:
1993 if not all_constant_keys_w:
1994 key.walkabout(self)
1995 d.values[i].walkabout(self)
1996 elements += 1
1997 if elements or containers == 0:
1998 if all_constant_keys_w:
1999 w_tup = self.space.newtuple(all_constant_keys_w)
2000 self.load_const(w_tup)
2001 self.emit_op_arg(ops.BUILD_CONST_KEY_MAP, elements)
2002 containers = 1
2003 else:
2004 self.emit_op_arg(ops.BUILD_MAP, elements)
2005 if containers > 0:
2006 self.emit_op(ops.DICT_UPDATE)
2007 else:
2008 containers = 1
2009 assert containers == 1
2010
2011 @update_pos_expr
2012 def visit_Set(self, s):
2013 self._visit_starunpack(s, s.elts, ops.BUILD_SET, ops.SET_ADD, ops.SET_UPDATE)
2014
2015 @update_pos_expr
2016 def visit_Name(self, name):
2017 self.name_op(name.id, name.ctx, name)
2018
2019 def visit_keyword(self, keyword):
2020 if keyword.arg is not None:
2021 self.load_const(self.space.newtext(keyword.arg))
2022 keyword.value.walkabout(self)
2023
2024 def _load_constant_tuple(self, content_w):
2025 self.load_const(self.space.newtuple(content_w[:]))
2026
2027 def _make_call(self, nargs_pushed, args, keywords):
2028 space = self.space
2029 CallCodeGenerator(self, nargs_pushed, args, keywords).emit_call()
2030
2031 @update_pos_expr
2032 def visit_Call(self, call):
2033 if self._optimize_method_call(call):
2034 return
2035 self._check_caller(call.func)
2036 call.func.walkabout(self)
2037 self._make_call(0, call.args, call.keywords)
2038
2039 def _check_caller(self, func):
2040 if func._literal_type:
2041 misc.syntax_warning(
2042 self.space,
2043 "'%s' object is not callable; perhaps you "
2044 "missed a comma?" % func._get_type_name(self.space),
2045 self.compile_info.filename,
2046 func.lineno,
2047 func.col_offset
2048 )
2049
2050 def _call_has_no_star_args(self, call):
2051 if call.args is not None:
2052 for elt in call.args:
2053 if isinstance(elt, ast.Starred):
2054 return False
2055 if call.keywords is not None:
2056 for kw in call.keywords:
2057 assert isinstance(kw, ast.keyword)
2058 if kw.arg is None:
2059 return False
2060 return True
2061
2062 def _call_has_simple_args(self, call):
2063 return self._call_has_no_star_args(call) and not call.keywords
2064
2065 def _optimize_method_call(self, call):
2066 space = self.space
2067 if not self._call_has_no_star_args(call) or \
2068 not isinstance(call.func, ast.Attribute):
2069 return False
2070 arg_count = len(call.args) if call.args is not None else 0
2071 kw_count = len(call.keywords) if call.keywords is not None else 0
2072 if arg_count > MAX_STACKDEPTH_CONTAINERS // 2 or kw_count > MAX_STACKDEPTH_CONTAINERS // 2:
2073 return False
2074 attr_lookup = call.func
2075 assert isinstance(attr_lookup, ast.Attribute)
2076 attr_lookup.value.walkabout(self)
2077 attr_col = attr_lookup.end_col_offset - len(attr_lookup.attr)
2078 self.update_position((attr_lookup.end_lineno, attr_lookup.end_lineno, attr_col, attr_lookup.end_col_offset))
2079 self.emit_op_name(ops.LOAD_METHOD, self.names, attr_lookup.attr)
2080 self.visit_sequence(call.args)
2081 if not call.keywords:
2082 self.emit_op_arg(ops.CALL_METHOD, arg_count)
2083 else:
2084 keyword_names_w = []
2085 for kw in call.keywords:
2086 assert isinstance(kw, ast.keyword)
2087 assert kw.arg # checked by self._call_has_no_star_args
2088 w_name = space.newtext(kw.arg)
2089 keyword_names_w.append(misc.intern_if_common_string(space, w_name))
2090 kw.value.walkabout(self)
2091 self._load_constant_tuple(keyword_names_w)
2092 self.emit_op_arg(ops.CALL_METHOD_KW, len(keyword_names_w) + arg_count)
2093 return True
2094
2095 @update_pos_expr
2096 def visit_ListComp(self, lc):
2097 self._compile_comprehension(lc, "<listcomp>",
2098 ComprehensionCodeGenerator)
2099
2100 def _comp_generator(self, node, generators, gen_index=0, built_object_stackdepth=0):
2101 gen = generators[gen_index]
2102 assert isinstance(gen, ast.comprehension)
2103 if gen.is_async:
2104 self._comp_async_generator(node, generators, gen_index, built_object_stackdepth)
2105 else:
2106 self._comp_sync_generator(node, generators, gen_index, built_object_stackdepth)
2107
2108 def _comp_sync_generator(self, node, generators, gen_index, built_object_stackdepth):
2109 anchor = self.new_block()
2110 gen = generators[gen_index]
2111 assert isinstance(gen, ast.comprehension)
2112 iter = gen.iter
2113 if gen_index > 0 and isinstance(iter, ast.List) and iter.elts is not None and len(iter.elts) == 1:
2114 # assignment "idiom" (hack really)
2115 iter.elts[0].walkabout(self)
2116 start = None
2117 if_cleanup = anchor
2118 else:
2119 if gen_index > 0:
2120 iter.walkabout(self)
2121 self.emit_op(ops.GET_ITER)
2122 start = self.new_block()
2123 if_cleanup = self.new_block()
2124 self.use_next_block(start)
2125 self.emit_jump(ops.FOR_ITER, anchor)
2126 self.use_next_block()
2127 built_object_stackdepth += 1
2128 gen.target.walkabout(self)
2129 if gen.ifs:
2130 for if_ in gen.ifs:
2131 if_.accept_jump_if(self, False, if_cleanup)
2132 self.use_next_block()
2133 gen_index += 1
2134 if gen_index < len(generators):
2135 self._comp_generator(node, generators, gen_index, built_object_stackdepth)
2136 else:
2137 node.accept_comp_iteration(self, built_object_stackdepth)
2138 if start is not None:
2139 self.use_next_block(if_cleanup)
2140 self.emit_jump(ops.JUMP_ABSOLUTE, start)
2141 self.use_next_block(anchor)
2142
2143 def _comp_async_generator(self, node, generators, gen_index, built_object_stackdepth):
2144 b_start = self.new_block()
2145 b_except = self.new_block()
2146 b_reraise = self.new_block()
2147 b_if_cleanup = self.new_block()
2148 b_end = self.new_block()
2149 gen = generators[gen_index]
2150 assert isinstance(gen, ast.comprehension)
2151 if gen_index > 0:
2152 gen.iter.walkabout(self)
2153 self.emit_op(ops.GET_AITER)
2154
2155 self.use_next_block(b_start)
2156
2157 b_anext = self.use_next_block()
2158 b_after_yield = self.new_block()
2159 # Narrow SETUP_FINALLY/POP_BLOCK pair covering only GET_ANEXT/YIELD_FROM.
2160 # The inner scope overrides any enclosing SETUP_WITH/SETUP_ASYNC_WITH,
2161 # routing StopAsyncIteration to b_except.
2162 self.emit_jump(_SETUP_FINALLY, b_except)
2163 self.emit_op(ops.GET_ANEXT)
2164 self.load_const(self.space.w_None)
2165 self.emit_op(ops.YIELD_FROM)
2166 self.emit_op(_POP_BLOCK)
2167 self.use_next_block(b_after_yield)
2168 gen.target.walkabout(self)
2169
2170 if gen.ifs:
2171 for if_ in gen.ifs:
2172 if_.accept_jump_if(self, False, b_if_cleanup)
2173 self.use_next_block()
2174 gen_index += 1
2175 built_object_stackdepth += 1
2176
2177 if gen_index < len(generators):
2178 self._comp_generator(node, generators, gen_index, built_object_stackdepth)
2179 else:
2180 node.accept_comp_iteration(self, gen_index)
2181
2182 self.use_next_block(b_if_cleanup)
2183 self.emit_jump(ops.JUMP_ABSOLUTE, b_start)
2184
2185 self._emit_async_for_handler(b_except, b_reraise, b_end)
2186
2187 def _compile_comprehension(self, node, name, sub_scope):
2188 is_async_function = self.scope.is_coroutine
2189 code, qualname = self.sub_scope(sub_scope, name, node, node.lineno)
2190 is_async_comprehension = self.symbols.find_scope(node).is_coroutine
2191 if is_async_comprehension and not self._check_async_function():
2192 if (not isinstance(node, ast.GeneratorExp) and
2193 not isinstance(self.scope, symtable.AsyncFunctionScope) and
2194 not isinstance(self.scope, symtable.ComprehensionScope)):
2195 self.error("asynchronous comprehension outside of "
2196 "an asynchronous function", node)
2197
2198 self.update_position(node)
2199 self._make_function(code, qualname=qualname)
2200 first_comp = node.get_generators()[0]
2201 assert isinstance(first_comp, ast.comprehension)
2202 first_comp.iter.walkabout(self)
2203 if first_comp.is_async:
2204 self.emit_op(ops.GET_AITER)
2205 else:
2206 self.emit_op(ops.GET_ITER)
2207 self.emit_op_arg(ops.CALL_FUNCTION, 1)
2208 if is_async_comprehension and sub_scope is not GenExpCodeGenerator:
2209 self.emit_op(ops.GET_AWAITABLE)
2210 self.load_const(self.space.w_None)
2211 self.emit_op(ops.YIELD_FROM)
2212
2213 @update_pos_expr
2214 def visit_GeneratorExp(self, genexp):
2215 self._compile_comprehension(genexp, "<genexpr>", GenExpCodeGenerator)
2216
2217 @update_pos_expr
2218 def visit_SetComp(self, setcomp):
2219 self._compile_comprehension(setcomp, "<setcomp>",
2220 ComprehensionCodeGenerator)
2221
2222 @update_pos_expr
2223 def visit_DictComp(self, dictcomp):
2224 self._compile_comprehension(dictcomp, "<dictcomp>",
2225 ComprehensionCodeGenerator)
2226
2227 def check_forbidden_name(self, name, node, ctx=ast.Store):
2228 if misc.check_forbidden_name(self.space, name):
2229 if ctx == ast.Store:
2230 self.error("cannot assign to " + name, node)
2231 elif ctx == ast.Load:
2232 # XXX not in CPython, but needed for __debug__ += 1
2233 pass
2234 else:
2235 assert ctx == ast.Del
2236 self.error("cannot delete " + name, node)
2237
2238 @update_pos_expr
2239 def visit_Attribute(self, attr):
2240 names = self.names
2241 ctx = attr.ctx
2242 attr.value.walkabout(self)
2243 attr_col = attr.end_col_offset - len(attr.attr)
2244 self.update_position((attr.end_lineno, attr.end_lineno, attr_col, attr.end_col_offset))
2245 if ctx == ast.Load:
2246 self.emit_op_name(ops.LOAD_ATTR, names, attr.attr)
2247 return
2248 self.check_forbidden_name(attr.attr, attr, ctx)
2249 if ctx == ast.Store:
2250 self.emit_op_name(ops.STORE_ATTR, names, attr.attr)
2251 elif ctx == ast.Del:
2252 self.emit_op_name(ops.DELETE_ATTR, names, attr.attr)
2253 else:
2254 raise AssertionError("unknown context")
2255
2256 @update_pos_expr
2257 def visit_Slice(self, slc):
2258 if slc.lower:
2259 slc.lower.walkabout(self)
2260 else:
2261 self.load_const(self.space.w_None)
2262 if slc.upper:
2263 slc.upper.walkabout(self)
2264 else:
2265 self.load_const(self.space.w_None)
2266 arg = 2
2267 if slc.step:
2268 slc.step.walkabout(self)
2269 arg += 1
2270 self.emit_op_arg(ops.BUILD_SLICE, arg)
2271
2272 @update_pos_expr
2273 def visit_Subscript(self, sub):
2274 ctx = sub.ctx
2275 if ctx == ast.Load:
2276 self._check_subscripter(sub.value)
2277 self._check_index(sub, sub.value, sub.slice)
2278 op = ops.BINARY_SUBSCR
2279 elif ctx == ast.Store:
2280 op = ops.STORE_SUBSCR
2281 elif ctx == ast.Del:
2282 op = ops.DELETE_SUBSCR
2283 else:
2284 assert 0
2285 sub.value.walkabout(self)
2286 sub.slice.walkabout(self)
2287 self.emit_op(op)
2288
2289 def _check_subscripter(self, sub):
2290 if (
2291 isinstance(sub, ast.Constant)
2292 and (
2293 self.space.isinstance_w(sub.value, self.space.w_tuple)
2294 or self.space.isinstance_w(sub.value, self.space.w_unicode)
2295 or self.space.isinstance_w(sub.value, self.space.w_bytes)
2296 )
2297 ):
2298 return None
2299 elif (type(sub) is not ast.Constant and type(sub) is not ast.Set and
2300 type(sub) is not ast.SetComp and
2301 type(sub) is not ast.GeneratorExp and
2302 type(sub) is not ast.Lambda):
2303 return None
2304
2305 misc.syntax_warning(
2306 self.space,
2307 "'%s' object is not subscriptable; perhaps"
2308 " you missed a comma?" % sub._get_type_name(self.space),
2309 self.compile_info.filename,
2310 sub.lineno,
2311 sub.col_offset
2312 )
2313
2314 def _check_index(self, node, sub, index):
2315 if not index._literal_type:
2316 return None
2317
2318 if isinstance(index, ast.Constant):
2319 if self.space.isinstance_w(
2320 index.value, self.space.w_int
2321 ):
2322 return None
2323
2324 if (isinstance(sub, ast.Constant)
2325 and not (
2326 self.space.isinstance_w(sub.value, self.space.w_tuple)
2327 or self.space.isinstance_w(sub.value, self.space.w_unicode)
2328 or self.space.isinstance_w(sub.value, self.space.w_bytes)
2329 )
2330 ):
2331 return None
2332
2333 if (
2334 type(sub) is not ast.Constant and
2335 type(sub) is not ast.Tuple and
2336 type(sub) is not ast.List and
2337 type(sub) is not ast.ListComp and
2338 type(sub) is not ast.JoinedStr and
2339 type(sub) is not ast.FormattedValue
2340 ):
2341 return None
2342
2343 # not quotes (on purpose to comply with TypeErrors)
2344 misc.syntax_warning(
2345 self.space,
2346 "%s indices must be integers or slices, "
2347 "not %s; perhaps you missed a comma?" % (
2348 sub._get_type_name(self.space),
2349 index._get_type_name(self.space)
2350 ),
2351 self.compile_info.filename,
2352 node.lineno,
2353 node.col_offset
2354 )
2355
2356 @update_pos_expr
2357 def visit_JoinedStr(self, joinedstr):
2358 for node in joinedstr.values:
2359 node.walkabout(self)
2360 if len(joinedstr.values) != 1:
2361 self.emit_op_arg(ops.BUILD_STRING, len(joinedstr.values))
2362
2363 @update_pos_expr
2364 def visit_FormattedValue(self, fmt):
2365 fmt.value.walkabout(self)
2366 arg = 0
2367 if fmt.conversion == ord('s'): arg = consts.FVC_STR
2368 if fmt.conversion == ord('r'): arg = consts.FVC_REPR
2369 if fmt.conversion == ord('a'): arg = consts.FVC_ASCII
2370 if fmt.format_spec is not None:
2371 arg |= consts.FVS_HAVE_SPEC
2372 fmt.format_spec.walkabout(self)
2373 self.emit_op_arg(ops.FORMAT_VALUE, arg)
2374
2375 @update_pos_expr
2376 def visit_NamedExpr(self, namedexpr):
2377 namedexpr.value.walkabout(self)
2378 self.emit_op(ops.DUP_TOP)
2379 namedexpr.target.walkabout(self)
2380
2381 def _revdb_metavar(self, node):
2382 # moved in its own function for the import statement
2383 from pypy.interpreter.reverse_debugging import dbstate
2384 if not dbstate.standard_code:
2385 self.emit_op_arg(ops.LOAD_REVDB_VAR, node.metavar)
2386 return True
2387 return False
2388
2389 @update_pos_expr
2390 def visit_RevDBMetaVar(self, node):
2391 if self.space.reverse_debugging and self._revdb_metavar(node):
2392 return
2393 self.error("Unknown character ('$NUM' is only valid in the "
2394 "reverse-debugger)", node)
2395
2396 def allows_top_level_await(self):
2397 return (
2398 self._allow_top_level_await
2399 and isinstance(self.scope, symtable.ModuleScope)
2400 )
2401
2402 def visit_Match(self, match):
2403 if not match.cases:
2404 return
2405
2406 end = self.new_block()
2407 match.subject.walkabout(self)
2408 with self.new_match_context() as match_context:
2409 last_index_for_dup = len(match.cases) - 1
2410 # TODO: fix this optimization: do we need to check for both pattern and name?
2411 # if isinstance(match.cases[-1], ast.MatchAs) and not match.cases[-1].name:
2412 # last_index_for_dup -= 1
2413 for i, case in enumerate(match.cases):
2414 is_last_case = i == last_index_for_dup
2415 # only the last case is allowed to always succeed
2416 assert isinstance(case, ast.match_case)
2417 match_context.allow_always_passing = is_last_case or case.guard is not None
2418 if not is_last_case:
2419 self.emit_op(ops.DUP_TOP)
2420
2421 assert match_context.on_top == 0
2422 self.update_position(case.pattern)
2423 case.pattern.walkabout(self)
2424 assert match_context.on_top == 0
2425 # the pattern visit methods will conditionally jump away if
2426 # it's not a match. so if the execution is still here, it's a
2427 # match
2428
2429 # now we need to actually do the variable bindings (the pattern
2430 # only stores the values on the stack)
2431 for i, name in enumerate(match_context.names_list):
2432 self.name_op(name, ast.Store, match_context.names_origins[i])
2433
2434 if case.guard:
2435 case.guard.accept_jump_if(self, False, match_context.next)
2436
2437 if not is_last_case:
2438 self.emit_op(ops.POP_TOP)
2439
2440 self._visit_body(case.body)
2441 self.emit_jump(ops.JUMP_FORWARD, end)
2442 match_context.next_case(case.pattern)
2443 self.use_next_block(end)
2444 # self.emit_op(ops.POP_TOP)
2445
2446 def visit_MatchValue(self, match_value):
2447 # check that it's either a literal or an attribute lookup
2448 value = match_value.value
2449 if (not isinstance(value, ast.Constant) and
2450 not isinstance(value, ast.Attribute)):
2451 self.error("patterns may only match literals and attribute lookups",
2452 match_value.value)
2453 match_value.value.walkabout(self)
2454 self.emit_compare(ast.Eq)
2455 self.match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2456
2457 def visit_MatchSingleton(self, match_singleton):
2458 w_value = match_singleton.value
2459 self.load_const(w_value)
2460 self.emit_op_arg(ops.IS_OP, 0)
2461 self.match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2462
2463 def _pattern_store_name(self, name, node, match_context):
2464 if name is None:
2465 self.emit_op(ops.POP_TOP)
2466 return
2467
2468 match_context.add_name(name, node, self)
2469
2470 # rotate this below any items we need to preserve
2471 targetpos = match_context.on_top + len(match_context.names_stored)
2472 self.emit_swaps(targetpos)
2473
2474 def visit_MatchAs(self, match_as):
2475 match_context = self.match_context
2476 if match_as.pattern is None:
2477 # this pattern always passes, check whether that is ok
2478 if not match_context.allow_always_passing:
2479 if match_as.name:
2480 self.error(
2481 "name capture '%s' makes remaining patterns unreachable" % (
2482 match_as.name, ),
2483 match_as)
2484 else:
2485 self.error(
2486 "wildcard makes remaining patterns unreachable",
2487 match_as)
2488 self._pattern_store_name(match_as.name, match_as, match_context)
2489 return
2490
2491 targetname = match_as.name
2492 if targetname:
2493 self.emit_op(ops.DUP_TOP)
2494 match_context.on_top += 1
2495
2496 # this will jump away if the pattern doesn't match
2497 match_as.pattern.walkabout(self)
2498
2499 if targetname:
2500 match_context.on_top -= 1
2501 self._pattern_store_name(match_as.name, match_as, match_context)
2502
2503 def visit_MatchSequence(self, match_sequence):
2504 match_context = self.match_context
2505 patterns = match_sequence.patterns
2506 if patterns is None:
2507 patterns = []
2508
2509 # input: (1, 2, 3, 4, 5)
2510 # pattern: (1, *rest, 4, 5)
2511 # stack = [(1,2,3,4,5)]
2512
2513 match_context.on_top += 1 # subject is on top
2514 self.emit_op(ops.MATCH_SEQUENCE)
2515 # stack = [(1,2,3,4,5), True]
2516
2517 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2518 # stack = [(1,2,3,4,5)]
2519
2520 star_index = -1
2521 star_captures = False
2522 for i, pattern in enumerate(patterns):
2523 if isinstance(pattern, ast.MatchStar):
2524 if star_index != -1:
2525 self.error("multiple starred names in sequence pattern", pattern)
2526 star_index = i
2527 star_captures = pattern.name is not None
2528
2529 length = len(patterns)
2530 if star_index >= 0:
2531 if length > 1:
2532 self.emit_op(ops.GET_LEN)
2533 # stack = [(1,2,3,4,5), 5]
2534 self.load_const(self.space.newint(length - 1))
2535 # stack = [(1,2,3,4,5), 3]
2536
2537 self.emit_compare(ast.GtE)
2538 # stack = [(1,2,3,4,5), True]
2539
2540 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2541 # stack = [(1,2,3,4,5)]
2542 left = star_index
2543 right = length - star_index - 1
2544 else:
2545 self.emit_op(ops.GET_LEN)
2546 # stack = [(1,2,3,4,5), 5]
2547 self.load_const(self.space.newint(length))
2548 self.emit_compare(ast.Eq)
2549 left = length - 1
2550 right = 0
2551 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2552 # stack = [(1,2,3,4,5)]
2553
2554
2555 match_context.on_top -= 1 # the rest consumes the subject
2556
2557 if star_index >= 0 and not star_captures:
2558 self._pattern_sequence_subscr(match_sequence, star_index, match_context)
2559 return
2560
2561 if star_index >= 0:
2562 self.emit_op_arg(ops.UNPACK_EX, left + (right << 8))
2563 # stack = [(1,2,3,4,5), 5, 4, (2, 3), 1]
2564 elif length > 0:
2565 self.emit_op_arg(ops.UNPACK_SEQUENCE, length)
2566 else:
2567 self.emit_op(ops.POP_TOP)
2568
2569 match_context.on_top += length
2570 with self.sub_pattern_context():
2571 for i, pattern in enumerate(patterns):
2572 match_context.on_top -= 1
2573 pattern.walkabout(self)
2574
2575 def _pattern_sequence_subscr(self, match_sequence, star_index, match_context):
2576 # optimization: don't unpack the whole iterable, just access positions
2577 patterns = match_sequence.patterns
2578 match_context.on_top += 1 # keep subject around
2579 with self.sub_pattern_context():
2580 size = len(patterns)
2581 for i, pattern in enumerate(patterns):
2582 if i == star_index:
2583 continue
2584 self.emit_op(ops.DUP_TOP)
2585 if i < star_index:
2586 self.load_const(self.space.newint(i))
2587 else:
2588 self.emit_op(ops.GET_LEN)
2589 self.load_const(self.space.newint(size - i))
2590 self.emit_op(ops.BINARY_SUBTRACT)
2591 self.emit_op(ops.BINARY_SUBSCR)
2592 pattern.walkabout(self)
2593 match_context.on_top -= 1
2594 self.emit_op(ops.POP_TOP)
2595
2596 def visit_MatchStar(self, match_star):
2597 self._pattern_store_name(match_star.name, match_star, self.match_context)
2598
2599 def visit_MatchMapping(self, match_mapping):
2600 match_context = self.match_context
2601
2602 self.emit_op(ops.MATCH_MAPPING)
2603 match_context.on_top += 1
2604 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2605
2606 if match_mapping.keys:
2607 length = len(match_mapping.keys)
2608 self.emit_op(ops.GET_LEN)
2609 self.load_const(self.space.newint(length))
2610 self.emit_compare(ast.GtE)
2611 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2612
2613 # check for duplicates and wrong kinds of nodes
2614 w_seen = self.space.newset()
2615 for key in match_mapping.keys:
2616 if isinstance(key, ast.Constant):
2617 if self.space.contains_w(w_seen, key.value):
2618 keyrepr = self.space.text_w(self.space.repr(key.value))
2619 self.error("mapping pattern checks duplicate key (%s)" % keyrepr, key)
2620 self.space.call_method(w_seen, "add", key.value)
2621 elif not isinstance(key, ast.Attribute):
2622 self.error("mapping pattern keys may only match literals and attribute lookups", key)
2623
2624 w_keys = self._tuple_of_consts(match_mapping.keys)
2625 if w_keys is not None:
2626 self.load_const(w_keys)
2627 else:
2628 for key in match_mapping.keys:
2629 key.walkabout(self)
2630 self.emit_op_arg(ops.BUILD_TUPLE, len(match_mapping.keys))
2631 else:
2632 length = 0
2633 self.load_const(self.space.newtuple([]))
2634
2635 # stack: [subject, keys_tuple]
2636 self.emit_op(ops.MATCH_KEYS)
2637 # stack: [subject, keys_tuple, values_or_None]
2638 match_context.on_top += 2 # keys_tuple and values_or_None above subject
2639
2640 # COPY 1 + LOAD_CONST None + IS_OP 1 mirrors CPython's compile.c pattern;
2641 # the peephole optimizer folds this into POP_JUMP_FORWARD_IF_NONE in CPython.
2642 self.emit_op_arg(ops.COPY, 1)
2643 self.load_const(self.space.w_None)
2644 self.emit_op_arg(ops.IS_OP, 1) # True if values_copy is not None
2645 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2646 # stack (success): [subject, keys_tuple, values_tuple]
2647
2648 if length:
2649 self.emit_op_arg(ops.UNPACK_SEQUENCE, length)
2650 # stack: [subject, keys_tuple, v_{n-1}, ..., v_0]
2651 match_context.on_top += length - 1 # values_tuple replaced by length values
2652
2653 with self.sub_pattern_context():
2654 for i in range(length):
2655 match_context.on_top -= 1
2656 match_mapping.patterns[i].walkabout(self)
2657 else:
2658 # empty {}: values_or_None is an empty tuple; discard it
2659 self.emit_op(ops.POP_TOP)
2660 match_context.on_top -= 1
2661
2662 # stack: [subject, keys_tuple]
2663 if match_mapping.rest:
2664 self.emit_op(ops.COPY_DICT_WITHOUT_KEYS)
2665 self.name_op(match_mapping.rest, ast.Store, match_mapping)
2666 else:
2667 self.emit_op(ops.POP_TOP) # discard keys_tuple
2668 match_context.on_top -= 1
2669
2670 self.emit_op(ops.POP_TOP) # discard subject
2671 match_context.on_top -= 1
2672
2673 def visit_MatchOr(self, match_or):
2674 end = self.new_block()
2675
2676 control = None
2677 control_list = None
2678 control_origins = None
2679 outer_match_context = self.match_context
2680 allow_always_passing = outer_match_context.allow_always_passing
2681
2682 with self.new_match_context() as match_context:
2683 for i, pattern in enumerate(match_or.patterns):
2684 is_not_last = i < len(match_or.patterns) - 1
2685 match_context.allow_always_passing = allow_always_passing and not is_not_last
2686 self.emit_op(ops.DUP_TOP)
2687
2688 assert match_context.on_top == 0
2689 if control is not None: # not the first case
2690 match_context._init_names()
2691 pattern.walkabout(self)
2692
2693 # make sure that the set of stored names is the same in all
2694 # branches
2695 if control is None:
2696 control = match_context.names_stored
2697 control_list = match_context.names_list
2698 control_origins = match_context.names_origins
2699 else:
2700 # check that the names are the same in the later alternative
2701 if len(control) != len(match_context.names_stored):
2702 self.error("alternative patterns bind different names", match_or)
2703 permutation = [-1] * len(control)
2704 for index, name in enumerate(match_context.names_list):
2705 if name not in control:
2706 self.error("alternative patterns bind different names", match_or)
2707 permutation[index] = control[name]
2708 permutation.reverse()
2709 rots = compute_reordering(permutation)
2710 for rot in rots:
2711 self.emit_swaps(rot)
2712 self.emit_jump(ops.JUMP_FORWARD, end)
2713 match_context.next_case()
2714
2715 # compile the "no match" case. pop the copy of the subject and fail
2716 # unconditionally.
2717 self.emit_op(ops.POP_TOP)
2718 outer_match_context.emit_fail_jump(ops.JUMP_FORWARD)
2719
2720 self.use_next_block(end)
2721 # now we need more rotates! yay yay yay!
2722 assert control_list is not None
2723 nstores = len(control_list)
2724 nrots = nstores + 1 + outer_match_context.on_top + len(outer_match_context.names_stored)
2725 for i, name in enumerate(control_list):
2726 self.emit_swaps(nrots)
2727 outer_match_context.add_name(name, control_origins[i], self)
2728
2729 # pop the copy of the subject
2730 self.emit_op(ops.POP_TOP)
2731
2732 def visit_MatchClass(self, match_class):
2733 match_context = self.match_context
2734
2735 if match_class.kwd_attrs:
2736 attrs = {}
2737 for attr in match_class.kwd_attrs:
2738 if attr in attrs:
2739 self.error("attribute name repeated in class pattern: '%s'" % attr, match_class)
2740 attrs[attr] = None
2741 kwd_attrs_w = [self.space.newtext(attr) for attr in match_class.kwd_attrs]
2742 else:
2743 kwd_attrs_w = []
2744
2745 nargs = len(match_class.patterns) if match_class.patterns else 0
2746 nattrs = len(kwd_attrs_w)
2747 n = nargs + nattrs
2748
2749 match_class.cls.walkabout(self)
2750 self.load_const(self.space.newtuple(kwd_attrs_w))
2751 self.emit_op_arg(ops.MATCH_CLASS, nargs)
2752 match_context.on_top += 1 # preserve the tuple (or None)
2753
2754 match_context.emit_fail_jump(ops.POP_JUMP_IF_FALSE)
2755
2756 if n:
2757 self.emit_op_arg(ops.UNPACK_SEQUENCE, n)
2758 # stack: [v_{n-1}, ..., v_0]
2759 match_context.on_top += n - 1 # tuple replaced by n values
2760
2761 with self.sub_pattern_context():
2762 for i in range(n):
2763 match_context.on_top -= 1
2764 if i < nargs:
2765 pattern = match_class.patterns[i]
2766 else:
2767 pattern = match_class.kwd_patterns[i - nargs]
2768 pattern.walkabout(self)
2769 # tuple already consumed by UNPACK_SEQUENCE
2770 else:
2771 # no sub-patterns: discard the empty tuple
2772 match_context.on_top -= 1
2773 self.emit_op(ops.POP_TOP)
2774
2775
2776 class TopLevelCodeGenerator(PythonCodeGenerator):
2777
2778 def __init__(self, space, tree, symbols, compile_info, set_debug_flag=False):
2779 if not we_are_translated():
2780 self._debug_flag = set_debug_flag # to set strategic pdbs
2781 self.is_async_seen = False
2782 PythonCodeGenerator.__init__(self, space, "<module>", tree, -1,
2783 symbols, compile_info, qualname=None)
2784
2785 def _compile(self, tree):
2786 if isinstance(tree, ast.Module):
2787 self.first_lineno = 1
2788
2789 self._maybe_setup_annotations()
2790 tree.walkabout(self)
2791
2792 def _get_code_flags(self):
2793 flags = 0
2794 if not self.cell_vars and not self.free_vars:
2795 flags |= consts.CO_NOFREE
2796 if self.scope.doc_removable:
2797 flags |= consts.CO_KILL_DOCSTRING
2798 if self.is_async_seen:
2799 flags |= consts.CO_COROUTINE
2800 return flags
2801
2802 def _check_async_function(self):
2803 top_level = self.allows_top_level_await()
2804 if top_level:
2805 self.is_async_seen = True
2806 return top_level
2807
2808
2809 class AbstractFunctionCodeGenerator(PythonCodeGenerator):
2810
2811 def _get_code_flags(self):
2812 scope = self.scope
2813 assert isinstance(scope, symtable.FunctionScope)
2814 flags = consts.CO_NEWLOCALS
2815 if scope.optimized:
2816 flags |= consts.CO_OPTIMIZED
2817 if scope.nested:
2818 flags |= consts.CO_NESTED
2819 if scope.is_generator and not scope.is_coroutine:
2820 flags |= consts.CO_GENERATOR
2821 if not scope.is_generator and scope.is_coroutine:
2822 flags |= consts.CO_COROUTINE
2823 if scope.is_generator and scope.is_coroutine:
2824 flags |= consts.CO_ASYNC_GENERATOR
2825 if scope.has_yield_inside_try:
2826 flags |= consts.CO_YIELD_INSIDE_TRY
2827 if scope.has_variable_arg:
2828 flags |= consts.CO_VARARGS
2829 if scope.has_keywords_arg:
2830 flags |= consts.CO_VARKEYWORDS
2831 if scope.doc_removable:
2832 flags |= consts.CO_KILL_DOCSTRING
2833 if not self.cell_vars and not self.free_vars:
2834 flags |= consts.CO_NOFREE
2835 return PythonCodeGenerator._get_code_flags(self) | flags
2836
2837 def _init_argcounts(self, args):
2838 if args.posonlyargs:
2839 self.argcount += len(args.posonlyargs)
2840 self.posonlyargcount = len(args.posonlyargs)
2841 if args.args:
2842 self.argcount += len(args.args)
2843 if args.kwonlyargs:
2844 self.kwonlyargcount = len(args.kwonlyargs)
2845
2846
2847 class FunctionCodeGenerator(AbstractFunctionCodeGenerator):
2848
2849 def _compile(self, func):
2850 assert isinstance(func, ast.FunctionDef)
2851 self.first_lineno = func.lineno
2852 if func.decorator_list and func.decorator_list[0].lineno > 0:
2853 self.first_lineno = func.decorator_list[0].lineno
2854 has_docstring = self.ensure_docstring_constant(func.body)
2855 args = func.args
2856 assert isinstance(args, ast.arguments)
2857 self._init_argcounts(args)
2858 start = 1 if has_docstring else 0
2859 self._visit_body(func.body, start)
2860
2861 class AsyncFunctionCodeGenerator(AbstractFunctionCodeGenerator):
2862
2863 def _compile(self, func):
2864 assert isinstance(func, ast.AsyncFunctionDef)
2865 self.first_lineno = func.lineno
2866 if func.decorator_list and func.decorator_list[0].lineno > 0:
2867 self.first_lineno = func.decorator_list[0].lineno
2868 has_docstring = self.ensure_docstring_constant(func.body)
2869 args = func.args
2870 assert isinstance(args, ast.arguments)
2871 self._init_argcounts(args)
2872 start = 1 if has_docstring else 0
2873 self._visit_body(func.body, start)
2874
2875 def _check_async_function(self):
2876 return True
2877
2878 class LambdaCodeGenerator(AbstractFunctionCodeGenerator):
2879
2880 def _compile(self, lam):
2881 assert isinstance(lam, ast.Lambda)
2882 args = lam.args
2883 assert isinstance(args, ast.arguments)
2884 self._init_argcounts(args)
2885 # Prevent a string from being the first constant and thus a docstring.
2886 self.add_const(self.space.w_None)
2887 lam.body.walkabout(self)
2888 self.emit_op(ops.RETURN_VALUE)
2889
2890
2891 class ComprehensionCodeGenerator(AbstractFunctionCodeGenerator):
2892
2893 def _compile(self, node):
2894 self.argcount = 1
2895 assert isinstance(node, ast.expr)
2896 self.update_position(node)
2897 node.build_container_and_load_iter(self)
2898 self._comp_generator(node, node.get_generators())
2899 self._end_comp()
2900
2901 def comprehension_load_iter(self):
2902 self.emit_op_arg(ops.LOAD_FAST, 0)
2903
2904 def _end_comp(self):
2905 self.emit_op(ops.RETURN_VALUE)
2906
2907 def _check_async_function(self):
2908 return True
2909
2910
2911 class GenExpCodeGenerator(ComprehensionCodeGenerator):
2912
2913 def _end_comp(self):
2914 pass
2915
2916 def _get_code_flags(self):
2917 flags = ComprehensionCodeGenerator._get_code_flags(self)
2918 return flags | consts.CO_GENERATOR
2919
2920
2921 class ClassCodeGenerator(PythonCodeGenerator):
2922
2923 def _compile(self, cls):
2924 assert isinstance(cls, ast.ClassDef)
2925 self.ensure_docstring_constant(cls.body)
2926 self.first_lineno = cls.lineno
2927 if cls.decorator_list and cls.decorator_list[0].lineno > 0:
2928 self.first_lineno = cls.decorator_list[0].lineno
2929 # bit weird, but CPython does that too: the line of the artificial
2930 # first instructions is that of the first decorator
2931 self.update_position((self.first_lineno, -1, -1, -1))
2932 self.argcount = 1
2933 # load (global) __name__ ...
2934 self.name_op("__name__", ast.Load, None)
2935 # ... and store it as __module__
2936 self.name_op("__module__", ast.Store, None)
2937 # store the qualname
2938 w_qualname = self.space.newtext(self.qualname)
2939 self.load_const(w_qualname)
2940 self.name_op("__qualname__", ast.Store, None)
2941 self._maybe_setup_annotations()
2942 # compile the body proper
2943 self._handle_body(cls.body)
2944
2945 self.no_position_info()
2946 # return the (empty) __class__ cell
2947 scope = self.scope.lookup("__class__")
2948 if scope == symtable.SCOPE_CELL_CLASS:
2949 # Return the cell where to store __class__
2950 self.emit_op_arg(ops.LOAD_CLOSURE, self.cell_vars["__class__"])
2951 self.emit_op(ops.DUP_TOP)
2952 self.name_op("__classcell__", ast.Store, None)
2953 else:
2954 # This happens when nobody references the cell
2955 self.load_const(self.space.w_None)
2956 self.emit_op(ops.RETURN_VALUE)
2957
2958 def _get_code_flags(self):
2959 flags = 0
2960 if self.scope.doc_removable:
2961 flags |= consts.CO_KILL_DOCSTRING
2962 return PythonCodeGenerator._get_code_flags(self) | flags
2963
2964
2965 class CallCodeGenerator(object):
2966 def __init__(self, codegenerator, nargs_pushed, args, keywords):
2967 self.space = codegenerator.space
2968 self.codegenerator = codegenerator
2969 self.nargs_pushed = nargs_pushed
2970 self.args = args
2971 self.keywords = keywords
2972
2973 self.have_starargs = False
2974 # the number of dictionaries on the stack
2975 self.have_kwargs = False
2976 self.keyword_names_w = []
2977 self.seen_keyword_names = {}
2978
2979 def _make_starargs_list(self):
2980 if not self.have_starargs:
2981 self.codegenerator.emit_op_arg(ops.BUILD_LIST, self.nargs_pushed)
2982 self.have_starargs = True
2983 self.nargs_pushed = 0
2984 else:
2985 assert self.nargs_pushed == 0
2986
2987 def _push_args(self):
2988 if len(self.args) == 1 and not self.nargs_pushed:
2989 arg = self.args[0]
2990 if isinstance(arg, ast.Starred):
2991 arg.value.walkabout(self.codegenerator)
2992 self.have_starargs = True
2993 return
2994
2995 for elt in self.args:
2996 if isinstance(elt, ast.Starred):
2997 # we have a *arg
2998 self._make_starargs_list()
2999 elt.value.walkabout(self.codegenerator)
3000 self.codegenerator.emit_op_arg(ops.LIST_EXTEND, 1)
3001 continue
3002 if self.nargs_pushed >= MAX_STACKDEPTH_CONTAINERS // 2:
3003 # stack depth getting too big
3004 self._make_starargs_list()
3005 elt.walkabout(self.codegenerator)
3006 if self.have_starargs:
3007 self.codegenerator.emit_op_arg(ops.LIST_APPEND, 1)
3008 else:
3009 self.nargs_pushed += 1
3010 if self.have_starargs:
3011 self.codegenerator.emit_op(ops.LIST_TO_TUPLE)
3012
3013 def _pack_kwargs_into_dict(self):
3014 if self.keyword_names_w:
3015 self.codegenerator._load_constant_tuple(self.keyword_names_w)
3016 # XXX use BUILD_MAP for size 1?
3017 self.codegenerator.emit_op_arg(ops.BUILD_CONST_KEY_MAP, len(self.keyword_names_w))
3018 self.keyword_names_w = []
3019 if self.have_kwargs: # we already have a map, merge the new one in
3020 self.codegenerator.emit_op(ops.DICT_MERGE)
3021 self.have_kwargs = True
3022
3023 def _push_kwargs(self):
3024 if len(self.keywords) == 1:
3025 kw = self.keywords[0]
3026 assert isinstance(kw, ast.keyword)
3027 if kw.arg is None:
3028 # exactly a **kwarg, no need to copy dicts around
3029 # (cpython cannot do this, because the call machinery really
3030 # *needs* a dict. but in argument.py deals with non-dicts just
3031 # fine)
3032 kw.value.walkabout(self.codegenerator)
3033 self.have_kwargs = True
3034 return
3035 for kw in self.keywords:
3036 assert isinstance(kw, ast.keyword)
3037 self.codegenerator.check_forbidden_name(kw.arg, kw)
3038 if kw.arg is None:
3039 # if we see **args or if the number of keywords is huge,
3040 # pack up keywords on the stack so far
3041 self._pack_kwargs_into_dict()
3042 if not self.have_kwargs:
3043 # no kwargs, build an empty dict
3044 self.codegenerator.emit_op_arg(ops.BUILD_MAP, 0)
3045 kw.value.walkabout(self.codegenerator)
3046 self.codegenerator.emit_op(ops.DICT_MERGE)
3047 self.have_kwargs = True
3048 continue
3049 if kw.arg in self.seen_keyword_names:
3050 self.codegenerator.error(
3051 "keyword argument repeated: %s" % (kw.arg, ), kw)
3052 self.seen_keyword_names[kw.arg] = None
3053 if len(self.keyword_names_w) > MAX_STACKDEPTH_CONTAINERS // 2:
3054 self._pack_kwargs_into_dict()
3055 w_name = self.space.newtext(kw.arg)
3056 self.keyword_names_w.append(misc.intern_if_common_string(self.space, w_name))
3057 kw.value.walkabout(self.codegenerator)
3058
3059 def _make_starargs_at_end(self):
3060 if self.nargs_pushed == 0:
3061 self.codegenerator._load_constant_tuple([])
3062 else:
3063 self.codegenerator.emit_op_arg(ops.BUILD_TUPLE, self.nargs_pushed)
3064 self.have_starargs = True
3065
3066 def _push_tuple_positional_args_if_necessary(self):
3067 if self.have_starargs:
3068 # can't use CALL_FUNCTION_KW anyway, because we already have a
3069 # tuple as the positional args
3070 return
3071 # we might get away with using CALL_FUNCTION_KW if there are no **kwargs
3072 for kw in self.keywords:
3073 assert isinstance(kw, ast.keyword)
3074 if kw.arg is None:
3075 # we found a **kwarg, thus we're using CALL_FUNCTION_EX, we
3076 # need to pack up positional arguments first
3077 self._make_starargs_at_end()
3078 break
3079 if not self.have_starargs and len(self.keywords) > MAX_STACKDEPTH_CONTAINERS // 2:
3080 # we have a huge amount of keyword args, thus we also need to use
3081 # CALL_FUNCTION_EX
3082 self._make_starargs_at_end()
3083
3084 def emit_call(self):
3085 keywords = self.keywords
3086 codegenerator = self.codegenerator
3087 space = self.space
3088 if self.args is not None:
3089 self._push_args()
3090
3091 # Repeat procedure for keyword args
3092 if keywords is None or len(keywords) == 0:
3093 if not self.have_starargs:
3094 # no *args, no keyword args, no **kwargs
3095 codegenerator.emit_op_arg(ops.CALL_FUNCTION, self.nargs_pushed)
3096 return
3097 else:
3098 self._push_tuple_positional_args_if_necessary()
3099 self._push_kwargs()
3100
3101 if not self.have_kwargs and not self.have_starargs:
3102 # can use CALL_FUNCTION_KW
3103 assert len(self.keyword_names_w) > 0 # otherwise we would have used CALL_FUNCTION
3104 codegenerator._load_constant_tuple(self.keyword_names_w)
3105 codegenerator.emit_op_arg(ops.CALL_FUNCTION_KW, self.nargs_pushed + len(self.keyword_names_w))
3106 else:
3107 self._pack_kwargs_into_dict()
3108 codegenerator.emit_op_arg(ops.CALL_FUNCTION_EX, int(self.have_kwargs))
3109
3110 def rot_n(l, rotarg):
3111 # act like the ROT_N bytecode on l
3112 top = l[-1]
3113 for i in range(rotarg - 1):
3114 l[-i-1] = l[-i-2]
3115 l[-rotarg] = top
3116
3117 def compute_reordering(l):
3118 if not we_are_translated():
3119 assert set(l) == set(range(len(l)))
3120
3121 # look for descending chains
3122 correct_lower_index = 0
3123 while correct_lower_index < len(l) - 1:
3124 if l[correct_lower_index] > l[correct_lower_index + 1]:
3125 correct_lower_index += 1
3126 else:
3127 break
3128
3129 rot_sequence = []
3130 while correct_lower_index < len(l) - 1:
3131 # bring the top element to the right place
3132 top = l[-1]
3133 if top > l[correct_lower_index]:
3134 # merge it into the chain at the beginning
3135 index = -1
3136 for index in range(correct_lower_index + 1):
3137 if l[index] < top:
3138 break
3139 assert index >= 0
3140 rotarg = len(l) - index
3141 else:
3142 # sort it next to the ascending chain
3143 rotarg = len(l) - correct_lower_index - 1
3144 rot_sequence.append(rotarg)
3145 rot_n(l, rotarg)
3146 correct_lower_index += 1
3147
3148 # paranoia
3149 target = len(l) - 1
3150 for element in l:
3151 assert element == target
3152 target -= 1
3153 assert target == -1
3154 return rot_sequence
3155
3156
3157 def view(startblock):
3158 from rpython.translator.tool.graphpage import GraphPage, DotGen
3159 if isinstance(startblock, list):
3160 blocks = startblock
3161 startblock = None
3162 else:
3163 blocks = startblock.post_order()
3164 graph = DotGen('block')
3165 blocknames = {block: "block_%s" % (i, ) for i, block in enumerate(blocks)}
3166 for i, block in enumerate(blocks):
3167 name = blocknames[block]
3168 label = ["pos in blocks: %s/%s\\n" % (i + 1, len(blocks))]
3169 if hasattr(block, 'initial_depth'):
3170 label.append('initial stack depth: %s' % (block.initial_depth, ))
3171 if block.marked != 0:
3172 label.append("marked: %s\\n" % block.marked)
3173
3174 fillcolor = "white"
3175 if block is startblock:
3176 fillcolor = "gray"
3177 color = "black"
3178
3179 for j, instr in enumerate(block.instructions):
3180 str_instr = "%5s: %s" % (instr.position_info[0], instr.opname())
3181 if instr.opcode >= ops.HAVE_ARGUMENT and instr.jump is None:
3182 str_instr += " %s" % (instr.arg, )
3183 if instr._stack_depth_after != -99:
3184 str_instr += " stack depth after: %s" % instr._stack_depth_after
3185 if instr._stack_depth_after < 0:
3186 fillcolor = "red"
3187 label.append(str_instr)
3188 if instr.jump is not None:
3189 graph.emit_node(name, shape="box", label="\\l".join(label), fillcolor=fillcolor, color=color)
3190 nextname = "block_%s_%s" % (i, j)
3191 graph.emit_edge(name, blocknames.get(instr.jump, "unknown_block"))
3192 if j != len(block.instructions) - 1:
3193 label = []
3194 graph.emit_edge(name, nextname, color="green")
3195 name = nextname
3196 color = "green"
3197 graph.emit_node(name, shape="box", label="\\l".join(label), fillcolor=fillcolor, color=color)
3198 if block.next_block is not None:
3199 if (not block.instructions or block.instructions[-1].opcode not in
3200 (ops.JUMP_FORWARD, ops.JUMP_ABSOLUTE, ops.RETURN_VALUE,
3201 ops.RERAISE, ops.RAISE_VARARGS)):
3202 color = "black"
3203 else:
3204 color = "grey"
3205 graph.emit_edge(name, blocknames.get(block.next_block, "unknown_block"), color=color)
3206
3207 from rpython.translator.tool.graphpage import FlowGraphPage
3208 p = GraphPage()
3209 p.links = {}
3210 p.source = graph.generate(target=None)
3211 p.display()
3212