[pypy-commit] pypy default: Unsure if "instance_ptr_iszero" and "instance_ptr_nonzero" are meant to
Author: Armin Rigo Branch: Changeset: r69279:c9f9e30aac58 Date: 2014-02-23 09:08 +0100 http://bitbucket.org/pypy/pypy/changeset/c9f9e30aac58/ Log:Unsure if "instance_ptr_iszero" and "instance_ptr_nonzero" are meant to appear or not during codewriting. Right now they do, and then metainterp crashes because they are not actually implemented. Fix? diff --git a/rpython/jit/codewriter/jtransform.py b/rpython/jit/codewriter/jtransform.py --- a/rpython/jit/codewriter/jtransform.py +++ b/rpython/jit/codewriter/jtransform.py @@ -967,8 +967,7 @@ if self._is_rclass_instance(op.args[0]): assert self._is_rclass_instance(op.args[1]) op = SpaceOperation('instance_ptr_eq', op.args, op.result) -prefix = 'instance_' -op1 = self._rewrite_equality(op, prefix + 'ptr_iszero') +op1 = self._rewrite_equality(op, 'ptr_iszero') return self._rewrite_cmp_ptrs(op1) def rewrite_op_ptr_ne(self, op): @@ -976,8 +975,7 @@ if self._is_rclass_instance(op.args[0]): assert self._is_rclass_instance(op.args[1]) op = SpaceOperation('instance_ptr_ne', op.args, op.result) -prefix = 'instance_' -op1 = self._rewrite_equality(op, prefix + 'ptr_nonzero') +op1 = self._rewrite_equality(op, 'ptr_nonzero') return self._rewrite_cmp_ptrs(op1) rewrite_op_ptr_iszero = _rewrite_cmp_ptrs diff --git a/rpython/jit/codewriter/test/test_jtransform.py b/rpython/jit/codewriter/test/test_jtransform.py --- a/rpython/jit/codewriter/test/test_jtransform.py +++ b/rpython/jit/codewriter/test/test_jtransform.py @@ -705,8 +705,8 @@ c0 = const(lltype.nullptr(rclass.OBJECT)) for opname, newopname, reducedname in [ -('ptr_eq', 'instance_ptr_eq', 'instance_ptr_iszero'), -('ptr_ne', 'instance_ptr_ne', 'instance_ptr_nonzero') +('ptr_eq', 'instance_ptr_eq', 'ptr_iszero'), +('ptr_ne', 'instance_ptr_ne', 'ptr_nonzero') ]: op = SpaceOperation(opname, [v1, v2], v3) op1 = Transformer().rewrite_operation(op) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: merge heads
Author: Armin Rigo Branch: Changeset: r69280:584db7c5330f Date: 2014-02-23 09:09 +0100 http://bitbucket.org/pypy/pypy/changeset/584db7c5330f/ Log:merge heads diff --git a/pypy/module/thread/os_lock.py b/pypy/module/thread/os_lock.py --- a/pypy/module/thread/os_lock.py +++ b/pypy/module/thread/os_lock.py @@ -8,6 +8,7 @@ from pypy.interpreter.baseobjspace import W_Root from pypy.interpreter.gateway import interp2app, unwrap_spec from pypy.interpreter.typedef import TypeDef +from pypy.interpreter.error import OperationError from rpython.rlib.rarithmetic import r_longlong ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: Remove dead code
Author: Armin Rigo Branch: Changeset: r69281:5dc7a91fe1e3 Date: 2014-02-23 09:18 +0100 http://bitbucket.org/pypy/pypy/changeset/5dc7a91fe1e3/ Log:Remove dead code diff --git a/rpython/jit/codewriter/jtransform.py b/rpython/jit/codewriter/jtransform.py --- a/rpython/jit/codewriter/jtransform.py +++ b/rpython/jit/codewriter/jtransform.py @@ -963,7 +963,6 @@ return self._rewrite_equality(op, 'int_is_true') def rewrite_op_ptr_eq(self, op): -prefix = '' if self._is_rclass_instance(op.args[0]): assert self._is_rclass_instance(op.args[1]) op = SpaceOperation('instance_ptr_eq', op.args, op.result) @@ -971,7 +970,6 @@ return self._rewrite_cmp_ptrs(op1) def rewrite_op_ptr_ne(self, op): -prefix = '' if self._is_rclass_instance(op.args[0]): assert self._is_rclass_instance(op.args[1]) op = SpaceOperation('instance_ptr_ne', op.args, op.result) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: Copy the py3k logic in Condition.wait()
Author: Armin Rigo Branch: Changeset: r69282:8d88f18cc867 Date: 2014-02-23 09:59 +0100 http://bitbucket.org/pypy/pypy/changeset/8d88f18cc867/ Log:Copy the py3k logic in Condition.wait() diff --git a/lib-python/2.7/threading.py b/lib-python/2.7/threading.py --- a/lib-python/2.7/threading.py +++ b/lib-python/2.7/threading.py @@ -244,22 +244,11 @@ if __debug__: self._note("%s.wait(): got it", self) else: -# Balancing act: We can't afford a pure busy loop, so we -# have to sleep; but if we sleep the whole timeout time, -# we'll be unresponsive. The scheme here sleeps very -# little at first, longer as time goes on, but never longer -# than 20 times per second (or the timeout time remaining). -endtime = _time() + timeout -delay = 0.0005 # 500 us -> initial delay of 1 ms -while True: -gotit = waiter.acquire(0) -if gotit: -break -remaining = endtime - _time() -if remaining <= 0: -break -delay = min(delay * 2, remaining, .05) -_sleep(delay) +# PyPy patch: use _py3k_acquire() +if timeout > 0: +gotit = waiter._py3k_acquire(True, timeout) +else: +gotit = waiter.acquire(False) if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: Support possibly-misaligned raw-storage getitems and setitems.
Author: Armin Rigo Branch: Changeset: r69283:6b8aaf94225a Date: 2014-02-23 10:35 +0100 http://bitbucket.org/pypy/pypy/changeset/6b8aaf94225a/ Log:Support possibly-misaligned raw-storage getitems and setitems. diff --git a/rpython/rlib/rawstorage.py b/rpython/rlib/rawstorage.py --- a/rpython/rlib/rawstorage.py +++ b/rpython/rlib/rawstorage.py @@ -18,17 +18,87 @@ def raw_storage_getitem(TP, storage, index): "NOT_RPYTHON" +_check_alignment(TP, index) return rffi.cast(rffi.CArrayPtr(TP), rffi.ptradd(storage, index))[0] def raw_storage_setitem(storage, index, item): "NOT_RPYTHON" -TP = rffi.CArrayPtr(lltype.typeOf(item)) -rffi.cast(TP, rffi.ptradd(storage, index))[0] = item +TP = lltype.typeOf(item) +_check_alignment(TP, index) +rffi.cast(rffi.CArrayPtr(TP), rffi.ptradd(storage, index))[0] = item @specialize.arg(1) def free_raw_storage(storage, track_allocation=True): lltype.free(storage, flavor='raw', track_allocation=track_allocation) +# +# +# Support for possibly-unaligned accesses + +from rpython.jit.backend import detect_cpu +try: +misaligned_is_fine = detect_cpu.autodetect().startswith('x86') +except detect_cpu.ProcessorAutodetectError: +misaligned_is_fine = False + + +class AlignmentError(NotImplementedError): +"Means that raw_storage_{get,set}item was used on unaligned memory" + +# Tweak? It seems a reasonable value for any system out there: requiring +# an aligned access to be up to 8-bytes-aligned, even for 64-bit data +# types on 32-bit systems. +MAXIMUM_ALIGNMENT = 8 + +@specialize.memo() +def _get_alignment_mask(TP): +size = rffi.sizeof(TP) +alignment = 1 +while (size & alignment) == 0 and alignment < MAXIMUM_ALIGNMENT: +alignment *= 2 +return alignment - 1 + +def _check_alignment(TP, index): +"""Check that the 'index' does indeed have the maximum alignment +for the given type.""" +mask = _get_alignment_mask(TP) +if (index & mask) != 0: +raise AlignmentError + +@specialize.ll() +def raw_storage_getitem_unaligned(TP, storage, index): +if misaligned_is_fine: +return raw_storage_getitem(TP, storage, index) +mask = _get_alignment_mask(TP) +if (index & mask) == 0: +return raw_storage_getitem(TP, storage, index) +ptr = rffi.ptradd(storage, index) +with lltype.scoped_alloc(rffi.CArray(TP), 1) as s_array: +rffi.c_memcpy(rffi.cast(rffi.VOIDP, s_array), + rffi.cast(rffi.VOIDP, ptr), + rffi.sizeof(TP)) +return rffi.cast(rffi.CArrayPtr(TP), s_array)[0] + +@specialize.ll() +def raw_storage_setitem_unaligned(storage, index, item): +if misaligned_is_fine: +raw_storage_setitem(storage, index, item) +return +TP = lltype.typeOf(item) +mask = _get_alignment_mask(TP) +if (index & mask) == 0: +raw_storage_setitem(storage, index, item) +return +ptr = rffi.ptradd(storage, index) +with lltype.scoped_alloc(rffi.CArray(TP), 1) as s_array: +rffi.cast(rffi.CArrayPtr(TP), s_array)[0] = item +rffi.c_memcpy(rffi.cast(rffi.VOIDP, ptr), + rffi.cast(rffi.VOIDP, s_array), + rffi.sizeof(TP)) + +# + + class RawStorageGetitemEntry(ExtRegistryEntry): _about_ = raw_storage_getitem diff --git a/rpython/rlib/test/test_rawstorage.py b/rpython/rlib/test/test_rawstorage.py --- a/rpython/rlib/test/test_rawstorage.py +++ b/rpython/rlib/test/test_rawstorage.py @@ -1,23 +1,91 @@ +import py +import sys +from rpython.rtyper.lltypesystem import lltype +from rpython.rlib import rawstorage +from rpython.rlib.rawstorage import alloc_raw_storage, free_raw_storage,\ + raw_storage_setitem, raw_storage_getitem, AlignmentError,\ + raw_storage_setitem_unaligned, raw_storage_getitem_unaligned +from rpython.rtyper.test.tool import BaseRtypingTest +from rpython.translator.c.test.test_genc import compile -from rpython.rtyper.lltypesystem import lltype -from rpython.rlib.rawstorage import alloc_raw_storage, free_raw_storage,\ - raw_storage_setitem, raw_storage_getitem -from rpython.rtyper.test.tool import BaseRtypingTest def test_untranslated_storage(): +r = alloc_raw_storage(37) +raw_storage_setitem(r, 8, 1<<30) +res = raw_storage_getitem(lltype.Signed, r, 8) +assert res == 1<<30 +raw_storage_setitem(r, 8, 3.14) +res = raw_storage_getitem(lltype.Float, r, 8) +assert res == 3.14 +py.test.raises(AlignmentError, raw_storage_getitem, lltype.Signed, r, 3) +py.test.raises(AlignmentError, raw_storage_setitem, r, 3, 42.5) +free_raw_storage(r) + +def test_untranslated_storage_unaligned(monkeypatch): +monkeypatch.setattr(rawstorage, 'misaligned_is_fine', False) r = alloc_raw_storage(15) -raw_storage_setitem(r, 3, 1<<30) -res = raw_storage_getit
[pypy-commit] stmgc c7-refactor: Tweaks
Author: Armin Rigo Branch: c7-refactor Changeset: r812:027470d9d12b Date: 2014-02-23 14:25 +0100 http://bitbucket.org/pypy/stmgc/changeset/027470d9d12b/ Log:Tweaks diff --git a/c7/stm/core.c b/c7/stm/core.c --- a/c7/stm/core.c +++ b/c7/stm/core.c @@ -128,8 +128,14 @@ uint8_t old_rv = STM_SEGMENT->transaction_read_version; STM_SEGMENT->transaction_read_version = old_rv + 1; -if (UNLIKELY(old_rv == 0xff)) +if (UNLIKELY(old_rv >= 0xfe)) { +/* reset if transaction_read_version was 0xfe or 0xff. If it's + 0xff, then we need it because the new value would overflow to + 0. But resetting it already from 0xfe is better for short + or medium transactions: at the next minor collection we'll + still have one free number to increase to. */ reset_transaction_read_version(); +} STM_PSEGMENT->min_read_version_outside_nursery = STM_SEGMENT->transaction_read_version; diff --git a/c7/stm/nursery.c b/c7/stm/nursery.c --- a/c7/stm/nursery.c +++ b/c7/stm/nursery.c @@ -245,18 +245,19 @@ static void trace_and_drag_out_of_nursery(object_t *obj) { -if (is_in_shared_pages(obj)) { -/* the object needs fixing only in one copy, because all copies - are shared and identical. */ -char *realobj = (char *)REAL_ADDRESS(stm_object_pages, obj); +long i; +for (i = 0; i < NB_SEGMENTS; i++) { +struct object_s *realobj = +(struct object_s *)REAL_ADDRESS(get_segment_base(i), obj); + +realobj->stm_flags &= ~GCFLAG_WRITE_BARRIER_CALLED; + stmcb_trace((struct object_s *)realobj, &minor_trace_if_young); -} -else { -/* every segment needs fixing */ -long i; -for (i = 0; i < NB_SEGMENTS; i++) { -char *realobj = (char *)REAL_ADDRESS(get_segment_base(i), obj); -stmcb_trace((struct object_s *)realobj, &minor_trace_if_young); + +if (i == 0 && is_in_shared_pages(obj)) { +/* the object needs fixing only in one copy, because all copies + are shared and identical. */ +break; } } } @@ -274,9 +275,9 @@ if ((obj->stm_flags & GCFLAG_WRITE_BARRIER_CALLED) == 0) continue; -/* Remove the flag GCFLAG_WRITE_BARRIER_CALLED. No live object - should have this flag set after a nursery collection. */ -obj->stm_flags &= ~GCFLAG_WRITE_BARRIER_CALLED; +/* The flag GCFLAG_WRITE_BARRIER_CALLED is going to be removed: + no live object should have this flag set after a nursery + collection. It is done in either one or NB_SEGMENTS copies. */ /* Trace the 'obj' to replace pointers to nursery with pointers outside the nursery, possibly forcing nursery objects out ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] stmgc c7-refactor: A first real test for nursery collection. Fails
Author: Armin Rigo Branch: c7-refactor Changeset: r813:07aa2f23e825 Date: 2014-02-23 14:40 +0100 http://bitbucket.org/pypy/stmgc/changeset/07aa2f23e825/ Log:A first real test for nursery collection. Fails diff --git a/c7/stm/gcpage.c b/c7/stm/gcpage.c --- a/c7/stm/gcpage.c +++ b/c7/stm/gcpage.c @@ -24,10 +24,6 @@ free_uniform_pages = NULL; } -//static void check_gcpage_still_shared(void) -//{ -////...; -//} #define GCPAGE_NUM_PAGES 20 diff --git a/c7/stm/gcpage.h b/c7/stm/gcpage.h --- a/c7/stm/gcpage.h +++ b/c7/stm/gcpage.h @@ -43,7 +43,6 @@ static void setup_gcpage(void); static void teardown_gcpage(void); -//static void check_gcpage_still_shared(void); static char *allocate_outside_nursery_large(uint64_t size); diff --git a/c7/stm/nursery.c b/c7/stm/nursery.c --- a/c7/stm/nursery.c +++ b/c7/stm/nursery.c @@ -29,6 +29,7 @@ static union { struct { uint64_t used;/* number of bytes from the nursery used so far */ +uint64_t initial_value_of_used; }; char reserved[64]; } nursery_ctl __attribute__((aligned(64))); @@ -51,6 +52,7 @@ static void teardown_nursery(void) { list_free(old_objects_pointing_to_young); +nursery_ctl.initial_value_of_used = 0; } static inline bool _is_in_nursery(object_t *obj) @@ -289,7 +291,7 @@ static void reset_nursery(void) { /* reset the global amount-of-nursery-used-so-far */ -nursery_ctl.used = 0; +nursery_ctl.used = nursery_ctl.initial_value_of_used; /* reset the write locks */ memset(write_locks + ((NURSERY_START >> 4) - READMARKER_START), @@ -332,7 +334,7 @@ if (old_end > NURSERY_START) { char *creation_markers = REAL_ADDRESS(other_pseg->pub.segment_base, NURSERY_START >> 8); -assert(old_end < NURSERY_START + NURSERY_SIZE); +assert(old_end <= NURSERY_START + NURSERY_SIZE); memset(creation_markers, 0, (old_end - NURSERY_START) >> 8); } else { @@ -371,8 +373,6 @@ information). */ -//check_gcpage_still_shared(); - collect_roots_in_nursery(); long i; @@ -516,5 +516,6 @@ assert(free_count == NURSERY_ALIGN(free_count)); assert(nursery_ctl.used <= NURSERY_SIZE - free_count); nursery_ctl.used = NURSERY_SIZE - free_count; +nursery_ctl.initial_value_of_used = nursery_ctl.used; } #endif diff --git a/c7/test/test_nursery.py b/c7/test/test_nursery.py --- a/c7/test/test_nursery.py +++ b/c7/test/test_nursery.py @@ -58,10 +58,31 @@ self.pop_root() # self.push_root(lp1) -lp2 = stm_allocate(16) +lp2 = stm_allocate(SOME_MEDIUM_SIZE) lp1b = self.pop_root() assert lp1b != lp1 # collection occurred +def test_several_minor_collections(self): +# make a long, ever-growing linked list of objects, in one transaction +lib._stm_set_nursery_free_count(NURSERY_SECTION_SIZE * 2) +self.start_transaction() +lp1 = stm_allocate(16) +self.push_root(lp1) +lp2 = lp1 +N = (NURSERY_SECTION_SIZE * 5) / 16 +for i in range(N): +self.push_root(lp2) +lp3 = stm_allocate(16) +lp2 = self.pop_root() +stm_set_ref(lp2, 0, lp3) +lp2 = lp3 +lp1 = self.pop_root() +lp2 = lp1 +for i in range(N): +assert lp2 +lp2 = stm_get_ref(lp2, 0) +assert lp2 == lp3 + def test_many_allocs(self): obj_size = 1024 num = (lib.NB_NURSERY_PAGES * 4096) / obj_size + 100 # more than what fits in the nursery ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] stmgc c7-refactor: Fixes for the test.
Author: Armin Rigo Branch: c7-refactor Changeset: r814:9a45fb18c2da Date: 2014-02-23 15:29 +0100 http://bitbucket.org/pypy/stmgc/changeset/9a45fb18c2da/ Log:Fixes for the test. diff --git a/c7/stm/misc.c b/c7/stm/misc.c --- a/c7/stm/misc.c +++ b/c7/stm/misc.c @@ -52,3 +52,24 @@ { return ((stm_creation_marker_t *)(((uintptr_t)obj) >> 8))->cm; } + +#ifdef STM_TESTS +object_t *_stm_enum_old_objects_pointing_to_young(void) +{ +static long index = 0; +struct list_s *lst = STM_PSEGMENT->old_objects_pointing_to_young; +if (index < list_count(lst)) +return (object_t *)list_item(lst, index++); +index = 0; +return (object_t *)-1; +} +object_t *_stm_enum_modified_objects(void) +{ +static long index = 0; +struct list_s *lst = STM_PSEGMENT->modified_objects; +if (index < list_count(lst)) +return (object_t *)list_item(lst, index++); +index = 0; +return (object_t *)-1; +} +#endif diff --git a/c7/stm/nursery.c b/c7/stm/nursery.c --- a/c7/stm/nursery.c +++ b/c7/stm/nursery.c @@ -159,6 +159,7 @@ /* Copy the object to segment 0 (as a first step) */ memcpy(copyobj, realobj, size); +((struct object_s *)copyobj)->stm_flags |= GCFLAG_WRITE_BARRIER_CALLED; nobj = (object_t *)(copyobj - stm_object_pages); @@ -193,6 +194,8 @@ for (i = 1; i < NB_SEGMENTS; i++) { uintptr_t diff = get_segment_base(i) - stm_object_pages; memcpy(copyobj + diff, realobj + diff, size); +((struct object_s *)(copyobj + diff))->stm_flags |= +GCFLAG_WRITE_BARRIER_CALLED; } } @@ -224,6 +227,7 @@ } /* Done copying the object. */ +//dprintf(("%p -> %p\n", obj, nobj)); pforwarded_array[0] = GCWORD_MOVED; pforwarded_array[1] = nobj; *pobj = nobj; diff --git a/c7/stmgc.h b/c7/stmgc.h --- a/c7/stmgc.h +++ b/c7/stmgc.h @@ -98,6 +98,8 @@ void _stm_start_safe_point(void); void _stm_stop_safe_point(void); void _stm_set_nursery_free_count(uint64_t free_count); +object_t *_stm_enum_old_objects_pointing_to_young(void); +object_t *_stm_enum_modified_objects(void); #endif #define _STM_GCFLAG_WRITE_BARRIER_CALLED 0x80 diff --git a/c7/test/support.py b/c7/test/support.py --- a/c7/test/support.py +++ b/c7/test/support.py @@ -76,50 +76,12 @@ void _stm_set_nursery_free_count(uint64_t free_count); ssize_t stmcb_size_rounded_up(struct object_s *obj); + +object_t *_stm_enum_old_objects_pointing_to_young(void); +object_t *_stm_enum_modified_objects(void); """) -TEMPORARILY_DISABLED = """ -void stm_start_inevitable_transaction(stm_thread_local_t *tl); - -void _stm_minor_collect(); - -void *memset(void *s, int c, size_t n); -extern size_t stmcb_size(struct object_s *); -extern void stmcb_trace(struct object_s *, void (object_t **)); - -uint8_t _stm_get_flags(object_t *obj); -uint8_t stm_get_page_flag(int pagenum); -enum { -SHARED_PAGE=0, -REMAPPING_PAGE, -PRIVATE_PAGE, -}; /* flag_page_private */ - -enum { -GCFLAG_WRITE_BARRIER = 1, -GCFLAG_NOT_COMMITTED = 2, -GCFLAG_MOVED = 4, -}; - -void stm_largemalloc_init(char *data_start, size_t data_size); -int stm_largemalloc_resize_arena(size_t new_size); - -object_t *stm_large_malloc(size_t request_size); -void stm_large_free(object_t *data); - -void _stm_large_dump(void); -char *_stm_largemalloc_data_start(void); - -void _stm_move_object(object_t* obj, char *src, char *dst); -size_t _stm_data_size(struct object_s *data); -void _stm_chunk_pages(struct object_s *data, uintptr_t *start, uintptr_t *num); - -void stm_become_inevitable(char* msg); -void stm_start_inevitable_transaction(); -""" - - lib = ffi.verify(''' #include #include @@ -222,6 +184,9 @@ void _set_ptr(object_t *obj, int n, object_t *v) { +int nrefs = ((myobj_t*)obj)->type_id - 421420; +assert(n < nrefs); + stm_char *field_addr = ((stm_char*)obj); field_addr += SIZEOF_MYOBJ; /* header */ field_addr += n * sizeof(void*); /* field */ @@ -231,6 +196,9 @@ object_t * _get_ptr(object_t *obj, int n) { +int nrefs = ((myobj_t*)obj)->type_id - 421420; +assert(n < nrefs); + stm_char *field_addr = ((stm_char*)obj); field_addr += SIZEOF_MYOBJ; /* header */ field_addr += n * sizeof(void*); /* field */ @@ -396,6 +364,15 @@ def stm_get_flags(o): return lib._stm_get_flags(o) +def old_objects_pointing_to_young(): +return list(iter(lib._stm_enum_old_objects_pointing_to_young, + ffi.cast("object_t *", -1))) + +def modified_objects(): +return list(iter(lib._stm_enum_modified_objects, + ffi.cast("object_t *", -1))) + + SHADOWSTACK_LENGTH = 100 _keepalive = weakref.WeakKeyDictionary() diff --git a/c7/test/test_basic.py b/c7/test/test_basic.py --- a/c7/test/test_basic.py +++ b/c7/test/test_basic.py @@ -50,6 +50,7 @@ assert stm_was_written(lp1) stm_write(lp1) assert stm_was_wr
[pypy-commit] pypy default: Fix a warning in the C code
Author: Armin Rigo Branch: Changeset: r69284:9535a395a13f Date: 2014-02-23 16:25 +0100 http://bitbucket.org/pypy/pypy/changeset/9535a395a13f/ Log:Fix a warning in the C code diff --git a/rpython/rlib/_stacklet_asmgcc.py b/rpython/rlib/_stacklet_asmgcc.py --- a/rpython/rlib/_stacklet_asmgcc.py +++ b/rpython/rlib/_stacklet_asmgcc.py @@ -189,7 +189,7 @@ pypy_asm_stackwalk2 = rffi.llexternal('pypy_asm_stackwalk', [FUNCNOARG_P, ASM_FRAMEDATA_HEAD_PTR], - _c.handle, sandboxsafe=True, + lltype.Signed, sandboxsafe=True, _nowrapper=True) @@ -273,6 +273,7 @@ # h = pypy_asm_stackwalk2(llhelper(FUNCNOARG_P, _new_callback), alternateanchor) +h = rffi.cast(_c.handle, h) # llop.gc_reattach_callback_pieces(lltype.Void, callback_pieces) return self.get_result_suspstack(h) @@ -292,6 +293,7 @@ # h = pypy_asm_stackwalk2(llhelper(FUNCNOARG_P, _switch_callback), alternateanchor) +h = rffi.cast(_c.handle, h) # llop.gc_reattach_callback_pieces(lltype.Void, callback_pieces) if not h: ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] stmgc c7-refactor: Failing test
Author: Armin Rigo Branch: c7-refactor Changeset: r816:8cbb49ebda1c Date: 2014-02-23 16:32 +0100 http://bitbucket.org/pypy/stmgc/changeset/8cbb49ebda1c/ Log:Failing test diff --git a/c7/stm/nursery.c b/c7/stm/nursery.c --- a/c7/stm/nursery.c +++ b/c7/stm/nursery.c @@ -413,7 +413,7 @@ /* We just waited here, either from mutex_lock() or from cond_wait(), so we should check again if another thread did the minor collection itself */ -if (nursery_ctl.used + request_size <= NURSERY_SIZE) +if (request_size <= NURSERY_SIZE - nursery_ctl.used) goto exit; if (!try_wait_for_other_safe_points(SP_SAFE_POINT_CAN_COLLECT)) @@ -428,6 +428,12 @@ mutex_unlock(); } +void stm_collect(long level) +{ +assert(level == 0); +stm_minor_collection(-1); +} + // diff --git a/c7/stmgc.h b/c7/stmgc.h --- a/c7/stmgc.h +++ b/c7/stmgc.h @@ -254,6 +254,9 @@ _stm_collectable_safe_point(); } +/* Forces a collection. */ +void stm_collect(long level); + /* END */ diff --git a/c7/test/support.py b/c7/test/support.py --- a/c7/test/support.py +++ b/c7/test/support.py @@ -79,6 +79,8 @@ object_t *_stm_enum_old_objects_pointing_to_young(void); object_t *_stm_enum_modified_objects(void); + +void stm_collect(long level); """) @@ -348,7 +350,7 @@ raise Conflict() def stm_minor_collect(): -lib._stm_minor_collect() +lib.stm_collect(0) def stm_get_page_flag(pagenum): return lib.stm_get_page_flag(pagenum) diff --git a/c7/test/test_nursery.py b/c7/test/test_nursery.py --- a/c7/test/test_nursery.py +++ b/c7/test/test_nursery.py @@ -129,11 +129,16 @@ assert young def test_larger_than_section(self): -obj_size = lib.NURSERY_SECTION + 16 +obj_size = NURSERY_SECTION_SIZE + 16 self.start_transaction() -new = stm_allocate(obj_size) -assert not is_in_nursery(new) +seen = set() +for i in range(10): +stm_minor_collect() +new = stm_allocate(obj_size) +assert not is_in_nursery(new) +seen.add(new) +assert len(seen) < 5 # addresses are reused def test_reset_partial_alloc_pages(self): self.start_transaction() ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] stmgc c7-refactor: Next test passes
Author: Armin Rigo Branch: c7-refactor Changeset: r815:8a68e946b423 Date: 2014-02-23 15:34 +0100 http://bitbucket.org/pypy/stmgc/changeset/8a68e946b423/ Log:Next test passes diff --git a/c7/test/support.py b/c7/test/support.py --- a/c7/test/support.py +++ b/c7/test/support.py @@ -373,7 +373,7 @@ ffi.cast("object_t *", -1))) -SHADOWSTACK_LENGTH = 100 +SHADOWSTACK_LENGTH = 1000 _keepalive = weakref.WeakKeyDictionary() def _allocate_thread_local(): diff --git a/c7/test/test_nursery.py b/c7/test/test_nursery.py --- a/c7/test/test_nursery.py +++ b/c7/test/test_nursery.py @@ -105,18 +105,21 @@ assert lp2 == lp3 def test_many_allocs(self): +lib._stm_set_nursery_free_count(NURSERY_SECTION_SIZE * 2) obj_size = 1024 -num = (lib.NB_NURSERY_PAGES * 4096) / obj_size + 100 # more than what fits in the nursery +num = (NURSERY_SECTION_SIZE * 4) / obj_size + 41 self.start_transaction() for i in range(num): new = stm_allocate(obj_size) +stm_set_char(new, chr(i % 255)) self.push_root(new) old = [] young = [] -for _ in range(num): +for i in reversed(range(num)): r = self.pop_root() +assert stm_get_char(r) == chr(i % 255) if is_in_nursery(r): young.append(r) else: ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: fix segfault on np.fromstring of record type
Author: Brian Kearns Branch: Changeset: r69288:cd632d18a772 Date: 2014-02-23 13:50 -0500 http://bitbucket.org/pypy/pypy/changeset/cd632d18a772/ Log:fix segfault on np.fromstring of record type diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -3058,6 +3058,7 @@ v = fromstring("abcd", dtype="|S2") assert v[0] == "ab" assert v[1] == "cd" + v = fromstring('@\x01\x99\x99\x99\x99\x99\x9a\xbf\xf1\x99\x99\x99\x99\x99\x9a', dtype=dtype('>c16')) assert v.tostring() == \ @@ -3073,6 +3074,18 @@ assert v.real == 2.2 assert v.imag == -1.1 +d = [('f0', 'i4'), ('f1', 'u2', (2, 3))] +if '__pypy__' not in sys.builtin_module_names: +r = fromstring('abcdefghijklmnop'*4*3, dtype=d) +assert (r[0:3:2]['f1'] == r['f1'][0:3:2]).all() +assert (r[0:3:2]['f1'][0] == r[0:3:2][0]['f1']).all() +assert (r[0:3:2]['f1'][0][()] == r[0:3:2][0]['f1'][()]).all() +assert r[0:3:2]['f1'][0].strides == r[0:3:2][0]['f1'].strides +else: +exc = raises(NotImplementedError, fromstring, + 'abcdefghijklmnop'*4*3, dtype=d) +assert exc.value[0] == "fromstring not implemented for record types" + def test_fromstring_types(self): from numpypy import fromstring, array, dtype a = fromstring('\xFF', dtype='int8') diff --git a/pypy/module/micronumpy/types.py b/pypy/module/micronumpy/types.py --- a/pypy/module/micronumpy/types.py +++ b/pypy/module/micronumpy/types.py @@ -1,7 +1,7 @@ import functools import math -from pypy.interpreter.error import OperationError +from pypy.interpreter.error import OperationError, oefmt from pypy.module.micronumpy import interp_boxes from pypy.module.micronumpy import support from pypy.module.micronumpy.arrayimpl.voidbox import VoidBoxStorage @@ -1897,6 +1897,10 @@ itemtype.store(arr, 0, ofs, w_box) return interp_boxes.W_VoidBox(arr, 0, dtype) +def runpack_str(self, space, s): +raise oefmt(space.w_NotImplementedError, +"fromstring not implemented for record types") + def store(self, arr, i, ofs, box): assert isinstance(box, interp_boxes.W_VoidBox) self._store(arr.storage, i, ofs, box, box.dtype.get_size()) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: support dtype from commastring
Author: Brian Kearns Branch: Changeset: r69286:b744291da355 Date: 2014-02-23 02:39 -0500 http://bitbucket.org/pypy/pypy/changeset/b744291da355/ Log:support dtype from commastring diff --git a/pypy/module/micronumpy/appbridge.py b/pypy/module/micronumpy/appbridge.py --- a/pypy/module/micronumpy/appbridge.py +++ b/pypy/module/micronumpy/appbridge.py @@ -4,6 +4,7 @@ w__mean = None w__var = None w__std = None +w__commastring = None w_array_repr = None w_array_str = None diff --git a/pypy/module/micronumpy/interp_dtype.py b/pypy/module/micronumpy/interp_dtype.py --- a/pypy/module/micronumpy/interp_dtype.py +++ b/pypy/module/micronumpy/interp_dtype.py @@ -1,3 +1,4 @@ +from pypy.interpreter.argument import Arguments from pypy.interpreter.baseobjspace import W_Root from pypy.interpreter.error import OperationError, oefmt from pypy.interpreter.gateway import interp2app, unwrap_spec @@ -8,6 +9,7 @@ from rpython.rlib.rarithmetic import LONG_BIT, r_longlong, r_ulonglong from rpython.rtyper.lltypesystem import rffi from rpython.rlib import jit +from pypy.module.micronumpy.appbridge import get_appbridge_cache from pypy.module.micronumpy.conversion_utils import byteorder_converter from pypy.module.micronumpy.constants import * @@ -391,9 +393,17 @@ "dtype from dict")) -def dtype_from_spec(space, name): -raise OperationError(space.w_NotImplementedError, space.wrap( -"dtype from spec")) +def dtype_from_spec(space, w_spec): +w_lst = get_appbridge_cache(space).call_method(space, +'numpy.core._internal', '_commastring', Arguments(space, [w_spec])) +if not space.isinstance_w(w_lst, space.w_list) or space.len_w(w_lst) < 1: +raise oefmt(space.w_RuntimeError, +"_commastring is not returning a list with len >= 1") +if space.len_w(w_lst) == 1: +return descr__new__(space, space.gettypefor(W_Dtype), +space.getitem(w_lst, space.wrap(0))) +else: +return dtype_from_list(space, w_lst) def descr__new__(space, w_subtype, w_dtype, w_align=None, w_copy=None, w_shape=None): @@ -427,7 +437,7 @@ elif space.isinstance_w(w_dtype, space.w_str): name = space.str_w(w_dtype) if ',' in name: -return dtype_from_spec(space, name) +return dtype_from_spec(space, w_dtype) try: return cache.dtypes_by_name[name] except KeyError: diff --git a/pypy/module/micronumpy/test/test_appbridge.py b/pypy/module/micronumpy/test/test_appbridge.py --- a/pypy/module/micronumpy/test/test_appbridge.py +++ b/pypy/module/micronumpy/test/test_appbridge.py @@ -9,3 +9,10 @@ op() except ImportError as e: assert str(e) == 'No module named numpy.core' + +def test_dtype_commastring(self): +import numpy as np +try: +d = np.dtype('u4,u4,u4') +except ImportError as e: +assert str(e) == 'No module named numpy.core' ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: fix dtype from commastring
Author: Brian Kearns Branch: Changeset: r69287:cf3918b33b35 Date: 2014-02-23 03:26 -0500 http://bitbucket.org/pypy/pypy/changeset/cf3918b33b35/ Log:fix dtype from commastring diff --git a/pypy/module/micronumpy/interp_dtype.py b/pypy/module/micronumpy/interp_dtype.py --- a/pypy/module/micronumpy/interp_dtype.py +++ b/pypy/module/micronumpy/interp_dtype.py @@ -357,26 +357,31 @@ self.w_box_type, endian, size=self.size) -def dtype_from_list(space, w_lst): +@specialize.arg(2) +def dtype_from_list(space, w_lst, simple): lst_w = space.listview(w_lst) fields = {} offset = 0 fieldnames = [] for i in range(len(lst_w)): w_elem = lst_w[i] -w_shape = space.newtuple([]) -if space.len_w(w_elem) == 3: -w_fldname, w_flddesc, w_shape = space.fixedview(w_elem) -if not base.issequence_w(space, w_shape): -w_shape = space.newtuple([w_shape]) +if simple: +subdtype = descr__new__(space, space.gettypefor(W_Dtype), w_elem) +fldname = 'f%d' % i else: -w_fldname, w_flddesc = space.fixedview(w_elem, 2) -subdtype = descr__new__(space, space.gettypefor(W_Dtype), w_flddesc, w_shape=w_shape) -fldname = space.str_w(w_fldname) -if fldname == '': -fldname = 'f%d' % i -if fldname in fields: -raise oefmt(space.w_ValueError, "two fields with the same name") +w_shape = space.newtuple([]) +if space.len_w(w_elem) == 3: +w_fldname, w_flddesc, w_shape = space.fixedview(w_elem) +if not base.issequence_w(space, w_shape): +w_shape = space.newtuple([w_shape]) +else: +w_fldname, w_flddesc = space.fixedview(w_elem, 2) +subdtype = descr__new__(space, space.gettypefor(W_Dtype), w_flddesc, w_shape=w_shape) +fldname = space.str_w(w_fldname) +if fldname == '': +fldname = 'f%d' % i +if fldname in fields: +raise oefmt(space.w_ValueError, "two fields with the same name") assert isinstance(subdtype, W_Dtype) fields[fldname] = (offset, subdtype) offset += subdtype.get_size() @@ -403,7 +408,7 @@ return descr__new__(space, space.gettypefor(W_Dtype), space.getitem(w_lst, space.wrap(0))) else: -return dtype_from_list(space, w_lst) +return dtype_from_list(space, w_lst, True) def descr__new__(space, w_subtype, w_dtype, w_align=None, w_copy=None, w_shape=None): @@ -446,7 +451,7 @@ return variable_dtype(space, name) raise oefmt(space.w_TypeError, 'data type "%s" not understood', name) elif space.isinstance_w(w_dtype, space.w_list): -return dtype_from_list(space, w_dtype) +return dtype_from_list(space, w_dtype, False) elif space.isinstance_w(w_dtype, space.w_tuple): w_dtype0 = space.getitem(w_dtype, space.wrap(0)) w_dtype1 = space.getitem(w_dtype, space.wrap(1)) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: merge heads
Author: Brian Kearns Branch: Changeset: r69289:d674245526d9 Date: 2014-02-23 14:01 -0500 http://bitbucket.org/pypy/pypy/changeset/d674245526d9/ Log:merge heads diff --git a/lib-python/2.7/threading.py b/lib-python/2.7/threading.py --- a/lib-python/2.7/threading.py +++ b/lib-python/2.7/threading.py @@ -244,22 +244,11 @@ if __debug__: self._note("%s.wait(): got it", self) else: -# Balancing act: We can't afford a pure busy loop, so we -# have to sleep; but if we sleep the whole timeout time, -# we'll be unresponsive. The scheme here sleeps very -# little at first, longer as time goes on, but never longer -# than 20 times per second (or the timeout time remaining). -endtime = _time() + timeout -delay = 0.0005 # 500 us -> initial delay of 1 ms -while True: -gotit = waiter.acquire(0) -if gotit: -break -remaining = endtime - _time() -if remaining <= 0: -break -delay = min(delay * 2, remaining, .05) -_sleep(delay) +# PyPy patch: use _py3k_acquire() +if timeout > 0: +gotit = waiter._py3k_acquire(True, timeout) +else: +gotit = waiter.acquire(False) if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) diff --git a/rpython/rlib/_stacklet_asmgcc.py b/rpython/rlib/_stacklet_asmgcc.py --- a/rpython/rlib/_stacklet_asmgcc.py +++ b/rpython/rlib/_stacklet_asmgcc.py @@ -189,7 +189,7 @@ pypy_asm_stackwalk2 = rffi.llexternal('pypy_asm_stackwalk', [FUNCNOARG_P, ASM_FRAMEDATA_HEAD_PTR], - _c.handle, sandboxsafe=True, + lltype.Signed, sandboxsafe=True, _nowrapper=True) @@ -273,6 +273,7 @@ # h = pypy_asm_stackwalk2(llhelper(FUNCNOARG_P, _new_callback), alternateanchor) +h = rffi.cast(_c.handle, h) # llop.gc_reattach_callback_pieces(lltype.Void, callback_pieces) return self.get_result_suspstack(h) @@ -292,6 +293,7 @@ # h = pypy_asm_stackwalk2(llhelper(FUNCNOARG_P, _switch_callback), alternateanchor) +h = rffi.cast(_c.handle, h) # llop.gc_reattach_callback_pieces(lltype.Void, callback_pieces) if not h: diff --git a/rpython/rlib/rawstorage.py b/rpython/rlib/rawstorage.py --- a/rpython/rlib/rawstorage.py +++ b/rpython/rlib/rawstorage.py @@ -18,17 +18,87 @@ def raw_storage_getitem(TP, storage, index): "NOT_RPYTHON" +_check_alignment(TP, index) return rffi.cast(rffi.CArrayPtr(TP), rffi.ptradd(storage, index))[0] def raw_storage_setitem(storage, index, item): "NOT_RPYTHON" -TP = rffi.CArrayPtr(lltype.typeOf(item)) -rffi.cast(TP, rffi.ptradd(storage, index))[0] = item +TP = lltype.typeOf(item) +_check_alignment(TP, index) +rffi.cast(rffi.CArrayPtr(TP), rffi.ptradd(storage, index))[0] = item @specialize.arg(1) def free_raw_storage(storage, track_allocation=True): lltype.free(storage, flavor='raw', track_allocation=track_allocation) +# +# +# Support for possibly-unaligned accesses + +from rpython.jit.backend import detect_cpu +try: +misaligned_is_fine = detect_cpu.autodetect().startswith('x86') +except detect_cpu.ProcessorAutodetectError: +misaligned_is_fine = False + + +class AlignmentError(NotImplementedError): +"Means that raw_storage_{get,set}item was used on unaligned memory" + +# Tweak? It seems a reasonable value for any system out there: requiring +# an aligned access to be up to 8-bytes-aligned, even for 64-bit data +# types on 32-bit systems. +MAXIMUM_ALIGNMENT = 8 + +@specialize.memo() +def _get_alignment_mask(TP): +size = rffi.sizeof(TP) +alignment = 1 +while (size & alignment) == 0 and alignment < MAXIMUM_ALIGNMENT: +alignment *= 2 +return alignment - 1 + +def _check_alignment(TP, index): +"""Check that the 'index' does indeed have the maximum alignment +for the given type.""" +mask = _get_alignment_mask(TP) +if (index & mask) != 0: +raise AlignmentError + +@specialize.ll() +def raw_storage_getitem_unaligned(TP, storage, index): +if misaligned_is_fine: +return raw_storage_getitem(TP, storage, index) +mask = _get_alignment_mask(TP) +if (index & mask) == 0: +return raw_storage_getitem(TP, storage, index) +ptr = rffi.ptradd(storage, index
[pypy-commit] pypy default: generalize numpy appbridge
Author: Brian Kearns Branch: Changeset: r69285:67f86a9b9918 Date: 2014-02-23 03:42 -0500 http://bitbucket.org/pypy/pypy/changeset/67f86a9b9918/ Log:generalize numpy appbridge diff --git a/pypy/module/micronumpy/appbridge.py b/pypy/module/micronumpy/appbridge.py --- a/pypy/module/micronumpy/appbridge.py +++ b/pypy/module/micronumpy/appbridge.py @@ -4,28 +4,20 @@ w__mean = None w__var = None w__std = None -w_module = None w_array_repr = None w_array_str = None def __init__(self, space): -self.w_import = space.appexec([], """(): -def f(): -import sys -__import__('numpy.core._methods') -return sys.modules['numpy.core._methods'] -return f -""") +pass -@specialize.arg(2) -def call_method(self, space, name, w_obj, args): -w_meth = getattr(self, 'w_' + name) -if w_meth is None: -if self.w_module is None: -self.w_module = space.call_function(self.w_import) -w_meth = space.getattr(self.w_module, space.wrap(name)) -setattr(self, 'w_' + name, w_meth) -return space.call_args(w_meth, args.prepend(w_obj)) +@specialize.arg(3) +def call_method(self, space, path, name, args): +w_method = getattr(self, 'w_' + name) +if w_method is None: +w_method = space.appexec([space.wrap(path), space.wrap(name)], +"(path, name): return getattr(__import__(path, fromlist=[name]), name)") +setattr(self, 'w_' + name, w_method) +return space.call_args(w_method, args) def set_string_function(space, w_f, w_repr): cache = get_appbridge_cache(space) diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py --- a/pypy/module/micronumpy/interp_numarray.py +++ b/pypy/module/micronumpy/interp_numarray.py @@ -969,13 +969,16 @@ other_critical_dim) def descr_mean(self, space, __args__): -return get_appbridge_cache(space).call_method(space, '_mean', self, __args__) +return get_appbridge_cache(space).call_method(space, +'numpy.core._methods', '_mean', __args__.prepend(self)) def descr_var(self, space, __args__): -return get_appbridge_cache(space).call_method(space, '_var', self, __args__) +return get_appbridge_cache(space).call_method(space, +'numpy.core._methods', '_var', __args__.prepend(self)) def descr_std(self, space, __args__): -return get_appbridge_cache(space).call_method(space, '_std', self, __args__) +return get_appbridge_cache(space).call_method(space, +'numpy.core._methods', '_std', __args__.prepend(self)) # --- reduce --- diff --git a/pypy/module/micronumpy/test/test_appbridge.py b/pypy/module/micronumpy/test/test_appbridge.py new file mode 100644 --- /dev/null +++ b/pypy/module/micronumpy/test/test_appbridge.py @@ -0,0 +1,11 @@ +from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest + +class AppTestAppBridge(BaseNumpyAppTest): +def test_array_methods(self): +import numpy as np +a = np.array(1.5) +for op in [a.mean, a.var, a.std]: +try: +op() +except ImportError as e: +assert str(e) == 'No module named numpy.core' ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: fix fill for complex with non-native byteorder
Author: Brian Kearns Branch: Changeset: r69290:793aeb9704c0 Date: 2014-02-23 15:05 -0500 http://bitbucket.org/pypy/pypy/changeset/793aeb9704c0/ Log:fix fill for complex with non-native byteorder diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -2684,7 +2684,7 @@ assert arange(3)[array(1)] == 1 def test_fill(self): -from numpypy import array, empty +from numpypy import array, empty, dtype, zeros a = array([1, 2, 3]) a.fill(10) assert (a == [10, 10, 10]).all() @@ -2721,6 +2721,11 @@ else: assert tuple(i) == (123,) * 5 +a = zeros(3, dtype=dtype(complex).newbyteorder()) +a.fill(1.5+2.5j) +for i in a: +assert i == 1.5+2.5j + def test_array_indexing_bool(self): from numpypy import arange a = arange(10) diff --git a/pypy/module/micronumpy/types.py b/pypy/module/micronumpy/types.py --- a/pypy/module/micronumpy/types.py +++ b/pypy/module/micronumpy/types.py @@ -1054,13 +1054,6 @@ op = '+' if imag >= 0 or rfloat.isnan(imag) else '' return ''.join(['(', real_str, op, imag_str, ')']) -def fill(self, storage, width, box, start, stop, offset): -real, imag = self.unbox(box) -for i in xrange(start, stop, width): -raw_storage_setitem(storage, i+offset, real) -raw_storage_setitem(storage, -i+offset+rffi.sizeof(self.T), imag) - def runpack_str(self, space, s): comp = self.ComponentBoxType._get_dtype(space).itemtype l = len(s) // 2 @@ -1149,6 +1142,11 @@ def store(self, arr, i, offset, box): self._write(arr.storage, i, offset, self.unbox(box)) +def fill(self, storage, width, box, start, stop, offset): +value = self.unbox(box) +for i in xrange(start, stop, width): +self._write(storage, i, offset, value) + @complex_binary_op def add(self, v1, v2): return rcomplex.c_add(v1, v2) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: make _get_dtype elidable
Author: Maciej Fijalkowski Branch: Changeset: r69291:cd6a5bc9740c Date: 2014-02-23 22:29 +0200 http://bitbucket.org/pypy/pypy/changeset/cd6a5bc9740c/ Log:make _get_dtype elidable diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py --- a/pypy/module/micronumpy/interp_boxes.py +++ b/pypy/module/micronumpy/interp_boxes.py @@ -33,6 +33,7 @@ def new_dtype_getter(name): +@jit.elidable def _get_dtype(space): from pypy.module.micronumpy.interp_dtype import get_dtype_cache return get_dtype_cache(space).dtypes_by_name[name] ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: I hate import *
Author: Maciej Fijalkowski Branch: Changeset: r69292:15169d58e5d5 Date: 2014-02-23 22:37 +0200 http://bitbucket.org/pypy/pypy/changeset/15169d58e5d5/ Log:I hate import * diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py --- a/pypy/module/micronumpy/interp_boxes.py +++ b/pypy/module/micronumpy/interp_boxes.py @@ -16,6 +16,7 @@ from pypy.interpreter.mixedmodule import MixedModule from rpython.rtyper.lltypesystem import lltype from rpython.rlib.rstring import StringBuilder +from rpython.rlib import jit from pypy.module.micronumpy.constants import * ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: kill them then
Author: Maciej Fijalkowski Branch: Changeset: r69293:b712696ed9bb Date: 2014-02-23 22:37 +0200 http://bitbucket.org/pypy/pypy/changeset/b712696ed9bb/ Log:kill them then diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py --- a/pypy/module/micronumpy/interp_boxes.py +++ b/pypy/module/micronumpy/interp_boxes.py @@ -17,7 +17,7 @@ from rpython.rtyper.lltypesystem import lltype from rpython.rlib.rstring import StringBuilder from rpython.rlib import jit -from pypy.module.micronumpy.constants import * +from pypy.module.micronumpy.constants import NPY_LONGDOUBLELTR, NPY_CLONGDOUBLELTR MIXIN_32 = (W_IntObject.typedef,) if LONG_BIT == 32 else () ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy align_float_cast: solved differently
Author: Matti Picus Branch: align_float_cast Changeset: r69294:ad533b895e2c Date: 2014-02-23 22:37 +0200 http://bitbucket.org/pypy/pypy/changeset/ad533b895e2c/ Log:solved differently ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy closed-branches: merge heads
Author: Matti Picus Branch: closed-branches Changeset: r69295:25ae739a8d5b Date: 2014-02-23 22:43 +0200 http://bitbucket.org/pypy/pypy/changeset/25ae739a8d5b/ Log:merge heads ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: specify unaligned accesses in micronumpy
Author: Brian Kearns Branch: Changeset: r69296:b9b994201abe Date: 2014-02-23 15:45 -0500 http://bitbucket.org/pypy/pypy/changeset/b9b994201abe/ Log:specify unaligned accesses in micronumpy diff --git a/pypy/module/micronumpy/types.py b/pypy/module/micronumpy/types.py --- a/pypy/module/micronumpy/types.py +++ b/pypy/module/micronumpy/types.py @@ -9,8 +9,8 @@ from pypy.objspace.std.floatobject import float2string from pypy.objspace.std.complexobject import str_format from rpython.rlib import rfloat, clibffi, rcomplex -from rpython.rlib.rawstorage import (alloc_raw_storage, raw_storage_setitem, - raw_storage_getitem) +from rpython.rlib.rawstorage import (alloc_raw_storage, +raw_storage_getitem_unaligned, raw_storage_setitem_unaligned) from rpython.rlib.objectmodel import specialize from rpython.rlib.rarithmetic import widen, byteswap, r_ulonglong, most_neg_value_of, LONG_BIT from rpython.rtyper.lltypesystem import lltype, rffi @@ -174,7 +174,7 @@ raise NotImplementedError def _read(self, storage, i, offset): -res = raw_storage_getitem(self.T, storage, i + offset) +res = raw_storage_getitem_unaligned(self.T, storage, i + offset) if not self.native: res = byteswap(res) return res @@ -182,7 +182,7 @@ def _write(self, storage, i, offset, value): if not self.native: value = byteswap(value) -raw_storage_setitem(storage, i + offset, value) +raw_storage_setitem_unaligned(storage, i + offset, value) def read(self, arr, i, offset, dtype=None): return self.box(self._read(arr.storage, i, offset)) @@ -990,7 +990,7 @@ return self.box(float_unpack(r_ulonglong(swapped), 2)) def _read(self, storage, i, offset): -hbits = raw_storage_getitem(self._STORAGE_T, storage, i + offset) +hbits = raw_storage_getitem_unaligned(self._STORAGE_T, storage, i + offset) if not self.native: hbits = byteswap(hbits) return float_unpack(r_ulonglong(hbits), 2) @@ -1003,7 +1003,7 @@ hbits = rffi.cast(self._STORAGE_T, hbits) if not self.native: hbits = byteswap(hbits) -raw_storage_setitem(storage, i + offset, hbits) +raw_storage_setitem_unaligned(storage, i + offset, hbits) class Float32(BaseType, Float): T = rffi.FLOAT @@ -1120,8 +1120,8 @@ return real, imag def _read(self, storage, i, offset): -real = raw_storage_getitem(self.T, storage, i + offset) -imag = raw_storage_getitem(self.T, storage, i + offset + rffi.sizeof(self.T)) +real = raw_storage_getitem_unaligned(self.T, storage, i + offset) +imag = raw_storage_getitem_unaligned(self.T, storage, i + offset + rffi.sizeof(self.T)) if not self.native: real = byteswap(real) imag = byteswap(imag) @@ -1136,8 +1136,8 @@ if not self.native: real = byteswap(real) imag = byteswap(imag) -raw_storage_setitem(storage, i + offset, real) -raw_storage_setitem(storage, i + offset + rffi.sizeof(self.T), imag) +raw_storage_setitem_unaligned(storage, i + offset, real) +raw_storage_setitem_unaligned(storage, i + offset + rffi.sizeof(self.T), imag) def store(self, arr, i, offset, box): self._write(arr.storage, i, offset, self.unbox(box)) diff --git a/rpython/rlib/rawstorage.py b/rpython/rlib/rawstorage.py --- a/rpython/rlib/rawstorage.py +++ b/rpython/rlib/rawstorage.py @@ -1,4 +1,4 @@ - +from rpython.rlib.objectmodel import we_are_translated from rpython.rtyper.extregistry import ExtRegistryEntry from rpython.rtyper.lltypesystem import lltype, rffi, llmemory from rpython.annotator import model as annmodel @@ -19,12 +19,21 @@ def raw_storage_getitem(TP, storage, index): "NOT_RPYTHON" _check_alignment(TP, index) +return raw_storage_getitem_unchecked(TP, storage, index) + +def raw_storage_getitem_unchecked(TP, storage, index): +"NOT_RPYTHON" return rffi.cast(rffi.CArrayPtr(TP), rffi.ptradd(storage, index))[0] def raw_storage_setitem(storage, index, item): "NOT_RPYTHON" TP = lltype.typeOf(item) _check_alignment(TP, index) +raw_storage_setitem_unchecked(storage, index, item) + +def raw_storage_setitem_unchecked(storage, index, item): +"NOT_RPYTHON" +TP = lltype.typeOf(item) rffi.cast(rffi.CArrayPtr(TP), rffi.ptradd(storage, index))[0] = item @specialize.arg(1) @@ -68,10 +77,16 @@ @specialize.ll() def raw_storage_getitem_unaligned(TP, storage, index): if misaligned_is_fine: -return raw_storage_getitem(TP, storage, index) +if we_are_translated(): +return raw_storage_getitem(TP, storage, index) +else: +return raw_storage_getitem_unchecked(TP, storage, index) mask = _get_alignment_mask(TP) if (index & mask) == 0: -return raw_storage_getit
[pypy-commit] pypy default: merge heads
Author: Brian Kearns Branch: Changeset: r69297:510c3afd0ff0 Date: 2014-02-23 15:46 -0500 http://bitbucket.org/pypy/pypy/changeset/510c3afd0ff0/ Log:merge heads diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py --- a/pypy/module/micronumpy/interp_boxes.py +++ b/pypy/module/micronumpy/interp_boxes.py @@ -16,7 +16,8 @@ from pypy.interpreter.mixedmodule import MixedModule from rpython.rtyper.lltypesystem import lltype from rpython.rlib.rstring import StringBuilder -from pypy.module.micronumpy.constants import * +from rpython.rlib import jit +from pypy.module.micronumpy.constants import NPY_LONGDOUBLELTR, NPY_CLONGDOUBLELTR MIXIN_32 = (W_IntObject.typedef,) if LONG_BIT == 32 else () @@ -33,6 +34,7 @@ def new_dtype_getter(name): +@jit.elidable def _get_dtype(space): from pypy.module.micronumpy.interp_dtype import get_dtype_cache return get_dtype_cache(space).dtypes_by_name[name] ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: different pattern for micronumpy constants
Author: Brian Kearns Branch: Changeset: r69298:cd03cd6fcd23 Date: 2014-02-23 16:12 -0500 http://bitbucket.org/pypy/pypy/changeset/cd03cd6fcd23/ Log:different pattern for micronumpy constants diff --git a/pypy/module/micronumpy/constants.py b/pypy/module/micronumpy/constants.py --- a/pypy/module/micronumpy/constants.py +++ b/pypy/module/micronumpy/constants.py @@ -1,88 +1,88 @@ -NPY_BOOL = 0 -NPY_BYTE = 1 -NPY_UBYTE = 2 -NPY_SHORT = 3 -NPY_USHORT = 4 -NPY_INT = 5 -NPY_UINT = 6 -NPY_LONG = 7 -NPY_ULONG = 8 -NPY_LONGLONG = 9 -NPY_ULONGLONG = 10 -NPY_FLOAT = 11 -NPY_DOUBLE = 12 -NPY_LONGDOUBLE = 13 -NPY_CFLOAT = 14 -NPY_CDOUBLE = 15 -NPY_CLONGDOUBLE = 16 -NPY_OBJECT = 17 -NPY_STRING = 18 -NPY_UNICODE = 19 -NPY_VOID = 20 -NPY_DATETIME = 21 -NPY_TIMEDELTA = 22 -NPY_HALF = 23 -NPY_NTYPES = 24 -NPY_NOTYPE = 25 -NPY_CHAR = 26 -NPY_USERDEF = 256 +BOOL = 0 +BYTE = 1 +UBYTE = 2 +SHORT = 3 +USHORT = 4 +INT = 5 +UINT = 6 +LONG = 7 +ULONG = 8 +LONGLONG = 9 +ULONGLONG = 10 +FLOAT = 11 +DOUBLE = 12 +LONGDOUBLE = 13 +CFLOAT = 14 +CDOUBLE = 15 +CLONGDOUBLE = 16 +OBJECT = 17 +STRING = 18 +UNICODE = 19 +VOID = 20 +DATETIME = 21 +TIMEDELTA = 22 +HALF = 23 +NTYPES = 24 +NOTYPE = 25 +CHAR = 26 +USERDEF = 256 -NPY_BOOLLTR = '?' -NPY_BYTELTR = 'b' -NPY_UBYTELTR = 'B' -NPY_SHORTLTR = 'h' -NPY_USHORTLTR = 'H' -NPY_INTLTR = 'i' -NPY_UINTLTR = 'I' -NPY_LONGLTR = 'l' -NPY_ULONGLTR = 'L' -NPY_LONGLONGLTR = 'q' -NPY_ULONGLONGLTR = 'Q' -NPY_HALFLTR = 'e' -NPY_FLOATLTR = 'f' -NPY_DOUBLELTR = 'd' -NPY_LONGDOUBLELTR = 'g' -NPY_CFLOATLTR = 'F' -NPY_CDOUBLELTR = 'D' -NPY_CLONGDOUBLELTR = 'G' -NPY_OBJECTLTR = 'O' -NPY_STRINGLTR = 'S' -NPY_STRINGLTR2 = 'a' -NPY_UNICODELTR = 'U' -NPY_VOIDLTR = 'V' -NPY_DATETIMELTR = 'M' -NPY_TIMEDELTALTR = 'm' -NPY_CHARLTR = 'c' +BOOLLTR = '?' +BYTELTR = 'b' +UBYTELTR = 'B' +SHORTLTR = 'h' +USHORTLTR = 'H' +INTLTR = 'i' +UINTLTR = 'I' +LONGLTR = 'l' +ULONGLTR = 'L' +LONGLONGLTR = 'q' +ULONGLONGLTR = 'Q' +HALFLTR = 'e' +FLOATLTR = 'f' +DOUBLELTR = 'd' +LONGDOUBLELTR = 'g' +CFLOATLTR = 'F' +CDOUBLELTR = 'D' +CLONGDOUBLELTR = 'G' +OBJECTLTR = 'O' +STRINGLTR = 'S' +STRINGLTR2 = 'a' +UNICODELTR = 'U' +VOIDLTR = 'V' +DATETIMELTR = 'M' +TIMEDELTALTR = 'm' +CHARLTR = 'c' -NPY_INTPLTR = 'p' -NPY_UINTPLTR = 'P' +INTPLTR = 'p' +UINTPLTR = 'P' -NPY_GENBOOLLTR ='b' -NPY_SIGNEDLTR = 'i' -NPY_UNSIGNEDLTR = 'u' -NPY_FLOATINGLTR = 'f' -NPY_COMPLEXLTR = 'c' +GENBOOLLTR ='b' +SIGNEDLTR = 'i' +UNSIGNEDLTR = 'u' +FLOATINGLTR = 'f' +COMPLEXLTR = 'c' -NPY_ANYORDER = -1 -NPY_CORDER = 0 -NPY_FORTRANORDER = 1 -NPY_KEEPORDER = 2 +ANYORDER = -1 +CORDER = 0 +FORTRANORDER = 1 +KEEPORDER = 2 -NPY_CLIP = 0 -NPY_WRAP = 1 -NPY_RAISE = 2 +CLIP = 0 +WRAP = 1 +RAISE = 2 -NPY_LITTLE = '<' -NPY_BIG = '>' -NPY_NATIVE = '=' -NPY_SWAP = 's' -NPY_IGNORE = '|' +LITTLE = '<' +BIG = '>' +NATIVE = '=' +SWAP = 's' +IGNORE = '|' import sys if sys.byteorder == 'big': -NPY_NATBYTE = NPY_BIG -NPY_OPPBYTE = NPY_LITTLE +NATBYTE = BIG +OPPBYTE = LITTLE else: -NPY_NATBYTE = NPY_LITTLE -NPY_OPPBYTE = NPY_BIG +NATBYTE = LITTLE +OPPBYTE = BIG del sys diff --git a/pypy/module/micronumpy/conversion_utils.py b/pypy/module/micronumpy/conversion_utils.py --- a/pypy/module/micronumpy/conversion_utils.py +++ b/pypy/module/micronumpy/conversion_utils.py @@ -1,21 +1,21 @@ from pypy.interpreter.error import OperationError -from pypy.module.micronumpy.constants import * +from pypy.module.micronumpy import constants as NPY def byteorder_converter(space, new_order): endian = new_order[0] -if endian not in (NPY_BIG, NPY_LITTLE, NPY_NATIVE, NPY_IGNORE, NPY_SWAP): +if endian not in (NPY.BIG, NPY.LITTLE, NPY.NATIVE, NPY.IGNORE, NPY.SWAP): ch = endian if ch in ('b', 'B'): -endian = NPY_BIG +endian = NPY.BIG elif ch in ('l', 'L'): -endian = NPY_LITTLE +endian = NPY.LITTLE elif ch in ('n', 'N'): -endian = NPY_NATIVE +endian = NPY.NATIVE elif ch in ('i', 'I'): -endian = NPY_IGNORE +endian = NPY.IGNORE elif ch in ('s', 'S'): -endian = NPY_SWAP +endian = NPY.SWAP else: raise OperationError(space.w_ValueError, space.wrap( "%s is an unrecognized byteorder" % new_order)) @@ -24,18 +24,18 @@ def clipmode_converter(space, w_mode): if space.is_none(w_mode): -return NPY_RAISE +return NPY.RAISE if space.isinstance_w(w_mode, space.w_str): mode = space.str_w(w_mode) if mode.startswith('C') or mode.startswith('c'): -return NPY_CLIP +return NPY.CLIP if mode.startswith('W') or mode.startswith('w'): -return NPY_WRAP +return NPY.WRAP if mode.startswith('R') or mode.startswith('r'): -return NPY_RAISE +return NPY.RAISE elif space.isinstance_w(w_mode, space.w_int): mode = space
[pypy-commit] pypy remove-remaining-smm: Kill complextype.py, kill conjugate SMM.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69299:4286faa95835 Date: 2014-02-23 21:36 +0100 http://bitbucket.org/pypy/pypy/changeset/4286faa95835/ Log:Kill complextype.py, kill conjugate SMM. diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py --- a/pypy/module/micronumpy/interp_boxes.py +++ b/pypy/module/micronumpy/interp_boxes.py @@ -6,7 +6,7 @@ from pypy.objspace.std.floattype import float_typedef from pypy.objspace.std.unicodeobject import W_UnicodeObject from pypy.objspace.std.intobject import W_IntObject -from pypy.objspace.std.complextype import complex_typedef +from pypy.objspace.std.complexobject import W_ComplexObject from rpython.rlib.rarithmetic import LONG_BIT from rpython.rtyper.lltypesystem import rffi from rpython.tool.sourcetools import func_with_new_name @@ -770,7 +770,7 @@ imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag), ) -W_Complex128Box.typedef = TypeDef("complex128", (W_ComplexFloatingBox.typedef, complex_typedef), +W_Complex128Box.typedef = TypeDef("complex128", (W_ComplexFloatingBox.typedef, W_ComplexObject.typedef), __module__ = "numpy", __new__ = interp2app(W_Complex128Box.descr__new__.im_func), __reduce__ = interp2app(W_Complex128Box.descr_reduce), @@ -785,7 +785,7 @@ __reduce__ = interp2app(W_FloatLongBox.descr_reduce), ) -W_ComplexLongBox.typedef = TypeDef("complex%d" % (long_double_size * 16), (W_ComplexFloatingBox.typedef, complex_typedef), +W_ComplexLongBox.typedef = TypeDef("complex%d" % (long_double_size * 16), (W_ComplexFloatingBox.typedef, W_ComplexObject.typedef), __module__ = "numpy", __new__ = interp2app(W_ComplexLongBox.descr__new__.im_func), __reduce__ = interp2app(W_ComplexLongBox.descr_reduce), diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -1,18 +1,27 @@ -from pypy.interpreter import gateway -from pypy.interpreter.error import OperationError +import math + +from pypy.interpreter.error import OperationError, oefmt +from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault from pypy.objspace.std import newformat +from pypy.objspace.std.floatobject import W_FloatObject, _hash_float from pypy.objspace.std.intobject import W_IntObject +from pypy.objspace.std.longobject import W_LongObject from pypy.objspace.std.model import registerimplementation, W_Object +from pypy.objspace.std.noneobject import W_NoneObject from pypy.objspace.std.register_all import register_all -from pypy.objspace.std.floatobject import W_FloatObject, _hash_float -from pypy.objspace.std.longobject import W_LongObject +from pypy.objspace.std.stdtypedef import GetSetProperty, StdTypeDef +from rpython.rlib import jit, rcomplex +from rpython.rlib.rarithmetic import intmask, r_ulonglong from rpython.rlib.rbigint import rbigint from rpython.rlib.rfloat import ( -formatd, DTSF_STR_PRECISION, isinf, isnan, copysign) -from rpython.rlib import jit, rcomplex -from rpython.rlib.rarithmetic import intmask, r_ulonglong +formatd, DTSF_STR_PRECISION, isinf, isnan, copysign, string_to_float) +from rpython.rlib.rstring import ParseStringError -import math + +# ERRORCODES + +ERR_WRONG_SECOND = "complex() can't take second arg if first is a string" +ERR_MALFORMED = "complex() arg is a malformed string" class W_AbstractComplexObject(W_Object): @@ -47,10 +56,168 @@ return space.newlong_from_rbigint(val) +def _split_complex(s): +slen = len(s) +if slen == 0: +raise ValueError +realstart = 0 +realstop = 0 +imagstart = 0 +imagstop = 0 +imagsign = ' ' +i = 0 +# ignore whitespace at beginning and end +while i < slen and s[i] == ' ': +i += 1 +while slen > 0 and s[slen-1] == ' ': +slen -= 1 + +if s[i] == '(' and s[slen-1] == ')': +i += 1 +slen -= 1 +# ignore whitespace after bracket +while i < slen and s[i] == ' ': +i += 1 + +# extract first number +realstart = i +pc = s[i] +while i < slen and s[i] != ' ': +if s[i] in ('+','-') and pc not in ('e','E') and i != realstart: +break +pc = s[i] +i += 1 + +realstop = i + +# ignore whitespace +while i < slen and s[i] == ' ': +i += 1 + +# return appropriate strings is only one number is there +if i >= slen: +newstop = realstop - 1 +if newstop < 0: +raise ValueError +if s[newstop] in ('j', 'J'): +if realstart == newstop: +imagpart = '1.0' +elif realstart == newstop-1 and s[realstart] == '+': +imagpart = '1.0' +elif realstart == newstop-1 and s[realstart] == '-': +imagpart = '-1.0' +else: +imagpart = s[realstart:newst
[pypy-commit] pypy remove-remaining-smm: IN-PROGESS: Kill binary SMMs of complex.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69300:e8346b7b8d72 Date: 2014-02-23 22:15 +0100 http://bitbucket.org/pypy/pypy/changeset/e8346b7b8d72/ Log:IN-PROGESS: Kill binary SMMs of complex. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -343,23 +343,95 @@ """(A+Bj).conjugate() -> A-Bj""" return space.newcomplex(self.realval, -self.imagval) +def descr_add(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +return W_ComplexObject(self.realval + w_rhs.realval, + self.imagval + w_rhs.imagval) + +def descr_radd(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +return W_ComplexObject(w_lhs.realval + self.realval, + w_lhs.imagval + self.imagval) + +def descr_sub(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +return W_ComplexObject(self.realval - w_rhs.realval, + self.imagval - w_rhs.imagval) + +def descr_rsub(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +return W_ComplexObject(w_lhs.realval - self.realval, + w_lhs.imagval - self.imagval) + +def descr_mul(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +return self.mul(w_rhs) + +def descr_truediv(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +try: +return self.div(w_rhs) +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) + +def descr_floordiv(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +w_rhs = to_complex(space, w_rhs) +# don't care about the slight slowdown you get from using divmod +try: +return self.divmod(space, w_rhs)[0] +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) + +def descr_mod(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +try: +return self.divmod(space, w_rhs)[1] +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) + +def descr_divmod(self, space, w_rhs): +w_rhs = to_complex(space, w_rhs) +try: +div, mod = self.divmod(space, w_rhs) +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) +return space.newtuple([div, mod]) + +@unwrap_spec(w_third_arg=WrappedDefault(None)) +def descr_pow(self, space, w_exponent, w_third_arg): +w_exponent = to_complex(space, w_exponent) +if not space.is_w(w_third_arg, space.w_None): +raise OperationError(space.w_ValueError, space.wrap('complex modulo')) +try: +r = w_exponent.realval +if w_exponent.imagval == 0.0 and -100.0 <= r <= 100.0 and r == int(r): +w_p = self.pow_small_int(int(r)) +else: +w_p = self.pow(w_exponent) +except ZeroDivisionError: +raise OperationError(space.w_ZeroDivisionError, space.wrap("0.0 to a negative or complex power")) +except OverflowError: +raise OperationError(space.w_OverflowError, space.wrap("complex exponentiation")) +return w_p + registerimplementation(W_ComplexObject) w_one = W_ComplexObject(1, 0) -def delegate_Bool2Complex(space, w_bool): -return W_ComplexObject(w_bool.intval, 0.0) - -def delegate_Int2Complex(space, w_int): -return W_ComplexObject(w_int.intval, 0.0) - -def delegate_Long2Complex(space, w_long): -dval = w_long.tofloat(space) -return W_ComplexObject(dval, 0.0) - -def delegate_Float2Complex(space, w_float): -return W_ComplexObject(w_float.floatval, 0.0) +def to_complex(space, w_obj): +if isinstance(w_obj, W_ComplexObject): +return w_obj +if space.isinstance_w(w_obj, space.w_bool): +return W_ComplexObject(w_obj.intval, 0.0) +if space.isinstance_w(w_obj, space.w_int): +return W_ComplexObject(w_obj.intval, 0.0) +if space.isinstance_w(w_obj, space.w_long): +dval = w_obj.tofloat(space) +return W_ComplexObject(dval, 0.0) +if space.isinstance_w(w_obj, space.w_float): +return W_ComplexObject(w_obj.floatval, 0.0) def hash__Complex(space, w_value): hashreal = _hash_float(space, w_value.realval) @@ -367,60 +439,6 @@ combined = intmask(hashreal + 103 * hashimg) return space.newint(combined) -def add__Complex_Complex(space, w_complex1, w_complex2): -return W_ComplexObject(w_complex1.realval + w_complex2.realval, - w_complex1.imagval + w_complex2.imagval) - -def sub__Complex_Complex(space, w_complex1, w_complex2): -re
[pypy-commit] pypy default: compare with a constant here instead of name
Author: Brian Kearns Branch: Changeset: r69301:f3d4ec29ecfc Date: 2014-02-23 16:25 -0500 http://bitbucket.org/pypy/pypy/changeset/f3d4ec29ecfc/ Log:compare with a constant here instead of name diff --git a/pypy/module/micronumpy/interp_ufuncs.py b/pypy/module/micronumpy/interp_ufuncs.py --- a/pypy/module/micronumpy/interp_ufuncs.py +++ b/pypy/module/micronumpy/interp_ufuncs.py @@ -312,7 +312,7 @@ else: res_dtype = calc_dtype if self.complex_to_float and calc_dtype.is_complex_type(): -if calc_dtype.name == 'complex64': +if calc_dtype.num == NPY.CFLOAT: res_dtype = interp_dtype.get_dtype_cache(space).w_float32dtype else: res_dtype = interp_dtype.get_dtype_cache(space).w_float64dtype ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: fix segfault on np.arr.astype(record)
Author: Brian Kearns Branch: Changeset: r69302:5ec998bf16a1 Date: 2014-02-23 16:40 -0500 http://bitbucket.org/pypy/pypy/changeset/5ec998bf16a1/ Log:fix segfault on np.arr.astype(record) diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py --- a/pypy/module/micronumpy/interp_numarray.py +++ b/pypy/module/micronumpy/interp_numarray.py @@ -569,7 +569,7 @@ cur_dtype = self.get_dtype() new_dtype = space.interp_w(interp_dtype.W_Dtype, space.call_function(space.gettypefor(interp_dtype.W_Dtype), w_dtype)) -if new_dtype.shape: +if new_dtype.num == NPY.VOID: raise oefmt(space.w_NotImplementedError, "%s.astype(%s) not implemented yet", cur_dtype.name, new_dtype.name) impl = self.implementation diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -3287,6 +3287,17 @@ assert arr[1]['y']['x'] == 0.0 assert arr[1]['x'] == 15 +def test_count_nonzero(self): +import numpy as np +import sys +d = [('f0', 'i4'), ('f1', 'i4', 2)] +arr = np.array([0, 1]) +if '__pypy__' not in sys.builtin_module_names: +arr = arr.astype(d)[:1] +assert np.count_nonzero(arr) == 0 +else: +raises(NotImplementedError, "arr.astype(d)") + def test_string_record(self): from numpypy import dtype, array ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: add dot bench script
Author: Brian Kearns Branch: Changeset: r69304:74eff28ac998 Date: 2014-02-23 16:57 -0500 http://bitbucket.org/pypy/pypy/changeset/74eff28ac998/ Log:add dot bench script diff --git a/pypy/module/micronumpy/bench/dot.py b/pypy/module/micronumpy/bench/dot.py new file mode 100644 --- /dev/null +++ b/pypy/module/micronumpy/bench/dot.py @@ -0,0 +1,28 @@ +import time + +try: +import numpypy +except ImportError: +pass + +import numpy + +def get_matrix(): +import random +n = 502 +x = numpy.zeros((n,n), dtype=numpy.float64) +for i in range(n): +for j in range(n): +x[i][j] = random.random() +return x + +def main(): +x = get_matrix() +y = get_matrix() +a = time.time() +#z = numpy.dot(x, y) # uses numpy possibly-blas-lib dot +z = numpy.core.multiarray.dot(x, y) # uses strictly numpy C dot +b = time.time() +print '%.2f seconds' % (b-a) + +main() ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: cleanup/pep8
Author: Brian Kearns Branch: Changeset: r69303:c814fb7f7341 Date: 2014-02-23 16:55 -0500 http://bitbucket.org/pypy/pypy/changeset/c814fb7f7341/ Log:cleanup/pep8 diff --git a/pypy/module/micronumpy/arrayimpl/scalar.py b/pypy/module/micronumpy/arrayimpl/scalar.py --- a/pypy/module/micronumpy/arrayimpl/scalar.py +++ b/pypy/module/micronumpy/arrayimpl/scalar.py @@ -1,7 +1,6 @@ from pypy.module.micronumpy.arrayimpl import base from pypy.module.micronumpy.base import W_NDimArray, convert_to_array from pypy.module.micronumpy import support -from pypy.module.micronumpy.interp_boxes import W_GenericBox from pypy.interpreter.error import OperationError class ScalarIterator(base.BaseArrayIterator): diff --git a/pypy/module/micronumpy/test/test_appbridge.py b/pypy/module/micronumpy/test/test_appbridge.py --- a/pypy/module/micronumpy/test/test_appbridge.py +++ b/pypy/module/micronumpy/test/test_appbridge.py @@ -1,5 +1,6 @@ from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest + class AppTestAppBridge(BaseNumpyAppTest): def test_array_methods(self): import numpy as np diff --git a/pypy/module/micronumpy/test/test_arrayops.py b/pypy/module/micronumpy/test/test_arrayops.py --- a/pypy/module/micronumpy/test/test_arrayops.py +++ b/pypy/module/micronumpy/test/test_arrayops.py @@ -1,5 +1,5 @@ +from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest -from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest class AppTestNumSupport(BaseNumpyAppTest): def test_where(self): diff --git a/pypy/module/micronumpy/test/test_base.py b/pypy/module/micronumpy/test/test_base.py --- a/pypy/module/micronumpy/test/test_base.py +++ b/pypy/module/micronumpy/test/test_base.py @@ -1,5 +1,6 @@ +from pypy.conftest import option from pypy.module.micronumpy import constants as NPY -from pypy.conftest import option + class BaseNumpyAppTest(object): spaceconfig = dict(usemodules=['micronumpy']) diff --git a/pypy/module/micronumpy/test/test_compile.py b/pypy/module/micronumpy/test/test_compile.py --- a/pypy/module/micronumpy/test/test_compile.py +++ b/pypy/module/micronumpy/test/test_compile.py @@ -1,4 +1,3 @@ - import py from pypy.module.micronumpy.compile import (numpy_compile, Assignment, ArrayConstant, FloatConstant, Operator, Variable, RangeConstant, Execute, diff --git a/pypy/module/micronumpy/test/test_complex.py b/pypy/module/micronumpy/test/test_complex.py --- a/pypy/module/micronumpy/test/test_complex.py +++ b/pypy/module/micronumpy/test/test_complex.py @@ -61,6 +61,7 @@ '%r and %r are not sufficiently close, %g > %g' %\ (a, b, absolute_error, max(abs_err, rel_err*abs(a + def parse_testfile(fname): """Parse a file with test values @@ -85,6 +86,7 @@ flags ) + class AppTestUfuncs(BaseNumpyAppTest): def setup_class(cls): import os diff --git a/pypy/module/micronumpy/test/test_dtypes.py b/pypy/module/micronumpy/test/test_dtypes.py --- a/pypy/module/micronumpy/test/test_dtypes.py +++ b/pypy/module/micronumpy/test/test_dtypes.py @@ -1,4 +1,3 @@ -import py, sys from pypy.conftest import option from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest from pypy.interpreter.gateway import interp2app diff --git a/pypy/module/micronumpy/test/test_iter.py b/pypy/module/micronumpy/test/test_iter.py --- a/pypy/module/micronumpy/test/test_iter.py +++ b/pypy/module/micronumpy/test/test_iter.py @@ -1,9 +1,11 @@ from pypy.module.micronumpy.iter import MultiDimViewIterator from pypy.module.micronumpy.arrayimpl.scalar import ScalarIterator + class MockArray(object): size = 1 + class TestIterDirect(object): def test_C_viewiterator(self): #Let's get started, simple iteration in C order with diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -24,6 +24,7 @@ def get_size(self): return 1 + def create_slice(space, a, chunks): return Chunks(chunks).apply(space, W_NDimArray(a)).implementation diff --git a/pypy/module/micronumpy/test/test_outarg.py b/pypy/module/micronumpy/test/test_outarg.py --- a/pypy/module/micronumpy/test/test_outarg.py +++ b/pypy/module/micronumpy/test/test_outarg.py @@ -1,6 +1,6 @@ -import py from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest + class AppTestOutArg(BaseNumpyAppTest): def test_reduce_out(self): from numpypy import arange, zeros, array diff --git a/pypy/module/micronumpy/test/test_subtype.py b/pypy/module/micronumpy/test/test_subtype.py --- a/pypy/module/micronumpy/test/test_subtype.py +++ b/pypy/module/micronumpy/test/test_subtype.py @@ -1,9 +1,9 @@ -import py from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest class AppTestSupport(BaseNumpyAppTest): spaceconfig
[pypy-commit] pypy remove-remaining-smm: Fix test_coerce().
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69305:ea4b812690a9 Date: 2014-02-23 22:47 +0100 http://bitbucket.org/pypy/pypy/changeset/ea4b812690a9/ Log:Fix test_coerce(). diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -490,8 +490,8 @@ return space.newbool((w_complex.realval != 0.0) or (w_complex.imagval != 0.0)) -def coerce__Complex_Complex(space, w_complex1, w_complex2): -#w_complex2 = to_complex(w_complex2) +def coerce__Complex_ANY(space, w_complex1, w_complex2): +w_complex2 = to_complex(space, w_complex2) return space.newtuple([w_complex1, w_complex2]) def float__Complex(space, w_complex): ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Add remaining __r*__ to complex.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69306:5f3f540c4ba5 Date: 2014-02-23 23:04 +0100 http://bitbucket.org/pypy/pypy/changeset/5f3f540c4ba5/ Log:Add remaining __r*__ to complex. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -18,12 +18,6 @@ from rpython.rlib.rstring import ParseStringError -# ERRORCODES - -ERR_WRONG_SECOND = "complex() can't take second arg if first is a string" -ERR_MALFORMED = "complex() arg is a malformed string" - - class W_AbstractComplexObject(W_Object): __slots__ = () @@ -215,6 +209,9 @@ return (space.float_w(space.float(w_complex)), 0.0) +ERR_MALFORMED = "complex() arg is a malformed string" + + class W_ComplexObject(W_AbstractComplexObject): """This is a reimplementation of the CPython "PyComplexObject" """ @@ -367,6 +364,10 @@ w_rhs = to_complex(space, w_rhs) return self.mul(w_rhs) +def descr_rmul(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +return w_lhs.mul(self) + def descr_truediv(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) try: @@ -374,15 +375,29 @@ except ZeroDivisionError, e: raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) +def descr_rtruediv(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +try: +return w_lhs.div(self) +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) + def descr_floordiv(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) -w_rhs = to_complex(space, w_rhs) # don't care about the slight slowdown you get from using divmod try: return self.divmod(space, w_rhs)[0] except ZeroDivisionError, e: raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) +def descr_rfloordiv(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +# don't care about the slight slowdown you get from using divmod +try: +return w_lhs.divmod(space, self)[0] +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) + def descr_mod(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) try: @@ -390,6 +405,13 @@ except ZeroDivisionError, e: raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) +def descr_rmod(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +try: +return w_lhs.divmod(space, self)[1] +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) + def descr_divmod(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) try: @@ -398,6 +420,14 @@ raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) return space.newtuple([div, mod]) +def descr_rdivmod(self, space, w_lhs): +w_lhs = to_complex(space, w_lhs) +try: +div, mod = w_lhs.divmod(space, self) +except ZeroDivisionError, e: +raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) +return space.newtuple([div, mod]) + @unwrap_spec(w_third_arg=WrappedDefault(None)) def descr_pow(self, space, w_exponent, w_third_arg): w_exponent = to_complex(space, w_exponent) @@ -558,11 +588,17 @@ __sub__ = interp2app(W_ComplexObject.descr_sub), __rsub__ = interp2app(W_ComplexObject.descr_rsub), __mul__ = interp2app(W_ComplexObject.descr_mul), +__rmul__ = interp2app(W_ComplexObject.descr_rmul), __div__ = interp2app(W_ComplexObject.descr_truediv), +__rdiv__ = interp2app(W_ComplexObject.descr_rtruediv), __truediv__ = interp2app(W_ComplexObject.descr_truediv), +__rtruediv__ = interp2app(W_ComplexObject.descr_rtruediv), __floordiv__ = interp2app(W_ComplexObject.descr_floordiv), +__rfloordiv__ = interp2app(W_ComplexObject.descr_rfloordiv), __mod__ = interp2app(W_ComplexObject.descr_mod), +__rmod__ = interp2app(W_ComplexObject.descr_rmod), __divmod__ = interp2app(W_ComplexObject.descr_divmod), +__rdivmod__ = interp2app(W_ComplexObject.descr_rdivmod), __pow__ = interp2app(W_ComplexObject.descr_pow), ) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Move descr_conjugate.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69307:3f359859555e Date: 2014-02-23 23:13 +0100 http://bitbucket.org/pypy/pypy/changeset/3f359859555e/ Log:Move descr_conjugate. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -336,10 +336,6 @@ return space.newtuple([space.newfloat(self.realval), space.newfloat(self.imagval)]) -def descr_conjugate(self, space): -"""(A+Bj).conjugate() -> A-Bj""" -return space.newcomplex(self.realval, -self.imagval) - def descr_add(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) return W_ComplexObject(self.realval + w_rhs.realval, @@ -445,6 +441,10 @@ raise OperationError(space.w_OverflowError, space.wrap("complex exponentiation")) return w_p +def descr_conjugate(self, space): +"""(A+Bj).conjugate() -> A-Bj""" +return space.newcomplex(self.realval, -self.imagval) + registerimplementation(W_ComplexObject) w_one = W_ComplexObject(1, 0) @@ -581,7 +581,6 @@ __getnewargs__ = interp2app(W_ComplexObject.descr___getnewargs__), real = complexwprop('realval'), imag = complexwprop('imagval'), -conjugate = interp2app(W_ComplexObject.descr_conjugate), __add__ = interp2app(W_ComplexObject.descr_add), __radd__ = interp2app(W_ComplexObject.descr_radd), @@ -600,6 +599,8 @@ __divmod__ = interp2app(W_ComplexObject.descr_divmod), __rdivmod__ = interp2app(W_ComplexObject.descr_rdivmod), __pow__ = interp2app(W_ComplexObject.descr_pow), + +conjugate = interp2app(W_ComplexObject.descr_conjugate), ) W_ComplexObject.typedef.registermethods(globals()) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill complex' comparison SMMs.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69311:539b3c1e0501 Date: 2014-02-23 23:46 +0100 http://bitbucket.org/pypy/pypy/changeset/539b3c1e0501/ Log:Kill complex' comparison SMMs. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -342,6 +342,34 @@ combined = intmask(hashreal + 103 * hashimg) return space.newint(combined) +def descr_eq(self, space, w_other): +if isinstance(w_other, W_ComplexObject): +return space.newbool((self.realval == w_other.realval) and + (self.imagval == w_other.imagval)) +if (space.isinstance_w(w_other, space.w_int) or +space.isinstance_w(w_other, space.w_long)): +if self.imagval: +return space.w_False +return space.eq(space.newfloat(self.realval), w_other) +return space.w_NotImplemented + +def descr_ne(self, space, w_other): +if isinstance(w_other, W_ComplexObject): +return space.newbool((self.realval != w_other.realval) or + (self.imagval != w_other.imagval)) +if (space.isinstance_w(w_other, space.w_int) or +space.isinstance_w(w_other, space.w_long)): +if self.imagval: +return space.w_True +return space.ne(space.newfloat(self.realval), w_other) +return space.w_NotImplemented + +def _fail_cmp(self, space, w_other): +if isinstance(w_other, W_ComplexObject): +raise OperationError(space.w_TypeError, + space.wrap('cannot compare complex numbers using <, <=, >, >=')) +return space.w_NotImplemented + def descr_add(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) if w_rhs is None: @@ -509,41 +537,6 @@ except OverflowError, e: raise OperationError(space.w_OverflowError, space.wrap(str(e))) -def eq__Complex_Complex(space, w_complex1, w_complex2): -return space.newbool((w_complex1.realval == w_complex2.realval) and -(w_complex1.imagval == w_complex2.imagval)) - -def ne__Complex_Complex(space, w_complex1, w_complex2): -return space.newbool((w_complex1.realval != w_complex2.realval) or -(w_complex1.imagval != w_complex2.imagval)) - -def eq__Complex_Long(space, w_complex1, w_long2): -if w_complex1.imagval: -return space.w_False -return space.eq(space.newfloat(w_complex1.realval), w_long2) -eq__Complex_Int = eq__Complex_Long - -def eq__Long_Complex(space, w_long1, w_complex2): -return eq__Complex_Long(space, w_complex2, w_long1) -eq__Int_Complex = eq__Long_Complex - -def ne__Complex_Long(space, w_complex1, w_long2): -if w_complex1.imagval: -return space.w_True -return space.ne(space.newfloat(w_complex1.realval), w_long2) -ne__Complex_Int = ne__Complex_Long - -def ne__Long_Complex(space, w_long1, w_complex2): -return ne__Complex_Long(space, w_complex2, w_long1) -ne__Int_Complex = ne__Long_Complex - -def lt__Complex_Complex(space, w_complex1, w_complex2): -raise OperationError(space.w_TypeError, space.wrap('cannot compare complex numbers using <, <=, >, >=')) - -gt__Complex_Complex = lt__Complex_Complex -ge__Complex_Complex = lt__Complex_Complex -le__Complex_Complex = lt__Complex_Complex - def nonzero__Complex(space, w_complex): return space.newbool((w_complex.realval != 0.0) or (w_complex.imagval != 0.0)) @@ -611,8 +604,14 @@ __getnewargs__ = interp2app(W_ComplexObject.descr___getnewargs__), real = complexwprop('realval'), imag = complexwprop('imagval'), +__hash__ = interp2app(W_ComplexObject.descr_hash), -__hash__ = interp2app(W_ComplexObject.descr_hash), +__eq__ = interp2app(W_ComplexObject.descr_eq), +__ne__ = interp2app(W_ComplexObject.descr_ne), +__lt__ = interp2app(W_ComplexObject._fail_cmp), +__le__ = interp2app(W_ComplexObject._fail_cmp), +__gt__ = interp2app(W_ComplexObject._fail_cmp), +__ge__ = interp2app(W_ComplexObject._fail_cmp), __add__ = interp2app(W_ComplexObject.descr_add), __radd__ = interp2app(W_ComplexObject.descr_radd), ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill dead imports.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69312:83173344840d Date: 2014-02-23 23:47 +0100 http://bitbucket.org/pypy/pypy/changeset/83173344840d/ Log:Kill dead imports. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -3,11 +3,8 @@ from pypy.interpreter.error import OperationError, oefmt from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault from pypy.objspace.std import newformat -from pypy.objspace.std.floatobject import W_FloatObject, _hash_float -from pypy.objspace.std.intobject import W_IntObject -from pypy.objspace.std.longobject import W_LongObject +from pypy.objspace.std.floatobject import _hash_float from pypy.objspace.std.model import registerimplementation, W_Object -from pypy.objspace.std.noneobject import W_NoneObject from pypy.objspace.std.register_all import register_all from pypy.objspace.std.stdtypedef import GetSetProperty, StdTypeDef from rpython.rlib import jit, rcomplex ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill remaining complex SMMs.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69313:b4df3096e70c Date: 2014-02-24 00:14 +0100 http://bitbucket.org/pypy/pypy/changeset/b4df3096e70c/ Log:Kill remaining complex SMMs. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -333,12 +333,74 @@ return space.newtuple([space.newfloat(self.realval), space.newfloat(self.imagval)]) +def _format_float(self, x, code, precision): +# like float2string, except that the ".0" is not necessary +if isinf(x): +if x > 0.0: +return "inf" +else: +return "-inf" +elif isnan(x): +return "nan" +else: +return formatd(x, code, precision) + +def _repr_format(self, x): +return self._format_float(x, 'r', 0) + +def _str_format(self, x): +return self._format_float(x, 'g', DTSF_STR_PRECISION) + +def descr_repr(self, space): +if self.realval == 0 and copysign(1., self.realval) == 1.: +return space.wrap(self._repr_format(self.imagval) + 'j') +sign = (copysign(1., self.imagval) == 1. or +isnan(self.imagval)) and '+' or '' +return space.wrap('(' + self._repr_format(self.realval) + + sign + self._repr_format(self.imagval) + 'j)') + +def descr_str(self, space): +if self.realval == 0 and copysign(1., self.realval) == 1.: +return space.wrap(self._str_format(self.imagval) + 'j') +sign = (copysign(1., self.imagval) == 1. or +isnan(self.imagval)) and '+' or '' +return space.wrap('(' + self._str_format(self.realval) + + sign + self._str_format(self.imagval) + 'j)') + def descr_hash(self, space): hashreal = _hash_float(space, self.realval) hashimg = _hash_float(space, self.imagval) combined = intmask(hashreal + 103 * hashimg) return space.newint(combined) +def descr_coerce(self, space, w_other): +w_other = to_complex(space, w_other) +if w_other is None: +return space.w_NotImplemented +return space.newtuple([self, w_other]) + +def descr_format(self, space, w_format_spec): +return newformat.run_formatter(space, w_format_spec, "format_complex", self) + +def descr_nonzero(self, space): +return space.newbool((self.realval != 0.0) or (self.imagval != 0.0)) + +def descr_float(self, space): +raise OperationError(space.w_TypeError, + space.wrap("can't convert complex to float; use abs(z)")) + +def descr_neg(self, space): +return W_ComplexObject(-self.realval, -self.imagval) + +def descr_pos(self, space): +return W_ComplexObject(self.realval, self.imagval) + +def descr_abs(self, space): +try: +return space.newfloat(math.hypot(self.realval, self.imagval)) +except OverflowError, e: +raise OperationError(space.w_OverflowError, space.wrap(str(e))) + def descr_eq(self, space, w_other): if isinstance(w_other, W_ComplexObject): return space.newbool((self.realval == w_other.realval) and @@ -522,67 +584,6 @@ if space.isinstance_w(w_obj, space.w_float): return W_ComplexObject(w_obj.floatval, 0.0) -def neg__Complex(space, w_complex): -return W_ComplexObject(-w_complex.realval, -w_complex.imagval) - -def pos__Complex(space, w_complex): -return W_ComplexObject(w_complex.realval, w_complex.imagval) - -def abs__Complex(space, w_complex): -try: -return space.newfloat(math.hypot(w_complex.realval, w_complex.imagval)) -except OverflowError, e: -raise OperationError(space.w_OverflowError, space.wrap(str(e))) - -def nonzero__Complex(space, w_complex): -return space.newbool((w_complex.realval != 0.0) or - (w_complex.imagval != 0.0)) - -def coerce__Complex_ANY(space, w_complex1, w_complex2): -w_complex2 = to_complex(space, w_complex2) -if w_complex2 is None: -return space.w_NotImplemented -return space.newtuple([w_complex1, w_complex2]) - -def float__Complex(space, w_complex): -raise OperationError(space.w_TypeError, space.wrap("can't convert complex to float; use abs(z)")) - -def format_float(x, code, precision): -# like float2string, except that the ".0" is not necessary -if isinf(x): -if x > 0.0: -return "inf" -else: -return "-inf" -elif isnan(x): -return "nan" -else: -return formatd(x, code, precision) - -def repr_format(x): -return format_float(x, 'r', 0) -def str_format(x): -return format_float(x, 'g', DTSF_STR_PRECISION) - -def repr__Complex(space, w_complex): -if w_complex.realval == 0 and copysign(1., w_complex.
[pypy-commit] pypy remove-remaining-smm: Make W_ComplexObject a W_Root.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69314:9bad70f6ed72 Date: 2014-02-24 00:18 +0100 http://bitbucket.org/pypy/pypy/changeset/9bad70f6ed72/ Log:Make W_ComplexObject a W_Root. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -1,11 +1,10 @@ import math +from pypy.interpreter.baseobjspace import W_Root from pypy.interpreter.error import OperationError, oefmt from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault from pypy.objspace.std import newformat from pypy.objspace.std.floatobject import _hash_float -from pypy.objspace.std.model import registerimplementation, W_Object -from pypy.objspace.std.register_all import register_all from pypy.objspace.std.stdtypedef import GetSetProperty, StdTypeDef from rpython.rlib import jit, rcomplex from rpython.rlib.rarithmetic import intmask, r_ulonglong @@ -15,7 +14,7 @@ from rpython.rlib.rstring import ParseStringError -class W_AbstractComplexObject(W_Object): +class W_AbstractComplexObject(W_Root): __slots__ = () def is_w(self, space, w_other): @@ -568,7 +567,6 @@ """(A+Bj).conjugate() -> A-Bj""" return space.newcomplex(self.realval, -self.imagval) -registerimplementation(W_ComplexObject) w_one = W_ComplexObject(1, 0) @@ -640,6 +638,3 @@ conjugate = interp2app(W_ComplexObject.descr_conjugate), ) - -W_ComplexObject.typedef.registermethods(globals()) -register_all(vars(), globals()) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill complex.__hash__ SMM.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69308:301f03687bca Date: 2014-02-23 23:16 +0100 http://bitbucket.org/pypy/pypy/changeset/301f03687bca/ Log:Kill complex.__hash__ SMM. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -336,6 +336,12 @@ return space.newtuple([space.newfloat(self.realval), space.newfloat(self.imagval)]) +def descr_hash(self, space): +hashreal = _hash_float(space, self.realval) +hashimg = _hash_float(space, self.imagval) +combined = intmask(hashreal + 103 * hashimg) +return space.newint(combined) + def descr_add(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) return W_ComplexObject(self.realval + w_rhs.realval, @@ -463,12 +469,6 @@ if space.isinstance_w(w_obj, space.w_float): return W_ComplexObject(w_obj.floatval, 0.0) -def hash__Complex(space, w_value): -hashreal = _hash_float(space, w_value.realval) -hashimg = _hash_float(space, w_value.imagval) -combined = intmask(hashreal + 103 * hashimg) -return space.newint(combined) - def neg__Complex(space, w_complex): return W_ComplexObject(-w_complex.realval, -w_complex.imagval) @@ -582,6 +582,8 @@ real = complexwprop('realval'), imag = complexwprop('imagval'), +__hash__ = interp2app(W_ComplexObject.descr_hash), + __add__ = interp2app(W_ComplexObject.descr_add), __radd__ = interp2app(W_ComplexObject.descr_radd), __sub__ = interp2app(W_ComplexObject.descr_sub), ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Don't special case w_bool.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69310:77fb097f2896 Date: 2014-02-23 23:26 +0100 http://bitbucket.org/pypy/pypy/changeset/77fb097f2896/ Log:Don't special case w_bool. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -489,8 +489,6 @@ def to_complex(space, w_obj): if isinstance(w_obj, W_ComplexObject): return w_obj -if space.isinstance_w(w_obj, space.w_bool): -return W_ComplexObject(w_obj.intval, 0.0) if space.isinstance_w(w_obj, space.w_int): return W_ComplexObject(w_obj.intval, 0.0) if space.isinstance_w(w_obj, space.w_long): ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Fix the case when binary ops are called with an unsupported operand.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69309:7d53c974e8fa Date: 2014-02-23 23:23 +0100 http://bitbucket.org/pypy/pypy/changeset/7d53c974e8fa/ Log:Fix the case when binary ops are called with an unsupported operand. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -344,34 +344,48 @@ def descr_add(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented return W_ComplexObject(self.realval + w_rhs.realval, self.imagval + w_rhs.imagval) def descr_radd(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented return W_ComplexObject(w_lhs.realval + self.realval, w_lhs.imagval + self.imagval) def descr_sub(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented return W_ComplexObject(self.realval - w_rhs.realval, self.imagval - w_rhs.imagval) def descr_rsub(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented return W_ComplexObject(w_lhs.realval - self.realval, w_lhs.imagval - self.imagval) def descr_mul(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented return self.mul(w_rhs) def descr_rmul(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented return w_lhs.mul(self) def descr_truediv(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented try: return self.div(w_rhs) except ZeroDivisionError, e: @@ -379,6 +393,8 @@ def descr_rtruediv(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented try: return w_lhs.div(self) except ZeroDivisionError, e: @@ -386,6 +402,8 @@ def descr_floordiv(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented # don't care about the slight slowdown you get from using divmod try: return self.divmod(space, w_rhs)[0] @@ -394,6 +412,8 @@ def descr_rfloordiv(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented # don't care about the slight slowdown you get from using divmod try: return w_lhs.divmod(space, self)[0] @@ -402,6 +422,8 @@ def descr_mod(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented try: return self.divmod(space, w_rhs)[1] except ZeroDivisionError, e: @@ -409,6 +431,8 @@ def descr_rmod(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented try: return w_lhs.divmod(space, self)[1] except ZeroDivisionError, e: @@ -416,6 +440,8 @@ def descr_divmod(self, space, w_rhs): w_rhs = to_complex(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented try: div, mod = self.divmod(space, w_rhs) except ZeroDivisionError, e: @@ -424,6 +450,8 @@ def descr_rdivmod(self, space, w_lhs): w_lhs = to_complex(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented try: div, mod = w_lhs.divmod(space, self) except ZeroDivisionError, e: @@ -433,6 +461,8 @@ @unwrap_spec(w_third_arg=WrappedDefault(None)) def descr_pow(self, space, w_exponent, w_third_arg): w_exponent = to_complex(space, w_exponent) +if w_exponent is None: +return space.w_NotImplemented if not space.is_w(w_third_arg, space.w_None): raise OperationError(space.w_ValueError, space.wrap('complex modulo')) try: @@ -522,6 +552,8 @@ def coerce__Complex_ANY(space, w_complex1, w_complex2): w_complex2 = to_complex(space, w_complex2) +if w_complex2 is None: +return space.w_NotImplemented return space.newtuple([w_complex1, w_complex2]) def float__Complex(space, w_complex): ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mai
[pypy-commit] pypy remove-remaining-smm: pep8
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69316:a141c6e25ef6 Date: 2014-02-24 00:35 +0100 http://bitbucket.org/pypy/pypy/changeset/a141c6e25ef6/ Log:pep8 diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -23,9 +23,9 @@ return False if self.user_overridden_class or w_other.user_overridden_class: return self is w_other -real1 = space.float_w(space.getattr(self,space.wrap("real"))) +real1 = space.float_w(space.getattr(self, space.wrap("real"))) real2 = space.float_w(space.getattr(w_other, space.wrap("real"))) -imag1 = space.float_w(space.getattr(self,space.wrap("imag"))) +imag1 = space.float_w(space.getattr(self, space.wrap("imag"))) imag2 = space.float_w(space.getattr(w_other, space.wrap("imag"))) real1 = float2longlong(real1) real2 = float2longlong(real2) @@ -73,7 +73,7 @@ realstart = i pc = s[i] while i < slen and s[i] != ' ': -if s[i] in ('+','-') and pc not in ('e','E') and i != realstart: +if s[i] in ('+', '-') and pc not in ('e', 'E') and i != realstart: break pc = s[i] i += 1 @@ -108,7 +108,7 @@ if imagsign == ' ': raise ValueError -i+=1 +i += 1 # whitespace while i < slen and s[i] == ' ': i += 1 @@ -118,7 +118,7 @@ imagstart = i pc = s[i] while i < slen and s[i] != ' ': -if s[i] in ('+','-') and pc not in ('e','E'): +if s[i] in ('+', '-') and pc not in ('e', 'E'): break pc = s[i] i += 1 @@ -126,14 +126,14 @@ imagstop = i - 1 if imagstop < 0: raise ValueError -if s[imagstop] not in ('j','J'): +if s[imagstop] not in ('j', 'J'): raise ValueError if imagstop < imagstart: raise ValueError -while i" % (self.realval, self.imagval) +return "" % (self.realval, self.imagval) def as_tuple(self): return (self.realval, self.imagval) @@ -287,7 +286,7 @@ return W_ComplexObject(w_obj.floatval, 0.0) @staticmethod -@unwrap_spec(w_real = WrappedDefault(0.0)) +@unwrap_spec(w_real=WrappedDefault(0.0)) def descr__new__(space, w_complextype, w_real, w_imag=None): from pypy.objspace.std.complexobject import W_ComplexObject @@ -297,7 +296,7 @@ # is itself a subclass of complex. noarg2 = w_imag is None if (noarg2 and space.is_w(w_complextype, space.w_complex) - and space.is_w(space.type(w_real), space.w_complex)): +and space.is_w(space.type(w_real), space.w_complex)): return w_real if space.isinstance_w(w_real, space.w_str) or \ @@ -637,4 +636,4 @@ __pow__ = interp2app(W_ComplexObject.descr_pow), conjugate = interp2app(W_ComplexObject.descr_conjugate), -) +) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Move to_complex().
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69315:5f71433268dc Date: 2014-02-24 00:21 +0100 http://bitbucket.org/pypy/pypy/changeset/5f71433268dc/ Log:Move to_complex(). diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -275,6 +275,17 @@ def int(self, space): raise OperationError(space.w_TypeError, space.wrap("can't convert complex to int; use int(abs(z))")) +def _to_complex(self, space, w_obj): +if isinstance(w_obj, W_ComplexObject): +return w_obj +if space.isinstance_w(w_obj, space.w_int): +return W_ComplexObject(w_obj.intval, 0.0) +if space.isinstance_w(w_obj, space.w_long): +dval = w_obj.tofloat(space) +return W_ComplexObject(dval, 0.0) +if space.isinstance_w(w_obj, space.w_float): +return W_ComplexObject(w_obj.floatval, 0.0) + @staticmethod @unwrap_spec(w_real = WrappedDefault(0.0)) def descr__new__(space, w_complextype, w_real, w_imag=None): @@ -373,7 +384,7 @@ return space.newint(combined) def descr_coerce(self, space, w_other): -w_other = to_complex(space, w_other) +w_other = self._to_complex(space, w_other) if w_other is None: return space.w_NotImplemented return space.newtuple([self, w_other]) @@ -429,47 +440,47 @@ return space.w_NotImplemented def descr_add(self, space, w_rhs): -w_rhs = to_complex(space, w_rhs) +w_rhs = self._to_complex(space, w_rhs) if w_rhs is None: return space.w_NotImplemented return W_ComplexObject(self.realval + w_rhs.realval, self.imagval + w_rhs.imagval) def descr_radd(self, space, w_lhs): -w_lhs = to_complex(space, w_lhs) +w_lhs = self._to_complex(space, w_lhs) if w_lhs is None: return space.w_NotImplemented return W_ComplexObject(w_lhs.realval + self.realval, w_lhs.imagval + self.imagval) def descr_sub(self, space, w_rhs): -w_rhs = to_complex(space, w_rhs) +w_rhs = self._to_complex(space, w_rhs) if w_rhs is None: return space.w_NotImplemented return W_ComplexObject(self.realval - w_rhs.realval, self.imagval - w_rhs.imagval) def descr_rsub(self, space, w_lhs): -w_lhs = to_complex(space, w_lhs) +w_lhs = self._to_complex(space, w_lhs) if w_lhs is None: return space.w_NotImplemented return W_ComplexObject(w_lhs.realval - self.realval, w_lhs.imagval - self.imagval) def descr_mul(self, space, w_rhs): -w_rhs = to_complex(space, w_rhs) +w_rhs = self._to_complex(space, w_rhs) if w_rhs is None: return space.w_NotImplemented return self.mul(w_rhs) def descr_rmul(self, space, w_lhs): -w_lhs = to_complex(space, w_lhs) +w_lhs = self._to_complex(space, w_lhs) if w_lhs is None: return space.w_NotImplemented return w_lhs.mul(self) def descr_truediv(self, space, w_rhs): -w_rhs = to_complex(space, w_rhs) +w_rhs = self._to_complex(space, w_rhs) if w_rhs is None: return space.w_NotImplemented try: @@ -478,7 +489,7 @@ raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) def descr_rtruediv(self, space, w_lhs): -w_lhs = to_complex(space, w_lhs) +w_lhs = self._to_complex(space, w_lhs) if w_lhs is None: return space.w_NotImplemented try: @@ -487,7 +498,7 @@ raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) def descr_floordiv(self, space, w_rhs): -w_rhs = to_complex(space, w_rhs) +w_rhs = self._to_complex(space, w_rhs) if w_rhs is None: return space.w_NotImplemented # don't care about the slight slowdown you get from using divmod @@ -497,7 +508,7 @@ raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) def descr_rfloordiv(self, space, w_lhs): -w_lhs = to_complex(space, w_lhs) +w_lhs = self._to_complex(space, w_lhs) if w_lhs is None: return space.w_NotImplemented # don't care about the slight slowdown you get from using divmod @@ -507,7 +518,7 @@ raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e))) def descr_mod(self, space, w_rhs): -w_rhs = to_complex(space, w_rhs) +w_rhs = self._to_complex(space, w_rhs) if w_rhs is None: return space.w_NotImplemented try: @@ -516,7 +527,7 @@ raise OperationError(space.w_ZeroDivisionError, s
[pypy-commit] pypy default: add a numpy constant
Author: Brian Kearns Branch: Changeset: r69318:1a50a1ac857b Date: 2014-02-23 19:08 -0500 http://bitbucket.org/pypy/pypy/changeset/1a50a1ac857b/ Log:add a numpy constant diff --git a/pypy/module/micronumpy/__init__.py b/pypy/module/micronumpy/__init__.py --- a/pypy/module/micronumpy/__init__.py +++ b/pypy/module/micronumpy/__init__.py @@ -27,7 +27,7 @@ class UMathModule(MixedModule): appleveldefs = {} -interpleveldefs = {} +interpleveldefs = {'FLOATING_POINT_SUPPORT': 'space.wrap(1)'} # ufuncs for exposed, impl in [ ("absolute", "absolute"), diff --git a/pypy/module/micronumpy/test/test_ufuncs.py b/pypy/module/micronumpy/test/test_ufuncs.py --- a/pypy/module/micronumpy/test/test_ufuncs.py +++ b/pypy/module/micronumpy/test/test_ufuncs.py @@ -83,6 +83,10 @@ class AppTestUfuncs(BaseNumpyAppTest): +def test_constants(self): +import numpy as np +assert np.FLOATING_POINT_SUPPORT == 1 + def test_ufunc_instance(self): from numpypy import add, ufunc ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: failing test for hash of record dtypes
Author: Brian Kearns Branch: Changeset: r69317:f33ed1c13f41 Date: 2014-02-23 18:14 -0500 http://bitbucket.org/pypy/pypy/changeset/f33ed1c13f41/ Log:failing test for hash of record dtypes diff --git a/pypy/module/micronumpy/test/test_dtypes.py b/pypy/module/micronumpy/test/test_dtypes.py --- a/pypy/module/micronumpy/test/test_dtypes.py +++ b/pypy/module/micronumpy/test/test_dtypes.py @@ -315,6 +315,22 @@ ]: assert hash(tp(value)) == hash(value) +d1 = numpy.dtype([('f0', 'i4'), ('f1', 'i4')]) +d2 = numpy.dtype([('f0', 'i4'), ('f1', 'i4')]) +d3 = numpy.dtype([('f0', 'i4'), ('f2', 'i4')]) +d4 = numpy.dtype([('f0', 'i4'), ('f1', d1)]) +d5 = numpy.dtype([('f0', 'i4'), ('f1', d2)]) +d6 = numpy.dtype([('f0', 'i4'), ('f1', d3)]) +import sys +if '__pypy__' not in sys.builtin_module_names: +assert hash(d1) == hash(d2) +assert hash(d1) != hash(d3) +assert hash(d4) == hash(d5) +assert hash(d4) != hash(d6) +else: +for d in [d1, d2, d3, d4, d5, d6]: +raises(TypeError, hash, d) + def test_pickle(self): from numpypy import array, dtype from cPickle import loads, dumps ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: fix ndarray.astype(S0)
Author: Brian Kearns Branch: Changeset: r69319:f2ff6d660efd Date: 2014-02-23 19:17 -0500 http://bitbucket.org/pypy/pypy/changeset/f2ff6d660efd/ Log:fix ndarray.astype(S0) diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py --- a/pypy/module/micronumpy/interp_numarray.py +++ b/pypy/module/micronumpy/interp_numarray.py @@ -572,6 +572,10 @@ if new_dtype.num == NPY.VOID: raise oefmt(space.w_NotImplementedError, "%s.astype(%s) not implemented yet", cur_dtype.name, new_dtype.name) +if new_dtype.num == NPY.STRING and new_dtype.size == 0: +if cur_dtype.num == NPY.STRING: +new_dtype = interp_dtype.variable_dtype(space, +'S' + str(cur_dtype.size)) impl = self.implementation if isinstance(impl, scalar.Scalar): return W_NDimArray.new_scalar(space, new_dtype, impl.value) diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -2102,6 +2102,7 @@ assert a[2] == 3.0 a = array('123') +assert a.astype('S0').dtype == 'S3' assert a.astype('i8') == 123 a = array('abcdefgh') exc = raises(ValueError, a.astype, 'i8') ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: better error for ndarray.take with unsupported mode
Author: Brian Kearns Branch: Changeset: r69320:036b96efb852 Date: 2014-02-23 19:59 -0500 http://bitbucket.org/pypy/pypy/changeset/036b96efb852/ Log:better error for ndarray.take with unsupported mode diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py --- a/pypy/module/micronumpy/interp_numarray.py +++ b/pypy/module/micronumpy/interp_numarray.py @@ -1234,7 +1234,8 @@ app_take = applevel(r""" def take(a, indices, axis, out, mode): -assert mode == 'raise' +if mode != 'raise': +raise NotImplementedError("mode != raise not implemented") if axis is None: from numpy import array indices = array(indices) diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -2822,6 +2822,10 @@ assert ((a + a).take([3]) == [6]).all() a = arange(12).reshape(2, 6) assert (a[:,::2].take([3, 2, 1]) == [6, 4, 2]).all() +import sys +if '__pypy__' in sys.builtin_module_names: +exc = raises(NotImplementedError, "a.take([3, 2, 1], mode='clip')") +assert exc.value[0] == "mode != raise not implemented" def test_ptp(self): import numpypy as np ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill float's binary SMMs.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69322:c12626ccdd0a Date: 2014-02-24 02:07 +0100 http://bitbucket.org/pypy/pypy/changeset/c12626ccdd0a/ Log:Kill float's binary SMMs. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -7,7 +7,6 @@ from pypy.interpreter.typedef import GetSetProperty from pypy.objspace.std import newformat from pypy.objspace.std.longobject import W_LongObject -from pypy.objspace.std.multimethod import FailedToImplementArgs from pypy.objspace.std.model import registerimplementation, W_Object from pypy.objspace.std.register_all import register_all from pypy.objspace.std.stdtypedef import StdTypeDef, SMM @@ -314,6 +313,160 @@ w_float = space.wrap(sign * value) return space.call_function(w_cls, w_float) +def _to_float(self, space, w_obj): +if isinstance(w_obj, W_FloatObject): +return w_obj +if space.isinstance_w(w_obj, space.w_int): +return W_FloatObject(float(w_obj.intval)) +if space.isinstance_w(w_obj, space.w_long): +return W_FloatObject(w_obj.tofloat(space)) + +def descr_coerce(self, space, w_other): +w_other = self._to_float(space, w_other) +if w_other is None: +return space.w_NotImplemented +return space.newtuple([self, w_other]) + +def descr_add(self, space, w_rhs): +w_rhs = self._to_float(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented +return W_FloatObject(self.floatval + w_rhs.floatval) + +def descr_radd(self, space, w_lhs): +w_lhs = self._to_float(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented +return W_FloatObject(w_lhs.floatval + self.floatval) + +def descr_sub(self, space, w_rhs): +w_rhs = self._to_float(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented +return W_FloatObject(self.floatval - w_rhs.floatval) + +def descr_rsub(self, space, w_lhs): +w_lhs = self._to_float(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented +return W_FloatObject(w_lhs.floatval - self.floatval) + +def descr_mul(self, space, w_rhs): +w_rhs = self._to_float(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented +return W_FloatObject(self.floatval * w_rhs.floatval) + +def descr_rmul(self, space, w_lhs): +w_lhs = self._to_float(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented +return W_FloatObject(w_lhs.floatval * self.floatval) + +def descr_div(self, space, w_rhs): +w_rhs = self._to_float(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented +rhs = w_rhs.floatval +if rhs == 0.0: +raise OperationError(space.w_ZeroDivisionError, space.wrap("float division")) +return W_FloatObject(self.floatval / rhs) + +def descr_rdiv(self, space, w_lhs): +w_lhs = self._to_float(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented +lhs = w_lhs.floatval +if lhs == 0.0: +raise OperationError(space.w_ZeroDivisionError, space.wrap("float division")) +return W_FloatObject(lhs / self.floatval) + +def descr_floordiv(self, space, w_rhs): +w_rhs = self._to_float(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented +return _divmod_w(space, self, w_rhs)[0] + +def descr_rfloordiv(self, space, w_lhs): +w_lhs = self._to_float(space, w_lhs) +if w_lhs is None: +return space.w_NotImplemented +return _divmod_w(space, w_lhs, self)[0] + +def descr_mod(self, space, w_rhs): +w_rhs = self._to_float(space, w_rhs) +if w_rhs is None: +return space.w_NotImplemented +x = self.floatval +y = w_rhs.floatval +if y == 0.0: +raise OperationError(space.w_ZeroDivisionError, space.wrap("float modulo")) +try: +mod = math.fmod(x, y) +except ValueError: +mod = rfloat.NAN +else: +if mod: +# ensure the remainder has the same sign as the denominator +if (y < 0.0) != (mod < 0.0): +mod += y +else: +# the remainder is zero, and in the presence of signed zeroes +# fmod returns different results across platforms; ensure +# it has the same sign as the denominator; we'd like to do +# "mod = y * 0.0", but that may get optimized away +mod = copysign(0.0, y) + +return W_FloatObject(mod) + +def descr_rmod(self, space, w_lhs): +w_lhs = self._to_float(space, w_l
[pypy-commit] pypy remove-remaining-smm: Kill floattype.py.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69321:2ae7ef84292e Date: 2014-02-24 01:08 +0100 http://bitbucket.org/pypy/pypy/changeset/2ae7ef84292e/ Log:Kill floattype.py. diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py --- a/pypy/module/micronumpy/interp_boxes.py +++ b/pypy/module/micronumpy/interp_boxes.py @@ -3,7 +3,7 @@ from pypy.interpreter.gateway import interp2app, unwrap_spec from pypy.interpreter.typedef import TypeDef, GetSetProperty from pypy.objspace.std.bytesobject import W_BytesObject -from pypy.objspace.std.floattype import float_typedef +from pypy.objspace.std.floatobject import W_FloatObject from pypy.objspace.std.unicodeobject import W_UnicodeObject from pypy.objspace.std.intobject import W_IntObject from pypy.objspace.std.complexobject import W_ComplexObject @@ -750,7 +750,7 @@ __reduce__ = interp2app(W_Float32Box.descr_reduce), ) -W_Float64Box.typedef = TypeDef("float64", (W_FloatingBox.typedef, float_typedef), +W_Float64Box.typedef = TypeDef("float64", (W_FloatingBox.typedef, W_FloatObject.typedef), __module__ = "numpy", __new__ = interp2app(W_Float64Box.descr__new__.im_func), __reduce__ = interp2app(W_Float64Box.descr_reduce), diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -1,24 +1,114 @@ +import math import operator +import sys from pypy.interpreter.error import OperationError, oefmt -from pypy.objspace.std import model, newformat -from pypy.objspace.std.floattype import float_typedef, W_AbstractFloatObject +from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault, interpindirect2app +from pypy.interpreter.typedef import GetSetProperty +from pypy.objspace.std import newformat +from pypy.objspace.std.longobject import W_LongObject from pypy.objspace.std.multimethod import FailedToImplementArgs from pypy.objspace.std.model import registerimplementation, W_Object from pypy.objspace.std.register_all import register_all -from pypy.objspace.std.noneobject import W_NoneObject -from pypy.objspace.std.longobject import W_LongObject +from pypy.objspace.std.stdtypedef import StdTypeDef, SMM +from rpython.rlib import rarithmetic, rfloat from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask, LONG_BIT from rpython.rlib.rfloat import ( isinf, isnan, isfinite, INFINITY, NAN, copysign, formatd, DTSF_ADD_DOT_0, DTSF_STR_PRECISION, float_as_rbigint_ratio) from rpython.rlib.rbigint import rbigint -from rpython.rlib import rfloat +from rpython.rlib.rstring import ParseStringError from rpython.tool.sourcetools import func_with_new_name +from rpython.rlib.unroll import unrolling_iterable +from pypy.objspace.std.intobject import W_IntObject -import math -from pypy.objspace.std.intobject import W_IntObject + +float_as_integer_ratio = SMM("as_integer_ratio", 1) +float_is_integer = SMM("is_integer", 1) +float_hex = SMM("hex", 1) + + +class W_AbstractFloatObject(W_Object): +__slots__ = () + +def is_w(self, space, w_other): +from rpython.rlib.longlong2float import float2longlong +if not isinstance(w_other, W_AbstractFloatObject): +return False +if self.user_overridden_class or w_other.user_overridden_class: +return self is w_other +one = float2longlong(space.float_w(self)) +two = float2longlong(space.float_w(w_other)) +return one == two + +def immutable_unique_id(self, space): +if self.user_overridden_class: +return None +from rpython.rlib.longlong2float import float2longlong +from pypy.objspace.std.model import IDTAG_FLOAT as tag +val = float2longlong(space.float_w(self)) +b = rbigint.fromrarith_int(val) +b = b.lshift(3).or_(rbigint.fromint(tag)) +return space.newlong_from_rbigint(b) + +def int(self, space): +raise NotImplementedError + + +def detect_floatformat(): +from rpython.rtyper.lltypesystem import rffi, lltype +buf = lltype.malloc(rffi.CCHARP.TO, 8, flavor='raw') +rffi.cast(rffi.DOUBLEP, buf)[0] = 9006104071832581.0 +packed = rffi.charpsize2str(buf, 8) +if packed == "\x43\x3f\xff\x01\x02\x03\x04\x05": +double_format = 'IEEE, big-endian' +elif packed == "\x05\x04\x03\x02\x01\xff\x3f\x43": +double_format = 'IEEE, little-endian' +else: +double_format = 'unknown' +lltype.free(buf, flavor='raw') +# +buf = lltype.malloc(rffi.CCHARP.TO, 4, flavor='raw') +rffi.cast(rffi.FLOATP, buf)[0] = rarithmetic.r_singlefloat(16711938.0) +packed = rffi.charpsize2str(buf, 4) +if packed == "\x4b\x7f\x01\x02": +float_format = 'IEEE, big-endian' +elif packed == "\x02\x01\x7f\x4b": +float_format = 'IEEE, little-endian' +else: +float_format = 'unknown' +lltype.free(buf, flavor='raw') + +
[pypy-commit] pypy remove-remaining-smm: Kill float's comparison SMMs.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69323:9b1c802844d9 Date: 2014-02-24 02:49 +0100 http://bitbucket.org/pypy/pypy/changeset/9b1c802844d9/ Log:Kill float's comparison SMMs. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -17,11 +17,8 @@ DTSF_ADD_DOT_0, DTSF_STR_PRECISION, float_as_rbigint_ratio) from rpython.rlib.rbigint import rbigint from rpython.rlib.rstring import ParseStringError -from rpython.tool.sourcetools import func_with_new_name from rpython.rlib.unroll import unrolling_iterable -from pypy.objspace.std.intobject import W_IntObject - float_as_integer_ratio = SMM("as_integer_ratio", 1) float_is_integer = SMM("is_integer", 1) @@ -110,6 +107,53 @@ return _hex_from_char(s[i]) +def make_compare_func(opname): +op = getattr(operator, opname) + +if opname == 'eq' or opname == 'ne': +def do_compare_bigint(f1, b2): +"""f1 is a float. b2 is a bigint.""" +if not isfinite(f1) or math.floor(f1) != f1: +return opname == 'ne' +b1 = rbigint.fromfloat(f1) +res = b1.eq(b2) +if opname == 'ne': +res = not res +return res +else: +def do_compare_bigint(f1, b2): +"""f1 is a float. b2 is a bigint.""" +if not isfinite(f1): +return op(f1, 0.0) +if opname == 'gt' or opname == 'le': +# 'float > long' <==> 'ceil(float) > long' +# 'float <= long' <==> 'ceil(float) <= long' +f1 = math.ceil(f1) +else: +# 'float < long' <==> 'floor(float) < long' +# 'float >= long' <==> 'floor(float) >= long' +f1 = math.floor(f1) +b1 = rbigint.fromfloat(f1) +return getattr(b1, opname)(b2) + +def _compare(self, space, w_other): +if isinstance(w_other, W_FloatObject): +return space.newbool(op(self.floatval, w_other.floatval)) +if space.isinstance_w(w_other, space.w_int): +f1 = self.floatval +i2 = w_other.intval +f2 = float(i2) +if LONG_BIT > 32 and int(f2) != i2: +res = do_compare_bigint(f1, rbigint.fromint(i2)) +else: +res = op(f1, f2) +return space.newbool(res) +if space.isinstance_w(w_other, space.w_long): +return space.newbool(do_compare_bigint(self.floatval, w_other.num)) +return space.w_NotImplemented +return _compare + + class W_FloatObject(W_AbstractFloatObject): """This is a implementation of the app-level 'float' type. The constructor takes an RPython float as an argument.""" @@ -327,6 +371,13 @@ return space.w_NotImplemented return space.newtuple([self, w_other]) +descr_eq = make_compare_func('eq') +descr_ne = make_compare_func('ne') +descr_lt = make_compare_func('lt') +descr_le = make_compare_func('le') +descr_gt = make_compare_func('gt') +descr_ge = make_compare_func('ge') + def descr_add(self, space, w_rhs): w_rhs = self._to_float(space, w_rhs) if w_rhs is None: @@ -498,6 +549,13 @@ fromhex = interp2app(W_FloatObject.descr_fromhex, as_classmethod=True), __coerce__ = interp2app(W_FloatObject.descr_coerce), +__eq__ = interp2app(W_FloatObject.descr_eq), +__ne__ = interp2app(W_FloatObject.descr_ne), +__lt__ = interp2app(W_FloatObject.descr_lt), +__le__ = interp2app(W_FloatObject.descr_le), +__gt__ = interp2app(W_FloatObject.descr_gt), +__ge__ = interp2app(W_FloatObject.descr_ge), + __add__ = interp2app(W_FloatObject.descr_add), __radd__ = interp2app(W_FloatObject.descr_radd), __sub__ = interp2app(W_FloatObject.descr_sub), @@ -614,113 +672,6 @@ def format__Float_ANY(space, w_float, w_spec): return newformat.run_formatter(space, w_spec, "format_float", w_float) -# -# A mess to handle all cases of float comparison without relying -# on delegation, which can unfortunately loose precision when -# casting an int or a long to a float. - -def list_compare_funcs(declarator): -for op in ['lt', 'le', 'eq', 'ne', 'gt', 'ge']: -func, name = declarator(op) -globals()[name] = func_with_new_name(func, name) - -def _reverse(opname): -if opname[0] == 'l': return 'g' + opname[1:] -elif opname[0] == 'g': return 'l' + opname[1:] -else: return opname - - -def declare_compare_bigint(opname): -"""Return a helper function that implements a float-bigint comparison.""" -op = getattr(operator, opname) -# -if opname == 'eq' or opname == 'ne': -def do_compare_bigint(f1, b2): -"""f1 is a float. b2 is a bigint.""" -if not isfinite(f1) or m
[pypy-commit] pypy default: fix some dtype str/repr cases
Author: Brian Kearns Branch: Changeset: r69325:00beb1b741ed Date: 2014-02-23 20:52 -0500 http://bitbucket.org/pypy/pypy/changeset/00beb1b741ed/ Log:fix some dtype str/repr cases diff --git a/pypy/module/micronumpy/arrayimpl/sort.py b/pypy/module/micronumpy/arrayimpl/sort.py --- a/pypy/module/micronumpy/arrayimpl/sort.py +++ b/pypy/module/micronumpy/arrayimpl/sort.py @@ -10,7 +10,7 @@ from rpython.rlib.unroll import unrolling_iterable from rpython.rlib.rarithmetic import widen from rpython.rlib.objectmodel import specialize -from pypy.interpreter.error import OperationError +from pypy.interpreter.error import OperationError, oefmt from pypy.module.micronumpy.base import W_NDimArray from pypy.module.micronumpy import interp_dtype, types from pypy.module.micronumpy.iter import AxisIterator @@ -175,9 +175,9 @@ return cache._lookup(tp)(arr, space, w_axis, itemtype.get_element_size()) # XXX this should probably be changed -raise OperationError(space.w_NotImplementedError, - space.wrap("sorting of non-numeric types " + \ - "'%s' is not implemented" % arr.dtype.get_name(), )) +raise oefmt(space.w_NotImplementedError, +"sorting of non-numeric types '%s' is not implemented", +arr.dtype.name) all_types = (types.all_float_types + types.all_complex_types + types.all_int_types) @@ -318,9 +318,9 @@ return cache._lookup(tp)(arr, space, w_axis, itemtype.get_element_size()) # XXX this should probably be changed -raise OperationError(space.w_NotImplementedError, - space.wrap("sorting of non-numeric types " + \ - "'%s' is not implemented" % arr.dtype.get_name(), )) +raise oefmt(space.w_NotImplementedError, +"sorting of non-numeric types '%s' is not implemented", +arr.dtype.name) all_types = (types.all_float_types + types.all_complex_types + types.all_int_types) diff --git a/pypy/module/micronumpy/interp_dtype.py b/pypy/module/micronumpy/interp_dtype.py --- a/pypy/module/micronumpy/interp_dtype.py +++ b/pypy/module/micronumpy/interp_dtype.py @@ -119,21 +119,30 @@ def get_size(self): return self.size * self.itemtype.get_element_size() -def get_name(self): -if self.char == 'S': -return '|S' + str(self.get_size()) -return self.name - def get_float_dtype(self, space): assert self.kind == NPY.COMPLEXLTR assert self.float_type is not None return get_dtype_cache(space).dtypes_by_name[self.byteorder + self.float_type] def descr_str(self, space): -return space.wrap(self.get_name()) +if not self.is_record_type(): +if self.char == 'S': +s = '|S' + str(self.get_size()) +else: +s = self.name +return space.wrap(s) +return space.str(self.descr_get_descr(space)) def descr_repr(self, space): -return space.wrap("dtype('%s')" % self.get_name()) +if not self.is_record_type(): +if self.char == 'S': +s = 'S' + str(self.get_size()) +else: +s = self.name +r = space.wrap(s) +else: +r = self.descr_get_descr(space) +return space.wrap("dtype(%s)" % space.str_w(space.repr(r))) def descr_get_itemsize(self, space): return space.wrap(self.get_size()) diff --git a/pypy/module/micronumpy/test/test_dtypes.py b/pypy/module/micronumpy/test/test_dtypes.py --- a/pypy/module/micronumpy/test/test_dtypes.py +++ b/pypy/module/micronumpy/test/test_dtypes.py @@ -160,6 +160,12 @@ d = dtype('?') assert repr(d) == "dtype('bool')" assert str(d) == "bool" +d = dtype([('', 'https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy default: handle ndarray getitem with ellipsis
Author: Brian Kearns Branch: Changeset: r69324:b7dd23fb75be Date: 2014-02-23 20:28 -0500 http://bitbucket.org/pypy/pypy/changeset/b7dd23fb75be/ Log:handle ndarray getitem with ellipsis diff --git a/pypy/module/micronumpy/compile.py b/pypy/module/micronumpy/compile.py --- a/pypy/module/micronumpy/compile.py +++ b/pypy/module/micronumpy/compile.py @@ -75,6 +75,7 @@ def __init__(self): """NOT_RPYTHON""" self.fromcache = InternalSpaceCache(self).getorbuild +self.w_Ellipsis = special.Ellipsis(self) self.w_NotImplemented = special.NotImplemented(self) def _freeze_(self): diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py --- a/pypy/module/micronumpy/interp_numarray.py +++ b/pypy/module/micronumpy/interp_numarray.py @@ -218,7 +218,9 @@ prefix) def descr_getitem(self, space, w_idx): -if isinstance(w_idx, W_NDimArray) and w_idx.get_dtype().is_bool_type() \ +if space.is_w(w_idx, space.w_Ellipsis): +return self +elif isinstance(w_idx, W_NDimArray) and w_idx.get_dtype().is_bool_type() \ and len(w_idx.get_shape()) > 0: return self.getitem_filter(space, w_idx) try: diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py --- a/pypy/module/micronumpy/test/test_numarray.py +++ b/pypy/module/micronumpy/test/test_numarray.py @@ -2259,6 +2259,13 @@ a[b] = 1. assert (a == [[1., 1., 1.]]).all() +def test_ellipsis_indexing(self): +import numpy as np +a = np.array(1.5) +assert a[...] is a +a = np.array([1, 2, 3]) +assert a[...] is a + class AppTestNumArrayFromBuffer(BaseNumpyAppTest): spaceconfig = dict(usemodules=["micronumpy", "array", "mmap"]) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy py3k: Redo 992e29624c5f, this time hopefully right -- it's a bit of a mess to call
Author: Armin Rigo Branch: py3k Changeset: r69326:f629c3ae62be Date: 2014-02-22 08:07 +0100 http://bitbucket.org/pypy/pypy/changeset/f629c3ae62be/ Log:Redo 992e29624c5f, this time hopefully right -- it's a bit of a mess to call c_mmap_safe() from two different points in translation (grafted from b771fb9117d277848fd63d41db349e53a635397a) diff --git a/rpython/rlib/rmmap.py b/rpython/rlib/rmmap.py --- a/rpython/rlib/rmmap.py +++ b/rpython/rlib/rmmap.py @@ -10,6 +10,7 @@ from rpython.rtyper.lltypesystem import rffi, lltype from rpython.rlib import rposix from rpython.translator.tool.cbuild import ExternalCompilationInfo +from rpython.rlib.objectmodel import we_are_translated from rpython.rlib.nonconst import NonConstant from rpython.rlib.rarithmetic import intmask @@ -675,14 +676,20 @@ return m def alloc_hinted(hintp, map_size): -flags = NonConstant(MAP_PRIVATE | MAP_ANONYMOUS) -prot = NonConstant(PROT_EXEC | PROT_READ | PROT_WRITE) +flags = MAP_PRIVATE | MAP_ANONYMOUS +prot = PROT_EXEC | PROT_READ | PROT_WRITE +if we_are_translated(): +flags = NonConstant(flags) +prot = NonConstant(prot) return c_mmap_safe(hintp, map_size, prot, flags, -1, 0) def clear_large_memory_chunk_aligned(addr, map_size): addr = rffi.cast(PTR, addr) -flags = NonConstant(MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS) -prot = NonConstant(PROT_READ | PROT_WRITE) +flags = MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS +prot = PROT_READ | PROT_WRITE +if we_are_translated(): +flags = NonConstant(flags) +prot = NonConstant(prot) res = c_mmap_safe(addr, map_size, prot, flags, -1, 0) return res == addr ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Make W_FloatObject a W_Root.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69333:ea78a007be31 Date: 2014-02-24 03:53 +0100 http://bitbucket.org/pypy/pypy/changeset/ea78a007be31/ Log:Make W_FloatObject a W_Root. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -2,13 +2,12 @@ import operator import sys +from pypy.interpreter.baseobjspace import W_Root from pypy.interpreter.error import OperationError, oefmt from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault from pypy.interpreter.typedef import GetSetProperty from pypy.objspace.std import newformat from pypy.objspace.std.longobject import W_LongObject -from pypy.objspace.std.model import registerimplementation, W_Object -from pypy.objspace.std.register_all import register_all from pypy.objspace.std.stdtypedef import StdTypeDef from rpython.rlib import rarithmetic, rfloat from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask, LONG_BIT @@ -122,7 +121,7 @@ return _compare -class W_FloatObject(W_Object): +class W_FloatObject(W_Root): """This is a implementation of the app-level 'float' type. The constructor takes an RPython float as an argument.""" _immutable_fields_ = ['floatval'] @@ -139,7 +138,7 @@ def int(self, space): if (type(self) is not W_FloatObject and space.is_overloaded(self, space.w_float, '__int__')): -return W_Object.int(self, space) +return W_Root.int(self, space) try: value = ovfcheck_float_to_int(self.floatval) except OverflowError: @@ -634,8 +633,6 @@ return space.wrap("0x%sp%s%d" % (s, sign, exp)) -registerimplementation(W_FloatObject) - W_FloatObject.typedef = StdTypeDef("float", __doc__ = '''float(x) -> floating point number @@ -691,7 +688,6 @@ as_integer_ratio = interp2app(W_FloatObject.descr_as_integer_ratio), hex = interp2app(W_FloatObject.descr_hex), ) -W_FloatObject.typedef.registermethods(globals()) def _char_from_hex(number): @@ -891,6 +887,3 @@ if negate_result: z = -z return z - - -register_all(vars(), globals()) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Remove trailing whitespace.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69331:cfa332355a56 Date: 2014-02-24 03:43 +0100 http://bitbucket.org/pypy/pypy/changeset/cfa332355a56/ Log:Remove trailing whitespace. diff --git a/pypy/objspace/std/test/test_floatobject.py b/pypy/objspace/std/test/test_floatobject.py --- a/pypy/objspace/std/test/test_floatobject.py +++ b/pypy/objspace/std/test/test_floatobject.py @@ -61,7 +61,7 @@ class AppTestAppFloatTest: spaceconfig = dict(usemodules=['binascii', 'rctime']) - + def setup_class(cls): cls.w_py26 = cls.space.wrap(sys.version_info >= (2, 6)) @@ -812,7 +812,7 @@ def check(a, b): assert (a, math.copysign(1.0, a)) == (b, math.copysign(1.0, b)) - + check(mod(-1.0, 1.0), 0.0) check(mod(-1e-100, 1.0), 1.0) check(mod(-0.0, 1.0), 0.0) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Organize imports.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69332:86996b85032a Date: 2014-02-24 03:46 +0100 http://bitbucket.org/pypy/pypy/changeset/86996b85032a/ Log:Organize imports. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -12,10 +12,10 @@ from pypy.objspace.std.stdtypedef import StdTypeDef from rpython.rlib import rarithmetic, rfloat from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask, LONG_BIT +from rpython.rlib.rbigint import rbigint from rpython.rlib.rfloat import ( isinf, isnan, isfinite, INFINITY, NAN, copysign, formatd, DTSF_ADD_DOT_0, DTSF_STR_PRECISION, float_as_rbigint_ratio) -from rpython.rlib.rbigint import rbigint from rpython.rlib.rstring import ParseStringError from rpython.rlib.unroll import unrolling_iterable diff --git a/pypy/objspace/std/test/test_floatobject.py b/pypy/objspace/std/test/test_floatobject.py --- a/pypy/objspace/std/test/test_floatobject.py +++ b/pypy/objspace/std/test/test_floatobject.py @@ -1,16 +1,16 @@ -from pypy.objspace.std import floatobject as fobj -from pypy.objspace.std.multimethod import FailedToImplement -import py, sys +import sys + +from pypy.objspace.std.floatobject import W_FloatObject + class TestW_FloatObject: - def test_pow_fff(self): x = 10.0 y = 2.0 z = 13.0 -f1 = fobj.W_FloatObject(x) -f2 = fobj.W_FloatObject(y) -f3 = fobj.W_FloatObject(z) +f1 = W_FloatObject(x) +f2 = W_FloatObject(y) +f3 = W_FloatObject(z) self.space.raises_w(self.space.w_TypeError, f1.descr_pow, self.space, f2, f3) @@ -18,20 +18,20 @@ def test_pow_ffn(self): x = 10.0 y = 2.0 -f1 = fobj.W_FloatObject(x) -f2 = fobj.W_FloatObject(y) +f1 = W_FloatObject(x) +f2 = W_FloatObject(y) v = f1.descr_pow(self.space, f2, self.space.w_None) assert v.floatval == x ** y -f1 = fobj.W_FloatObject(-1.23) -f2 = fobj.W_FloatObject(-4.56) +f1 = W_FloatObject(-1.23) +f2 = W_FloatObject(-4.56) self.space.raises_w(self.space.w_ValueError, f1.descr_pow, self.space, f2, self.space.w_None) x = -10 y = 2.0 -f1 = fobj.W_FloatObject(x) -f2 = fobj.W_FloatObject(y) +f1 = W_FloatObject(x) +f2 = W_FloatObject(y) v = f1.descr_pow(self.space, f2, self.space.w_None) assert v.floatval == x**y ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Move descr___getformat__().
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69329:ae5780334104 Date: 2014-02-24 03:31 +0100 http://bitbucket.org/pypy/pypy/changeset/ae5780334104/ Log:Move descr___getformat__(). diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -199,6 +199,16 @@ return w_obj @staticmethod +@unwrap_spec(kind=str) +def descr___getformat__(space, w_cls, kind): +if kind == "float": +return space.wrap(_float_format) +elif kind == "double": +return space.wrap(_double_format) +raise OperationError(space.w_ValueError, + space.wrap("only float and double are valid")) + +@staticmethod @unwrap_spec(s=str) def descr_fromhex(space, w_cls, s): length = len(s) @@ -573,16 +583,6 @@ def descr_get_imag(self, space): return space.wrap(0.0) -@staticmethod -@unwrap_spec(kind=str) -def descr___getformat__(space, w_cls, kind): -if kind == "float": -return space.wrap(_float_format) -elif kind == "double": -return space.wrap(_double_format) -raise OperationError(space.w_ValueError, - space.wrap("only float and double are valid")) - registerimplementation(W_FloatObject) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill W_AbstractFloatObject, its only subclass is W_FloatObject.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69327:0893e9d51fd5 Date: 2014-02-24 02:54 +0100 http://bitbucket.org/pypy/pypy/changeset/0893e9d51fd5/ Log:Kill W_AbstractFloatObject, its only subclass is W_FloatObject. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -25,33 +25,6 @@ float_hex = SMM("hex", 1) -class W_AbstractFloatObject(W_Object): -__slots__ = () - -def is_w(self, space, w_other): -from rpython.rlib.longlong2float import float2longlong -if not isinstance(w_other, W_AbstractFloatObject): -return False -if self.user_overridden_class or w_other.user_overridden_class: -return self is w_other -one = float2longlong(space.float_w(self)) -two = float2longlong(space.float_w(w_other)) -return one == two - -def immutable_unique_id(self, space): -if self.user_overridden_class: -return None -from rpython.rlib.longlong2float import float2longlong -from pypy.objspace.std.model import IDTAG_FLOAT as tag -val = float2longlong(space.float_w(self)) -b = rbigint.fromrarith_int(val) -b = b.lshift(3).or_(rbigint.fromint(tag)) -return space.newlong_from_rbigint(b) - -def int(self, space): -raise NotImplementedError - - def detect_floatformat(): from rpython.rtyper.lltypesystem import rffi, lltype buf = lltype.malloc(rffi.CCHARP.TO, 8, flavor='raw') @@ -154,7 +127,7 @@ return _compare -class W_FloatObject(W_AbstractFloatObject): +class W_FloatObject(W_Object): """This is a implementation of the app-level 'float' type. The constructor takes an RPython float as an argument.""" _immutable_fields_ = ['floatval'] @@ -179,6 +152,26 @@ else: return space.newint(value) +def is_w(self, space, w_other): +from rpython.rlib.longlong2float import float2longlong +if not isinstance(w_other, W_FloatObject): +return False +if self.user_overridden_class or w_other.user_overridden_class: +return self is w_other +one = float2longlong(space.float_w(self)) +two = float2longlong(space.float_w(w_other)) +return one == two + +def immutable_unique_id(self, space): +if self.user_overridden_class: +return None +from rpython.rlib.longlong2float import float2longlong +from pypy.objspace.std.model import IDTAG_FLOAT as tag +val = float2longlong(space.float_w(self)) +b = rbigint.fromrarith_int(val) +b = b.lshift(3).or_(rbigint.fromint(tag)) +return space.newlong_from_rbigint(b) + def __repr__(self): return "" % self.floatval @@ -578,7 +571,7 @@ conjugate = interp2app(W_FloatObject.descr_conjugate), real = GetSetProperty(W_FloatObject.descr_get_real), imag = GetSetProperty(W_FloatObject.descr_get_imag), -__int__ = interpindirect2app(W_AbstractFloatObject.int), +__int__ = interpindirect2app(W_FloatObject.int), ) W_FloatObject.typedef.registermethods(globals()) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Kill last float SMMs.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69330:a2d089c94859 Date: 2014-02-24 03:41 +0100 http://bitbucket.org/pypy/pypy/changeset/a2d089c94859/ Log:Kill last float SMMs. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -9,7 +9,7 @@ from pypy.objspace.std.longobject import W_LongObject from pypy.objspace.std.model import registerimplementation, W_Object from pypy.objspace.std.register_all import register_all -from pypy.objspace.std.stdtypedef import StdTypeDef, SMM +from pypy.objspace.std.stdtypedef import StdTypeDef from rpython.rlib import rarithmetic, rfloat from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask, LONG_BIT from rpython.rlib.rfloat import ( @@ -20,11 +20,6 @@ from rpython.rlib.unroll import unrolling_iterable -float_as_integer_ratio = SMM("as_integer_ratio", 1) -float_is_integer = SMM("is_integer", 1) -float_hex = SMM("hex", 1) - - def detect_floatformat(): from rpython.rtyper.lltypesystem import rffi, lltype buf = lltype.malloc(rffi.CCHARP.TO, 8, flavor='raw') @@ -574,15 +569,70 @@ return space.w_NotImplemented return w_lhs.descr_pow(space, self, w_third_arg) -def descr_conjugate(self, space): -return space.float(self) - def descr_get_real(self, space): return space.float(self) def descr_get_imag(self, space): return space.wrap(0.0) +def descr_conjugate(self, space): +return space.float(self) + +def descr_is_integer(self, space): +v = self.floatval +if not rfloat.isfinite(v): +return space.w_False +return space.wrap(math.floor(v) == v) + +def descr_as_integer_ratio(self, space): +value = self.floatval +try: +num, den = float_as_rbigint_ratio(value) +except OverflowError: +w_msg = space.wrap("cannot pass infinity to as_integer_ratio()") +raise OperationError(space.w_OverflowError, w_msg) +except ValueError: +w_msg = space.wrap("cannot pass nan to as_integer_ratio()") +raise OperationError(space.w_ValueError, w_msg) + +w_num = space.newlong_from_rbigint(num) +w_den = space.newlong_from_rbigint(den) +# Try to return int +return space.newtuple([space.int(w_num), space.int(w_den)]) + +def descr_hex(self, space): +value = self.floatval +if not isfinite(value): +return self.descr_str(space) +if value == 0.0: +if copysign(1., value) == -1.: +return space.wrap("-0x0.0p+0") +else: +return space.wrap("0x0.0p+0") +mant, exp = math.frexp(value) +shift = 1 - max(rfloat.DBL_MIN_EXP - exp, 0) +mant = math.ldexp(mant, shift) +mant = abs(mant) +exp -= shift +result = ['\0'] * ((TOHEX_NBITS - 1) // 4 + 2) +result[0] = _char_from_hex(int(mant)) +mant -= int(mant) +result[1] = "." +for i in range((TOHEX_NBITS - 1) // 4): +mant *= 16.0 +result[i + 2] = _char_from_hex(int(mant)) +mant -= int(mant) +if exp < 0: +sign = "-" +else: +sign = "+" +exp = abs(exp) +s = ''.join(result) +if value < 0.0: +return space.wrap("-0x%sp%s%d" % (s, sign, exp)) +else: +return space.wrap("0x%sp%s%d" % (s, sign, exp)) + registerimplementation(W_FloatObject) @@ -634,9 +684,12 @@ __pow__ = interp2app(W_FloatObject.descr_pow), __rpow__ = interp2app(W_FloatObject.descr_rpow), -conjugate = interp2app(W_FloatObject.descr_conjugate), real = GetSetProperty(W_FloatObject.descr_get_real), imag = GetSetProperty(W_FloatObject.descr_get_imag), +conjugate = interp2app(W_FloatObject.descr_conjugate), +is_integer = interp2app(W_FloatObject.descr_is_integer), +as_integer_ratio = interp2app(W_FloatObject.descr_as_integer_ratio), +hex = interp2app(W_FloatObject.descr_hex), ) W_FloatObject.typedef.registermethods(globals()) @@ -646,39 +699,6 @@ TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4 -def float_hex__Float(space, w_float): -value = w_float.floatval -if not isfinite(value): -return w_float.descr_str(space) -if value == 0.0: -if copysign(1., value) == -1.: -return space.wrap("-0x0.0p+0") -else: -return space.wrap("0x0.0p+0") -mant, exp = math.frexp(value) -shift = 1 - max(rfloat.DBL_MIN_EXP - exp, 0) -mant = math.ldexp(mant, shift) -mant = abs(mant) -exp -= shift -result = ['\0'] * ((TOHEX_NBITS - 1) // 4 + 2) -result[0] = _char_from_hex(int(mant)) -mant -= int(mant) -result[1] = "." -for i in range((TOHEX_NBITS - 1) // 4): -mant *= 16.0 -
[pypy-commit] pypy remove-remaining-smm: Kill float's unary SMMs.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69328:ccf5419c3a76 Date: 2014-02-24 03:22 +0100 http://bitbucket.org/pypy/pypy/changeset/ccf5419c3a76/ Log:Kill float's unary SMMs. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -3,7 +3,7 @@ import sys from pypy.interpreter.error import OperationError, oefmt -from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault, interpindirect2app +from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault from pypy.interpreter.typedef import GetSetProperty from pypy.objspace.std import newformat from pypy.objspace.std.longobject import W_LongObject @@ -358,12 +358,65 @@ if space.isinstance_w(w_obj, space.w_long): return W_FloatObject(w_obj.tofloat(space)) +def descr_repr(self, space): +return space.wrap(float2string(self.floatval, 'r', 0)) + +def descr_str(self, space): +return space.wrap(float2string(self.floatval, 'g', DTSF_STR_PRECISION)) + +def descr_hash(self, space): +return space.wrap(_hash_float(space, self.floatval)) + +def descr_format(self, space, w_spec): +return newformat.run_formatter(space, w_spec, "format_float", self) + def descr_coerce(self, space, w_other): w_other = self._to_float(space, w_other) if w_other is None: return space.w_NotImplemented return space.newtuple([self, w_other]) +def descr_nonzero(self, space): +return space.newbool(self.floatval != 0.0) + +def descr_float(self, space): +if space.is_w(space.type(self), space.w_float): +return self +a = self.floatval +return W_FloatObject(a) + +def descr_long(self, space): +try: +return W_LongObject.fromfloat(space, self.floatval) +except OverflowError: +raise OperationError( +space.w_OverflowError, +space.wrap("cannot convert float infinity to integer")) +except ValueError: +raise OperationError(space.w_ValueError, + space.wrap("cannot convert float NaN to integer")) + +def descr_trunc(self, space): +whole = math.modf(self.floatval)[1] +try: +value = ovfcheck_float_to_int(whole) +except OverflowError: +return self.descr_long(space) +else: +return space.newint(value) + +def descr_neg(self, space): +return W_FloatObject(-self.floatval) + +def descr_pos(self, space): +return self.descr_float(space) + +def descr_abs(self, space): +return W_FloatObject(abs(self.floatval)) + +def descr_getnewargs(self, space): +return space.newtuple([self.descr_float(space)]) + descr_eq = make_compare_func('eq') descr_ne = make_compare_func('ne') descr_lt = make_compare_func('lt') @@ -540,7 +593,20 @@ __new__ = interp2app(W_FloatObject.descr__new__), __getformat__ = interp2app(W_FloatObject.descr___getformat__, as_classmethod=True), fromhex = interp2app(W_FloatObject.descr_fromhex, as_classmethod=True), +__repr__ = interp2app(W_FloatObject.descr_repr), +__str__ = interp2app(W_FloatObject.descr_str), +__hash__ = interp2app(W_FloatObject.descr_hash), +__format__ = interp2app(W_FloatObject.descr_format), __coerce__ = interp2app(W_FloatObject.descr_coerce), +__nonzero__ = interp2app(W_FloatObject.descr_nonzero), +__int__ = interp2app(W_FloatObject.int), +__float__ = interp2app(W_FloatObject.descr_float), +__long__ = interp2app(W_FloatObject.descr_long), +__trunc__ = interp2app(W_FloatObject.descr_trunc), +__neg__ = interp2app(W_FloatObject.descr_neg), +__pos__ = interp2app(W_FloatObject.descr_pos), +__abs__ = interp2app(W_FloatObject.descr_abs), +__getnewargs__ = interp2app(W_FloatObject.descr_getnewargs), __eq__ = interp2app(W_FloatObject.descr_eq), __ne__ = interp2app(W_FloatObject.descr_ne), @@ -571,40 +637,10 @@ conjugate = interp2app(W_FloatObject.descr_conjugate), real = GetSetProperty(W_FloatObject.descr_get_real), imag = GetSetProperty(W_FloatObject.descr_get_imag), -__int__ = interpindirect2app(W_FloatObject.int), ) W_FloatObject.typedef.registermethods(globals()) -# float__Float is supposed to do nothing, unless it has -# a derived float object, where it should return -# an exact one. -def float__Float(space, w_float1): -if space.is_w(space.type(w_float1), space.w_float): -return w_float1 -a = w_float1.floatval -return W_FloatObject(a) - -def long__Float(space, w_floatobj): -try: -return W_LongObject.fromfloat(space, w_floatobj.floatval) -except OverflowError: -raise OperationError( -space.w_OverflowError, -space.wrap("cannot convert
[pypy-commit] pypy remove-remaining-smm: Move _string_to_float().
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69334:3952560d233a Date: 2014-02-24 03:57 +0100 http://bitbucket.org/pypy/pypy/changeset/3952560d233a/ Log:Move _string_to_float(). diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -48,14 +48,6 @@ _double_format, _float_format = detect_floatformat() -def _string_to_float(space, w_source, string): -try: -return rfloat.string_to_float(string) -except ParseStringError as e: -from pypy.objspace.std.intobject import wrap_parsestringerror -raise wrap_parsestringerror(space, e, w_source) - - _alpha = zip("abcdef", range(10, 16)) + zip("ABCDEF", range(10, 16)) _hex_to_int = zip("0123456789", range(10)) + _alpha _hex_to_int_iterable = unrolling_iterable(_hex_to_int) @@ -172,7 +164,13 @@ @staticmethod @unwrap_spec(w_x=WrappedDefault(0.0)) def descr__new__(space, w_floattype, w_x): -from pypy.objspace.std.floatobject import W_FloatObject +def _string_to_float(space, w_source, string): +try: +return rfloat.string_to_float(string) +except ParseStringError as e: +from pypy.objspace.std.intobject import wrap_parsestringerror +raise wrap_parsestringerror(space, e, w_source) + w_value = w_x # 'x' is the keyword argument name in CPython if space.lookup(w_value, "__float__") is not None: w_obj = space.float(w_value) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Move wrap_parsestringerror() -> pypy.objspace.std.util.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69335:82db216f833a Date: 2014-02-24 04:09 +0100 http://bitbucket.org/pypy/pypy/changeset/82db216f833a/ Log:Move wrap_parsestringerror() -> pypy.objspace.std.util. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -9,6 +9,7 @@ from pypy.objspace.std import newformat from pypy.objspace.std.longobject import W_LongObject from pypy.objspace.std.stdtypedef import StdTypeDef +from pypy.objspace.std.util import wrap_parsestringerror from rpython.rlib import rarithmetic, rfloat from rpython.rlib.rarithmetic import ovfcheck_float_to_int, intmask, LONG_BIT from rpython.rlib.rbigint import rbigint @@ -168,7 +169,6 @@ try: return rfloat.string_to_float(string) except ParseStringError as e: -from pypy.objspace.std.intobject import wrap_parsestringerror raise wrap_parsestringerror(space, e, w_source) w_value = w_x # 'x' is the keyword argument name in CPython diff --git a/pypy/objspace/std/intobject.py b/pypy/objspace/std/intobject.py --- a/pypy/objspace/std/intobject.py +++ b/pypy/objspace/std/intobject.py @@ -13,8 +13,7 @@ from rpython.rlib.rarithmetic import ( LONG_BIT, is_valid_int, ovfcheck, r_longlong, r_uint, string_to_int) from rpython.rlib.rbigint import rbigint -from rpython.rlib.rstring import ( -InvalidBaseError, ParseStringError, ParseStringOverflowError) +from rpython.rlib.rstring import ParseStringError, ParseStringOverflowError from rpython.tool.sourcetools import func_renamer, func_with_new_name from pypy.interpreter import typedef @@ -26,6 +25,7 @@ from pypy.objspace.std.model import ( BINARY_OPS, CMP_OPS, COMMUTATIVE_OPS, IDTAG_INT) from pypy.objspace.std.stdtypedef import StdTypeDef +from pypy.objspace.std.util import wrap_parsestringerror SENTINEL = object() @@ -605,15 +605,6 @@ return w_res -def wrap_parsestringerror(space, e, w_source): -if isinstance(e, InvalidBaseError): -w_msg = space.wrap(e.msg) -else: -w_msg = space.wrap('%s: %s' % (e.msg, - space.str_w(space.repr(w_source -return OperationError(space.w_ValueError, w_msg) - - def _recover_with_smalllong(space): """True if there is a chance that a SmallLong would fit when an Int does not diff --git a/pypy/objspace/std/util.py b/pypy/objspace/std/util.py --- a/pypy/objspace/std/util.py +++ b/pypy/objspace/std/util.py @@ -1,3 +1,7 @@ +from pypy.interpreter.error import oefmt +from rpython.rlib.rstring import InvalidBaseError + + def negate(f): """Create a function which calls `f` and negates its result. When the result is ``space.w_NotImplemented``, ``space.w_NotImplemented`` is @@ -22,3 +26,11 @@ where = length assert where >= 0 return where + + +def wrap_parsestringerror(space, e, w_source): +if isinstance(e, InvalidBaseError): +raise oefmt(space.w_ValueError, e.msg) +else: +raise oefmt(space.w_ValueError, '%s: %s', +e.msg, space.str_w(space.repr(w_source))) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Fix imports.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69336:cc55e80e9b8a Date: 2014-02-24 04:15 +0100 http://bitbucket.org/pypy/pypy/changeset/cc55e80e9b8a/ Log:Fix imports. diff --git a/pypy/module/_csv/interp_reader.py b/pypy/module/_csv/interp_reader.py --- a/pypy/module/_csv/interp_reader.py +++ b/pypy/module/_csv/interp_reader.py @@ -7,6 +7,7 @@ from pypy.module._csv.interp_csv import _build_dialect from pypy.module._csv.interp_csv import (QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE) +from pypy.objspace.std.util import wrap_parsestringerror (START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, @@ -48,7 +49,6 @@ try: ff = string_to_float(field) except ParseStringError as e: -from pypy.objspace.std.intobject import wrap_parsestringerror raise wrap_parsestringerror(space, e, space.wrap(field)) w_obj = space.wrap(ff) else: diff --git a/pypy/objspace/std/longobject.py b/pypy/objspace/std/longobject.py --- a/pypy/objspace/std/longobject.py +++ b/pypy/objspace/std/longobject.py @@ -18,6 +18,7 @@ from pypy.objspace.std.model import ( BINARY_OPS, CMP_OPS, COMMUTATIVE_OPS, IDTAG_LONG) from pypy.objspace.std.stdtypedef import StdTypeDef +from pypy.objspace.std.util import wrap_parsestringerror def delegate_other(func): @@ -538,7 +539,6 @@ try: bigint = rbigint.fromstr2(string, base) except ParseStringError as e: -from pypy.objspace.std.intobject import wrap_parsestringerror raise wrap_parsestringerror(space, e, w_source) return newbigint(space, w_longtype, bigint) _string_to_w_long._dont_inline_ = True ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Do style changes and clean up module namespace a bit.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69340:d3d741d4b31a Date: 2014-02-24 05:07 +0100 http://bitbucket.org/pypy/pypy/changeset/d3d741d4b31a/ Log:Do style changes and clean up module namespace a bit. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -66,6 +66,9 @@ i = co_end - 1 - j return _hex_from_char(s[i]) +def _char_from_hex(number): +return "0123456789abcdef"[number] + def make_compare_func(opname): op = getattr(operator, opname) @@ -179,7 +182,8 @@ value = space.float_w(w_obj) elif (space.isinstance_w(w_value, space.w_str) or space.isinstance_w(w_value, space.w_bytearray)): -value = _string_to_float(space, w_value, space.bufferstr_w(w_value)) +value = _string_to_float(space, w_value, + space.bufferstr_w(w_value)) elif space.isinstance_w(w_value, space.w_unicode): from unicodeobject import unicode_to_decimal_w value = _string_to_float(space, w_value, @@ -291,7 +295,7 @@ elif exp >= sys.maxint // 2: raise oefmt(space.w_OverflowError, "too large") else: -exp -= 4 * float_digits +exp -= 4 * float_digits top_exp = exp + 4 * (total_digits - 1) digit = _hex_digit(s, total_digits - 1, co_end, float_digits) while digit: @@ -350,11 +354,25 @@ if space.isinstance_w(w_obj, space.w_long): return W_FloatObject(w_obj.tofloat(space)) +def _float2string(self, x, code, precision): +# we special-case explicitly inf and nan here +if isfinite(x): +s = formatd(x, code, precision, DTSF_ADD_DOT_0) +elif isinf(x): +if x > 0.0: +s = "inf" +else: +s = "-inf" +else: # isnan(x): +s = "nan" +return s + def descr_repr(self, space): -return space.wrap(float2string(self.floatval, 'r', 0)) +return space.wrap(self._float2string(self.floatval, 'r', 0)) def descr_str(self, space): -return space.wrap(float2string(self.floatval, 'g', DTSF_STR_PRECISION)) +return space.wrap(self._float2string(self.floatval, 'g', + DTSF_STR_PRECISION)) def descr_hash(self, space): return space.wrap(_hash_float(space, self.floatval)) @@ -544,8 +562,8 @@ try: result = _pow(space, x, y) except PowDomainError: -raise oefmt(space.w_ValueError, -"negative number cannot be raised to a fractional power") +raise oefmt(space.w_ValueError, "negative number cannot be raised " +"to a fractional power") return W_FloatObject(result) @unwrap_spec(w_third_arg=WrappedDefault(None)) @@ -587,6 +605,7 @@ return space.newtuple([space.int(w_num), space.int(w_den)]) def descr_hex(self, space): +TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4 value = self.floatval if not isfinite(value): return self.descr_str(space) @@ -677,27 +696,6 @@ ) -def _char_from_hex(number): -return "0123456789abcdef"[number] - -TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4 - -def float2string(x, code, precision): -# we special-case explicitly inf and nan here -if isfinite(x): -s = formatd(x, code, precision, DTSF_ADD_DOT_0) -elif isinf(x): -if x > 0.0: -s = "inf" -else: -s = "-inf" -else: # isnan(x): -s = "nan" -return s - - -# - def _hash_float(space, v): if isnan(v): return 0 @@ -785,6 +783,7 @@ return [W_FloatObject(floordiv), W_FloatObject(mod)] + class PowDomainError(ValueError): """Signals a negative number raised to a fractional power""" @@ -862,7 +861,7 @@ try: # We delegate to our implementation of math.pow() the error detection. -z = math.pow(x,y) +z = math.pow(x, y) except OverflowError: raise oefmt(space.w_OverflowError, "float power") except ValueError: ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Use oefmt and split some long lines.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69337:f5478e57e58e Date: 2014-02-24 04:30 +0100 http://bitbucket.org/pypy/pypy/changeset/f5478e57e58e/ Log:Use oefmt and split some long lines. diff --git a/pypy/objspace/std/complexobject.py b/pypy/objspace/std/complexobject.py --- a/pypy/objspace/std/complexobject.py +++ b/pypy/objspace/std/complexobject.py @@ -183,9 +183,8 @@ return (space.float_w(w_z), 0.0) elif isinstance(w_z, W_ComplexObject): return (w_z.realval, w_z.imagval) -raise OperationError(space.w_TypeError, - space.wrap("__complex__() must return" -" a complex number")) +raise oefmt(space.w_TypeError, +"__complex__() must return a complex number") # # no '__complex__' method, so we assume it is a float, @@ -272,7 +271,8 @@ return w_result def int(self, space): -raise OperationError(space.w_TypeError, space.wrap("can't convert complex to int; use int(abs(z))")) +raise oefmt(space.w_TypeError, +"can't convert complex to int; use int(abs(z))") def _to_complex(self, space, w_obj): if isinstance(w_obj, W_ComplexObject): @@ -303,27 +303,28 @@ space.isinstance_w(w_real, space.w_unicode): # a string argument if not noarg2: -raise OperationError(space.w_TypeError, - space.wrap("complex() can't take second arg" -" if first is a string")) +raise oefmt(space.w_TypeError, "complex() can't take second" + " arg if first is a string") try: realstr, imagstr = _split_complex(space.str_w(w_real)) except ValueError: -raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED)) +raise oefmt(space.w_ValueError, ERR_MALFORMED) try: realval = string_to_float(realstr) imagval = string_to_float(imagstr) except ParseStringError: -raise OperationError(space.w_ValueError, space.wrap(ERR_MALFORMED)) +raise oefmt(space.w_ValueError, ERR_MALFORMED) else: # non-string arguments -realval, imagval = unpackcomplex(space, w_real, strict_typing=False) +realval, imagval = unpackcomplex(space, w_real, + strict_typing=False) # now take w_imag into account if not noarg2: # complex(x, y) == x+y*j, even if 'y' is already a complex. -realval2, imagval2 = unpackcomplex(space, w_imag, strict_typing=False) +realval2, imagval2 = unpackcomplex(space, w_imag, + strict_typing=False) # try to preserve the signs of zeroes of realval and realval2 if imagval2 != 0.0: @@ -389,14 +390,15 @@ return space.newtuple([self, w_other]) def descr_format(self, space, w_format_spec): -return newformat.run_formatter(space, w_format_spec, "format_complex", self) +return newformat.run_formatter(space, w_format_spec, "format_complex", + self) def descr_nonzero(self, space): return space.newbool((self.realval != 0.0) or (self.imagval != 0.0)) def descr_float(self, space): -raise OperationError(space.w_TypeError, - space.wrap("can't convert complex to float; use abs(z)")) +raise oefmt(space.w_TypeError, +"can't convert complex to float; use abs(z)") def descr_neg(self, space): return W_ComplexObject(-self.realval, -self.imagval) @@ -408,7 +410,7 @@ try: return space.newfloat(math.hypot(self.realval, self.imagval)) except OverflowError, e: -raise OperationError(space.w_OverflowError, space.wrap(str(e))) +raise oefmt(space.w_OverflowError, str(e)) def descr_eq(self, space, w_other): if isinstance(w_other, W_ComplexObject): @@ -434,8 +436,8 @@ def _fail_cmp(self, space, w_other): if isinstance(w_other, W_ComplexObject): -raise OperationError(space.w_TypeError, - space.wrap('cannot compare complex numbers using <, <=, >, >=')) +raise oefmt(space.w_TypeError, +"cannot compare complex numbers using <, <=, >, >=") return space.w_NotImplemented def descr_add(self, space, w_rhs): @@ -485,7 +487,7 @@ try: return self.div(w_rhs) except ZeroDivisionError, e: -raise OperationError(space.w_ZeroDivisionError, space.wrap(str
[pypy-commit] pypy remove-remaining-smm: Fix.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69338:947db7701d1b Date: 2014-02-24 04:34 +0100 http://bitbucket.org/pypy/pypy/changeset/947db7701d1b/ Log:Fix. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -475,10 +475,10 @@ w_lhs = self._to_float(space, w_lhs) if w_lhs is None: return space.w_NotImplemented -lhs = w_lhs.floatval -if lhs == 0.0: +selfval = self.floatval +if selfval == 0.0: raise OperationError(space.w_ZeroDivisionError, space.wrap("float division")) -return W_FloatObject(lhs / self.floatval) +return W_FloatObject(w_lhs.floatval / selfval) def descr_floordiv(self, space, w_rhs): w_rhs = self._to_float(space, w_rhs) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Make W_NoneObject a W_Root.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69341:9f9e64ea5ddc Date: 2014-02-24 05:17 +0100 http://bitbucket.org/pypy/pypy/changeset/9f9e64ea5ddc/ Log:Make W_NoneObject a W_Root. diff --git a/pypy/objspace/std/model.py b/pypy/objspace/std/model.py --- a/pypy/objspace/std/model.py +++ b/pypy/objspace/std/model.py @@ -34,7 +34,6 @@ from pypy.objspace.std.objecttype import object_typedef from pypy.objspace.std.typeobject import type_typedef from pypy.objspace.std.slicetype import slice_typedef -from pypy.objspace.std.nonetype import none_typedef self.pythontypes = [value for key, value in result.__dict__.items() if not key.startswith('_')] # don't look @@ -67,6 +66,7 @@ # not-multimethod based types +self.pythontypes.append(noneobject.W_NoneObject.typedef) self.pythontypes.append(tupleobject.W_TupleObject.typedef) self.pythontypes.append(listobject.W_ListObject.typedef) self.pythontypes.append(dictmultiobject.W_DictMultiObject.typedef) diff --git a/pypy/objspace/std/noneobject.py b/pypy/objspace/std/noneobject.py --- a/pypy/objspace/std/noneobject.py +++ b/pypy/objspace/std/noneobject.py @@ -1,27 +1,23 @@ -""" - None Object implementation +from pypy.interpreter.baseobjspace import W_Root +from pypy.interpreter.gateway import interp2app +from pypy.objspace.std.stdtypedef import StdTypeDef - ok and tested -""" -from pypy.objspace.std.model import registerimplementation, W_Object -from pypy.objspace.std.register_all import register_all - -class W_NoneObject(W_Object): -from pypy.objspace.std.nonetype import none_typedef as typedef - +class W_NoneObject(W_Root): def unwrap(w_self, space): return None -registerimplementation(W_NoneObject) +def descr_nonzero(self, space): +return space.w_False + +def descr_repr(self, space): +return space.wrap('None') + W_NoneObject.w_None = W_NoneObject() -def nonzero__None(space, w_none): -return space.w_False - -def repr__None(space, w_none): -return space.wrap('None') - -register_all(vars()) - +W_NoneObject.typedef = StdTypeDef("NoneType", +__nonzero__ = interp2app(W_NoneObject.descr_nonzero), +__repr__ = interp2app(W_NoneObject.descr_repr), +) +W_NoneObject.typedef.acceptable_as_base_class = False diff --git a/pypy/objspace/std/nonetype.py b/pypy/objspace/std/nonetype.py deleted file mode 100644 --- a/pypy/objspace/std/nonetype.py +++ /dev/null @@ -1,8 +0,0 @@ -from pypy.objspace.std.stdtypedef import StdTypeDef - - -# - -none_typedef = StdTypeDef("NoneType", -) -none_typedef.acceptable_as_base_class = False diff --git a/pypy/objspace/std/test/test_noneobject.py b/pypy/objspace/std/test/test_noneobject.py --- a/pypy/objspace/std/test/test_noneobject.py +++ b/pypy/objspace/std/test/test_noneobject.py @@ -1,11 +1,7 @@ - - - class TestW_NoneObject: - def test_equality(self): assert self.space.eq_w(self.space.w_None, self.space.w_None) - + def test_inequality(self): neresult = self.space.ne(self.space.w_None, self.space.w_None) assert not self.space.is_true(neresult) ___ pypy-commit mailing list pypy-commit@python.org https://mail.python.org/mailman/listinfo/pypy-commit
[pypy-commit] pypy remove-remaining-smm: Use oefmt.
Author: Manuel Jacob Branch: remove-remaining-smm Changeset: r69339:33053f5a43be Date: 2014-02-24 04:43 +0100 http://bitbucket.org/pypy/pypy/changeset/33053f5a43be/ Log:Use oefmt. diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py --- a/pypy/objspace/std/floatobject.py +++ b/pypy/objspace/std/floatobject.py @@ -3,7 +3,7 @@ import sys from pypy.interpreter.baseobjspace import W_Root -from pypy.interpreter.error import OperationError, oefmt +from pypy.interpreter.error import oefmt from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault from pypy.interpreter.typedef import GetSetProperty from pypy.objspace.std import newformat @@ -197,8 +197,7 @@ return space.wrap(_float_format) elif kind == "double": return space.wrap(_double_format) -raise OperationError(space.w_ValueError, - space.wrap("only float and double are valid")) +raise oefmt(space.w_ValueError, "only float and double are valid") @staticmethod @unwrap_spec(s=str) @@ -209,8 +208,7 @@ while i < length and s[i].isspace(): i += 1 if i == length: -raise OperationError(space.w_ValueError, - space.wrap("invalid hex string")) +raise oefmt(space.w_ValueError, "invalid hex string") sign = 1 if s[i] == "-": sign = -1 @@ -218,8 +216,7 @@ elif s[i] == "+": i += 1 if length == i: -raise OperationError(space.w_ValueError, - space.wrap("invalid hex string")) +raise oefmt(space.w_ValueError, "invalid hex string") if s[i] == "i" or s[i] == "I": i += 1 if length - i >= 2 and s[i:i + 2].lower() == "nf": @@ -250,28 +247,24 @@ total_digits = co_end - co_start float_digits = co_end - whole_end if not total_digits: -raise OperationError(space.w_ValueError, - space.wrap("invalid hex string")) +raise oefmt(space.w_ValueError, "invalid hex string") const_one = rfloat.DBL_MIN_EXP - rfloat.DBL_MANT_DIG + sys.maxint // 2 const_two = sys.maxint // 2 + 1 - rfloat.DBL_MAX_EXP if total_digits > min(const_one, const_two) // 4: -raise OperationError(space.w_ValueError, space.wrap("way too long")) +raise oefmt(space.w_ValueError, "way too long") if i < length and (s[i] == "p" or s[i] == "P"): i += 1 if i == length: -raise OperationError(space.w_ValueError, - space.wrap("invalid hex string")) +raise oefmt(space.w_ValueError, "invalid hex string") exp_sign = 1 if s[i] == "-" or s[i] == "+": if s[i] == "-": exp_sign = -1 i += 1 if i == length: -raise OperationError(space.w_ValueError, - space.wrap("invalid hex string")) +raise oefmt(space.w_ValueError, "invalid hex string") if not s[i].isdigit(): -raise OperationError(space.w_ValueError, - space.wrap("invalid hex string")) +raise oefmt(space.w_ValueError, "invalid hex string") exp = ord(s[i]) - ord('0') i += 1 while i < length and s[i].isdigit(): @@ -296,7 +289,7 @@ if not total_digits or exp <= -sys.maxint / 2: value = 0.0 elif exp >= sys.maxint // 2: -raise OperationError(space.w_OverflowError, space.wrap("too large")) +raise oefmt(space.w_OverflowError, "too large") else: exp -= 4 * float_digits top_exp = exp + 4 * (total_digits - 1) @@ -307,8 +300,7 @@ if top_exp < rfloat.DBL_MIN_EXP - rfloat.DBL_MANT_DIG: value = 0.0 elif top_exp > rfloat.DBL_MAX_EXP: -raise OperationError(space.w_OverflowError, - space.wrap("too large")) +raise oefmt(space.w_OverflowError, "too large") else: lsb = max(top_exp, rfloat.DBL_MIN_EXP) - rfloat.DBL_MANT_DIG value = 0 @@ -341,14 +333,12 @@ mant_dig = rfloat.DBL_MANT_DIG if (top_exp == rfloat.DBL_MAX_EXP and value == math.ldexp(2 * half_eps, mant_dig)): -raise OperationError(space.w_OverflowError, -