rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
'Connection', base_typedef, __new__ = interp2app(W_FileConnection.descr_new.im_func),
'Connection', W_BaseConnection.typedef, __new__ = interp2app(W_FileConnection.descr_new_file.im_func),
W_FileConnection.typedef = TypeDef( 'Connection', base_typedef, __new__ = interp2app(W_FileConnection.descr_new.im_func), fileno = interp2app(W_FileConnection.fileno),
def descr_new(space, w_subtype, w_handle, readable=True, writable=True):
def descr_new_pipe(space, w_subtype, w_handle, readable=True, writable=True):
def descr_new(space, w_subtype, w_handle, readable=True, writable=True): from pypy.module._multiprocessing.interp_win32 import handle_w handle = handle_w(space, w_handle) flags = (readable and READABLE) | (writable and WRITABLE)
raise operrfmt(
raise operationerrfmt(
def do_send_string(self, space, buffer, offset, size): from pypy.module._multiprocessing.interp_win32 import ( _WriteFile, ERROR_NO_SYSTEM_RESOURCES) from pypy.rlib import rwin32
return read_ptr[0], None
return read_ptr[0], lltype.nullptr(rffi.CCHARP.TO)
def do_recv_string(self, space, maxlength): from pypy.module._multiprocessing.interp_win32 import ( _ReadFile) from pypy.rlib import rwin32
return MP_BAD_MESSAGE_LENGTH
return MP_BAD_MESSAGE_LENGTH, lltype.nullptr(rffi.CCHARP.TO)
def do_recv_string(self, space, maxlength): from pypy.module._multiprocessing.interp_win32 import ( _ReadFile) from pypy.rlib import rwin32
return MP_STANDARD_ERROR, None
return MP_STANDARD_ERROR, lltype.nullptr(rffi.CCHARP.TO)
def do_recv_string(self, space, maxlength): from pypy.module._multiprocessing.interp_win32 import ( _ReadFile) from pypy.rlib import rwin32
elif self.format == 'elf64':
elif self.format in ('elf64', 'darwin64'):
def _variant(**kwargs): txt = kwargs[self.format] print >> output, "\t%s" % txt
ResOperation(rop.DEBUG_MERGE_POINT, [FakeString("hello")], None),
ResOperation(rop.DEBUG_MERGE_POINT, [FakeString("hello"), 0], None),
def _get_str(self): return self.val
ResOperation(rop.DEBUG_MERGE_POINT, [FakeString("bye")], None),
ResOperation(rop.DEBUG_MERGE_POINT, [FakeString("bye"), 0], None),
def _get_str(self): return self.val
minsize = 2 * (self.nonlarge_max + 1)
minsize = int(1.9 * self.nonlarge_max) if we_are_translated(): minsize = (minsize + 4095) & ~4095
def setup(self): """Called at run-time to initialize the GC.""" # # Hack: MovingGCBase.setup() sets up stuff related to id(), which # we implement differently anyway. So directly call GCBase.setup(). GCBase.setup(self) # # A list of all raw_malloced objects (the objects too large) self.rawmalloced_objects = self.AddressStack() self.rawmalloced_total_size = r_uint(0) # # A list of all objects with finalizers (never in the nursery). self.objects_with_finalizers = self.AddressDeque() # # Two lists of the objects with weakrefs. No weakref can be an # old object weakly pointing to a young object: indeed, weakrefs # are immutable so they cannot point to an object that was # created after it. self.young_objects_with_weakrefs = self.AddressStack() self.old_objects_with_weakrefs = self.AddressStack() # # Support for id and identityhash: map nursery objects with # GCFLAG_HAS_SHADOW to their future location at the next # minor collection. self.young_objects_shadows = self.AddressDict() # # Allocate a nursery. In case of auto_nursery_size, start by # allocating a very small nursery, enough to do things like look # up the env var, which requires the GC; and then really # allocate the nursery of the final size. if not self.read_from_env: self.allocate_nursery() else: # defaultsize = self.nursery_size minsize = 2 * (self.nonlarge_max + 1) self.nursery_size = minsize self.allocate_nursery() # # From there on, the GC is fully initialized and the code # below can use it newsize = env.read_from_env('PYPY_GC_NURSERY') # PYPY_GC_NURSERY=smallvalue means that minor collects occur # very frequently; the extreme case is PYPY_GC_NURSERY=1, which # forces a minor collect for every malloc. Useful to debug # external factors, like trackgcroot or the handling of the write # barrier. Implemented by still using 'minsize' for the nursery # size (needed to handle e.g. mallocs of 8249 words) but hacking # at the current nursery position in collect_and_reserve(). if newsize <= 0: newsize = env.estimate_best_nursery_size() if newsize <= 0: newsize = defaultsize if newsize < minsize: self.debug_tiny_nursery = newsize & ~(WORD-1) newsize = minsize # major_coll = env.read_float_from_env('PYPY_GC_MAJOR_COLLECT') if major_coll > 1.0: self.major_collection_threshold = major_coll # growth = env.read_float_from_env('PYPY_GC_GROWTH') if growth > 1.0: self.growth_rate_max = growth # min_heap_size = env.read_uint_from_env('PYPY_GC_MIN') if min_heap_size > 0: self.min_heap_size = float(min_heap_size) else: # defaults to 8 times the nursery self.min_heap_size = newsize * 8 # max_heap_size = env.read_uint_from_env('PYPY_GC_MAX') if max_heap_size > 0: self.max_heap_size = float(max_heap_size) # max_delta = env.read_uint_from_env('PYPY_GC_MAX_DELTA') if max_delta > 0: self.max_delta = float(max_delta) else: self.max_delta = 0.125 * env.get_total_memory() # self.minor_collection() # to empty the nursery llarena.arena_free(self.nursery) self.nursery_size = newsize self.allocate_nursery()
FILE = rffi.VOIDP_real.TO FILEP = lltype.Ptr(FILE)
def PyFile_AsFile(space, p): """Return the file object associated with p as a FILE*. If the caller will ever use the returned FILE* object while the GIL is released it must also call the PyFile_IncUseCount() and PyFile_DecUseCount() functions described below as appropriate.""" raise NotImplementedError
def optimize_loop(self, ops, spectext, optops, checkspecnodes=True):
def optimize_loop(self, ops, spectext, optops, checkspecnodes=True, expected_preamble=None):
def optimize_loop(self, ops, spectext, optops, checkspecnodes=True): loop = self.parse(ops) # if checkspecnodes: # verify that 'spectext' is indeed what optimizefindnode would # compute for this loop cpu = self.cpu perfect_specialization_finder = PerfectSpecializationFinder(cpu) perfect_specialization_finder.find_nodes_loop(loop) self.check_specnodes(loop.token.specnodes, spectext) else: # for cases where we want to see how optimizeopt behaves with # combinations different from the one computed by optimizefindnode loop.token.specnodes = self.unpack_specnodes(spectext) # self.loop = loop loop.preamble = TreeLoop('preamble') metainterp_sd = FakeMetaInterpStaticData(self.cpu) if hasattr(self, 'vrefinfo'): metainterp_sd.virtualref_info = self.vrefinfo optimize_loop_1(metainterp_sd, loop) # expected = self.parse(optops) print print "Ops: " print '\n'.join([str(o) for o in loop.operations]) self.assert_equal(loop, expected)
[i] i0 = int_sub(i, 1) guard_value(i0, 0) [i0] jump(i) """ expected = """ [i] i0 = int_sub(i, 1) guard_value(i0, 0) [i0] jump(1) """ self.optimize_loop(ops, 'Not', expected)
[] f = escape() f0 = float_sub(f, 1.0) guard_value(f0, 0.0) [f0] escape(f) jump() """ self.optimize_loop(ops, '', ops)
def test_simple(self): ops = """ [i] i0 = int_sub(i, 1) guard_value(i0, 0) [i0] jump(i) """ expected = """ [i] i0 = int_sub(i, 1) guard_value(i0, 0) [i0] jump(1) """ self.optimize_loop(ops, 'Not', expected)
expected = """
preamble = """
def test_remove_guard_class_1(self): ops = """ [p0] guard_class(p0, ConstClass(node_vtable)) [] guard_class(p0, ConstClass(node_vtable)) [] jump(p0) """ expected = """ [p0] guard_class(p0, ConstClass(node_vtable)) [] jump(p0) """ self.optimize_loop(ops, 'Not', expected)
self.optimize_loop(ops, 'Not', expected)
expected = """ [p0] jump(p0) """ self.optimize_loop(ops, 'Not', expected, expected_preamble=preamble)
def test_remove_guard_class_1(self): ops = """ [p0] guard_class(p0, ConstClass(node_vtable)) [] guard_class(p0, ConstClass(node_vtable)) [] jump(p0) """ expected = """ [p0] guard_class(p0, ConstClass(node_vtable)) [] jump(p0) """ self.optimize_loop(ops, 'Not', expected)
[i0, i1]
[] i0 = escape() i1 = escape()
def test_bound_eq(self): ops = """ [i0, i1] i2 = int_le(i0, 4) guard_true(i2) [] i3 = int_eq(i0, i1) guard_true(i3) [] i4 = int_lt(i1, 5) guard_true(i4) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_le(i0, 4) guard_true(i2) [] i3 = int_eq(i0, i1) guard_true(i3) [] jump(i0, i1) """ self.optimize_loop(ops, 'Not, Not', expected)
jump(i0, i1) """ expected = """ [i0, i1]
jump() """ expected = """ [] i0 = escape() i1 = escape()
def test_bound_eq(self): ops = """ [i0, i1] i2 = int_le(i0, 4) guard_true(i2) [] i3 = int_eq(i0, i1) guard_true(i3) [] i4 = int_lt(i1, 5) guard_true(i4) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_le(i0, 4) guard_true(i2) [] i3 = int_eq(i0, i1) guard_true(i3) [] jump(i0, i1) """ self.optimize_loop(ops, 'Not, Not', expected)
jump(i0, i1) """ self.optimize_loop(ops, 'Not, Not', expected)
jump() """ self.optimize_loop(ops, '', expected)
def test_bound_eq(self): ops = """ [i0, i1] i2 = int_le(i0, 4) guard_true(i2) [] i3 = int_eq(i0, i1) guard_true(i3) [] i4 = int_lt(i1, 5) guard_true(i4) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_le(i0, 4) guard_true(i2) [] i3 = int_eq(i0, i1) guard_true(i3) [] jump(i0, i1) """ self.optimize_loop(ops, 'Not, Not', expected)
[i0]
[] i0 = escape()
def test_bound_eq_const(self): ops = """ [i0] i1 = int_eq(i0, 7) guard_true(i1) [] i2 = int_add(i0, 3) jump(i2) """ expected = """ [i0] i1 = int_eq(i0, 7) guard_true(i1) [] jump(10)
jump(i2) """ expected = """ [i0]
escape(i2) jump() """ expected = """ [] i0 = escape()
def test_bound_eq_const(self): ops = """ [i0] i1 = int_eq(i0, 7) guard_true(i1) [] i2 = int_add(i0, 3) jump(i2) """ expected = """ [i0] i1 = int_eq(i0, 7) guard_true(i1) [] jump(10)
jump(10) """ self.optimize_loop(ops, 'Not', expected)
escape(10) jump() """ self.optimize_loop(ops, '', expected)
def test_bound_eq_const(self): ops = """ [i0] i1 = int_eq(i0, 7) guard_true(i1) [] i2 = int_add(i0, 3) jump(i2) """ expected = """ [i0] i1 = int_eq(i0, 7) guard_true(i1) [] jump(10)
"guard_isnull",
def main(n): s = 0 for i in range(n): s += g(n)[i] return s
def LOOKUP_METHOD(self, nameindex, next_instr): space = self.space w_obj = self.popvalue() w_name = self.getname_w(nameindex) w_value = space.getattr(w_obj, w_name) self.pushvalue(w_value) def CALL_METHOD(self, nargs, next_instr): w_callable = self.peekvalue(nargs) try: w_result = self.space.call_valuestack(w_callable, nargs, self) finally: self.dropvalues(nargs + 1) self.pushvalue(w_result)
LOOKUP_METHOD = LOAD_ATTR CALL_METHOD = CALL_FUNCTION
def LOOKUP_METHOD(self, nameindex, next_instr): # overridden by faster version in the standard object space. space = self.space w_obj = self.popvalue() w_name = self.getname_w(nameindex) w_value = space.getattr(w_obj, w_name) self.pushvalue(w_value)
'pypy\\lib\\_pypy_interact.py' in r.lower()) and
r'pypy\\lib\\_pypy_interact.py' in r.lower()) and
def test_repr(self): import sys r = repr(sys) assert r == "<module 'sys' (built-in)>" import _pypy_interact # known to be in pypy/lib r = repr(_pypy_interact) assert (r.startswith("<module '_pypy_interact' from ") and ('pypy/lib/_pypy_interact.py' in r or 'pypy\\lib\\_pypy_interact.py' in r.lower()) and r.endswith('>')) nofile = type(_pypy_interact)('nofile', 'foo') assert repr(nofile) == "<module 'nofile' from ?>"
if argtype._ffishape == 'u':
if argtype._ffishape == 'u' or argtype._ffishape == 'c':
def _unwrap_args(self, argtypes, args): """ Convert from ctypes high-level values to low-level values suitables to be passed to _ffi """ assert len(argtypes) == len(args) newargs = [] # XXX: investigate the difference between _ffishape and _ffiargshape for argtype, arg in zip(argtypes, args): if argtype._ffishape == 'u': # XXX: who should do this conversion? Maybe _ffi? value = arg.value assert isinstance(value, basestring) and len(value) == 1 value = ord(value) elif argtype._ffishape == 'P': value = arg._get_buffer_value() elif argtype._ffishape == 'z': value = arg._get_buffer_value() elif self._is_struct_shape(arg._ffiargshape): value = arg._get_buffer_value() else: value = arg.value newargs.append(value) return newargs
rstack.resume_point("CALL_METHOD", f, w_self, n_args, returns=w_result)
def CALL_METHOD(f, oparg, *ignored): # opargs contains the arg, and kwarg count, excluding the implicit 'self' n_args = oparg & 0xff n_kwargs = (oparg >> 8) & 0xff w_self = f.peekvalue(n_args + (2 * n_kwargs)) w_callable = f.peekvalue(n_args + (2 * n_kwargs) + 1) n = n_args + (w_self is not None) if not n_kwargs: try: w_result = f.space.call_valuestack(w_callable, n, f) rstack.resume_point("CALL_METHOD", f, w_self, n_args, returns=w_result) finally: f.dropvalues(n_args + 2) else: keywords = [None] * n_kwargs keywords_w = [None] * n_kwargs while True: n_kwargs -= 1 if n_kwargs < 0: break w_value = f.popvalue() w_key = f.popvalue() key = f.space.str_w(w_key) keywords[n_kwargs] = key keywords_w[n_kwargs] = w_value arguments = f.popvalues(n) args = f.argument_factory(arguments, keywords, keywords_w, None, None) try: w_result = f.space.call_args(w_callable, args) rstack.resume_point("CALL_METHOD", f, w_self, n_args, returns=w_result) finally: f.dropvalues(1 + (w_self is None)) f.pushvalue(w_result)
self.cpu.assembler.setup()
self.cpu.assembler.setup_once()
def f(size): allocs.insert(0, size) buf = ctypes.create_string_buffer(size) all.append(buf) return ctypes.cast(buf, ctypes.c_void_p).value
self.check_tree_loop_count(2)
if self.optimizer == OPTIMIZER_SIMPLE: self.check_tree_loop_count(1) else: self.check_tree_loop_count(2)
def f(y): state = State() x = 0 while y > 0: myjitdriver.can_enter_jit(x=x, y=y, state=state) myjitdriver.jit_merge_point(x=x, y=y, state=state) x += state.externfn(y)() y -= 1 return x
self.cbcalled = 0 def callback(self, ref): self.cbcalled += 1 class ReferencesTestCase(TestBase): def test_basic_ref(self): self.check_basic_ref(C) self.check_basic_ref(create_function) self.check_basic_ref(create_bound_method) self.check_basic_ref(create_unbound_method) o = C() wr = weakref.ref(o) repr(wr) del o repr(wr) def test_basic_callback(self): self.check_basic_callback(C) self.check_basic_callback(create_function) self.check_basic_callback(create_bound_method) self.check_basic_callback(create_unbound_method) def test_multiple_callbacks(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del o gc_collect() self.assertTrue(ref1() is None, "expected reference to be invalidated") self.assertTrue(ref2() is None, "expected reference to be invalidated") self.assertTrue(self.cbcalled == 2, "callback not called the right number of times") def test_multiple_selfref_callbacks(self): def callback(object, self=self): self.ref() c = C() self.ref = weakref.ref(c, callback) ref1 = weakref.ref(c, callback) del c def test_proxy_ref(self): o = C() o.bar = 1 ref1 = weakref.proxy(o, self.callback) ref2 = weakref.proxy(o, self.callback) del o gc_collect() def check(proxy): proxy.bar self.assertRaises(weakref.ReferenceError, check, ref1) self.assertRaises(weakref.ReferenceError, check, ref2) ref3 = weakref.proxy(C()) gc_collect() self.assertRaises(weakref.ReferenceError, bool, ref3) self.assertTrue(self.cbcalled == 2) def check_basic_ref(self, factory): o = factory() ref = weakref.ref(o) self.assertTrue(ref() is not None, "weak reference to live object should be live") o2 = ref() self.assertTrue(o is o2, "<ref>() should return original object if live") def check_basic_callback(self, factory): self.cbcalled = 0 o = factory() ref = weakref.ref(o, self.callback) del o gc_collect() self.assertTrue(self.cbcalled == 1, "callback did not properly set 'cbcalled'") self.assertTrue(ref() is None, "ref2 should be dead after deleting object reference") def test_ref_reuse(self): o = C() ref1 = weakref.ref(o) proxy = weakref.proxy(o) ref2 = weakref.ref(o) self.assertTrue(ref1 is ref2, "reference object w/out callback should be re-used") o = C() proxy = weakref.proxy(o) ref1 = weakref.ref(o) ref2 = weakref.ref(o) self.assertTrue(ref1 is ref2, "reference object w/out callback should be re-used") self.assertTrue(weakref.getweakrefcount(o) == 2, "wrong weak ref count for object") del proxy gc_collect() self.assertTrue(weakref.getweakrefcount(o) == 1, "wrong weak ref count for object after deleting proxy") def test_proxy_reuse(self): o = C() proxy1 = weakref.proxy(o) ref = weakref.ref(o) proxy2 = weakref.proxy(o) self.assertTrue(proxy1 is proxy2, "proxy object w/out callback should have been re-used") def test_basic_proxy(self): o = C() self.check_proxy(o, weakref.proxy(o)) L = UserList.UserList() p = weakref.proxy(L) self.assertFalse(p, "proxy for empty UserList should be false") p.append(12) self.assertEqual(len(L), 1) self.assertTrue(p, "proxy for non-empty UserList should be true") with test_support.check_py3k_warnings(): p[:] = [2, 3] self.assertEqual(len(L), 2) self.assertEqual(len(p), 2) self.assertIn(3, p, "proxy didn't support __contains__() properly") p[1] = 5 self.assertEqual(L[1], 5) self.assertEqual(p[1], 5) L2 = UserList.UserList(L) p2 = weakref.proxy(L2) self.assertEqual(p, p2) L3 = UserList.UserList(range(10)) p3 = weakref.proxy(L3) with test_support.check_py3k_warnings(): self.assertEqual(L3[:], p3[:]) self.assertEqual(L3[5:], p3[5:]) self.assertEqual(L3[:5], p3[:5]) self.assertEqual(L3[2:5], p3[2:5]) def test_proxy_unicode(self): class C(object): def __str__(self): return "string" def __unicode__(self): return u"unicode" instance = C() self.assertIn("__unicode__", dir(weakref.proxy(instance))) self.assertEqual(unicode(weakref.proxy(instance)), u"unicode") def test_proxy_index(self): class C: def __index__(self): return 10 o = C() p = weakref.proxy(o) self.assertEqual(operator.index(p), 10) def test_proxy_div(self): class C: def __floordiv__(self, other): return 42 def __ifloordiv__(self, other): return 21 o = C() p = weakref.proxy(o) self.assertEqual(p // 5, 42) p //= 5 self.assertEqual(p, 21) def test_shared_ref_without_callback(self): self.check_shared_without_callback(weakref.ref) def test_shared_proxy_without_callback(self): self.check_shared_without_callback(weakref.proxy) def check_shared_without_callback(self, makeref): o = Object(1) p1 = makeref(o, None) p2 = makeref(o, None) self.assertTrue(p1 is p2, "both callbacks were None in the C API") del p1, p2 p1 = makeref(o) p2 = makeref(o, None) self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API") del p1, p2 p1 = makeref(o) p2 = makeref(o) self.assertTrue(p1 is p2, "both callbacks were NULL in the C API") del p1, p2 p1 = makeref(o, None) p2 = makeref(o) self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API") def test_callable_proxy(self): o = Callable() ref1 = weakref.proxy(o) self.check_proxy(o, ref1) self.assertTrue(type(ref1) is weakref.CallableProxyType, "proxy is not of callable type") ref1('twinkies!') self.assertTrue(o.bar == 'twinkies!', "call through proxy not passed through to original") ref1(x='Splat.') self.assertTrue(o.bar == 'Splat.', "call through proxy not passed through to original") self.assertRaises(TypeError, ref1) self.assertRaises(TypeError, ref1, 1, 2, 3) def check_proxy(self, o, proxy): o.foo = 1 self.assertTrue(proxy.foo == 1, "proxy does not reflect attribute addition") o.foo = 2 self.assertTrue(proxy.foo == 2, "proxy does not reflect attribute modification") del o.foo self.assertTrue(not hasattr(proxy, 'foo'), "proxy does not reflect attribute removal") proxy.foo = 1 self.assertTrue(o.foo == 1, "object does not reflect attribute addition via proxy") proxy.foo = 2 self.assertTrue( o.foo == 2, "object does not reflect attribute modification via proxy") del proxy.foo self.assertTrue(not hasattr(o, 'foo'), "object does not reflect attribute removal via proxy") def test_proxy_deletion(self): class Foo: result = None def __delitem__(self, accessor): self.result = accessor g = Foo() f = weakref.proxy(g) del f[0] self.assertEqual(f.result, 0) def test_proxy_bool(self): class List(list): pass lyst = List() self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst)) def test_getweakrefcount(self): o = C() ref1 = weakref.ref(o) ref2 = weakref.ref(o, self.callback) self.assertTrue(weakref.getweakrefcount(o) == 2, "got wrong number of weak reference objects") proxy1 = weakref.proxy(o) proxy2 = weakref.proxy(o, self.callback) self.assertTrue(weakref.getweakrefcount(o) == 4, "got wrong number of weak reference objects") del ref1, ref2, proxy1, proxy2 gc_collect() self.assertTrue(weakref.getweakrefcount(o) == 0, "weak reference objects not unlinked from" " referent when discarded.") self.assertTrue(weakref.getweakrefcount(1) == 0, "got wrong number of weak reference objects for int") def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 gc_collect() self.assertTrue(weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 gc_collect() self.assertTrue(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 gc_collect() self.assertTrue(weakref.getweakrefs(o) == [], "list of refs not cleared") self.assertTrue(weakref.getweakrefs(1) == [], "list of refs does not match for int") def test_newstyle_number_ops(self): class F(float): pass f = F(2.0) p = weakref.proxy(f) self.assertTrue(p + 1.0 == 3.0) self.assertTrue(1.0 + p == 3.0) def test_callbacks_protected(self): class BogusError(Exception): pass data = {} def remove(k): del data[k] def encapsulate(): f = lambda : () data[weakref.ref(f, remove)] = None raise BogusError try: encapsulate() except BogusError: pass else: self.fail("exception not properly restored") try: encapsulate() except BogusError: pass else: self.fail("exception not properly restored") def test_sf_bug_840829(self): class C(object): pass c = C() wr = weakref.ref(c, lambda ignore: gc_collect()) del c del wr c1 = C() c1.i = C() wr = weakref.ref(c1.i, lambda ignore: gc_collect()) c2 = C() c2.c1 = c1 del c1 del c2 def test_callback_in_cycle_1(self): class J(object): pass class II(object): def acallback(self, ignore): self.J I = II() I.J = J I.wr = weakref.ref(J, I.acallback) del I, J, II gc_collect() def test_callback_in_cycle_2(self): class J(object): pass class II: def acallback(self, ignore): self.J I = II() I.J = J I.wr = weakref.ref(J, I.acallback) del I, J, II gc_collect() def test_callback_in_cycle_3(self): class C: def cb(self, ignore): self.me self.c1 self.wr c1, c2 = C(), C() c2.me = c2 c2.c1 = c1 c2.wr = weakref.ref(c1, c2.cb) del c1, c2 gc_collect() def test_callback_in_cycle_4(self): class C(object): def cb(self, ignore): self.me self.c1 self.wr class D: pass c1, c2 = D(), C() c2.me = c2 c2.c1 = c1 c2.wr = weakref.ref(c1, c2.cb) del c1, c2, C, D gc_collect() def test_callback_in_cycle_resurrection(self): alist = [] class C(object): def __init__(self, value): self.attribute = value def acallback(self, ignore): alist.append(self.c) c1, c2 = C(1), C(2) c1.c = c2 c2.c = c1 c1.wr = weakref.ref(c2, c1.acallback) c2.wr = weakref.ref(c1, c2.acallback) def C_went_away(ignore): alist.append("C went away") wr = weakref.ref(C, C_went_away) del c1, c2, C self.assertEqual(alist, []) gc_collect() self.assertEqual(alist, ["C went away"]) self.assertEqual(wr(), None) del alist[:] gc_collect() self.assertEqual(alist, []) def test_callbacks_on_callback(self): alist = [] def safe_callback(ignore): alist.append("safe_callback called") class C(object): def cb(self, ignore): alist.append("cb called") c, d = C(), C() c.other = d d.other = c callback = c.cb c.wr = weakref.ref(d, callback) d.wr = weakref.ref(callback, d.cb) external_wr = weakref.ref(callback, safe_callback) self.assertTrue(external_wr() is callback) del callback, c, d, C self.assertEqual(alist, []) gc_collect() self.assertEqual(alist, ["safe_callback called"]) self.assertEqual(external_wr(), None) del alist[:] gc_collect() self.assertEqual(alist, []) def test_gc_during_ref_creation(self): self.check_gc_during_creation(weakref.ref) def test_gc_during_proxy_creation(self): self.check_gc_during_creation(weakref.proxy) def check_gc_during_creation(self, makeref): if test_support.check_impl_detail(): import gc thresholds = gc.get_threshold() gc.set_threshold(1, 1, 1) gc_collect() class A: pass def callback(*args): pass referenced = A() a = A() a.a = a a.wr = makeref(referenced) try: a = A() weakref.ref(referenced, callback) finally: if test_support.check_impl_detail(): gc.set_threshold(*thresholds) def test_ref_created_during_del(self): class Target(object): def __del__(self): global ref_from_del ref_from_del = weakref.ref(self) w = Target()
self.items = [SomeClass(c) for c in ('a', 'b', 'c')] self.items2 = [SomeClass(c) for c in ('x', 'y', 'z')] self.letters = [SomeClass(c) for c in string.ascii_letters] self.s = WeakSet(self.items) self.d = dict.fromkeys(self.items) self.obj = SomeClass('F') self.fs = WeakSet([self.obj]) def test_methods(self): weaksetmethods = dir(WeakSet) for method in dir(set): if method == 'test_c_api' or method.startswith('_'): continue self.assertIn(method, weaksetmethods, "WeakSet missing method " + method) def test_new_or_init(self): self.assertRaises(TypeError, WeakSet, [], 2) def test_len(self): self.assertEqual(len(self.s), len(self.d)) self.assertEqual(len(self.fs), 1) del self.obj test_support.gc_collect() self.assertEqual(len(self.fs), 0) def test_contains(self): for c in self.letters: self.assertEqual(c in self.s, c in self.d) self.assertRaises(TypeError, self.s.__contains__, [[]]) self.assertIn(self.obj, self.fs) del self.obj test_support.gc_collect() self.assertNotIn(SomeClass('F'), self.fs) def test_union(self): u = self.s.union(self.items2) for c in self.letters: self.assertEqual(c in u, c in self.d or c in self.items2) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(u), WeakSet) self.assertRaises(TypeError, self.s.union, [[]]) for C in set, frozenset, dict.fromkeys, list, tuple: x = WeakSet(self.items + self.items2) c = C(self.items2) self.assertEqual(self.s.union(c), x) def test_or(self): i = self.s.union(self.items2) self.assertEqual(self.s | set(self.items2), i) self.assertEqual(self.s | frozenset(self.items2), i) def test_intersection(self): i = self.s.intersection(self.items2) for c in self.letters: self.assertEqual(c in i, c in self.d and c in self.items2) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(i), WeakSet) for C in set, frozenset, dict.fromkeys, list, tuple: x = WeakSet([]) self.assertEqual(self.s.intersection(C(self.items2)), x) def test_isdisjoint(self): self.assertTrue(self.s.isdisjoint(WeakSet(self.items2))) self.assertTrue(not self.s.isdisjoint(WeakSet(self.letters))) def test_and(self): i = self.s.intersection(self.items2) self.assertEqual(self.s & set(self.items2), i) self.assertEqual(self.s & frozenset(self.items2), i) def test_difference(self): i = self.s.difference(self.items2) for c in self.letters: self.assertEqual(c in i, c in self.d and c not in self.items2) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(i), WeakSet) self.assertRaises(TypeError, self.s.difference, [[]]) def test_sub(self): i = self.s.difference(self.items2) self.assertEqual(self.s - set(self.items2), i) self.assertEqual(self.s - frozenset(self.items2), i) def test_symmetric_difference(self): i = self.s.symmetric_difference(self.items2) for c in self.letters: self.assertEqual(c in i, (c in self.d) ^ (c in self.items2)) self.assertEqual(self.s, WeakSet(self.items)) self.assertEqual(type(i), WeakSet) self.assertRaises(TypeError, self.s.symmetric_difference, [[]]) def test_xor(self): i = self.s.symmetric_difference(self.items2) self.assertEqual(self.s ^ set(self.items2), i) self.assertEqual(self.s ^ frozenset(self.items2), i) def test_sub_and_super(self): pl, ql, rl = map(lambda s: [SomeClass(c) for c in s], ['ab', 'abcde', 'def']) p, q, r = map(WeakSet, (pl, ql, rl)) self.assertTrue(p < q) self.assertTrue(p <= q) self.assertTrue(q <= q) self.assertTrue(q > p) self.assertTrue(q >= p) self.assertFalse(q < r) self.assertFalse(q <= r) self.assertFalse(q > r) self.assertFalse(q >= r) self.assertTrue(set('a').issubset('abc')) self.assertTrue(set('abc').issuperset('a')) self.assertFalse(set('a').issubset('cbs')) self.assertFalse(set('cbs').issuperset('a')) def test_gc(self): s = WeakSet(Foo() for i in range(1000)) for elem in s: elem.cycle = s elem.sub = elem elem.set = WeakSet([elem]) def test_subclass_with_custom_hash(self): class H(WeakSet): def __hash__(self): return int(id(self) & 0x7fffffff) s=H() f=set() f.add(s) self.assertIn(s, f) f.remove(s) f.add(s) f.discard(s)
def setUp(self): self.cbcalled = 0
r = weakref.ref(Exception) self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0) gc_collect() def test_classes(self): class A(object): pass class B: pass l = [] weakref.ref(int) a = weakref.ref(A, l.append) A = None gc_collect() self.assertEqual(a(), None) self.assertEqual(l, [a]) b = weakref.ref(B, l.append) B = None gc_collect() self.assertEqual(b(), None) self.assertEqual(l, [a, b]) class SubclassableWeakrefTestCase(TestBase): def test_subclass_refs(self): class MyRef(weakref.ref): def __init__(self, ob, callback=None, value=42): self.value = value super(MyRef, self).__init__(ob, callback) def __call__(self): self.called = True return super(MyRef, self).__call__() o = Object("foo") mr = MyRef(o, value=24) self.assertTrue(mr() is o) self.assertTrue(mr.called) self.assertEqual(mr.value, 24) del o gc_collect() self.assertTrue(mr() is None) self.assertTrue(mr.called) def test_subclass_refs_dont_replace_standard_refs(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) self.assertTrue(r1 is not r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) self.assertTrue(r2 is refs[0]) self.assertIn(r1, refs[1:]) self.assertIn(r3, refs[1:]) def test_subclass_refs_dont_conflate_callbacks(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o, id) r2 = MyRef(o, str) self.assertTrue(r1 is not r2) refs = weakref.getweakrefs(o) self.assertIn(r1, refs) self.assertIn(r2, refs) def test_subclass_refs_with_slots(self): class MyRef(weakref.ref): __slots__ = "slot1", "slot2" def __new__(type, ob, callback, slot1, slot2): return weakref.ref.__new__(type, ob, callback) def __init__(self, ob, callback, slot1, slot2): self.slot1 = slot1 self.slot2 = slot2 def meth(self): return self.slot1 + self.slot2 o = Object(42) r = MyRef(o, None, "abc", "def") self.assertEqual(r.slot1, "abc") self.assertEqual(r.slot2, "def") self.assertEqual(r.meth(), "abcdef") self.assertFalse(hasattr(r, "__dict__")) def test_subclass_refs_with_cycle(self): class MyRef(weakref.ref): pass def callback(w): self.cbcalled += 1 o = C() r1 = MyRef(o, callback) r1.o = o del o del r1 self.assertEqual(self.cbcalled, 0) o = C() r1 = MyRef(o, callback) r2 = MyRef(o, callback) r1.r = r2 r2.o = o del o del r2 del r1 self.assertEqual(self.cbcalled, 0) class Object: def __init__(self, arg): self.arg = arg def __repr__(self): return "<Object %r>" % self.arg class MappingTestCase(TestBase): COUNT = 10 def test_weak_values(self): dict, objects = self.make_weak_valued_dict() for o in objects: self.assertTrue(weakref.getweakrefcount(o) == 1, "wrong number of weak references to %r!" % o) self.assertTrue(o is dict[o.arg], "wrong object returned by weak dict!") items1 = dict.items() items2 = dict.copy().items() items1.sort() items2.sort() self.assertTrue(items1 == items2, "cloning of weak-valued dictionary did not work!") del items1, items2 self.assertTrue(len(dict) == self.COUNT) del objects[0] gc_collect() self.assertTrue(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o gc_collect() self.assertTrue(len(dict) == 0, "deleting the values did not clear the dictionary") dict = weakref.WeakValueDictionary() self.assertRaises(KeyError, dict.__getitem__, 1) dict[2] = C() gc_collect() self.assertRaises(KeyError, dict.__getitem__, 2) def test_weak_keys(self): dict, objects = self.make_weak_keyed_dict() for o in objects: self.assertTrue(weakref.getweakrefcount(o) == 1, "wrong number of weak references to %r!" % o) self.assertTrue(o.arg is dict[o], "wrong object returned by weak dict!") items1 = dict.items() items2 = dict.copy().items() self.assertTrue(set(items1) == set(items2), "cloning of weak-keyed dictionary did not work!") del items1, items2 self.assertTrue(len(dict) == self.COUNT) del objects[0] gc_collect() self.assertTrue(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o gc_collect() self.assertTrue(len(dict) == 0, "deleting the keys did not clear the dictionary") o = Object(42) dict[o] = "What is the meaning of the universe?" self.assertIn(o, dict) self.assertNotIn(34, dict) def test_weak_keyed_iters(self): dict, objects = self.make_weak_keyed_dict() self.check_iters(dict) refs = dict.keyrefs() self.assertEqual(len(refs), len(objects)) objects2 = list(objects) for wr in refs: ob = wr() self.assertIn(ob, dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) objects2 = list(objects) self.assertEqual(len(list(dict.iterkeyrefs())), len(objects)) for wr in dict.iterkeyrefs(): ob = wr() self.assertIn(ob, dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) def test_weak_valued_iters(self): dict, objects = self.make_weak_valued_dict() self.check_iters(dict) refs = dict.valuerefs() self.assertEqual(len(refs), len(objects)) objects2 = list(objects) for wr in refs: ob = wr() self.assertEqual(ob, dict[ob.arg]) self.assertEqual(ob.arg, dict[ob.arg].arg) objects2.remove(ob) self.assertEqual(len(objects2), 0) objects2 = list(objects) self.assertEqual(len(list(dict.itervaluerefs())), len(objects)) for wr in dict.itervaluerefs(): ob = wr() self.assertEqual(ob, dict[ob.arg]) self.assertEqual(ob.arg, dict[ob.arg].arg) objects2.remove(ob) self.assertEqual(len(objects2), 0) def check_iters(self, dict): items = dict.items() for item in dict.iteritems(): items.remove(item) self.assertTrue(len(items) == 0, "iteritems() did not touch all items") keys = dict.keys() for k in dict: keys.remove(k) self.assertTrue(len(keys) == 0, "__iter__() did not touch all keys") keys = dict.keys() for k in dict.iterkeys(): keys.remove(k) self.assertTrue(len(keys) == 0, "iterkeys() did not touch all keys") values = dict.values() for v in dict.itervalues(): values.remove(v) self.assertTrue(len(values) == 0, "itervalues() did not touch all values") def test_make_weak_keyed_dict_from_dict(self): o = Object(3) dict = weakref.WeakKeyDictionary({o:364}) self.assertTrue(dict[o] == 364) def test_make_weak_keyed_dict_from_weak_keyed_dict(self): o = Object(3) dict = weakref.WeakKeyDictionary({o:364}) dict2 = weakref.WeakKeyDictionary(dict) self.assertTrue(dict[o] == 364) def make_weak_keyed_dict(self): dict = weakref.WeakKeyDictionary() objects = map(Object, range(self.COUNT)) for o in objects: dict[o] = o.arg return dict, objects def make_weak_valued_dict(self): dict = weakref.WeakValueDictionary() objects = map(Object, range(self.COUNT)) for o in objects: dict[o.arg] = o return dict, objects def check_popitem(self, klass, key1, value1, key2, value2): weakdict = klass() weakdict[key1] = value1 weakdict[key2] = value2 self.assertTrue(len(weakdict) == 2) k, v = weakdict.popitem() self.assertTrue(len(weakdict) == 1) if k is key1: self.assertTrue(v is value1) else: self.assertTrue(v is value2) k, v = weakdict.popitem() self.assertTrue(len(weakdict) == 0) if k is key1: self.assertTrue(v is value1) else: self.assertTrue(v is value2) def test_weak_valued_dict_popitem(self): self.check_popitem(weakref.WeakValueDictionary, "key1", C(), "key2", C()) def test_weak_keyed_dict_popitem(self): self.check_popitem(weakref.WeakKeyDictionary, C(), "value 1", C(), "value 2") def check_setdefault(self, klass, key, value1, value2): self.assertTrue(value1 is not value2, "invalid test" " -- value parameters must be distinct objects") weakdict = klass() o = weakdict.setdefault(key, value1) self.assertIs(o, value1) self.assertIn(key, weakdict) self.assertIs(weakdict.get(key), value1) self.assertIs(weakdict[key], value1) o = weakdict.setdefault(key, value2) self.assertIs(o, value1) self.assertIn(key, weakdict) self.assertIs(weakdict.get(key), value1) self.assertIs(weakdict[key], value1) def test_weak_valued_dict_setdefault(self): self.check_setdefault(weakref.WeakValueDictionary, "key", C(), C()) def test_weak_keyed_dict_setdefault(self): self.check_setdefault(weakref.WeakKeyDictionary, C(), "value 1", "value 2") def check_update(self, klass, dict): weakdict = klass() weakdict.update(dict) self.assertEqual(len(weakdict), len(dict)) for k in weakdict.keys(): self.assertIn(k, dict, "mysterious new key appeared in weak dict") v = dict.get(k) self.assertIs(v, weakdict[k]) self.assertIs(v, weakdict.get(k)) for k in dict.keys(): self.assertIn(k, weakdict, "original key disappeared in weak dict") v = dict[k] self.assertIs(v, weakdict[k]) self.assertIs(v, weakdict.get(k)) def test_weak_valued_dict_update(self): self.check_update(weakref.WeakValueDictionary, {1: C(), 'a': C(), C(): C()}) def test_weak_keyed_dict_update(self): self.check_update(weakref.WeakKeyDictionary, {C(): 1, C(): 2, C(): 3}) def test_weak_keyed_delitem(self): d = weakref.WeakKeyDictionary() o1 = Object('1') o2 = Object('2') d[o1] = 'something' d[o2] = 'something' self.assertTrue(len(d) == 2) del d[o1] self.assertTrue(len(d) == 1) self.assertTrue(d.keys() == [o2]) def test_weak_valued_delitem(self): d = weakref.WeakValueDictionary() o1 = Object('1') o2 = Object('2') d['something'] = o1 d['something else'] = o2 self.assertTrue(len(d) == 2) del d['something'] self.assertTrue(len(d) == 1) self.assertTrue(d.items() == [('something else', o2)]) def test_weak_keyed_bad_delitem(self): d = weakref.WeakKeyDictionary() o = Object('1') self.assertRaises(KeyError, d.__delitem__, o) self.assertRaises(KeyError, d.__getitem__, o) self.assertRaises(TypeError, d.__delitem__, 13) self.assertRaises(TypeError, d.__getitem__, 13) self.assertRaises(TypeError, d.__setitem__, 13, 13) def test_weak_keyed_cascading_deletes(self): d = weakref.WeakKeyDictionary() mutate = False class C(object): def __init__(self, i): self.value = i def __hash__(self): return hash(self.value) def __eq__(self, other): if mutate: del objs[-1] return self.value == other.value objs = [C(i) for i in range(4)] for o in objs: d[o] = o.value del o objs = d.keys() objs.reverse() mutate = True count = 0 for o in objs: count += 1 del d[o] gc_collect() self.assertEqual(len(d), 0) self.assertEqual(count, 2) from test import mapping_tests class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): """Check that WeakValueDictionary conforms to the mapping protocol""" __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)} type2test = weakref.WeakValueDictionary def _reference(self): return self.__ref.copy() class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): """Check that WeakKeyDictionary conforms to the mapping protocol""" __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3} type2test = weakref.WeakKeyDictionary def _reference(self): return self.__ref.copy() libreftest = """ Doctest for examples in the library reference: weakref.rst >>> import weakref >>> class Dict(dict): ... pass ... >>> obj = Dict(red=1, green=2, blue=3) >>> r = weakref.ref(obj) >>> print r() is obj True >>> import weakref >>> class Object: ... pass ... >>> o = Object() >>> r = weakref.ref(o) >>> o2 = r() >>> o is o2 True >>> del o, o2 >>> print r() None >>> import weakref >>> class ExtendedRef(weakref.ref): ... def __init__(self, ob, callback=None, **annotations): ... super(ExtendedRef, self).__init__(ob, callback) ... self.__counter = 0 ... for k, v in annotations.iteritems(): ... setattr(self, k, v) ... def __call__(self): ... '''Return a pair containing the referent and the number of ... times the reference has been called. ... ''' ... ob = super(ExtendedRef, self).__call__() ... if ob is not None: ... self.__counter += 1 ... ob = (ob, self.__counter) ... return ob ... >>> class A: ... pass ... >>> a = A() >>> r = ExtendedRef(a, foo=1, bar="baz") >>> r.foo 1 >>> r.bar 'baz' >>> r()[1] 1 >>> r()[1] 2 >>> r()[0] is a True >>> import weakref >>> _id2obj_dict = weakref.WeakValueDictionary() >>> def remember(obj): ... oid = id(obj) ... _id2obj_dict[oid] = obj ... return oid ... >>> def id2obj(oid): ... return _id2obj_dict[oid] ... >>> a = A() >>> a_id = remember(a) >>> id2obj(a_id) is a True >>> del a >>> try: ... id2obj(a_id) ... except KeyError: ... print 'OK' ... else: ... print 'WeakValueDictionary error' OK """ __test__ = {'libreftest' : libreftest} def test_main(): test_support.run_unittest( ReferencesTestCase, MappingTestCase, WeakValueDictionaryTestCase, WeakKeyDictionaryTestCase, SubclassableWeakrefTestCase, ) test_support.run_doctest(sys.modules[__name__])
s = WeakSet() s.__init__(self.items) self.assertEqual(s, self.s) s.__init__(self.items2) self.assertEqual(s, WeakSet(self.items2)) self.assertRaises(TypeError, s.__init__, s, 2); self.assertRaises(TypeError, s.__init__, 1); def test_constructor_identity(self): s = WeakSet(self.items) t = WeakSet(s) self.assertNotEqual(id(s), id(t)) def test_hash(self): self.assertRaises(TypeError, hash, self.s) def test_clear(self): self.s.clear() self.assertEqual(self.s, WeakSet([])) self.assertEqual(len(self.s), 0) def test_copy(self): dup = self.s.copy() self.assertEqual(self.s, dup) self.assertNotEqual(id(self.s), id(dup)) def test_add(self): x = SomeClass('Q') self.s.add(x) self.assertIn(x, self.s) dup = self.s.copy() self.s.add(x) self.assertEqual(self.s, dup) self.assertRaises(TypeError, self.s.add, []) self.fs.add(Foo()) test_support.gc_collect() self.assertTrue(len(self.fs) == 1) self.fs.add(self.obj) self.assertTrue(len(self.fs) == 1) def test_remove(self): x = SomeClass('a') self.s.remove(x) self.assertNotIn(x, self.s) self.assertRaises(KeyError, self.s.remove, x) self.assertRaises(TypeError, self.s.remove, []) def test_discard(self): a, q = SomeClass('a'), SomeClass('Q') self.s.discard(a) self.assertNotIn(a, self.s) self.s.discard(q) self.assertRaises(TypeError, self.s.discard, []) def test_pop(self): for i in range(len(self.s)): elem = self.s.pop() self.assertNotIn(elem, self.s) self.assertRaises(KeyError, self.s.pop) def test_update(self): retval = self.s.update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): self.assertIn(c, self.s) self.assertRaises(TypeError, self.s.update, [[]]) def test_update_set(self): self.s.update(set(self.items2)) for c in (self.items + self.items2): self.assertIn(c, self.s) def test_ior(self): self.s |= set(self.items2) for c in (self.items + self.items2): self.assertIn(c, self.s) def test_intersection_update(self): retval = self.s.intersection_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if c in self.items2 and c in self.items: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(TypeError, self.s.intersection_update, [[]]) def test_iand(self): self.s &= set(self.items2) for c in (self.items + self.items2): if c in self.items2 and c in self.items: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_difference_update(self): retval = self.s.difference_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if c in self.items and c not in self.items2: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(TypeError, self.s.difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) def test_isub(self): self.s -= set(self.items2) for c in (self.items + self.items2): if c in self.items and c not in self.items2: self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_symmetric_difference_update(self): retval = self.s.symmetric_difference_update(self.items2) self.assertEqual(retval, None) for c in (self.items + self.items2): if (c in self.items) ^ (c in self.items2): self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) def test_ixor(self): self.s ^= set(self.items2) for c in (self.items + self.items2): if (c in self.items) ^ (c in self.items2): self.assertIn(c, self.s) else: self.assertNotIn(c, self.s) def test_inplace_on_self(self): t = self.s.copy() t |= t self.assertEqual(t, self.s) t &= t self.assertEqual(t, self.s) t -= t self.assertEqual(t, WeakSet()) t = self.s.copy() t ^= t self.assertEqual(t, WeakSet()) def test_eq(self): self.assertTrue(self.s == self.s) self.assertTrue(self.s == WeakSet(self.items)) self.assertFalse(self.s == set(self.items)) self.assertFalse(self.s == list(self.items)) self.assertFalse(self.s == tuple(self.items)) self.assertFalse(self.s == 1) def test_weak_destroy_while_iterating(self): items = [SomeClass(c) for c in ('a', 'b', 'c')] s = WeakSet(items) it = iter(s) next(it) del items[-1] gc.collect() self.assertIn(len(list(it)), [len(items), len(items) - 1]) del it self.assertEqual(len(s), len(items)) def test_weak_destroy_and_mutate_while_iterating(self): items = [SomeClass(c) for c in string.ascii_letters] s = WeakSet(items) @contextlib.contextmanager def testcontext(): try: it = iter(s) next(it) u = SomeClass(str(items.pop())) gc.collect() yield u finally: it = None with testcontext() as u: self.assertNotIn(u, s) with testcontext() as u: self.assertRaises(KeyError, s.remove, u) self.assertNotIn(u, s) with testcontext() as u: s.add(u) self.assertIn(u, s) t = s.copy() with testcontext() as u: s.update(t) self.assertEqual(len(s), len(t)) with testcontext() as u: s.clear() self.assertEqual(len(s), 0) def test_main(verbose=None): test_support.run_unittest(TestWeakSet)
def test_init(self): # Issue 3634 # <weakref to class>.__init__() doesn't check errors correctly r = weakref.ref(Exception) self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0) # No exception should be raised here gc_collect()
test_main()
test_main(verbose=True)
def test_main(): test_support.run_unittest( ReferencesTestCase, MappingTestCase, WeakValueDictionaryTestCase, WeakKeyDictionaryTestCase, SubclassableWeakrefTestCase, ) test_support.run_doctest(sys.modules[__name__])
assert exc.msg == "EOF in multi-line statement"
assert exc.msg == "parenthesis is never closed"
def test_syntax_error(self): parse = self.parse exc = py.test.raises(SyntaxError, parse, "name another for").value assert exc.msg == "invalid syntax" assert exc.lineno == 1 assert exc.offset == 5 assert exc.text.startswith("name another for") exc = py.test.raises(SyntaxError, parse, "x = \"blah\n\n\n").value assert exc.msg == "EOL while scanning single-quoted string" assert exc.lineno == 1 assert exc.offset == 5 exc = py.test.raises(SyntaxError, parse, "x = '''\n\n\n").value assert exc.msg == "EOF while scanning triple-quoted string" assert exc.lineno == 1 assert exc.offset == 5 for input in ("())", "(()", "((", "))"): py.test.raises(SyntaxError, parse, input) exc = py.test.raises(SyntaxError, parse, "x = (\n\n(),\n(),").value assert exc.msg == "EOF in multi-line statement" assert exc.lineno == 1 assert exc.offset == 5
return space.wrap(_strcoll(rffi.str2charp(s1), rffi.str2charp(s2)))
s1_c = rffi.str2charp(s1) s2_c = rffi.str2charp(s2) try: return space.wrap(_strcoll(s1_c, s2_c)) finally: rffi.free_charp(s1_c) rffi.free_charp(s2_c)
def strcoll(space, w_s1, w_s2): "string,string -> int. Compares two strings according to the locale." if space.is_true(space.isinstance(w_s1, space.w_str)) and \ space.is_true(space.isinstance(w_s2, space.w_str)): s1, s2 = space.str_w(w_s1), space.str_w(w_s2) return space.wrap(_strcoll(rffi.str2charp(s1), rffi.str2charp(s2))) #if not space.is_true(space.isinstance(w_s1, space.w_unicode)) and \ # not space.is_true(space.isinstance(w_s2, space.w_unicode)): # raise OperationError(space.w_ValueError, # space.wrap("strcoll arguments must be strings")) s1, s2 = space.unicode_w(w_s1), space.unicode_w(w_s2) s1_c = rffi.unicode2wcharp(s1) s2_c = rffi.unicode2wcharp(s2) result = _wcscoll(s1_c, s2_c) return space.wrap(result)
result = _wcscoll(s1_c, s2_c)
try: result = _wcscoll(s1_c, s2_c) finally: rffi.free_wcharp(s1_c) rffi.free_wcharp(s2_c)
def strcoll(space, w_s1, w_s2): "string,string -> int. Compares two strings according to the locale." if space.is_true(space.isinstance(w_s1, space.w_str)) and \ space.is_true(space.isinstance(w_s2, space.w_str)): s1, s2 = space.str_w(w_s1), space.str_w(w_s2) return space.wrap(_strcoll(rffi.str2charp(s1), rffi.str2charp(s2))) #if not space.is_true(space.isinstance(w_s1, space.w_unicode)) and \ # not space.is_true(space.isinstance(w_s2, space.w_unicode)): # raise OperationError(space.w_ValueError, # space.wrap("strcoll arguments must be strings")) s1, s2 = space.unicode_w(w_s1), space.unicode_w(w_s2) s1_c = rffi.unicode2wcharp(s1) s2_c = rffi.unicode2wcharp(s2) result = _wcscoll(s1_c, s2_c) return space.wrap(result)
n2 = _strxfrm(buf, rffi.str2charp(s), n1) + 1
s_c = rffi.str2charp(s) try: n2 = _strxfrm(buf, s_c, n1) + 1 finally: rffi.free_charp(s_c)
def strxfrm(space, s): "string -> string. Returns a string that behaves for cmp locale-aware." n1 = len(s) + 1 buf = lltype.malloc(rffi.CCHARP.TO, n1, flavor="raw", zero=True) n2 = _strxfrm(buf, rffi.str2charp(s), n1) + 1 if n2 > n1: # more space needed lltype.free(buf, flavor="raw") buf = lltype.malloc(rffi.CCHARP.TO, intmask(n2), flavor="raw", zero=True) _strxfrm(buf, rffi.str2charp(s), n2) val = rffi.charp2str(buf) lltype.free(buf, flavor="raw") return space.wrap(val)
_strxfrm(buf, rffi.str2charp(s), n2)
s_c = rffi.str2charp(s) try: _strxfrm(buf, s_c, n2) finally: rffi.free_charp(s_c)
def strxfrm(space, s): "string -> string. Returns a string that behaves for cmp locale-aware." n1 = len(s) + 1 buf = lltype.malloc(rffi.CCHARP.TO, n1, flavor="raw", zero=True) n2 = _strxfrm(buf, rffi.str2charp(s), n1) + 1 if n2 > n1: # more space needed lltype.free(buf, flavor="raw") buf = lltype.malloc(rffi.CCHARP.TO, intmask(n2), flavor="raw", zero=True) _strxfrm(buf, rffi.str2charp(s), n2) val = rffi.charp2str(buf) lltype.free(buf, flavor="raw") return space.wrap(val)
return space.wrap(rffi.charp2str(_gettext(rffi.str2charp(msg))))
msg_c = rffi.str2charp(msg) try: return space.wrap(rffi.charp2str(_gettext(msg_c))) finally: rffi.free_charp(msg_c)
def gettext(space, msg): """gettext(msg) -> string Return translation of msg.""" return space.wrap(rffi.charp2str(_gettext(rffi.str2charp(msg))))
result = _dgettext(domain, rffi.str2charp(msg))
msg_c = rffi.str2charp(msg) try: result = _dgettext(domain, msg_c) finally: rffi.free_charp(msg_c)
def dgettext(space, w_domain, msg): """dgettext(domain, msg) -> string Return translation of msg in domain.""" if space.is_w(w_domain, space.w_None): domain = None result = _dgettext(domain, rffi.str2charp(msg)) else: domain = space.str_w(w_domain) result = _dgettext(rffi.str2charp(domain), rffi.str2charp(msg))
result = _dgettext(rffi.str2charp(domain), rffi.str2charp(msg))
domain_c = rffi.str2charp(domain) msg_c = rffi.str2charp(msg) try: result = _dgettext(domain_c, msg_c) finally: rffi.free_charp(domain_c) rffi.free_charp(msg_c)
def dgettext(space, w_domain, msg): """dgettext(domain, msg) -> string Return translation of msg in domain.""" if space.is_w(w_domain, space.w_None): domain = None result = _dgettext(domain, rffi.str2charp(msg)) else: domain = space.str_w(w_domain) result = _dgettext(rffi.str2charp(domain), rffi.str2charp(msg))
result = _dcgettext(domain, rffi.str2charp(msg), rffi.cast(rffi.INT, category))
msg_c = rffi.str2charp(msg) try: result = _dcgettext(domain, msg_c, rffi.cast(rffi.INT, category)) finally: rffi.free_charp(msg_c)
def dcgettext(space, w_domain, msg, category): """dcgettext(domain, msg, category) -> string Return translation of msg in domain and category."""
result = _dcgettext(rffi.str2charp(domain), rffi.str2charp(msg), rffi.cast(rffi.INT, category))
domain_c = rffi.str2charp(domain) msg_c = rffi.str2charp(msg) try: result = _dcgettext(domain_c, msg_c, rffi.cast(rffi.INT, category)) finally: rffi.free_charp(domain_c) rffi.free_charp(msg_c)
def dcgettext(space, w_domain, msg, category): """dcgettext(domain, msg, category) -> string Return translation of msg in domain and category."""
result = _textdomain(rffi.str2charp(domain))
domain_c = rffi.str2charp(domain) try: result = _textdomain(domain_c) finally: rffi.free_charp(domain_c)
def textdomain(space, w_domain): """textdomain(domain) -> string Set the C library's textdomain to domain, returning the new domain."""
dirname = _bindtextdomain(rffi.str2charp(domain), dir)
domain_c = rffi.str2charp(domain) try: dirname = _bindtextdomain(domain_c, dir) finally: rffi.free_charp(domain_c)
def bindtextdomain(space, domain, w_dir): """bindtextdomain(domain, dir) -> string Bind the C library's domain to dir."""
dirname = _bindtextdomain(rffi.str2charp(domain), rffi.str2charp(dir))
domain_c = rffi.str2charp(domain) dir_c = rffi.str2charp(dir) try: dirname = _bindtextdomain(domain_c, dir_c) finally: rffi.free_charp(domain_c) rffi.free_charp(dir_c)
def bindtextdomain(space, domain, w_dir): """bindtextdomain(domain, dir) -> string Bind the C library's domain to dir."""
result = _bind_textdomain_codeset( rffi.str2charp(domain), codeset)
domain_c = rffi.str2charp(domain) try: result = _bind_textdomain_codeset(domain_c, codeset) finally: rffi.free_charp(domain_c)
def bind_textdomain_codeset(space, domain, w_codeset): """bind_textdomain_codeset(domain, codeset) -> string Bind the C library's domain to codeset."""
result = _bind_textdomain_codeset(rffi.str2charp(domain), rffi.str2charp(codeset))
domain_c = rffi.str2charp(domain) codeset_c = rffi.str2charp(codeset) try: result = _bind_textdomain_codeset(domain_c, codeset_c) finally: rffi.free_charp(domain_c) rffi.free_charp(codeset_c)
def bind_textdomain_codeset(space, domain, w_codeset): """bind_textdomain_codeset(domain, codeset) -> string Bind the C library's domain to codeset."""
if str(exc) == excmsg:
if excmsg is None or str(exc) == excmsg:
def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception, exc: if str(exc) == excmsg: if verbose: print "yes" else: if verbose: print 'no' print 'Unexpected ', exception, ':', repr(str(exc)) except: if verbose: print 'no' print 'Unexpected exception' raise else: raise TestFailed, 'did not get expected exception: %s' % excmsg
test_exc('%d', '1', TypeError, "int argument required") test_exc('%g', '1', TypeError, "float argument required")
test_exc('%d', '1', TypeError, None) test_exc('%g', '1', TypeError, None)
def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception, exc: if str(exc) == excmsg: if verbose: print "yes" else: if verbose: print 'no' print 'Unexpected ', exception, ':', repr(str(exc)) except: if verbose: print 'no' print 'Unexpected exception' raise else: raise TestFailed, 'did not get expected exception: %s' % excmsg
code = [0] * n for i in range(n): x = space.uint_w(space.getitem(w_code, space.wrap(i))) code[i] = intmask(x)
code = [intmask(space.uint_w(space.getitem(w_code, space.wrap(i)))) for i in range(n)]
def SRE_Pattern__new__(space, w_subtype, w_pattern, flags, w_code, groups=0, w_groupindex=None, w_indexgroup=None): n = space.int_w(space.len(w_code)) code = [0] * n for i in range(n): x = space.uint_w(space.getitem(w_code, space.wrap(i))) code[i] = intmask(x) # w_srepat = space.allocate_instance(W_SRE_Pattern, w_subtype) srepat = space.interp_w(W_SRE_Pattern, w_srepat) srepat.space = space srepat.w_pattern = w_pattern # the original uncompiled pattern srepat.flags = flags srepat.code = code srepat.num_groups = groups srepat.w_groupindex = w_groupindex srepat.w_indexgroup = w_indexgroup return w_srepat
box.unique = UNIQUE_NO
def mark_escaped(self): # invariant: if escaped=True, then dependencies is None if not self.escaped: self.escaped = True if self.dependencies is not None: deps = self.dependencies self.dependencies = None for box in deps: box.mark_escaped() # see test_find_nodes_store_into_loop_constant_1 for this: box.unique = UNIQUE_NO
if tc in 'IL':
if tc == 'L':
def test_array_sum(self): for tc, maxops in zip('bhilBHILfd', (38,) * 6 + (40, 40, 41, 38)): res = 19352859 if tc in 'IL': res = long(res) elif tc in 'fd': res = float(res) self.run_source(''' from array import array
elif tc == 'I' and sys.maxint == 2147483647: res = long(res)
def test_array_sum(self): for tc, maxops in zip('bhilBHILfd', (38,) * 6 + (40, 40, 41, 38)): res = 19352859 if tc in 'IL': res = long(res) elif tc in 'fd': res = float(res) self.run_source(''' from array import array
if tc in 'IL':
if tc == 'L':
def test_array_intimg(self): # XXX this test is way too imprecise in what it is actually testing # it should count the number of guards instead for tc, maxops in zip('ilILd', (67, 67, 70, 70, 61)): print print '='*65 print '='*20, 'running test for tc=%r' % (tc,), '='*20 res = 73574560 if tc in 'IL': res = long(res) elif tc in 'fd': res = float(res) self.run_source(''' from array import array
elif tc == 'I' and sys.maxint == 2147483647: res = long(res)
def test_array_intimg(self): # XXX this test is way too imprecise in what it is actually testing # it should count the number of guards instead for tc, maxops in zip('ilILd', (67, 67, 70, 70, 61)): print print '='*65 print '='*20, 'running test for tc=%r' % (tc,), '='*20 res = 73574560 if tc in 'IL': res = long(res) elif tc in 'fd': res = float(res) self.run_source(''' from array import array
filename = '<codegen %s:%d>' % (fn, lineno)
filename = base + '%s:%d>' % (fn, lineno)
def compile(self, filename=None, mode='exec', flag=generators.compiler_flag, dont_inherit=0, _genframe=None): """ return compiled code object. if filename is None invent an artificial filename which displays the source/line position of the caller frame. """ if not filename or py.path.local(filename).check(file=0): if _genframe is None: _genframe = sys._getframe(1) # the caller fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno if not filename: filename = '<codegen %s:%d>' % (fn, lineno) else: filename = '<codegen %r %s:%d>' % (filename, fn, lineno) source = "\n".join(self.lines) + '\n' try: co = cpy_compile(source, filename, mode, flag) except SyntaxError: ex = sys.exc_info()[1] # re-represent syntax errors from parsing python strings msglines = self.lines[:ex.lineno] if ex.offset: msglines.append(" "*ex.offset + '^') msglines.append("syntax error probably generated here: %s" % filename) newex = SyntaxError('\n'.join(msglines)) newex.offset = ex.offset newex.lineno = ex.lineno newex.text = ex.text raise newex else: if flag & _AST_FLAG: return co lines = [(x + "\n") for x in self.lines] if sys.version_info[0] >= 3: # XXX py3's inspect.getsourcefile() checks for a module # and a pep302 __loader__ ... we don't have a module # at code compile-time so we need to fake it here m = ModuleType("_pycodecompile_pseudo_module") py.std.inspect.modulesbyfile[filename] = None py.std.sys.modules[None] = m m.__loader__ = 1 py.std.linecache.cache[filename] = (1, None, lines, filename) return co
filename = '<codegen %r %s:%d>' % (filename, fn, lineno)
filename = base + '%r %s:%d>' % (filename, fn, lineno)
def compile(self, filename=None, mode='exec', flag=generators.compiler_flag, dont_inherit=0, _genframe=None): """ return compiled code object. if filename is None invent an artificial filename which displays the source/line position of the caller frame. """ if not filename or py.path.local(filename).check(file=0): if _genframe is None: _genframe = sys._getframe(1) # the caller fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno if not filename: filename = '<codegen %s:%d>' % (fn, lineno) else: filename = '<codegen %r %s:%d>' % (filename, fn, lineno) source = "\n".join(self.lines) + '\n' try: co = cpy_compile(source, filename, mode, flag) except SyntaxError: ex = sys.exc_info()[1] # re-represent syntax errors from parsing python strings msglines = self.lines[:ex.lineno] if ex.offset: msglines.append(" "*ex.offset + '^') msglines.append("syntax error probably generated here: %s" % filename) newex = SyntaxError('\n'.join(msglines)) newex.offset = ex.offset newex.lineno = ex.lineno newex.text = ex.text raise newex else: if flag & _AST_FLAG: return co lines = [(x + "\n") for x in self.lines] if sys.version_info[0] >= 3: # XXX py3's inspect.getsourcefile() checks for a module # and a pep302 __loader__ ... we don't have a module # at code compile-time so we need to fake it here m = ModuleType("_pycodecompile_pseudo_module") py.std.inspect.modulesbyfile[filename] = None py.std.sys.modules[None] = m m.__loader__ = 1 py.std.linecache.cache[filename] = (1, None, lines, filename) return co
self.mc.CMP_rr(l0.value, l1.getint())
self.mc.CMP_ri(l0.value, l1.getint())
def emit_op_guard_value(self, op, regalloc, fcond): a0 = op.getarg(0) a1 = op.getarg(1) l0 = regalloc.make_sure_var_in_reg(a0, imm_fine=False) l1 = regalloc.make_sure_var_in_reg(a1) if l1.is_imm(): self.mc.CMP_rr(l0.value, l1.getint()) else: self.mc.CMP_rr(l0.value, l1.value) regalloc.possibly_free_vars_for_op(op) return self._emit_guard(op, regalloc, c.NE)
value &= BIT_MASK(numbits - 1)
value &= rffi.cast(ll_t, BIT_MASK(numbits - 1))
def cast_pos(self, i, ll_t): pos = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[i]) TP = lltype.Ptr(rffi.CArray(ll_t)) value = rffi.cast(TP, pos)[0] # Handle bitfields for c in unroll_letters_for_numbers: if LL_TYPEMAP[c] is ll_t and self.shape.ll_bitsizes: bitsize = self.shape.ll_bitsizes[i] numbits = NUM_BITS(bitsize) lowbit = LOW_BIT(bitsize) if numbits: if ll_t is lltype.Bool or signedtype(ll_t._type): value >>= lowbit sign = (value >> (numbits - 1)) & 1 value &= BIT_MASK(numbits - 1) if sign: value = ~value else: # unsigned is easier value >>= lowbit value &= BIT_MASK(numbits) break return value
value &= BIT_MASK(numbits)
value &= rffi.cast(ll_t, BIT_MASK(numbits))
def cast_pos(self, i, ll_t): pos = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[i]) TP = lltype.Ptr(rffi.CArray(ll_t)) value = rffi.cast(TP, pos)[0] # Handle bitfields for c in unroll_letters_for_numbers: if LL_TYPEMAP[c] is ll_t and self.shape.ll_bitsizes: bitsize = self.shape.ll_bitsizes[i] numbits = NUM_BITS(bitsize) lowbit = LOW_BIT(bitsize) if numbits: if ll_t is lltype.Bool or signedtype(ll_t._type): value >>= lowbit sign = (value >> (numbits - 1)) & 1 value &= BIT_MASK(numbits - 1) if sign: value = ~value else: # unsigned is easier value >>= lowbit value &= BIT_MASK(numbits) break return value
space = gettestobjspace(usemodules=('_stackless',))
space = gettestobjspace(usemodules=('_stackless','_socket'))
def setup_class(cls): space = gettestobjspace(usemodules=('_stackless',)) cls.space = space # cannot test the unpickle part on top of py.py cls.w_can_unpickle = space.wrap(bool(option.runappdirect))
return
return 0
def PyType_Ready(space, pto): if pto.c_tp_flags & Py_TPFLAGS_READY: return assert pto.c_tp_flags & Py_TPFLAGS_READYING == 0 pto.c_tp_flags |= Py_TPFLAGS_READYING try: type_realize(space, rffi.cast(PyObject, pto)) pto.c_tp_flags |= Py_TPFLAGS_READY finally: pto.c_tp_flags &= ~Py_TPFLAGS_READYING return 0
n = self._write(space, data[written:size - written])
n = self._write(space, data[written:])
def write_w(self, space, w_data): self._check_closed(space, "write to closed file") data = space.str_w(w_data) size = len(data)
self.staticdata.log('cancelled, going on...')
self.staticdata.log('cancelled, tracing more...')
def reached_loop_header(self, greenboxes, redboxes): duplicates = {} self.remove_consts_and_duplicates(redboxes, len(redboxes), duplicates) live_arg_boxes = greenboxes + redboxes if self.jitdriver_sd.virtualizable_info is not None: # we use pop() to remove the last item, which is the virtualizable # itself self.remove_consts_and_duplicates(self.virtualizable_boxes, len(self.virtualizable_boxes)-1, duplicates) live_arg_boxes += self.virtualizable_boxes live_arg_boxes.pop() assert len(self.virtualref_boxes) == 0, "missing virtual_ref_finish()?" # Called whenever we reach the 'loop_header' hint. # First, attempt to make a bridge: # - if self.resumekey is a ResumeGuardDescr, it starts from a guard # that failed; # - if self.resumekey is a ResumeFromInterpDescr, it starts directly # from the interpreter. self.compile_bridge(live_arg_boxes) # raises in case it works -- which is the common case, hopefully, # at least for bridges starting from a guard.
self.check_loop_count(2) self.check_tree_loop_count(2)
if self.optimizer == OPTIMIZER_FULL: self.check_loop_count(2) self.check_tree_loop_count(2) else: self.check_loop_count(2) self.check_tree_loop_count(1)
def f(x, y): z = Z(y) while x > 0: myjitdriver.can_enter_jit(x=x, z=z) myjitdriver.jit_merge_point(x=x, z=z) if x % 5 != 0: externfn(z) z = Z(z.elem + 1) x -= 1 return z.elem
if endian < 0: pendian[0] = -1 elif endian > 0: pendian[0] = 1 else: pendian[0] = 0
pendian[0] = rffi.cast(rffi.INT, value)
def test(encoded, endian, realendian=None): encoded_charp = rffi.str2charp(encoded) strict_charp = rffi.str2charp("strict") if endian is not None: pendian = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') if endian < 0: pendian[0] = -1 elif endian > 0: pendian[0] = 1 else: pendian[0] = 0 else: pendian = None
errcode = g_gettimeofday(t)
errcode = c_gettimeofday(t)
def time_time_llimpl(): void = lltype.nullptr(rffi.VOIDP.TO) result = -1.0 if self.HAVE_GETTIMEOFDAY: t = lltype.malloc(self.TIMEVAL, flavor='raw')
'int', descr=descr)
'void', descr=descr)
def test_raw_malloced_setarrayitem(self): ARRAY = rffi.CArray(lltype.Signed) descr = self.cpu.arraydescrof(ARRAY) a = lltype.malloc(ARRAY, 10, flavor='raw') addr = llmemory.cast_ptr_to_adr(a) abox = BoxInt(heaptracker.adr2int(addr)) self.execute_operation(rop.SETARRAYITEM_RAW, [abox, BoxInt(5), BoxInt(12345)], 'int', descr=descr) assert a[5] == 12345 lltype.free(a, flavor='raw')
cmd = "%s %s %d %s %s %s %s %s" %(
cmd = "%s %s %d %s -S %s %s %s %s" %(
def getinvocation(self, regrtest): fspath = regrtest.getfspath() python = sys.executable pypy_script = pypydir.join('bin', 'py.py') alarm_script = pypydir.join('tool', 'alarm.py') if sys.platform == 'win32': watchdog_name = 'watchdog_nt.py' else: watchdog_name = 'watchdog.py' watchdog_script = pypydir.join('tool', watchdog_name)
"<_rawffi.Array '?' (%d, %d)>" % (4*lsize, lsize))
"<_rawffi.Array '\0' (%d, %d)>" % (4*lsize, lsize))
def test_repr(self): import _rawffi, struct isize = struct.calcsize("i") lsize = struct.calcsize("l") assert (repr(_rawffi.Array('i')) == "<_rawffi.Array 'i' (%d, %d)>" % (isize, isize))
'large_object_gcptrs': 10*WORD,
def test_malloc_nonmovable_fixsize(self): py.test.skip("not supported")
py.test.skip("XXX this needs to be fixed, maybe") class X: def m(self): return 3 def f(): x = X() return x.m() pypy_code = 't\x00\x00\x83\x00\x00}\x00\x00|\x00\x00\x91\x02\x00\x92\x00\x00Sd\x00\x00S' new_c = self.monkey_patch_code(f.func_code, 3, 3, pypy_code, ('X', 'x', 'm'), ('x',)) f2 = new.function(new_c, locals(), 'f') graph = self.codetest(f2) all_ops = self.all_operations(graph) assert all_ops['simple_call'] == 2 assert all_ops['getattr'] == 1
flow_meth_names = flowcontext.FlowSpaceFrame.opcode_method_names pyframe_meth_names = PyFrame.opcode_method_names for name in ['CALL_METHOD', 'LOOKUP_METHOD']: num = bytecode_spec.opmap[name] locals()['old_' + name] = flow_meth_names[num] flow_meth_names[num] = pyframe_meth_names[num] try: class X: def m(self): return 3 def f(): x = X() return x.m() pypy_code = 't\x00\x00\x83\x00\x00}\x00\x00|\x00\x00\x91\x02\x00\x92\x00\x00Sd\x00\x00S' new_c = self.monkey_patch_code(f.func_code, 3, 3, pypy_code, ('X', 'x', 'm'), ('x',)) f2 = new.function(new_c, locals(), 'f') graph = self.codetest(f2) all_ops = self.all_operations(graph) assert all_ops['simple_call'] == 2 assert all_ops['getattr'] == 1 finally: for name in ['CALL_METHOD', 'LOOKUP_METHOD']: num = bytecode_spec.opmap[name] flow_meth_names[num] = locals()['old_' + name]
def test_callmethod_opcode(self): """ Tests code generated by pypy-c compiled with CALL_METHOD bytecode """ py.test.skip("XXX this needs to be fixed, maybe") class X: def m(self): return 3
i = 0
i = 1
def portal(codeno, j): i = 0 while 1: driver.jit_merge_point(codeno=codeno, i=i, j=j) if i == 1: if j == 0: return portal(2, j - 1) elif i == 3: return i += 1 driver.can_enter_jit(codeno=codeno, i=i, j=j)
if i == 1:
if (i >> 1) == 1:
def portal(codeno, j): i = 0 while 1: driver.jit_merge_point(codeno=codeno, i=i, j=j) if i == 1: if j == 0: return portal(2, j - 1) elif i == 3: return i += 1 driver.can_enter_jit(codeno=codeno, i=i, j=j)
elif i == 3:
elif i == 5:
def portal(codeno, j): i = 0 while 1: driver.jit_merge_point(codeno=codeno, i=i, j=j) if i == 1: if j == 0: return portal(2, j - 1) elif i == 3: return i += 1 driver.can_enter_jit(codeno=codeno, i=i, j=j)
portal(2, 50)
portal(2, 5)
def portal(codeno, j): i = 0 while 1: driver.jit_merge_point(codeno=codeno, i=i, j=j) if i == 1: if j == 0: return portal(2, j - 1) elif i == 3: return i += 1 driver.can_enter_jit(codeno=codeno, i=i, j=j)
self.meta_interp(portal, [2, 20], inline=True) self.check_loops(call_assembler=1, call_may_force=0,
self.meta_interp(portal, [2, 5], inline=True) self.check_loops(call_assembler=2, call_may_force=0,
def my_ctc(*args): looptoken = original_ctc(*args) trace.append(looptoken) return looptoken
expected = """
preamble = """
def test_duplicate_setfield_4(self): ops = """ [p1, i1, i2, p3] setfield_gc(p1, i1, descr=valuedescr) # # some operations on which the above setfield_gc cannot have effect i3 = getarrayitem_gc_pure(p3, 1, descr=arraydescr) i4 = getarrayitem_gc(p3, i3, descr=arraydescr) i5 = int_add(i3, i4) setarrayitem_gc(p3, 0, i5, descr=arraydescr) setfield_gc(p1, i4, descr=nextdescr) # setfield_gc(p1, i2, descr=valuedescr) jump(p1, i1, i2, p3) """ expected = """ [p1, i1, i2, p3] # i3 = getarrayitem_gc_pure(p3, 1, descr=arraydescr) i4 = getarrayitem_gc(p3, i3, descr=arraydescr) i5 = int_add(i3, i4) setarrayitem_gc(p3, 0, i5, descr=arraydescr) # setfield_gc(p1, i2, descr=valuedescr) setfield_gc(p1, i4, descr=nextdescr) jump(p1, i1, i2, p3) """ self.optimize_loop(ops, 'Not, Not, Not, Not', expected)
jump(p1, i1, i2, p3) """ self.optimize_loop(ops, 'Not, Not, Not, Not', expected)
jump(p1, i1, i2, p3, i3) """ expected = """ [p1, i1, i2, p3, i3] i4 = getarrayitem_gc(p3, i3, descr=arraydescr) i5 = int_add(i3, i4) setarrayitem_gc(p3, 0, i5, descr=arraydescr) setfield_gc(p1, i2, descr=valuedescr) setfield_gc(p1, i4, descr=nextdescr) jump(p1, i1, i2, p3, i3) """ self.optimize_loop(ops, 'Not, Not, Not, Not', expected, preamble)
def test_duplicate_setfield_4(self): ops = """ [p1, i1, i2, p3] setfield_gc(p1, i1, descr=valuedescr) # # some operations on which the above setfield_gc cannot have effect i3 = getarrayitem_gc_pure(p3, 1, descr=arraydescr) i4 = getarrayitem_gc(p3, i3, descr=arraydescr) i5 = int_add(i3, i4) setarrayitem_gc(p3, 0, i5, descr=arraydescr) setfield_gc(p1, i4, descr=nextdescr) # setfield_gc(p1, i2, descr=valuedescr) jump(p1, i1, i2, p3) """ expected = """ [p1, i1, i2, p3] # i3 = getarrayitem_gc_pure(p3, 1, descr=arraydescr) i4 = getarrayitem_gc(p3, i3, descr=arraydescr) i5 = int_add(i3, i4) setarrayitem_gc(p3, 0, i5, descr=arraydescr) # setfield_gc(p1, i2, descr=valuedescr) setfield_gc(p1, i4, descr=nextdescr) jump(p1, i1, i2, p3) """ self.optimize_loop(ops, 'Not, Not, Not, Not', expected)
import py; py.test.skip("Disabled for now, sorry")
def __init__(self, config, chunk_size=DEFAULT_CHUNK_SIZE, space_size=4096): import py; py.test.skip("Disabled for now, sorry") self.param_space_size = space_size MovingGCBase.__init__(self, config, chunk_size)
if self.config.gcconfig.debugprint: self.program_start_time = time.time()
self.program_start_time = time.time()
def setup(self): self.space_size = self.param_space_size self.next_collect_after = self.param_space_size/2 # whatever...
if self.config.gcconfig.debugprint: llop.debug_print(lltype.Void) llop.debug_print(lltype.Void, ".----------- Full collection ------------------")
if have_debug_prints(): debug_start("gc-collect") debug_print() debug_print(".----------- Full collection ------------------")
def debug_collect_start(self): if self.config.gcconfig.debugprint: llop.debug_print(lltype.Void) llop.debug_print(lltype.Void, ".----------- Full collection ------------------") start_time = time.time() return start_time
return start_time
return start_time return -1
def debug_collect_start(self): if self.config.gcconfig.debugprint: llop.debug_print(lltype.Void) llop.debug_print(lltype.Void, ".----------- Full collection ------------------") start_time = time.time() return start_time
if self.config.gcconfig.debugprint:
if start_time != -1:
def debug_collect_finish(self, start_time): if self.config.gcconfig.debugprint: end_time = time.time() elapsed_time = end_time - start_time self.total_collection_time += elapsed_time self.total_collection_count += 1 total_program_time = end_time - self.program_start_time ct = self.total_collection_time cc = self.total_collection_count llop.debug_print(lltype.Void, "| number of collections so far ", cc) llop.debug_print(lltype.Void, "| total collections per second: ", cc / total_program_time) llop.debug_print(lltype.Void, "| total time in markcompact-collect: ", ct, "seconds") llop.debug_print(lltype.Void, "| percentage collection<->total time:", ct * 100.0 / total_program_time, "%") llop.debug_print(lltype.Void, "`----------------------------------------------")
llop.debug_print(lltype.Void, "| number of collections so far ", cc) llop.debug_print(lltype.Void, "| total collections per second: ", cc / total_program_time) llop.debug_print(lltype.Void, "| total time in markcompact-collect: ", ct, "seconds") llop.debug_print(lltype.Void, "| percentage collection<->total time:", ct * 100.0 / total_program_time, "%") llop.debug_print(lltype.Void, "`----------------------------------------------")
debug_print("| number of collections so far ", cc) debug_print("| total collections per second: ", cc / total_program_time) debug_print("| total time in markcompact-collect: ", ct, "seconds") debug_print("| percentage collection<->total time:", ct * 100.0 / total_program_time, "%") debug_print("`----------------------------------------------") debug_stop("gc-collect")
def debug_collect_finish(self, start_time): if self.config.gcconfig.debugprint: end_time = time.time() elapsed_time = end_time - start_time self.total_collection_time += elapsed_time self.total_collection_count += 1 total_program_time = end_time - self.program_start_time ct = self.total_collection_time cc = self.total_collection_count llop.debug_print(lltype.Void, "| number of collections so far ", cc) llop.debug_print(lltype.Void, "| total collections per second: ", cc / total_program_time) llop.debug_print(lltype.Void, "| total time in markcompact-collect: ", ct, "seconds") llop.debug_print(lltype.Void, "| percentage collection<->total time:", ct * 100.0 / total_program_time, "%") llop.debug_print(lltype.Void, "`----------------------------------------------")
self._emit_call(descr._arm_direct_bootstrap_code, op.getarglist(), regalloc, fcond, resbox)
self._emit_call(descr._arm_direct_bootstrap_code, op.getarglist(), regalloc, fcond, result=resbox)
def emit_guard_call_assembler(self, op, guard_op, regalloc, fcond): faildescr = guard_op.getdescr() fail_index = self.cpu.get_fail_descr_number(faildescr) self._write_fail_index(fail_index, regalloc)
c = stdoutcapture.Capture(mixed_out_err = True)
def build(self, noerr=False): basename = self.outputfilename.new(ext='') data = '' try: saved_environ = os.environ.copy() try: c = stdoutcapture.Capture(mixed_out_err = True) self._build() finally: # workaround for a distutils bugs where some env vars can # become longer and longer every time it is used for key, value in saved_environ.items(): if os.environ.get(key) != value: os.environ[key] = value foutput, foutput = c.done() data = foutput.read() if data: fdump = basename.new(ext='errors').open("w") fdump.write(data) fdump.close() except: if not noerr: print >>sys.stderr, data raise
counter = 0
counter = 1
def splitloops(loops): real_loops = [] counter = 0 for loop in loops: firstline = loop[:loop.find("\n")] counter += loop.count("\n") m = re.match('# Loop (\d+)', firstline) if m: no = int(m.group(1)) assert len(real_loops) == no real_loops.append(FinalBlock(loop, None)) real_loops[-1].startlineno = counter else: m = re.search("bridge out of Guard (\d+)", firstline) assert m guard_s = 'Guard' + m.group(1) split_one_loop(real_loops, guard_s, loop, counter) return real_loops
counter += loop.count("\n")
def splitloops(loops): real_loops = [] counter = 0 for loop in loops: firstline = loop[:loop.find("\n")] counter += loop.count("\n") m = re.match('# Loop (\d+)', firstline) if m: no = int(m.group(1)) assert len(real_loops) == no real_loops.append(FinalBlock(loop, None)) real_loops[-1].startlineno = counter else: m = re.search("bridge out of Guard (\d+)", firstline) assert m guard_s = 'Guard' + m.group(1) split_one_loop(real_loops, guard_s, loop, counter) return real_loops
m = re.search("debug_merge_point\('<code object (.*?)>", loop.content)
m = re.search("debug_merge_point\('<code object (.*?)> (.*?)'", loop.content)
def postprocess_loop(loop, loops, memo): if loop in memo: return memo.add(loop) if loop is None: return m = re.search("debug_merge_point\('<code object (.*?)>", loop.content) if m is None: name = '?' else: name = m.group(1) opsno = loop.content.count("\n") lastline = loop.content[loop.content.rfind("\n", 0, len(loop.content) - 2):] m = re.search('descr=<Loop(\d+)', lastline) if m is not None: assert isinstance(loop, FinalBlock) loop.target = loops[int(m.group(1))] bcodes = loop.content.count('debug_merge_point') loop.linksource = "loop" + str(loop.no) loop.header = "%s loop%d\n%d operations\n%d opcodes" % (name, loop.no, opsno, bcodes) loop.header += "\n" * (opsno / 100) if bcodes == 0: loop.ratio = opsno else: loop.ratio = float(opsno) / bcodes loop.content = "Logfile at %d" % loop.startlineno loop.postprocess(loops, memo)
name = m.group(1)
name = m.group(1) + " " + m.group(2)
def postprocess_loop(loop, loops, memo): if loop in memo: return memo.add(loop) if loop is None: return m = re.search("debug_merge_point\('<code object (.*?)>", loop.content) if m is None: name = '?' else: name = m.group(1) opsno = loop.content.count("\n") lastline = loop.content[loop.content.rfind("\n", 0, len(loop.content) - 2):] m = re.search('descr=<Loop(\d+)', lastline) if m is not None: assert isinstance(loop, FinalBlock) loop.target = loops[int(m.group(1))] bcodes = loop.content.count('debug_merge_point') loop.linksource = "loop" + str(loop.no) loop.header = "%s loop%d\n%d operations\n%d opcodes" % (name, loop.no, opsno, bcodes) loop.header += "\n" * (opsno / 100) if bcodes == 0: loop.ratio = opsno else: loop.ratio = float(opsno) / bcodes loop.content = "Logfile at %d" % loop.startlineno loop.postprocess(loops, memo)
dll = goal_dir.join('libpypy-c.exe.dll')
dll = goal_dir / 'libpypy-c.dll'
def filenames_from_platform(platform): if platform == 'win32': files = [goal_dir / 'pypy-c.exe'] dll = goal_dir.join('libpypy-c.exe.dll') if dll.check(): files.append(dll) else: files = [goal_dir / 'pypy-c'] for file in files: if not file.check(): print "Necessary file (%s) missing, build pypy" % file sys.exit(1) return files
elif arg == '-O':
elif arg == '-O' or arg == '-OO':
def parse_command_line(argv): go_interactive = False run_command = False import_site = True i = 0 run_module = False run_stdin = False warnoptions = [] unbuffered = False while i < len(argv): arg = argv[i] if not arg.startswith('-'): break if arg == '-i': go_interactive = True elif arg.startswith('-c'): cmd, i = get_argument('-c', argv, i) argv[i] = '-c' run_command = True break elif arg == '-u': unbuffered = True elif arg == '-O': pass elif arg == '--version' or arg == '-V': print "Python", sys.version return elif arg == '--info': print_info() return elif arg == '-h' or arg == '--help': print_help() return elif arg == '-S': import_site = False elif arg == '-': run_stdin = True break # not an option but a file name representing stdin elif arg.startswith('-m'): module, i = get_argument('-m', argv, i) argv[i] = module run_module = True break elif arg.startswith('-W'): warnoptions, i = get_argument('-W', argv, i) elif arg.startswith('--jit'): jitparam, i = get_argument('--jit', argv, i) if 'pypyjit' not in sys.builtin_module_names: print >> sys.stderr, ("Warning: No jit support in %s" % (sys.executable,)) else: import pypyjit pypyjit.set_param(jitparam) elif arg == '--': i += 1 break # terminates option list else: raise CommandLineError('unrecognized option %r' % (arg,)) i += 1 sys.argv[:] = argv[i:] # don't change the list that sys.argv is bound to if not sys.argv: # (relevant in case of "reload(sys)") sys.argv.append('') run_stdin = True return locals()
s = py.path.local(__file__).read()
filename = __file__ if filename.lower().endswith('.pyc'): filename = filename[:-1] s = py.path.local(filename).read()
def test_parse_this(self): s = py.path.local(__file__).read() t = self.parse(s) t = self.ToAST.transform(t)
if prefix and len(name) != len(filename):
if prefix and not prefix.endswith(ZIPSEP):
def descr_new_zipimporter(space, w_type, name): w = space.wrap w_ZipImportError = space.getattr(space.getbuiltinmodule('zipimport'), w('ZipImportError')) ok = False parts_ends = [i for i in range(0, len(name)) if name[i] == os.path.sep or name[i] == ZIPSEP] parts_ends.append(len(name)) filename = "" # make annotator happy for i in parts_ends: filename = name[:i] if not filename: filename = os.path.sep try: s = os.stat(filename) except OSError: raise operationerrfmt(w_ZipImportError, "Cannot find name %s", filename) if not stat.S_ISDIR(s.st_mode): ok = True break if not ok: raise operationerrfmt(w_ZipImportError, "Did not find %s to be a valid zippath", name) try: w_result = zip_cache.get(filename) if w_result is None: raise operationerrfmt(w_ZipImportError, "Cannot import %s from zipfile, recursion detected or" "already tried and failed", name) except KeyError: zip_cache.cache[filename] = None try: zip_file = RZipFile(filename, 'r') except (BadZipfile, OSError): raise operationerrfmt(w_ZipImportError, "%s seems not to be a zipfile", filename) zip_file.close() prefix = name[len(filename):] if prefix.startswith(os.path.sep) or prefix.startswith(ZIPSEP): prefix = prefix[1:] if prefix and len(name) != len(filename): prefix += ZIPSEP w_result = space.wrap(W_ZipImporter(space, name, filename, zip_file.NameToInfo, prefix)) zip_cache.set(filename, w_result) return w_result
rstack.resume_point("CALL_METHOD", f, n_args, returns=w_result)
rstack.resume_point("CALL_METHOD_no_kwargs", f, n_args, returns=w_result)
def CALL_METHOD(f, oparg, *ignored): # opargs contains the arg, and kwarg count, excluding the implicit 'self' n_args = oparg & 0xff n_kwargs = (oparg >> 8) & 0xff w_self = f.peekvalue(n_args + (2 * n_kwargs)) w_callable = f.peekvalue(n_args + (2 * n_kwargs) + 1) n = n_args + (w_self is not None) if not n_kwargs: try: w_result = f.space.call_valuestack(w_callable, n, f) rstack.resume_point("CALL_METHOD", f, n_args, returns=w_result) finally: f.dropvalues(n_args + 2) else: keywords = [None] * n_kwargs keywords_w = [None] * n_kwargs while True: n_kwargs -= 1 if n_kwargs < 0: break w_value = f.popvalue() w_key = f.popvalue() key = f.space.str_w(w_key) keywords[n_kwargs] = key keywords_w[n_kwargs] = w_value arguments = f.popvalues(n) args = f.argument_factory(arguments, keywords, keywords_w, None, None) try: w_result = f.space.call_args(w_callable, args) rstack.resume_point("CALL_METHOD", f, returns=w_result) finally: f.dropvalues(1 + (w_self is None)) f.pushvalue(w_result)
assert module.from_unsignedlong() == (1<<32) - 1
import sys if sys.maxint < 1<<32: assert module.from_unsignedlong() == (1<<32) - 1 else: assert module.from_unsignedlong() == (1<<64) - 1
def test_fromunsignedlong(self): module = self.import_extension('foo', [ ("from_unsignedlong", "METH_NOARGS", """ return PyLong_FromUnsignedLong((unsigned long)-1); """)]) assert module.from_unsignedlong() == (1<<32) - 1
assert not pypypolicy.look_inside_function(id__ANY)
assert pypypolicy.look_inside_function(id__ANY)
def test_id_any(): from pypy.objspace.std.default import id__ANY assert not pypypolicy.look_inside_function(id__ANY)
assert string_to_w_long(space, s).longval() == expected
assert string_to_bigint(s).tolong() == expected
def test_string_to_int(self): space = self.space cases = [('0', 0), ('1', 1), ('9', 9), ('10', 10), ('09', 9), ('0000101', 101), # not octal unless base 0 or 8 ('5123', 5123), (' 0', 0), ('0 ', 0), (' \t \n 32313 \f \v \r \n\r ', 32313), ('+12', 12), ('-5', -5), ('- 5', -5), ('+ 5', 5), (' -123456789 ', -123456789), ] for s, expected in cases: assert string_to_int(s) == expected assert string_to_w_long(space, s).longval() == expected
def test_string_to_w_long(self): space = self.space assert string_to_w_long(space, '123L').longval() == 123 assert string_to_w_long(space, '123L ').longval() == 123 raises(ParseStringError, string_to_w_long, space, 'L') raises(ParseStringError, string_to_w_long, space, 'L ') assert string_to_w_long(space, '123L', 4).longval() == 27 assert string_to_w_long(space, '123L', 30).longval() == 27000 + 1800 + 90 + 21 assert string_to_w_long(space, '123L', 22).longval() == 10648 + 968 + 66 + 21 assert string_to_w_long(space, '123L', 21).longval() == 441 + 42 + 3 assert string_to_w_long(space, '1891234174197319').longval() == 1891234174197319
def test_string_to_bigint(self): assert string_to_bigint('123L').tolong() == 123 assert string_to_bigint('123L ').tolong() == 123 raises(ParseStringError, string_to_bigint, 'L') raises(ParseStringError, string_to_bigint, 'L ') assert string_to_bigint('123L', 4).tolong() == 27 assert string_to_bigint('123L', 30).tolong() == 27000 + 1800 + 90 + 21 assert string_to_bigint('123L', 22).tolong() == 10648 + 968 + 66 + 21 assert string_to_bigint('123L', 21).tolong() == 441 + 42 + 3 assert string_to_bigint('1891234174197319').tolong() == 1891234174197319
def test_string_to_w_long(self): space = self.space assert string_to_w_long(space, '123L').longval() == 123 assert string_to_w_long(space, '123L ').longval() == 123 raises(ParseStringError, string_to_w_long, space, 'L') raises(ParseStringError, string_to_w_long, space, 'L ') assert string_to_w_long(space, '123L', 4).longval() == 27 assert string_to_w_long(space, '123L', 30).longval() == 27000 + 1800 + 90 + 21 assert string_to_w_long(space, '123L', 22).longval() == 10648 + 968 + 66 + 21 assert string_to_w_long(space, '123L', 21).longval() == 441 + 42 + 3 assert string_to_w_long(space, '1891234174197319').longval() == 1891234174197319
os.write(12312312, "xxx")
os.write(bad_fd, "xxx")
def g(): try: os.write(12312312, "xxx") except OSError: pass return get_errno()