Debian Codegraph @

pypy/interpreter/pyframe.py

raw symbols SCIP
1 """ PyFrame class implementation with the interpreter main loop.
2 """
3
4 import sys
5 from rpython.rlib import jit, rweakref
6 from rpython.rlib.debug import make_sure_not_resized, check_nonneg
7 from rpython.rlib.debug import ll_assert_not_none
8 from rpython.rlib.jit import hint
9 from rpython.rlib.objectmodel import instantiate, specialize, we_are_translated
10 from rpython.rlib.objectmodel import not_rpython
11 from rpython.rlib.rarithmetic import intmask, r_uint, LONG_BIT
12 from rpython.tool.pairtype import extendabletype
13
14 from pypy.interpreter import pycode, pytraceback
15 from pypy.interpreter.argument import Arguments
16 from pypy.interpreter.astcompiler import consts
17 from pypy.interpreter.baseobjspace import W_Root
18 from pypy.interpreter.error import (
19 OperationError, oefmt)
20 from pypy.interpreter.executioncontext import ExecutionContext
21 from pypy.interpreter.nestedscope import Cell
22 from pypy.tool import stdlib_opcode
23
24 # Define some opcodes used
25 for op in '''DUP_TOP POP_TOP BEFORE_WITH
26 BEFORE_ASYNC_WITH YIELD_VALUE
27 NOP FOR_ITER EXTENDED_ARG END_ASYNC_FOR LOAD_CONST CALL_FUNCTION
28 JUMP_IF_FALSE_OR_POP JUMP_IF_TRUE_OR_POP POP_JUMP_IF_FALSE POP_JUMP_IF_TRUE
29 JUMP_IF_NOT_EXC_MATCH JUMP_ABSOLUTE JUMP_FORWARD GET_ITER GET_AITER
30 POP_JUMP_FORWARD_IF_NONE POP_JUMP_FORWARD_IF_NOT_NONE
31 RETURN_VALUE RERAISE RAISE_VARARGS POP_EXCEPT PUSH_EXC_INFO
32 '''.split():
33 globals()[op] = stdlib_opcode.opmap[op]
34
35 class FrameDebugData(object):
36 """ A small object that holds debug data for tracing
37 """
38 w_f_trace = None
39 instr_prev_plus_one = 0
40 f_lineno = 0 # current lineno for tracing
41 is_being_profiled = False
42 is_in_line_tracing = False
43 f_trace_lines = True
44 f_trace_opcodes = False
45 w_locals = None
46 hidden_operationerr = None
47
48 def __init__(self, pycode, init_lineno=-1):
49 self.f_lineno = init_lineno
50 self.w_globals = pycode.w_globals
51
52 class PyFrame(W_Root):
53 """Represents a frame for a regular Python function
54 that needs to be interpreted.
55
56 Public fields:
57 * 'space' is the object space this frame is running in
58 * 'code' is the PyCode object this frame runs
59 * 'w_locals' is the locals dictionary to use, if needed, stored on a
60 debug object
61 * 'w_globals' is the attached globals dictionary
62 * 'builtin' is the attached built-in module
63 * 'valuestack_w', 'blockstack', control the interpretation
64
65 Cell Vars:
66 my local variables that are exposed to my inner functions
67 Free Vars:
68 variables coming from a parent function in which i'm nested
69 'closure' is a list of Cell instances: the received free vars.
70 """
71
72 __metaclass__ = extendabletype
73
74 frame_finished_execution = False
75 f_generator_wref = rweakref.dead_ref # for generators/coroutines
76 f_generator_nowref = None # (only one of the two attrs)
77 w_yielding_from = None
78 last_instr = -1
79 f_backref = jit.vref_None
80
81 escaped = False # see mark_as_escaped()
82 debugdata = None
83
84 pycode = None # code object executed by that frame
85 locals_cells_stack_w = None # the list of all locals, cells and the valuestack
86 valuestackdepth = 0 # number of items on valuestack
87
88 # other fields:
89
90 # builtin - builtin cache, only if honor__builtins__ is True
91 # defaults to False
92
93 # there is also self.space which is removed by the annotator
94
95 # additionally JIT uses vable_token field that is representing
96 # frame current virtualizable state as seen by the JIT
97
98 def __init__(self, space, code, w_globals, outer_func):
99 self = hint(self, access_directly=True, fresh_virtualizable=True)
100 assert isinstance(code, pycode.PyCode)
101 self.space = space
102 self.pycode = code
103 if code.frame_stores_global(w_globals):
104 self.getorcreatedebug().w_globals = w_globals
105 stackstart = self._stack_start()
106 size = stackstart + code.co_stacksize
107 # the layout of this list is as follows:
108 # | local vars | cells | stack |
109 self.locals_cells_stack_w = [None] * size
110 self.valuestackdepth = stackstart
111 make_sure_not_resized(self.locals_cells_stack_w)
112 check_nonneg(self.valuestackdepth)
113 #
114 if space.config.objspace.honor__builtins__:
115 self.builtin = space.builtin.pick_builtin(w_globals)
116 # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS.
117 # class bodies only have CO_NEWLOCALS.
118 self.initialize_frame_scopes(outer_func, code)
119
120 def getdebug(self):
121 return self.debugdata
122
123 def getorcreatedebug(self, init_lineno=-1):
124 if self.debugdata is None:
125 self.debugdata = FrameDebugData(self.pycode, init_lineno)
126 return self.debugdata
127
128 def get_w_globals(self):
129 debugdata = self.getdebug()
130 if debugdata is not None:
131 return debugdata.w_globals
132 return jit.promote(self.pycode).w_globals
133
134 def get_w_f_trace(self):
135 d = self.getdebug()
136 if d is None:
137 return None
138 return d.w_f_trace
139
140 def get_is_being_profiled(self):
141 d = self.getdebug()
142 if d is None:
143 return False
144 return d.is_being_profiled
145
146 def get_w_locals(self):
147 d = self.getdebug()
148 if d is None:
149 return None
150 return d.w_locals
151
152 def get_f_trace_lines(self):
153 d = self.getdebug()
154 if d is None:
155 return True
156 return d.f_trace_lines
157
158 def get_f_trace_opcodes(self):
159 d = self.getdebug()
160 if d is None:
161 return False
162 return d.f_trace_opcodes
163
164 @not_rpython
165 def __repr__(self):
166 # useful in tracebacks
167 return "<%s.%s executing %s at line %s" % (
168 self.__class__.__module__, self.__class__.__name__,
169 self.pycode, self.get_last_lineno())
170
171 def _getcell(self, varindex):
172 cell = self.locals_cells_stack_w[varindex + self.pycode.co_nlocals]
173 assert isinstance(cell, Cell)
174 return cell
175
176 def mark_as_escaped(self):
177 """
178 Must be called on frames that are exposed to applevel, e.g. by
179 sys._getframe(). This ensures that the virtualref holding the frame
180 is properly forced by ec.leave(), and thus the frame will be still
181 accessible even after the corresponding C stack died.
182 """
183 self.escaped = True
184
185 def _restore_exc_info(self, w_prev):
186 """Restore sys.exc_info from w_prev (the value saved by PUSH_EXC_INFO)."""
187 space = self.space
188 if not self.hide():
189 space.getexecutioncontext().set_sys_exc_info3(w_prev)
190 else:
191 if space.is_none(w_prev):
192 self.getorcreatedebug().hidden_operationerr = None
193 else:
194 from pypy.module.exceptions.interp_exceptions import W_BaseException
195 w_val = space.interp_w(W_BaseException, w_prev)
196 operr = OperationError(space.type(w_prev), w_prev, w_val.w_traceback)
197 self.getorcreatedebug().hidden_operationerr = operr
198
199 def get_builtin(self):
200 if self.space.config.objspace.honor__builtins__:
201 return self.builtin
202 else:
203 return self.space.builtin
204
205 @jit.unroll_safe
206 def initialize_frame_scopes(self, outer_func, code):
207 # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS.
208 # class bodies only have CO_NEWLOCALS.
209 # CO_NEWLOCALS: make a locals dict unless optimized is also set
210 # CO_OPTIMIZED: no locals dict needed at all
211 flags = code.co_flags
212 if not (flags & pycode.CO_OPTIMIZED):
213 if flags & pycode.CO_NEWLOCALS:
214 self.getorcreatedebug().w_locals = self.space.newdict(module=True)
215 else:
216 w_globals = self.get_w_globals()
217 assert w_globals is not None
218 self.getorcreatedebug().w_locals = w_globals
219
220 ncellvars = len(code.co_cellvars)
221 nfreevars = len(code.co_freevars)
222 if not nfreevars:
223 if not ncellvars:
224 return # no cells needed - fast path
225 elif outer_func is None:
226 space = self.space
227 raise oefmt(space.w_TypeError,
228 "directly executed code object may not contain free "
229 "variables")
230 if outer_func and outer_func.closure:
231 closure_size = len(outer_func.closure)
232 else:
233 closure_size = 0
234 if closure_size != nfreevars:
235 raise ValueError("code object received a closure with "
236 "an unexpected number of free variables")
237 index = code.co_nlocals
238 for i in range(ncellvars):
239 self.locals_cells_stack_w[index] = Cell(
240 None, self.pycode.cell_families[i])
241 index += 1
242 for i in range(nfreevars):
243 self.locals_cells_stack_w[index] = outer_func.closure[i]
244 index += 1
245
246 def _is_generator_or_coroutine(self):
247 return (self.getcode().co_flags & (pycode.CO_COROUTINE |
248 pycode.CO_GENERATOR |
249 pycode.CO_ASYNC_GENERATOR)) != 0
250
251 def run(self, name=None, qualname=None):
252 """Start this frame's execution."""
253 if self._is_generator_or_coroutine():
254 return self.initialize_as_generator(name, qualname)
255 else:
256 return self.execute_frame()
257 run._always_inline_ = True
258
259 def initialize_as_generator(self, name, qualname):
260 space = self.space
261 flags = self.getcode().co_flags
262 if flags & pycode.CO_COROUTINE:
263 from pypy.interpreter.generator import Coroutine
264 gen = Coroutine(self, name, qualname)
265 ec = space.getexecutioncontext()
266 gen.capture_origin(ec)
267 elif flags & pycode.CO_ASYNC_GENERATOR:
268 from pypy.interpreter.generator import AsyncGenerator
269 gen = AsyncGenerator(self, name, qualname)
270 elif flags & pycode.CO_GENERATOR:
271 from pypy.interpreter.generator import GeneratorIterator
272 gen = GeneratorIterator(self, name, qualname)
273 else:
274 raise AssertionError("bad co_flags")
275
276 if space.config.translation.rweakref:
277 self.f_generator_wref = rweakref.ref(gen)
278 else:
279 self.f_generator_nowref = gen
280 w_gen = gen
281 return w_gen
282
283 def resume_execute_frame(self, w_arg_or_err):
284 # Called from execute_frame() just before resuming the bytecode
285 # interpretation.
286 from pypy.interpreter.pyopcode import SApplicationException
287 space = self.space
288 w_yf = self.w_yielding_from
289 if w_yf is not None:
290 self.w_yielding_from = None
291 try:
292 self.next_yield_from(w_yf, w_arg_or_err)
293 except OperationError as operr:
294 operr.record_context(space, space.getexecutioncontext())
295 return self.handle_generator_error(operr)
296 # Normal case: the call above raises Yield.
297 # We reach this point if the iterable is exhausted.
298 last_instr = jit.promote(self.last_instr)
299 assert last_instr & 1 == 0
300 assert last_instr >= 0
301 return r_uint(last_instr + 2)
302
303 if isinstance(w_arg_or_err, SApplicationException):
304 operr = w_arg_or_err.operr
305 operr.record_context(space, space.getexecutioncontext())
306 return self.handle_generator_error(operr)
307
308 last_instr = jit.promote(self.last_instr)
309 if last_instr != -1:
310 assert last_instr & 1 == 0
311 self.pushvalue(w_arg_or_err)
312 return r_uint(last_instr + 2)
313 else:
314 return r_uint(0)
315
316 def execute_frame(self, w_arg_or_err=None):
317 """Execute this frame. Main entry point to the interpreter.
318 'w_arg_or_err' is non-None iff we are starting or resuming
319 a generator or coroutine frame; in that case, w_arg_or_err
320 is the input argument -or- an SApplicationException instance.
321 """
322 from pypy.interpreter import pyopcode as pyopcode
323 # the following 'assert' is an annotation hint: it hides from
324 # the annotator all methods that are defined in PyFrame but
325 # overridden in the {,Host}FrameClass subclasses of PyFrame.
326 assert (isinstance(self, self.space.FrameClass) or
327 not self.space.config.translating)
328 executioncontext = self.space.getexecutioncontext()
329 executioncontext.enter(self)
330 got_exception = True
331 w_exitvalue = self.space.w_None
332 try:
333 executioncontext.call_trace(self)
334 #
335 # Execution starts just after the last_instr. Initially,
336 # last_instr is -1. After a generator suspends it points to
337 # the YIELD_VALUE/YIELD_FROM instruction.
338 try:
339 try:
340 if w_arg_or_err is None:
341 assert self.last_instr == -1
342 next_instr = r_uint(0)
343 else:
344 next_instr = self.resume_execute_frame(w_arg_or_err)
345 except pyopcode.Yield:
346 w_exitvalue = self.popvalue()
347 else:
348 w_exitvalue = self.dispatch(self.pycode, next_instr,
349 executioncontext)
350 except OperationError:
351 raise
352 except Exception as e: # general fall-back
353 raise self._convert_unexpected_exception(e)
354 finally:
355 executioncontext.return_trace(self, w_exitvalue)
356 got_exception = False
357 finally:
358 executioncontext.leave(self, w_exitvalue, got_exception)
359 return w_exitvalue
360 execute_frame.insert_stack_check_here = True
361
362 # stack manipulation helpers
363 def pushvalue(self, w_object):
364 depth = self.valuestackdepth
365 self.locals_cells_stack_w[depth] = ll_assert_not_none(w_object)
366 self.valuestackdepth = depth + 1
367
368 def pushvalue_none(self):
369 depth = self.valuestackdepth
370 # the entry is already None, and remains None
371 assert self.locals_cells_stack_w[depth] is None
372 self.valuestackdepth = depth + 1
373
374 def pushvalue_maybe_none(self, w_object):
375 depth = self.valuestackdepth
376 self.locals_cells_stack_w[depth] = w_object
377 self.valuestackdepth = depth + 1
378
379 def assert_stack_index(self, index):
380 if we_are_translated():
381 return
382 if not self._check_stack_index(index):
383 #import pdb; pdb.set_trace()
384 assert 0
385
386 def _stack_start(self):
387 code = self.pycode
388 return code.co_nlocals + len(code.co_cellvars) + len(code.co_freevars)
389
390 def _check_stack_index(self, index):
391 return index >= self._stack_start()
392
393 def popvalue(self):
394 return ll_assert_not_none(self.popvalue_maybe_none())
395
396 def popvalue_maybe_none(self):
397 depth = self.valuestackdepth - 1
398 self.assert_stack_index(depth)
399 assert depth >= 0
400 w_object = self.locals_cells_stack_w[depth]
401 self.locals_cells_stack_w[depth] = None
402 self.valuestackdepth = depth
403 return w_object
404
405
406 # we need two popvalues that return different data types:
407 # one in case we want list another in case of tuple
408 def _new_popvalues():
409 @jit.unroll_safe
410 def popvalues(self, n):
411 values_w = [None] * n
412 while True:
413 n -= 1
414 if n < 0:
415 break
416 values_w[n] = self.popvalue()
417 return values_w
418 return popvalues
419 popvalues = _new_popvalues()
420 popvalues_mutable = _new_popvalues()
421 del _new_popvalues
422
423 @jit.unroll_safe
424 def peekvalues(self, n):
425 values_w = [None] * n
426 base = self.valuestackdepth - n
427 self.assert_stack_index(base)
428 assert base >= 0
429 while True:
430 n -= 1
431 if n < 0:
432 break
433 values_w[n] = self.locals_cells_stack_w[base+n]
434 return values_w
435
436 @jit.unroll_safe
437 def dropvalues(self, n):
438 n = hint(n, promote=True)
439 finaldepth = self.valuestackdepth - n
440 self.assert_stack_index(finaldepth)
441 assert finaldepth >= 0
442 while True:
443 n -= 1
444 if n < 0:
445 break
446 self.locals_cells_stack_w[finaldepth+n] = None
447 self.valuestackdepth = finaldepth
448
449 @jit.unroll_safe
450 def pushrevvalues(self, n, values_w): # n should be len(values_w)
451 make_sure_not_resized(values_w)
452 while True:
453 n -= 1
454 if n < 0:
455 break
456 self.pushvalue(values_w[n])
457
458 @jit.unroll_safe
459 def dupvalues(self, n):
460 delta = n-1
461 while True:
462 n -= 1
463 if n < 0:
464 break
465 w_value = self.peekvalue(delta)
466 self.pushvalue(w_value)
467
468 def peekvalue(self, index_from_top=0):
469 # NOTE: top of the stack is peekvalue(0).
470 # Contrast this with CPython where it's PEEK(-1).
471 return ll_assert_not_none(self.peekvalue_maybe_none(index_from_top))
472
473 def peekvalue_maybe_none(self, index_from_top=0):
474 index_from_top = hint(index_from_top, promote=True)
475 index = self.valuestackdepth + ~index_from_top
476 self.assert_stack_index(index)
477 assert index >= 0
478 return self.locals_cells_stack_w[index]
479
480 def settopvalue(self, w_object, index_from_top=0):
481 index_from_top = hint(index_from_top, promote=True)
482 index = self.valuestackdepth + ~index_from_top
483 self.assert_stack_index(index)
484 assert index >= 0
485 self.locals_cells_stack_w[index] = ll_assert_not_none(w_object)
486
487 @jit.unroll_safe
488 def dropvaluesuntil(self, finaldepth):
489 depth = self.valuestackdepth - 1
490 finaldepth = hint(finaldepth, promote=True)
491 assert finaldepth >= 0
492 while depth >= finaldepth:
493 self.locals_cells_stack_w[depth] = None
494 depth -= 1
495 self.valuestackdepth = finaldepth
496
497 def make_arguments(self, nargs, methodcall=False, w_function=None):
498 return Arguments(
499 self.space, self.peekvalues(nargs), methodcall=methodcall, w_function=w_function)
500
501 def argument_factory(self, arguments, keyword_names_w, keywords_w, w_star, w_starstar, methodcall=False, w_function=None):
502 return Arguments(
503 self.space, arguments, keyword_names_w, keywords_w, w_star,
504 w_starstar, methodcall=methodcall, w_function=w_function)
505
506 def hide(self):
507 return self.pycode.hidden_applevel
508
509 def getcode(self):
510 return hint(self.pycode, promote=True)
511
512 @jit.look_inside_iff(lambda self, scope_w: jit.isvirtual(scope_w))
513 def setfastscope(self, scope_w):
514 """Initialize the fast locals from a list of values,
515 where the order is according to self.pycode.signature()."""
516 scope_len = len(scope_w)
517 if scope_len > self.pycode.co_nlocals:
518 raise ValueError("new fastscope is longer than the allocated area")
519 # don't assign directly to 'locals_cells_stack_w[:scope_len]' to be
520 # virtualizable-friendly
521 for i in range(scope_len):
522 self.locals_cells_stack_w[i] = scope_w[i]
523 self.init_cells()
524
525 def getdictscope(self):
526 """
527 Get the locals as a dictionary
528 """
529 self.fast2locals()
530 return self.debugdata.w_locals
531
532 def setdictscope(self, w_locals, skip_free_vars=False):
533 """
534 Initialize the locals from a dictionary.
535 """
536 self.getorcreatedebug().w_locals = w_locals
537 self.locals2fast(skip_free_vars=skip_free_vars)
538
539 @jit.unroll_safe
540 def fast2locals(self):
541 # Copy values from the fastlocals to self.w_locals
542 d = self.getorcreatedebug()
543 w_locals = d.w_locals
544 write = False
545 if w_locals is None:
546 w_locals = self.space.newdict(instance=True)
547 write = True
548 varnames = self.getcode().getvarnames()
549 for i in range(min(len(varnames), self.getcode().co_nlocals)):
550 name = varnames[i]
551 w_value = self.locals_cells_stack_w[i]
552 if w_value is not None:
553 self.space.setitem_str(w_locals, name, w_value)
554 else:
555 w_name = self.space.newtext(name)
556 try:
557 self.space.delitem(w_locals, w_name)
558 except OperationError as e:
559 if not e.match(self.space, self.space.w_KeyError):
560 raise
561
562 # cellvars are values exported to inner scopes
563 # freevars are values coming from outer scopes
564 # (see locals2fast for why CO_OPTIMIZED)
565 freevarnames = self.pycode.co_cellvars
566 if self.pycode.co_flags & consts.CO_OPTIMIZED:
567 freevarnames = freevarnames + self.pycode.co_freevars
568 for i in range(len(freevarnames)):
569 name = freevarnames[i]
570 cell = self._getcell(i)
571 try:
572 w_value = cell.get()
573 except ValueError:
574 w_name = self.space.newtext(name)
575 try:
576 self.space.delitem(w_locals, w_name)
577 except OperationError as e:
578 if not e.match(self.space, self.space.w_KeyError):
579 raise
580 else:
581 self.space.setitem_str(w_locals, name, w_value)
582 if write:
583 d.w_locals = w_locals
584
585
586 @jit.unroll_safe
587 def locals2fast(self, skip_free_vars=False):
588 # Copy values from self.w_locals to the fastlocals
589 w_locals = self.getorcreatedebug().w_locals
590 assert w_locals is not None
591 varnames = self.getcode().getvarnames()
592 numlocals = self.getcode().co_nlocals
593
594 new_fastlocals_w = [None] * numlocals
595
596 for i in range(min(len(varnames), numlocals)):
597 name = varnames[i]
598 w_value = self.space.finditem_str(w_locals, name)
599 if w_value is not None:
600 new_fastlocals_w[i] = w_value
601
602 self.setfastscope(new_fastlocals_w)
603
604 freevarnames = self.pycode.co_cellvars
605 if self.pycode.co_flags & consts.CO_OPTIMIZED and not skip_free_vars:
606 freevarnames = freevarnames + self.pycode.co_freevars
607 # If the namespace is unoptimized, then one of the
608 # following cases applies:
609 # 1. It does not contain free variables, because it
610 # uses import * or is a top-level namespace.
611 # 2. It is a class namespace.
612 # We don't want to accidentally copy free variables
613 # into the locals dict used by the class.
614 for i in range(len(freevarnames)):
615 name = freevarnames[i]
616 cell = self._getcell(i)
617 w_value = self.space.finditem_str(w_locals, name)
618 if w_value is not None:
619 cell.set(w_value)
620 else:
621 cell.set(None)
622
623 @jit.unroll_safe
624 def init_cells(self):
625 """
626 Initialize cellvars from self.locals_cells_stack_w.
627 """
628 args_to_copy = self.pycode._args_as_cellvars
629 index = self.pycode.co_nlocals
630 for i in range(len(args_to_copy)):
631 argnum = args_to_copy[i]
632 if argnum >= 0:
633 cell = self.locals_cells_stack_w[index]
634 assert isinstance(cell, Cell)
635 cell.set(self.locals_cells_stack_w[argnum])
636 index += 1
637
638 def getclosure(self):
639 return None
640
641 def fget_code(self, space):
642 return self.getcode()
643
644 def fget_getdictscope(self, space):
645 return self.getdictscope()
646
647 def fget_w_globals(self, space):
648 # bit silly, but GetSetProperty passes a space
649 return self.get_w_globals()
650
651
652 ### line numbers ###
653
654 def fget_f_lineno(self, space):
655 "Returns the line number of the instruction currently being executed."
656 lineno = self.get_last_lineno()
657 if self.get_w_f_trace() is None:
658 if lineno == -1:
659 return space.w_None
660 return space.newint(lineno)
661 else:
662 if lineno == -1:
663 lineno = self.pycode.co_firstlineno
664 return space.newint(lineno)
665
666 def fset_f_lineno(self, space, w_new_lineno):
667 "Change the line number of the instruction currently being executed."
668 try:
669 new_lineno = space.int_w(w_new_lineno)
670 except OperationError:
671 raise oefmt(space.w_ValueError, "lineno must be an integer")
672
673 # You can only do this from within a trace function, not via
674 # _getframe or similar hackery.
675 if space.int_w(self.fget_f_lasti(space)) == -1:
676 raise oefmt(space.w_ValueError,
677 "can't jump from the 'call' trace event of a new frame")
678 if self.get_w_f_trace() is None:
679 raise oefmt(space.w_ValueError,
680 "f_lineno can only be set by a trace function")
681
682 # Allow jumps from a 'line' event, or from a 'return' event when the
683 # frame is suspended at a yield (FRAME_SUSPENDED in CPython terms).
684 d = self.getorcreatedebug()
685 if not d.is_in_line_tracing:
686 code = self.pycode.co_code
687 if ord(code[self.last_instr]) != YIELD_VALUE:
688 raise oefmt(space.w_ValueError,
689 "can only jump from a 'line' trace event")
690
691 line = self.pycode.co_firstlineno
692 if new_lineno < line:
693 raise oefmt(space.w_ValueError,
694 "line %d comes before the current code block", new_lineno)
695
696 lines = self.pycode._marklines()
697 x = first_line_not_before(lines, new_lineno)
698
699 # If we didn't reach the requested line, return an error.
700 if x == -1:
701 raise oefmt(space.w_ValueError,
702 "line %d comes after the current code block", new_lineno)
703 new_lineno = x
704
705 stacks = mark_stacks(self.pycode)
706 instr_idx = self.last_instr // 2
707 start_stack = stacks[instr_idx]
708 best_stack = stacks.UNINITIALIZED
709
710 error = "cannot find bytecode for specified line"
711 best_addr = -1
712 for i in range(len(lines)):
713 if lines[i] == new_lineno:
714 target_stack = stacks[i]
715 if stacks.compatible(start_stack, target_stack):
716 error = None
717 if target_stack > best_stack:
718 best_stack = target_stack
719 best_addr = i * 2
720 elif error is not None:
721 if start_stack == stacks.OVERFLOWED:
722 error = "stack too deep to analyze"
723 elif start_stack == stacks.UNINITIALIZED:
724 error = "can't jump from unreachable code"
725 elif target_stack > 0:
726 error = stacks.explain_incompatible(target_stack)
727 else:
728 error = "code may be unreachable"
729 if error is not None:
730 raise OperationError(space.w_ValueError, space.newtext(error))
731
732 # If suspended at a yield, YIELD_VALUE has already popped the value
733 # from the runtime stack. Account for this before unwinding.
734 # (CPython: "Account for value popped by yield", frameobject.c)
735 _co_code = self.pycode.co_code
736 if ord(_co_code[self.last_instr]) == YIELD_VALUE:
737 start_stack = start_stack >> stacks.BITS
738
739 while start_stack > best_stack:
740 kind = start_stack & stacks.MASK
741 if kind == stacks.EXCEPT:
742 # pop prev_exc from value stack and restore sys.exc_info
743 w_prev = self.popvalue()
744 self._restore_exc_info(w_prev)
745 elif kind == stacks.WITH:
746 # pop __exit__ from value stack; no FinallyBlock to pop (Phase 6)
747 self.popvalue()
748 else:
749 # Iterator, Object: just discard
750 self.popvalue()
751 start_stack = start_stack >> stacks.BITS
752
753 d.f_lineno = new_lineno
754 assert best_addr & 1 == 0
755 self.last_instr = best_addr
756
757 def get_last_lineno(self):
758 "Returns the line number of the instruction currently being executed."
759 return pytraceback.offset2lineno(self.pycode, self.last_instr)
760
761 def fget_f_builtins(self, space):
762 return self.get_builtin().getdict(space)
763
764 def get_f_back(self):
765 return ExecutionContext.getnextframe_nohidden(self)
766
767 def fget_f_back(self, space):
768 return self.get_f_back()
769
770 def fget_f_lasti(self, space):
771 return self.space.newint(self.last_instr)
772
773 def fget_f_trace(self, space):
774 return self.get_w_f_trace()
775
776 def fset_f_trace(self, space, w_trace):
777 if space.is_w(w_trace, space.w_None):
778 self.getorcreatedebug().w_f_trace = None
779 else:
780 d = self.getorcreatedebug()
781 d.w_f_trace = w_trace
782 d.f_lineno = self.get_last_lineno()
783
784 def fdel_f_trace(self, space):
785 self.getorcreatedebug().w_f_trace = None
786
787 def fget_f_trace_lines(self, space):
788 return space.newbool(self.get_f_trace_lines())
789
790 def fset_f_trace_lines(self, space, w_trace):
791 self.getorcreatedebug().f_trace_lines = space.is_true(w_trace)
792
793 def fget_f_trace_opcodes(self, space):
794 return space.newbool(self.get_f_trace_opcodes())
795
796 def fset_f_trace_opcodes(self, space, w_trace):
797 self.getorcreatedebug().f_trace_opcodes = space.is_true(w_trace)
798
799 def get_generator(self):
800 if self.space.config.translation.rweakref:
801 return self.f_generator_wref()
802 else:
803 return self.f_generator_nowref
804
805 def descr_clear(self, space):
806 """F.clear(): clear most references held by the frame"""
807 # Clears a random subset of the attributes: the local variables
808 # and the w_locals. Note that CPython doesn't clear f_locals
809 # (which can create leaks) but it's hard to notice because
810 # the next Python-level read of 'frame.f_locals' will clear it.
811 if not self.frame_finished_execution:
812 if not self._is_generator_or_coroutine():
813 raise oefmt(space.w_RuntimeError,
814 "cannot clear an executing frame")
815 gen = self.get_generator()
816 if gen is not None:
817 if gen.running:
818 raise oefmt(space.w_RuntimeError,
819 "cannot clear an executing frame")
820 gen._finalize_()
821
822 debug = self.getdebug()
823 if debug is not None:
824 debug.w_f_trace = None
825 if debug.w_locals is not None:
826 debug.w_locals = space.newdict()
827
828 # clear the locals, including the cell/free vars, and the stack
829 for i in range(len(self.locals_cells_stack_w)):
830 w_oldvalue = self.locals_cells_stack_w[i]
831 if isinstance(w_oldvalue, Cell):
832 # we can't mutate w_oldvalue here, because that could still be
833 # shared by an inner/outer function
834 w_newvalue = Cell(
835 None, w_oldvalue.family)
836 else:
837 w_newvalue = None
838 self.locals_cells_stack_w[i] = w_newvalue
839 self.valuestackdepth = 0
840
841 def _convert_unexpected_exception(self, e):
842 from pypy.interpreter import error
843
844 operr = error.get_converted_unexpected_exception(self.space, e)
845 pytraceback.record_application_traceback(
846 self.space, operr, self, self.last_instr)
847 raise operr
848
849 def descr_repr(self, space):
850 code = self.pycode
851 moreinfo = ", file '%s', line %s, code %s" % (
852 code.co_filename, self.get_last_lineno(), code.co_name)
853 return self.getrepr(space, "frame", moreinfo)
854
855 # ____________________________________________________________
856 # Abstract value-stack state tracking for fset_f_lineno.
857 # Stack values are packed integers: BITS bits per slot, TOS in the lowest bits.
858
859 class MarkStacks(object):
860 """Abstract value-stack state computed by mark_stacks.
861
862 Returned by mark_stacks(); supports index access (stacks[i]) and len().
863 Stack values are packed ints: BITS bits per slot, TOS in lowest bits.
864 """
865 BITS = 3
866 MASK = (1 << BITS) - 1
867 # 20 slots on 64-bit, 10 on 32-bit: result must fit in a signed platform int
868 _WILL_OVERFLOW = 1 << min(LONG_BIT - 2, 20 * BITS)
869
870 UNINITIALIZED = -2
871 OVERFLOWED = -1
872 EMPTY = 0
873 ITERATOR = 1 # iterator pushed by GET_ITER/GET_AITER
874 EXCEPT = 2 # prev_exc pushed by PUSH_EXC_INFO
875 OBJECT = 3 # ordinary value
876 WITH = 4 # __exit__ callable pushed by BEFORE_WITH (PyPy-specific)
877 LASTI = 5 # raise-site offset pushed on lasti=True handler dispatch
878
879 def __init__(self, n):
880 self._stacks = [self.UNINITIALIZED] * (n + 1)
881 self._stacks[0] = self.EMPTY
882
883 def push(self, stack, kind):
884 if stack < 0 or stack >= self._WILL_OVERFLOW:
885 return self.OVERFLOWED
886 return (stack << self.BITS) | kind
887
888 def pop_to_level(self, stack, level):
889 while True:
890 depth = 0
891 tmp = stack
892 while tmp:
893 depth += 1
894 tmp >>= self.BITS
895 if depth <= level:
896 break
897 stack >>= self.BITS
898 return stack
899
900 def set(self, idx, s, changed=False):
901 if self._stacks[idx] == self.UNINITIALIZED:
902 self._stacks[idx] = s
903 return True
904 return changed
905
906 def __getitem__(self, idx):
907 return self._stacks[idx]
908
909 def __len__(self):
910 return len(self._stacks)
911
912 def compatible(self, from_stack, to_stack):
913 if from_stack < 0 or to_stack < 0:
914 return False
915 from_depth = 0
916 tmp = from_stack
917 while tmp:
918 from_depth += 1
919 tmp >>= self.BITS
920 to_depth = 0
921 tmp = to_stack
922 while tmp:
923 to_depth += 1
924 tmp >>= self.BITS
925 if from_depth < to_depth:
926 return False
927 # Strip extra items from from_stack to match to_stack depth.
928 fs = from_stack >> (self.BITS * (from_depth - to_depth))
929 ts = to_stack
930 while ts:
931 fk = fs & self.MASK
932 tk = ts & self.MASK
933 if not self._compatible_kind(fk, tk):
934 return False
935 fs >>= self.BITS
936 ts >>= self.BITS
937 return True
938
939 def _compatible_kind(self, from_kind, to_kind):
940 if to_kind == self.OBJECT:
941 return from_kind != 0
942 return from_kind == to_kind
943
944 def explain_incompatible(self, to_stack):
945 if to_stack == self.OVERFLOWED:
946 return "stack too deep to analyze"
947 if to_stack == self.UNINITIALIZED or to_stack == self.EMPTY:
948 return "code may be unreachable"
949 ts = to_stack
950 kind = self.EMPTY
951 while ts:
952 kind = ts & self.MASK
953 ts >>= self.BITS
954 if kind == self.EXCEPT:
955 return "can't jump into an 'except' block as there's no exception"
956 elif kind == self.ITERATOR:
957 return "can't jump into the body of a for loop"
958 elif kind == self.WITH:
959 return "can't jump into the body of a with statement"
960 else:
961 return "can't jump to target"
962
963
964 def first_line_not_before(lines, line):
965 result = sys.maxint
966 for index, l in enumerate(lines):
967 if l < result and l >= line:
968 result = l
969 if result == sys.maxint:
970 return -1
971 return result
972
973 def mark_stacks(code):
974 """Compute abstract value-stack state at each instruction index.
975
976 Returns a MarkStacks instance of length (len(co_code)//2 + 1).
977 """
978 from pypy.interpreter.astcompiler.assemble import _opcode_stack_effect
979 from pypy.interpreter.pycode import _decode_varint
980
981 n = len(code.co_code) // 2
982 ms = MarkStacks(n)
983 raw = code.co_exceptiontable
984
985 changed = True
986 while changed:
987 changed = False
988 for i in range(n):
989 stack = ms[i]
990 if stack < 0:
991 continue
992 opcode = ord(code.co_code[i * 2])
993 # Handle EXTENDED_ARG: _get_arg reads at byte address i*2
994 arg = _get_arg(code.co_code, i * 2)
995
996 if opcode == RETURN_VALUE or opcode == RAISE_VARARGS or opcode == RERAISE:
997 pass # terminal; no fall-through
998 elif opcode == JUMP_FORWARD:
999 j = arg + i + 1 # instruction index
1000 changed = ms.set(j, stack, changed)
1001 elif opcode == JUMP_ABSOLUTE:
1002 j = arg # instruction index
1003 changed = ms.set(j, stack, changed)
1004 elif (opcode == POP_JUMP_IF_FALSE or opcode == POP_JUMP_IF_TRUE):
1005 # pop TOS (condition), branch or fall
1006 popped = stack >> ms.BITS
1007 j = arg # absolute instruction index
1008 changed = ms.set(j, popped, changed)
1009 changed = ms.set(i + 1, popped, changed)
1010 elif (opcode == POP_JUMP_FORWARD_IF_NONE or
1011 opcode == POP_JUMP_FORWARD_IF_NOT_NONE):
1012 # pop TOS, branch forward (relative) or fall through
1013 popped = stack >> ms.BITS
1014 j = arg + i + 1 # relative instruction index
1015 changed = ms.set(j, popped, changed)
1016 changed = ms.set(i + 1, popped, changed)
1017 elif (opcode == JUMP_IF_FALSE_OR_POP or opcode == JUMP_IF_TRUE_OR_POP):
1018 j = arg # absolute instruction index
1019 # branch: TOS stays; fall-through: TOS popped
1020 changed = ms.set(j, stack, changed)
1021 changed = ms.set(i + 1, stack >> ms.BITS, changed)
1022 elif opcode == JUMP_IF_NOT_EXC_MATCH:
1023 # pops two values (exc + type), branches if no match
1024 popped = stack >> (ms.BITS * 2)
1025 j = arg # absolute instruction index
1026 changed = ms.set(j, popped, changed)
1027 changed = ms.set(i + 1, popped, changed)
1028 elif opcode == FOR_ITER:
1029 # fall-through: iterator still on stack, push Object (loop var)
1030 ft = ms.push(stack, ms.OBJECT)
1031 changed = ms.set(i + 1, ft, changed)
1032 # branch (exhausted): pop iterator
1033 j = arg + i + 1
1034 changed = ms.set(j, stack >> ms.BITS, changed)
1035 elif opcode == GET_ITER or opcode == GET_AITER:
1036 # replace TOS Object with Iterator
1037 new_stack = ms.push(stack >> ms.BITS, ms.ITERATOR)
1038 changed = ms.set(i + 1, new_stack, changed)
1039 elif opcode == END_ASYNC_FOR:
1040 # pops 2: iterator + exception (or similar)
1041 new_stack = stack >> (ms.BITS * 2)
1042 changed = ms.set(i + 1, new_stack, changed)
1043 elif opcode == PUSH_EXC_INFO:
1044 # pops Object (new_exc), pushes prev_exc (Except) then new_exc (Object)
1045 below = stack >> ms.BITS
1046 new_stack = ms.push(ms.push(below, ms.EXCEPT), ms.OBJECT)
1047 changed = ms.set(i + 1, new_stack, changed)
1048 elif opcode == POP_EXCEPT:
1049 # pops the prev_exc (Except slot)
1050 new_stack = stack >> ms.BITS
1051 changed = ms.set(i + 1, new_stack, changed)
1052 elif opcode == BEFORE_WITH or opcode == BEFORE_ASYNC_WITH:
1053 # pops manager, pushes __exit__ (WITH kind) then __enter__ result (Object)
1054 below = stack >> ms.BITS
1055 new_stack = ms.push(ms.push(below, ms.WITH), ms.OBJECT)
1056 changed = ms.set(i + 1, new_stack, changed)
1057 elif opcode == EXTENDED_ARG:
1058 # Prefix byte; no stack effect.
1059 changed = ms.set(i + 1, stack, changed)
1060 else:
1061 delta = _opcode_stack_effect(opcode, arg)
1062 new_stack = stack
1063 if delta < 0:
1064 new_stack = new_stack >> (ms.BITS * (-delta))
1065 elif delta > 0:
1066 for _ in range(delta):
1067 new_stack = ms.push(new_stack, ms.OBJECT)
1068 changed = ms.set(i + 1, new_stack, changed)
1069 # Exception table scan: seed handler entries from the body-range start stack.
1070 # Must be inside the while-changed loop so ms[start_raw] is initialized.
1071 pos = 0
1072 while pos < len(raw):
1073 start_raw, pos = _decode_varint(raw, pos)
1074 length_raw, pos = _decode_varint(raw, pos)
1075 target_raw, pos = _decode_varint(raw, pos)
1076 dl, pos = _decode_varint(raw, pos)
1077 depth = dl >> 1
1078 lasti = dl & 1
1079 start_stack = ms[start_raw]
1080 if start_stack != ms.UNINITIALIZED:
1081 handler_stack = ms.pop_to_level(start_stack, depth)
1082 if lasti:
1083 handler_stack = ms.push(handler_stack, ms.LASTI)
1084 handler_stack = ms.push(handler_stack, ms.EXCEPT)
1085 changed = ms.set(target_raw, handler_stack, changed)
1086 return ms
1087
1088 def _get_arg(code, addr):
1089 # read backwards for EXTENDED_ARG; addr is a byte address
1090 oparg = ord(code[addr + 1])
1091 if addr >= 2 and ord(code[addr - 2]) == EXTENDED_ARG:
1092 oparg |= ord(code[addr - 1]) << 8
1093 if addr >= 4 and ord(code[addr - 4]) == EXTENDED_ARG:
1094 raise ValueError("fix me please!")
1095 return oparg
1096
1097