Debian Codegraph @

pypy/interpreter/pycode.py

raw symbols SCIP
1 # encoding: utf-8
2 """
3 Python-style code objects.
4 PyCode instances have the same co_xxx arguments as CPython code objects.
5 The bytecode interpreter itself is implemented by the PyFrame class.
6 """
7
8 import imp, struct, types, sys, os
9
10 from pypy.interpreter import eval
11 from pypy.interpreter.signature import Signature
12 from pypy.interpreter.baseobjspace import W_Root
13 from pypy.interpreter.error import OperationError, oefmt
14 from pypy.interpreter.gateway import unwrap_spec, applevel
15 from pypy.interpreter.astcompiler.consts import (
16 CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS, CO_NESTED,
17 CO_GENERATOR, CO_COROUTINE, CO_KILL_DOCSTRING, CO_YIELD_INSIDE_TRY,
18 CO_ITERABLE_COROUTINE, CO_ASYNC_GENERATOR)
19 from pypy.tool.stdlib_opcode import opcodedesc, HAVE_ARGUMENT
20 from rpython.rlib.rarithmetic import intmask, r_uint
21 from rpython.rlib.objectmodel import compute_hash, we_are_translated, not_rpython, always_inline
22 from rpython.rlib import jit, rstring
23
24
25 class BytecodeCorruption(Exception):
26 """Detected bytecode corruption. Never caught; it's an error."""
27
28 # helper
29
30 def unpack_text_tuple(space, w_str_tuple):
31 return [space.text_w(w_el) for w_el in space.unpackiterable(w_str_tuple)]
32
33
34 # Magic numbers for the bytecode version in code objects.
35 # See comments in pypy/module/imp/importing.
36 cpython_magic, = struct.unpack("<i", imp.get_magic()) # host magic number
37
38 # we compute the magic number in a similar way to CPython, but we use a
39 # different value for the highest 16 bits. Bump pypy_incremental_magic every
40 # time you make pyc files incompatible. This value ends up in the frozen
41 # importlib, via MAGIC_NUMBER in module/_frozen_importlib/__init__.
42
43 pypy_incremental_magic = 432 # bump it by 16
44 assert pypy_incremental_magic % 16 == 0
45 assert pypy_incremental_magic < 3000 # the magic number of Python 3. There are
46 # no known magic numbers below this value
47 default_magic = pypy_incremental_magic | (ord('\r')<<16) | (ord('\n')<<24)
48
49 def make_signature(code):
50 """Return a Signature instance."""
51 kwonlyargcount = code.co_kwonlyargcount
52 argcount = code.co_argcount + kwonlyargcount
53 varnames = code.co_varnames
54 posonlyargcount = code.co_posonlyargcount
55 assert argcount >= 0 # annotator hint
56 assert kwonlyargcount >= 0
57 assert posonlyargcount >= 0
58 argnames = list(varnames[:argcount])
59 if code.co_flags & CO_VARARGS:
60 varargname = varnames[argcount]
61 argcount += 1
62 else:
63 varargname = None
64 if code.co_flags & CO_VARKEYWORDS:
65 kwargname = code.co_varnames[argcount]
66 else:
67 kwargname = None
68 return Signature(argnames, varargname, kwargname, kwonlyargcount, posonlyargcount)
69
70 class CodeHookCache(object):
71 def __init__(self, space):
72 self._code_hook = None
73
74 app = applevel("""
75 def replace(self, kwds):
76 args = []
77 for attr in ("co_argcount", "co_posonlyargcount", "co_kwonlyargcount",
78 "co_nlocals", "co_stacksize", "co_flags", "co_code",
79 "co_consts", "co_names", "co_varnames", "co_filename",
80 "co_name", "co_qualname", "co_firstlineno", "co_linetable", "co_freevars",
81 "co_cellvars", "co_exceptiontable"):
82 if attr not in kwds:
83 args.append(getattr(self, attr))
84 else:
85 args.append(kwds.pop(attr))
86 if kwds:
87 raise TypeError(f"{kwds.popitem()[0]!r} is an invalid keyword argument for replace()")
88 return type(self)(*args)
89 """, filename=__file__)
90
91 codereplace = app.interphook("replace")
92
93 class PyCode(eval.Code):
94 "CPython-style code objects."
95 _immutable_fields_ = ["_signature", "co_argcount", "co_posonlyargcount", "co_kwonlyargcount",
96 "co_cellvars[*]",
97 "co_code", "co_consts_w[*]", "co_filename", "w_filename",
98 "co_qualname",
99 "co_firstlineno", "co_flags", "co_freevars[*]",
100 "co_names_w[*]", "co_nlocals",
101 "co_stacksize", "co_varnames[*]",
102 "_args_as_cellvars[*]",
103 "co_linetable",
104 "co_exceptiontable",
105 "w_globals?",
106 "cell_families[*]"]
107
108 def __init__(self, space, argcount, posonlyargcount, kwonlyargcount,
109 nlocals, stacksize, flags,
110 code, consts, names, varnames, filename,
111 name, qualname, firstlineno, linetable, freevars, cellvars,
112 hidden_applevel=False, magic=default_magic,
113 exceptiontable=''):
114 """Initialize a new code object from parameters given by
115 the pypy compiler"""
116 self.space = space
117 eval.Code.__init__(self, name)
118 assert nlocals >= 0
119 self.co_argcount = argcount
120 self.co_posonlyargcount = posonlyargcount
121 self.co_kwonlyargcount = kwonlyargcount
122 self.co_nlocals = nlocals
123 self.co_stacksize = stacksize
124 self.co_flags = flags
125 self.co_code = code
126 self.co_consts_w = consts
127 self.co_names_w = [
128 space.new_interned_str(aname)
129 for aname in names]
130 self.co_varnames = varnames
131 self.co_freevars = freevars
132 self.co_cellvars = cellvars
133 assert isinstance(filename, str)
134 rstring.check_str0(filename)
135 self.co_filename = filename
136 self.w_filename = space.newfilename(filename)
137 self.co_name = name
138 if qualname is None:
139 qualname = name
140 assert isinstance(qualname, str)
141 self.co_qualname = qualname
142 assert isinstance(firstlineno, int)
143 self.co_firstlineno = firstlineno
144 self.co_linetable = linetable
145 self.co_exceptiontable = exceptiontable
146 # store the first globals object that the code object is run in in
147 # here. if a frame is run in that globals object, it does not need to
148 # store it at all
149 self.w_globals = None
150 self.hidden_applevel = hidden_applevel
151 self.magic = magic
152 self._signature = make_signature(self)
153 self._initialize()
154 self._init_ready()
155 self.new_code_hook()
156
157 self._linelist = None # lazily initialized list of line numbers
158
159 def frame_stores_global(self, w_globals):
160 if self.w_globals is None:
161 self.w_globals = w_globals
162 return False
163 if self.w_globals is w_globals:
164 return False
165 return True
166
167 def new_code_hook(self):
168 code_hook = self.space.fromcache(CodeHookCache)._code_hook
169 if code_hook is not None:
170 try:
171 self.space.call_function(code_hook, self)
172 except OperationError as e:
173 e.write_unraisable(self.space, "new_code_hook()")
174
175 def _initialize(self):
176 from pypy.objspace.std.mapdict import init_mapdict_cache
177 from pypy.interpreter.nestedscope import CellFamily
178 if self.co_cellvars:
179 argcount = self.co_argcount
180 argcount += self.co_kwonlyargcount
181 assert argcount >= 0 # annotator hint
182 if self.co_flags & CO_VARARGS:
183 argcount += 1
184 if self.co_flags & CO_VARKEYWORDS:
185 argcount += 1
186 argvars = self.co_varnames
187 cellvars = self.co_cellvars
188 args_as_cellvars = _compute_args_as_cellvars(argvars, cellvars, argcount)
189 self._args_as_cellvars = args_as_cellvars
190 self.cell_families = [CellFamily(name) for name in cellvars]
191 else:
192 self._args_as_cellvars = []
193 self.cell_families = []
194
195 self._compute_flatcall()
196
197 init_mapdict_cache(self)
198 self._globals_caches = [None] * len(self.co_names_w)
199
200 def _init_ready(self):
201 "This is a hook for the vmprof module, which overrides this method."
202
203 def _cleanup_(self):
204 if (self.magic == cpython_magic and
205 '__pypy__' not in sys.builtin_module_names):
206 raise Exception("CPython host codes should not be rendered")
207 # When translating PyPy, freeze the file name
208 # <builtin>/lastdirname/basename.py
209 # instead of freezing the complete translation-time path.
210 filename = self.co_filename
211 if (filename.startswith('<builtin>') or
212 filename == '<frozen importlib._bootstrap>'):
213 return
214 filename = filename.lstrip('<').rstrip('>')
215 if filename.lower().endswith('.pyc'):
216 filename = filename[:-1]
217 basename = os.path.basename(filename)
218 lastdirname = os.path.basename(os.path.dirname(filename))
219 if lastdirname:
220 basename = '%s/%s' % (lastdirname, basename)
221 self.co_filename = '<builtin>/%s' % (basename,)
222 self.w_filename = self.space.newfilename(self.co_filename)
223
224 co_names = property(lambda self: [self.space.text_w(w_name) for w_name in self.co_names_w]) # for trace
225
226 def signature(self):
227 return self._signature
228
229 @jit.elidable
230 def lookup_exceptiontable(self, instr_offset):
231 """Search co_exceptiontable for a handler covering instr_offset.
232 Returns (target, depth, lasti) as (r_uint, int, bool).
233 depth == -1 means no handler was found (sentinel for not-found)."""
234 table = self.co_exceptiontable
235 best = (r_uint(0), -1, False)
236 if not table:
237 return best
238 i = 0
239 n = len(table)
240 while i < n:
241 start_raw, i = _decode_varint(table, i)
242 start = start_raw * 2
243 length_raw, i = _decode_varint(table, i)
244 length = length_raw * 2
245 target_raw, i = _decode_varint(table, i)
246 target = target_raw * 2
247 dl, i = _decode_varint(table, i)
248 depth = dl >> 1
249 lasti = bool(dl & 1)
250 if start <= instr_offset < start + length:
251 best = (r_uint(target), depth, lasti)
252 elif start > instr_offset:
253 break
254 return best # depth == -1 means not found
255
256 def _compute_flatcall(self):
257 # Speed hack!
258 self.fast_natural_arity = eval.Code.HOPELESS
259 if self.co_flags & (CO_VARARGS | CO_VARKEYWORDS):
260 return
261 if len(self._args_as_cellvars) > 0:
262 return
263 if self.co_kwonlyargcount > 0:
264 return
265 if self.co_argcount > 0xff:
266 return
267
268 self.fast_natural_arity = eval.Code.FLATPYCALL | self.co_argcount
269
270 def funcrun(self, func, args):
271 frame = self.space.createframe(self, func.w_func_globals,
272 func)
273 sig = self._signature
274 # speed hack
275 fresh_frame = jit.hint(frame, access_directly=True,
276 fresh_virtualizable=True)
277 args.parse_into_scope(None, fresh_frame.locals_cells_stack_w, func.qualname,
278 sig, func.defs_w, func.w_kw_defs)
279 fresh_frame.init_cells()
280 return frame.run(func.name, func.qualname)
281
282 def funcrun_obj(self, func, w_obj, args):
283 frame = self.space.createframe(self, func.w_func_globals,
284 func)
285 sig = self._signature
286 # speed hack
287 fresh_frame = jit.hint(frame, access_directly=True,
288 fresh_virtualizable=True)
289 args.parse_into_scope(w_obj, fresh_frame.locals_cells_stack_w, func.qualname,
290 sig, func.defs_w, func.w_kw_defs)
291 fresh_frame.init_cells()
292 return frame.run(func.name, func.qualname)
293
294 def getvarnames(self):
295 return self.co_varnames
296
297 def getdocstring(self, space):
298 if self.co_consts_w: # it is probably never empty
299 w_first = self.co_consts_w[0]
300 if space.isinstance_w(w_first, space.w_unicode):
301 return w_first
302 return space.w_None
303
304 def remove_docstrings(self, space):
305 if self.co_flags & CO_KILL_DOCSTRING:
306 self.co_consts_w[0] = space.w_None
307 for w_co in self.co_consts_w:
308 if isinstance(w_co, PyCode):
309 w_co.remove_docstrings(space)
310
311 def exec_host_bytecode(self, w_globals, w_locals):
312 raise Exception("no longer supported after the switch to wordcode!")
313
314 @not_rpython
315 def dump(self):
316 """A dis.dis() dump of the code object."""
317 from pypy.tool import dis3
318 dis3._disassemble_recursive(self)
319
320 @property
321 @not_rpython
322 def co_consts(self):
323 return [w if isinstance(w, PyCode) else self.space.unwrap(w)
324 for w in self.co_consts_w]
325
326 def fget_co_consts(self, space):
327 return space.newtuple(self.co_consts_w)
328
329 def fget_co_names(self, space):
330 return space.newtuple(self.co_names_w)
331
332 def fget_co_varnames(self, space):
333 return space.newtuple([space.newtext(name) for name in self.co_varnames])
334
335 def fget_co_cellvars(self, space):
336 return space.newtuple([space.newtext(name) for name in self.co_cellvars])
337
338 def fget_co_freevars(self, space):
339 return space.newtuple([space.newtext(name) for name in self.co_freevars])
340
341 @unwrap_spec(index=int)
342 def descr__varname_from_oparg(self, space, index):
343 """Return the local variable name for the given oparg index.
344
345 The index maps into co_varnames + co_cellvars + co_freevars.
346 """
347 nlocals = self.co_nlocals
348 ncellvars = len(self.co_cellvars)
349 nfreevars = len(self.co_freevars)
350
351 if index >= 0:
352 if index < nlocals:
353 return space.newtext(self.co_varnames[index])
354 index -= nlocals
355 if index < ncellvars:
356 return space.newtext(self.co_cellvars[index])
357 index -= ncellvars
358 if index < nfreevars:
359 return space.newtext(self.co_freevars[index])
360 raise oefmt(space.w_IndexError, "tuple index out of range")
361
362 def descr_code__eq__(self, w_other):
363 space = self.space
364 if not isinstance(w_other, PyCode):
365 return space.w_NotImplemented
366 areEqual = (self.co_name == w_other.co_name and
367 self.co_qualname == w_other.co_qualname and
368 self.co_argcount == w_other.co_argcount and
369 self.co_posonlyargcount == w_other.co_posonlyargcount and
370 self.co_kwonlyargcount == w_other.co_kwonlyargcount and
371 self.co_nlocals == w_other.co_nlocals and
372 self.co_flags == w_other.co_flags and
373 self.co_firstlineno == w_other.co_firstlineno and
374 self.co_code == w_other.co_code and
375 len(self.co_consts_w) == len(w_other.co_consts_w) and
376 len(self.co_names_w) == len(w_other.co_names_w) and
377 self.co_varnames == w_other.co_varnames and
378 self.co_freevars == w_other.co_freevars and
379 self.co_cellvars == w_other.co_cellvars)
380 if not areEqual:
381 return space.w_False
382
383 for i in range(len(self.co_names_w)):
384 if not space.eq_w(self.co_names_w[i], w_other.co_names_w[i]):
385 return space.w_False
386
387 for i in range(len(self.co_consts_w)):
388 if not _code_const_eq(space, self.co_consts_w[i], w_other.co_consts_w[i]):
389 return space.w_False
390
391 return space.w_True
392
393 def descr_code__ne__(self, w_other):
394 space = self.space
395 if not isinstance(w_other, PyCode):
396 return space.w_NotImplemented
397 return space.not_(self.descr_code__eq__(w_other))
398
399 def descr_code__hash__(self):
400 def scramble_in(result, h):
401 result ^= h
402 return intmask(r_uint(result) * r_uint(1000003))
403 space = self.space
404 result = 20250211
405 result = scramble_in(result, compute_hash(self.co_name))
406 result = scramble_in(result, compute_hash(self.co_qualname))
407 result = scramble_in(result, self.co_argcount)
408 result = scramble_in(result, self.co_posonlyargcount)
409 result = scramble_in(result, self.co_kwonlyargcount)
410 result = scramble_in(result, self.co_nlocals)
411 result = scramble_in(result, self.co_flags)
412 result = scramble_in(result, self.co_firstlineno)
413 result = scramble_in(result, compute_hash(self.co_code))
414 for name in self.co_varnames: result = scramble_in(result, compute_hash(name))
415 for name in self.co_freevars: result = scramble_in(result, compute_hash(name))
416 for name in self.co_cellvars: result = scramble_in(result, compute_hash(name))
417 for w_name in self.co_names_w:
418 result = scramble_in(result, space.hash_w(w_name))
419 for w_const in self.co_consts_w:
420 result = scramble_in(result, space.hash_w(w_const))
421 w_result = space.newint(intmask(result))
422 return w_result
423
424 @staticmethod
425 def const_comparison_key(space, w_obj):
426 return _convert_const(space, w_obj)
427
428 @unwrap_spec(argcount=int, posonlyargcount=int, kwonlyargcount=int,
429 nlocals=int, stacksize=int, flags=int,
430 codestring='bytes',
431 filename='fsencode', name='text', qualname='text', firstlineno=int,
432 linetable='bytes', exceptiontable='bytes', magic=int)
433 def descr_code__new__(space, w_subtype,
434 argcount, posonlyargcount, kwonlyargcount,
435 nlocals, stacksize, flags,
436 codestring, w_constants, w_names,
437 w_varnames, filename, name, qualname, firstlineno,
438 linetable, w_freevars=None, w_cellvars=None,
439 exceptiontable='', magic=default_magic):
440 if argcount < 0:
441 raise oefmt(space.w_ValueError,
442 "code: argcount must not be negative")
443 if posonlyargcount < 0:
444 raise oefmt(space.w_ValueError,
445 "code: posonlyargcount must not be negative")
446 if kwonlyargcount < 0:
447 raise oefmt(space.w_ValueError,
448 "code: kwonlyargcount must not be negative")
449 if nlocals < 0:
450 raise oefmt(space.w_ValueError,
451 "code: nlocals must not be negative")
452 if not space.isinstance_w(w_constants, space.w_tuple):
453 raise oefmt(space.w_TypeError, "Expected tuple for constants")
454 consts_w = space.fixedview(w_constants)
455 names = unpack_text_tuple(space, w_names)
456 varnames = unpack_text_tuple(space, w_varnames)
457 if w_freevars is not None:
458 freevars = unpack_text_tuple(space, w_freevars)
459 else:
460 freevars = []
461 if w_cellvars is not None:
462 cellvars = unpack_text_tuple(space, w_cellvars)
463 else:
464 cellvars = []
465 code = space.allocate_instance(PyCode, w_subtype)
466 PyCode.__init__(code, space, argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags, codestring, consts_w[:], names,
467 varnames, filename, name, qualname, firstlineno, linetable, freevars, cellvars, magic=magic,
468 exceptiontable=exceptiontable)
469 return code
470
471 def descr__reduce__(self, space):
472 from pypy.interpreter.mixedmodule import MixedModule
473 w_mod = space.getbuiltinmodule('_pickle_support')
474 mod = space.interp_w(MixedModule, w_mod)
475 new_inst = mod.get('code_new')
476 tup = [
477 space.newint(self.co_argcount),
478 space.newint(self.co_posonlyargcount),
479 space.newint(self.co_kwonlyargcount),
480 space.newint(self.co_nlocals),
481 space.newint(self.co_stacksize),
482 space.newint(self.co_flags),
483 space.newbytes(self.co_code),
484 space.newtuple(self.co_consts_w),
485 space.newtuple(self.co_names_w),
486 space.newtuple([space.newtext(v) for v in self.co_varnames]),
487 self.w_filename,
488 space.newtext(self.co_name),
489 space.newtext(self.co_qualname),
490 space.newint(self.co_firstlineno),
491 space.newbytes(self.co_linetable),
492 space.newtuple([space.newtext(v) for v in self.co_freevars]),
493 space.newtuple([space.newtext(v) for v in self.co_cellvars]),
494 space.newbytes(self.co_exceptiontable),
495 space.newint(self.magic),
496 ]
497 return space.newtuple2(new_inst, space.newtuple(tup))
498
499 def descr_co_positions(self, space):
500 """A list of 4-element tuples that represent the position information corresponding to each
501 instruction."""
502 from pypy.interpreter.location import _decode_entry, DecodeError
503 def w(space, i):
504 if i == -1:
505 return space.w_None
506 return space.newint(i)
507
508 # Check for -X no_debug_ranges / PYTHONNODEBUGRANGES: strip column info.
509 no_debug_ranges = False
510 w_xopts = space.sys.getdictvalue(space, '_xoptions')
511 if w_xopts is not None:
512 try:
513 space.getitem(w_xopts, space.newtext('no_debug_ranges'))
514 no_debug_ranges = True
515 except OperationError:
516 pass
517
518 if self.co_linetable == '':
519 return space.newlist([])
520
521 table_w = []
522 position = 0
523 table = self.co_linetable
524 while position < len(table):
525 try:
526 lineno, end_lineno, col_offset, end_col_offset, position = _decode_entry(table, self.co_firstlineno, position)
527 except DecodeError:
528 break
529 if no_debug_ranges and lineno != -1:
530 end_lineno = lineno
531 col_offset = -1
532 end_col_offset = -1
533 tup_w = [
534 w(space, lineno),
535 w(space, end_lineno),
536 w(space, col_offset),
537 w(space, end_col_offset)
538 ]
539 table_w.append(space.newtuple(tup_w))
540 return space.newlist(table_w)
541
542
543 def descr_replace(self, space, __args__):
544 """ replace(self, /, *, co_argcount=-1, co_posonlyargcount=-1, co_kwonlyargcount=-1, co_nlocals=-1, co_stacksize=-1, co_flags=-1, co_firstlineno=-1, co_code=None, co_consts=None, co_names=None, co_varnames=None, co_freevars=None, co_cellvars=None, co_filename=None, co_name=None, co_linetable=None, co_exceptiontable=None)
545 | Return a new code object with new specified fields.
546 """
547 w_args, w_kwds = __args__.topacked()
548 if space.is_true(w_args):
549 raise oefmt(space.w_TypeError, "replace() takes no positional arguments")
550 return codereplace(space, self, w_kwds)
551
552 def get_repr(self):
553 # This is called by the default get_printable_location so it
554 # must avoid doing too much (that might release the gil)
555 return '<code object %s, file "%s", line %d>' % (
556 self.co_name, self.co_filename,
557 -1 if self.co_firstlineno == 0 else self.co_firstlineno)
558
559 def iterator_greenkey_printable(self):
560 return self.get_repr()
561
562 def __repr__(self):
563 return self.get_repr()
564
565 def repr(self, space):
566 space = self.space
567 # co_name should be an identifier
568 name = self.co_name
569 fn = space.utf8_w(self.w_filename)
570 return space.newtext(b'<code object %s at 0x%s, file "%s", line %d>' % (
571 name, self.getaddrstring(space), fn,
572 -1 if self.co_firstlineno == 0 else self.co_firstlineno))
573
574 def co_lines(self, space):
575 # from PEP 626:
576 # The co_lines() method will return an iterator which yields tuples of
577 # values, each representing the line number of a range of bytecodes.
578 # Each tuple will consist of three values:
579 #
580 # - start - The offset (inclusive) of the start of the bytecode
581 # range
582 # - end - The offset (exclusive) of the end of the bytecode range
583 # - line - The line number, or None if the bytecodes in the given
584 # range do not have a line number.
585 #
586 #
587 # The sequence generated will have the following properties:
588 #
589 # - The first range in the sequence with have a start of 0
590 # - The (start, end) ranges will be non-decreasing and consecutive.
591 # That is, for any pair of tuples the start of the second will
592 # equal to the end of the first.
593 # - No range will be backwards, that is end >= start for all
594 # triples.
595 # - The final range in the sequence with have end equal to the size
596 # of the bytecode.
597 # - line will either be a positive integer, or None
598 return W_LineIterator(self.space, self)
599
600 def fget_co_lnotab(self, space):
601 return space.newbytes(
602 self.get_co_lnotab())
603
604 def get_co_lnotab(self):
605 from pypy.interpreter.location import linetable2lnotab
606 return linetable2lnotab(self.co_linetable, self.co_firstlineno)
607
608 @jit.elidable
609 def _get_lineno_for_pc_tracing(self, pc):
610 """ compute the lineno for a given pc. this is meant to be used when
611 tracing because it uses a bit of extra memory. """
612 from pypy.interpreter.location import _decode_entry, DecodeError
613 if self._linelist is None:
614 l = [-1] * (len(self.co_code) // 2)
615 position = 0
616 for i in range(len(l)):
617 try:
618 tup = _decode_entry(self.co_linetable, self.co_firstlineno, position)
619 except DecodeError:
620 break
621 position = tup[-1]
622 l[i] = tup[0]
623 self._linelist = l
624 return self._linelist[pc // 2]
625
626 def _marklines(self):
627 """ return a list of len(co_code) // 2 where every entry is -1 except
628 for those opcodes that start a new line, where the entry is the line
629 number. """
630 from pypy.interpreter.location import marklines, DecodeError
631 try:
632 return marklines(self.co_linetable, self.co_firstlineno)
633 except DecodeError:
634 return [-1] * (len(self.co_code) // 2)
635
636 class W_LineIterator(W_Root):
637 def __init__(self, space, w_code):
638 self.space = space
639 self.w_code = w_code
640 self.position = 0
641 self.pc = 0
642 self.line = w_code.co_firstlineno
643
644 def descr_iter(self):
645 return self
646
647 def descr_next(self):
648 from pypy.interpreter.location import DecodeError
649 try:
650 return self._next()
651 except DecodeError:
652 self.position = len(self.w_code.co_linetable)
653 space = self.space
654 raise OperationError(space.w_StopIteration, space.newtext(''))
655
656 def _next(self):
657 from pypy.interpreter.location import _decode_entry
658 space = self.space
659 linetable = self.w_code.co_linetable
660 position = self.position
661 if position >= len(linetable):
662 raise OperationError(space.w_StopIteration, space.newtext(''))
663 start = self.pc
664 lineno, _, _, _, position = _decode_entry(linetable, self.w_code.co_firstlineno, position)
665 self.pc += 2
666 while position < len(linetable):
667 next_lineno, _, _, _, next_position = _decode_entry(linetable, self.w_code.co_firstlineno, position)
668 if lineno == next_lineno:
669 position = next_position
670 self.pc += 2
671 continue
672 break
673 assert self.position != position
674 self.position = position
675 w_res = space.newtuple([
676 space.newint(start),
677 space.newint(self.pc),
678 space.newint(lineno) if lineno != -1 else space.w_None,
679 ])
680 return w_res
681
682 @always_inline # to not have to allocate the tuple result
683 def _decode_varint(table, i):
684 """Decode one CPython-3.11-compatible varint from table at byte position i.
685 Returns (value, new_i). Reads 6 bits per byte, MSB first. Bit 6 is the
686 continuation flag; bit 7 is the start-of-entry marker which is ignored
687 here (masked off along with the continuation bit by ``& 63``)."""
688 b = ord(table[i])
689 i += 1
690 value = b & 63
691 while b & 64:
692 b = ord(table[i])
693 i += 1
694 value = (value << 6) | (b & 63)
695 return value, i
696
697
698 def _compute_args_as_cellvars(varnames, cellvars, argcount):
699 # Cell vars could shadow already-set arguments.
700 # The compiler used to be clever about the order of
701 # the variables in both co_varnames and co_cellvars, but
702 # it no longer is for the sake of simplicity. Moreover
703 # code objects loaded from CPython don't necessarily follow
704 # an order, which could lead to strange bugs if .pyc files
705 # produced by CPython are loaded by PyPy. Note that CPython
706 # contains the following bad-looking nested loops at *every*
707 # function call!
708
709 # Precompute what arguments need to be copied into cellvars
710 args_as_cellvars = []
711 for i in range(len(cellvars)):
712 cellname = cellvars[i]
713 for j in range(argcount):
714 if cellname == varnames[j]:
715 # argument j has the same name as the cell var i
716 while len(args_as_cellvars) < i:
717 args_as_cellvars.append(-1) # pad
718 args_as_cellvars.append(j)
719 last_arg_cellarg = i
720 return args_as_cellvars[:]
721
722 def _code_const_eq(space, w_a, w_b):
723 # this is a mess! CPython has complicated logic for this. essentially this
724 # is supposed to be a "strong" equal, that takes types and signs of numbers
725 # into account, quite similar to how PyPy's 'is' behaves, but recursively
726 # in tuples and frozensets as well. Since PyPy already implements these
727 # rules correctly for ints, floats, bools, complex in 'is' and 'id', just
728 # use those.
729 return space.eq_w(_convert_const(space, w_a), _convert_const(space, w_b))
730
731 def _convert_const(space, w_a):
732 # use id to convert constants. for tuples and frozensets use tuples and
733 # frozensets of converted contents.
734 w_type = space.type(w_a)
735 if space.is_w(w_type, space.w_unicode):
736 # unicodes are supposed to compare by value, but not equal to bytes
737 return space.newtuple2(w_type, w_a)
738 if space.is_w(w_type, space.w_bytes):
739 # and vice versa
740 return space.newtuple2(w_type, w_a)
741 if type(w_a) is PyCode:
742 return w_a
743 # for tuples and frozensets convert recursively
744 if space.is_w(w_type, space.w_tuple):
745 elements_w = [_convert_const(space, w_x)
746 for w_x in space.unpackiterable(w_a)]
747 return space.newtuple(elements_w)
748 if space.is_w(w_type, space.w_frozenset):
749 elements_w = [_convert_const(space, w_x)
750 for w_x in space.unpackiterable(w_a)]
751 return space.newfrozenset(elements_w)
752 # use id for the rest
753 return space.id(w_a)
754