PageRenderTime 34ms CodeModel.GetById 21ms 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
  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': return self.lt(w_x1, w_x2)
  1123. if op == 'le': return self.le(w_x1, w_x2)
  1124. if op == 'gt': return self.gt(w_x1, w_x2)
  1125. if op == 'ge': return self.ge(w_x1, w_x2)
  1126. assert False, "bad value for op"
  1127. compare_by_iteration._annspecialcase_ = 'specialize:arg(3)'
  1128. def decode_index(self, w_index_or_slice, seqlength):
  1129. """Helper for custom sequence implementations
  1130. -> (index, 0, 0) or
  1131. (start, stop, step)
  1132. """
  1133. if self.isinstance_w(w_index_or_slice, self.w_slice):
  1134. from pypy.objspace.std.sliceobject import W_SliceObject
  1135. assert isinstance(w_index_or_slice, W_SliceObject)
  1136. start, stop, step = w_index_or_slice.indices3(self, seqlength)
  1137. else:
  1138. start = self.int_w(w_index_or_slice, allow_conversion=False)
  1139. if start < 0:
  1140. start += seqlength
  1141. if not (0 <= start < seqlength):
  1142. raise oefmt(self.w_IndexError, "index out of range")
  1143. stop = 0
  1144. step = 0
  1145. return start, stop, step
  1146. def decode_index4(self, w_index_or_slice, seqlength):
  1147. """Helper for custom sequence implementations
  1148. -> (index, 0, 0, 1) or
  1149. (start, stop, step, slice_length)
  1150. """
  1151. if self.isinstance_w(w_index_or_slice, self.w_slice):
  1152. from pypy.objspace.std.sliceobject import W_SliceObject
  1153. assert isinstance(w_index_or_slice, W_SliceObject)
  1154. start, stop, step, length = w_index_or_slice.indices4(self,
  1155. seqlength)
  1156. else:
  1157. start = self.int_w(w_index_or_slice, allow_conversion=False)
  1158. if start < 0:
  1159. start += seqlength
  1160. if not (0 <= start < seqlength):
  1161. raise oefmt(self.w_IndexError, "index out of range")
  1162. stop = 0
  1163. step = 0
  1164. length = 1
  1165. return start, stop, step, length
  1166. def getindex_w(self, w_obj, w_exception, objdescr=None):
  1167. """Return w_obj.__index__() as an RPython int.
  1168. If w_exception is None, silently clamp in case of overflow;
  1169. else raise w_exception.
  1170. """
  1171. try:
  1172. w_index = self.index(w_obj)
  1173. except OperationError as err:
  1174. if objdescr is None or not err.match(self, self.w_TypeError):
  1175. raise
  1176. raise oefmt(self.w_TypeError, "%s must be an integer, not %T",
  1177. objdescr, w_obj)
  1178. try:
  1179. # allow_conversion=False it's not really necessary because the
  1180. # return type of __index__ is already checked by space.index(),
  1181. # but there is no reason to allow conversions anyway
  1182. index = self.int_w(w_index, allow_conversion=False)
  1183. except OperationError as err:
  1184. if not err.match(self, self.w_OverflowError):
  1185. raise
  1186. if not w_exception:
  1187. # w_index should be a long object, but can't be sure of that
  1188. if self.is_true(self.lt(w_index, self.wrap(0))):
  1189. return -sys.maxint-1
  1190. else:
  1191. return sys.maxint
  1192. else:
  1193. raise oefmt(w_exception,
  1194. "cannot fit '%T' into an index-sized integer",
  1195. w_obj)
  1196. else:
  1197. return index
  1198. def r_longlong_w(self, w_obj, allow_conversion=True):
  1199. bigint = self.bigint_w(w_obj, allow_conversion)
  1200. try:
  1201. return bigint.tolonglong()
  1202. except OverflowError:
  1203. raise oefmt(self.w_OverflowError, "integer too large")
  1204. def r_ulonglong_w(self, w_obj, allow_conversion=True):
  1205. bigint = self.bigint_w(w_obj, allow_conversion)
  1206. try:
  1207. return bigint.toulonglong()
  1208. except OverflowError:
  1209. raise oefmt(self.w_OverflowError, "integer too large")
  1210. except ValueError:
  1211. raise oefmt(self.w_ValueError,
  1212. "cannot convert negative integer to unsigned int")
  1213. BUF_SIMPLE = 0x0000
  1214. BUF_WRITABLE = 0x0001
  1215. BUF_FORMAT = 0x0004
  1216. BUF_ND = 0x0008
  1217. BUF_STRIDES = 0x0010 | BUF_ND
  1218. BUF_INDIRECT = 0x0100 | BUF_STRIDES
  1219. BUF_CONTIG_RO = BUF_ND
  1220. BUF_CONTIG = BUF_ND | BUF_WRITABLE
  1221. BUF_FULL_RO = BUF_INDIRECT | BUF_FORMAT
  1222. BUF_FULL = BUF_INDIRECT | BUF_FORMAT | BUF_WRITABLE
  1223. def check_buf_flags(self, flags, readonly):
  1224. if readonly and flags & self.BUF_WRITABLE == self.BUF_WRITABLE:
  1225. raise oefmt(self.w_BufferError, "Object is not writable.")
  1226. def buffer_w(self, w_obj, flags):
  1227. # New buffer interface, returns a buffer based on flags (PyObject_GetBuffer)
  1228. try:
  1229. return w_obj.buffer_w(self, flags)
  1230. except BufferInterfaceNotFound:
  1231. raise oefmt(self.w_TypeError,
  1232. "'%T' does not have the buffer interface", w_obj)
  1233. def readbuf_w(self, w_obj):
  1234. # Old buffer interface, returns a readonly buffer (PyObject_AsReadBuffer)
  1235. try:
  1236. return w_obj.readbuf_w(self)
  1237. except BufferInterfaceNotFound:
  1238. raise oefmt(self.w_TypeError,
  1239. "expected a readable buffer object")
  1240. def writebuf_w(self, w_obj):
  1241. # Old buffer interface, returns a writeable buffer (PyObject_AsWriteBuffer)
  1242. try:
  1243. return w_obj.writebuf_w(self)
  1244. except BufferInterfaceNotFound:
  1245. raise oefmt(self.w_TypeError,
  1246. "expected a writeable buffer object")
  1247. def charbuf_w(self, w_obj):
  1248. # Old buffer interface, returns a character buffer (PyObject_AsCharBuffer)
  1249. try:
  1250. return w_obj.charbuf_w(self)
  1251. except BufferInterfaceNotFound:
  1252. raise oefmt(self.w_TypeError,
  1253. "expected a character buffer object")
  1254. def _getarg_error(self, expected, w_obj):
  1255. if self.is_none(w_obj):
  1256. e = oefmt(self.w_TypeError, "must be %s, not None", expected)
  1257. else:
  1258. e = oefmt(self.w_TypeError, "must be %s, not %T", expected, w_obj)
  1259. raise e
  1260. @specialize.arg(1)
  1261. def getarg_w(self, code, w_obj):
  1262. if code == 'z*':
  1263. if self.is_none(w_obj):
  1264. return None
  1265. code = 's*'
  1266. if code == 's*':
  1267. if self.isinstance_w(w_obj, self.w_str):
  1268. return w_obj.readbuf_w(self)
  1269. if self.isinstance_w(w_obj, self.w_unicode):
  1270. return self.str(w_obj).readbuf_w(self)
  1271. try:
  1272. return w_obj.buffer_w(self, 0)
  1273. except BufferInterfaceNotFound:
  1274. pass
  1275. try:
  1276. return w_obj.readbuf_w(self)
  1277. except BufferInterfaceNotFound:
  1278. self._getarg_error("string or buffer", w_obj)
  1279. elif code == 's#':
  1280. if self.isinstance_w(w_obj, self.w_str):
  1281. return w_obj.str_w(self)
  1282. if self.isinstance_w(w_obj, self.w_unicode):
  1283. return self.str(w_obj).str_w(self)
  1284. try:
  1285. return w_obj.readbuf_w(self).as_str()
  1286. except BufferInterfaceNotFound:
  1287. self._getarg_error("string or read-only buffer", w_obj)
  1288. elif code == 'w*':
  1289. try:
  1290. return w_obj.buffer_w(self, self.BUF_WRITABLE)
  1291. except OperationError:
  1292. self._getarg_error("read-write buffer", w_obj)
  1293. except BufferInterfaceNotFound:
  1294. pass
  1295. try:
  1296. return w_obj.writebuf_w(self)
  1297. except BufferInterfaceNotFound:
  1298. self._getarg_error("read-write buffer", w_obj)
  1299. elif code == 't#':
  1300. try:
  1301. return w_obj.charbuf_w(self)
  1302. except BufferInterfaceNotFound:
  1303. self._getarg_error("string or read-only character buffer", w_obj)
  1304. else:
  1305. assert False
  1306. # XXX rename/replace with code more like CPython getargs for buffers
  1307. def bufferstr_w(self, w_obj):
  1308. # Directly returns an interp-level str. Note that if w_obj is a
  1309. # unicode string, this is different from str_w(buffer(w_obj)):
  1310. # indeed, the latter returns a string with the raw bytes from
  1311. # the underlying unicode buffer, but bufferstr_w() just converts
  1312. # the unicode to an ascii string. This inconsistency is kind of
  1313. # needed because CPython has the same issue. (Well, it's
  1314. # unclear if there is any use at all for getting the bytes in
  1315. # the unicode buffer.)
  1316. try:
  1317. return self.bytes_w(w_obj)
  1318. except OperationError as e:
  1319. if not e.match(self, self.w_TypeError):
  1320. raise
  1321. try:
  1322. buf = w_obj.buffer_w(self, 0)
  1323. except BufferInterfaceNotFound:
  1324. pass
  1325. else:
  1326. return buf.as_str()
  1327. try:
  1328. buf = w_obj.readbuf_w(self)
  1329. except BufferInterfaceNotFound:
  1330. self._getarg_error("string or buffer", w_obj)
  1331. else:
  1332. return buf.as_str()
  1333. def str_or_None_w(self, w_obj):
  1334. return None if self.is_none(w_obj) else self.str_w(w_obj)
  1335. def str_w(self, w_obj):
  1336. return w_obj.str_w(self)
  1337. bytes_w = str_w # Python2
  1338. def str0_w(self, w_obj):
  1339. "Like str_w, but rejects strings with NUL bytes."
  1340. from rpython.rlib import rstring
  1341. result = w_obj.str_w(self)
  1342. if '\x00' in result:
  1343. raise oefmt(self.w_TypeError,
  1344. "argument must be a string without NUL characters")
  1345. return rstring.assert_str0(result)
  1346. def int_w(self, w_obj, allow_conversion=True):
  1347. """
  1348. Unwrap an app-level int object into an interpret-level int.
  1349. If allow_conversion==True, w_obj might be of any type which implements
  1350. __int__, *except* floats which are explicitly rejected. This is the
  1351. same logic as CPython's PyArg_ParseTuple. If you want to also allow
  1352. floats, you can call space.int_w(space.int(w_obj)).
  1353. If allow_conversion=False, w_obj needs to be an app-level int or a
  1354. subclass.
  1355. """
  1356. return w_obj.int_w(self, allow_conversion)
  1357. def int(self, w_obj):
  1358. return w_obj.int(self)
  1359. def uint_w(self, w_obj):
  1360. return w_obj.uint_w(self)
  1361. def bigint_w(self, w_obj, allow_conversion=True):
  1362. """
  1363. Like int_w, but return a rlib.rbigint object and call __long__ if
  1364. allow_conversion is True.
  1365. """
  1366. return w_obj.bigint_w(self, allow_conversion)
  1367. def float_w(self, w_obj, allow_conversion=True):
  1368. """
  1369. Like int_w, but return an interp-level float and call __float__ if
  1370. allow_conversion is True.
  1371. """
  1372. return w_obj.float_w(self, allow_conversion)
  1373. def realstr_w(self, w_obj):
  1374. # Like str_w, but only works if w_obj is really of type 'str'.
  1375. if not self.isinstance_w(w_obj, self.w_str):
  1376. raise oefmt(self.w_TypeError, "argument must be a string")
  1377. return self.str_w(w_obj)
  1378. def unicode_w(self, w_obj):
  1379. return w_obj.unicode_w(self)
  1380. def unicode0_w(self, w_obj):
  1381. "Like unicode_w, but rejects strings with NUL bytes."
  1382. from rpython.rlib import rstring
  1383. result = w_obj.unicode_w(self)
  1384. if u'\x00' in result:
  1385. raise oefmt(self.w_TypeError,
  1386. "argument must be a unicode string without NUL "
  1387. "characters")
  1388. return rstring.assert_str0(result)
  1389. def realunicode_w(self, w_obj):
  1390. # Like unicode_w, but only works if w_obj is really of type
  1391. # 'unicode'.
  1392. if not self.isinstance_w(w_obj, self.w_unicode):
  1393. raise oefmt(self.w_TypeError, "argument must be a unicode")
  1394. return self.unicode_w(w_obj)
  1395. def bool_w(self, w_obj):
  1396. # Unwraps a bool, also accepting an int for compatibility.
  1397. # This is here mostly just for gateway.int_unwrapping_space_method().
  1398. return bool(self.int_w(w_obj))
  1399. def ord(self, w_obj):
  1400. return w_obj.ord(self)
  1401. # This is all interface for gateway.py.
  1402. gateway_int_w = int_w
  1403. gateway_float_w = float_w
  1404. gateway_r_longlong_w = r_longlong_w
  1405. gateway_r_ulonglong_w = r_ulonglong_w
  1406. def gateway_r_uint_w(self, w_obj):
  1407. if self.isinstance_w(w_obj, self.w_float):
  1408. raise oefmt(self.w_TypeError,
  1409. "integer argument expected, got float")
  1410. return self.uint_w(self.int(w_obj))
  1411. def gateway_nonnegint_w(self, w_obj):
  1412. # Like space.gateway_int_w(), but raises an app-level ValueError if
  1413. # the integer is negative. Here for gateway.py.
  1414. value = self.gateway_int_w(w_obj)
  1415. if value < 0:
  1416. raise oefmt(self.w_ValueError, "expected a non-negative integer")
  1417. return value
  1418. def c_int_w(self, w_obj):
  1419. # Like space.gateway_int_w(), but raises an app-level OverflowError if
  1420. # the integer does not fit in 32 bits. Here for gateway.py.
  1421. value = self.gateway_int_w(w_obj)
  1422. if value < INT_MIN or value > INT_MAX:
  1423. raise oefmt(self.w_OverflowError, "expected a 32-bit integer")
  1424. return value
  1425. def c_uint_w(self, w_obj):
  1426. # Like space.gateway_uint_w(), but raises an app-level OverflowError if
  1427. # the integer does not fit in 32 bits. Here for gateway.py.
  1428. value = self.uint_w(w_obj)
  1429. if value > UINT_MAX:
  1430. raise oefmt(self.w_OverflowError,
  1431. "expected an unsigned 32-bit integer")
  1432. return value
  1433. def c_nonnegint_w(self, w_obj):
  1434. # Like space.gateway_int_w(), but raises an app-level ValueError if
  1435. # the integer is negative or does not fit in 32 bits. Here
  1436. # for gateway.py.
  1437. value = self.int_w(w_obj)
  1438. if value < 0:
  1439. raise oefmt(self.w_ValueError, "expected a non-negative integer")
  1440. if value > INT_MAX:
  1441. raise oefmt(self.w_OverflowError, "expected a 32-bit integer")
  1442. return value
  1443. def c_short_w(self, w_obj):
  1444. value = self.int_w(w_obj)
  1445. if value < SHRT_MIN:
  1446. raise oefmt(self.w_OverflowError,
  1447. "signed short integer is less than minimum")
  1448. elif value > SHRT_MAX:
  1449. raise oefmt(self.w_OverflowError,
  1450. "signed short integer is greater than maximum")
  1451. return value
  1452. def c_ushort_w(self, w_obj):
  1453. value = self.int_w(w_obj)
  1454. if value < 0:
  1455. raise oefmt(self.w_OverflowError,
  1456. "can't convert negative value to C unsigned short")
  1457. elif value > USHRT_MAX:
  1458. raise oefmt(self.w_OverflowError,
  1459. "Python int too large for C unsigned short")
  1460. return value
  1461. def c_uid_t_w(self, w_obj):
  1462. # xxx assumes that uid_t and gid_t are a C unsigned int.
  1463. # Equivalent to space.c_uint_w(), with the exception that
  1464. # it also accepts -1 and converts that to UINT_MAX, which
  1465. # is (uid_t)-1. And values smaller than -1 raise
  1466. # OverflowError, not ValueError.
  1467. try:
  1468. return self.c_uint_w(w_obj)
  1469. except OperationError as e:
  1470. if e.match(self, self.w_ValueError):
  1471. # ValueError: cannot convert negative integer to unsigned
  1472. if self.int_w(w_obj) == -1:
  1473. return UINT_MAX
  1474. raise oefmt(self.w_OverflowError,
  1475. "user/group id smaller than minimum (-1)")
  1476. raise
  1477. def truncatedint_w(self, w_obj, allow_conversion=True):
  1478. # Like space.gateway_int_w(), but return the integer truncated
  1479. # instead of raising OverflowError. For obscure cases only.
  1480. try:
  1481. return self.int_w(w_obj, allow_conversion)
  1482. except OperationError as e:
  1483. if not e.match(self, self.w_OverflowError):
  1484. raise
  1485. from rpython.rlib.rarithmetic import intmask
  1486. return intmask(self.bigint_w(w_obj).uintmask())
  1487. def truncatedlonglong_w(self, w_obj, allow_conversion=True):
  1488. # Like space.gateway_r_longlong_w(), but return the integer truncated
  1489. # instead of raising OverflowError.
  1490. try:
  1491. return self.r_longlong_w(w_obj, allow_conversion)
  1492. except OperationError as e:
  1493. if not e.match(self, self.w_OverflowError):
  1494. raise
  1495. from rpython.rlib.rarithmetic import longlongmask
  1496. return longlongmask(self.bigint_w(w_obj).ulonglongmask())
  1497. def c_filedescriptor_w(self, w_fd):
  1498. # This is only used sometimes in CPython, e.g. for os.fsync() but
  1499. # not os.close(). It's likely designed for 'select'. It's irregular
  1500. # in the sense that it expects either a real int/long or an object
  1501. # with a fileno(), but not an object with an __int__().
  1502. if (not self.isinstance_w(w_fd, self.w_int) and
  1503. not self.isinstance_w(w_fd, self.w_long)):
  1504. try:
  1505. w_fileno = self.getattr(w_fd, self.wrap("fileno"))
  1506. except OperationError as e:
  1507. if e.match(self, self.w_AttributeError):
  1508. raise oefmt(self.w_TypeError,
  1509. "argument must be an int, or have a fileno() "
  1510. "method.")
  1511. raise
  1512. w_fd = self.call_function(w_fileno)
  1513. if (not self.isinstance_w(w_fd, self.w_int) and
  1514. not self.isinstance_w(w_fd, self.w_long)):
  1515. raise oefmt(self.w_TypeError,
  1516. "fileno() returned a non-integer")
  1517. try:
  1518. fd = self.c_int_w(w_fd)
  1519. except OperationError as e:
  1520. if e.match(self, self.w_OverflowError):
  1521. fd = -1
  1522. else:
  1523. raise
  1524. if fd < 0:
  1525. raise oefmt(self.w_ValueError,
  1526. "file descriptor cannot be a negative integer (%d)", fd)
  1527. return fd
  1528. def warn(self, w_msg, w_warningcls, stacklevel=2):
  1529. self.appexec([w_msg, w_warningcls, self.wrap(stacklevel)],
  1530. """(msg, warningcls, stacklevel):
  1531. import _warnings
  1532. _warnings.warn(msg, warningcls, stacklevel=stacklevel)
  1533. """)
  1534. def resource_warning(self, w_msg, w_tb):
  1535. self.appexec([w_msg, w_tb],
  1536. """(msg, tb):
  1537. import sys
  1538. print >> sys.stderr, msg
  1539. if tb:
  1540. print >> sys.stderr, "Created at (most recent call last):"
  1541. print >> sys.stderr, tb
  1542. """)
  1543. def format_traceback(self):
  1544. # we need to disable track_resources before calling the traceback
  1545. # module. Else, it tries to open more files to format the traceback,
  1546. # the file constructor will call space.format_traceback etc., in an
  1547. # inifite recursion
  1548. flag = self.sys.track_resources
  1549. self.sys.track_resources = False
  1550. try:
  1551. return self.appexec([],
  1552. """():
  1553. import sys, traceback
  1554. # the "1" is because we don't want to show THIS code
  1555. # object in the traceback
  1556. try:
  1557. f = sys._getframe(1)
  1558. except ValueError:
  1559. # this happens if you call format_traceback at the very beginning
  1560. # of startup, when there is no bottom code object
  1561. return '<no stacktrace available>'
  1562. return "".join(traceback.format_stack(f))
  1563. """)
  1564. finally:
  1565. self.sys.track_resources = flag
  1566. class AppExecCache(SpaceCache):
  1567. def build(cache, source):
  1568. """ NOT_RPYTHON """
  1569. space = cache.space
  1570. # XXX will change once we have our own compiler
  1571. import py
  1572. source = source.lstrip()
  1573. assert source.startswith('('), "incorrect header in:\n%s" % (source,)
  1574. source = py.code.Source("def anonymous%s\n" % source)
  1575. w_glob = space.newdict(module=True)
  1576. space.exec_(str(source), w_glob, w_glob)
  1577. return space.getitem(w_glob, space.wrap('anonymous'))
  1578. # Table describing the regular part of the interface of object spaces,
  1579. # namely all methods which only take w_ arguments and return a w_ result
  1580. # (if any).
  1581. ObjSpace.MethodTable = [
  1582. # method name # symbol # number of arguments # special method name(s)
  1583. ('is_', 'is', 2, []),
  1584. ('id', 'id', 1, []),
  1585. ('type', 'type', 1, []),
  1586. ('isinstance', 'isinstance', 2, ['__instancecheck__']),
  1587. ('issubtype', 'issubtype', 2, ['__subclasscheck__']), # not for old-style classes
  1588. ('repr', 'repr', 1, ['__repr__']),
  1589. ('str', 'str', 1, ['__str__']),
  1590. ('format', 'format', 2, ['__format__']),
  1591. ('len', 'len', 1, ['__len__']),
  1592. ('hash', 'hash', 1, ['__hash__']),
  1593. ('getattr', 'getattr', 2, ['__getattribute__']),
  1594. ('setattr', 'setattr', 3, ['__setattr__']),
  1595. ('delattr', 'delattr', 2, ['__delattr__']),
  1596. ('getitem', 'getitem', 2, ['__getitem__']),
  1597. ('setitem', 'setitem', 3, ['__setitem__']),
  1598. ('delitem', 'delitem', 2, ['__delitem__']),
  1599. ('getslice', 'getslice', 3, ['__getslice__']),
  1600. ('setslice', 'setslice', 4, ['__setslice__']),
  1601. ('delslice', 'delslice', 3, ['__delslice__']),
  1602. ('trunc', 'trunc', 1, ['__trunc__']),
  1603. ('pos', 'pos', 1, ['__pos__']),
  1604. ('neg', 'neg', 1, ['__neg__']),
  1605. ('nonzero', 'truth', 1, ['__nonzero__']),
  1606. ('abs', 'abs', 1, ['__abs__']),
  1607. ('hex', 'hex', 1, ['__hex__']),
  1608. ('oct', 'oct', 1, ['__oct__']),
  1609. ('ord', 'ord', 1, []),
  1610. ('invert', '~', 1, ['__invert__']),
  1611. ('add', '+', 2, ['__add__', '__radd__']),
  1612. ('sub', '-', 2, ['__sub__', '__rsub__']),
  1613. ('mul', '*', 2, ['__mul__', '__rmul__']),
  1614. ('truediv', '/', 2, ['__truediv__', '__rtruediv__']),
  1615. ('floordiv', '//', 2, ['__floordiv__', '__rfloordiv__']),
  1616. ('div', 'div', 2, ['__div__', '__rdiv__']),
  1617. ('mod', '%', 2, ['__mod__', '__rmod__']),
  1618. ('divmod', 'divmod', 2, ['__divmod__', '__rdivmod__']),
  1619. ('pow', '**', 3, ['__pow__', '__rpow__']),
  1620. ('lshift', '<<', 2, ['__lshift__', '__rlshift__']),
  1621. ('rshift', '>>', 2, ['__rshift__', '__rrshift__']),
  1622. ('and_', '&', 2, ['__and__', '__rand__']),
  1623. ('or_', '|', 2, ['__or__', '__ror__']),
  1624. ('xor', '^', 2, ['__xor__', '__rxor__']),
  1625. ('int', 'int', 1, ['__int__']),
  1626. ('index', 'index', 1, ['__index__']),
  1627. ('float', 'float', 1, ['__float__']),
  1628. ('long', 'long', 1, ['__long__']),
  1629. ('inplace_add', '+=', 2, ['__iadd__']),
  1630. ('inplace_sub', '-=', 2, ['__isub__']),
  1631. ('inplace_mul', '*=', 2, ['__imul__']),
  1632. ('inplace_truediv', '/=', 2, ['__itruediv__']),
  1633. ('inplace_floordiv','//=', 2, ['__ifloordiv__']),
  1634. ('inplace_div', 'div=', 2, ['__idiv__']),
  1635. ('inplace_mod', '%=', 2, ['__imod__']),
  1636. ('inplace_pow', '**=', 2, ['__ipow__']),
  1637. ('inplace_lshift', '<<=', 2, ['__ilshift__']),
  1638. ('inplace_rshift', '>>=', 2, ['__irshift__']),
  1639. ('inplace_and', '&=', 2, ['__iand__']),
  1640. ('inplace_or', '|=', 2, ['__ior__']),
  1641. ('inplace_xor', '^=', 2, ['__ixor__']),
  1642. ('lt', '<', 2, ['__lt__', '__gt__']),
  1643. ('le', '<=', 2, ['__le__', '__ge__']),
  1644. ('eq', '==', 2, ['__eq__', '__eq__']),
  1645. ('ne', '!=', 2, ['__ne__', '__ne__']),
  1646. ('gt', '>', 2, ['__gt__', '__lt__']),
  1647. ('ge', '>=', 2, ['__ge__', '__le__']),
  1648. ('cmp', 'cmp', 2, ['__cmp__']), # rich cmps preferred
  1649. ('coerce', 'coerce', 2, ['__coerce__', '__coerce__']),
  1650. ('contains', 'contains', 2, ['__contains__']),
  1651. ('iter', 'iter', 1, ['__iter__']),
  1652. ('next', 'next', 1, ['next']),
  1653. # ('call', 'call', 3, ['__call__']),
  1654. ('get', 'get', 3, ['__get__']),
  1655. ('set', 'set', 3, ['__set__']),
  1656. ('delete', 'delete', 2, ['__delete__']),
  1657. ]
  1658. ObjSpace.BuiltinModuleTable = [
  1659. '__builtin__',
  1660. 'sys',
  1661. ]
  1662. ObjSpace.ConstantTable = [
  1663. 'None',
  1664. 'False',
  1665. 'True',
  1666. 'Ellipsis',
  1667. 'NotImplemented',
  1668. ]
  1669. ObjSpace.ExceptionTable = [
  1670. 'ArithmeticError',
  1671. 'AssertionError',
  1672. 'AttributeError',
  1673. 'BaseException',
  1674. 'BufferError',
  1675. 'DeprecationWarning',
  1676. 'EOFError',
  1677. 'EnvironmentError',
  1678. 'Exception',
  1679. 'FloatingPointError',
  1680. 'IOError',
  1681. 'ImportError',
  1682. 'ImportWarning',
  1683. 'IndentationError',
  1684. 'IndexError',
  1685. 'KeyError',
  1686. 'KeyboardInterrupt',
  1687. 'LookupError',
  1688. 'MemoryError',
  1689. 'NameError',
  1690. 'NotImplementedError',
  1691. 'OSError',
  1692. 'OverflowError',
  1693. 'ReferenceError',
  1694. 'RuntimeError',
  1695. 'StandardError',
  1696. 'StopIteration',
  1697. 'SyntaxError',
  1698. 'SystemError',
  1699. 'SystemExit',
  1700. 'TabError',
  1701. 'TypeError',
  1702. 'UnboundLocalError',
  1703. 'UnicodeDecodeError',
  1704. 'UnicodeError',
  1705. 'UnicodeEncodeError',
  1706. 'UnicodeTranslateError',
  1707. 'ValueError',
  1708. 'ZeroDivisionError',
  1709. 'RuntimeWarning',
  1710. 'PendingDeprecationWarning',
  1711. ]
  1712. if sys.platform.startswith("win"):
  1713. ObjSpace.ExceptionTable += ['WindowsError']
  1714. ## Irregular part of the interface:
  1715. #
  1716. # wrap(x) -> w_x
  1717. # str_w(w_str) -> str
  1718. # int_w(w_ival or w_long_ival) -> ival
  1719. # float_w(w_floatval) -> floatval
  1720. # uint_w(w_ival or w_long_ival) -> r_uint_val (unsigned int value)
  1721. # bigint_w(w_ival or w_long_ival) -> rbigint
  1722. # unwrap(w_x) -> x
  1723. # is_true(w_x) -> True or False
  1724. # newtuple([w_1, w_2,...]) -> w_tuple
  1725. # newlist([w_1, w_2,...]) -> w_list
  1726. # newdict() -> empty w_dict
  1727. # newslice(w_start,w_stop,w_step) -> w_slice
  1728. # call_args(w_obj,Arguments()) -> w_result
  1729. ObjSpace.IrregularOpTable = [
  1730. 'wrap',
  1731. 'str_w',
  1732. 'int_w',
  1733. 'float_w',
  1734. 'uint_w',
  1735. 'bigint_w',
  1736. 'unicode_w',
  1737. 'unwrap',
  1738. 'is_true',
  1739. 'is_w',
  1740. 'newtuple',
  1741. 'newlist',
  1742. 'newdict',
  1743. 'newslice',
  1744. 'call_args',
  1745. ]