PageRenderTime 49ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/interpreter/baseobjspace.py

https://bitbucket.org/pypy/pypy/
Python | 2007 lines | 1932 code | 40 blank | 35 comment | 40 complexity | 5f327c59d619829d7c4621f520fa1037 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. import sys
  2. from rpython.rlib.cache import Cache
  3. from rpython.tool.uid import HUGEVAL_BYTES
  4. from rpython.rlib import jit, types
  5. from rpython.rlib.debug import make_sure_not_resized
  6. from rpython.rlib.objectmodel import (we_are_translated, newlist_hint,
  7. compute_unique_id, specialize)
  8. from rpython.rlib.signature import signature
  9. from rpython.rlib.rarithmetic import r_uint, SHRT_MIN, SHRT_MAX, \
  10. INT_MIN, INT_MAX, UINT_MAX, USHRT_MAX
  11. from pypy.interpreter.executioncontext import (ExecutionContext, ActionFlag,
  12. make_finalizer_queue)
  13. from pypy.interpreter.error import OperationError, new_exception_class, oefmt
  14. from pypy.interpreter.argument import Arguments
  15. from pypy.interpreter.miscutils import ThreadLocals, make_weak_value_dictionary
  16. __all__ = ['ObjSpace', 'OperationError', 'W_Root']
  17. unpackiterable_driver = jit.JitDriver(name='unpackiterable',
  18. greens=['tp'],
  19. reds=['items', 'w_iterator'])
  20. class W_Root(object):
  21. """This is the abstract root class of all wrapped objects that live
  22. in a 'normal' object space like StdObjSpace."""
  23. __slots__ = ('__weakref__',)
  24. _must_be_light_finalizer_ = True
  25. user_overridden_class = False
  26. def getdict(self, space):
  27. return None
  28. def getdictvalue(self, space, attr):
  29. w_dict = self.getdict(space)
  30. if w_dict is not None:
  31. return space.finditem_str(w_dict, attr)
  32. return None
  33. def setdictvalue(self, space, attr, w_value):
  34. w_dict = self.getdict(space)
  35. if w_dict is not None:
  36. space.setitem_str(w_dict, attr, w_value)
  37. return True
  38. return False
  39. def deldictvalue(self, space, attr):
  40. w_dict = self.getdict(space)
  41. if w_dict is not None:
  42. try:
  43. space.delitem(w_dict, space.wrap(attr))
  44. return True
  45. except OperationError as ex:
  46. if not ex.match(space, space.w_KeyError):
  47. raise
  48. return False
  49. def setdict(self, space, w_dict):
  50. raise oefmt(space.w_TypeError,
  51. "attribute '__dict__' of %T objects is not writable",
  52. self)
  53. # to be used directly only by space.type implementations
  54. def getclass(self, space):
  55. return space.gettypeobject(self.typedef)
  56. def setclass(self, space, w_subtype):
  57. raise oefmt(space.w_TypeError,
  58. "__class__ assignment: only for heap types")
  59. def user_setup(self, space, w_subtype):
  60. raise NotImplementedError("only for interp-level user subclasses "
  61. "from typedef.py")
  62. def getname(self, space):
  63. try:
  64. return space.str_w(space.getattr(self, space.wrap('__name__')))
  65. except OperationError as e:
  66. if e.match(space, space.w_TypeError) or e.match(space, space.w_AttributeError):
  67. return '?'
  68. raise
  69. def getaddrstring(self, space):
  70. # slowish
  71. w_id = space.id(self)
  72. w_4 = space.wrap(4)
  73. w_0x0F = space.wrap(0x0F)
  74. i = 2 * HUGEVAL_BYTES
  75. addrstring = [' '] * i
  76. while True:
  77. n = space.int_w(space.and_(w_id, w_0x0F), allow_conversion=False)
  78. n += ord('0')
  79. if n > ord('9'):
  80. n += (ord('a') - ord('9') - 1)
  81. i -= 1
  82. addrstring[i] = chr(n)
  83. if i == 0:
  84. break
  85. w_id = space.rshift(w_id, w_4)
  86. return ''.join(addrstring)
  87. def getrepr(self, space, info, moreinfo=''):
  88. addrstring = self.getaddrstring(space)
  89. return space.wrap("<%s at 0x%s%s>" % (info, addrstring,
  90. moreinfo))
  91. def getslotvalue(self, index):
  92. raise NotImplementedError
  93. def setslotvalue(self, index, w_val):
  94. raise NotImplementedError
  95. def delslotvalue(self, index):
  96. raise NotImplementedError
  97. def descr_call_mismatch(self, space, opname, RequiredClass, args):
  98. if RequiredClass is None:
  99. classname = '?'
  100. else:
  101. classname = wrappable_class_name(RequiredClass)
  102. raise oefmt(space.w_TypeError,
  103. "'%s' object expected, got '%T' instead", classname, self)
  104. # used by _weakref implemenation
  105. def getweakref(self):
  106. return None
  107. def setweakref(self, space, weakreflifeline):
  108. raise oefmt(space.w_TypeError,
  109. "cannot create weak reference to '%T' object", self)
  110. def delweakref(self):
  111. pass
  112. def clear_all_weakrefs(self):
  113. """Ensures that weakrefs (if any) are cleared now. This is
  114. called by UserDelAction before the object is finalized further.
  115. """
  116. lifeline = self.getweakref()
  117. if lifeline is not None:
  118. # Clear all weakrefs to this object before we proceed with
  119. # the destruction of the object. We detach the lifeline
  120. # first: if the code following before_del() calls the
  121. # app-level, e.g. a user-defined __del__(), and this code
  122. # tries to use weakrefs again, it won't reuse the broken
  123. # (already-cleared) weakrefs from this lifeline.
  124. self.delweakref()
  125. lifeline.clear_all_weakrefs()
  126. def _finalize_(self):
  127. """The RPython-level finalizer.
  128. By default, it is *not called*. See self.register_finalizer().
  129. Be ready to handle the case where the object is only half
  130. initialized. Also, in some cases the object might still be
  131. visible to app-level after _finalize_() is called (e.g. if
  132. there is a __del__ that resurrects).
  133. """
  134. def register_finalizer(self, space):
  135. """Register a finalizer for this object, so that
  136. self._finalize_() will be called. You must call this method at
  137. most once. Be ready to handle in _finalize_() the case where
  138. the object is half-initialized, even if you only call
  139. self.register_finalizer() at the end of the initialization.
  140. This is because there are cases where the finalizer is already
  141. registered before: if the user makes an app-level subclass with
  142. a __del__. (In that case only, self.register_finalizer() does
  143. nothing, because the finalizer is already registered in
  144. allocate_instance().)
  145. """
  146. if self.user_overridden_class and self.getclass(space).hasuserdel:
  147. # already registered by space.allocate_instance()
  148. if not we_are_translated():
  149. assert space.finalizer_queue._already_registered(self)
  150. else:
  151. if not we_are_translated():
  152. # does not make sense if _finalize_ is not overridden
  153. assert self._finalize_.im_func is not W_Root._finalize_.im_func
  154. space.finalizer_queue.register_finalizer(self)
  155. # hooks that the mapdict implementations needs:
  156. def _get_mapdict_map(self):
  157. return None
  158. def _set_mapdict_map(self, map):
  159. raise NotImplementedError
  160. def _mapdict_read_storage(self, index):
  161. raise NotImplementedError
  162. def _mapdict_write_storage(self, index, value):
  163. raise NotImplementedError
  164. def _mapdict_storage_length(self):
  165. raise NotImplementedError
  166. def _set_mapdict_storage_and_map(self, storage, map):
  167. raise NotImplementedError
  168. # -------------------------------------------------------------------
  169. def is_w(self, space, w_other):
  170. return self is w_other
  171. def immutable_unique_id(self, space):
  172. return None
  173. def buffer_w(self, space, flags):
  174. w_impl = space.lookup(self, '__buffer__')
  175. if w_impl is not None:
  176. w_result = space.get_and_call_function(w_impl, self)
  177. if space.isinstance_w(w_result, space.w_buffer):
  178. return w_result.buffer_w(space, flags)
  179. raise BufferInterfaceNotFound
  180. def readbuf_w(self, space):
  181. w_impl = space.lookup(self, '__buffer__')
  182. if w_impl is not None:
  183. w_result = space.get_and_call_function(w_impl, self)
  184. if space.isinstance_w(w_result, space.w_buffer):
  185. return w_result.readbuf_w(space)
  186. raise BufferInterfaceNotFound
  187. def writebuf_w(self, space):
  188. w_impl = space.lookup(self, '__buffer__')
  189. if w_impl is not None:
  190. w_result = space.get_and_call_function(w_impl, self)
  191. if space.isinstance_w(w_result, space.w_buffer):
  192. return w_result.writebuf_w(space)
  193. raise BufferInterfaceNotFound
  194. def charbuf_w(self, space):
  195. w_impl = space.lookup(self, '__buffer__')
  196. if w_impl is not None:
  197. w_result = space.get_and_call_function(w_impl, self)
  198. if space.isinstance_w(w_result, space.w_buffer):
  199. return w_result.charbuf_w(space)
  200. raise BufferInterfaceNotFound
  201. def str_w(self, space):
  202. self._typed_unwrap_error(space, "string")
  203. def unicode_w(self, space):
  204. self._typed_unwrap_error(space, "unicode")
  205. def bytearray_list_of_chars_w(self, space):
  206. self._typed_unwrap_error(space, "bytearray")
  207. def int_w(self, space, allow_conversion=True):
  208. # note that W_IntObject.int_w has a fast path and W_FloatObject.int_w
  209. # raises w_TypeError
  210. w_obj = self
  211. if allow_conversion:
  212. w_obj = space.int(self)
  213. return w_obj._int_w(space)
  214. def _int_w(self, space):
  215. self._typed_unwrap_error(space, "integer")
  216. def float_w(self, space, allow_conversion=True):
  217. w_obj = self
  218. if allow_conversion:
  219. w_obj = space.float(self)
  220. return w_obj._float_w(space)
  221. def _float_w(self, space):
  222. self._typed_unwrap_error(space, "float")
  223. def uint_w(self, space):
  224. self._typed_unwrap_error(space, "integer")
  225. def bigint_w(self, space, allow_conversion=True):
  226. # note that W_IntObject and W_LongObject have fast paths,
  227. # W_FloatObject.rbigint_w raises w_TypeError raises
  228. w_obj = self
  229. if allow_conversion:
  230. w_obj = space.long(self)
  231. return w_obj._bigint_w(space)
  232. def _bigint_w(self, space):
  233. self._typed_unwrap_error(space, "integer")
  234. def _typed_unwrap_error(self, space, expected):
  235. raise oefmt(space.w_TypeError,
  236. "expected %s, got %T object", expected, self)
  237. def int(self, space):
  238. w_impl = space.lookup(self, '__int__')
  239. if w_impl is None:
  240. self._typed_unwrap_error(space, "integer")
  241. w_result = space.get_and_call_function(w_impl, self)
  242. if (space.isinstance_w(w_result, space.w_int) or
  243. space.isinstance_w(w_result, space.w_long)):
  244. return w_result
  245. raise oefmt(space.w_TypeError,
  246. "__int__ returned non-int (type '%T')", w_result)
  247. def ord(self, space):
  248. raise oefmt(space.w_TypeError,
  249. "ord() expected string of length 1, but %T found", self)
  250. def __spacebind__(self, space):
  251. return self
  252. def unwrap(self, space):
  253. """NOT_RPYTHON"""
  254. # _____ this code is here to support testing only _____
  255. return self
  256. def unpackiterable_int(self, space):
  257. lst = space.listview_int(self)
  258. if lst:
  259. return lst[:]
  260. return None
  261. def unpackiterable_float(self, space):
  262. lst = space.listview_float(self)
  263. if lst:
  264. return lst[:]
  265. return None
  266. class InterpIterable(object):
  267. def __init__(self, space, w_iterable):
  268. self.w_iter = space.iter(w_iterable)
  269. self.space = space
  270. def __iter__(self):
  271. return self
  272. def next(self):
  273. space = self.space
  274. try:
  275. return space.next(self.w_iter)
  276. except OperationError as e:
  277. if not e.match(space, space.w_StopIteration):
  278. raise
  279. raise StopIteration
  280. class InternalSpaceCache(Cache):
  281. """A generic cache for an object space. Arbitrary information can
  282. be attached to the space by defining a function or class 'f' which
  283. can be called as 'f(space)'. Its result is stored in this
  284. ObjSpaceCache.
  285. """
  286. def __init__(self, space):
  287. Cache.__init__(self)
  288. self.space = space
  289. def _build(self, callable):
  290. return callable(self.space)
  291. class SpaceCache(Cache):
  292. """A base class for all our concrete caches."""
  293. def __init__(self, space):
  294. Cache.__init__(self)
  295. self.space = space
  296. def _build(self, key):
  297. return self.build(key)
  298. def _ready(self, result):
  299. return self.ready(result)
  300. def ready(self, result):
  301. pass
  302. class DescrMismatch(Exception):
  303. pass
  304. class BufferInterfaceNotFound(Exception):
  305. pass
  306. def wrappable_class_name(Class):
  307. try:
  308. return Class.typedef.name
  309. except AttributeError:
  310. return 'internal subclass of %s' % (Class.__name__,)
  311. wrappable_class_name._annspecialcase_ = 'specialize:memo'
  312. class CannotHaveLock(Exception):
  313. """Raised by space.allocate_lock() if we're translating."""
  314. # ____________________________________________________________
  315. class ObjSpace(object):
  316. """Base class for the interpreter-level implementations of object spaces.
  317. http://pypy.readthedocs.org/en/latest/objspace.html"""
  318. def __init__(self, config=None):
  319. "NOT_RPYTHON: Basic initialization of objects."
  320. self.fromcache = InternalSpaceCache(self).getorbuild
  321. self.threadlocals = ThreadLocals()
  322. # set recursion limit
  323. # sets all the internal descriptors
  324. if config is None:
  325. from pypy.config.pypyoption import get_pypy_config
  326. config = get_pypy_config(translating=False)
  327. self.config = config
  328. self.builtin_modules = {}
  329. self.reloading_modules = {}
  330. self.interned_strings = make_weak_value_dictionary(self, str, W_Root)
  331. self.actionflag = ActionFlag() # changed by the signal module
  332. self.check_signal_action = None # changed by the signal module
  333. make_finalizer_queue(W_Root, self)
  334. self._code_of_sys_exc_info = None
  335. # can be overridden to a subclass
  336. self.initialize()
  337. def startup(self):
  338. # To be called before using the space
  339. self.threadlocals.enter_thread(self)
  340. # Initialize already imported builtin modules
  341. from pypy.interpreter.module import Module
  342. w_modules = self.sys.get('modules')
  343. for w_modname in self.unpackiterable(
  344. self.sys.get('builtin_module_names')):
  345. try:
  346. w_mod = self.getitem(w_modules, w_modname)
  347. except OperationError as e:
  348. if e.match(self, self.w_KeyError):
  349. continue
  350. raise
  351. if isinstance(w_mod, Module) and not w_mod.startup_called:
  352. w_mod.init(self)
  353. def finish(self):
  354. self.wait_for_thread_shutdown()
  355. w_exitfunc = self.sys.getdictvalue(self, 'exitfunc')
  356. if w_exitfunc is not None:
  357. try:
  358. self.call_function(w_exitfunc)
  359. except OperationError as e:
  360. e.write_unraisable(self, 'sys.exitfunc == ', w_exitfunc)
  361. from pypy.interpreter.module import Module
  362. for w_mod in self.builtin_modules.values():
  363. if isinstance(w_mod, Module) and w_mod.startup_called:
  364. w_mod.shutdown(self)
  365. def wait_for_thread_shutdown(self):
  366. """Wait until threading._shutdown() completes, provided the threading
  367. module was imported in the first place. The shutdown routine will
  368. wait until all non-daemon 'threading' threads have completed."""
  369. if not self.config.translation.thread:
  370. return
  371. w_modules = self.sys.get('modules')
  372. w_mod = self.finditem_str(w_modules, 'threading')
  373. if w_mod is None:
  374. return
  375. try:
  376. self.call_method(w_mod, "_shutdown")
  377. except OperationError as e:
  378. e.write_unraisable(self, "threading._shutdown()")
  379. def __repr__(self):
  380. try:
  381. return self._this_space_repr_
  382. except AttributeError:
  383. return self.__class__.__name__
  384. def setbuiltinmodule(self, importname):
  385. """NOT_RPYTHON. load a lazy pypy/module and put it into sys.modules"""
  386. if '.' in importname:
  387. fullname = importname
  388. importname = fullname.rsplit('.', 1)[1]
  389. else:
  390. fullname = "pypy.module.%s" % importname
  391. Module = __import__(fullname,
  392. None, None, ["Module"]).Module
  393. if Module.applevel_name is not None:
  394. name = Module.applevel_name
  395. else:
  396. name = importname
  397. mod = Module(self, self.wrap(name))
  398. mod.install()
  399. return name
  400. def getbuiltinmodule(self, name, force_init=False, reuse=True):
  401. w_name = self.wrap(name)
  402. w_modules = self.sys.get('modules')
  403. if not force_init:
  404. assert reuse
  405. try:
  406. return self.getitem(w_modules, w_name)
  407. except OperationError as e:
  408. if not e.match(self, self.w_KeyError):
  409. raise
  410. # If the module is a builtin but not yet imported,
  411. # retrieve it and initialize it
  412. try:
  413. w_mod = self.builtin_modules[name]
  414. except KeyError:
  415. raise oefmt(self.w_SystemError,
  416. "getbuiltinmodule() called with non-builtin module %s",
  417. name)
  418. # Add the module to sys.modules and initialize the module. The
  419. # order is important to avoid recursions.
  420. from pypy.interpreter.module import Module
  421. if isinstance(w_mod, Module):
  422. if not reuse and w_mod.startup_called:
  423. # create a copy of the module. (see issue1514) eventlet
  424. # patcher relies on this behaviour.
  425. w_mod2 = self.wrap(Module(self, w_name))
  426. self.setitem(w_modules, w_name, w_mod2)
  427. w_mod.getdict(self) # unlazy w_initialdict
  428. self.call_method(w_mod2.getdict(self), 'update',
  429. w_mod.w_initialdict)
  430. return w_mod2
  431. self.setitem(w_modules, w_name, w_mod)
  432. w_mod.init(self)
  433. else:
  434. self.setitem(w_modules, w_name, w_mod)
  435. return w_mod
  436. def get_builtinmodule_to_install(self):
  437. """NOT_RPYTHON"""
  438. try:
  439. return self._builtinmodule_list
  440. except AttributeError:
  441. pass
  442. modules = []
  443. # You can enable more modules by specifying --usemodules=xxx,yyy
  444. for name, value in self.config.objspace.usemodules:
  445. if value and name not in modules:
  446. modules.append(name)
  447. if self.config.objspace.extmodules:
  448. for name in self.config.objspace.extmodules.split(','):
  449. if name not in modules:
  450. modules.append(name)
  451. self._builtinmodule_list = modules
  452. return self._builtinmodule_list
  453. ALL_BUILTIN_MODULES = [
  454. 'posix', 'nt', 'os2', 'mac', 'ce', 'riscos',
  455. 'math', 'array', 'select',
  456. '_random', '_sre', 'time', '_socket', 'errno',
  457. 'unicodedata',
  458. 'parser', 'fcntl', '_codecs', 'binascii'
  459. ]
  460. # These modules are treated like CPython treats built-in modules,
  461. # i.e. they always shadow any xx.py. The other modules are treated
  462. # like CPython treats extension modules, and are loaded in sys.path
  463. # order by the fake entry '.../lib_pypy/__extensions__'.
  464. MODULES_THAT_ALWAYS_SHADOW = dict.fromkeys([
  465. '__builtin__', '__pypy__', '_ast', '_codecs', '_sre', '_warnings',
  466. '_weakref', 'errno', 'exceptions', 'gc', 'imp', 'marshal',
  467. 'posix', 'nt', 'pwd', 'signal', 'sys', 'thread', 'zipimport',
  468. ], None)
  469. def make_builtins(self):
  470. "NOT_RPYTHON: only for initializing the space."
  471. from pypy.module.exceptions import Module
  472. w_name = self.wrap('exceptions')
  473. self.exceptions_module = Module(self, w_name)
  474. self.exceptions_module.install()
  475. from pypy.module.sys import Module
  476. w_name = self.wrap('sys')
  477. self.sys = Module(self, w_name)
  478. self.sys.install()
  479. from pypy.module.imp import Module
  480. w_name = self.wrap('imp')
  481. mod = Module(self, w_name)
  482. mod.install()
  483. from pypy.module.__builtin__ import Module
  484. w_name = self.wrap('__builtin__')
  485. self.builtin = Module(self, w_name)
  486. w_builtin = self.wrap(self.builtin)
  487. w_builtin.install()
  488. self.setitem(self.builtin.w_dict, self.wrap('__builtins__'), w_builtin)
  489. bootstrap_modules = set(('sys', 'imp', '__builtin__', 'exceptions'))
  490. installed_builtin_modules = list(bootstrap_modules)
  491. exception_types_w = self.export_builtin_exceptions()
  492. # initialize with "bootstrap types" from objspace (e.g. w_None)
  493. types_w = (self.get_builtin_types().items() +
  494. exception_types_w.items())
  495. for name, w_type in types_w:
  496. self.setitem(self.builtin.w_dict, self.wrap(name), w_type)
  497. # install mixed modules
  498. for mixedname in self.get_builtinmodule_to_install():
  499. if mixedname not in bootstrap_modules:
  500. self.install_mixedmodule(mixedname, installed_builtin_modules)
  501. installed_builtin_modules.sort()
  502. w_builtin_module_names = self.newtuple(
  503. [self.wrap(fn) for fn in installed_builtin_modules])
  504. # force this value into the dict without unlazyfying everything
  505. self.setitem(self.sys.w_dict, self.wrap('builtin_module_names'),
  506. w_builtin_module_names)
  507. def get_builtin_types(self):
  508. """Get a dictionary mapping the names of builtin types to the type
  509. objects."""
  510. raise NotImplementedError
  511. def export_builtin_exceptions(self):
  512. """NOT_RPYTHON"""
  513. w_dic = self.exceptions_module.getdict(self)
  514. w_keys = self.call_method(w_dic, "keys")
  515. exc_types_w = {}
  516. for w_name in self.unpackiterable(w_keys):
  517. name = self.str_w(w_name)
  518. if not name.startswith('__'):
  519. excname = name
  520. w_exc = self.getitem(w_dic, w_name)
  521. exc_types_w[name] = w_exc
  522. setattr(self, "w_" + excname, w_exc)
  523. return exc_types_w
  524. def install_mixedmodule(self, mixedname, installed_builtin_modules):
  525. """NOT_RPYTHON"""
  526. modname = self.setbuiltinmodule(mixedname)
  527. if modname:
  528. assert modname not in installed_builtin_modules, (
  529. "duplicate interp-level module enabled for the "
  530. "app-level module %r" % (modname,))
  531. installed_builtin_modules.append(modname)
  532. def setup_builtin_modules(self):
  533. "NOT_RPYTHON: only for initializing the space."
  534. if self.config.objspace.usemodules.cpyext:
  535. from pypy.module.cpyext.state import State
  536. self.fromcache(State).build_api(self)
  537. self.getbuiltinmodule('sys')
  538. self.getbuiltinmodule('imp')
  539. self.getbuiltinmodule('__builtin__')
  540. for mod in self.builtin_modules.values():
  541. mod.setup_after_space_initialization()
  542. def initialize(self):
  543. """NOT_RPYTHON: Abstract method that should put some minimal
  544. content into the w_builtins."""
  545. def getexecutioncontext(self):
  546. "Return what we consider to be the active execution context."
  547. # Important: the annotator must not see a prebuilt ExecutionContext:
  548. # you should not see frames while you translate
  549. # so we make sure that the threadlocals never *have* an
  550. # ExecutionContext during translation.
  551. if not we_are_translated():
  552. if self.config.translating:
  553. assert self.threadlocals.get_ec() is None, (
  554. "threadlocals got an ExecutionContext during translation!")
  555. try:
  556. return self._ec_during_translation
  557. except AttributeError:
  558. ec = self.createexecutioncontext()
  559. self._ec_during_translation = ec
  560. return ec
  561. else:
  562. ec = self.threadlocals.get_ec()
  563. if ec is None:
  564. self.threadlocals.enter_thread(self)
  565. ec = self.threadlocals.get_ec()
  566. return ec
  567. else:
  568. # translated case follows. self.threadlocals is either from
  569. # 'pypy.interpreter.miscutils' or 'pypy.module.thread.threadlocals'.
  570. # the result is assumed to be non-null: enter_thread() was called
  571. # by space.startup().
  572. ec = self.threadlocals.get_ec()
  573. assert ec is not None
  574. return ec
  575. def _freeze_(self):
  576. return True
  577. def createexecutioncontext(self):
  578. "Factory function for execution contexts."
  579. return ExecutionContext(self)
  580. def createcompiler(self):
  581. "Factory function creating a compiler object."
  582. try:
  583. return self.default_compiler
  584. except AttributeError:
  585. from pypy.interpreter.pycompiler import PythonAstCompiler
  586. compiler = PythonAstCompiler(self)
  587. self.default_compiler = compiler
  588. return compiler
  589. def createframe(self, code, w_globals, outer_func=None):
  590. "Create an empty PyFrame suitable for this code object."
  591. return self.FrameClass(self, code, w_globals, outer_func)
  592. def allocate_lock(self):
  593. """Return an interp-level Lock object if threads are enabled,
  594. and a dummy object if they are not."""
  595. from rpython.rlib import rthread
  596. if not self.config.objspace.usemodules.thread:
  597. return rthread.dummy_lock
  598. # hack: we can't have prebuilt locks if we're translating.
  599. # In this special situation we should just not lock at all
  600. # (translation is not multithreaded anyway).
  601. if not we_are_translated() and self.config.translating:
  602. raise CannotHaveLock()
  603. try:
  604. return rthread.allocate_lock()
  605. except rthread.error:
  606. raise oefmt(self.w_RuntimeError, "out of resources")
  607. # Following is a friendly interface to common object space operations
  608. # that can be defined in term of more primitive ones. Subclasses
  609. # may also override specific functions for performance.
  610. def not_(self, w_obj):
  611. return self.wrap(not self.is_true(w_obj))
  612. def eq_w(self, w_obj1, w_obj2):
  613. """Implements equality with the double check 'x is y or x == y'."""
  614. return self.is_w(w_obj1, w_obj2) or self.is_true(self.eq(w_obj1, w_obj2))
  615. def is_(self, w_one, w_two):
  616. return self.newbool(self.is_w(w_one, w_two))
  617. def is_w(self, w_one, w_two):
  618. # done by a method call on w_two (and not on w_one, because of the
  619. # expected programming style where we say "if x is None" or
  620. # "if x is object").
  621. assert w_two is not None
  622. return w_two.is_w(self, w_one)
  623. def is_none(self, w_obj):
  624. """ mostly for checking inputargs that have unwrap_spec and
  625. can accept both w_None and None
  626. """
  627. return w_obj is None or self.is_w(w_obj, self.w_None)
  628. def id(self, w_obj):
  629. w_result = w_obj.immutable_unique_id(self)
  630. if w_result is None:
  631. # in the common case, returns an unsigned value
  632. w_result = self.wrap(r_uint(compute_unique_id(w_obj)))
  633. return w_result
  634. def hash_w(self, w_obj):
  635. """shortcut for space.int_w(space.hash(w_obj))"""
  636. return self.int_w(self.hash(w_obj))
  637. def len_w(self, w_obj):
  638. """shortcut for space.int_w(space.len(w_obj))"""
  639. return self.int_w(self.len(w_obj))
  640. def contains_w(self, w_container, w_item):
  641. """shortcut for space.is_true(space.contains(w_container, w_item))"""
  642. return self.is_true(self.contains(w_container, w_item))
  643. def setitem_str(self, w_obj, key, w_value):
  644. return self.setitem(w_obj, self.wrap(key), w_value)
  645. def finditem_str(self, w_obj, key):
  646. return self.finditem(w_obj, self.wrap(key))
  647. def finditem(self, w_obj, w_key):
  648. try:
  649. return self.getitem(w_obj, w_key)
  650. except OperationError as e:
  651. if e.match(self, self.w_KeyError):
  652. return None
  653. raise
  654. def findattr(self, w_object, w_name):
  655. try:
  656. return self.getattr(w_object, w_name)
  657. except OperationError as e:
  658. # a PyPy extension: let SystemExit and KeyboardInterrupt go through
  659. if e.async(self):
  660. raise
  661. return None
  662. @signature(types.any(), types.bool(), returns=types.instance(W_Root))
  663. def newbool(self, b):
  664. if b:
  665. return self.w_True
  666. else:
  667. return self.w_False
  668. def new_interned_w_str(self, w_s):
  669. assert isinstance(w_s, W_Root) # and is not None
  670. s = self.str_w(w_s)
  671. if not we_are_translated():
  672. assert type(s) is str
  673. w_s1 = self.interned_strings.get(s)
  674. if w_s1 is None:
  675. w_s1 = w_s
  676. self.interned_strings.set(s, w_s1)
  677. return w_s1
  678. def new_interned_str(self, s):
  679. if not we_are_translated():
  680. assert type(s) is str
  681. w_s1 = self.interned_strings.get(s)
  682. if w_s1 is None:
  683. w_s1 = self.wrap(s)
  684. self.interned_strings.set(s, w_s1)
  685. return w_s1
  686. def is_interned_str(self, s):
  687. # interface for marshal_impl
  688. if not we_are_translated():
  689. assert type(s) is str
  690. return self.interned_strings.get(s) is not None
  691. def descr_self_interp_w(self, RequiredClass, w_obj):
  692. if not isinstance(w_obj, RequiredClass):
  693. raise DescrMismatch()
  694. return w_obj
  695. descr_self_interp_w._annspecialcase_ = 'specialize:arg(1)'
  696. def interp_w(self, RequiredClass, w_obj, can_be_None=False):
  697. """
  698. Unwrap w_obj, checking that it is an instance of the required internal
  699. interpreter class.
  700. """
  701. assert RequiredClass is not None
  702. if can_be_None and self.is_none(w_obj):
  703. return None
  704. if not isinstance(w_obj, RequiredClass): # or obj is None
  705. raise oefmt(self.w_TypeError,
  706. "'%s' object expected, got '%N' instead",
  707. wrappable_class_name(RequiredClass),
  708. w_obj.getclass(self))
  709. return w_obj
  710. interp_w._annspecialcase_ = 'specialize:arg(1)'
  711. def unpackiterable(self, w_iterable, expected_length=-1):
  712. """Unpack an iterable into a real (interpreter-level) list.
  713. Raise an OperationError(w_ValueError) if the length is wrong."""
  714. w_iterator = self.iter(w_iterable)
  715. if expected_length == -1:
  716. # xxx special hack for speed
  717. from pypy.interpreter.generator import GeneratorIterator
  718. if isinstance(w_iterator, GeneratorIterator):
  719. lst_w = []
  720. w_iterator.unpack_into(lst_w)
  721. return lst_w
  722. # /xxx
  723. return self._unpackiterable_unknown_length(w_iterator, w_iterable)
  724. else:
  725. lst_w = self._unpackiterable_known_length(w_iterator,
  726. expected_length)
  727. return lst_w[:] # make the resulting list resizable
  728. def iteriterable(self, w_iterable):
  729. return InterpIterable(self, w_iterable)
  730. def _unpackiterable_unknown_length(self, w_iterator, w_iterable):
  731. """Unpack an iterable of unknown length into an interp-level
  732. list.
  733. """
  734. # If we can guess the expected length we can preallocate.
  735. try:
  736. items = newlist_hint(self.length_hint(w_iterable, 0))
  737. except MemoryError:
  738. items = [] # it might have lied
  739. tp = self.type(w_iterator)
  740. while True:
  741. unpackiterable_driver.jit_merge_point(tp=tp,
  742. w_iterator=w_iterator,
  743. items=items)
  744. try:
  745. w_item = self.next(w_iterator)
  746. except OperationError as e:
  747. if not e.match(self, self.w_StopIteration):
  748. raise
  749. break # done
  750. items.append(w_item)
  751. #
  752. return items
  753. @jit.dont_look_inside
  754. def _unpackiterable_known_length(self, w_iterator, expected_length):
  755. # Unpack a known length list, without letting the JIT look inside.
  756. # Implemented by just calling the @jit.unroll_safe version, but
  757. # the JIT stopped looking inside already.
  758. return self._unpackiterable_known_length_jitlook(w_iterator,
  759. expected_length)
  760. @jit.unroll_safe
  761. def _unpackiterable_known_length_jitlook(self, w_iterator,
  762. expected_length):
  763. items = [None] * expected_length
  764. idx = 0
  765. while True:
  766. try:
  767. w_item = self.next(w_iterator)
  768. except OperationError as e:
  769. if not e.match(self, self.w_StopIteration):
  770. raise
  771. break # done
  772. if idx == expected_length:
  773. raise oefmt(self.w_ValueError, "too many values to unpack")
  774. items[idx] = w_item
  775. idx += 1
  776. if idx < expected_length:
  777. raise oefmt(self.w_ValueError,
  778. "need more than %d value%s to unpack",
  779. idx, "" if idx == 1 else "s")
  780. return items
  781. def unpackiterable_unroll(self, w_iterable, expected_length):
  782. # Like unpackiterable(), but for the cases where we have
  783. # an expected_length and want to unroll when JITted.
  784. # Returns a fixed-size list.
  785. w_iterator = self.iter(w_iterable)
  786. assert expected_length != -1
  787. return self._unpackiterable_known_length_jitlook(w_iterator,
  788. expected_length)
  789. def unpackiterable_int(self, w_obj):
  790. """
  791. Return a RPython list of unwrapped ints out of w_obj. The list is
  792. guaranteed to be acopy of the actual data contained in w_obj, so you
  793. can freely modify it. It might return None if not supported.
  794. """
  795. return w_obj.unpackiterable_int(self)
  796. def unpackiterable_float(self, w_obj):
  797. """
  798. Same as unpackiterable_int, but for floats.
  799. """
  800. return w_obj.unpackiterable_float(self)
  801. def length_hint(self, w_obj, default):
  802. """Return the length of an object, consulting its __length_hint__
  803. method if necessary.
  804. """
  805. try:
  806. return self.len_w(w_obj)
  807. except OperationError as e:
  808. if not (e.match(self, self.w_TypeError) or
  809. e.match(self, self.w_AttributeError)):
  810. raise
  811. w_descr = self.lookup(w_obj, '__length_hint__')
  812. if w_descr is None:
  813. return default
  814. try:
  815. w_hint = self.get_and_call_function(w_descr, w_obj)
  816. except OperationError as e:
  817. if not (e.match(self, self.w_TypeError) or
  818. e.match(self, self.w_AttributeError)):
  819. raise
  820. return default
  821. if self.is_w(w_hint, self.w_NotImplemented):
  822. return default
  823. hint = self.int_w(w_hint)
  824. if hint < 0:
  825. raise oefmt(self.w_ValueError,
  826. "__length_hint__() should return >= 0")
  827. return hint
  828. def fixedview(self, w_iterable, expected_length=-1):
  829. """ A fixed list view of w_iterable. Don't modify the result
  830. """
  831. return make_sure_not_resized(self.unpackiterable(w_iterable,
  832. expected_length)[:])
  833. fixedview_unroll = fixedview
  834. def listview(self, w_iterable, expected_length=-1):
  835. """ A non-fixed view of w_iterable. Don't modify the result
  836. """
  837. return self.unpackiterable(w_iterable, expected_length)
  838. def listview_no_unpack(self, w_iterable):
  839. """ Same as listview() if cheap. If 'w_iterable' is something like
  840. a generator, for example, then return None instead.
  841. May return None anyway.
  842. """
  843. return None
  844. def listview_bytes(self, w_list):
  845. """ Return a list of unwrapped strings out of a list of strings. If the
  846. argument is not a list or does not contain only strings, return None.
  847. May return None anyway.
  848. """
  849. return None
  850. def listview_unicode(self, w_list):
  851. """ Return a list of unwrapped unicode out of a list of unicode. If the
  852. argument is not a list or does not contain only unicode, return None.
  853. May return None anyway.
  854. """
  855. return None
  856. def listview_int(self, w_list):
  857. """ Return a list of unwrapped int out of a list of int. If the
  858. argument is not a list or does not contain only int, return None.
  859. May return None anyway.
  860. """
  861. return None
  862. def listview_float(self, w_list):
  863. """ Return a list of unwrapped float out of a list of float. If the
  864. argument is not a list or does not contain only float, return None.
  865. May return None anyway.
  866. """
  867. return None
  868. def view_as_kwargs(self, w_dict):
  869. """ if w_dict is a kwargs-dict, return two lists, one of unwrapped
  870. strings and one of wrapped values. otherwise return (None, None)
  871. """
  872. return (None, None)
  873. def newlist_bytes(self, list_s):
  874. return self.newlist([self.newbytes(s) for s in list_s])
  875. def newlist_unicode(self, list_u):
  876. return self.newlist([self.wrap(u) for u in list_u])
  877. def newlist_int(self, list_i):
  878. return self.newlist([self.wrap(i) for i in list_i])
  879. def newlist_float(self, list_f):
  880. return self.newlist([self.wrap(f) for f in list_f])
  881. def newlist_hint(self, sizehint):
  882. from pypy.objspace.std.listobject import make_empty_list_with_size
  883. return make_empty_list_with_size(self, sizehint)
  884. @jit.unroll_safe
  885. def exception_match(self, w_exc_type, w_check_class):
  886. """Checks if the given exception type matches 'w_check_class'."""
  887. if self.is_w(w_exc_type, w_check_class):
  888. return True # fast path (also here to handle string exceptions)
  889. try:
  890. if self.isinstance_w(w_check_class, self.w_tuple):
  891. for w_t in self.fixedview(w_check_class):
  892. if self.exception_match(w_exc_type, w_t):
  893. return True
  894. else:
  895. return False
  896. return self.exception_issubclass_w(w_exc_type, w_check_class)
  897. except OperationError as e:
  898. if e.match(self, self.w_TypeError): # string exceptions maybe
  899. return False
  900. raise
  901. def call_obj_args(self, w_callable, w_obj, args):
  902. if not self.config.objspace.disable_call_speedhacks:
  903. # start of hack for performance
  904. from pypy.interpreter.function import Function
  905. if isinstance(w_callable, Function):
  906. return w_callable.call_obj_args(w_obj, args)
  907. # end of hack for performance
  908. return self.call_args(w_callable, args.prepend(w_obj))
  909. def call(self, w_callable, w_args, w_kwds=None):
  910. args = Arguments.frompacked(self, w_args, w_kwds)
  911. return self.call_args(w_callable, args)
  912. def _try_fetch_pycode(self, w_func):
  913. from pypy.interpreter.function import Function, Method
  914. if isinstance(w_func, Method):
  915. w_func = w_func.w_function
  916. if isinstance(w_func, Function):
  917. return w_func.code
  918. return None
  919. def call_function(self, w_func, *args_w):
  920. nargs = len(args_w) # used for pruning funccall versions
  921. if not self.config.objspace.disable_call_speedhacks and nargs < 5:
  922. # start of hack for performance
  923. from pypy.interpreter.function import Function, Method
  924. if isinstance(w_func, Method):
  925. w_inst = w_func.w_instance
  926. if w_inst is not None:
  927. if nargs < 4:
  928. func = w_func.w_function
  929. if isinstance(func, Function):
  930. return func.funccall(w_inst, *args_w)
  931. elif args_w and (
  932. self.abstract_isinstance_w(args_w[0], w_func.w_class)):
  933. w_func = w_func.w_function
  934. if isinstance(w_func, Function):
  935. return w_func.funccall(*args_w)
  936. # end of hack for performance
  937. args = Arguments(self, list(args_w))
  938. return self.call_args(w_func, args)
  939. def call_valuestack(self, w_func, nargs, frame):
  940. from pypy.interpreter.function import Function, Method, is_builtin_code
  941. if frame.get_is_being_profiled() and is_builtin_code(w_func):
  942. # XXX: this code is copied&pasted :-( from the slow path below
  943. # call_valuestack().
  944. args = frame.make_arguments(nargs)
  945. return self.call_args_and_c_profile(frame, w_func, args)
  946. if not self.config.objspace.disable_call_speedhacks:
  947. # start of hack for performance
  948. if isinstance(w_func, Method):
  949. w_inst = w_func.w_instance
  950. if w_inst is not None:
  951. w_func = w_func.w_function
  952. # reuse callable stack place for w_inst
  953. frame.settopvalue(w_inst, nargs)
  954. nargs += 1
  955. elif nargs > 0 and (
  956. self.abstract_isinstance_w(frame.peekvalue(nargs-1), # :-(
  957. w_func.w_class)):
  958. w_func = w_func.w_function
  959. if isinstance(w_func, Function):
  960. return w_func.funccall_valuestack(nargs, frame)
  961. # end of hack for performance
  962. args = frame.make_arguments(nargs)
  963. return self.call_args(w_func, args)
  964. def call_args_and_c_profile(self, frame, w_func, args):
  965. ec = self.getexecutioncontext()
  966. ec.c_call_trace(frame, w_func, args)
  967. try:
  968. w_res = self.call_args(w_func, args)
  969. except OperationError:
  970. ec.c_exception_trace(frame, w_func)
  971. raise
  972. ec.c_return_trace(frame, w_func, args)
  973. return w_res
  974. def call_method(self, w_obj, methname, *arg_w):
  975. w_meth = self.getattr(w_obj, self.wrap(methname))
  976. return self.call_function(w_meth, *arg_w)
  977. def raise_key_error(self, w_key):
  978. e = self.call_function(self.w_KeyError, w_key)
  979. raise OperationError(self.w_KeyError, e)
  980. def lookup(self, w_obj, name):
  981. w_type = self.type(w_obj)
  982. w_mro = self.getattr(w_type, self.wrap("__mro__"))
  983. for w_supertype in self.fixedview(w_mro):
  984. w_value = w_supertype.getdictvalue(self, name)
  985. if w_value is not None:
  986. return w_value
  987. return None
  988. def is_oldstyle_instance(self, w_obj):
  989. # xxx hack hack hack
  990. from pypy.module.__builtin__.interp_classobj import W_InstanceObject
  991. return isinstance(w_obj, W_InstanceObject)
  992. def callable(self, w_obj):
  993. if self.lookup(w_obj, "__call__") is not None:
  994. if self.is_oldstyle_instance(w_obj):
  995. # ugly old style class special treatment, but well ...
  996. try:
  997. self.getattr(w_obj, self.wrap("__call__"))
  998. return self.w_True
  999. except OperationError as e:
  1000. if not e.match(self, self.w_AttributeError):
  1001. raise
  1002. return self.w_False
  1003. else:
  1004. return self.w_True
  1005. return self.w_False
  1006. def issequence_w(self, w_obj):
  1007. if self.is_oldstyle_instance(w_obj):
  1008. return (self.findattr(w_obj, self.wrap('__getitem__')) is not None)
  1009. flag = self.type(w_obj).flag_map_or_seq
  1010. if flag == 'M':
  1011. return False
  1012. elif flag == 'S':
  1013. return True
  1014. else:
  1015. return (self.lookup(w_obj, '__getitem__') is not None)
  1016. def ismapping_w(self, w_obj):
  1017. if self.is_oldstyle_instance(w_obj):
  1018. return (self.findattr(w_obj, self.wrap('__getitem__')) is not None)
  1019. flag = self.type(w_obj).flag_map_or_seq
  1020. if flag == 'M':
  1021. return True
  1022. elif flag == 'S':
  1023. return False
  1024. else:
  1025. return (self.lookup(w_obj, '__getitem__') is not None and
  1026. self.lookup(w_obj, '__getslice__') is None)
  1027. # The code below only works
  1028. # for the simple case (new-style instance).
  1029. # These methods are patched with the full logic by the __builtin__
  1030. # module when it is loaded
  1031. def abstract_issubclass_w(self, w_cls1, w_cls2):
  1032. # Equivalent to 'issubclass(cls1, cls2)'.
  1033. return self.issubtype_w(w_cls1, w_cls2)
  1034. def abstract_isinstance_w(self, w_obj, w_cls):
  1035. # Equivalent to 'isinstance(obj, cls)'.
  1036. return self.isinstance_w(w_obj, w_cls)
  1037. def abstract_isclass_w(self, w_obj):
  1038. # Equivalent to 'isinstance(obj, type)'.
  1039. return self.isinstance_w(w_obj, self.w_type)
  1040. def abstract_getclass(self, w_obj):
  1041. # Equivalent to 'obj.__class__'.
  1042. return self.type(w_obj)
  1043. # CPython rules allows old style classes or subclasses
  1044. # of BaseExceptions to be exceptions.
  1045. # This is slightly less general than the case above, so we prefix
  1046. # it with exception_
  1047. def exception_is_valid_obj_as_class_w(self, w_obj):
  1048. if not self.isinstance_w(w_obj, self.w_type):
  1049. return False
  1050. return self.issubtype_w(w_obj, self.w_BaseException)
  1051. def exception_is_valid_class_w(self, w_cls):
  1052. return self.issubtype_w(w_cls, self.w_BaseException)
  1053. def exception_getclass(self, w_obj):
  1054. return self.type(w_obj)
  1055. def exception_issubclass_w(self, w_cls1, w_cls2):
  1056. return self.issubtype_w(w_cls1, w_cls2)
  1057. def new_exception_class(self, *args, **kwargs):
  1058. "NOT_RPYTHON; convenience method to create excceptions in modules"
  1059. return new_exception_class(self, *args, **kwargs)
  1060. # end of special support code
  1061. def eval(self, expression, w_globals, w_locals, hidden_applevel=False):
  1062. "NOT_RPYTHON: For internal debugging."
  1063. if isinstance(expression, str):
  1064. compiler = self.createcompiler()
  1065. expression = compiler.compile(expression, '?', 'eval', 0,
  1066. hidden_applevel=hidden_applevel)
  1067. else:
  1068. raise TypeError('space.eval(): expected a string, code or PyCode object')
  1069. return expression.exec_code(self, w_globals, w_locals)
  1070. def exec_(self, statement, w_globals, w_locals, hidden_applevel=False,
  1071. filename=None):
  1072. "NOT_RPYTHON: For internal debugging."
  1073. if filename is None:
  1074. filename = '?'
  1075. from pypy.interpreter.pycode import PyCode
  1076. if isinstance(statement, str):
  1077. compiler = self.createcompiler()
  1078. statement = compiler.compile(statement, filename, 'exec', 0,
  1079. hidden_applevel=hidden_applevel)
  1080. if not isinstance(statement, PyCode):
  1081. raise TypeError('space.exec_(): expected a string, code or PyCode object')
  1082. w_key = self.wrap('__builtins__')
  1083. if not self.contains_w(w_globals, w_key):
  1084. self.setitem(w_globals, w_key, self.wrap(self.builtin))
  1085. return statement.exec_code(self, w_globals, w_locals)
  1086. def appexec(self, posargs_w, source):
  1087. """ return value from executing given source at applevel.
  1088. EXPERIMENTAL. The source must look like
  1089. '''(x, y):
  1090. do_stuff...
  1091. return result
  1092. '''
  1093. """
  1094. w_func = self.fromcache(AppExecCache).getorbuild(source)
  1095. args = Arguments(self, list(posargs_w))
  1096. return self.call_args(w_func, args)
  1097. appexec._annspecialcase_ = 'specialize:arg(2)'
  1098. def _next_or_none(self, w_it):
  1099. try:
  1100. return self.next(w_it)
  1101. except OperationError as e:
  1102. if not e.match(self, self.w_StopIteration):
  1103. raise
  1104. return None
  1105. def compare_by_iteration(self, w_iterable1, w_iterable2, op):
  1106. w_it1 = self.iter(w_iterable1)
  1107. w_it2 = self.iter(w_iterable2)
  1108. while True:
  1109. w_x1 = self._next_or_none(w_it1)
  1110. w_x2 = self._next_or_none(w_it2)
  1111. if w_x1 is None or w_x2 is None:
  1112. if op == 'eq': return self.newbool(w_x1 is w_x2) # both None
  1113. if op == 'ne': return self.newbool(w_x1 is not w_x2)
  1114. if op == 'lt': return self.newbool(w_x2 is not None)
  1115. if op == 'le': return self.newbool(w_x1 is None)
  1116. if op == 'gt': return self.newbool(w_x1 is not None)
  1117. if op == 'ge': return self.newbool(w_x2 is None)
  1118. assert False, "bad value for op"
  1119. if not self.eq_w(w_x1, w_x2):
  1120. if op == 'eq': return self.w_False
  1121. if op == 'ne': return self.w_True
  1122. if op == 'lt':

Large files files are truncated, but you can click here to view the full file