PageRenderTime 30ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/interpreter/baseobjspace.py

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

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