Debian Codegraph @

pypy/interpreter/baseobjspace.py

raw symbols SCIP
1 import sys
2 import py
3
4 from rpython.rlib.cache import Cache
5 from rpython.tool.uid import HUGEVAL_BYTES
6 from rpython.rlib import jit, types, rutf8, rstring
7 from rpython.rlib.debug import make_sure_not_resized, check_not_access_directly
8 from rpython.rlib.objectmodel import (we_are_translated, newlist_hint,
9 compute_unique_id, specialize, not_rpython)
10 from rpython.rlib.signature import signature
11 from rpython.rlib.rarithmetic import r_uint, SHRT_MIN, SHRT_MAX, \
12 INT_MIN, INT_MAX, UINT_MAX, USHRT_MAX
13 from rpython.rlib.buffer import StringBuffer
14
15 from pypy.interpreter.buffer import BufferInterfaceNotFound
16 from pypy.interpreter.executioncontext import (ExecutionContext, ActionFlag,
17 make_finalizer_queue)
18 from pypy.interpreter.error import OperationError, new_exception_class, oefmt
19 from pypy.interpreter.argument import Arguments
20 from pypy.interpreter.miscutils import ThreadLocals, make_weak_value_dictionary
21 from pypy.tool.generate_stdlib_module_names import get_stdlib_names
22
23
24 __all__ = ['ObjSpace', 'OperationError', 'W_Root']
25
26 def get_printable_location(greenkey):
27 return "unpackiterable [%s]" % (greenkey.iterator_greenkey_printable(), )
28
29 unpackiterable_driver = jit.JitDriver(name='unpackiterable',
30 greens=['greenkey'],
31 reds='auto',
32 get_printable_location=get_printable_location)
33
34
35 class W_Root(object):
36 """This is the abstract root class of all wrapped objects that live
37 in a 'normal' object space like StdObjSpace."""
38 __slots__ = ('__weakref__',)
39 _must_be_light_finalizer_ = True
40 user_overridden_class = False
41
42 def getdict(self, space):
43 return None
44
45 def getdictvalue(self, space, attr):
46 w_dict = self.getdict(space)
47 if w_dict is not None:
48 return space.finditem_str(w_dict, attr)
49 return None
50
51 def setdictvalue(self, space, attr, w_value):
52 w_dict = self.getdict(space)
53 if w_dict is not None:
54 space.setitem_str(w_dict, attr, w_value)
55 return True
56 return False
57
58 def deldictvalue(self, space, attr):
59 w_dict = self.getdict(space)
60 if w_dict is not None:
61 try:
62 space.delitem(w_dict, space.newtext(attr))
63 return True
64 except OperationError as ex:
65 if not ex.match(space, space.w_KeyError):
66 raise
67 return False
68
69 def setdict(self, space, w_dict):
70 raise oefmt(space.w_TypeError,
71 "attribute '__dict__' of %T objects is not writable",
72 self)
73
74 # to be used directly only by space.type implementations
75 def getclass(self, space):
76 # make sure that we never annotate this with access_directly set to
77 # True. otherwise every call to getclass (and other methods) has an
78 # extra indirection due to a much more complicated function set
79 check_not_access_directly(self)
80 return space.gettypefor(self.__class__)
81
82 def setclass(self, space, w_subtype):
83 raise oefmt(space.w_TypeError,
84 "__class__ assignment: only for heap types")
85
86 def user_setup(self, space, w_subtype):
87 raise NotImplementedError("only for interp-level user subclasses "
88 "from typedef.py")
89
90 def getname(self, space):
91 try:
92 return space.utf8_w(space.getattr(self, space.newtext('__name__')))
93 except OperationError:
94 return '?'
95
96 def getaddrstring(self, space):
97 # slowish
98 w_id = space.id(self)
99 w_4 = space.newint(4)
100 w_0x0F = space.newint(0x0F)
101 i = 2 * HUGEVAL_BYTES
102 addrstring = [' '] * i
103 while True:
104 n = space.int_w(space.and_(w_id, w_0x0F), allow_conversion=False)
105 n += ord('0')
106 if n > ord('9'):
107 n += (ord('a') - ord('9') - 1)
108 i -= 1
109 addrstring[i] = chr(n)
110 if i == 0:
111 break
112 w_id = space.rshift(w_id, w_4)
113 return ''.join(addrstring)
114
115 def getrepr(self, space, info, moreinfo=''):
116 addrstring = self.getaddrstring(space)
117 return space.newtext("<%s at 0x%s%s>" % (info, addrstring, moreinfo))
118
119 def getslotvalue(self, index):
120 raise NotImplementedError
121
122 def setslotvalue(self, index, w_val):
123 raise NotImplementedError
124
125 def delslotvalue(self, index):
126 raise NotImplementedError
127
128 def descr_call_mismatch(self, space, opname, RequiredClass, args):
129 if RequiredClass is None:
130 classname = '?'
131 else:
132 classname = wrappable_class_name(RequiredClass)
133 raise oefmt(space.w_TypeError,
134 "'%s' object expected, got '%T' instead", classname, self)
135
136 # used by _weakref implemenation
137
138 def getweakref(self):
139 return None
140
141 def setweakref(self, space, weakreflifeline):
142 raise oefmt(space.w_TypeError,
143 "cannot create weak reference to '%T' object", self)
144
145 def delweakref(self):
146 pass
147
148 def clear_all_weakrefs(self):
149 """Ensures that weakrefs (if any) are cleared now. This is
150 called by UserDelAction before the object is finalized further.
151 """
152 lifeline = self.getweakref()
153 if lifeline is not None:
154 # Clear all weakrefs to this object before we proceed with
155 # the destruction of the object. We detach the lifeline
156 # first: if the code following before_del() calls the
157 # app-level, e.g. a user-defined __del__(), and this code
158 # tries to use weakrefs again, it won't reuse the broken
159 # (already-cleared) weakrefs from this lifeline.
160 self.delweakref()
161 lifeline.clear_all_weakrefs()
162
163 def _finalize_(self):
164 """The RPython-level finalizer.
165
166 By default, it is *not called*. See self.register_finalizer().
167 Be ready to handle the case where the object is only half
168 initialized. Also, in some cases the object might still be
169 visible to app-level after _finalize_() is called (e.g. if
170 there is a __del__ that resurrects).
171 """
172
173 def register_finalizer(self, space):
174 """Register a finalizer for this object, so that
175 self._finalize_() will be called. You must call this method at
176 most once. Be ready to handle in _finalize_() the case where
177 the object is half-initialized, even if you only call
178 self.register_finalizer() at the end of the initialization.
179 This is because there are cases where the finalizer is already
180 registered before: if the user makes an app-level subclass with
181 a __del__. (In that case only, self.register_finalizer() does
182 nothing, because the finalizer is already registered in
183 allocate_instance().)
184 """
185 if self.user_overridden_class and self.getclass(space).hasuserdel:
186 # already registered by space.allocate_instance()
187 if not we_are_translated():
188 assert space.finalizer_queue._already_registered(self)
189 else:
190 if not we_are_translated():
191 # does not make sense if _finalize_ is not overridden
192 assert self._finalize_.im_func is not W_Root._finalize_.im_func
193 space.finalizer_queue.register_finalizer(self)
194
195 def may_unregister_rpython_finalizer(self, space):
196 """Optimization hint only: if there is no user-defined __del__()
197 method, pass the hint ``don't call any finalizer'' to rgc.
198 """
199 if not self.getclass(space).hasuserdel:
200 from rpython.rlib import rgc
201 rgc.may_ignore_finalizer(self)
202
203 # hooks that the mapdict implementations needs:
204 def _get_mapdict_map(self):
205 return None
206 def _set_mapdict_map(self, map):
207 raise NotImplementedError
208 def _mapdict_read_storage(self, index):
209 raise NotImplementedError
210 def _mapdict_write_storage(self, index, value):
211 raise NotImplementedError
212 def _mapdict_storage_length(self):
213 raise NotImplementedError
214 def _set_mapdict_storage_and_map(self, storage, map):
215 raise NotImplementedError
216
217
218 # -------------------------------------------------------------------
219 # cpyext support
220 # these functions will only be seen by the annotator if we translate
221 # with the cpyext module
222
223 def _cpyext_as_pyobj(self, space):
224 from pypy.module.cpyext.pyobject import w_root_as_pyobj
225 return w_root_as_pyobj(self, space)
226
227 def _cpyext_attach_pyobj(self, space, py_obj):
228 from pypy.module.cpyext.pyobject import w_root_attach_pyobj
229 return w_root_attach_pyobj(self, space, py_obj)
230
231 # -------------------------------------------------------------------
232
233 # hpy support
234
235 def _hpy_get_raw_storage(self, space):
236 raise oefmt(space.w_SystemError, "trying to read hpy storage from wrong object of type %T", self)
237
238 def _hpy_get_gc_storage(self, space):
239 raise oefmt(space.w_SystemError, "trying to read hpy storage from wrong object of type %T", self)
240
241 def _hpy_set_raw_storage(self, space, storage):
242 raise oefmt(space.w_SystemError, "trying to write hpy storage into wrong object of type %T", self)
243
244 # -------------------------------------------------------------------
245
246 def is_w(self, space, w_other):
247 return self is w_other
248
249 def immutable_unique_id(self, space):
250 return None
251
252 def buffer_w(self, space, flags):
253 return self.__buffer_w(space, flags).buffer_w(space, flags)
254
255 def __buffer_w(self, space, flags):
256 w_impl = space.lookup(self, '__buffer__')
257 if w_impl is not None:
258 w_result = space.get_and_call_function(w_impl, self,
259 space.newint(flags))
260 if space.isinstance_w(w_result, space.w_memoryview):
261 return w_result
262 raise BufferInterfaceNotFound
263
264 def bytes_w(self, space):
265 self._typed_unwrap_error(space, "bytes")
266
267 def text_w(self, space):
268 self._typed_unwrap_error(space, "str")
269
270 def utf8_w(self, space):
271 self._typed_unwrap_error(space, "str")
272
273 def convert_to_w_unicode(self, space):
274 self._typed_unwrap_error(space, "str")
275
276 def bytearray_list_of_chars_w(self, space):
277 self._typed_unwrap_error(space, "bytearray")
278
279 def int_w(self, space, allow_conversion=True):
280 # note that W_IntObject.int_w has a fast path and W_FloatObject.int_w
281 # raises w_TypeError
282 w_obj = self
283 if allow_conversion:
284 w_obj = space.int(self)
285 return w_obj._int_w(space)
286
287 def _int_w(self, space):
288 self._typed_unwrap_error(space, "integer")
289
290 def float_w(self, space, allow_conversion=True):
291 w_obj = self
292 if allow_conversion:
293 w_obj = space.float(self)
294 return w_obj._float_w(space)
295
296 def _float_w(self, space):
297 self._typed_unwrap_error(space, "float")
298
299 def uint_w(self, space):
300 self._typed_unwrap_error(space, "integer")
301
302 def bigint_w(self, space, allow_conversion=True):
303 # note that W_IntObject and W_LongObject have fast paths,
304 # W_FloatObject.rbigint_w raises w_TypeError raises
305 w_obj = self
306 if allow_conversion:
307 w_obj = space.int(self)
308 return w_obj._bigint_w(space)
309
310 def _bigint_w(self, space):
311 self._typed_unwrap_error(space, "integer")
312
313 def _typed_unwrap_error(self, space, expected):
314 raise oefmt(space.w_TypeError,
315 "expected %s, got %T object", expected, self)
316
317 def int(self, space):
318 from pypy.objspace.std.intobject import W_AbstractIntObject
319 w_impl = space.lookup(self, '__int__')
320 if w_impl is None:
321 w_impl = space.lookup(self, '__index__')
322 if w_impl is None:
323 self._typed_unwrap_error(space, "integer")
324 w_result = space.get_and_call_function(w_impl, self)
325
326 if space.is_w(space.type(w_result), space.w_int):
327 assert isinstance(w_result, W_AbstractIntObject)
328 return w_result
329 if space.isinstance_w(w_result, space.w_int):
330 assert isinstance(w_result, W_AbstractIntObject)
331 tp = space.type(w_result).name
332 space.warn(space.newtext(
333 "__int__ returned non-int (type %s). "
334 "The ability to return an instance of a strict subclass of int "
335 "is deprecated, and may be removed in a future version of "
336 "Python." % (tp,)), space.w_DeprecationWarning)
337 return w_result
338 raise oefmt(space.w_TypeError,
339 "__int__ returned non-int (type '%T')", w_result)
340
341 def ord(self, space):
342 raise oefmt(space.w_TypeError,
343 "ord() expected string of length 1, but %T found", self)
344
345 def spacebind(self, space):
346 """ Return a version of the object bound to a specific object space
347 instance. This is used for objects (like e.g. TypeDefs) that are
348 constructed before there is an object space instance. """
349 return self
350
351 @not_rpython
352 def unwrap(self, space):
353 # _____ this code is here to support testing only _____
354 return self
355
356 def unpackiterable_int(self, space):
357 lst = space.listview_int(self)
358 if lst:
359 return lst[:]
360 return None
361
362 def unpackiterable_float(self, space):
363 lst = space.listview_float(self)
364 if lst:
365 return lst[:]
366 return None
367
368 def iterator_greenkey(self, space):
369 """ Return something that can be used as a green key in jit drivers
370 that iterate over self. by default, it's just the type of self, but
371 custom iterators should override it. """
372 return space.type(self)
373
374 def iterator_greenkey_printable(self):
375 return "?"
376
377
378 class InternalSpaceCache(Cache):
379 """A generic cache for an object space. Arbitrary information can
380 be attached to the space by defining a function or class 'f' which
381 can be called as 'f(space)'. Its result is stored in this
382 ObjSpaceCache.
383 """
384 def __init__(self, space):
385 Cache.__init__(self)
386 self.space = space
387 def _build(self, callable):
388 return callable(self.space)
389
390 class SpaceCache(Cache):
391 """A base class for all our concrete caches."""
392 def __init__(self, space):
393 Cache.__init__(self)
394 self.space = space
395
396 def _build(self, key):
397 return self.build(key)
398
399 def _ready(self, result):
400 return self.ready(result)
401
402 def ready(self, result):
403 pass
404
405 class DescrMismatch(Exception):
406 pass
407
408 @specialize.memo()
409 def wrappable_class_name(Class):
410 if 'exact_class_applevel_name' in Class.__dict__:
411 return Class.exact_class_applevel_name
412 try:
413 return Class.typedef.name
414 except AttributeError:
415 return 'internal subclass of %s' % (Class.__name__,)
416
417 class CannotHaveLock(Exception):
418 """Raised by space.allocate_lock() if we're translating."""
419
420 # ____________________________________________________________
421
422 class ObjSpace(object):
423 """Base class for the interpreter-level implementations of object spaces.
424 http://pypy.readthedocs.org/en/latest/objspace.html"""
425
426 reverse_debugging = False
427
428 @not_rpython
429 def __init__(self, config=None):
430 "Basic initialization of objects."
431 self.w_default_importlib_import = None
432
433 self.fromcache = InternalSpaceCache(self).getorbuild
434 self.threadlocals = ThreadLocals()
435 # set recursion limit
436 # sets all the internal descriptors
437 if config is None:
438 from pypy.config.pypyoption import get_pypy_config
439 config = get_pypy_config(translating=False)
440 self.config = config
441 self.reverse_debugging = config.translation.reverse_debugger
442
443 self.builtin_modules = {}
444 self.reloading_modules = {}
445
446 self.interned_strings = make_weak_value_dictionary(self, str, W_Root)
447 self.actionflag = ActionFlag() # changed by the signal module
448 self.check_signal_action = None # changed by the signal module
449 make_finalizer_queue(W_Root, self)
450 self._code_of_sys_exc_info = None
451
452 self._builtin_functions_by_identifier = {'': None}
453
454 # can be overridden to a subclass
455 self.initialize()
456
457 def startup(self):
458 # To be called before using the space
459 if self.reverse_debugging:
460 self._revdb_startup()
461
462 self.threadlocals.enter_thread(self)
463
464 # Initialize already imported builtin modules
465 from pypy.interpreter.module import Module
466 w_modules = self.sys.get('modules')
467 for w_modname in self.unpackiterable(
468 self.sys.get('builtin_module_names')):
469 try:
470 w_mod = self.getitem(w_modules, w_modname)
471 except OperationError as e:
472 if e.match(self, self.w_KeyError):
473 continue
474 raise
475 if isinstance(w_mod, Module) and not w_mod.startup_called:
476 w_mod.init(self)
477
478 def finish(self):
479 ret = 0
480 self.wait_for_thread_shutdown()
481 w_atexit = self.getbuiltinmodule('atexit')
482 try:
483 self.call_method(w_atexit, '_run_exitfuncs')
484 except OperationError as e:
485 try:
486 e.write_unraisable(self, '_run_exitfuncs')
487 except Exception:
488 pass
489 # discard exceptions, see call_py_exitfuncs in pylifecycle.c in
490 # CPython
491 pass
492 self.sys.finalizing = True
493 if self.sys.flush_std_files(self) < 0:
494 ret = -1
495 from pypy.interpreter.module import Module
496 for w_mod in self.builtin_modules.values():
497 if isinstance(w_mod, Module) and w_mod.startup_called:
498 w_mod.shutdown(self)
499 return ret
500
501 def wait_for_thread_shutdown(self):
502 """Wait until threading._shutdown() completes, provided the threading
503 module was imported in the first place. The shutdown routine will
504 wait until all non-daemon 'threading' threads have completed."""
505 if not self.config.translation.thread:
506 return
507
508 w_modules = self.sys.get('modules')
509 w_mod = self.finditem_str(w_modules, 'threading')
510 if w_mod is None:
511 return
512
513 try:
514 self.call_method(w_mod, "_shutdown")
515 except OperationError as e:
516 e.write_unraisable(self, "threading._shutdown()")
517
518 def __repr__(self):
519 try:
520 return self._this_space_repr_
521 except AttributeError:
522 return self.__class__.__name__
523
524 @not_rpython
525 def setbuiltinmodule(self, pkgname):
526 """load a lazy pypy/module and put it into sys.modules"""
527 if '.' in pkgname:
528 fullname = "%s.moduledef" % (pkgname,)
529 importname = pkgname.rsplit('.', 1)[1]
530 else:
531 fullname = "pypy.module.%s.moduledef" % pkgname
532 importname = pkgname
533
534 Module = __import__(fullname,
535 None, None, ["Module"]).Module
536 if Module.applevel_name is not None:
537 name = Module.applevel_name
538 else:
539 name = importname
540
541 mod = Module(self, self.newtext(name))
542 mod.install()
543
544 return name
545
546 def getbuiltinmodule(self, name, force_init=False, reuse=True):
547 w_name = self.newtext(name)
548 w_modules = self.sys.get('modules')
549 if not force_init:
550 assert reuse
551 try:
552 return self.getitem(w_modules, w_name)
553 except OperationError as e:
554 if not e.match(self, self.w_KeyError):
555 raise
556
557 # If the module is a builtin but not yet imported,
558 # retrieve it and initialize it
559 try:
560 w_mod = self.builtin_modules[name]
561 except KeyError:
562 raise oefmt(self.w_SystemError,
563 "getbuiltinmodule() called with non-builtin module %s",
564 name)
565
566 # Add the module to sys.modules and initialize the module. The
567 # order is important to avoid recursions.
568 from pypy.interpreter.module import Module
569 if isinstance(w_mod, Module):
570 if not reuse and w_mod.startup_called:
571 # create a copy of the module. (see issue1514) eventlet
572 # patcher relies on this behaviour.
573 w_mod2 = Module(self, w_name)
574 self.setitem(w_modules, w_name, w_mod2)
575 w_mod.getdict(self) # unlazy w_initialdict
576 self.call_method(w_mod2.getdict(self), 'update',
577 w_mod.w_initialdict)
578 return w_mod2
579 self.setitem(w_modules, w_name, w_mod)
580 w_mod.init(self)
581 else:
582 self.setitem(w_modules, w_name, w_mod)
583 return w_mod
584
585 @not_rpython
586 def get_builtinmodule_to_install(self):
587 try:
588 return self._builtinmodule_list
589 except AttributeError:
590 pass
591
592 # Install __pypy__ first for bootstrapping
593 modules = ['__pypy__']
594
595 # _frozen_importlib imports lib-python/3/importlib/_bootstrap_external,
596 # which imports many builtins. Make sure it is imported last
597 append__frozen_importlib = False
598 # and zipimport even laster
599 append_zipimport = False
600
601 # You can enable more modules by specifying --usemodules=xxx,yyy
602 for name, value in self.config.objspace.usemodules:
603 if name == '_frozen_importlib':
604 append__frozen_importlib = True
605 continue
606 if name == "zipimport":
607 append_zipimport = True
608 continue
609 if value and name not in modules:
610 modules.append(name)
611
612 if self.config.objspace.extmodules:
613 for name in self.config.objspace.extmodules.split(','):
614 if name not in modules:
615 modules.append(name)
616 if append__frozen_importlib:
617 modules.append('_frozen_importlib')
618 if append_zipimport:
619 modules.append('zipimport')
620 self._builtinmodule_list = modules
621 return self._builtinmodule_list
622
623 @not_rpython
624 def make_builtins(self):
625 "only for initializing the space."
626
627 from pypy.module.exceptions.moduledef import Module
628 w_name = self.newtext('__exceptions__')
629 self.exceptions_module = Module(self, w_name)
630 self.exceptions_module.install()
631
632 from pypy.module.imp.moduledef import Module
633 w_name = self.newtext('_imp')
634 mod = Module(self, w_name)
635 mod.install()
636
637 from pypy.module.sys.moduledef import Module
638 w_name = self.newtext('sys')
639 self.sys = Module(self, w_name)
640 self.sys.install()
641
642 from pypy.module.__builtin__.moduledef import Module
643 w_name = self.newtext('builtins')
644 self.builtin = Module(self, w_name)
645 w_builtin = self.builtin
646 w_builtin.install()
647 self.setitem(self.builtin.w_dict, self.newtext('__builtins__'), w_builtin)
648
649
650 exception_types_w = self.export_builtin_exceptions()
651
652 # initialize with "bootstrap types" from objspace (e.g. w_None)
653 types_w = (self.get_builtin_types().items() +
654 exception_types_w.items())
655 for name, w_type in types_w:
656 self.setitem(self.builtin.w_dict, self.newtext(name), w_type)
657
658 # install mixed modules
659 bootstrap_modules = set(('sys', 'imp', 'builtins', 'exceptions',
660 'zipimport', '_frozen_importlib'))
661 for mixedname in self.get_builtinmodule_to_install():
662 if mixedname not in bootstrap_modules:
663 self.install_mixedmodule(mixedname)
664
665 w_builtin_module_names = self.newtuple([self.newtext(name) for name in sorted(self.builtin_modules)])
666 stdlib = [self.newtext(name) for name in sorted(list(self.builtin_modules.keys()) + get_stdlib_names())]
667 w_stdlib_module_names = self.newfrozenset(stdlib)
668
669
670 # force these value into the dict without unlazyfying everything
671 self.setitem(self.sys.w_dict, self.newtext('builtin_module_names'),
672 w_builtin_module_names)
673 self.setitem(self.sys.w_dict, self.newtext('stdlib_module_names'),
674 w_stdlib_module_names)
675
676
677 def get_builtin_types(self):
678 """Get a dictionary mapping the names of builtin types to the type
679 objects."""
680 raise NotImplementedError
681
682 @not_rpython
683 def export_builtin_exceptions(self):
684 w_dic = self.exceptions_module.getdict(self)
685 exc_types_w = {}
686 w_iter = self.iter(w_dic)
687 while True:
688 try:
689 w_name = self.next(w_iter)
690 except OperationError as e:
691 if not e.match(self, self.w_StopIteration):
692 raise
693 break
694 name = self.text_w(w_name)
695 if not name.startswith('_'):
696 excname = name
697 w_exc = self.getitem(w_dic, w_name)
698 exc_types_w[name] = w_exc
699 setattr(self, "w_" + excname, w_exc)
700 return exc_types_w
701
702 @not_rpython
703 def install_mixedmodule(self, mixedname):
704 self.setbuiltinmodule(mixedname)
705
706 @not_rpython
707 def setup_builtin_modules(self):
708 "only for initializing the space."
709 if self.config.objspace.usemodules.cpyext:
710 # Special-case this to have state.install_dll() called early, which
711 # is required to initialise sys on Windows.
712 from pypy.module.cpyext.state import State
713 self.fromcache(State).build_api()
714 elif self.config.objspace.usemodules._cffi_backend:
715 from pypy.module._cffi_backend import copy_includes
716 copy_includes.main()
717
718 # now we can setup _frozen_importlib, after the dll is installed
719 self.install_mixedmodule('_frozen_importlib')
720
721 self.getbuiltinmodule('sys')
722 self.getbuiltinmodule('_imp')
723 frozen_importlib = self.getbuiltinmodule('_frozen_importlib')
724 self.getbuiltinmodule('builtins')
725 for mod in self.builtin_modules.values():
726 mod.setup_after_space_initialization()
727 self.w_default_importlib_import = frozen_importlib.w_import
728 # special-casing zipimport: it needs a lot of things already in place,
729 # so we even install it here!
730 self.install_mixedmodule('zipimport')
731 self.getbuiltinmodule('zipimport')
732
733 @not_rpython
734 def initialize(self):
735 """Abstract method that should put some minimal
736 content into the w_builtins."""
737
738 def getexecutioncontext(self):
739 "Return what we consider to be the active execution context."
740 # Important: the annotator must not see a prebuilt ExecutionContext:
741 # you should not see frames while you translate
742 # so we make sure that the threadlocals never *have* an
743 # ExecutionContext during translation.
744 if not we_are_translated():
745 if self.config.translating:
746 assert self.threadlocals.get_ec() is None, (
747 "threadlocals got an ExecutionContext during translation!")
748 try:
749 return self._ec_during_translation
750 except AttributeError:
751 ec = self.createexecutioncontext()
752 self._ec_during_translation = ec
753 return ec
754 else:
755 ec = self.threadlocals.get_ec()
756 if ec is None:
757 self.threadlocals.enter_thread(self)
758 ec = self.threadlocals.get_ec()
759 return ec
760 else:
761 # translated case follows. self.threadlocals is either from
762 # 'pypy.interpreter.miscutils' or 'pypy.module.thread.threadlocals'.
763 # the result is assumed to be non-null: enter_thread() was called
764 # by space.startup().
765 ec = self.threadlocals.get_ec()
766 assert ec is not None
767 return ec
768
769 def _freeze_(self):
770 return True
771
772 def createexecutioncontext(self):
773 "Factory function for execution contexts."
774 return ExecutionContext(self)
775
776 def createcompiler(self):
777 "Factory function creating a compiler object."
778 try:
779 return self.default_compiler
780 except AttributeError:
781 from pypy.interpreter.pycompiler import PythonAstCompiler
782 compiler = PythonAstCompiler(self)
783 self.default_compiler = compiler
784 return compiler
785
786 def createnewcompiler(self):
787 "Factory function creating a compiler object."
788 try:
789 return self.default_newcompiler
790 except AttributeError:
791 from pypy.interpreter.pycompiler import PythonAstCompiler
792 compiler = PythonAstCompiler(self)
793 self.default_newcompiler = compiler
794 return compiler
795
796 def createframe(self, code, w_globals, outer_func=None):
797 "Create an empty PyFrame suitable for this code object."
798 return self.FrameClass(self, code, w_globals, outer_func)
799
800 def allocate_lock(self):
801 """Return an interp-level Lock object if threads are enabled,
802 and a dummy object if they are not."""
803 from rpython.rlib import rthread
804 if not self.config.objspace.usemodules.thread:
805 return rthread.dummy_lock
806 # hack: we can't have prebuilt locks if we're translating.
807 # In this special situation we should just not lock at all
808 # (translation is not multithreaded anyway).
809 if not we_are_translated() and self.config.translating:
810 raise CannotHaveLock()
811 try:
812 return rthread.allocate_lock()
813 except rthread.error:
814 raise oefmt(self.w_RuntimeError, "out of resources")
815
816 # Following is a friendly interface to common object space operations
817 # that can be defined in term of more primitive ones. Subclasses
818 # may also override specific functions for performance.
819
820 def not_(self, w_obj):
821 return self.newbool(not self.is_true(w_obj))
822
823 def eq_w(self, w_obj1, w_obj2):
824 """Implements equality with the double check 'x is y or x == y'."""
825 return self.is_w(w_obj1, w_obj2) or self.is_true(self.eq(w_obj1, w_obj2))
826
827 def is_(self, w_one, w_two):
828 return self.newbool(self.is_w(w_one, w_two))
829
830 def is_w(self, w_one, w_two):
831 # done by a method call on w_two (and not on w_one, because of the
832 # expected programming style where we say "if x is None" or
833 # "if x is object").
834 assert w_two is not None
835 return w_two.is_w(self, w_one)
836
837 def is_none(self, w_obj):
838 """ mostly for checking inputargs that have unwrap_spec and
839 can accept both w_None and None
840 """
841 return w_obj is None or self.is_w(w_obj, self.w_None)
842
843 def id(self, w_obj):
844 w_result = w_obj.immutable_unique_id(self)
845 if w_result is None:
846 # in the common case, returns an unsigned value
847 id = compute_unique_id(w_obj)
848 if id >= 0:
849 w_result = self.newint(id)
850 else:
851 # the following path returns W_LongObject, but it should happen
852 # only on 32-bit platforms
853 w_result = self.newint(r_uint(id))
854 return w_result
855
856 def contains_w(self, w_container, w_item):
857 """shortcut for space.is_true(space.contains(w_container, w_item))"""
858 return self.is_true(self.contains(w_container, w_item))
859
860 def setitem_str(self, w_obj, key, w_value):
861 # key is a "text", i.e. a byte string (in python3 it
862 # represents a valid utf-8-encoded unicode)
863 return self.setitem(w_obj, self.newtext(key), w_value)
864
865 def finditem_str(self, w_obj, key):
866 # key is a "text", i.e. a byte string (in python3 it
867 # represents a valid utf-8-encoded unicode)
868 return self.finditem(w_obj, self.newtext(key))
869
870 def finditem(self, w_obj, w_key):
871 try:
872 return self.getitem(w_obj, w_key)
873 except OperationError as e:
874 if e.match(self, self.w_KeyError):
875 return None
876 raise
877
878 def findattr(self, w_object, w_name):
879 try:
880 return self.getattr(w_object, w_name)
881 except OperationError as e:
882 # a PyPy extension: let SystemExit and KeyboardInterrupt go through
883 if e.async(self):
884 raise
885 return None
886
887 def wrap_none(self, w_obj):
888 if w_obj is None:
889 return self.w_None
890 return w_obj
891
892 @signature(types.any(), types.bool(), returns=types.any())
893 def newbool(self, b):
894 if b:
895 return self.w_True
896 else:
897 return self.w_False
898
899 def new_interned_w_str(self, w_u):
900 assert isinstance(w_u, W_Root) # and is not None
901 u = self.utf8_w(w_u)
902 if not we_are_translated():
903 assert type(u) is str
904 w_u1 = self.interned_strings.get(u)
905 if w_u1 is None:
906 w_u1 = w_u
907 if self._side_effects_ok():
908 self.interned_strings.set(u, w_u1)
909 return w_u1
910
911 def new_interned_str(self, s):
912 # Assumes an identifier (utf-8 encoded str)
913 # returns a "text" object (ie str in python2 and unicode in python3)
914 if not we_are_translated():
915 assert type(s) is str
916 w_s1 = self.interned_strings.get(s)
917 if w_s1 is None:
918 w_s1 = self.newtext(s)
919 if self._side_effects_ok():
920 self.interned_strings.set(s, w_s1)
921 return w_s1
922
923 def _revdb_startup(self):
924 # moved in its own function for the import statement
925 from pypy.interpreter.reverse_debugging import setup_revdb
926 setup_revdb(self)
927
928 def _revdb_standard_code(self):
929 # moved in its own function for the import statement
930 from pypy.interpreter.reverse_debugging import dbstate
931 return dbstate.standard_code
932
933 def _side_effects_ok(self):
934 # For the reverse debugger: we run compiled watchpoint
935 # expressions in a fast way that will crash if they have
936 # side-effects. The obvious Python code with side-effects is
937 # documented "don't do that"; but some non-obvious side
938 # effects are also common, like interning strings (from
939 # unmarshalling the code object containing the watchpoint
940 # expression) to the two attribute caches in mapdict.py and
941 # typeobject.py. For now, we have to identify such places
942 # that are not acceptable for "reasonable" read-only
943 # watchpoint expressions, and write:
944 #
945 # if not space._side_effects_ok():
946 # don't cache.
947 #
948 if self.reverse_debugging:
949 return self._revdb_standard_code()
950 return True
951
952 def get_interned_str(self, s):
953 """Assumes an identifier (utf-8 encoded str). Returns None if
954 the identifier is not interned, or not a valid utf-8 string at all.
955 """
956 # interface for marshal_impl
957 if not we_are_translated():
958 assert type(s) is str
959 return self.interned_strings.get(s) # may be None
960
961 @specialize.arg(1)
962 def descr_self_interp_w(self, RequiredClass, w_obj):
963 if not isinstance(w_obj, RequiredClass):
964 raise DescrMismatch()
965 return w_obj
966
967 @specialize.arg(1)
968 def interp_w(self, RequiredClass, w_obj, can_be_None=False):
969 """
970 Unwrap w_obj, checking that it is an instance of the required internal
971 interpreter class.
972 """
973 assert RequiredClass is not None
974 if can_be_None and self.is_none(w_obj):
975 return None
976 if not isinstance(w_obj, RequiredClass): # or obj is None
977 raise oefmt(self.w_TypeError,
978 "'%s' object expected, got '%T' instead",
979 wrappable_class_name(RequiredClass),
980 w_obj)
981 return w_obj
982
983 def unpackiterable(self, w_iterable, expected_length=-1):
984 """Unpack an iterable into a real (interpreter-level) list.
985
986 Raise an OperationError(w_ValueError) if the length is wrong."""
987 w_iterator = self.iter(w_iterable)
988 if expected_length == -1:
989 if self.is_generator(w_iterator):
990 # special hack for speed
991 lst_w = []
992 w_iterator.unpack_into(lst_w)
993 return lst_w
994 return self._unpackiterable_unknown_length(w_iterator, w_iterable)
995 else:
996 lst_w = self._unpackiterable_known_length(w_iterator,
997 expected_length)
998 return lst_w[:] # make the resulting list resizable
999
1000 def _unpackiterable_unknown_length(self, w_iterator, w_iterable):
1001 """Unpack an iterable of unknown length into an interp-level
1002 list.
1003 """
1004 # If we can guess the expected length we can preallocate.
1005 try:
1006 items = newlist_hint(self.length_hint(w_iterable, 0))
1007 except MemoryError:
1008 items = [] # it might have lied
1009
1010 greenkey = self.iterator_greenkey(w_iterator)
1011 while True:
1012 unpackiterable_driver.jit_merge_point(greenkey=greenkey)
1013 try:
1014 w_item = self.next(w_iterator)
1015 except OperationError as e:
1016 if not e.match(self, self.w_StopIteration):
1017 raise
1018 break # done
1019 items.append(w_item)
1020 #
1021 return items
1022
1023 @jit.dont_look_inside
1024 def _unpackiterable_known_length(self, w_iterator, expected_length):
1025 # Unpack a known length list, without letting the JIT look inside.
1026 # Implemented by just calling the @jit.unroll_safe version, but
1027 # the JIT stopped looking inside already.
1028 return self._unpackiterable_known_length_jitlook(w_iterator,
1029 expected_length)
1030
1031 @jit.unroll_safe
1032 def _unpackiterable_known_length_jitlook(self, w_iterator,
1033 expected_length):
1034 items = [None] * expected_length
1035 idx = 0
1036 while True:
1037 try:
1038 w_item = self.next(w_iterator)
1039 except OperationError as e:
1040 if not e.match(self, self.w_StopIteration):
1041 raise
1042 break # done
1043 if idx == expected_length:
1044 raise oefmt(self.w_ValueError,
1045 "too many values to unpack (expected %d)",
1046 expected_length)
1047 items[idx] = w_item
1048 idx += 1
1049 if idx < expected_length:
1050 raise oefmt(self.w_ValueError,
1051 "not enough values to unpack (expected %d, got %d)",
1052 expected_length, idx)
1053 return items
1054
1055 def unpackiterable_unroll(self, w_iterable, expected_length):
1056 # Like unpackiterable(), but for the cases where we have
1057 # an expected_length and want to unroll when JITted.
1058 # Returns a fixed-size list.
1059 w_iterator = self.iter(w_iterable)
1060 assert expected_length != -1
1061 return self._unpackiterable_known_length_jitlook(w_iterator,
1062 expected_length)
1063
1064
1065 def unpackiterable_int(self, w_obj):
1066 """
1067 Return a RPython list of unwrapped ints out of w_obj. The list is
1068 guaranteed to be acopy of the actual data contained in w_obj, so you
1069 can freely modify it. It might return None if not supported.
1070 """
1071 return w_obj.unpackiterable_int(self)
1072
1073 def unpackiterable_float(self, w_obj):
1074 """
1075 Same as unpackiterable_int, but for floats.
1076 """
1077 return w_obj.unpackiterable_float(self)
1078
1079
1080 def length_hint(self, w_obj, default):
1081 """Return the length of an object, consulting its __length_hint__
1082 method if necessary.
1083 """
1084 try:
1085 return self.len_w(w_obj)
1086 except OperationError as e:
1087 if not (e.match(self, self.w_TypeError) or
1088 e.match(self, self.w_AttributeError)):
1089 raise
1090
1091 w_descr = self.lookup(w_obj, '__length_hint__')
1092 if w_descr is None:
1093 return default
1094 try:
1095 w_hint = self.get_and_call_function(w_descr, w_obj)
1096 except OperationError as e:
1097 if not (e.match(self, self.w_TypeError) or
1098 e.match(self, self.w_AttributeError)):
1099 raise
1100 return default
1101 if self.is_w(w_hint, self.w_NotImplemented):
1102 return default
1103
1104 hint = self.int_w(w_hint)
1105 if hint < 0:
1106 raise oefmt(self.w_ValueError,
1107 "__length_hint__() should return >= 0")
1108 return hint
1109
1110 def fixedview(self, w_iterable, expected_length=-1):
1111 """ A fixed list view of w_iterable. Don't modify the result
1112 """
1113 return make_sure_not_resized(self.unpackiterable(w_iterable,
1114 expected_length)[:])
1115
1116 fixedview_unroll = fixedview
1117
1118 def listview(self, w_iterable, expected_length=-1):
1119 """ A non-fixed view of w_iterable. Don't modify the result
1120 """
1121 return self.unpackiterable(w_iterable, expected_length)
1122
1123 def listview_no_unpack(self, w_iterable):
1124 """ Same as listview() if cheap. If 'w_iterable' is something like
1125 a generator, for example, then return None instead.
1126 May return None anyway.
1127 """
1128 return None
1129
1130 def listview_bytes(self, w_list):
1131 """ Return a list of unwrapped strings out of a list of strings. If the
1132 argument is not a list or does not contain only strings, return None.
1133 May return None anyway.
1134 """
1135 return None
1136
1137 def listview_ascii(self, w_list):
1138 """ Return a list of unwrapped **ASCII** strings out of a list of
1139 unicode. If the argument is not a list, does not contain only unicode,
1140 or contains a unicode with non-ascii characters, return None.
1141 May return None anyway.
1142 """
1143 return None
1144
1145 def listview_int(self, w_list):
1146 """ Return a list of unwrapped int out of a list of int. If the
1147 argument is not a list or does not contain only int, return None.
1148 May return None anyway.
1149 """
1150 return None
1151
1152 def listview_float(self, w_list):
1153 """ Return a list of unwrapped float out of a list of float. If the
1154 argument is not a list or does not contain only float, return None.
1155 May return None anyway.
1156 """
1157 return None
1158
1159 def view_as_kwargs(self, w_dict):
1160 """ if w_dict is a kwargs-dict, return two lists, one of unwrapped
1161 strings and one of wrapped values. otherwise return (None, None)
1162 """
1163 return (None, None)
1164
1165 def newlist_bytes(self, list_s):
1166 return self.newlist([self.newbytes(s) for s in list_s])
1167
1168 def newlist_utf8(self, list_u, is_ascii):
1169 l_w = [None] * len(list_u)
1170 for i, item in enumerate(list_u):
1171 if not is_ascii:
1172 length = rutf8.check_utf8(item, True)
1173 else:
1174 length = len(item)
1175 l_w[i] = self.newutf8(item, length)
1176 return self.newlist(l_w)
1177
1178 def newlist_int(self, list_i):
1179 return self.newlist([self.newint(i) for i in list_i])
1180
1181 def newlist_float(self, list_f):
1182 return self.newlist([self.newfloat(f) for f in list_f])
1183
1184 def newlist_hint(self, sizehint):
1185 from pypy.objspace.std.listobject import make_empty_list_with_size
1186 return make_empty_list_with_size(self, sizehint)
1187
1188 @jit.unroll_safe
1189 def exception_match(self, w_exc_type, w_check_class):
1190 """Checks if the given exception type matches 'w_check_class'."""
1191 if self.is_w(w_exc_type, w_check_class):
1192 return True # fast path
1193 if self.isinstance_w(w_check_class, self.w_tuple):
1194 for w_t in self.fixedview(w_check_class):
1195 if self.exception_match(w_exc_type, w_t):
1196 return True
1197 else:
1198 return False
1199 return self.exception_issubclass_w(w_exc_type, w_check_class)
1200
1201 def call_obj_args(self, w_callable, w_obj, args):
1202 if not self.config.objspace.disable_call_speedhacks:
1203 # start of hack for performance
1204 from pypy.interpreter.function import Function
1205 if isinstance(w_callable, Function):
1206 return w_callable.call_obj_args(w_obj, args)
1207 # end of hack for performance
1208 return self.call_args(w_callable, args.prepend(w_obj))
1209
1210 def call(self, w_callable, w_args, w_kwds=None):
1211 args = Arguments.frompacked(self, w_args, w_kwds)
1212 return self.call_args(w_callable, args)
1213
1214 def _try_fetch_pycode(self, w_func):
1215 from pypy.interpreter.function import Function, _Method
1216 if isinstance(w_func, _Method):
1217 w_func = w_func.w_function
1218 if isinstance(w_func, Function):
1219 return w_func.code
1220 return None
1221
1222 def call_function(self, w_func, *args_w):
1223 nargs = len(args_w) # used for pruning funccall versions
1224 if not self.config.objspace.disable_call_speedhacks and nargs < 5:
1225 # start of hack for performance
1226 from pypy.interpreter.function import Function, _Method
1227 if isinstance(w_func, _Method):
1228 if nargs < 4:
1229 func = w_func.w_function
1230 if isinstance(func, Function):
1231 return func.funccall(w_func.w_instance, *args_w)
1232
1233 if isinstance(w_func, Function):
1234 return w_func.funccall(*args_w)
1235 # end of hack for performance
1236
1237 args = Arguments(self, list(args_w))
1238 return self.call_args(w_func, args)
1239
1240 def call_valuestack(self, w_func, nargs, frame, dropvalues, methodcall=False):
1241 # methodcall is only used for better error messages in argument.py
1242 from pypy.interpreter.function import Function, _Method, is_builtin_code
1243 if frame.get_is_being_profiled() and is_builtin_code(w_func):
1244 # XXX: this code is copied&pasted :-( from the slow path below
1245 # call_valuestack().
1246 args = frame.make_arguments(nargs, w_function=w_func)
1247 frame.dropvalues(dropvalues)
1248 return self.call_args_and_c_profile(frame, w_func, args)
1249
1250 if not self.config.objspace.disable_call_speedhacks:
1251 # start of hack for performance
1252 if isinstance(w_func, _Method):
1253 # reuse callable stack place for w_inst
1254 frame.settopvalue(w_func.w_instance, nargs)
1255 nargs += 1
1256 methodcall = True
1257 w_func = w_func.w_function
1258
1259 if isinstance(w_func, Function):
1260 return w_func.funccall_valuestack(
1261 nargs, frame, methodcall=methodcall, dropvalues=dropvalues)
1262
1263 # end of hack for performance
1264
1265 args = frame.make_arguments(nargs, w_function=w_func)
1266 frame.dropvalues(dropvalues)
1267 return self.call_args(w_func, args)
1268
1269 def call_args_and_c_profile(self, frame, w_func, args):
1270 ec = self.getexecutioncontext()
1271 ec.c_call_trace(frame, w_func, args)
1272 try:
1273 w_res = self.call_args(w_func, args)
1274 except OperationError:
1275 ec.c_exception_trace(frame, w_func)
1276 raise
1277 ec.c_return_trace(frame, w_func, args)
1278 return w_res
1279
1280 def call_method(self, w_obj, methname, *arg_w):
1281 w_meth = self.getattr(w_obj, self.newtext(methname))
1282 return self.call_function(w_meth, *arg_w)
1283
1284 def raise_key_error(self, w_key):
1285 e = self.call_function(self.w_KeyError, w_key)
1286 raise OperationError(self.w_KeyError, e)
1287
1288 def lookup(self, w_obj, name):
1289 w_type = self.type(w_obj)
1290 w_mro = self.getattr(w_type, self.newtext("__mro__"))
1291 for w_supertype in self.fixedview(w_mro):
1292 w_value = w_supertype.getdictvalue(self, name)
1293 if w_value is not None:
1294 return w_value
1295 return None
1296
1297 def is_generator(self, w_obj):
1298 from pypy.interpreter.generator import GeneratorIterator
1299 return isinstance(w_obj, GeneratorIterator)
1300
1301 def callable_w(self, w_obj):
1302 return self.lookup(w_obj, "__call__") is not None
1303
1304 def callable(self, w_obj):
1305 return self.newbool(self.callable_w(w_obj))
1306
1307 def issequence_w(self, w_obj):
1308 flag = self.type(w_obj).flag_map_or_seq
1309 if flag == 'M':
1310 return False
1311 elif flag == 'S':
1312 return True
1313 else:
1314 return (self.lookup(w_obj, '__getitem__') is not None)
1315
1316 def ismapping_w(self, w_obj):
1317 flag = self.type(w_obj).flag_map_or_seq
1318 if flag == 'M':
1319 return True
1320 elif flag == 'S':
1321 return False
1322 else:
1323 return self.lookup(w_obj, '__getitem__') is not None
1324
1325 # The code below only works
1326 # for the simple case (new-style instance).
1327 # These methods are patched with the full logic by the builtins
1328 # module when it is loaded
1329
1330 def abstract_issubclass_w(self, w_cls1, w_cls2, allow_override=False):
1331 # Equivalent to 'issubclass(cls1, cls2)'.
1332 return self.issubtype_w(w_cls1, w_cls2)
1333
1334 def abstract_isinstance_w(self, w_obj, w_cls, allow_override=False):
1335 # Equivalent to 'isinstance(obj, cls)'.
1336 return self.isinstance_w(w_obj, w_cls)
1337
1338 def abstract_isclass_w(self, w_obj):
1339 # Equivalent to 'isinstance(obj, type)'.
1340 return self.isinstance_w(w_obj, self.w_type)
1341
1342 def abstract_getclass(self, w_obj):
1343 # Equivalent to 'obj.__class__'.
1344 return self.type(w_obj)
1345
1346 def isabstractmethod_w(self, w_obj):
1347 try:
1348 w_result = self.getattr(w_obj, self.newtext("__isabstractmethod__"))
1349 except OperationError as e:
1350 if e.match(self, self.w_AttributeError):
1351 return False
1352 raise
1353 return self.is_true(w_result)
1354
1355 # CPython rules allows subclasses of BaseExceptions to be exceptions.
1356 # This is slightly less general than the case above, so we prefix
1357 # it with exception_
1358
1359 def exception_is_valid_obj_as_class_w(self, w_obj):
1360 if not self.isinstance_w(w_obj, self.w_type):
1361 return False
1362 return self.issubtype_w(w_obj, self.w_BaseException)
1363
1364 def exception_is_valid_class_w(self, w_cls):
1365 return self.issubtype_w(w_cls, self.w_BaseException)
1366
1367 def exception_getclass(self, w_obj):
1368 return self.type(w_obj)
1369
1370 def exception_issubclass_w(self, w_cls1, w_cls2):
1371 return self.issubtype_w(w_cls1, w_cls2)
1372
1373 @not_rpython
1374 def new_exception_class(self, *args, **kwargs):
1375 "convenience method to create excceptions in modules"
1376 return new_exception_class(self, *args, **kwargs)
1377
1378 # end of special support code
1379
1380 @not_rpython
1381 def eval(self, expression, w_globals, w_locals, hidden_applevel=False):
1382 "For internal debugging."
1383 if isinstance(expression, str):
1384 compiler = self.createcompiler()
1385 expression = compiler.compile(expression, '?', 'eval', 0,
1386 hidden_applevel=hidden_applevel)
1387 else:
1388 raise TypeError('space.eval(): expected a string, code or PyCode object')
1389 return expression.exec_code(self, w_globals, w_locals)
1390
1391 @not_rpython
1392 def exec_(self, statement, w_globals, w_locals, hidden_applevel=False,
1393 filename=None):
1394 "For internal debugging."
1395 if filename is None:
1396 filename = '?'
1397 from pypy.interpreter.pycode import PyCode
1398 if isinstance(statement, str):
1399 statement = self._cached_compile(filename, statement, 'exec', 0, hidden_applevel)
1400 if not isinstance(statement, PyCode):
1401 raise TypeError('space.exec_(): expected a string, code or PyCode object')
1402 w_key = self.newtext('__builtins__')
1403 if not self.contains_w(w_globals, w_key):
1404 self.setitem(w_globals, w_key, self.builtin)
1405 return statement.exec_code(self, w_globals, w_locals)
1406
1407
1408 @not_rpython
1409 def _cached_compile(self, filename, source, mode, flags, hidden_applevel, ast_transform=None):
1410 import os
1411 from hashlib import md5
1412 from rpython.config.translationoption import CACHE_DIR
1413 from rpython.tool.gcc_cache import try_atomic_write
1414 from pypy.module.marshal import interp_marshal
1415 from pypy.interpreter.pycode import default_magic
1416 h = md5(str(default_magic))
1417 h.update(filename)
1418 h.update(source)
1419 h.update(mode)
1420 h.update(str(flags))
1421 h.update(str(hidden_applevel))
1422 addition = ''
1423 if ast_transform:
1424 addition = ast_transform.func_name
1425
1426 cachename = os.path.join(
1427 CACHE_DIR, "applevel_exec_%s_%s" % (addition, h.hexdigest()))
1428 try:
1429 if self.config.translating:
1430 raise IOError("don't use the cache when translating pypy")
1431 with open(cachename, 'rb') as f:
1432 w_bin = self.newbytes(f.read())
1433 w_code = interp_marshal._loads(self, w_bin, hidden_applevel)
1434 except IOError:
1435 # must (re)compile the source
1436 ec = self.getexecutioncontext()
1437 if ast_transform:
1438 c = self.createcompiler()
1439 tree = c.compile_to_ast(source, filename, "exec", 0)
1440 tree = ast_transform(self, tree)
1441 w_code = c.compile_ast(tree, filename, 'exec', 0)
1442 else:
1443 w_code = ec.compiler.compile(
1444 source, filename, mode, flags, hidden_applevel)
1445 w_bin = interp_marshal.dumps(self, w_code)
1446 content = self.bytes_w(w_bin)
1447 try_atomic_write(cachename, content)
1448 return w_code
1449
1450
1451 @not_rpython
1452 def appdef(self, source):
1453 '''Create interp-level function object from app-level source.
1454
1455 The source should be in the same format as for space.appexec():
1456 """(foo, bar): return 'baz'"""
1457 '''
1458 source = source.lstrip()
1459 assert source.startswith('('), "incorrect header in:\n%s" % (source,)
1460 source = py.code.Source("def anonymous%s\n" % source)
1461 w_glob = self.newdict(module=True)
1462 self.exec_(str(source), w_glob, w_glob)
1463 return self.getitem(w_glob, self.newtext('anonymous'))
1464
1465 @specialize.arg(2)
1466 def appexec(self, posargs_w, source, cache=True):
1467 """ return value from executing given source at applevel.
1468 The source must look like
1469 '''(x, y):
1470 do_stuff...
1471 return result
1472 '''
1473 """
1474 if cache:
1475 w_func = self.fromcache(AppExecCache).getorbuild(source)
1476 else:
1477 # NB: since appdef() is not-RPython, using cache=False also is.
1478 w_func = self.appdef(source)
1479 args = Arguments(self, list(posargs_w))
1480 return self.call_args(w_func, args)
1481
1482 def _next_or_none(self, w_it):
1483 try:
1484 return self.next(w_it)
1485 except OperationError as e:
1486 if not e.match(self, self.w_StopIteration):
1487 raise
1488 return None
1489
1490 @specialize.arg(3)
1491 def compare_by_iteration(self, w_iterable1, w_iterable2, op):
1492 w_it1 = self.iter(w_iterable1)
1493 w_it2 = self.iter(w_iterable2)
1494 while True:
1495 w_x1 = self._next_or_none(w_it1)
1496 w_x2 = self._next_or_none(w_it2)
1497 if w_x1 is None or w_x2 is None:
1498 if op == 'eq': return self.newbool(w_x1 is w_x2) # both None
1499 if op == 'ne': return self.newbool(w_x1 is not w_x2)
1500 if op == 'lt': return self.newbool(w_x2 is not None)
1501 if op == 'le': return self.newbool(w_x1 is None)
1502 if op == 'gt': return self.newbool(w_x1 is not None)
1503 if op == 'ge': return self.newbool(w_x2 is None)
1504 assert False, "bad value for op"
1505 if not self.eq_w(w_x1, w_x2):
1506 if op == 'eq': return self.w_False
1507 if op == 'ne': return self.w_True
1508 if op == 'lt': return self.lt(w_x1, w_x2)
1509 if op == 'le': return self.le(w_x1, w_x2)
1510 if op == 'gt': return self.gt(w_x1, w_x2)
1511 if op == 'ge': return self.ge(w_x1, w_x2)
1512 assert False, "bad value for op"
1513
1514 def decode_index4_unsafe(self, w_index_or_slice, seqlength):
1515 """Helper for custom sequence implementations
1516 -> (index, 0, 0, 1) or
1517 (start, stop, step, slice_length)
1518
1519 UNSAFE: if the __index__ method of one of the slice's start/stop/step
1520 fields changes the sequence, then the result can be incorrect
1521 """
1522 if self.isinstance_w(w_index_or_slice, self.w_slice):
1523 from pypy.objspace.std.sliceobject import W_SliceObject
1524 assert isinstance(w_index_or_slice, W_SliceObject)
1525 start, stop, step, length = w_index_or_slice.indices4(self,
1526 seqlength)
1527 else:
1528 start = self.getindex_w(w_index_or_slice, self.w_OverflowError)
1529 if start < 0:
1530 start += seqlength
1531 if not (0 <= start < seqlength):
1532 raise oefmt(self.w_IndexError, "index out of range")
1533 stop = 0
1534 step = 0
1535 length = 1
1536 return start, stop, step, length
1537
1538 def decode_index4(self, w_index_or_slice, w_seq):
1539 """Helper for custom sequence implementations
1540 -> (index, 0, 0, 1) or
1541 (start, stop, step, slice_length)
1542 """
1543 if self.isinstance_w(w_index_or_slice, self.w_slice):
1544 from pypy.objspace.std.sliceobject import W_SliceObject
1545 assert isinstance(w_index_or_slice, W_SliceObject)
1546 # it's important to first unpack the slice and then read the length
1547 # of the sequence, because the former can change the latter
1548 start, stop, step = w_index_or_slice.unpack(self)
1549 seqlength = self.len_w(w_seq)
1550 start, stop, step, length = w_index_or_slice.adjust_indices(start, stop, step, seqlength)
1551 else:
1552 start = self.getindex_w(w_index_or_slice, self.w_OverflowError)
1553 seqlength = self.len_w(w_seq)
1554 if start < 0:
1555 start += seqlength
1556 if not (0 <= start < seqlength):
1557 raise oefmt(self.w_IndexError, "index out of range")
1558 stop = 0
1559 step = 0
1560 length = 1
1561 return start, stop, step, length
1562
1563
1564 def getindex_w(self, w_obj, w_exception, objdescr=None):
1565 """Return w_obj.__index__() as an RPython int.
1566 If w_exception is None, silently clamp in case of overflow;
1567 else raise w_exception.
1568 """
1569 try:
1570 w_index = self.index(w_obj)
1571 except OperationError as err:
1572 if objdescr is None or not err.match(self, self.w_TypeError):
1573 raise
1574 raise oefmt(self.w_TypeError,
1575 "%s indices must be integers or slices, not %T",
1576 objdescr, w_obj)
1577 try:
1578 # allow_conversion=False it's not really necessary because the
1579 # return type of __index__ is already checked by space.index(),
1580 # but there is no reason to allow conversions anyway
1581 index = self.int_w(w_index, allow_conversion=False)
1582 except OperationError as err:
1583 if not err.match(self, self.w_OverflowError):
1584 raise
1585 if not w_exception:
1586 # w_index should be a long object, but can't be sure of that
1587 if self.is_true(self.lt(w_index, self.newint(0))):
1588 return -sys.maxint-1
1589 else:
1590 return sys.maxint
1591 else:
1592 raise oefmt(w_exception,
1593 "cannot fit '%T' into an index-sized integer",
1594 w_obj)
1595 else:
1596 return index
1597
1598 def getslice(space, w_obj, w_start, w_stop):
1599 w_slice = space.newslice(w_start, w_stop, space.w_None)
1600 return space.getitem(w_obj, w_slice)
1601
1602 def setslice(space, w_obj, w_start, w_stop, w_sequence):
1603 w_slice = space.newslice(w_start, w_stop, space.w_None)
1604 return space.setitem(w_obj, w_slice, w_sequence)
1605
1606 def delslice(space, w_obj, w_start, w_stop):
1607 w_slice = space.newslice(w_start, w_stop, space.w_None)
1608 return space.delitem(w_obj, w_slice)
1609
1610 def r_longlong_w(self, w_obj, allow_conversion=True):
1611 bigint = self.bigint_w(w_obj, allow_conversion)
1612 try:
1613 return bigint.tolonglong()
1614 except OverflowError:
1615 raise oefmt(self.w_OverflowError, "integer too large")
1616
1617 def r_ulonglong_w(self, w_obj, allow_conversion=True):
1618 bigint = self.bigint_w(w_obj, allow_conversion)
1619 try:
1620 return bigint.toulonglong()
1621 except OverflowError:
1622 raise oefmt(self.w_OverflowError, "integer too large")
1623 except ValueError:
1624 raise oefmt(self.w_ValueError,
1625 "cannot convert negative integer to unsigned int")
1626
1627 BUF_SIMPLE = 0x0000
1628 BUF_WRITABLE = 0x0001
1629 BUF_FORMAT = 0x0004
1630 BUF_ND = 0x0008
1631 BUF_STRIDES = 0x0010 | BUF_ND
1632 BUF_C_CONTIGUOUS = 0x0020 | BUF_STRIDES
1633 BUF_F_CONTIGUOUS = 0x0040 | BUF_STRIDES
1634 BUF_ANY_CONTIGUOUS = 0x0080 | BUF_STRIDES
1635 BUF_INDIRECT = 0x0100 | BUF_STRIDES
1636
1637 BUF_CONTIG_RO = BUF_ND
1638 BUF_CONTIG = BUF_ND | BUF_WRITABLE
1639
1640 BUF_FULL_RO = BUF_INDIRECT | BUF_FORMAT
1641 BUF_FULL = BUF_INDIRECT | BUF_FORMAT | BUF_WRITABLE
1642
1643 def check_buf_flags(self, flags, readonly):
1644 if readonly and flags & self.BUF_WRITABLE == self.BUF_WRITABLE:
1645 raise oefmt(self.w_BufferError, "Object is not writable.")
1646
1647 def _try_buffer_w(self, w_obj, flags):
1648 if not we_are_translated():
1649 if w_obj.buffer_w.im_func != W_Root.buffer_w.im_func:
1650 # when 'buffer_w()' is overridden in the subclass of
1651 # W_Root, we need to specify __buffer="read" or
1652 # __buffer="read-write" in the TypeDef.
1653 assert type(w_obj).typedef.buffer is not None
1654 return w_obj.buffer_w(self, flags)
1655
1656 def buffer_w(self, w_obj, flags):
1657 # New buffer interface, returns a buffer based on flags (PyObject_GetBuffer)
1658 try:
1659 return self._try_buffer_w(w_obj, flags)
1660 except BufferInterfaceNotFound:
1661 raise oefmt(self.w_TypeError,
1662 "a bytes-like object is required, not '%T'", w_obj)
1663
1664 def readbuf_w(self, w_obj):
1665 # Old buffer interface, returns a readonly buffer (PyObject_AsReadBuffer)
1666 try:
1667 return self._try_buffer_w(w_obj, self.BUF_SIMPLE).as_readbuf()
1668 except BufferInterfaceNotFound:
1669 self._getarg_error("bytes-like object", w_obj)
1670
1671 def writebuf_w(self, w_obj):
1672 # Old buffer interface, returns a writeable buffer (PyObject_AsWriteBuffer)
1673 try:
1674 return self._try_buffer_w(w_obj, self.BUF_WRITABLE).as_writebuf()
1675 except (BufferInterfaceNotFound, OperationError):
1676 self._getarg_error("read-write bytes-like object", w_obj)
1677
1678 def charbuf_w(self, w_obj):
1679 # Old buffer interface, returns a character buffer (PyObject_AsCharBuffer)
1680 if self.isinstance_w(w_obj, self.w_bytes): # XXX: is this shortcut useful?
1681 return w_obj.bytes_w(self)
1682 else:
1683 return self.readbuf_w(w_obj).as_str()
1684
1685 def _getarg_error(self, expected, w_obj):
1686 if self.is_none(w_obj):
1687 e = oefmt(self.w_TypeError, "a %s is required, not None", expected)
1688 else:
1689 e = oefmt(self.w_TypeError, "a %s is required, not %T", expected, w_obj)
1690 raise e
1691
1692 @specialize.arg(1)
1693 def getarg_w(self, code, w_obj):
1694 if code == 'z*':
1695 if self.is_none(w_obj):
1696 return None
1697 code = 's*'
1698 if code == 's*':
1699 # NOTE: 's*' is almost not used any more inside CPython 3.5.
1700 # Try not to use it pointlessly: it accepts unicodes, which
1701 # most API in CPython 3.x no longer do.
1702 if self.isinstance_w(w_obj, self.w_bytes):
1703 return StringBuffer(w_obj.bytes_w(self))
1704 if self.isinstance_w(w_obj, self.w_unicode):
1705 # NB. CPython forbids surrogates here
1706 return StringBuffer(w_obj.text_w(self))
1707 try:
1708 return self._try_buffer_w(w_obj, self.BUF_SIMPLE).as_readbuf()
1709 except BufferInterfaceNotFound:
1710 self._getarg_error("bytes or buffer", w_obj)
1711 elif code == 's#':
1712 # NOTE: 's#' is almost not used any more inside CPython 3.5.
1713 # Try not to use it pointlessly: it accepts unicodes, which
1714 # most API in CPython 3.x no longer do.
1715 if self.isinstance_w(w_obj, self.w_bytes):
1716 return w_obj.bytes_w(self)
1717 if self.isinstance_w(w_obj, self.w_unicode): # NB. CPython forbids
1718 return w_obj.text_w(self) # surrogates here
1719 try:
1720 return self._try_buffer_w(w_obj, self.BUF_SIMPLE).as_str()
1721 except BufferInterfaceNotFound:
1722 self._getarg_error("bytes or read-only buffer", w_obj)
1723 elif code == 'w*':
1724 return self.writebuf_w(w_obj)
1725 elif code == 'y*':
1726 return self.readbuf_w(w_obj)
1727 elif code == 'y#':
1728 return self.charbuf_w(w_obj)
1729 else:
1730 assert False
1731
1732 if self.isinstance_w(w_obj, self.w_unicode):
1733 return w_obj.charbuf_w(self)
1734
1735 def text_or_none_w(self, w_obj):
1736 return None if self.is_none(w_obj) else self.text_w(w_obj)
1737
1738 def text0_or_none_w(self, w_obj):
1739 return None if self.is_none(w_obj) else self.text0_w(w_obj)
1740
1741 @specialize.argtype(1)
1742 def bytes_w(self, w_obj):
1743 """ Takes an application level :py:class:`bytes`
1744 (on PyPy2 this equals `str`) and returns a rpython byte string.
1745 """
1746 assert w_obj is not None
1747 return w_obj.bytes_w(self)
1748
1749 @specialize.argtype(1)
1750 def text_w(self, w_obj):
1751 """ PyPy2 takes either a :py:class:`str` and returns a
1752 rpython byte string, or it takes an :py:class:`unicode`
1753 and uses the systems default encoding to return a rpython
1754 byte string.
1755
1756 On PyPy3 it takes a :py:class:`str` and it will return
1757 an utf-8 encoded rpython string.
1758 """
1759 assert w_obj is not None
1760 if not self.isinstance_w(w_obj, self.w_unicode):
1761 w_obj._typed_unwrap_error(self, "str")
1762 return w_obj.text_w(self)
1763
1764 @not_rpython # tests only; should be replaced with bytes_w or text_w
1765 def str_w(self, w_obj):
1766 """
1767 if w_obj is unicode, call utf8_w() (i.e., return the UTF-8-nosg
1768 encoded string). Else, call bytes_w().
1769
1770 We should kill str_w completely and manually substitute it with
1771 text_w/bytes_w at all call sites. It remains for now for tests only.
1772 """
1773 XXX # deprecated, leaving in place for clear errors
1774 if self.isinstance_w(w_obj, self.w_unicode):
1775 # XXX lo text_w, but better to deprecate str_w than to fix this
1776 return w_obj.text_w(self)
1777 else:
1778 return w_obj.bytes_w(self)
1779
1780 def bytes0_w(self, w_obj):
1781 "Like bytes_w, but rejects strings with NUL bytes."
1782 from rpython.rlib import rstring
1783 result = self.bytes_w(w_obj)
1784 if '\x00' in result:
1785 raise oefmt(self.w_ValueError, "embedded null byte")
1786 return rstring.assert_str0(result)
1787
1788 def text0_w(self, w_obj):
1789 "Like text_w, but rejects strings with NUL bytes."
1790 result = self.text_w(w_obj)
1791 if '\x00' in result:
1792 raise oefmt(self.w_ValueError, "embedded null character")
1793 return rstring.assert_str0(result)
1794
1795 def fsencode_or_none_w(self, w_obj):
1796 return None if self.is_none(w_obj) else self.fsencode_w(w_obj)
1797
1798 def byte_w(self, w_obj):
1799 """
1800 Convert an index-like object to an interp-level char
1801
1802 Used for app-level code like "bytearray(b'abc')[0] = 42".
1803 """
1804 value = self.getindex_w(w_obj, None)
1805 if not 0 <= value < 256:
1806 # this includes the OverflowError in case the long is too large
1807 raise oefmt(self.w_ValueError, "byte must be in range(0, 256)")
1808 return chr(value)
1809
1810 @specialize.argtype(1)
1811 def int_w(self, w_obj, allow_conversion=True):
1812 """
1813 Unwrap an app-level int object into an interpret-level int.
1814
1815 If allow_conversion==True, w_obj might be of any type which implements
1816 __int__, *except* floats which are explicitly rejected. This is the
1817 same logic as CPython's PyArg_ParseTuple. If you want to also allow
1818 floats, you can call space.int_w(space.int(w_obj)).
1819
1820 If allow_conversion=False, w_obj needs to be an app-level int or a
1821 subclass.
1822 """
1823 assert w_obj is not None
1824 return w_obj.int_w(self, allow_conversion)
1825
1826 @specialize.argtype(1)
1827 def int(self, w_obj):
1828 assert w_obj is not None
1829 return w_obj.int(self)
1830 long = int
1831
1832 @specialize.argtype(1)
1833 def uint_w(self, w_obj):
1834 assert w_obj is not None
1835 return w_obj.uint_w(self)
1836
1837 @specialize.argtype(1)
1838 def bigint_w(self, w_obj, allow_conversion=True):
1839 """
1840 Like int_w, but return a rlib.rbigint object and call __long__ if
1841 allow_conversion is True.
1842 """
1843 assert w_obj is not None
1844 return w_obj.bigint_w(self, allow_conversion)
1845
1846 @specialize.argtype(1)
1847 def float_w(self, w_obj, allow_conversion=True):
1848 """
1849 Like int_w, but return an interp-level float and call __float__ if
1850 allow_conversion is True.
1851 """
1852 assert w_obj is not None
1853 return w_obj.float_w(self, allow_conversion)
1854
1855 def utf8_w(self, w_obj):
1856 return w_obj.utf8_w(self)
1857
1858 def convert_to_w_unicode(self, w_obj):
1859 return w_obj.convert_to_w_unicode(self)
1860
1861 def realunicode_w(self, w_obj):
1862 from pypy.interpreter.unicodehelper import decode_utf8sp
1863 utf8 = self.utf8_w(w_obj)
1864 return decode_utf8sp(self, utf8)[0].decode('utf8')
1865
1866 def utf8_0_w(self, w_obj):
1867 "Like utf8_w, but rejects strings with NUL bytes."
1868 from rpython.rlib import rstring
1869 result = w_obj.utf8_w(self)
1870 if '\x00' in result:
1871 raise oefmt(self.w_ValueError,
1872 "argument must be a utf8 string without NUL "
1873 "characters")
1874 return rstring.assert_str0(result)
1875
1876 realtext_w = text_w # Python 2 compatibility
1877
1878 def fsencode(space, w_obj):
1879 from pypy.interpreter.unicodehelper import fsencode
1880 return fsencode(space, w_obj)
1881
1882 def fsdecode(space, w_obj):
1883 from pypy.interpreter.unicodehelper import fsdecode
1884 return fsdecode(space, w_obj)
1885
1886 def fsencode_w(self, w_obj, allowed_types="string, bytes, or os.PathLike"):
1887 try:
1888 self._try_buffer_w(w_obj, self.BUF_FULL_RO)
1889 if not self.isinstance_w(w_obj, self.w_bytes):
1890 tp = self.type(w_obj).name
1891 self.warn(self.newtext(
1892 "path should be %s, not %s" % (allowed_types, tp,)),
1893 self.w_DeprecationWarning)
1894 except BufferInterfaceNotFound:
1895 from pypy.module.posix.interp_posix import fspath
1896 w_obj = fspath(self, w_obj)
1897 if self.isinstance_w(w_obj, self.w_unicode):
1898 w_obj = self.fsencode(w_obj)
1899 return self.bytesbuf0_w(w_obj)
1900
1901 def convert_arg_to_w_unicode(self, w_obj, strict=None):
1902 # XXX why convert_to_w_unicode does something slightly different?
1903 from pypy.objspace.std.unicodeobject import W_UnicodeObject
1904 assert not hasattr(self, 'is_fake_objspace')
1905 return W_UnicodeObject.convert_arg_to_w_unicode(self, w_obj, strict)
1906
1907 def utf8_len_w(self, w_obj):
1908 w_obj = self.convert_arg_to_w_unicode(w_obj)
1909 return w_obj.utf8_w(self), w_obj._len()
1910
1911 def realutf8_w(self, w_obj):
1912 # Like utf8_w(), but only works if w_obj is really of type
1913 # 'unicode'. On Python 3 this is the same as utf8_w().
1914 from pypy.objspace.std.unicodeobject import W_UnicodeObject
1915 # for z_translation tests
1916 if hasattr(self, 'is_fake_objspace'): return self.newtext("foobar")
1917 if not isinstance(w_obj, W_UnicodeObject):
1918 raise oefmt(self.w_TypeError, "argument must be a unicode")
1919 return self.utf8_w(w_obj)
1920
1921 def bytesbuf0_w(self, w_obj):
1922 # Like bytes0_w(), but also accept a read-only buffer.
1923 from rpython.rlib import rstring
1924 try:
1925 result = self.bytes_w(w_obj)
1926 except OperationError as e:
1927 if not e.match(self, self.w_TypeError):
1928 raise
1929 result = self.buffer_w(w_obj, self.BUF_FULL_RO).as_str()
1930 if '\x00' in result:
1931 raise oefmt(self.w_ValueError, "embedded null byte")
1932 return rstring.assert_str0(result)
1933
1934 def fsdecode_w(self, w_obj):
1935 try:
1936 self._try_buffer_w(w_obj, self.BUF_FULL_RO)
1937 except BufferInterfaceNotFound:
1938 from pypy.module.posix.interp_posix import fspath
1939 w_obj = fspath(self, w_obj)
1940 else:
1941 w_obj = self.fsdecode(w_obj)
1942 return self.utf8_w(w_obj)
1943
1944 def bool_w(self, w_obj):
1945 # Unwraps a bool, also accepting an int for compatibility.
1946 # For cases where you need to accept bools and ints and nothing
1947 # else. Note that saying 'bool' in unwrap_spec() doesn't call
1948 # this, but the general is_true(), accepting any object.
1949 return bool(self.int_w(w_obj))
1950
1951 @specialize.argtype(1)
1952 def ord(self, w_obj):
1953 assert w_obj is not None
1954 return w_obj.ord(self)
1955
1956 # This is all interface for gateway.py.
1957 gateway_int_w = int_w
1958 gateway_float_w = float_w
1959 gateway_r_longlong_w = r_longlong_w
1960 gateway_r_ulonglong_w = r_ulonglong_w
1961
1962 def gateway_r_uint_w(self, w_obj):
1963 if self.isinstance_w(w_obj, self.w_float):
1964 raise oefmt(self.w_TypeError,
1965 "integer argument expected, got float")
1966 return self.uint_w(self.int(w_obj))
1967
1968 def gateway_nonnegint_w(self, w_obj):
1969 # Like space.gateway_int_w(), but raises an app-level ValueError if
1970 # the integer is negative. Here for gateway.py.
1971 value = self.gateway_int_w(w_obj)
1972 if value < 0:
1973 raise oefmt(self.w_ValueError, "expected a non-negative integer")
1974 return value
1975
1976 def c_int_w(self, w_obj):
1977 # Like space.gateway_int_w(), but raises an app-level OverflowError if
1978 # the integer does not fit in 32 bits. Here for gateway.py.
1979 value = self.gateway_int_w(w_obj)
1980 if value < INT_MIN or value > INT_MAX:
1981 raise oefmt(self.w_OverflowError, "expected a 32-bit integer")
1982 return value
1983
1984 def c_uint_w(self, w_obj):
1985 # Like space.gateway_r_uint_w(), but raises an app-level OverflowError if
1986 # the integer does not fit in 32 bits. Here for gateway.py.
1987 value = self.uint_w(w_obj)
1988 if value > UINT_MAX:
1989 raise oefmt(self.w_OverflowError,
1990 "expected an unsigned 32-bit integer")
1991 return value
1992
1993 def c_nonnegint_w(self, w_obj):
1994 # Like space.gateway_int_w(), but raises an app-level ValueError if
1995 # the integer is negative or does not fit in 32 bits. Here
1996 # for gateway.py.
1997 value = self.int_w(w_obj)
1998 if value < 0:
1999 raise oefmt(self.w_ValueError, "expected a non-negative integer")
2000 if value > INT_MAX:
2001 raise oefmt(self.w_OverflowError, "expected a 32-bit integer")
2002 return value
2003
2004 def c_short_w(self, w_obj):
2005 value = self.int_w(w_obj)
2006 if value < SHRT_MIN:
2007 raise oefmt(self.w_OverflowError,
2008 "signed short integer is less than minimum")
2009 elif value > SHRT_MAX:
2010 raise oefmt(self.w_OverflowError,
2011 "signed short integer is greater than maximum")
2012 return value
2013
2014 def c_ushort_w(self, w_obj):
2015 value = self.int_w(w_obj)
2016 if value < 0:
2017 raise oefmt(self.w_ValueError,
2018 "value must be positive")
2019 elif value > USHRT_MAX:
2020 raise oefmt(self.w_OverflowError,
2021 "Python int too large for C unsigned short")
2022 return value
2023
2024 def c_uid_t_w(self, w_obj):
2025 # xxx assumes that uid_t and gid_t are a C unsigned int.
2026 # Equivalent to space.c_uint_w(), with the exception that
2027 # it also accepts -1 and converts that to UINT_MAX, which
2028 # is (uid_t)-1. And values smaller than -1 raise
2029 # OverflowError, not ValueError.
2030 try:
2031 return self.c_uint_w(w_obj)
2032 except OperationError as e:
2033 if e.match(self, self.w_ValueError):
2034 # ValueError: cannot convert negative integer to unsigned
2035 if self.int_w(w_obj) == -1:
2036 return UINT_MAX
2037 raise oefmt(self.w_OverflowError,
2038 "user/group id smaller than minimum (-1)")
2039 raise
2040
2041 def truncatedint_w(self, w_obj, allow_conversion=True):
2042 # Like space.gateway_int_w(), but return the integer truncated
2043 # instead of raising OverflowError. For obscure cases only.
2044 try:
2045 return self.int_w(w_obj, allow_conversion)
2046 except OperationError as e:
2047 if not e.match(self, self.w_OverflowError):
2048 raise
2049 from rpython.rlib.rarithmetic import intmask
2050 return intmask(self.bigint_w(w_obj).uintmask())
2051
2052 def truncatedlonglong_w(self, w_obj, allow_conversion=True):
2053 # Like space.gateway_r_longlong_w(), but return the integer truncated
2054 # instead of raising OverflowError.
2055 try:
2056 return self.r_longlong_w(w_obj, allow_conversion)
2057 except OperationError as e:
2058 if not e.match(self, self.w_OverflowError):
2059 raise
2060 from rpython.rlib.rarithmetic import longlongmask
2061 return longlongmask(self.bigint_w(w_obj).ulonglongmask())
2062
2063 def c_filedescriptor_w(self, w_fd):
2064 # This is only used sometimes in CPython, e.g. for os.fsync() but
2065 # not os.close(). It's likely designed for 'select'. It's irregular
2066 # in the sense that it expects either a real int/long or an object
2067 # with a fileno(), but not an object with an __int__().
2068 if not self.isinstance_w(w_fd, self.w_int):
2069 try:
2070 w_fileno = self.getattr(w_fd, self.newtext("fileno"))
2071 except OperationError as e:
2072 if e.match(self, self.w_AttributeError):
2073 raise oefmt(self.w_TypeError,
2074 "argument must be an int, or have a fileno() "
2075 "method.")
2076 raise
2077 w_fd = self.call_function(w_fileno)
2078 if not self.isinstance_w(w_fd, self.w_int):
2079 raise oefmt(self.w_TypeError,
2080 "fileno() returned a non-integer")
2081 fd = self.c_int_w(w_fd) # Can raise w_OverflowError
2082 if fd < 0:
2083 raise oefmt(self.w_ValueError,
2084 "file descriptor cannot be a negative integer (%d)", fd)
2085 return fd
2086
2087 def warn(self, w_msg, w_warningcls, stacklevel=2):
2088 from pypy.module._warnings.interp_warnings import do_warn
2089
2090 # 'w_warningcls' must a Warning subclass
2091 if not we_are_translated():
2092 assert self.issubtype_w(w_warningcls, self.w_Warning)
2093 do_warn(self, w_msg, w_warningcls, stacklevel - 1)
2094
2095 def audit(self, event, args_w):
2096 from pypy.module.sys.vm import audit
2097 audit(self, event, args_w)
2098
2099 def iterator_greenkey(self, w_iterable):
2100 """ Return something that can be used as a green key in jit drivers
2101 that iterate over self. by default, it's just the type of self, but
2102 custom iterators should override it. """
2103 return w_iterable.iterator_greenkey(self)
2104
2105 def object_functionstr(self, w_function):
2106 """Like CPython's _PyObject_FunctionStr: returns 'module.qualname()' or
2107 'qualname()' using __qualname__/__module__, falling back to str(x)."""
2108 from pypy.interpreter.function import Function, _Method
2109 if isinstance(w_function, Function):
2110 # fast path: direct attribute access for Python functions
2111 qualname = w_function.qualname
2112 w_module = w_function.fget___module__(self)
2113 if not self.is_w(w_module, self.w_None):
2114 try:
2115 module = self.text_w(w_module)
2116 if module and module != 'builtins':
2117 return module + '.' + qualname + '()'
2118 except OperationError:
2119 pass
2120 return qualname + '()'
2121 if isinstance(w_function, _Method):
2122 return self.object_functionstr(w_function.w_function)
2123 # generic path: try __qualname__ like CPython
2124 w_qualname = self.findattr(w_function, self.newtext('__qualname__'))
2125 if w_qualname is not None:
2126 try:
2127 qualname = self.text_w(w_qualname)
2128 w_module = self.findattr(w_function, self.newtext('__module__'))
2129 if w_module is not None and not self.is_w(w_module, self.w_None):
2130 module = self.text_w(w_module)
2131 if module and module != 'builtins':
2132 return module + '.' + qualname + '()'
2133 return qualname + '()'
2134 except OperationError:
2135 pass
2136 # fallback to str(x) like CPython
2137 try:
2138 return self.text_w(self.str(w_function))
2139 except OperationError:
2140 return self.type(w_function).getname(self) + ' object'
2141
2142
2143 class AppExecCache(SpaceCache):
2144 @not_rpython
2145 def build(cache, source):
2146 return cache.space.appdef(source)
2147
2148
2149 # Table describing the regular part of the interface of object spaces,
2150 # namely all methods which only take w_ arguments and return a w_ result
2151 # (if any).
2152
2153 ObjSpace.MethodTable = [
2154 # method name # symbol # number of arguments # special method name(s)
2155 ('is_', 'is', 2, []),
2156 ('id', 'id', 1, []),
2157 ('type', 'type', 1, []),
2158 ('isinstance', 'isinstance', 2, ['__instancecheck__']),
2159 ('issubtype', 'issubtype', 2, ['__subclasscheck__']), # not for old-style classes
2160 ('repr', 'repr', 1, ['__repr__']),
2161 ('str', 'str', 1, ['__str__']),
2162 ('format', 'format', 2, ['__format__']),
2163 ('len', 'len', 1, ['__len__']),
2164 ('hash', 'hash', 1, ['__hash__']),
2165 ('getattr', 'getattr', 2, ['__getattribute__']),
2166 ('setattr', 'setattr', 3, ['__setattr__']),
2167 ('delattr', 'delattr', 2, ['__delattr__']),
2168 ('getitem', 'getitem', 2, ['__getitem__']),
2169 ('setitem', 'setitem', 3, ['__setitem__']),
2170 ('delitem', 'delitem', 2, ['__delitem__']),
2171 ('trunc', 'trunc', 1, ['__trunc__']),
2172 ('pos', 'pos', 1, ['__pos__']),
2173 ('neg', 'neg', 1, ['__neg__']),
2174 ('nonzero', 'truth', 1, ['__bool__']),
2175 ('abs', 'abs', 1, ['__abs__']),
2176 ('ord', 'ord', 1, []),
2177 ('invert', '~', 1, ['__invert__']),
2178 ('add', '+', 2, ['__add__', '__radd__']),
2179 ('sub', '-', 2, ['__sub__', '__rsub__']),
2180 ('mul', '*', 2, ['__mul__', '__rmul__']),
2181 ('truediv', '/', 2, ['__truediv__', '__rtruediv__']),
2182 ('floordiv', '//', 2, ['__floordiv__', '__rfloordiv__']),
2183 ('div', 'div', 2, ['__div__', '__rdiv__']),
2184 ('mod', '%', 2, ['__mod__', '__rmod__']),
2185 ('divmod', 'divmod', 2, ['__divmod__', '__rdivmod__']),
2186 ('pow', '**', 3, ['__pow__', '__rpow__']),
2187 ('lshift', '<<', 2, ['__lshift__', '__rlshift__']),
2188 ('rshift', '>>', 2, ['__rshift__', '__rrshift__']),
2189 ('and_', '&', 2, ['__and__', '__rand__']),
2190 ('or_', '|', 2, ['__or__', '__ror__']),
2191 ('xor', '^', 2, ['__xor__', '__rxor__']),
2192 ('matmul', '@', 2, ['__matmul__', '__rmatmul__']),
2193 ('int', 'int', 1, ['__int__']),
2194 ('index', 'index', 1, ['__index__']),
2195 ('float', 'float', 1, ['__float__']),
2196 ('inplace_add', '+=', 2, ['__iadd__']),
2197 ('inplace_sub', '-=', 2, ['__isub__']),
2198 ('inplace_mul', '*=', 2, ['__imul__']),
2199 ('inplace_truediv', '/=', 2, ['__itruediv__']),
2200 ('inplace_floordiv','//=', 2, ['__ifloordiv__']),
2201 ('inplace_div', 'div=', 2, ['__idiv__']),
2202 ('inplace_mod', '%=', 2, ['__imod__']),
2203 ('inplace_pow', '**=', 2, ['__ipow__']),
2204 ('inplace_lshift', '<<=', 2, ['__ilshift__']),
2205 ('inplace_rshift', '>>=', 2, ['__irshift__']),
2206 ('inplace_and', '&=', 2, ['__iand__']),
2207 ('inplace_or', '|=', 2, ['__ior__']),
2208 ('inplace_xor', '^=', 2, ['__ixor__']),
2209 ('inplace_matmul', '@=', 2, ['__imatmul__']),
2210 ('lt', '<', 2, ['__lt__', '__gt__']),
2211 ('le', '<=', 2, ['__le__', '__ge__']),
2212 ('eq', '==', 2, ['__eq__', '__eq__']),
2213 ('ne', '!=', 2, ['__ne__', '__ne__']),
2214 ('gt', '>', 2, ['__gt__', '__lt__']),
2215 ('ge', '>=', 2, ['__ge__', '__le__']),
2216 ('contains', 'contains', 2, ['__contains__']),
2217 ('iter', 'iter', 1, ['__iter__']),
2218 ('next', 'next', 1, ['__next__']),
2219 # ('call', 'call', 3, ['__call__']),
2220 ('get', 'get', 3, ['__get__']),
2221 ('set', 'set', 3, ['__set__']),
2222 ('delete', 'delete', 2, ['__delete__']),
2223 ]
2224
2225 ObjSpace.BuiltinModuleTable = [
2226 'builtins',
2227 'sys',
2228 ]
2229
2230 ObjSpace.ConstantTable = [
2231 'None',
2232 'False',
2233 'True',
2234 'Ellipsis',
2235 'NotImplemented',
2236 ]
2237
2238 ObjSpace.ExceptionTable = [
2239 'ArithmeticError',
2240 'AssertionError',
2241 'AttributeError',
2242 'BaseException',
2243 'BufferError',
2244 'BytesWarning',
2245 'BlockingIOError',
2246 'DeprecationWarning',
2247 'EOFError',
2248 'EnvironmentError',
2249 'Exception',
2250 'FloatingPointError',
2251 'FutureWarning',
2252 'GeneratorExit',
2253 'IOError',
2254 'ImportError',
2255 'ImportWarning',
2256 'IndentationError',
2257 'IndexError',
2258 'KeyError',
2259 'KeyboardInterrupt',
2260 'LookupError',
2261 'MemoryError',
2262 'NameError',
2263 'NotImplementedError',
2264 'OSError',
2265 'OverflowError',
2266 'ReferenceError',
2267 'ResourceWarning',
2268 'RecursionError',
2269 'RuntimeError',
2270 'StopIteration',
2271 'SyntaxError',
2272 'SyntaxWarning',
2273 'SystemError',
2274 'SystemExit',
2275 'TabError',
2276 'TypeError',
2277 'UnboundLocalError',
2278 'UnicodeDecodeError',
2279 'UnicodeEncodeError',
2280 'UnicodeError',
2281 'UnicodeTranslateError',
2282 'UnicodeWarning',
2283 'ValueError',
2284 'Warning',
2285 'ZeroDivisionError',
2286 'RuntimeWarning',
2287 'PendingDeprecationWarning',
2288 'UserWarning',
2289 ]
2290
2291 if sys.platform.startswith("win"):
2292 ObjSpace.ExceptionTable += ['WindowsError']
2293
2294 ## Irregular part of the interface:
2295 #
2296 # wrap(x) -> w_x
2297 # str_w(w_str) -> str
2298 # int_w(w_ival or w_long_ival) -> ival
2299 # float_w(w_floatval) -> floatval
2300 # uint_w(w_ival or w_long_ival) -> r_uint_val (unsigned int value)
2301 # bigint_w(w_ival or w_long_ival) -> rbigint
2302 # unwrap(w_x) -> x
2303 # is_true(w_x) -> True or False
2304 # newtuple([w_1, w_2,...]) -> w_tuple
2305 # newlist([w_1, w_2,...]) -> w_list
2306 # newdict() -> empty w_dict
2307 # newslice(w_start,w_stop,w_step) -> w_slice
2308 # call_args(w_obj,Arguments()) -> w_result
2309
2310 ObjSpace.IrregularOpTable = [
2311 'wrap',
2312 'bytes_w',
2313 'int_w',
2314 'float_w',
2315 'uint_w',
2316 'bigint_w',
2317 'utf8_w',
2318 'unwrap',
2319 'is_true',
2320 'is_w',
2321 'newtuple',
2322 'newlist',
2323 'newdict',
2324 'newslice',
2325 'call_args',
2326 ]