From sanxiyn at codespeak.net Tue Feb 1 02:50:30 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 1 Feb 2005 02:50:30 +0100 (MET) Subject: [pypy-svn] r8781 - pypy/dist/pypy/lib Message-ID: <20050201015030.F146B27B55@code1.codespeak.net> Author: sanxiyn Date: Tue Feb 1 02:50:30 2005 New Revision: 8781 Added: pypy/dist/pypy/lib/README.regex pypy/dist/pypy/lib/re.py - copied unchanged from r8718, pypy/dist/pypy/lib/re.py pypy/dist/pypy/lib/sre_adapt.py - copied unchanged from r8718, pypy/dist/pypy/lib/sre_adapt.py pypy/dist/pypy/lib/sre_parse.py - copied unchanged from r8718, pypy/dist/pypy/lib/sre_parse.py Log: Undelete files, with explanation. Added: pypy/dist/pypy/lib/README.regex ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/README.regex Tue Feb 1 02:50:30 2005 @@ -0,0 +1,28 @@ +Regular Expression related modules in PyPy + +History + Seo Sanghyeon, 2004-02-01 + +See also + http://codespeak.net/pipermail/pypy-dev/2005q1/001794.html + +Following files in this directory are related to regular expression +in PyPy: re.py, dumbre.py, plexre.py, sre_adapt.py, sre_parse.py. + +re.py contains backend-neutral interfaces and utilities. + +re.py imports Pattern class, with signature __init__(self, pattern, flags), +from backends. Pattern class implements methods of _sre.SRE_Pattern, +like match and search. + +dumbre.py is a backend that exits as soon as regular expression is met. +plexre.py uses Plex module to implement regular expression. sre_adapt.py +cheats and imports CPython _sre. + +Importing CPython _sre doesn't work currently, because C types are not +succesfully faked. The reason seems to be the lack of __dict__. This is +also why we have pure Python random.py from 2.2 in this directory. + +sre_parse.py is patched because it uses deprecated __getslice__ in +a special way, and PyPy fails to interpret it correctly. Delete this +file when this is fixed. From sanxiyn at codespeak.net Tue Feb 1 02:52:48 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 1 Feb 2005 02:52:48 +0100 (MET) Subject: [pypy-svn] r8782 - pypy/dist/pypy/lib Message-ID: <20050201015248.E670027B55@code1.codespeak.net> Author: sanxiyn Date: Tue Feb 1 02:52:48 2005 New Revision: 8782 Modified: pypy/dist/pypy/lib/README.regex (props changed) Log: oops From hpk at codespeak.net Tue Feb 1 09:46:42 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 1 Feb 2005 09:46:42 +0100 (MET) Subject: [pypy-svn] r8783 - pypy/dist/pypy/documentation Message-ID: <20050201084642.6F72727B95@code1.codespeak.net> Author: hpk Date: Tue Feb 1 09:46:42 2005 New Revision: 8783 Modified: pypy/dist/pypy/documentation/howtopypy.txt Log: fix getting started information regarding pystone and testing. Modified: pypy/dist/pypy/documentation/howtopypy.txt ============================================================================== --- pypy/dist/pypy/documentation/howtopypy.txt (original) +++ pypy/dist/pypy/documentation/howtopypy.txt Tue Feb 1 09:46:42 2005 @@ -200,7 +200,7 @@ modules will not run yet, and others will run too slowly to be worth waiting for, but a few are fun to run:: - >>>> import pystone + >>>> from test2 import pystone >>>> pystone.main(10) Note that this is a slightly modified version of pystone -- the @@ -212,16 +212,17 @@ 5. To list the PyPy interpreter command line options, type:: + cd dist-pypy/pypy/interpreter python py.py --help As an example of using PyPy from the command line, you could type:: - python py.py -c "import pystone; pystone.main(10)" + python py.py -c "from test2 import pystone; pystone.main(10)" Alternatively, as with regular Python, you can simply give a script name on the command line:: - python py.py ../appspace/pystone.py + python py.py ../lib/test2/pystone.py (Note that this will run "forever" -- actually, "just" for many hours, with the current implementation of PyPy.) @@ -243,14 +244,22 @@ ``test_all.py`` is actually just a synonym for `py.test`_ which is our external testing tool. If you have installed that then you can as well just issue ``py.test DIRECTORY_OR_FILE`` in order - to perform test runs. + to perform test runs or simply start it without arguments to + run all tests below the current directory. - Finally, there are some more advanced tests (which are derived from - some of the standard CPython tests). These are not part of the unit - tests, because they take longer than the standard unit tests:: + Finally, there are standard regression tests which you can + run like this:: - cd dist-pypy/pypy/interpreter - python py.py ../appspace/builtin_types_test.py + cd dist-pypy/lib-python-2.3.4/test + python ../../pypy/test_all.py + + or if you have `installed py.test`_ then you simply say:: + + py.test + + from the lib-python-2.3.4/test directory. + +.. _`installed py.test`: http://codespeak.net/py/current/doc/getting_started.html Trying out the translator ========================= From pedronis at codespeak.net Tue Feb 1 14:17:27 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 1 Feb 2005 14:17:27 +0100 (MET) Subject: [pypy-svn] r8785 - in pypy/dist/pypy/objspace: . std Message-ID: <20050201131727.A2F5827B9A@code1.codespeak.net> Author: pedronis Date: Tue Feb 1 14:17:27 2005 New Revision: 8785 Modified: pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/objspace.py Log: class C: def __pow__(x,y): return y c = C() c ** 1 works Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Feb 1 14:17:27 2005 @@ -200,13 +200,18 @@ w_obj1, w_obj2 = w_obj2, w_obj1 w_left_impl, w_right_impl = w_right_impl, w_left_impl if w_left_impl is not None: - w_res = space.get_and_call_function(w_left_impl, w_obj1, w_obj2, - w_obj3) + if space.is_w(w_obj3, space.w_None): + w_res = space.get_and_call_function(w_left_impl, w_obj1, w_obj2) + else: + w_res = space.get_and_call_function(w_left_impl, w_obj1, w_obj2, w_obj3) if _check_notimplemented(space, w_res): return w_res if w_right_impl is not None: - w_res = space.get_and_call_function(w_right_impl, w_obj2, w_obj1, - w_obj3) + if space.is_w(w_obj3, space.w_None): + w_res = space.get_and_call_function(w_right_impl, w_obj2, w_obj1) + else: + w_res = space.get_and_call_function(w_right_impl, w_obj2, w_obj1, + w_obj3) if _check_notimplemented(space, w_res): return w_res Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Tue Feb 1 14:17:27 2005 @@ -404,10 +404,10 @@ # add all regular multimethods to StdObjSpace for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: if not hasattr(StdObjSpace.MM, _name): -## if isinstance(getattr(StdObjSpace, _name, None), MultiMethod): -## mm = getattr(StdObjSpace, _name) -## else: - mm = MultiMethod(_symbol, _arity, _specialnames) + if _name == 'pow': + mm = MultiMethod(_symbol, _arity, _specialnames, defaults=(None,)) + else: + mm = MultiMethod(_symbol, _arity, _specialnames) setattr(StdObjSpace.MM, _name, mm) if not hasattr(StdObjSpace, _name): setattr(StdObjSpace, _name, getattr(StdObjSpace.MM, _name)) From pedronis at codespeak.net Tue Feb 1 15:19:31 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 1 Feb 2005 15:19:31 +0100 (MET) Subject: [pypy-svn] r8787 - pypy/dist/pypy/lib Message-ID: <20050201141931.DA1C527B9A@code1.codespeak.net> Author: pedronis Date: Tue Feb 1 15:19:31 2005 New Revision: 8787 Modified: pypy/dist/pypy/lib/_classobj.py Log: more of old-style classes impl, rearranged how we check for __init__ presence to make a test in test_class that checks that AttributeErrors are not swallowed pass Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Tue Feb 1 15:19:31 2005 @@ -169,11 +169,8 @@ inst = object.__new__(instance) dic = inst.__dict__ dic['__class__'] = self - try: - init = self.__init__ - except AttributeError: - pass - else: + init = instance_getattr1(inst,'__init__', False) + if init: ret = init(inst, *args, **kwds) if ret is not None: raise TypeError("__init__() should return None") @@ -289,6 +286,7 @@ ret = _hash() if not isinstance(ret, int): raise TypeError("__hash__() should return an int") + return ret else: return id(self) @@ -305,21 +303,21 @@ if isinstance(key, slice) and key.step is None: func = instance_getattr1(self, '__getslice__', False) if func: - return func(key.start, key.end) + return func(key.start, key.stop) return instance_getattr1(self, '__getitem__')(key) def __setitem__(self, key, value): if isinstance(key, slice) and key.step is None: func = instance_getattr1(self, '__setslice__', False) if func: - func(key.start, key.end, value) + func(key.start, key.stop, value) instance_getattr1(self, '__setitem__')(key, value) def __delitem__(self, key): if isinstance(key, slice) and key.step is None: func = instance_getattr1(self, '__delslice__', False) if func: - func(key.start, key.end) + func(key.start, key.stop) instance_getattr1(self, '__delitem__')(key) def __contains__(self, obj): @@ -333,12 +331,13 @@ return False # unary operators - def __neg__(self): - return instance_getattr1(self, '__neg__')() - def __pos__(self): - return instance_getattr1(self, '__abs__')() - def __abs__(self): - return instance_getattr1(self, '__abs__')() + for op in "neg pos abs invert int long float oct hex".split(): + exec (""" +def __%(op)s__(self): + return instance_getattr1(self, '__%(op)s__')() +""") % {"op": op} + del op + # binary operators for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split(): @@ -378,3 +377,60 @@ """) % {"op": op} del op + + def __pow__(self, other, modulo=None): + if modulo is None: + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__pow__', False) + if func: + return func(other) + return NotImplemented + else: + return operator.pow(self, other) + else: + # CPython also doesn't try coercion in this case + func = instance_getattr1(self, '__pow__', False) + if func: + return func(other, modulo) + return NotImplemented + + + def __rpow__(self, other, modulo=None): + if modulo is None: + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__rpow__', False) + if func: + return func(other) + return NotImplemented + else: + return operator.pow(other, self) + else: + # CPython also doesn't try coercion in this case + func = instance_getattr1(self, '__rpow__', False) + if func: + return func(other, modulo) + return NotImplemented + + + def __nonzero__(self): + func = instance_getattr1(self, '__nonzero__', False) + if not func: + func = instance_getattr1(self, '__nonzero__', False) + if not func: # default to true + return True + ret = func() + if isinstance(ret, int): + if ret < 0: + raise ValueError("__nonzero__() should return >= 0") + return ret > 0 + else: + raise TypeError("__nonzero__() should return an int") + + + def __call__(self, *args, **kwds): + func = instance_getattr1(self, '__call__', False) + if not func: + raise AttributeError, "%s instance has no __call__ method" % (self.__class__.__name__) + return func(*args, **kwds) From pedronis at codespeak.net Tue Feb 1 17:16:26 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 1 Feb 2005 17:16:26 +0100 (MET) Subject: [pypy-svn] r8789 - pypy/dist/pypy/lib Message-ID: <20050201161626.2819127B9A@code1.codespeak.net> Author: pedronis Date: Tue Feb 1 17:16:25 2005 New Revision: 8789 Modified: pypy/dist/pypy/lib/_classobj.py Log: __iter__, next rich comparison operations __cmp__ up to coerce support everything is here, and we survive test_class still not integrated Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Tue Feb 1 17:16:25 2005 @@ -434,3 +434,79 @@ if not func: raise AttributeError, "%s instance has no __call__ method" % (self.__class__.__name__) return func(*args, **kwds) + + # rich comparison operations + for op in 'eq ne gt lt ge le'.split(): + exec (""" +def __%(op)s__(self, other): + try: + return instance_getattr1(self, '__%(op)s__')(other) + except AttributeError: + return NotImplemented + +""") % {"op": op} + del op + + + def __iter__(self): + func = instance_getattr1(self, '__iter__', False) + if func: + ret = func() + if not mro_lookup(ret, 'next'): + raise TypeError, ("__iter__ returned non-iterator of type %s" + % type(ret).__name__) + return ret + func = instance_getattr1(self, '__getitem__') + if not func: + raise TypeError, "iteration over non-sequence" + def seqiter(): # XXX may want to access and instatiate the internal + # sequence-iterator type instead + i = 0 + while 1: + try: + yield func(i) + except IndexError: + return + i += 1 + return seqiter() + + def next(self): + func = instance_getattr1(self, '__next__', False) + if not func: + raise TypeError, "instance has no next() method" + return func() + + def __cmp__(self, other): # do all the work here like CPython + coerced = coerce(self, other) + if coerced is None: + v = self + w = other + else: + v = coerced[0] + w = coerced[1] + if not isinstance(v, instance) and not isinstance(w, instance): + return operator.cmp(v,w) + if isinstance(v, instance): + func = instance_getattr1(v, '__cmp__', False) + if func: + res = func(w) + if isinstance(res, int): + if res > 0: + return 1 + if res < 0: + return -1 + return 0 + raise TypeError,"__cmp__ must return int" + if isinstance(w, instance): + func = instance_getattr1(v, '__cmp__', False) + if func: + res = func(v) + if isinstance(res, int): + if res > 0: + return 1 + if res < 0: + return -1 + return 0 + raise TypeError,"__cmp__ must return int" + return NotImplemented + From adim at codespeak.net Tue Feb 1 17:24:43 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 1 Feb 2005 17:24:43 +0100 (MET) Subject: [pypy-svn] r8790 - in pypy/dist/pypy/module: . test Message-ID: <20050201162443.C8CCB27B9A@code1.codespeak.net> Author: adim Date: Tue Feb 1 17:24:43 2005 New Revision: 8790 Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_builtin.py Log: made xrange a bit more CPython compatible added keywords for the sorted() builtin (looks like I forgot this one last week) Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Tue Feb 1 17:24:43 2005 @@ -466,12 +466,21 @@ class xrange: def __init__(self, start, stop=None, step=1): - if stop is None: + if not isinstance(start, (int, long, float)): + raise TypeError('an integer is required') + start = int(start) + if stop is None: self.start = 0 self.stop = start else: + if not isinstance(stop, (int, long, float)): + raise TypeError('an integer is required') + stop = int(stop) self.start = start self.stop = stop + if not isinstance(step, (int, long, float)): + raise TypeError('an integer is required') + step = int(step) if step == 0: raise ValueError, 'xrange() step-argument (arg 3) must not be zero' self.step = step @@ -931,10 +940,10 @@ def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" -def sorted(lst): +def sorted(lst, cmp=None, key=None, reverse=None): "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" sorted_lst = list(lst) - sorted_lst.sort() + sorted_lst.sort(cmp, key, reverse) return sorted_lst def reversed(iterable): Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Tue Feb 1 17:24:43 2005 @@ -132,6 +132,11 @@ assert x.stop == 10 assert x.step == 2 + x = xrange(2.3, 10.5, 2.4) + assert x.start == 2 + assert x.stop == 10 + assert x.step == 2 + raises(ValueError, xrange, 0, 1, 0) def test_xrange_up(self): @@ -159,10 +164,14 @@ def test_xrange_len(self): x = xrange(33) assert len(x) == 33 + x = xrange(33.2) + assert len(x) == 33 x = xrange(33,0,-1) assert len(x) == 33 x = xrange(33,0) assert len(x) == 0 + x = xrange(33,0.2) + assert len(x) == 0 x = xrange(0,33) assert len(x) == 33 x = xrange(0,33,-1) @@ -180,6 +189,15 @@ raises(IndexError, x.__getitem__, -18) raises(TypeError, x.__getitem__, slice(0,3,1)) + def test_xrange_bad_args(self): + raises(TypeError, xrange, '1') + raises(TypeError, xrange, None) + raises(TypeError, xrange, 3+2j) + raises(TypeError, xrange, 1, '1') + raises(TypeError, xrange, 1, 3+2j) + raises(TypeError, xrange, 1, 2, '1') + raises(TypeError, xrange, 1, 2, 3+2j) + def test_sorted(self): l = [] sorted_l = sorted(l) @@ -188,6 +206,15 @@ l = [1, 5, 2, 3] sorted_l = sorted(l) assert sorted_l == [1, 2, 3, 5] + + def test_sorted_with_keywords(self): + l = ['a', 'C', 'b'] + sorted_l = sorted(l, reverse = True) + assert sorted_l is not l + assert sorted_l == ['b', 'a', 'C'] + sorted_l = sorted(l, reverse = True, key = lambda x: x.lower()) + assert sorted_l is not l + assert sorted_l == ['C', 'b', 'a'] def test_reversed_simple_sequences(self): l = range(5) From adim at codespeak.net Tue Feb 1 18:13:55 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Tue, 1 Feb 2005 18:13:55 +0100 (MET) Subject: [pypy-svn] r8791 - in pypy/dist/pypy/module: . test Message-ID: <20050201171355.9103327B9A@code1.codespeak.net> Author: adim Date: Tue Feb 1 18:13:55 2005 New Revision: 8791 Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_builtin.py Log: trying to enumerate a non-sequence now raises a TypeError Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Tue Feb 1 18:13:55 2005 @@ -63,13 +63,6 @@ return yield result -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - i = 0 - it = iter(collection) - while 1: - yield (i, it.next()) - i += 1 def apply(function, args, kwds={}): """call a function (or other callable object) and return its result""" @@ -463,6 +456,20 @@ # ________________________________________________________________________ +class enumerate: + 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' + def __init__(self, collection): + self.iter = iter(collection) + self.index = 0 + + def __iter__(self): + return self + + def next(self): + value = self.iter.next() + index = self.index + self.index += 1 + return index, value class xrange: def __init__(self, start, stop=None, step=1): Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Tue Feb 1 18:13:55 2005 @@ -120,6 +120,9 @@ assert enum.next() == (0, 2) assert enum.next() == (1, 3) raises(StopIteration, enum.next) + raises(TypeError, enumerate, 1) + raises(TypeError, enumerate, None) + def test_xrange_args(self): x = xrange(2) From pedronis at codespeak.net Tue Feb 1 18:49:10 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 1 Feb 2005 18:49:10 +0100 (MET) Subject: [pypy-svn] r8792 - pypy/extradoc/sprintinfo Message-ID: <20050201174910.CB87727BA7@code1.codespeak.net> Author: pedronis Date: Tue Feb 1 18:49:10 2005 New Revision: 8792 Added: pypy/extradoc/sprintinfo/LeysinReport.txt (contents, props changed) Log: Leysin Sprint summary Added: pypy/extradoc/sprintinfo/LeysinReport.txt ============================================================================== --- (empty file) +++ pypy/extradoc/sprintinfo/LeysinReport.txt Tue Feb 1 18:49:10 2005 @@ -0,0 +1,152 @@ + +Hello, + +This is a summary of what was accomplished and worked on during last sprint +in Leysin. Leysin is a village in the Swiss Alps, home to Armin Rigo. The +views of the surrounding mountains were spectacular. It seemed to inspire us +to work harder. Thanks to Armin for organizing it: + +* All project participants met and worked together for the first time. + We introduced newcomers to the project to the PyPy code base and the + development process. We gave introductions to the basic functioning + and the structure of the code base. py.test our unit testing + framework was introduced to those who hadn't seen it before. + +* We also got to know our Process Manager, Bea D?ring from + Changemaker. Bea will produce her own report. If you don't know + the difference between 'project management', 'people management', + and 'process management' then you probably would enjoy learning the + differences from Bea. Bea interviewed the sprint participants to + find out about their expectations, dissemination and more general + ideas about the PyPy project and where it should go in the future. + This Sprint went extremely well, but future ones should go even + better, since we are learning how to improve all the time. Bea is + making a report that discusses this more. + +* We made plans for new and improved infrastructure. Thank you svn, we + can change our repository layout whenever we feel it would be a good + idea. :-) + +But as for technical changes to pypy itself: + +* The flow object space now uses variable names derived from the + original python ones and propagate them as possible. (Armin, Olivier + Dormond) + +* The typedunwrap branch has been merged back to the trunk. (Armin, + Samuele) + + Type specific unwraps (int_w, str_w, ...) should be used everywhere + possible. The type generic unwrap should be used only in tests, at + bootstrap time and or temporarily in cases where we are borrowing + heavily from underlying CPython, because it is annotator unfriendly + and is able to unwrap mixed types containers which are not + reasonably RPythonic. + +* Updated documentation to describe new type specific unwrap + operations. (Michael, Samuele) + +* We can now import and run the CPython tests on top of PyPy. This + found lots of small problems, and a few not so small ones. So we + made lots of small fixes, and implemented missing stuff, which was a + good way for newcomers to get to know the codebase. We added or + completed functionality to sys module: + + - _getframe() + - set/getrecursionlevel() + - exc_clear() ... + + (Adrien Di Mascio, Anders Chrigstr?m, Armin, Christian, Holger, + Jacek Generowicz, Ludovic Aubry, Olivier, Samuele, Laura) + +* Work on the annotator: + - SomeBuiltin.call + + - implemented annotation for some built-ins that were missing + + - SomeSlice support and annotating some ops involving them + + - iter built-in + + - dict methods support for SomeDict + + - preserve instance types when unifying with None + + - dict object dummy value is a W_Root subclass instance, so as not + to confuse the annotator + + - taught the annotator how to deduce the type of e in + + try: + ... + except SomeException, e: + ... <-- here + + - removal of most *args call sites used in the multi-method slicing + mechanism, like what was done for gateways. The annotator no longer + chokes on such call sites. :-) + + - wrote a small test case to show the remaining problems with the + current setup of BuiltinCode and BuiltinFrame subclasses and the + highly polymorphic BuiltinCode.func callable attribute. + + (Adrien, Michael, Samuele, some design discussion with Armin) + +* Added shortcuts is_w(.,.) (= space.is_true(space.is_(.,.))), + eq_w(.,.) (= space.is_true(space.eq(.,.))) to base object + space. (Adrien) + +* Allow arguments to be named in the stdobjspace's type's methods. As + a first example, this enables list.sort(cmp=...). (Armin) + +* Generated app-level exceptions module and from there using + geninterplevel an interp-level module (in particular this circumvent + bootstrap issues). (Christian) + + This implementation approach for built-in modules should be polished + and generalized. + +* Added python library as of 2.3.4 to our tree as + dist/lib-python-2.3.4. After discussion, it was agreed that this + should be left unchanged and modules needing modifications should be + copied to pypy/lib (renamed from appspace) and modified there, also + new pypy-specific app-level modules should live there. That means + that as general rule we should copy and borrow from this specific + Python version, in the not too distant future we will switch to + Python 2.4. + + Pypy specific modified or new app-level tests should go to + pypy/lib/test2. (Holger) + + Work is needed on how those should be run, we would like to be able + to run them both on PyPy and on CPython. + +* py.test support for unittest and output-comparing tests has been + added to dist/lib-python-2.3.4 (this is a special exception to the + above rules), as conftest.py and pypy_unittest.py in + dist/lib-python-2.3.4/test. Look at conftest.py for details, there + are lists of passing tests there (Anders, Holger) + +* Work on our sio based file implementation. (Armin did a major + rework) + +* Support for __del__ on user-defined classes. For now borrowing + functionality from underlying CPython. (Armin) + +* Work has been started on an app-level implementation for old-style + classes, we have a good chunk of the implementation but it is not + that much tested nor integrated for now. (Christian, Samuele) + +* Marcus Denker gave a presentation on Squeak, its continuations based + web framework Seaside and Croquet. We discussed whether PyPy is a + sensible approach to give in the future comprehensive Python support + as scripting language to Squeak/Croquet. + +* We set tasks for the next few weeks, and now begin to prepare for the + next Sprint, before PyCon. + +regards. +Samuele and Laura + + +PS: I (Samuele) did the listing of tech changes, sorry if I missed someone's credits. From hpk at codespeak.net Tue Feb 1 21:30:29 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 1 Feb 2005 21:30:29 +0100 (MET) Subject: [pypy-svn] r8793 - pypy/extradoc/sprintinfo Message-ID: <20050201203029.9190E27BA2@code1.codespeak.net> Author: hpk Date: Tue Feb 1 21:30:29 2005 New Revision: 8793 Modified: pypy/extradoc/sprintinfo/LeysinReport.txt Log: fixed ReST problem. Modified: pypy/extradoc/sprintinfo/LeysinReport.txt ============================================================================== --- pypy/extradoc/sprintinfo/LeysinReport.txt (original) +++ pypy/extradoc/sprintinfo/LeysinReport.txt Tue Feb 1 21:30:29 2005 @@ -82,7 +82,7 @@ except SomeException, e: ... <-- here - - removal of most *args call sites used in the multi-method slicing + - removal of most ``*args`` call sites used in the multi-method slicing mechanism, like what was done for gateways. The annotator no longer chokes on such call sites. :-) From ac at codespeak.net Wed Feb 2 11:50:23 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 2 Feb 2005 11:50:23 +0100 (MET) Subject: [pypy-svn] r8796 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050202105023.AF8EA27BA7@code1.codespeak.net> Author: ac Date: Wed Feb 2 11:50:23 2005 New Revision: 8796 Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Log: Fix typo Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/pypy_unittest.py (original) +++ pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Wed Feb 2 11:50:23 2005 @@ -42,12 +42,12 @@ def assertRaises(self, exc, call, *args, **kwargs): raises(exc, call, *args, **kwargs) - def assertAlmostEqual(self, x, y, places07, msg=None): + def assertAlmostEqual(self, x, y, places=7, msg=None): if msg is None: msg = '%r != %r within %r places' %(x, y, places) assert round(y-x, places) == 0, msg - def assertNotAlmostEqual(self, x, y, places07, msg=None): + def assertNotAlmostEqual(self, x, y, places=7, msg=None): if msg is None: msg = '%r == %r within %r places' %(x, y, places) assert round(y-x, places) != 0, msg From arigo at codespeak.net Wed Feb 2 12:23:36 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:23:36 +0100 (MET) Subject: [pypy-svn] r8797 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050202112336.6062527BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:23:36 2005 New Revision: 8797 Modified: pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/test/test_listobject.py Log: List slice assignment should accept any iterable. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Wed Feb 2 12:23:36 2005 @@ -227,6 +227,10 @@ t = w_tuple.wrappeditems return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) +def setitem__List_Slice_ANY(space, w_list, w_slice, w_iterable): + t = space.unpackiterable(w_iterable) + return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) + def _setitem_slice_helper(space, w_list, w_slice, sequence2, len2): start, stop, step, slicelength = slicetype.indices4(space, w_slice, w_list.ob_size) assert slicelength >= 0 Modified: pypy/dist/pypy/objspace/std/test/test_listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_listobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_listobject.py Wed Feb 2 12:23:36 2005 @@ -370,3 +370,8 @@ l = ['a', 'b', 'c', 'd', 'e', 'f'] raises(TypeError, l.index, 'c', 0, 4.3) raises(TypeError, l.index, 'c', 1.0, 5.6) + + def test_ass_slice(self): + l = range(6) + l[1:3] = 'abc' + assert l == [0, 'a', 'b', 'c', 3, 4, 5] From arigo at codespeak.net Wed Feb 2 12:24:58 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:24:58 +0100 (MET) Subject: [pypy-svn] r8798 - pypy/dist/pypy/objspace/std Message-ID: <20050202112458.5D2CD27BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:24:58 2005 New Revision: 8798 Modified: pypy/dist/pypy/objspace/std/stringobject.py Log: Fixed the signature of string multimethods to replace Int with ANY for integer arguments that are unwrapped with int_w() anyway. Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Wed Feb 2 12:24:58 2005 @@ -256,7 +256,7 @@ return space.wrap("".join(buffer)) -def str_split__String_None_Int(space, w_self, w_none, w_maxsplit=-1): +def str_split__String_None_ANY(space, w_self, w_none, w_maxsplit=-1): res = [] inword = 0 value = w_self._value @@ -284,7 +284,7 @@ res[i] = W_StringObject(space, res[i]) return W_ListObject(space, res) -def str_split__String_String_Int(space, w_self, w_by, w_maxsplit=-1): +def str_split__String_String_ANY(space, w_self, w_by, w_maxsplit=-1): res = [] start = 0 value = w_self._value @@ -440,7 +440,7 @@ return space.wrap(res) -def str_replace__String_String_String_Int(space, w_self, w_sub, w_by, w_maxsplit=-1): +def str_replace__String_String_String_ANY(space, w_self, w_sub, w_by, w_maxsplit=-1): input = w_self._value sub = w_sub._value @@ -591,7 +591,7 @@ return _strip_none(space, w_self, left=1, right=0) -def str_center__String_Int(space, w_self, w_arg): +def str_center__String_ANY(space, w_self, w_arg): u_self = w_self._value u_arg = space.int_w(w_arg) @@ -684,7 +684,7 @@ return distance -def str_expandtabs__String_Int(space, w_self, w_tabsize): +def str_expandtabs__String_ANY(space, w_self, w_tabsize): u_self = w_self._value u_tabsize = space.int_w(w_tabsize) @@ -701,9 +701,9 @@ return W_StringObject(space, u_expanded) -def str_splitlines__String_Int(space, w_self, w_keepends): +def str_splitlines__String_ANY(space, w_self, w_keepends): u_self = w_self._value - u_keepends = space.is_true(w_keepends) + u_keepends = space.int_w(w_keepends) # truth value, but type checked selflen = len(u_self) L = [] @@ -720,7 +720,7 @@ break return W_ListObject(space, L) -def str_zfill__String_Int(space, w_self, w_width): +def str_zfill__String_ANY(space, w_self, w_width): input = w_self._value width = space.int_w(w_width) From arigo at codespeak.net Wed Feb 2 12:26:39 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:26:39 +0100 (MET) Subject: [pypy-svn] r8799 - pypy/dist/pypy/objspace/std Message-ID: <20050202112639.0A53227BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:26:38 2005 New Revision: 8799 Modified: pypy/dist/pypy/objspace/std/stringobject.py Log: These app-level helpers are probably better off with more ANYs in their mm signature. Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Wed Feb 2 12:26:38 2005 @@ -748,7 +748,7 @@ return space.wrap("".join(buf)) -def app_str_translate__String_String_String(s, table, deletechars=''): +def app_str_translate__String_ANY_ANY(s, table, deletechars=''): """charfilter - unicode handling is not implemented Return a copy of the string where all characters occurring @@ -762,7 +762,7 @@ L = [ table[ord(s[i])] for i in range(len(s)) if s[i] not in deletechars ] return ''.join(L) -str_translate__String_String_String = gateway.app2interp(app_str_translate__String_String_String) +str_translate__String_ANY_ANY = gateway.app2interp(app_str_translate__String_ANY_ANY) def str_w__String(space, w_str): @@ -956,10 +956,10 @@ from pypy.objspace.std import iterobject return iterobject.W_SeqIterObject(space, w_list) -def app_contains__String_String(self, sub): +def app_contains__String_ANY(self, sub): return self.find(sub) >= 0 -contains__String_String = gateway.app2interp(app_contains__String_String) +contains__String_ANY = gateway.app2interp(app_contains__String_ANY) def app_repr__String(s): quote = "'" From arigo at codespeak.net Wed Feb 2 12:27:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:27:09 +0100 (MET) Subject: [pypy-svn] r8800 - pypy/dist/pypy/objspace/std Message-ID: <20050202112709.737F727BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:27:09 2005 New Revision: 8800 Modified: pypy/dist/pypy/objspace/std/objectobject.py pypy/dist/pypy/objspace/std/unicodeobject.py Log: Less delegation for multimethods. Modified: pypy/dist/pypy/objspace/std/objectobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/objectobject.py (original) +++ pypy/dist/pypy/objspace/std/objectobject.py Wed Feb 2 12:27:09 2005 @@ -6,13 +6,6 @@ 'object()' call.""" from pypy.objspace.std.objecttype import object_typedef as typedef - -# any-to-object delegation is quite trivial, because W_ObjectObject is. -def delegate__ANY(space, w_obj): - return W_ObjectObject(space) -delegate__ANY.result_class = W_ObjectObject -delegate__ANY.priority = PRIORITY_PARENT_TYPE - # ____________________________________________________________ Modified: pypy/dist/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/unicodeobject.py (original) +++ pypy/dist/pypy/objspace/std/unicodeobject.py Wed Feb 2 12:27:09 2005 @@ -9,7 +9,6 @@ return W_UnicodeObject(space, unicode(space.str_w(w_str))) delegate__String.result_class = W_UnicodeObject delegate__String.priority = PRIORITY_CHANGE_TYPE -delegate__String.can_fail = True def eq__Unicode_ANY(space, w_uni, w_other): try: From arigo at codespeak.net Wed Feb 2 12:33:41 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:33:41 +0100 (MET) Subject: [pypy-svn] r8801 - pypy/dist/pypy/objspace/std Message-ID: <20050202113341.92B0527BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:33:41 2005 New Revision: 8801 Modified: pypy/dist/pypy/objspace/std/floatobject.py Log: Minor fix. Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Wed Feb 2 12:33:41 2005 @@ -235,7 +235,7 @@ W_FloatObject(space, mod)]) def pow__Float_Float_ANY(space, w_float1, w_float2, thirdArg): - if thirdArg is not space.w_None: + if not space.is_w(thirdArg, space.w_None): raise FailedToImplement(space.w_TypeError, space.wrap("pow() 3rd argument not allowed unless all arguments are integers")) x = w_float1.floatval y = w_float2.floatval From arigo at codespeak.net Wed Feb 2 12:34:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:34:09 +0100 (MET) Subject: [pypy-svn] r8802 - pypy/dist/pypy/objspace/std Message-ID: <20050202113409.6DEE927BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:34:09 2005 New Revision: 8802 Modified: pypy/dist/pypy/objspace/std/listobject.py Log: Minor changes to lower the multimethod's dispatch arity. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Wed Feb 2 12:34:09 2005 @@ -220,11 +220,24 @@ items[idx] = w_any return space.w_None -def setitem__List_Slice_List(space, w_list, w_slice, w_list2): - return _setitem_slice_helper(space, w_list, w_slice, w_list2.ob_item, w_list2.ob_size) +# XXX the following is disabled, so that 'setitem' can be a binary multimethod. +##def setitem__List_Slice_List(space, w_list, w_slice, w_list2): +## return _setitem_slice_helper(space, w_list, w_slice, w_list2.ob_item, w_list2.ob_size) + +##def setitem__List_Slice_Tuple(space, w_list, w_slice, w_tuple): +## t = w_tuple.wrappeditems +## return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) -def setitem__List_Slice_Tuple(space, w_list, w_slice, w_tuple): - t = w_tuple.wrappeditems +def setitem__List_Slice_ANY(space, w_list, w_slice, w_iterable): + # for performance, check for common cases of w_iterable + # (this used to be done by the disabled cases of 'setitem' above) + if isinstance(w_iterable, W_ListObject): + return _setitem_slice_helper(space, w_list, w_slice, + w_iterable.ob_item, w_iterable.ob_size) + if isinstance(w_iterable, W_TupleObject): + t = w_tuple.wrappeditems + else: + t = space.unpackiterable(w_iterable) return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) def setitem__List_Slice_ANY(space, w_list, w_slice, w_iterable): @@ -346,8 +359,8 @@ items[where] = w_any w_list.ob_size += 1 -def list_insert__List_Int_ANY(space, w_list, w_where, w_any): - _ins1(w_list, w_where.intval, w_any) +def list_insert__List_ANY_ANY(space, w_list, w_where, w_any): + _ins1(w_list, space.int_w(w_where), w_any) return space.w_None def list_append__List_ANY(space, w_list, w_any): @@ -391,11 +404,11 @@ items[i] = None # note that the default value will come back wrapped!!! -def list_pop__List_Int(space, w_list, w_idx=-1): +def list_pop__List_ANY(space, w_list, w_idx=-1): if w_list.ob_size == 0: raise OperationError(space.w_IndexError, space.wrap("pop from empty list")) - i = w_idx.intval + i = space.int_w(w_idx) if i < 0: i += w_list.ob_size if i < 0 or i >= w_list.ob_size: From arigo at codespeak.net Wed Feb 2 12:34:36 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 2 Feb 2005 12:34:36 +0100 (MET) Subject: [pypy-svn] r8803 - pypy/dist/pypy/objspace/std Message-ID: <20050202113436.CDE2C27BA7@code1.codespeak.net> Author: arigo Date: Wed Feb 2 12:34:36 2005 New Revision: 8803 Modified: pypy/dist/pypy/objspace/std/dump_multimethod.py Log: Changed to display the dispatch arities of the multimethods. Modified: pypy/dist/pypy/objspace/std/dump_multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/dump_multimethod.py (original) +++ pypy/dist/pypy/objspace/std/dump_multimethod.py Wed Feb 2 12:34:36 2005 @@ -4,8 +4,6 @@ from pypy.objspace.std import StdObjSpace from pypy.objspace.std.multimethod import * -# TODO: local multimethods - IMPLEMENTATIONS = [ "pypy.objspace.std.objectobject.W_ObjectObject", "pypy.objspace.std.boolobject.W_BoolObject", @@ -145,9 +143,9 @@ if (not restrict and name != 'delegate') or name in restrict: print print '==========', name, '==========' - print >> sys.stderr, name # progress bar + print >> sys.stderr, '[%d] %s' % (mm.dispatch_arity, name) print - dump_table(mm, impls) + #dump_table(mm, impls) total += 1 if not total: print >> sys.stderr, "no matching multimethod name" From adim at codespeak.net Wed Feb 2 14:08:26 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Wed, 2 Feb 2005 14:08:26 +0100 (MET) Subject: [pypy-svn] r8804 - in pypy/dist: lib-python-2.3.4 pypy/lib/test2 pypy/module Message-ID: <20050202130826.8635727BB1@code1.codespeak.net> Author: adim Date: Wed Feb 2 14:08:26 2005 New Revision: 8804 Added: pypy/dist/lib-python-2.3.4/itertools.py pypy/dist/pypy/lib/test2/test_itertools.py - copied, changed from r8803, pypy/dist/lib-python-2.3.4/test/test_itertools.py Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/sysinterp.py Log: - added Python implementation of itertools - removed an assertion in test_itertools.py for something not feasible in PyPy (C optmization dealing with refcount for izip()) and added the modified file in pypy/lib/test2 - removed itertools from the "stolen modules" list - modified enumerate() so that it raises a TypeError instead of AttributeError when "next()" is not defined on the iterator used inside enumerate. Added: pypy/dist/lib-python-2.3.4/itertools.py ============================================================================== --- (empty file) +++ pypy/dist/lib-python-2.3.4/itertools.py Wed Feb 2 14:08:26 2005 @@ -0,0 +1,629 @@ +"""Functional tools for creating and using iterators. + +Infinite iterators: +count([n]) --> n, n+1, n+2, ... +cycle(p) --> p0, p1, ... plast, p0, p1, ... +repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times + +Iterators terminating on the shortest input sequence: +izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... +ifilter(pred, seq) --> elements of seq where pred(elem) is True +ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False +islice(seq, [start,] stop [, step]) --> elements from + seq[start:stop:step] +imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ... +starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ... +tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n +chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... +takewhile(pred, seq) --> seq[0], seq[1], until pred fails +dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails +groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v) +""" + +__all__ = ['chain', 'count', 'cycle', 'dropwhile', 'groupby', 'ifilter', + 'ifilterfalse', 'imap', 'islice', 'izip', 'repeat', 'starmap', + 'takewhile', 'tee'] + + +class chain: + """Make an iterator that returns elements from the first iterable + until it is exhausted, then proceeds to the next iterable, until + all of the iterables are exhausted. Used for treating consecutive + sequences as a single sequence. + + Equivalent to : + + def chain(*iterables): + for it in iterables: + for element in it: + yield element + """ + def __init__(self, *iterables): + self._iterables_iter = iter(map(iter, iterables)) + # little trick for the first chain.next() call + self._cur_iterable_iter = iter([]) + + def __iter__(self): + return self + + def next(self): + try: + next_elt = self._cur_iterable_iter.next() + except StopIteration: + # The current list's iterator is exhausted, switch to next one + self._cur_iterable_iter = iter(self._iterables_iter.next()) + try: + next_elt = self._cur_iterable_iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._cur_iterable_iter)) + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._cur_iterable_iter)) + + return next_elt + + +class count: + """Make an iterator that returns consecutive integers starting + with n. If not specified n defaults to zero. Does not currently + support python long integers. Often used as an argument to imap() + to generate consecutive data points. Also, used with izip() to + add sequence numbers. + + Equivalent to : + + def count(n=0): + if not isinstance(n, int): + raise TypeError("%s is not a regular integer" % n) + while True: + yield n + n += 1 + """ + def __init__(self, n=0): + if not isinstance(n, int): + raise TypeError('%s is not a regular integer' % n) + self.times = n-1 + + def __iter__(self): + return self + + def next(self): + self.times += 1 + return self.times + + def __repr__(self): + return 'count(%d)' % (self.times + 1) + + + +class cycle: + """Make an iterator returning elements from the iterable and + saving a copy of each. When the iterable is exhausted, return + elements from the saved copy. Repeats indefinitely. + + Equivalent to : + + def cycle(iterable): + saved = [] + for element in iterable: + yield element + saved.append(element) + while saved: + for element in saved: + yield element + """ + def __init__(self, iterable): + self._cur_iter = iter(iterable) + self._saved = [] + self._must_save = True + + def __iter__(self): + return self + + def next(self): + # XXX Could probably be improved + try: + next_elt = self._cur_iter.next() + if self._must_save: + self._saved.append(next_elt) + except StopIteration: + self._cur_iter = iter(self._saved) + next_elt = self._cur_iter.next() + self._must_save = False + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._cur_iter)) + return next_elt + + +class dropwhile: + """Make an iterator that drops elements from the iterable as long + as the predicate is true; afterwards, returns every + element. Note, the iterator does not produce any output until the + predicate is true, so it may have a lengthy start-up time. + + Equivalent to : + + def dropwhile(predicate, iterable): + iterable = iter(iterable) + for x in iterable: + if not predicate(x): + yield x + break + for x in iterable: + yield x + """ + def __init__(self, predicate, iterable): + self._predicate = predicate + self._iter = iter(iterable) + self._dropped = False + + def __iter__(self): + return self + + def next(self): + try: + value = self._iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._iter)) + if self._dropped: + return value + while self._predicate(value): + value = self._iter.next() + self._dropped = True + return value + +class groupby: + """Make an iterator that returns consecutive keys and groups from the + iterable. The key is a function computing a key value for each + element. If not specified or is None, key defaults to an identity + function and returns the element unchanged. Generally, the + iterable needs to already be sorted on the same key function. + + The returned group is itself an iterator that shares the + underlying iterable with groupby(). Because the source is shared, + when the groupby object is advanced, the previous group is no + longer visible. So, if that data is needed later, it should be + stored as a list: + + groups = [] + uniquekeys = [] + for k, g in groupby(data, keyfunc): + groups.append(list(g)) # Store group iterator as a list + uniquekeys.append(k) + """ + def __init__(self, iterable, key=None): + if key is None: + key = lambda x: x + self.keyfunc = key + self.it = iter(iterable) + self.tgtkey = self.currkey = self.currvalue = xrange(0) + + def __iter__(self): + return self + + def next(self): + while self.currkey == self.tgtkey: + try: + self.currvalue = self.it.next() # Exit on StopIteration + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self.it)) + self.currkey = self.keyfunc(self.currvalue) + self.tgtkey = self.currkey + return (self.currkey, self._grouper(self.tgtkey)) + + def _grouper(self, tgtkey): + while self.currkey == tgtkey: + yield self.currvalue + self.currvalue = self.it.next() # Exit on StopIteration + self.currkey = self.keyfunc(self.currvalue) + + + +class _ifilter_base: + """base class for ifilter and ifilterflase""" + def __init__(self, predicate, iterable): + # Make sure iterable *IS* iterable + self._iter = iter(iterable) + if predicate is None: + self._predicate = bool + else: + self._predicate = predicate + + def __iter__(self): + return self + +class ifilter(_ifilter_base): + """Make an iterator that filters elements from iterable returning + only those for which the predicate is True. If predicate is + None, return the items that are true. + + Equivalent to : + + def ifilter: + if predicate is None: + predicate = bool + for x in iterable: + if predicate(x): + yield x + """ + def next(self): + try: + next_elt = self._iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._iter)) + while True: + if self._predicate(next_elt): + return next_elt + next_elt = self._iter.next() + +class ifilterfalse(_ifilter_base): + """Make an iterator that filters elements from iterable returning + only those for which the predicate is False. If predicate is + None, return the items that are false. + + Equivalent to : + + def ifilterfalse(predicate, iterable): + if predicate is None: + predicate = bool + for x in iterable: + if not predicate(x): + yield x + """ + def next(self): + try: + next_elt = self._iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._iter)) + while True: + if not self._predicate(next_elt): + return next_elt + next_elt = self._iter.next() + + + + +class imap: + """Make an iterator that computes the function using arguments + from each of the iterables. If function is set to None, then + imap() returns the arguments as a tuple. Like map() but stops + when the shortest iterable is exhausted instead of filling in + None for shorter iterables. The reason for the difference is that + infinite iterator arguments are typically an error for map() + (because the output is fully evaluated) but represent a common + and useful way of supplying arguments to imap(). + + Equivalent to : + + def imap(function, *iterables): + iterables = map(iter, iterables) + while True: + args = [i.next() for i in iterables] + if function is None: + yield tuple(args) + else: + yield function(*args) + + """ + def __init__(self, function, iterable, *other_iterables): + self._func = function + self._iters = map(iter, (iterable, ) + other_iterables) + + def __iter__(self): + return self + + def next(self): + try: + args = [it.next() for it in self._iters] + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (it)) + if self._func is None: + return tuple(args) + else: + return self._func(*args) + + + +class islice: + """Make an iterator that returns selected elements from the + iterable. If start is non-zero, then elements from the iterable + are skipped until start is reached. Afterward, elements are + returned consecutively unless step is set higher than one which + results in items being skipped. If stop is None, then iteration + continues until the iterator is exhausted, if at all; otherwise, + it stops at the specified position. Unlike regular slicing, + islice() does not support negative values for start, stop, or + step. Can be used to extract related fields from data where the + internal structure has been flattened (for example, a multi-line + report may list a name field on every third line). + + Equivalent to : + + def islice(iterable, *args): + s = slice(*args) + next, stop, step = s.start or 0, s.stop, s.step or 1 + for cnt, element in enumerate(iterable): + if cnt < next: + continue + if stop is not None and cnt >= stop: + break + yield element + next += step + """ + def __init__(self, iterable, arg, *other_args): + if len(other_args) > 2 : + raise TypeError("islice() takes at most 4 arguments, got %s" % + (2 + len(other_args))) + self._enum = enumerate(iterable) + start, stop, step = 0, -1, 1 + # We must do the same checks that in the CPython implementation + # Only one arg passed means it's the "stop" one + if not other_args: + stop = arg + else: + start = arg + try: + stop, step = other_args + except ValueError: # <=> No step specified + stop = other_args[0] + if not isinstance(start, int): + raise ValueError("Start argument must be an integer") + if stop is not None and not isinstance(stop, int): + raise ValueError("Stop argument must be an integer or None") + if start < 0 or (stop is not None and stop < -1): + raise ValueError("Indices for islice() must be non-negative integers.") + if step < 1: + raise ValueError("Step must be one or larger for islice()") + s = slice(start, stop, step) + self._next, self._stop, self._step = start, stop, step + # self._next, self._stop, self._step = s.start or 0, s.stop, s.step or 1 + + + def __iter__(self): + return self + + def next(self): + while True: + index, element = self._enum.next() + if self._stop is not None and index >= self._stop: + raise StopIteration() + if index < self._next: + continue + self._next += self._step + return element + + + +class izip: + """Make an iterator that aggregates elements from each of the + iterables. Like zip() except that it returns an iterator instead + of a list. Used for lock-step iteration over several iterables at + a time. + + Equivalent to : + + def izip(*iterables): + iterables = map(iter, iterables) + while iterables: + result = [i.next() for i in iterables] + yield tuple(result) + """ + def __init__(self, *iterables): + self._iterators = map(iter, iterables) + self._result = [None] * len(self._iterators) + + def __iter__(self): + return self + + def next(self): + if not self._iterators: + raise StopIteration() + try: + return tuple([i.next() for i in self._iterators]) + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % (i)) + + +class repeat: + """Make an iterator that returns object over and over again. + Runs indefinitely unless the times argument is specified. Used + as argument to imap() for invariant parameters to the called + function. Also used with izip() to create an invariant part of a + tuple record. + + Equivalent to : + + def repeat(object, times=None): + if times is None: + while True: + yield object + else: + for i in xrange(times): + yield object + """ + def __init__(self, obj, times=None): + self._obj = obj + if times is not None: + xrange(times) # Raise a TypeError + if times < 0: + times = 0 + self._times = times + + def __iter__(self): + return self + + def next(self): + # next() *need* to decrement self._times when consumed + if self._times is not None: + if self._times <= 0: + raise StopIteration() + self._times -= 1 + return self._obj + + def __repr__(self): + if self._times is not None: + return 'repeat(%r, %r)' % (self._obj, self._times) + else: + return 'repeat(%r)' % (self._obj,) + + def __len__(self): + if self._times == -1 or self._times is None: + raise TypeError("len() of uniszed object") + return self._times + + +class starmap: + """Make an iterator that computes the function using arguments + tuples obtained from the iterable. Used instead of imap() when + argument parameters are already grouped in tuples from a single + iterable (the data has been ``pre-zipped''). The difference + between imap() and starmap() parallels the distinction between + function(a,b) and function(*c). + + Equivalent to : + + def starmap(function, iterable): + iterable = iter(iterable) + while True: + yield function(*iterable.next()) + """ + def __init__(self, function, iterable): + self._func = function + self._iter = iter(iterable) + + def __iter__(self): + return self + + def next(self): + # CPython raises a TypeError when the iterator doesn't return a tuple + try: + t = self._iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % self._iter) + if not isinstance(t, tuple): + raise TypeError("iterator must return a tuple") + return self._func(*t) + + + +class takewhile: + """Make an iterator that returns elements from the iterable as + long as the predicate is true. + + Equivalent to : + + def takewhile(predicate, iterable): + for x in iterable: + if predicate(x): + yield x + else: + break + """ + def __init__(self, predicate, iterable): + self._predicate = predicate + self._iter = iter(iterable) + + def __iter__(self): + return self + + def next(self): + try: + value = self._iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % \ + (self._iter)) + if not self._predicate(value): + raise StopIteration() + return value + + +class TeeData(object): + """Holds cached values for TeeObjects""" + def __init__(self, iterator): + self.data = [] + self._iter = iterator + + def __getitem__(self, i): + # iterates until 'i' if not done yet + while i>= len(self.data): + try: + self.data.append( self._iter.next() ) + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % self._iter) + return self.data[i] + + +class TeeObject(object): + """Iterables / Iterators as returned by the tee() function""" + def __init__(self, iterable=None, tee_data=None): + if tee_data: + self.tee_data = tee_data + self.pos = 0 + # <=> Copy constructor + elif isinstance(iterable, TeeObject): + self.tee_data = iterable.tee_data + self.pos = iterable.pos + else: + self.tee_data = TeeData(iter(iterable)) + self.pos = 0 + + def next(self): + data = self.tee_data[self.pos] + self.pos += 1 + return data + + def __iter__(self): + return self + + +def tee(iterable, n=2): + """Return n independent iterators from a single iterable. + Note : once tee() has made a split, the original iterable + should not be used anywhere else; otherwise, the iterable could get + advanced without the tee objects being informed. + + Note : this member of the toolkit may require significant auxiliary + storage (depending on how much temporary data needs to be stored). + In general, if one iterator is going to use most or all of the + data before the other iterator, it is faster to use list() instead + of tee() + + Equivalent to : + + def tee(iterable, n=2): + def gen(next, data={}, cnt=[0]): + for i in count(): + if i == cnt[0]: + item = data[i] = next() + cnt[0] += 1 + else: + item = data.pop(i) + yield item + it = iter(iterable) + return tuple([gen(it.next) for i in range(n)]) + """ + if isinstance(iterable, TeeObject): + # a,b = tee(range(10)) ; c,d = tee(a) ; self.assert_(a is c) + return tuple([iterable] + + [TeeObject(tee_data=iterable.tee_data) for i in xrange(n-1)]) + tee_data = TeeData(iter(iterable)) + return tuple([TeeObject(tee_data=tee_data) for i in xrange(n)]) Copied: pypy/dist/pypy/lib/test2/test_itertools.py (from r8803, pypy/dist/lib-python-2.3.4/test/test_itertools.py) ============================================================================== --- pypy/dist/lib-python-2.3.4/test/test_itertools.py (original) +++ pypy/dist/pypy/lib/test2/test_itertools.py Wed Feb 2 14:08:26 2005 @@ -95,8 +95,9 @@ zip('abc', 'def')) self.assertEqual([pair for pair in izip('abc', 'def')], zip('abc', 'def')) - ids = map(id, izip('abc', 'def')) - self.assertEqual(min(ids), max(ids)) + + # ids = map(id, izip('abc', 'def')) + # self.assertEqual(min(ids), max(ids)) ## NOT FEASIBLE IN PYPY ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Feb 2 14:08:26 2005 @@ -466,7 +466,11 @@ return self def next(self): - value = self.iter.next() + try: + value = self.iter.next() + except AttributeError: + # CPython raises a TypeError when next() is not defined + raise TypeError('%s has no next() method' % self.iter) index = self.index self.index += 1 return index, value Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Wed Feb 2 14:08:26 2005 @@ -36,7 +36,7 @@ # The following built-in modules are not written in PyPy, so we # steal them from Python. for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos', - 'itertools', 'math', '_codecs', 'array', + 'math', '_codecs', 'array', '_random', '_sre', 'time', '_socket', 'errno', 'marshal', 'binascii', 'parser']: if fn not in builtin_modules: From adim at codespeak.net Wed Feb 2 14:16:11 2005 From: adim at codespeak.net (adim at codespeak.net) Date: Wed, 2 Feb 2005 14:16:11 +0100 (MET) Subject: [pypy-svn] r8805 - in pypy/dist: lib-python-2.3.4 pypy/lib Message-ID: <20050202131611.7962727BB1@code1.codespeak.net> Author: adim Date: Wed Feb 2 14:16:11 2005 New Revision: 8805 Added: pypy/dist/pypy/lib/itertools.py - copied unchanged from r8804, pypy/dist/lib-python-2.3.4/itertools.py Removed: pypy/dist/lib-python-2.3.4/itertools.py Log: Oops, did not commit it in the right place ... sorry Deleted: /pypy/dist/lib-python-2.3.4/itertools.py ============================================================================== --- /pypy/dist/lib-python-2.3.4/itertools.py Wed Feb 2 14:16:11 2005 +++ (empty file) @@ -1,629 +0,0 @@ -"""Functional tools for creating and using iterators. - -Infinite iterators: -count([n]) --> n, n+1, n+2, ... -cycle(p) --> p0, p1, ... plast, p0, p1, ... -repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times - -Iterators terminating on the shortest input sequence: -izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... -ifilter(pred, seq) --> elements of seq where pred(elem) is True -ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False -islice(seq, [start,] stop [, step]) --> elements from - seq[start:stop:step] -imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ... -starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ... -tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n -chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... -takewhile(pred, seq) --> seq[0], seq[1], until pred fails -dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails -groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v) -""" - -__all__ = ['chain', 'count', 'cycle', 'dropwhile', 'groupby', 'ifilter', - 'ifilterfalse', 'imap', 'islice', 'izip', 'repeat', 'starmap', - 'takewhile', 'tee'] - - -class chain: - """Make an iterator that returns elements from the first iterable - until it is exhausted, then proceeds to the next iterable, until - all of the iterables are exhausted. Used for treating consecutive - sequences as a single sequence. - - Equivalent to : - - def chain(*iterables): - for it in iterables: - for element in it: - yield element - """ - def __init__(self, *iterables): - self._iterables_iter = iter(map(iter, iterables)) - # little trick for the first chain.next() call - self._cur_iterable_iter = iter([]) - - def __iter__(self): - return self - - def next(self): - try: - next_elt = self._cur_iterable_iter.next() - except StopIteration: - # The current list's iterator is exhausted, switch to next one - self._cur_iterable_iter = iter(self._iterables_iter.next()) - try: - next_elt = self._cur_iterable_iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._cur_iterable_iter)) - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._cur_iterable_iter)) - - return next_elt - - -class count: - """Make an iterator that returns consecutive integers starting - with n. If not specified n defaults to zero. Does not currently - support python long integers. Often used as an argument to imap() - to generate consecutive data points. Also, used with izip() to - add sequence numbers. - - Equivalent to : - - def count(n=0): - if not isinstance(n, int): - raise TypeError("%s is not a regular integer" % n) - while True: - yield n - n += 1 - """ - def __init__(self, n=0): - if not isinstance(n, int): - raise TypeError('%s is not a regular integer' % n) - self.times = n-1 - - def __iter__(self): - return self - - def next(self): - self.times += 1 - return self.times - - def __repr__(self): - return 'count(%d)' % (self.times + 1) - - - -class cycle: - """Make an iterator returning elements from the iterable and - saving a copy of each. When the iterable is exhausted, return - elements from the saved copy. Repeats indefinitely. - - Equivalent to : - - def cycle(iterable): - saved = [] - for element in iterable: - yield element - saved.append(element) - while saved: - for element in saved: - yield element - """ - def __init__(self, iterable): - self._cur_iter = iter(iterable) - self._saved = [] - self._must_save = True - - def __iter__(self): - return self - - def next(self): - # XXX Could probably be improved - try: - next_elt = self._cur_iter.next() - if self._must_save: - self._saved.append(next_elt) - except StopIteration: - self._cur_iter = iter(self._saved) - next_elt = self._cur_iter.next() - self._must_save = False - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._cur_iter)) - return next_elt - - -class dropwhile: - """Make an iterator that drops elements from the iterable as long - as the predicate is true; afterwards, returns every - element. Note, the iterator does not produce any output until the - predicate is true, so it may have a lengthy start-up time. - - Equivalent to : - - def dropwhile(predicate, iterable): - iterable = iter(iterable) - for x in iterable: - if not predicate(x): - yield x - break - for x in iterable: - yield x - """ - def __init__(self, predicate, iterable): - self._predicate = predicate - self._iter = iter(iterable) - self._dropped = False - - def __iter__(self): - return self - - def next(self): - try: - value = self._iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._iter)) - if self._dropped: - return value - while self._predicate(value): - value = self._iter.next() - self._dropped = True - return value - -class groupby: - """Make an iterator that returns consecutive keys and groups from the - iterable. The key is a function computing a key value for each - element. If not specified or is None, key defaults to an identity - function and returns the element unchanged. Generally, the - iterable needs to already be sorted on the same key function. - - The returned group is itself an iterator that shares the - underlying iterable with groupby(). Because the source is shared, - when the groupby object is advanced, the previous group is no - longer visible. So, if that data is needed later, it should be - stored as a list: - - groups = [] - uniquekeys = [] - for k, g in groupby(data, keyfunc): - groups.append(list(g)) # Store group iterator as a list - uniquekeys.append(k) - """ - def __init__(self, iterable, key=None): - if key is None: - key = lambda x: x - self.keyfunc = key - self.it = iter(iterable) - self.tgtkey = self.currkey = self.currvalue = xrange(0) - - def __iter__(self): - return self - - def next(self): - while self.currkey == self.tgtkey: - try: - self.currvalue = self.it.next() # Exit on StopIteration - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self.it)) - self.currkey = self.keyfunc(self.currvalue) - self.tgtkey = self.currkey - return (self.currkey, self._grouper(self.tgtkey)) - - def _grouper(self, tgtkey): - while self.currkey == tgtkey: - yield self.currvalue - self.currvalue = self.it.next() # Exit on StopIteration - self.currkey = self.keyfunc(self.currvalue) - - - -class _ifilter_base: - """base class for ifilter and ifilterflase""" - def __init__(self, predicate, iterable): - # Make sure iterable *IS* iterable - self._iter = iter(iterable) - if predicate is None: - self._predicate = bool - else: - self._predicate = predicate - - def __iter__(self): - return self - -class ifilter(_ifilter_base): - """Make an iterator that filters elements from iterable returning - only those for which the predicate is True. If predicate is - None, return the items that are true. - - Equivalent to : - - def ifilter: - if predicate is None: - predicate = bool - for x in iterable: - if predicate(x): - yield x - """ - def next(self): - try: - next_elt = self._iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._iter)) - while True: - if self._predicate(next_elt): - return next_elt - next_elt = self._iter.next() - -class ifilterfalse(_ifilter_base): - """Make an iterator that filters elements from iterable returning - only those for which the predicate is False. If predicate is - None, return the items that are false. - - Equivalent to : - - def ifilterfalse(predicate, iterable): - if predicate is None: - predicate = bool - for x in iterable: - if not predicate(x): - yield x - """ - def next(self): - try: - next_elt = self._iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._iter)) - while True: - if not self._predicate(next_elt): - return next_elt - next_elt = self._iter.next() - - - - -class imap: - """Make an iterator that computes the function using arguments - from each of the iterables. If function is set to None, then - imap() returns the arguments as a tuple. Like map() but stops - when the shortest iterable is exhausted instead of filling in - None for shorter iterables. The reason for the difference is that - infinite iterator arguments are typically an error for map() - (because the output is fully evaluated) but represent a common - and useful way of supplying arguments to imap(). - - Equivalent to : - - def imap(function, *iterables): - iterables = map(iter, iterables) - while True: - args = [i.next() for i in iterables] - if function is None: - yield tuple(args) - else: - yield function(*args) - - """ - def __init__(self, function, iterable, *other_iterables): - self._func = function - self._iters = map(iter, (iterable, ) + other_iterables) - - def __iter__(self): - return self - - def next(self): - try: - args = [it.next() for it in self._iters] - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (it)) - if self._func is None: - return tuple(args) - else: - return self._func(*args) - - - -class islice: - """Make an iterator that returns selected elements from the - iterable. If start is non-zero, then elements from the iterable - are skipped until start is reached. Afterward, elements are - returned consecutively unless step is set higher than one which - results in items being skipped. If stop is None, then iteration - continues until the iterator is exhausted, if at all; otherwise, - it stops at the specified position. Unlike regular slicing, - islice() does not support negative values for start, stop, or - step. Can be used to extract related fields from data where the - internal structure has been flattened (for example, a multi-line - report may list a name field on every third line). - - Equivalent to : - - def islice(iterable, *args): - s = slice(*args) - next, stop, step = s.start or 0, s.stop, s.step or 1 - for cnt, element in enumerate(iterable): - if cnt < next: - continue - if stop is not None and cnt >= stop: - break - yield element - next += step - """ - def __init__(self, iterable, arg, *other_args): - if len(other_args) > 2 : - raise TypeError("islice() takes at most 4 arguments, got %s" % - (2 + len(other_args))) - self._enum = enumerate(iterable) - start, stop, step = 0, -1, 1 - # We must do the same checks that in the CPython implementation - # Only one arg passed means it's the "stop" one - if not other_args: - stop = arg - else: - start = arg - try: - stop, step = other_args - except ValueError: # <=> No step specified - stop = other_args[0] - if not isinstance(start, int): - raise ValueError("Start argument must be an integer") - if stop is not None and not isinstance(stop, int): - raise ValueError("Stop argument must be an integer or None") - if start < 0 or (stop is not None and stop < -1): - raise ValueError("Indices for islice() must be non-negative integers.") - if step < 1: - raise ValueError("Step must be one or larger for islice()") - s = slice(start, stop, step) - self._next, self._stop, self._step = start, stop, step - # self._next, self._stop, self._step = s.start or 0, s.stop, s.step or 1 - - - def __iter__(self): - return self - - def next(self): - while True: - index, element = self._enum.next() - if self._stop is not None and index >= self._stop: - raise StopIteration() - if index < self._next: - continue - self._next += self._step - return element - - - -class izip: - """Make an iterator that aggregates elements from each of the - iterables. Like zip() except that it returns an iterator instead - of a list. Used for lock-step iteration over several iterables at - a time. - - Equivalent to : - - def izip(*iterables): - iterables = map(iter, iterables) - while iterables: - result = [i.next() for i in iterables] - yield tuple(result) - """ - def __init__(self, *iterables): - self._iterators = map(iter, iterables) - self._result = [None] * len(self._iterators) - - def __iter__(self): - return self - - def next(self): - if not self._iterators: - raise StopIteration() - try: - return tuple([i.next() for i in self._iterators]) - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % (i)) - - -class repeat: - """Make an iterator that returns object over and over again. - Runs indefinitely unless the times argument is specified. Used - as argument to imap() for invariant parameters to the called - function. Also used with izip() to create an invariant part of a - tuple record. - - Equivalent to : - - def repeat(object, times=None): - if times is None: - while True: - yield object - else: - for i in xrange(times): - yield object - """ - def __init__(self, obj, times=None): - self._obj = obj - if times is not None: - xrange(times) # Raise a TypeError - if times < 0: - times = 0 - self._times = times - - def __iter__(self): - return self - - def next(self): - # next() *need* to decrement self._times when consumed - if self._times is not None: - if self._times <= 0: - raise StopIteration() - self._times -= 1 - return self._obj - - def __repr__(self): - if self._times is not None: - return 'repeat(%r, %r)' % (self._obj, self._times) - else: - return 'repeat(%r)' % (self._obj,) - - def __len__(self): - if self._times == -1 or self._times is None: - raise TypeError("len() of uniszed object") - return self._times - - -class starmap: - """Make an iterator that computes the function using arguments - tuples obtained from the iterable. Used instead of imap() when - argument parameters are already grouped in tuples from a single - iterable (the data has been ``pre-zipped''). The difference - between imap() and starmap() parallels the distinction between - function(a,b) and function(*c). - - Equivalent to : - - def starmap(function, iterable): - iterable = iter(iterable) - while True: - yield function(*iterable.next()) - """ - def __init__(self, function, iterable): - self._func = function - self._iter = iter(iterable) - - def __iter__(self): - return self - - def next(self): - # CPython raises a TypeError when the iterator doesn't return a tuple - try: - t = self._iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % self._iter) - if not isinstance(t, tuple): - raise TypeError("iterator must return a tuple") - return self._func(*t) - - - -class takewhile: - """Make an iterator that returns elements from the iterable as - long as the predicate is true. - - Equivalent to : - - def takewhile(predicate, iterable): - for x in iterable: - if predicate(x): - yield x - else: - break - """ - def __init__(self, predicate, iterable): - self._predicate = predicate - self._iter = iter(iterable) - - def __iter__(self): - return self - - def next(self): - try: - value = self._iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % \ - (self._iter)) - if not self._predicate(value): - raise StopIteration() - return value - - -class TeeData(object): - """Holds cached values for TeeObjects""" - def __init__(self, iterator): - self.data = [] - self._iter = iterator - - def __getitem__(self, i): - # iterates until 'i' if not done yet - while i>= len(self.data): - try: - self.data.append( self._iter.next() ) - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % self._iter) - return self.data[i] - - -class TeeObject(object): - """Iterables / Iterators as returned by the tee() function""" - def __init__(self, iterable=None, tee_data=None): - if tee_data: - self.tee_data = tee_data - self.pos = 0 - # <=> Copy constructor - elif isinstance(iterable, TeeObject): - self.tee_data = iterable.tee_data - self.pos = iterable.pos - else: - self.tee_data = TeeData(iter(iterable)) - self.pos = 0 - - def next(self): - data = self.tee_data[self.pos] - self.pos += 1 - return data - - def __iter__(self): - return self - - -def tee(iterable, n=2): - """Return n independent iterators from a single iterable. - Note : once tee() has made a split, the original iterable - should not be used anywhere else; otherwise, the iterable could get - advanced without the tee objects being informed. - - Note : this member of the toolkit may require significant auxiliary - storage (depending on how much temporary data needs to be stored). - In general, if one iterator is going to use most or all of the - data before the other iterator, it is faster to use list() instead - of tee() - - Equivalent to : - - def tee(iterable, n=2): - def gen(next, data={}, cnt=[0]): - for i in count(): - if i == cnt[0]: - item = data[i] = next() - cnt[0] += 1 - else: - item = data.pop(i) - yield item - it = iter(iterable) - return tuple([gen(it.next) for i in range(n)]) - """ - if isinstance(iterable, TeeObject): - # a,b = tee(range(10)) ; c,d = tee(a) ; self.assert_(a is c) - return tuple([iterable] + - [TeeObject(tee_data=iterable.tee_data) for i in xrange(n-1)]) - tee_data = TeeData(iter(iterable)) - return tuple([TeeObject(tee_data=tee_data) for i in xrange(n)]) From lac at codespeak.net Wed Feb 2 16:29:37 2005 From: lac at codespeak.net (lac at codespeak.net) Date: Wed, 2 Feb 2005 16:29:37 +0100 (MET) Subject: [pypy-svn] r8806 - pypy/dist/pypy/documentation Message-ID: <20050202152937.9D39427BB3@code1.codespeak.net> Author: lac Date: Wed Feb 2 16:29:37 2005 New Revision: 8806 Modified: pypy/dist/pypy/documentation/cmodules.txt Log: http://home.clear.net.nz/pages/c.evans/sw/ for crypt? Modified: pypy/dist/pypy/documentation/cmodules.txt ============================================================================== --- pypy/dist/pypy/documentation/cmodules.txt (original) +++ pypy/dist/pypy/documentation/cmodules.txt Wed Feb 2 16:29:37 2005 @@ -49,7 +49,7 @@ collectionsmodule - Raymond Hettinger has an ASPN recipe (which has a 'deque' drop-in replacement): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 -cryptmodule +cryptmodule - see http://home.clear.net.nz/pages/c.evans/sw/ datetimemodule - already exists From sanxiyn at codespeak.net Wed Feb 2 16:51:18 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Wed, 2 Feb 2005 16:51:18 +0100 (MET) Subject: [pypy-svn] r8808 - in pypy/dist/pypy/module: . test Message-ID: <20050202155118.9A70D27BB3@code1.codespeak.net> Author: sanxiyn Date: Wed Feb 2 16:51:18 2005 New Revision: 8808 Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_builtin.py Log: call __cmp__ in builtin cmp() Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Feb 2 16:51:18 2005 @@ -281,6 +281,9 @@ """return 0 when x == y, -1 when x < y and 1 when x > y """ if x is y: return 0 + if type(x) is type(y): + if hasattr(x, '__cmp__'): + return x.__cmp__(y) if x == y: return 0 elif x < y: Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Wed Feb 2 16:51:18 2005 @@ -241,6 +241,16 @@ assert cmp(0,9) < 0 assert cmp(9,0) > 0 + def test_cmp_more(self): + class C: + def __eq__(self, other): + return True + def __cmp__(self, other): + raise RuntimeError + c1 = C() + c2 = C() + raises(RuntimeError, cmp, c1, c2) + def test_return_None(self): class X: pass x = X() From sanxiyn at codespeak.net Wed Feb 2 17:08:58 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Wed, 2 Feb 2005 17:08:58 +0100 (MET) Subject: [pypy-svn] r8809 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050202160858.2A77E27BA4@code1.codespeak.net> Author: sanxiyn Date: Wed Feb 2 17:08:57 2005 New Revision: 8809 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: Let conftest actually work Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Wed Feb 2 17:08:57 2005 @@ -54,11 +54,11 @@ class Directory(py.test.collect.Directory): def __iter__(self): - for x in self.fspath.listdir('test_*.py'): - if fspath.basename not in working_outputtests and \ - fspath.basename not in working_unittests: + for test in self.fspath.listdir('test_*.py'): + if test.basename not in working_outputtests and \ + test.basename not in working_unittests: continue - yield Module(x) + yield Module(test) def app_list_testmethods(mod, testcaseclass): """ return [(instance.setUp, instance.tearDown, From pedronis at codespeak.net Wed Feb 2 19:35:35 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 2 Feb 2005 19:35:35 +0100 (MET) Subject: [pypy-svn] r8810 - pypy/dist/pypy/lib Message-ID: <20050202183535.09A1327BB1@code1.codespeak.net> Author: pedronis Date: Wed Feb 2 19:35:34 2005 New Revision: 8810 Modified: pypy/dist/pypy/lib/_classobj.py Log: fix Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Wed Feb 2 19:35:34 2005 @@ -171,7 +171,7 @@ dic['__class__'] = self init = instance_getattr1(inst,'__init__', False) if init: - ret = init(inst, *args, **kwds) + ret = init(*args, **kwds) if ret is not None: raise TypeError("__init__() should return None") return inst @@ -335,7 +335,7 @@ exec (""" def __%(op)s__(self): return instance_getattr1(self, '__%(op)s__')() -""") % {"op": op} +""") % {"op": op} del op @@ -509,4 +509,4 @@ return 0 raise TypeError,"__cmp__ must return int" return NotImplemented - + From tismer at codespeak.net Thu Feb 3 01:27:09 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 01:27:09 +0100 (MET) Subject: [pypy-svn] r8816 - pypy/dist/pypy/lib Message-ID: <20050203002709.2DAEB27BC9@code1.codespeak.net> Author: tismer Date: Thu Feb 3 01:27:09 2005 New Revision: 8816 Modified: pypy/dist/pypy/lib/_classobj.py Log: the generated codev looks much nicer, and also an explicit raise is nicer than an implitone, so I patched this... Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 3 01:27:09 2005 @@ -14,7 +14,7 @@ return (MASK + id(o)) & (MASK-1) def type_err(arg, expected, v): - raise TypeError("argument %s must be %s, not %s" % (arg, expected, type(v).__name__)) + return TypeError("argument %s must be %s, not %s" % (arg, expected, type(v).__name__)) def set_name(cls, name): if not isinstance(name, str): @@ -80,16 +80,16 @@ def __new__(subtype, name, bases, dic): if not isinstance(name, str): - type_err('name', 'string', name) + raise type_err('name', 'string', name) if bases is None: bases = () if not isinstance(bases, tuple): - type_err('bases', 'tuple', bases) + raise type_err('bases', 'tuple', bases) if not isinstance(dic, dict): - type_err('dict', 'dict', dic) + raise type_err('dict', 'dict', dic) try: dic['__doc__'] From hpk at codespeak.net Thu Feb 3 09:57:22 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 3 Feb 2005 09:57:22 +0100 (MET) Subject: [pypy-svn] r8817 - pypy/dist/pypy/documentation Message-ID: <20050203085722.EC08B27BEB@code1.codespeak.net> Author: hpk Date: Thu Feb 3 09:57:22 2005 New Revision: 8817 Modified: pypy/dist/pypy/documentation/coding-style.txt pypy/dist/pypy/documentation/testdesign.txt Log: fix documentation somewhat with respect to tests (this is referenced from coding-style.txt and we don't want to mislead people :-) Modified: pypy/dist/pypy/documentation/coding-style.txt ============================================================================== --- pypy/dist/pypy/documentation/coding-style.txt (original) +++ pypy/dist/pypy/documentation/coding-style.txt Thu Feb 3 09:57:22 2005 @@ -64,4 +64,4 @@ - see some more information about tests at the test-design_ document. -.. _test-design: ../devel/testdesign.html +.. _test-design: testdesign.html Modified: pypy/dist/pypy/documentation/testdesign.txt ============================================================================== --- pypy/dist/pypy/documentation/testdesign.txt (original) +++ pypy/dist/pypy/documentation/testdesign.txt Thu Feb 3 09:57:22 2005 @@ -2,7 +2,8 @@ Test Design ============= -Our tests are based on the unittest framework. All tests of modules +Our tests are based on the new `py.test`_ tool which lets you write +unittests without boilerplate. All tests of modules in a directory usually reside in a subdirectory **test**. There are basically two types of unit tests: @@ -14,26 +15,15 @@ Both types of tests need an objectspace they can run with (the interpreter dispatches operations on objects to an objectspace). If you run a test you -can usually give the '-S' or '-T' switch for using the Standard or the Trivial -ObjectSpace respectively. +can usually give the '-o' switch to select an object space. E.g. '-o trivial' +will select the trivial object space. The default is the "Standard Object Space". + +.. _`py.test`: http://codespeak.net/py/current/doc/test.html Writing a test -------------- -The best reference is to go to some test files and look how they are done. -Almost all tests start with the following lines:: - - import autopath - from pypy.tool import test - -of which the first line determines the package path automatically by searching -for **pypy** among the parents of the test-file's directory. The second -line imports PyPy's test-hook of which ''test.main()'' is the most important -and is usually the last line of the testfile. Further below you will find -some preliminary information about a new test module that was recently -developed at the Amsterdam Sprint (Dec. 2003) and still is under development. - -Note that we are using a unittest2 framework (but not for long) +Currently the best reference is to go to some test files and look how they are done. Command line tool test_all -------------------------- @@ -45,94 +35,10 @@ which will run all tests against the Standard Object Space. If you want to test against the TrivialObjectSpace then issue:: - python test_all.py -T + python test_all.py -o trivial For more switches invoke "python test_all.py -h". This used to be reversed -- the TrivialObjectSpace was the default, and you had to specify the StandardObjectSpace. You may find some documentation that has not been changed to reflect the new reality. - -------------------------------------------------------------------------------- - -.. _mail: http://codespeak.net/pipermail/pypy-dev/2003q2/000789.html - -New unit testing framework (not ready yet) ------------------------------------------- - -Current implementation -~~~~~~~~~~~~~~~~~~~~~~ - -The following picture is an UML class diagram of the framework. This -diagram is taken from the source code, which can currently be found -at src/pypy/tool/newtest.py as of 2003-12-19. (Most probably, the name -of the file will change, however.) - -:: - - +------------+ 1 1 +----------+ - | TestResult |----------------------------------------| TestItem | - | (abstract) | +----------+ - +------------+ | * - A | - - | - | | 1 - +----------------------------+-----------+ +-----------+ - | | | | TestSuite | - +-------------------------+ +---------+ +---------+ +-----------+ - | TestResultWithTraceback | | Success | | Skipped | A - | (abstract) | +---------+ +---------+ | - +-------------------------+ | loaded by - A A | - - - | * - | | +------------+ - | | | TestCase | - +-------+ +---------+ | (abstract) | - | Error | | Failure | +------------+ - +-------+ +---------+ A - - - | - | - concrete test - case classes - -Like the unittest framework of Python, our framework implements -tests as test methods in TestCase classes. Custom test case classes -derive from the shown TestCase class, defined in this module. As in -Python's unittest, a test case class can contain setUp and tearDown -methods. Additionally, it contains a method 'skip' which can be -called to stop a test prematurely. This won't be counted as a failure -or error. - -Test cases are loaded by a TestSuite class via the method init_from_dir. -This method will read all test modules in and below a specified -directory, inspect them for classes derived from TestCase (i. e. *our* -TestCase), and in turn inspect them for test methods (like in -unittest, all methods which start with "test"). - -For every found method, TestSuite will store its module, class and -unbound method objects in a TestItem object. There are also other -properties stored, e. g. the source code for each method and its -docstring. - -When the TestSuite's method 'run' is called, all collected TestItems -are run and, according to the outcome of the test, a TestResult object -is generated which holds a reference to "its" TestItem object. - -The TestResult classes Success and Skipped denote a passed test. A -skipped test means that not all test code has been run (and no error -or failure occurred before the skip method was called). If a test -fails, resulting in a Failure object, a test, e. g. tested with -assertEqual, has failed. An Error object is generated if something -else causes an unforeseen exception to be raised. - -Outlook -~~~~~~~ - -To be directly usable for the PyPy project, the selection of specific -object spaces has to be implemented. Moreover, the existing test -modules have to be converted. Because the TestCase class interface -remains compatible, this should only involve changes which can be -performed automatically, that is, changing the import statement for -this test module and the base class of test cases. - From hpk at codespeak.net Thu Feb 3 13:19:05 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 3 Feb 2005 13:19:05 +0100 (MET) Subject: [pypy-svn] r8818 - pypy/funding Message-ID: <20050203121905.D428C27BF4@code1.codespeak.net> Author: hpk Date: Thu Feb 3 13:19:05 2005 New Revision: 8818 Modified: pypy/funding/physical-person-model.txt Log: dramatic shortening of the model. Use more definite phrases and no "maybe"s. PLEASE read and counter-check if you like this all! Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Thu Feb 3 13:19:05 2005 @@ -78,91 +78,54 @@ --------------------------------------------------------- We want to implement an effective process for integrating physical -persons into the EU project. The technical board is to -actively invite people and partners to join our sprints and -other developments. The board will select people according to -criterias like usefulness for the project, past contributions -and specific fields of knowledge. - -However, on the formal side there are still some details to -resolve and we ask everyone, including our EU project officer -and the national EU offices we have contacts to, to help us in -setting up a model that can then be reused by other open -and transparent projects as well. - -Here are some of the issues and our proposed solutions: - -- physical persons enter the EU contract by means of - an Accession form. They are to get reimbursement for their - travel and accomodation costs but not for their work - costs. (See 2.4.7 of the Financial Guidelines from 04/2004). - We do not think that we will have physical persons with - full accounting systems and thus expect them to use - the AC model (in a very simple way). - -- We would like to reimburse costs to the external - sprint participants (as physical persons) while they - are on the sprint venue. They should usually - receive the money after we received copies of their - receipts for travel/accomodation costs. Although the - EU commission prepays only 80% of the full funding amount, - we may want to reimburse 100% of their costs at once to - simplify administration. - -- Physical persons are to sign an amendment to our Consortium - contract. Here we need to specialize their membership - internally in order to allow the consortium of full partners - to continue to act efficiently. We cannot make sprint - participants (physical persons) full members of the consortium - because it would make meetings and decisions ever more difficult. - - Therefore, physical persons are to enter as "associated - partners" which waive their voting rights and are not - required to attend consortium meetings. We consider this - mostly an internal detail of the consortium than something - the EU commission has to care about. - - Also we want physical persons to _not_ participate in the - general common liability of the full consortium partners - towards the EU commission. We feel that it is unwarranted - to receive work and contribution "for free" from sprint - participants and then make them liable if the full partners - cannot deliver as promised to the EU. - -- sprint participants (formally physical persons) should - not be required to deliver audit certificates. - If this is not feasible then we need to find an auditor who - is willing to audit the very simple cost statements of the physical - persons in a way that does not affect the management budget. - (The costs for audit certificates are accounted to the - management budget as far as we know). If audit certificates - are neccessary even for one or two-time attenders of sprints - then we kindly ask the EU commission for special allowance to - not count the according costs to the "7% management Cap" rule. +persons into the EU project according to Annex B.4.2. We aim +to have this model reusable by other open and agile projects. +Our experiences will be documented under WP14 (documentation +and dissemination). + +The technical board is to actively invite people and partners +to join our sprints and other developments. The board will +select people according to criterias like project requirements, +past contributions and specific fields of knowledge. + +Here are formal details about the implementation of B.4.2: + +- physical persons enter the EU contract by means of Form B. + They get reimbursement for their travel and accomodation costs + but not for their work costs. (See 2.4.7 of the Financial + Guidelines from 04/2004). We do not envision that we will + have physical persons with full accounting systems and + thus expect them to use the AC model in a simple way + and with small budgets. + +- Physical persons are to get 80% of their costs after they + show travel and accomodation receipts. Those receipts + will be audited by one auditor (payed for on an hourly basis). + +- Physical persons are to sign our Consortium contract. We will + specialcase their membership internally in order to allow the + consortium of full partners to continue to act efficiently + as they continue to bear the responsibility and liability for + the full implementation of the project. Please note that the costs for sprint participants (physical -persons) will only affect a very small portion of the overall -budget. Also we are - as explicitely stated in the proposal - -pioneering agile development/sprinting methods within -an EU project we hope that the commission will help us -to design the process in the proposed lightweight manner. - -Time frame ----------- - -We would like to setup the full model and process for -getting physical persons into the EU project by mid -February 2005. We have a number of people already interested -and many of them are already explicitely mentioned in -the proposal (B.4.2.1.4 and B.4.2.2.1 in the last amended -version of December 2004). - -Feedback --------- - -Please direct any feedback to pypy-funding at codespeak.net or to -Laura Creighton and Holger Krekel - who have been tasked by the partners -to find a workable and efficient model for sprint participants -to enter the project as physical persons. +persons) will only affect a small portion of the overall +budget which fully fits our accepted budget planning. + +Also we are - as explicitely stated in the proposal - +pioneering agile development/sprinting methods within our EU +project and we hope that the commission will later help us to +think about designing open-source/agile development processes +more effectively. + +Time frame / Request for confirmation +------------------------------------- + +We want to perform the implementation of B.4.2 as soon as posssible, +but no later than March 2005. We respectfully request a confirmation +in writing that we can proceed as outlined. + +We have a number of people already interested and most of them +are even explicitely mentioned in the proposal (B.4.2.1.4 +and B.4.2.2.1 in the December 2004 version). From hpk at codespeak.net Thu Feb 3 13:21:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 3 Feb 2005 13:21:17 +0100 (MET) Subject: [pypy-svn] r8819 - pypy/funding Message-ID: <20050203122117.2435E27BF2@code1.codespeak.net> Author: hpk Date: Thu Feb 3 13:21:16 2005 New Revision: 8819 Modified: pypy/funding/physical-person-model.txt Log: once more stress B.4.2 Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Thu Feb 3 13:21:16 2005 @@ -74,16 +74,16 @@ the wide community of interested researchers, experts and interested developers. -The model of getting physical persons into the consortium ---------------------------------------------------------- +Implementing the details of B.4.2 (foreseen amendments) +------------------------------------------------------- We want to implement an effective process for integrating physical persons into the EU project according to Annex B.4.2. We aim -to have this model reusable by other open and agile projects. +to have this process reusable by other open and agile projects. Our experiences will be documented under WP14 (documentation and dissemination). -The technical board is to actively invite people and partners +The technical board is to actively invite researchers and developers to join our sprints and other developments. The board will select people according to criterias like project requirements, past contributions and specific fields of knowledge. From hpk at codespeak.net Thu Feb 3 13:28:48 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 3 Feb 2005 13:28:48 +0100 (MET) Subject: [pypy-svn] r8820 - pypy/funding Message-ID: <20050203122848.E976727BEC@code1.codespeak.net> Author: hpk Date: Thu Feb 3 13:28:48 2005 New Revision: 8820 Modified: pypy/funding/physical-person-model.txt Log: added that phys persons get after the final audit by the EU their remaining costs reimbursed Modified: pypy/funding/physical-person-model.txt ============================================================================== --- pypy/funding/physical-person-model.txt (original) +++ pypy/funding/physical-person-model.txt Thu Feb 3 13:28:48 2005 @@ -101,6 +101,8 @@ - Physical persons are to get 80% of their costs after they show travel and accomodation receipts. Those receipts will be audited by one auditor (payed for on an hourly basis). + After the final acceptance by the EU they will get the + remaining reimbursements. - Physical persons are to sign our Consortium contract. We will specialcase their membership internally in order to allow the From tismer at codespeak.net Thu Feb 3 16:00:00 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 16:00:00 +0100 (MET) Subject: [pypy-svn] r8827 - pypy/dist/pypy/lib Message-ID: <20050203150000.2D4EC27BF5@code1.codespeak.net> Author: tismer Date: Thu Feb 3 16:00:00 2005 New Revision: 8827 Modified: pypy/dist/pypy/lib/_classobj.py Log: complicated the uid masking a little, avoiding to create a const larger than word size. This is relevant for generating interp-level. Well, maybe this could be avoided by generating long object calls instead of refusing. Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 3 16:00:00 2005 @@ -8,10 +8,14 @@ obj_setattr = object.__setattr__ obj_getattribute = object.__getattribute__ -MASK = sys.maxint * 2 + 2 +MASK = sys.maxint * 2 + 1 def uid(o): - return (MASK + id(o)) & (MASK-1) + v = id(o) + if v < 0: + v += MASK + v += 1 + return v & MASK def type_err(arg, expected, v): return TypeError("argument %s must be %s, not %s" % (arg, expected, type(v).__name__)) From tismer at codespeak.net Thu Feb 3 16:02:19 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 16:02:19 +0100 (MET) Subject: [pypy-svn] r8828 - pypy/dist/pypy/lib Message-ID: <20050203150219.7C4CB27BF7@code1.codespeak.net> Author: tismer Date: Thu Feb 3 16:02:19 2005 New Revision: 8828 Modified: pypy/dist/pypy/lib/_classobj.py Log: fixed a typo. Found it with flow space, which is great for that! Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 3 16:02:19 2005 @@ -236,7 +236,7 @@ # for now, we need to copy things, because we are using # the __dict__for our class as well. This will vanish! value['__class__'] = self.__class__ - obj_setattr(inst, '__dict__', value) + obj_setattr(self, '__dict__', value) elif name == '__class__': if not isinstance(value, classobj): raise TypeError("__class__ must be set to a class") From tismer at codespeak.net Thu Feb 3 16:18:29 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 16:18:29 +0100 (MET) Subject: [pypy-svn] r8829 - pypy/dist/pypy/lib Message-ID: <20050203151829.72FC827BF7@code1.codespeak.net> Author: tismer Date: Thu Feb 3 16:18:29 2005 New Revision: 8829 Modified: pypy/dist/pypy/lib/_classobj.py Log: flow space cannot handle nested functions, so I changed this. Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 3 16:18:29 2005 @@ -79,6 +79,15 @@ return x.__dict__[name] return None +def seqiter(func): # XXX may want to access and instatiate the internal + # sequence-iterator type instead + i = 0 + while 1: + try: + yield func(i) + except IndexError: + return + i += 1 class classobj(object): @@ -463,16 +472,9 @@ func = instance_getattr1(self, '__getitem__') if not func: raise TypeError, "iteration over non-sequence" - def seqiter(): # XXX may want to access and instatiate the internal - # sequence-iterator type instead - i = 0 - while 1: - try: - yield func(i) - except IndexError: - return - i += 1 - return seqiter() + # moved sequiter away from here: + # flow space cannot handle nested functions. + return seqiter(func) def next(self): func = instance_getattr1(self, '__next__', False) From arigo at codespeak.net Thu Feb 3 16:22:38 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 3 Feb 2005 16:22:38 +0100 (MET) Subject: [pypy-svn] r8831 - pypy/dist/pypy/module/test Message-ID: <20050203152238.7537527BF7@code1.codespeak.net> Author: arigo Date: Thu Feb 3 16:22:38 2005 New Revision: 8831 Modified: pypy/dist/pypy/module/test/test_builtin.py Log: Don't test xrange() attributes, as they are deprecated and no longer present in Python 2.3 (thanks Seo). Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Thu Feb 3 16:22:38 2005 @@ -125,29 +125,26 @@ def test_xrange_args(self): - x = xrange(2) - assert x.start == 0 - assert x.stop == 2 - assert x.step == 1 - - x = xrange(2,10,2) - assert x.start == 2 - assert x.stop == 10 - assert x.step == 2 - - x = xrange(2.3, 10.5, 2.4) - assert x.start == 2 - assert x.stop == 10 - assert x.step == 2 +## # xrange() attributes are deprecated and were removed in Python 2.3. +## x = xrange(2) +## assert x.start == 0 +## assert x.stop == 2 +## assert x.step == 1 + +## x = xrange(2,10,2) +## assert x.start == 2 +## assert x.stop == 10 +## assert x.step == 2 + +## x = xrange(2.3, 10.5, 2.4) +## assert x.start == 2 +## assert x.stop == 10 +## assert x.step == 2 raises(ValueError, xrange, 0, 1, 0) def test_xrange_up(self): x = xrange(2) - assert x.start == 0 - assert x.stop == 2 - assert x.step == 1 - iter_x = iter(x) assert iter_x.next() == 0 assert iter_x.next() == 1 From tismer at codespeak.net Thu Feb 3 16:55:29 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 16:55:29 +0100 (MET) Subject: [pypy-svn] r8832 - pypy/dist/pypy/translator Message-ID: <20050203155529.EA3D627BFB@code1.codespeak.net> Author: tismer Date: Thu Feb 3 16:55:29 2005 New Revision: 8832 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: temporary check-in. Stillno nice cmd-line interface and quite hackish. I'm trying to resolve this after _classobj works better. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 3 16:55:29 2005 @@ -98,7 +98,18 @@ def appendnew(self, arg): "always append" list.append(self, arg) - + +class AugmentedFlowSpace(FlowObjSpace): + def __init__(self): + FlowObjSpace.__init__(self) +## #Eeek +## from pypy.objspace.std import Space +## other_space = Space() +## if not hasattr(self,"w_dict"): +## self.w_dict = other_space.w_dict +## if not hasattr(self,"w_TypeError"): +## self.w_TypeError = other_space.w_TypeError + class GenRpy: def __init__(self, translator, modname=None): self.translator = translator @@ -127,8 +138,8 @@ for name in "newtuple newlist newdict newstring".split(): self.has_listarg[name] = name - self.space = FlowObjSpace() # for introspection - + self.space = AugmentedFlowSpace() # for introspection + self.use_fast_call = False def expr(self, v, localnames, wrapped = True): @@ -239,12 +250,13 @@ src = self.expr(a1, localvars) left.append(self.expr(a2, localvars)) right.append(src) - txt = "%s = %s" % (", ".join(left), ", ".join(right)) - if len(txt) <= 65: # arbitrary - yield txt - else: - for line in self.large_assignment(left, right): - yield line + if left: # anything at all? + txt = "%s = %s" % (", ".join(left), ", ".join(right)) + if len(txt) <= 65: # arbitrary + yield txt + else: + for line in self.large_assignment(left, right): + yield line goto = blocknum[link.target] yield 'goto = %d' % goto if goto <= blocknum[block]: @@ -602,6 +614,7 @@ dict: 'space.w_dict', str: 'space.w_str', float: 'space.w_float', + slice: 'space.w_slice', type(Exception()): 'space.wrap(types.InstanceType)', type: 'space.w_type', complex:'space.wrap(types.ComplexType)', @@ -840,7 +853,7 @@ f_name = 'f_' + cname[6:] # collect all the local variables - graph = self.translator.getflowgraph(func) + graph = self.translator.getflowgraph(func, SpaceClass=AugmentedFlowSpace) localslst = [] def visit(node): if isinstance(node, Block): @@ -944,7 +957,8 @@ def rpyfunction_body(self, func, localvars): try: - graph = self.translator.getflowgraph(func) + graph = self.translator.getflowgraph(func, + SpaceClass=AugmentedFlowSpace) except Exception, e: print 20*"*", e print func @@ -958,7 +972,7 @@ f = self.f t = self.translator #t.simplify(func) - graph = t.getflowgraph(func) + graph = t.getflowgraph(func, SpaceClass=AugmentedFlowSpace) start = graph.startblock @@ -1066,6 +1080,8 @@ """NOT_RPYTHON""" class m: pass # fake module m.__dict__ = globals() + # make sure that this function is run only once: + m.init%(modname)s = lambda *ign:True ''' RPY_INIT_FOOTER = ''' @@ -1264,6 +1280,18 @@ #return [thing for thing in _exceptions.__dict__.values()] return dic, test_exceptions +def make_class_instance_helper(): + import pypy + prefix = os.path.dirname(pypy.__file__) + libdir = os.path.join(prefix, "lib") + hold = sys.path + sys.path.insert(0, libdir) + import _classobj + sys.path = hold + def make_class_instance(): + return _classobj.classobj, _classobj.instance + return None, make_class_instance + def all_entries(): res = [func() for func in entrypoints[:-1]] return res @@ -1280,6 +1308,7 @@ test_strutil, test_struct, test_exceptions_helper, + make_class_instance_helper, all_entries) entrypoint = entrypoints[-2] @@ -1305,12 +1334,6 @@ fname = os.path.join(pth, gen.modname+".py") gen.gen_source(fname, ftmpname) - #t.simplify() - #t.view() - # debugging - graph = t.getflowgraph() - ab = ordered_blocks(graph) # use ctrl-b in PyWin with ab - def crazy_test(): """ this thingy is generating the whole interpreter in itself""" # but doesn't work, my goto's give a problem for flow space From arigo at codespeak.net Thu Feb 3 17:17:31 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 3 Feb 2005 17:17:31 +0100 (MET) Subject: [pypy-svn] r8833 - pypy/dist/pypy/objspace/std Message-ID: <20050203161731.6B8B527C06@code1.codespeak.net> Author: arigo Date: Thu Feb 3 17:17:31 2005 New Revision: 8833 Modified: pypy/dist/pypy/objspace/std/listobject.py Log: Oops, a function with the same name was defined twice. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Thu Feb 3 17:17:31 2005 @@ -240,10 +240,6 @@ t = space.unpackiterable(w_iterable) return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) -def setitem__List_Slice_ANY(space, w_list, w_slice, w_iterable): - t = space.unpackiterable(w_iterable) - return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) - def _setitem_slice_helper(space, w_list, w_slice, sequence2, len2): start, stop, step, slicelength = slicetype.indices4(space, w_slice, w_list.ob_size) assert slicelength >= 0 From tismer at codespeak.net Thu Feb 3 17:37:13 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 17:37:13 +0100 (MET) Subject: [pypy-svn] r8834 - pypy/dist/pypy/module Message-ID: <20050203163713.98F7627C06@code1.codespeak.net> Author: tismer Date: Thu Feb 3 17:37:13 2005 New Revision: 8834 Modified: pypy/dist/pypy/module/exceptionsinterp.py Log: made it impossible to run the init code twice, which would cause an attempt too double-wrap __doc__ Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Thu Feb 3 17:37:13 2005 @@ -976,7 +976,7 @@ ##SECTION## ## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' ## function 'test_exceptions' -## firstlineno 1261 +## firstlineno 1272 ##SECTION## # global declarations # global object gfunc_test_exceptions @@ -1140,6 +1140,8 @@ """NOT_RPYTHON""" class m: pass # fake module m.__dict__ = globals() + # make sure that this function is run only once: + m.inittest_exceptions_1 = lambda *ign:True from pypy.interpreter.gateway import interp2app m.gfunc_test_exceptions = space.wrap(interp2app(f_test_exceptions)) From tismer at codespeak.net Thu Feb 3 17:38:14 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 3 Feb 2005 17:38:14 +0100 (MET) Subject: [pypy-svn] r8835 - pypy/dist/pypy/translator Message-ID: <20050203163814.E893127C08@code1.codespeak.net> Author: tismer Date: Thu Feb 3 17:38:14 2005 New Revision: 8835 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: this version works wit _classobj, given that **kwds calls are removed. TODO (urgently): Make this a stand-alone tool and provide tests. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 3 17:38:14 2005 @@ -99,17 +99,6 @@ "always append" list.append(self, arg) -class AugmentedFlowSpace(FlowObjSpace): - def __init__(self): - FlowObjSpace.__init__(self) -## #Eeek -## from pypy.objspace.std import Space -## other_space = Space() -## if not hasattr(self,"w_dict"): -## self.w_dict = other_space.w_dict -## if not hasattr(self,"w_TypeError"): -## self.w_TypeError = other_space.w_TypeError - class GenRpy: def __init__(self, translator, modname=None): self.translator = translator @@ -138,7 +127,7 @@ for name in "newtuple newlist newdict newstring".split(): self.has_listarg[name] = name - self.space = AugmentedFlowSpace() # for introspection + self.space = FlowObjSpace() # for introspection self.use_fast_call = False @@ -853,7 +842,7 @@ f_name = 'f_' + cname[6:] # collect all the local variables - graph = self.translator.getflowgraph(func, SpaceClass=AugmentedFlowSpace) + graph = self.translator.getflowgraph(func) localslst = [] def visit(node): if isinstance(node, Block): @@ -957,8 +946,7 @@ def rpyfunction_body(self, func, localvars): try: - graph = self.translator.getflowgraph(func, - SpaceClass=AugmentedFlowSpace) + graph = self.translator.getflowgraph(func) except Exception, e: print 20*"*", e print func @@ -972,7 +960,7 @@ f = self.f t = self.translator #t.simplify(func) - graph = t.getflowgraph(func, SpaceClass=AugmentedFlowSpace) + graph = t.getflowgraph(func) start = graph.startblock @@ -1088,10 +1076,15 @@ # entry point: %(entrypointname)s, %(entrypoint)s) if __name__ == "__main__": from pypy.objspace.std import StdObjSpace + from pypy.objspace.std.default import UnwrapError space = StdObjSpace() init%(modname)s(space) - print space.unwrap(space.call( - gfunc_%(entrypointname)s, space.newtuple([]))) + ret = space.call(gfunc_%(entrypointname)s, space.newtuple([])) + try: + print space.unwrap(ret) + except UnwrapError: + print "cannot unwrap, here the wrapped result:" + print ret ''' # a translation table suitable for str.translate() to remove From arigo at codespeak.net Fri Feb 4 13:41:54 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:41:54 +0100 (MET) Subject: [pypy-svn] r8836 - in pypy/dist/pypy: annotation interpreter translator translator/test Message-ID: <20050204124154.2133827C3B@code1.codespeak.net> Author: arigo Date: Thu Feb 3 18:13:45 2005 New Revision: 8836 Modified: pypy/dist/pypy/annotation/bookkeeper.py pypy/dist/pypy/interpreter/argument.py pypy/dist/pypy/translator/genc.h pypy/dist/pypy/translator/genpyrex.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_ctrans.py pypy/dist/pypy/translator/test/test_pyrextrans.py Log: - modified the Argument class to unpack ** arguments lazily too, just like * arguments. This allows the flow object space to handle ** arguments in calls. - updated genc.h accordingly to accept and decode ** arguments between the C functions. - removed the skip_on_error() in test_ctrans -- these ones mask real errors, and skipping should be restricted on "no C compiler found" kind of errors. - genpyrex.py probably works, but writing a test for that is slightly messy. Still, a proto-test found a previous bug in genpyrex.py. Modified: pypy/dist/pypy/annotation/bookkeeper.py ============================================================================== --- pypy/dist/pypy/annotation/bookkeeper.py (original) +++ pypy/dist/pypy/annotation/bookkeeper.py Thu Feb 3 18:13:45 2005 @@ -226,7 +226,7 @@ elif func.func_code.co_flags & CO_VARARGS: # calls to *arg functions: create one version per number of args - assert not args.kwds_w, ( + assert not args.has_keywords(), ( "keyword forbidden in calls to *arg functions") nbargs = len(args.arguments_w) if args.w_stararg is not None: Modified: pypy/dist/pypy/interpreter/argument.py ============================================================================== --- pypy/dist/pypy/interpreter/argument.py (original) +++ pypy/dist/pypy/interpreter/argument.py Thu Feb 3 18:13:45 2005 @@ -22,25 +22,7 @@ self.arguments_w = list(args_w) self.kwds_w = kwds_w.copy() self.w_stararg = w_stararg - if w_starstararg is not None: - # unlike the * argument we unpack the ** argument immediately. - # maybe we could allow general mappings? - if not space.is_true(space.isinstance(w_starstararg, space.w_dict)): - raise OperationError(space.w_TypeError, - space.wrap("the keywords must be " - "a dictionary")) - for w_key in space.unpackiterable(w_starstararg): - try: - key = space.str_w(w_key) - except OperationError: - raise OperationError(space.w_TypeError, - space.wrap("keywords must be strings")) - if key in self.kwds_w: - raise OperationError(self.space.w_TypeError, - self.space.wrap("got multiple values " - "for keyword argument " - "'%s'" % key)) - self.kwds_w[key] = space.getitem(w_starstararg, w_key) + self.w_starstararg = w_starstararg def frompacked(space, w_args=None, w_kwds=None): """Convenience static method to build an Arguments @@ -49,6 +31,11 @@ frompacked = staticmethod(frompacked) def __repr__(self): + if self.w_starstararg is not None: + return 'Arguments(%s, %s, %s, %s)' % (self.arguments_w, + self.kwds_w, + self.w_stararg, + self.w_starstararg) if self.w_stararg is None: if not self.kwds_w: return 'Arguments(%s)' % (self.arguments_w,) @@ -63,22 +50,52 @@ def unpack(self): "Return a ([w1,w2...], {'kw':w3...}) pair." + # --- unpack the * argument now --- if self.w_stararg is not None: self.arguments_w += self.space.unpackiterable(self.w_stararg) self.w_stararg = None + # --- unpack the ** argument now --- + if self.w_starstararg is not None: + space = self.space + w_starstararg = self.w_starstararg + # maybe we could allow general mappings? + if not space.is_true(space.isinstance(w_starstararg, space.w_dict)): + raise OperationError(space.w_TypeError, + space.wrap("the keywords must be " + "a dictionary")) + d = self.kwds_w.copy() # don't change the original yet, + # in case something goes wrong + for w_key in space.unpackiterable(w_starstararg): + try: + key = space.str_w(w_key) + except OperationError: + raise OperationError(space.w_TypeError, + space.wrap("keywords must be strings")) + if key in d: + raise OperationError(self.space.w_TypeError, + self.space.wrap("got multiple values " + "for keyword argument " + "'%s'" % key)) + d[key] = space.getitem(w_starstararg, w_key) + self.kwds_w = d + self.w_starstararg = None return self.arguments_w, self.kwds_w def prepend(self, w_firstarg): "Return a new Arguments with a new argument inserted first." args = Arguments(self.space, [w_firstarg] + self.arguments_w, - self.kwds_w, self.w_stararg) + self.kwds_w, self.w_stararg, self.w_starstararg) args.blind_arguments = self.blind_arguments + 1 return args + def has_keywords(self): + return self.kwds_w or (self.w_starstararg is not None and + self.space.is_true(self.w_starstararg)) + def fixedunpack(self, argcount): """The simplest argument parsing: get the 'argcount' arguments, or raise a real ValueError if the length is wrong.""" - if self.kwds_w: + if self.has_keywords(): raise ValueError, "no keyword arguments expected" if len(self.arguments_w) > argcount: raise ValueError, "too many arguments (%d expected)" % argcount @@ -143,6 +160,10 @@ pass else: self.unpack() # sets self.w_stararg to None + # always unpack the ** arguments + if self.w_starstararg is not None: + self.unpack() + args_w = self.arguments_w kwds_w = self.kwds_w @@ -198,21 +219,32 @@ shape_cnt = len(self.arguments_w) # Number of positional args shape_keys = self.kwds_w.keys() # List of keywords (strings) shape_star = self.w_stararg is not None # Flag: presence of *arg + shape_stst = self.w_starstararg is not None # Flag: presence of **kwds data_w = self.arguments_w + [self.kwds_w[key] for key in shape_keys] if shape_star: data_w.append(self.w_stararg) - return (shape_cnt, tuple(shape_keys), shape_star), data_w + if shape_stst: + data_w.append(self.w_starstararg) + return (shape_cnt, tuple(shape_keys), shape_star, shape_stst), data_w - def fromshape(space, (shape_cnt, shape_keys, shape_star), data_w): + def fromshape(space, (shape_cnt,shape_keys,shape_star,shape_stst), data_w): args_w = data_w[:shape_cnt] + p = shape_cnt kwds_w = {} for i in range(len(shape_keys)): - kwds_w[shape_keys[i]] = data_w[shape_cnt+i] + kwds_w[shape_keys[i]] = data_w[p] + p += 1 if shape_star: - w_star = data_w[-1] + w_star = data_w[p] + p += 1 else: w_star = None - return Arguments(space, args_w, kwds_w, w_star) + if shape_stst: + w_starstar = data_w[p] + p += 1 + else: + w_starstar = None + return Arguments(space, args_w, kwds_w, w_star, w_starstar) fromshape = staticmethod(fromshape) # XXX the "shape" tuple should be considered as a black box from # other code, but translator/genc.h examines it. Modified: pypy/dist/pypy/translator/genc.h ============================================================================== --- pypy/dist/pypy/translator/genc.h (original) +++ pypy/dist/pypy/translator/genc.h Thu Feb 3 18:13:45 2005 @@ -470,19 +470,21 @@ PyObject* o; PyObject* key; PyObject* t2; - int i, nargs, nkwds, nvarargs, starflag; + int i, nargs, nkwds, nvarargs, starflag, starstarflag; va_list vargs; if (!PyTuple_Check(shape) || - PyTuple_GET_SIZE(shape) != 3 || + PyTuple_GET_SIZE(shape) != 4 || !PyInt_Check(PyTuple_GET_ITEM(shape, 0)) || !PyTuple_Check(PyTuple_GET_ITEM(shape, 1)) || - !PyInt_Check(PyTuple_GET_ITEM(shape, 2))) { + !PyInt_Check(PyTuple_GET_ITEM(shape, 2)) || + !PyInt_Check(PyTuple_GET_ITEM(shape, 3))) { Py_FatalError("in genc.h: invalid 'shape' argument"); } nargs = PyInt_AS_LONG(PyTuple_GET_ITEM(shape, 0)); nkwds = PyTuple_GET_SIZE(PyTuple_GET_ITEM(shape, 1)); starflag = PyInt_AS_LONG(PyTuple_GET_ITEM(shape, 2)); + starstarflag = PyInt_AS_LONG(PyTuple_GET_ITEM(shape, 3)); va_start(vargs, shape); t = PyTuple_New(nargs); @@ -516,6 +518,22 @@ if (t == NULL) goto finally; } + if (starstarflag) { + int len1, len2, len3; + o = va_arg(vargs, PyObject *); + len1 = PyDict_Size(d); + len2 = PyDict_Size(o); + if (len1 < 0 || len2 < 0) + goto finally; + if (PyDict_Update(d, o) < 0) + goto finally; + len3 = PyDict_Size(d); + if (len1 + len2 != len3) { + PyErr_SetString(PyExc_TypeError, + "genc.h: duplicate keyword arguments"); + goto finally; + } + } va_end(vargs); result = PyObject_Call(callable, t, d); Modified: pypy/dist/pypy/translator/genpyrex.py ============================================================================== --- pypy/dist/pypy/translator/genpyrex.py (original) +++ pypy/dist/pypy/translator/genpyrex.py Thu Feb 3 18:13:45 2005 @@ -114,10 +114,12 @@ shape = self.op.args[1].value args = Arguments.fromshape(None, shape, a[2:]) lst = args.arguments_w[:] - for key, value in args.kwds_w: + for key, value in args.kwds_w.items(): lst.append("%s=%s" % (key, value)) if args.w_stararg is not None: lst.append("*%s" % args.w_stararg) + if args.w_starstararg is not None: + lst.append("**%s" % args.w_starstararg) return "%s = %s(%s)" % (self.resultname, a[0], ", ".join(lst)) def op_simple_call(self): Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Thu Feb 3 18:13:45 2005 @@ -540,6 +540,9 @@ def call_with_keyword(z): return default_args(-20, z=z) +def call_very_complex(z, args, kwds): + return default_args(-20, z=z, *args, **kwds) + def powerset(setsize=int): """Powerset Modified: pypy/dist/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_ctrans.py (original) +++ pypy/dist/pypy/translator/test/test_ctrans.py Thu Feb 3 18:13:45 2005 @@ -15,12 +15,14 @@ class TestNoTypeCGenTestCase: objspacename = 'flow' - def build_cfunc(self, func): + def build_cfunc(self, func, *morefuncs): try: func = func.im_func except AttributeError: pass t = Translator(func) + for fn in morefuncs: + t.getflowgraph(fn) t.simplify() - return py.test.skip_on_error(t.ccompile) + return t.ccompile() def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) @@ -153,6 +155,13 @@ call_with_keyword = self.build_cfunc(snippet.call_with_keyword) assert call_with_keyword(100) == 82 + def test_call_very_complex(self): + call_very_complex = self.build_cfunc(snippet.call_very_complex, + snippet.default_args) + assert call_very_complex(5, (3,), {}) == -12 + assert call_very_complex(5, (), {'y': 3}) == -12 + raises(TypeError, call_very_complex, 5, (3,), {'y': 4}) + def test_finallys(self): finallys = self.build_cfunc(snippet.finallys) assert finallys(['hello']) == 8 @@ -196,7 +205,7 @@ argstypelist.append(spec) a = t.annotate(argstypelist) a.simplify() - return py.test.skip_on_error(t.ccompile) + return t.ccompile() def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) Modified: pypy/dist/pypy/translator/test/test_pyrextrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_pyrextrans.py (original) +++ pypy/dist/pypy/translator/test/test_pyrextrans.py Thu Feb 3 18:13:45 2005 @@ -91,6 +91,15 @@ assert sand(0, 6) == "no" assert sand(0, 0) == "no" +# -- the following test doesn't really work right now -- +## def test_call_very_complex(self): +## call_very_complex = self.build_cfunc(snippet.call_very_complex, +## snippet.default_args) +## assert call_very_complex(5, (3,), {}) == -12 +## assert call_very_complex(5, (), {'y': 3}) == -12 +## py.test.raises("call_very_complex(5, (3,), {'y': 4})") + + class TestTypedTestCase: def getcompiled(self, func): From arigo at codespeak.net Fri Feb 4 13:43:44 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:44 +0100 (MET) Subject: [pypy-svn] r8837 - in pypy/dist/pypy/translator: test tool Message-ID: <20050204124344.EAE8327C3D@code1.codespeak.net> Author: arigo Date: Thu Feb 3 19:18:33 2005 New Revision: 8837 Modified: pypy/dist/pypy/translator/test/test_ctrans.py pypy/dist/pypy/translator/test/test_pyrextrans.py pypy/dist/pypy/translator/tool/buildpyxmodule.py Log: When no C compiler is found, I guess that the distutils give a DistutilsPlatformError. This allows a better control of when to skip tests. It's also a bit saner not to use distutils.core.setup(), as explained in buildpyxmodule.py. (The latter change should probably be ported to the py lib's getpymodule() as well.) Modified: pypy/dist/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_ctrans.py (original) +++ pypy/dist/pypy/translator/test/test_ctrans.py Thu Feb 3 19:18:33 2005 @@ -4,6 +4,7 @@ from pypy.translator.genc import GenC from pypy.objspace.flow.model import * from pypy.translator.tool.buildpyxmodule import make_module_from_c +from pypy.translator.tool.buildpyxmodule import skip_missing_compiler from pypy.translator.translator import Translator from pypy.translator.test import snippet @@ -22,7 +23,7 @@ for fn in morefuncs: t.getflowgraph(fn) t.simplify() - return t.ccompile() + return skip_missing_compiler(t.ccompile) def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) @@ -205,7 +206,7 @@ argstypelist.append(spec) a = t.annotate(argstypelist) a.simplify() - return t.ccompile() + return skip_missing_compiler(t.ccompile) def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) Modified: pypy/dist/pypy/translator/test/test_pyrextrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_pyrextrans.py (original) +++ pypy/dist/pypy/translator/test/test_pyrextrans.py Thu Feb 3 19:18:33 2005 @@ -4,6 +4,7 @@ from pypy.translator.genpyrex import GenPyrex from pypy.objspace.flow.model import * from pypy.translator.tool.buildpyxmodule import build_cfunc +from pypy.translator.tool.buildpyxmodule import skip_missing_compiler from pypy.translator.translator import Translator from pypy.translator.test import snippet @@ -25,7 +26,7 @@ 'simplify' : 1, 'dot' : dot, } - return py.test.skip_on_error(build_cfunc, func, **options) + return skip_missing_compiler(build_cfunc, func, **options) def test_simple_func(self): cfunc = self.build_cfunc(snippet.simple_func) @@ -113,7 +114,7 @@ spec = spec[0] # use the first type only for the tests argstypelist.append(spec) t.annotate(argstypelist) - return py.test.skip_on_error(t.compile) + return skip_missing_compiler(t.compile) def test_set_attr(self): set_attr = self.getcompiled(snippet.set_attr) Modified: pypy/dist/pypy/translator/tool/buildpyxmodule.py ============================================================================== --- pypy/dist/pypy/translator/tool/buildpyxmodule.py (original) +++ pypy/dist/pypy/translator/tool/buildpyxmodule.py Thu Feb 3 19:18:33 2005 @@ -68,20 +68,28 @@ cmd += ' -I%s' % dir cmdexec(cmd) else: - from distutils.core import setup + from distutils.dist import Distribution from distutils.extension import Extension saved_environ = os.environ.items() try: - setup( - name = "testmodules", - ext_modules=[ + # distutils.core.setup() is really meant for end-user + # interactive usage, because it eats most exceptions and + # turn them into SystemExits. Instead, we directly + # instantiate a Distribution, which also allows us to + # ignore unwanted features like config files. + attrs = { + 'name': "testmodule", + 'ext_modules': [ Extension(modname, [str(cfile)], include_dirs=include_dirs) - ], - script_name = 'setup.py', - script_args = ['-q', 'build_ext', '--inplace'] - #script_args = ['build_ext', '--inplace'] - ) + ], + 'script_name': 'setup.py', + 'script_args': ['-q', 'build_ext', '--inplace'], + } + dist = Distribution(attrs) + if not dist.parse_command_line(): + raise ValueError, "distutils cmdline parse error" + dist.run_commands() finally: for key, value in saved_environ: if os.environ.get(key) != value: @@ -124,6 +132,13 @@ cfile = pyxfile.new(ext='.c') return cfile +def skip_missing_compiler(fn, *args, **kwds): + from distutils.errors import DistutilsPlatformError + try: + return fn(*args, **kwds) + except DistutilsPlatformError, e: + py.test.skip('DistutilsPlatformError: %s' % (e,)) + def build_cfunc(func, simplify=1, dot=1, inputargtypes=None): """ return a pyrex-generated cfunction from the given func. From arigo at codespeak.net Fri Feb 4 13:43:45 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:45 +0100 (MET) Subject: [pypy-svn] r8838 - pypy/dist/pypy/interpreter Message-ID: <20050204124345.35C0C27C3D@code1.codespeak.net> Author: arigo Date: Thu Feb 3 19:30:15 2005 New Revision: 8838 Modified: pypy/dist/pypy/interpreter/argument.py Log: Docstring fix. Modified: pypy/dist/pypy/interpreter/argument.py ============================================================================== --- pypy/dist/pypy/interpreter/argument.py (original) +++ pypy/dist/pypy/interpreter/argument.py Thu Feb 3 19:30:15 2005 @@ -143,7 +143,7 @@ def match_signature(self, signature, defaults_w=[]): """Parse args and kwargs according to the signature of a code object, - or raise ArgumentMatch in case of failure. + or raise an ArgErr in case of failure. """ argnames, varargname, kwargname = signature # From pedronis at codespeak.net Fri Feb 4 13:43:45 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 4 Feb 2005 13:43:45 +0100 (MET) Subject: [pypy-svn] r8839 - pypy/dist/pypy/lib Message-ID: <20050204124345.769F527C3D@code1.codespeak.net> Author: pedronis Date: Thu Feb 3 19:40:38 2005 New Revision: 8839 Modified: pypy/dist/pypy/lib/_classobj.py Log: fixes to old-style classes iterator support Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 3 19:40:38 2005 @@ -469,7 +469,7 @@ raise TypeError, ("__iter__ returned non-iterator of type %s" % type(ret).__name__) return ret - func = instance_getattr1(self, '__getitem__') + func = instance_getattr1(self, '__getitem__', False) if not func: raise TypeError, "iteration over non-sequence" # moved sequiter away from here: @@ -477,7 +477,7 @@ return seqiter(func) def next(self): - func = instance_getattr1(self, '__next__', False) + func = instance_getattr1(self, 'next', False) if not func: raise TypeError, "instance has no next() method" return func() From arigo at codespeak.net Fri Feb 4 13:43:45 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:45 +0100 (MET) Subject: [pypy-svn] r8840 - pypy/dist/pypy/translator Message-ID: <20050204124345.BD80F27C3D@code1.codespeak.net> Author: arigo Date: Thu Feb 3 19:49:59 2005 New Revision: 8840 Modified: pypy/dist/pypy/translator/simplify.py pypy/dist/pypy/translator/transform.py Log: Deleted the duplicate definition of transform_dead_op_vars(). Modified: pypy/dist/pypy/translator/simplify.py ============================================================================== --- pypy/dist/pypy/translator/simplify.py (original) +++ pypy/dist/pypy/translator/simplify.py Thu Feb 3 19:49:59 2005 @@ -112,16 +112,16 @@ def transform_dead_op_vars(graph): """Remove dead operations and variables that are passed over a link but not used in the target block. Input is a graph.""" - blocklist = [] + blocks = {} def visit(block): if isinstance(block, Block): - blocklist.append(block) + blocks[block] = True traverse(visit, graph) - return transform_dead_op_vars_blocklist(blocklist) + return transform_dead_op_vars_in_blocks(blocks) -def transform_dead_op_vars_blocklist(blocklist): +def transform_dead_op_vars_in_blocks(blocks): """Remove dead operations and variables that are passed over a link - but not used in the target block. Input is a block list""" + but not used in the target block. Input is a set of blocks""" # the set of operations that can safely be removed (no side effects) CanRemove = {'newtuple': True, 'newlist': True, @@ -132,7 +132,7 @@ variable_flow = {} # map {Var: list-of-Vars-it-depends-on} # compute variable_flow and an initial read_vars - for block in blocklist: + for block in blocks: # figure out which variables are ever read for op in block.operations: if op.opname not in CanRemove: # mark the inputs as really needed @@ -149,7 +149,7 @@ if block.exits: for link in block.exits: - if link.target not in blocklist: + if link.target not in blocks: for arg, targetarg in zip(link.args, link.target.inputargs): read_vars[arg] = True read_vars[targetarg] = True @@ -176,7 +176,7 @@ read_vars[prevvar] = True pending.append(prevvar) - for block in blocklist: + for block in blocks: # look for removable operations whose result is never used for i in range(len(block.operations)-1, -1, -1): @@ -205,7 +205,7 @@ del link.args[i] # the above assert would fail here - for block in blocklist: + for block in blocks: # look for input variables never used # The corresponding link.args have already been all removed above for i in range(len(block.inputargs)-1, -1, -1): Modified: pypy/dist/pypy/translator/transform.py ============================================================================== --- pypy/dist/pypy/translator/transform.py (original) +++ pypy/dist/pypy/translator/transform.py Thu Feb 3 19:49:59 2005 @@ -119,101 +119,12 @@ ## block.operations = operations -# XXX this function now lives in simplify, too. -# there, it accepts a graph or a block list as argument. -# Fell free to use it instead, and remove the function here. def transform_dead_op_vars(self): - """Remove dead operations and variables that are passed over a link - but not used in the target block.""" - # the set of operations that can safely be removed (no side effects) - CanRemove = {'newtuple': True, - 'newlist': True, - 'newdict': True, - 'is_': True, - 'is_true': True} - read_vars = {} # set of variables really used - variable_flow = {} # map {Var: list-of-Vars-it-depends-on} - - # compute variable_flow and an initial read_vars - for block in self.annotated: - # figure out which variables are ever read - for op in block.operations: - if op.opname not in CanRemove: # mark the inputs as really needed - for arg in op.args: - read_vars[arg] = True - else: - # if CanRemove, only mark dependencies of the result - # on the input variables - deps = variable_flow.setdefault(op.result, []) - deps.extend(op.args) - - if isinstance(block.exitswitch, Variable): - read_vars[block.exitswitch] = True - - if block.exits: - for link in block.exits: - if link.target not in self.annotated: - for arg, targetarg in zip(link.args, link.target.inputargs): - read_vars[arg] = True - read_vars[targetarg] = True - else: - for arg, targetarg in zip(link.args, link.target.inputargs): - deps = variable_flow.setdefault(targetarg, []) - deps.append(arg) - else: - # return and except blocks implicitely use their input variable(s) - for arg in block.inputargs: - read_vars[arg] = True - # an input block's inputargs should not be modified, even if some - # of the function's input arguments are not actually used - if block.isstartblock: - for arg in block.inputargs: - read_vars[arg] = True - - # flow read_vars backwards so that any variable on which a read_vars - # depends is also included in read_vars - pending = list(read_vars) - for var in pending: - for prevvar in variable_flow.get(var, []): - if prevvar not in read_vars: - read_vars[prevvar] = True - pending.append(prevvar) - - for block in self.annotated: - - # look for removable operations whose result is never used - for i in range(len(block.operations)-1, -1, -1): - op = block.operations[i] - if op.result not in read_vars: - if op.opname in CanRemove: - del block.operations[i] - elif op.opname == 'simple_call': - # XXX we want to have a more effective and safe - # way to check if this operation has side effects - # ... - if op.args and isinstance(op.args[0], Constant): - func = op.args[0].value - if func is isinstance: - del block.operations[i] - - # look for output variables never used - # warning: this must be completely done *before* we attempt to - # remove the corresponding variables from block.inputargs! - # Otherwise the link.args get out of sync with the - # link.target.inputargs. - for link in block.exits: - assert len(link.args) == len(link.target.inputargs) - for i in range(len(link.args)-1, -1, -1): - if link.target.inputargs[i] not in read_vars: - del link.args[i] - # the above assert would fail here - - for block in self.annotated: - # look for input variables never used - # The corresponding link.args have already been all removed above - for i in range(len(block.inputargs)-1, -1, -1): - if block.inputargs[i] not in read_vars: - del block.inputargs[i] + # we redo the same simplification from simplify.py, + # to kill dead (never-followed) links, + # which can possibly remove more variables. + from pypy.translator.simplify import transform_dead_op_vars_in_blocks + transform_dead_op_vars_in_blocks(self.annotated) # expands the += operation between lists into a basic block loop. # a = inplace_add(b, c) From arigo at codespeak.net Fri Feb 4 13:43:46 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:46 +0100 (MET) Subject: [pypy-svn] r8841 - pypy/dist/pypy/module Message-ID: <20050204124346.1C12D27C3D@code1.codespeak.net> Author: arigo Date: Thu Feb 3 19:57:40 2005 New Revision: 8841 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Yet another rewrite of enumerate(). This one is not a type, but we can safely ignore tests that check this. It solves the previous version's problem that the .next() special method would be looked up on the iterator instance. Besides, generators rule :-) Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Thu Feb 3 19:57:40 2005 @@ -459,24 +459,15 @@ # ________________________________________________________________________ -class enumerate: +def enumerate(collection): 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - def __init__(self, collection): - self.iter = iter(collection) - self.index = 0 - - def __iter__(self): - return self - - def next(self): - try: - value = self.iter.next() - except AttributeError: - # CPython raises a TypeError when next() is not defined - raise TypeError('%s has no next() method' % self.iter) - index = self.index - self.index += 1 - return index, value + it = iter(collection) # raises a TypeError early + def do_enumerate(it): + index = 0 + for value in it: + yield index, value + index += 1 + return do_enumerate(it) class xrange: def __init__(self, start, stop=None, step=1): From arigo at codespeak.net Fri Feb 4 13:43:46 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:46 +0100 (MET) Subject: [pypy-svn] r8842 - in pypy/dist/pypy: interpreter module objspace Message-ID: <20050204124346.8889D27C42@code1.codespeak.net> Author: arigo Date: Thu Feb 3 20:16:29 2005 New Revision: 8842 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/objspace/descroperation.py Log: Argh, it seems that we need a 'cmp' space operation to implement the built-in cmp() correctly. Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Thu Feb 3 20:16:29 2005 @@ -128,7 +128,7 @@ def is_w(self, w_obj1, w_obj2): """shortcut for space.is_true(space.is_(w_obj1, w_obj2))""" return self.is_true(self.is_(w_obj1, w_obj2)) - + def newbool(self, b): if b: return self.w_True @@ -310,6 +310,7 @@ ('ne', '!=', 2, ['__ne__', '__ne__']), ('gt', '>', 2, ['__gt__', '__lt__']), ('ge', '>=', 2, ['__ge__', '__le__']), + ('cmp', 'cmp', 2, ['__cmp__']), # rich cmps preferred ('contains', 'contains', 2, ['__contains__']), ('iter', 'iter', 1, ['__iter__']), ('next', 'next', 1, ['next']), Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Thu Feb 3 20:16:29 2005 @@ -286,6 +286,10 @@ def id(w_object): return space.id(w_object) +def cmp(w_x, w_y): + """return 0 when x == y, -1 when x < y and 1 when x > y """ + return space.cmp(w_x, w_y) + #XXX works only for new-style classes. #So we have to fix it, when we add support for old-style classes def _issubtype(w_cls1, w_cls2): Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Thu Feb 3 20:16:29 2005 @@ -277,20 +277,6 @@ def divmod(x, y): return x//y, x%y -def cmp(x, y): - """return 0 when x == y, -1 when x < y and 1 when x > y """ - if x is y: - return 0 - if type(x) is type(y): - if hasattr(x, '__cmp__'): - return x.__cmp__(y) - if x == y: - return 0 - elif x < y: - return -1 - else: - return 1 - def vars(*obj): """return a dictionary of all the attributes currently bound in obj. If called with no argument, return the variables bound in local scope.""" @@ -447,7 +433,7 @@ __interplevel__execfile('__builtin__interp.py') from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round +from __interplevel__ import hash, oct, hex, round, cmp from __interplevel__ import getattr, setattr, delattr, iter, hash, id from __interplevel__ import _issubtype from __interplevel__ import compile, eval Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Thu Feb 3 20:16:29 2005 @@ -253,6 +253,24 @@ if w_del is not None: space.get_and_call_function(w_del, w_obj) + def cmp(space, w_x, w_y): + # full compliant implementation of the built-in cmp(). + if space.is_w(w_x, w_y): + return space.wrap(0) # identical objects always compare equal. + if space.is_w(space.type(w_x), space.type(w_y)): + # for object of the same type, prefer __cmp__ over rich comparison. + w_cmp = space.lookup(w_x, '__cmp__') + w_res = _invoke_binop(space, w_cmp, w_x, w_y) + if w_res is not None: + return w_res + # fall back to rich comparison. + if space.eq_w(w_x, w_y): + return space.wrap(0) + elif space.is_true(space.lt(w_x, w_y)): + return space.wrap(-1) + else: + return space.wrap(1) + # xxx round, ord From pedronis at codespeak.net Fri Feb 4 13:43:47 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 4 Feb 2005 13:43:47 +0100 (MET) Subject: [pypy-svn] r8843 - in pypy/dist/pypy: interpreter interpreter/test lib module objspace/std objspace/std/test Message-ID: <20050204124347.0F6F427C4E@code1.codespeak.net> Author: pedronis Date: Thu Feb 3 20:52:51 2005 New Revision: 8843 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/interpreter/function.py pypy/dist/pypy/interpreter/pyframe.py pypy/dist/pypy/interpreter/pyopcode.py pypy/dist/pypy/interpreter/test/test_class.py pypy/dist/pypy/interpreter/test/test_function.py pypy/dist/pypy/interpreter/test/test_raise.py pypy/dist/pypy/lib/types.py pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/objspace/std/test/test_dictproxy.py pypy/dist/pypy/objspace/std/test/test_floatobject.py pypy/dist/pypy/objspace/std/test/test_intobject.py pypy/dist/pypy/objspace/std/test/test_typeobject.py pypy/dist/pypy/objspace/std/test/test_userobject.py pypy/dist/pypy/objspace/std/typeobject.py pypy/dist/pypy/objspace/std/typetype.py Log: preparatory changes for old-style class integration modified: - type.__new__ with metaclass conflict logic and ingnoring old-style classes mro computation to consider classic case type lookup to be able to cope with old-style classes - lower-level abstract_isinstance and abstract_issubclass in baseobspace that can work also with old-style classes: used to do proper class-kind-agnostic type-checking in function.Method and exception catching - exception raising works with old-style classes - issubclass and isistance builtins added dummy w_classobj and w_instance to baseobjspace, to be substituted with the real thing, needed for example by type.__new__ they are also exposed in builtins as _classobj and _instance Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Thu Feb 3 20:52:51 2005 @@ -189,7 +189,7 @@ return True try: # Match subclasses. - if self.is_true(self.issubtype(w_exc_type, w_item)): + if self.is_true(self.abstract_issubclass(w_exc_type, w_item, failhard=True)): return True except OperationError: # Assume that this is a TypeError: w_item not a type, @@ -219,6 +219,39 @@ w_objtype = self.type(w_obj) return self.issubtype(w_objtype, w_type) + def abstract_issubclass(self, w_obj, w_cls, failhard=False): + try: + return self.issubtype(w_obj, w_cls) + except OperationError: + try: + self.getattr(w_cls, self.wrap('__bases__')) # type sanity check + return self.recursive_issubclass(w_obj, w_cls) + except OperationError: + if failhard: + raise + else: + return self.w_False + + def recursive_issubclass(self, w_obj, w_cls): + if self.is_w(w_obj, w_cls): + return self.w_True + for w_base in self.unpackiterable(self.getattr(w_obj, + self.wrap('__bases__'))): + if self.is_true(self.recursive_issubclass(w_base, w_cls)): + return self.w_True + return self.w_False + + def abstract_isinstance(self, w_obj, w_cls): + try: + return self.isinstance(w_obj, w_cls) + except OperationError: + try: + w_objcls = self.getattr(w_obj, self.wrap('__class__')) + return self.abstract_issubclass(w_objcls, w_cls) + except OperationError: + return self.w_False + + def eval(self, expression, w_globals, w_locals): "NOT_RPYTHON: For internal debugging." import types Modified: pypy/dist/pypy/interpreter/function.py ============================================================================== --- pypy/dist/pypy/interpreter/function.py (original) +++ pypy/dist/pypy/interpreter/function.py Thu Feb 3 20:52:51 2005 @@ -55,8 +55,8 @@ not space.is_true(space.is_(w_obj, space.w_None)) or space.is_true(space.is_(w_cls, space.type(space.w_None)))) if asking_for_bound: - if w_cls == space.w_None: - w_cls = space.type(w_obj) + #if w_cls == space.w_None: + # w_cls = space.type(w_obj) return wrap(Method(space, wrap(self), w_obj, w_cls)) else: return wrap(Method(space, wrap(self), None, w_cls)) @@ -160,7 +160,7 @@ # unbound method w_firstarg = args.firstarg() if w_firstarg is not None and self.space.is_true( - self.space.isinstance(w_firstarg, self.w_class)): + self.space.abstract_isinstance(w_firstarg, self.w_class)): pass # ok else: msg = ("unbound method must be called with " @@ -175,9 +175,9 @@ return space.wrap(self) # already bound else: # only allow binding to a more specific class than before - if w_cls == space.w_None: - w_cls = space.type(w_obj) - if not space.is_true(space.issubtype(w_cls, self.w_class)): + #if w_cls == space.w_None: + # w_cls = space.type(w_obj) + if w_cls is not None and w_cls != space.w_None and not space.is_true(space.abstract_issubclass(w_cls, self.w_class)): return space.wrap(self) # subclass test failed return space.get(self.w_function, w_obj, w_cls) Modified: pypy/dist/pypy/interpreter/pyframe.py ============================================================================== --- pypy/dist/pypy/interpreter/pyframe.py (original) +++ pypy/dist/pypy/interpreter/pyframe.py Thu Feb 3 20:52:51 2005 @@ -223,7 +223,7 @@ # mistakes here usually show up as infinite recursion, which is fun. while isinstance(etype, tuple): etype = etype[0] - if isinstance(etype, type): + if isinstance(etype, (type, _classobj)): if not isinstance(value, etype): if value is None: # raise Type: we assume we have to instantiate Type Modified: pypy/dist/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/dist/pypy/interpreter/pyopcode.py (original) +++ pypy/dist/pypy/interpreter/pyopcode.py Thu Feb 3 20:52:51 2005 @@ -417,7 +417,7 @@ w_bases = f.valuestack.pop() w_name = f.valuestack.pop() w_metaclass = find_metaclass(f.space, w_bases, - w_methodsdict, f.w_globals) + w_methodsdict, f.w_globals, f.w_builtins) w_newclass = f.space.call_function(w_metaclass, w_name, w_bases, w_methodsdict) f.valuestack.push(w_newclass) @@ -824,7 +824,7 @@ stream.write("\n") file_softspace(stream, False) -def app_find_metaclass(bases, namespace, globals): +def app_find_metaclass(bases, namespace, globals, builtins): if '__metaclass__' in namespace: return namespace['__metaclass__'] elif len(bases) > 0: @@ -835,6 +835,8 @@ return type(base) elif '__metaclass__' in globals: return globals['__metaclass__'] + elif '__metaclass__' in builtins: + return builtins['__metaclass__'] else: return type Modified: pypy/dist/pypy/interpreter/test/test_class.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_class.py (original) +++ pypy/dist/pypy/interpreter/test/test_class.py Thu Feb 3 20:52:51 2005 @@ -2,7 +2,7 @@ class AppTestClass: def test_class(self): - class C: + class C(object): pass assert C.__class__ == type c = C() @@ -124,7 +124,7 @@ assert c.meth_doc.__doc__ == """this is a docstring""" def test_getattribute(self): - class C: + class C(object): def __getattribute__(self, attr): if attr == 'one': return 'two' Modified: pypy/dist/pypy/interpreter/test/test_function.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_function.py (original) +++ pypy/dist/pypy/interpreter/test/test_function.py Thu Feb 3 20:52:51 2005 @@ -227,5 +227,5 @@ assert meth4.call_args(args) == obj2 # Check method returned from unbound_method.__get__() # --- with an incompatible class - w_meth5 = meth3.descr_method_get(space.wrap('hello'), space.w_None) + w_meth5 = meth3.descr_method_get(space.wrap('hello'), space.w_str) assert space.is_true(space.is_(w_meth5, w_meth3)) Modified: pypy/dist/pypy/interpreter/test/test_raise.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_raise.py (original) +++ pypy/dist/pypy/interpreter/test/test_raise.py Thu Feb 3 20:52:51 2005 @@ -117,9 +117,9 @@ try: raise B except A, b: - assert type(b) == B + assert b.__class__ == B try: raise A, B(42) except B, b: - assert type(b) == B + assert b.__class__ == B assert b.x == 42 Modified: pypy/dist/pypy/lib/types.py ============================================================================== --- pypy/dist/pypy/lib/types.py (original) +++ pypy/dist/pypy/lib/types.py Thu Feb 3 20:52:51 2005 @@ -70,19 +70,16 @@ del g # checking whether we can make copy_reg happy -##class _C: -## def _m(self): pass -##ClassType = type(_C) -class ClassType: pass class _C: - def _m(self):pass -## end of testing hack + def _m(self): pass + +ClassType = _classobj # from builtins try: UnboundMethodType = type(_C._m) # Same as MethodType except AttributeError: pass _x = _C() -InstanceType = type(_x) +InstanceType = _instance # from builtins MethodType = type(_x._m) BuiltinFunctionType = type(len) Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Thu Feb 3 20:52:51 2005 @@ -15,6 +15,11 @@ file = __interplevel__eval('space.wrap(file)') open = file +# old-style classes dummy support +__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') +__builtins__['_instance'] = __interplevel__eval('space.w_instance') + + # TODO Fix this later to show Ctrl-D on Unix quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." @@ -174,6 +179,14 @@ return initial +def _recursive_issubclass(cls, klass_or_tuple): + if cls is klass_or_tuple: + return True + for base in cls.__bases__: + if _recursive_issubclass(base, klass_or_tuple): + return True + return False + def issubclass(cls, klass_or_tuple): if _issubtype(type(klass_or_tuple), tuple): for klass in klass_or_tuple: @@ -183,7 +196,12 @@ try: return _issubtype(cls, klass_or_tuple) except TypeError: - raise TypeError, "arg 2 must be a class or type or a tuple thereof" + if not hasattr(cls, '__bases__'): + raise TypeError, "arg 1 must be a class or type" + if not hasattr(klass_or_tuple, '__bases__'): + raise TypeError, "arg 2 must be a class or type or a tuple thereof" + return _recursive_issubclass(cls, klass_or_tuple) + def isinstance(obj, klass_or_tuple): if issubclass(type(obj), klass_or_tuple): @@ -441,6 +459,7 @@ # The following must be the last import from __interplevel__ because it # overwrites the special __import__ hook with the normal one. + from __interplevel__ import __import__ @@ -455,7 +474,7 @@ index += 1 return do_enumerate(it) -class xrange: +class xrange(object): def __init__(self, start, stop=None, step=1): if not isinstance(start, (int, long, float)): raise TypeError('an integer is required') @@ -927,7 +946,7 @@ # ________________________________________________________________________ -class buffer: +class buffer(object): def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" @@ -953,3 +972,7 @@ #from _file import file #open = file + +#default __metaclass__ +# XXX can use _classobj when we have a working one integrated +__metaclass__ = type Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Thu Feb 3 20:52:51 2005 @@ -202,6 +202,10 @@ w_type = self.gettypeobject(typedef) setattr(self, 'w_' + typedef.name, w_type) for_builtins[typedef.name] = w_type + + # dummy old-style classes types + self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {}) + self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {}) # exceptions ##for_builtins.update(self.clone_exception_hierarchy()) Modified: pypy/dist/pypy/objspace/std/test/test_dictproxy.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_dictproxy.py (original) +++ pypy/dist/pypy/objspace/std/test/test_dictproxy.py Thu Feb 3 20:52:51 2005 @@ -4,7 +4,7 @@ class AppTestUserObject: def test_dictproxy(self): - class NotEmpty: + class NotEmpty(object): a = 1 assert isinstance(NotEmpty.__dict__, dict) == False assert 'a' in NotEmpty.__dict__ Modified: pypy/dist/pypy/objspace/std/test/test_floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_floatobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_floatobject.py Thu Feb 3 20:52:51 2005 @@ -87,4 +87,4 @@ class b: pass - raises(TypeError, float, b()) + raises((AttributeError, TypeError), float, b()) Modified: pypy/dist/pypy/objspace/std/test/test_intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_intobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_intobject.py Thu Feb 3 20:52:51 2005 @@ -345,7 +345,7 @@ class b: pass - raises(TypeError, int, b()) + raises((AttributeError,TypeError), int, b()) def test_special_long(self): class a: @@ -358,4 +358,4 @@ class b: pass - raises(TypeError, int, b()) + raises((AttributeError,TypeError), long, b()) Modified: pypy/dist/pypy/objspace/std/test/test_typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_typeobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_typeobject.py Thu Feb 3 20:52:51 2005 @@ -57,7 +57,8 @@ class AppTestTypeObject: def test_bases(self): assert int.__bases__ == (object,) - class X: pass + class X: + __metaclass__ = type assert X.__bases__ == (object,) class Y(X): pass assert Y.__bases__ == (X,) @@ -191,3 +192,47 @@ raise AssertionError, '__doc__ should not be writable' assert ImmutableDoc.__doc__ == 'foo' + + def test_metaclass_conflict(self): + + class T1(type): + pass + class T2(type): + pass + class D1: + __metaclass__ = T1 + class D2: + __metaclass__ = T2 + def conflict(): + class C(D1,D2): + pass + raises(TypeError, conflict) + + def test_metaclass_choice(self): + events = [] + + class T1(type): + def __new__(*args): + events.append(args) + return type.__new__(*args) + + class D1: + __metaclass__ = T1 + + class C(D1): + pass + + class F(object): + pass + + class G(F,D1): + pass + + assert len(events) == 3 + assert type(D1) is T1 + assert type(C) is T1 + assert type(G) is T1 + + + + Modified: pypy/dist/pypy/objspace/std/test/test_userobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_userobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_userobject.py Thu Feb 3 20:52:51 2005 @@ -58,15 +58,15 @@ def test_descr_get(self): class C: - class desc: + class desc(object): def __get__(self, ob, cls=None): return 42 prop = desc() assert C().prop == 42 def test_descr_set(self): - class C: - class desc: + class C(object): + class desc(object): def __set__(self, ob, val): ob.wibble = val prop = desc() @@ -75,8 +75,8 @@ assert c.wibble == 32 def test_descr_delete(self): - class C: - class desc: + class C(object): + class desc(object): def __set__(self, ob, val): oogabooga def __delete__(self, ob): @@ -110,7 +110,7 @@ assert c1("hello", "world") == ("hello", "world") def test_getattribute(self): - class C: + class C(object): def __getattribute__(self, name): return '->' + name c1 = C() Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Thu Feb 3 20:52:51 2005 @@ -1,6 +1,7 @@ from pypy.objspace.std.objspace import * from pypy.interpreter.function import Function, StaticMethod from pypy.interpreter.argument import Arguments +from pypy.interpreter import gateway from pypy.objspace.std.stdtypedef import std_dict_descr, issubtypedef from pypy.objspace.std.objecttype import object_typedef @@ -15,13 +16,15 @@ w_self.dict_w = dict_w w_self.ensure_static__new__() - w_self.mro_w = compute_C3_mro(w_self) + w_self.mro_w = compute_C3_mro(space, w_self) if overridetypedef is not None: w_self.instancetypedef = overridetypedef else: # find the most specific typedef instancetypedef = object_typedef for w_base in bases_w: + if not space.is_true(space.isinstance(w_base, space.w_type)): + continue if issubtypedef(w_base.instancetypedef, instancetypedef): instancetypedef = w_base.instancetypedef elif not issubtypedef(instancetypedef, w_base.instancetypedef): @@ -56,7 +59,14 @@ space = w_self.space for w_class in w_self.mro_w: try: - return w_class.dict_w[key] + if isinstance(w_class, W_TypeObject): + return w_class.dict_w[key] + else: + try: + return space.getitem(space.getdict(w_class),space.wrap(key)) + except OperationError,e: + if not e.match(space, space.w_KeyError): + raise except KeyError: pass return None @@ -67,7 +77,14 @@ space = w_self.space for w_class in w_self.mro_w: try: - return w_class, w_class.dict_w[key] + if isinstance(w_class, W_TypeObject): + return w_class, w_class.dict_w[key] + else: + try: + return w_class, space.getitem(space.getdict(w_class),space.wrap(key)) + except OperationError,e: + if not e.match(space, space.w_KeyError): + raise except KeyError: pass return None, None @@ -167,9 +184,31 @@ # ____________________________________________________________ -def compute_C3_mro(cls): + +def app_abstract_mro(klass): # abstract/classic mro + mro = [] + def fill_mro(klass): + if klass not in mro: + mro.append(klass) + assert isinstance(klass.__bases__, tuple) + for base in klass.__bases__: + fill_mro(base) + fill_mro(klass) + return mro + +abstract_mro = gateway.app2interp(app_abstract_mro) + + +def get_mro(space, klass): + if isinstance(klass, W_TypeObject): + return list(klass.mro_w) + else: + return space.unpackiterable(abstract_mro(space, klass)) + + +def compute_C3_mro(space, cls): order = [] - orderlists = [list(base.mro_w) for base in cls.bases_w] + orderlists = [get_mro(space, base) for base in cls.bases_w] orderlists.append([cls] + cls.bases_w) while orderlists: for candidatelist in orderlists: Modified: pypy/dist/pypy/objspace/std/typetype.py ============================================================================== --- pypy/dist/pypy/objspace/std/typetype.py (original) +++ pypy/dist/pypy/objspace/std/typetype.py Thu Feb 3 20:52:51 2005 @@ -1,3 +1,4 @@ +from pypy.interpreter.error import OperationError from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.dictproxyobject import dictproxy_descr @@ -5,10 +6,33 @@ def descr__new__(space, w_typetype, w_name, w_bases, w_dict): "This is used to create user-defined classes only." from pypy.objspace.std.typeobject import W_TypeObject - # XXX check types + # XXX check types + bases_w = space.unpackiterable(w_bases) + + w_winner = w_typetype + for base in bases_w: + w_typ = space.type(base) + if space.is_w(w_typ, space.w_classobj): + continue # special-case old-style classes + if space.is_true(space.issubtype(w_winner, w_typ)): + continue + if space.is_true(space.issubtype(w_typ, w_winner)): + w_winner = w_typ + continue + raise OperationError(space.w_TypeError, + space.wrap("metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases")) + + if not space.is_w(w_winner, w_typetype): + newfunc = space.getattr(w_winner, space.wrap('__new__')) + if not space.is_w(newfunc, space.getattr(space.w_type, space.wrap('__new__'))): + return space.call_function(newfunc, w_winner, w_name, w_bases, w_dict) + w_typetype = w_winner + name = space.str_w(w_name) assert isinstance(name, str) - bases_w = space.unpackiterable(w_bases) dict_w = {} dictkeys_w = space.unpackiterable(w_dict) for w_key in dictkeys_w: From tismer at codespeak.net Fri Feb 4 13:43:47 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 4 Feb 2005 13:43:47 +0100 (MET) Subject: [pypy-svn] r8844 - pypy/dist/pypy/translator Message-ID: <20050204124347.43CB027C4E@code1.codespeak.net> Author: tismer Date: Thu Feb 3 20:55:37 2005 New Revision: 8844 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: changed geninterpreterlevel to use the nice new __args__ interface. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 3 20:55:37 2005 @@ -14,7 +14,7 @@ But I need to ask how we want to integrate it. XXX open questions: -- do we wantamoduleperapp-spaceoperation? +- do we want a moduleperapp-spaceoperation? - do we want to auto-generate stuff? - do we want to create code that is more similar to the app code? - do we want to create specialized code for constants? @@ -30,7 +30,7 @@ from pypy.objspace.flow.model import last_exception, last_exc_value from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph from pypy.translator.simplify import remove_direct_loops -from pypy.interpreter.pycode import CO_VARARGS +from pypy.interpreter.pycode import CO_VARARGS, CO_VARKEYWORDS from pypy.annotation import model as annmodel from types import FunctionType, CodeType from pypy.interpreter.error import OperationError @@ -851,69 +851,63 @@ localnames = [self.expr(a, locals) for a in uniqueitems(localslst)] # collect all the arguments + vararg = varkw = None + varargname = varkwname = None + all_args = graph.getargs() + p = len(all_args) + if func.func_code.co_flags & CO_VARKEYWORDS: + p -= 1 + varkw = graph.getargs()[p] + varkwname = func.func_code.co_varnames[p] if func.func_code.co_flags & CO_VARARGS: - vararg = graph.getargs()[-1] - positional_args = graph.getargs()[:-1] - else: - vararg = None - positional_args = graph.getargs() - min_number_of_args = len(positional_args) - len(name_of_defaults) + p -= 1 + vararg = graph.getargs()[p] + varargname = func.func_code.co_varnames[p] + positional_args = all_args[:p] fast_args = [self.expr(a, locals) for a in positional_args] if vararg is not None: fast_args.append(self.expr(vararg, locals)) + if varkw is not None: + fast_args.append(self.expr(varkw, locals)) fast_name = 'fast' + f_name fast_set = dict(zip(fast_args, fast_args)) # create function declaration name = self.trans_funcname(func.__name__) # for - argstr = ", ".join(fast_args) - fast_function_header = ('def %s(space, %s):' + argstr = ", ".join(['space'] + fast_args) + fast_function_header = ('def %s(%s):' % (name, argstr)) - print >> f, 'def %s(space, *args_w):' % (name,) + print >> f, 'def %s(space, __args__):' % (name,) if docstr is not None: print >> f, docstr - kwlist = ['"%s"' % var for var in - func.func_code.co_varnames[:func.func_code.co_argcount]] - print >> f, ' kwlist = [%s]' % (', '.join(kwlist),) - - # argument unpacking - if vararg is not None: - varname = self.expr(vararg, locals) - lenargs = len(positional_args) - print >> f, ' %s = space.newtuple(list(args_w[%d:]))' % ( - varname, lenargs) - print >> f, ' _args_w = args_w[:%d]' % (lenargs,) - else: - print >> f, ' _args_w = args_w' - varname = None - + print >> f def tupstr(seq): if len(seq) == 1: fmt = '%s,' else: fmt = '%s' return fmt % ', '.join(seq) + def tupassstr(seq): + if not seq: + return "" + else: + return tupstr(seq) + " = " - print >> f, ' defaults_w = (%s)' % tupstr(name_of_defaults) - - theargs = [arg for arg in fast_args if arg != varname] - txt = inspect.getsource(PyArg_ParseMini) + ('\n' - 'm.PyArg_ParseMini = PyArg_ParseMini\n' - 'from pypy.interpreter.error import OperationError\n' - 'm.OperationError = OperationError') - self.initcode.append(txt) print >> f, ' funcname = "%s"' % func.__name__ - if theargs: - txt = ' %s = PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' - print >>f, txt % (tupstr(theargs), - min_number_of_args, len(positional_args)) - else: - txt = ' PyArg_ParseMini(space, funcname, %d, %d, _args_w, defaults_w)' - print >>f, txt % (min_number_of_args, len(positional_args)) - print >> f, ' return %s(space, %s)' % (fast_name, ', '.join(fast_args)) + + kwlist = list(func.func_code.co_varnames[:func.func_code.co_argcount]) + signature = ' signature = %r' % kwlist + signature = ", ".join([signature, repr(varargname), repr(varkwname)]) + print >> f, signature + + print >> f, ' def_w = [%s]' % ", ".join(name_of_defaults) + + print >> f, ' %s__args__.parse(funcname, signature, def_w)' % ( + tupassstr(fast_args),) + print >> f, ' return %s(%s)' % (fast_name, ', '.join(["space"]+fast_args)) print >> f, '%s = globals().pop("%s")' % (f_name, name) print >> f @@ -1340,3 +1334,11 @@ t = Translator(test, verbose=False, simplifying=True) gen = GenRpy(t) gen.gen_source("/tmp/look2.py") + +##>>> def f_foo(space, __args__): +##... signature = ["a", "b"], "args", "kwds" +##... defaults_w = space.w_int(42) # is this the default for b? +##... w_a, w_b, w_args, w_kwds = __args__.parse("foo", signature, defaults_w) +##... return fastf_foo(w_a, w_b, w_args, w_kwds) +##... # args/kwds can be None. +##... # then I don't receive w_xxx for them as well. From arigo at codespeak.net Fri Feb 4 13:43:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:47 +0100 (MET) Subject: [pypy-svn] r8845 - pypy/dist/pypy/translator Message-ID: <20050204124347.732B727C4E@code1.codespeak.net> Author: arigo Date: Thu Feb 3 21:24:47 2005 New Revision: 8845 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: Simplified a bit the code generated for simple_call(). Generate the correct code for the more complicated call_args(). Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 3 21:24:47 2005 @@ -34,6 +34,7 @@ from pypy.annotation import model as annmodel from types import FunctionType, CodeType from pypy.interpreter.error import OperationError +from pypy.interpreter.argument import Arguments from pypy.objspace.std.restricted_int import r_int, r_uint from pypy.translator.translator import Translator @@ -179,8 +180,7 @@ fmt = "%(res)s = %(func)s(%(args)s)" else: # default for a spacecall: - fmt = ("_tup = space.newtuple([%(args)s])\n" - "%(res)s = space.call(%(func)s, _tup)") + fmt = "%(res)s = space.call_function(%(func)s, %(args)s)" # see if we can optimize for a fast call. # we just do the very simple ones. if self.use_fast_call and (isinstance(v, Constant) @@ -193,6 +193,18 @@ return fmt % {"res" : self.expr(op.result, localnames), "func": exv, "args": self.arglist(op.args[1:], localnames) } + if op.opname == "call_args": + v = op.args[0] + exv = self.expr(v, localnames) + fmt = ( + "_args = Arguments.fromshape(space, %(shape)s, [%(data_w)s])\n" + "%(res)s = space.call_args(%(func)s, _args)") + assert isinstance(op.args[1], Constant) + shape = op.args[1].value + return fmt % {"res": self.expr(op.result, localnames), + "func": exv, + "shape": repr(shape), + "data_w": self.arglist(op.args[2:], localnames) } if op.opname in self.has_listarg: fmt = "%s = %s([%s])" else: @@ -1052,7 +1064,11 @@ # ____________________________________________________________ - RPY_HEADER = '#!/bin/env python\n# -*- coding: LATIN-1 -*-' + RPY_HEADER = '''#!/bin/env python +# -*- coding: LATIN-1 -*- + +from pypy.interpreter.argument import Arguments +''' RPY_SEP = "#*************************************************************" From arigo at codespeak.net Fri Feb 4 13:43:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:47 +0100 (MET) Subject: [pypy-svn] r8846 - pypy/dist/pypy/objspace/flow Message-ID: <20050204124347.A9BCD27C4E@code1.codespeak.net> Author: arigo Date: Thu Feb 3 21:54:16 2005 New Revision: 8846 Modified: pypy/dist/pypy/objspace/flow/flowcontext.py pypy/dist/pypy/objspace/flow/objspace.py Log: Detect constant operations that always raise an exception. These ones are most probably bugs in the user's source code. Modified: pypy/dist/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/dist/pypy/objspace/flow/flowcontext.py (original) +++ pypy/dist/pypy/objspace/flow/flowcontext.py Thu Feb 3 21:54:16 2005 @@ -5,6 +5,10 @@ from pypy.objspace.flow.framestate import FrameState +class OperationThatShouldNotBePropagatedError(OperationError): + pass + + class SpamBlock(Block): dead = False @@ -210,6 +214,11 @@ continue # restarting a dead SpamBlock try: w_result = frame.resume() + except OperationThatShouldNotBePropagatedError, e: + raise Exception( + 'found an operation that always raises %s: %s' % ( + self.space.unwrap(e.w_type).__name__, + self.space.unwrap(e.w_value))) except OperationError, e: link = Link([e.w_type, e.w_value], self.graph.exceptblock) self.crnt_block.closeblock(link) Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Thu Feb 3 21:54:16 2005 @@ -140,11 +140,6 @@ def getexecutioncontext(self): return self.executioncontext - def reraise(self): - etype, evalue, etb = sys.exc_info() - #print >> sys.stderr, '*** reraise', etype, evalue - raise OperationError, OperationError(self.wrap(etype), self.wrap(evalue)), etb - def setup_executioncontext(self, ec): self.executioncontext = ec from pypy.objspace.flow import specialcase @@ -364,7 +359,11 @@ try: result = op(*args) except: - self.reraise() + etype, evalue, etb = sys.exc_info() + msg = "generated by a constant operation: %s%r" % ( + name, tuple(args)) + raise flowcontext.OperationThatShouldNotBePropagatedError( + self.wrap(etype), self.wrap(msg)) else: return self.wrap(result) From arigo at codespeak.net Fri Feb 4 13:43:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:47 +0100 (MET) Subject: [pypy-svn] r8847 - pypy/dist/pypy/lib Message-ID: <20050204124347.F12E527C52@code1.codespeak.net> Author: arigo Date: Thu Feb 3 21:59:15 2005 New Revision: 8847 Modified: pypy/dist/pypy/lib/_classobj.py Log: divmod() and cmp() are not in the operator module. Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 3 21:59:15 2005 @@ -363,7 +363,7 @@ return func(other) return NotImplemented else: - return operator.%(op2)s(self, other) + return %(module)s%(op2)s(self, other) def __r%(op)s__(self, other): coerced = coerce(self, other) @@ -373,8 +373,9 @@ return func(other) return NotImplemented else: - return operator.%(op2)s(other, self) -""") % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')]} + return %(module)s%(op2)s(other, self) +""") % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')], + "module": ('operator.', '')[op == 'divmod']} del op @@ -491,7 +492,7 @@ v = coerced[0] w = coerced[1] if not isinstance(v, instance) and not isinstance(w, instance): - return operator.cmp(v,w) + return cmp(v,w) if isinstance(v, instance): func = instance_getattr1(v, '__cmp__', False) if func: From sanxiyn at codespeak.net Fri Feb 4 13:43:48 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Fri, 4 Feb 2005 13:43:48 +0100 (MET) Subject: [pypy-svn] r8849 - pypy/dist/pypy/lib Message-ID: <20050204124348.C889A27C54@code1.codespeak.net> Author: sanxiyn Date: Fri Feb 4 05:08:50 2005 New Revision: 8849 Modified: pypy/dist/pypy/lib/re.py Log: Regular expression flags Modified: pypy/dist/pypy/lib/re.py ============================================================================== --- pypy/dist/pypy/lib/re.py (original) +++ pypy/dist/pypy/lib/re.py Fri Feb 4 05:08:50 2005 @@ -3,6 +3,15 @@ # from sre_adapt import Pattern +# Constants, from CPython +I = IGNORECASE = 2 +L = LOCALE = 4 +M = MULTILINE = 8 +S = DOTALL = 16 +U = UNICODE = 32 +X = VERBOSE = 64 + + # From CPython def escape(pattern): "Escape all non-alphanumeric characters in pattern." From ac at codespeak.net Fri Feb 4 13:43:49 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 4 Feb 2005 13:43:49 +0100 (MET) Subject: [pypy-svn] r8852 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050204124349.B602127C6C@code1.codespeak.net> Author: ac Date: Fri Feb 4 10:50:12 2005 New Revision: 8852 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: Another test passes. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Fri Feb 4 10:50:12 2005 @@ -31,6 +31,7 @@ 'test_bisect.py', 'test_call', 'test_codeop.py', +'test_operator.py', 'test_compile.py', 'test_operator.py', 'test_heapq.py', From arigo at codespeak.net Fri Feb 4 13:43:52 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:43:52 +0100 (MET) Subject: [pypy-svn] r8862 - in pypy/dist/pypy/module: . test Message-ID: <20050204124352.06D8927C3D@code1.codespeak.net> Author: arigo Date: Fri Feb 4 12:12:40 2005 New Revision: 8862 Modified: pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_builtin.py Log: Patch from David Fraser. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Fri Feb 4 12:12:40 2005 @@ -577,8 +577,8 @@ def __get__(self, obj, klass=None): if klass is None: klass = type(obj) - def newfunc(*args): - return self.f(klass, *args) + def newfunc(*args, **kwargs): + return self.f(klass, *args, **kwargs) return newfunc if not hasattr(dict, 'fromkeys'): Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Fri Feb 4 12:12:40 2005 @@ -323,6 +323,30 @@ raises(TypeError, issubclass, int, 6) raises(TypeError, issubclass, int, (float, 6)) + def test_staticmethod(self): + class X: + def f(*args, **kwds): return args, kwds + f = staticmethod(f) + assert X.f() == ((), {}) + assert X.f(42, x=43) == ((42,), {'x': 43}) + assert X().f() == ((), {}) + assert X().f(42, x=43) == ((42,), {'x': 43}) + + def test_classmethod(self): + class X: + def f(*args, **kwds): return args, kwds + f = classmethod(f) + class Y(X): + pass + assert X.f() == ((X,), {}) + assert X.f(42, x=43) == ((X, 42), {'x': 43}) + assert X().f() == ((X,), {}) + assert X().f(42, x=43) == ((X, 42), {'x': 43}) + assert Y.f() == ((Y,), {}) + assert Y.f(42, x=43) == ((Y, 42), {'x': 43}) + assert Y().f() == ((Y,), {}) + assert Y().f(42, x=43) == ((Y, 42), {'x': 43}) + class TestInternal: From arigo at codespeak.net Fri Feb 4 13:48:35 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 13:48:35 +0100 (MET) Subject: [pypy-svn] r8864 - pypy/dist/pypy/objspace/flow/test Message-ID: <20050204124835.5CD4827C09@code1.codespeak.net> Author: arigo Date: Fri Feb 4 13:48:35 2005 New Revision: 8864 Modified: pypy/dist/pypy/objspace/flow/test/test_model.py Log: Fixed the test. Modified: pypy/dist/pypy/objspace/flow/test/test_model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/test/test_model.py (original) +++ pypy/dist/pypy/objspace/flow/test/test_model.py Fri Feb 4 13:48:35 2005 @@ -11,8 +11,12 @@ func = func.im_func except AttributeError: pass - #name = func.func_name - return self.space.build_flow(func) + # disable implicit exceptions to keep the graphs simple and checkable + self.space.handle_implicit_exceptions = lambda exceptions: None + try: + return self.space.build_flow(func) + finally: + del self.space.handle_implicit_exceptions #_____________________________________________ def simplefunc(x): From ac at codespeak.net Fri Feb 4 14:33:44 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 4 Feb 2005 14:33:44 +0100 (MET) Subject: [pypy-svn] r8866 - pypy/dist/pypy/objspace/std Message-ID: <20050204133344.A270D27C68@code1.codespeak.net> Author: ac Date: Fri Feb 4 14:33:44 2005 New Revision: 8866 Modified: pypy/dist/pypy/objspace/std/longobject.py Log: Have pow() raise exceptions properly when operationg on long. Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Fri Feb 4 14:33:44 2005 @@ -151,7 +151,14 @@ x = w_long1.longval y = w_long2.longval z = w_long3.longval - t = pow(x, y, z) + try: + t = pow(x, y, z) + except TypeError, e: + raise OperationError(space.w_TypeError, + space.wrap(e.args[0])) + except ValueError, e: + raise OperationError(space.w_ValueError, + space.wrap(e.args[0])) return W_LongObject(space, t) def neg__Long(space, w_long1): From ac at codespeak.net Fri Feb 4 14:35:43 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 4 Feb 2005 14:35:43 +0100 (MET) Subject: [pypy-svn] r8867 - in pypy/dist: lib-python-2.3.4/test pypy/module Message-ID: <20050204133543.5A03827C68@code1.codespeak.net> Author: ac Date: Fri Feb 4 14:35:43 2005 New Revision: 8867 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Log: Implement a primitive sys.getrefcount() (It gets test_sys to work). Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Fri Feb 4 14:35:43 2005 @@ -35,6 +35,7 @@ 'test_compile.py', 'test_operator.py', 'test_heapq.py', +'test_sys.py', ) working_outputtests = ( Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Fri Feb 4 14:35:43 2005 @@ -188,3 +188,15 @@ def getdefaultencoding(): """getdefaultencoding() -> return the default encoding used for UNICODE""" return space.wrap(cpy_sys.getdefaultencoding()) + +def getrefcount(w_obj): + """getrefcount(object) -> integer + +Return the reference count of object. The count returned is generally +one higher than you might expect, because it includes the (temporary) +reference as an argument to getrefcount(). +""" + # From the results i get when using this i need to apply a fudge + # value of 6 to get results comparable to cpythons. /Arre + return space.wrap(cpy_sys.getrefcount(w_obj) - 6) + Modified: pypy/dist/pypy/module/sysmodule.py ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/dist/pypy/module/sysmodule.py Fri Feb 4 14:35:43 2005 @@ -20,7 +20,7 @@ from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir from __interplevel__ import getrecursionlimit, setrecursionlimit from __interplevel__ import getcheckinterval, setcheckinterval -from __interplevel__ import getdefaultencoding +from __interplevel__ import getdefaultencoding, getrefcount # Dummy executable = 'py.py' From pedronis at codespeak.net Fri Feb 4 16:44:48 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 4 Feb 2005 16:44:48 +0100 (MET) Subject: [pypy-svn] r8873 - in pypy/dist/pypy/objspace: . test Message-ID: <20050204154448.6682C27BEA@code1.codespeak.net> Author: pedronis Date: Fri Feb 4 16:44:48 2005 New Revision: 8873 Added: pypy/dist/pypy/objspace/test/test_descroperation.py (contents, props changed) Modified: pypy/dist/pypy/objspace/descroperation.py Log: support for __getslice__, __setslice__ and __delslice__ for new-style classes too Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Fri Feb 4 16:44:48 2005 @@ -168,6 +168,13 @@ return space.get_and_call_function(w_descr, w_obj) def getitem(space, w_obj, w_key): + if space.is_true(space.isinstance(w_key, space.w_slice)): + if space.is_w(space.getattr(w_key, space.wrap('step')), space.w_None): + w_descr = space.lookup(w_obj, '__getslice__') + if w_descr is not None: + return space.get_and_call_function(w_descr, w_obj, + space.getattr(w_key, space.wrap('start')), + space.getattr(w_key, space.wrap('stop'))) w_descr = space.lookup(w_obj, '__getitem__') if w_descr is None: raise OperationError(space.w_TypeError, @@ -175,6 +182,14 @@ return space.get_and_call_function(w_descr, w_obj, w_key) def setitem(space, w_obj, w_key, w_val): + if space.is_true(space.isinstance(w_key, space.w_slice)): + if space.is_w(space.getattr(w_key, space.wrap('step')), space.w_None): + w_descr = space.lookup(w_obj, '__setslice__') + if w_descr is not None: + return space.get_and_call_function(w_descr, w_obj, + space.getattr(w_key, space.wrap('start')), + space.getattr(w_key, space.wrap('stop')), + w_val) w_descr = space.lookup(w_obj, '__setitem__') if w_descr is None: raise OperationError(space.w_TypeError, @@ -182,6 +197,13 @@ return space.get_and_call_function(w_descr, w_obj, w_key, w_val) def delitem(space, w_obj, w_key): + if space.is_true(space.isinstance(w_key, space.w_slice)): + if space.is_w(space.getattr(w_key, space.wrap('step')), space.w_None): + w_descr = space.lookup(w_obj, '__delslice__') + if w_descr is not None: + return space.get_and_call_function(w_descr, w_obj, + space.getattr(w_key, space.wrap('start')), + space.getattr(w_key, space.wrap('stop'))) w_descr = space.lookup(w_obj, '__delitem__') if w_descr is None: raise OperationError(space.w_TypeError, Added: pypy/dist/pypy/objspace/test/test_descroperation.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/objspace/test/test_descroperation.py Fri Feb 4 16:44:48 2005 @@ -0,0 +1,15 @@ + + +class AppTest_Descroperation: + + def test_getslice(self): + class Sq(object): + def __getslice__(self, start, stop): + return (start, stop) + + def __getitem__(self, key): + return "booh" + + sq = Sq() + + assert sq[1:3] == (1,3) From pedronis at codespeak.net Fri Feb 4 17:14:24 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 4 Feb 2005 17:14:24 +0100 (MET) Subject: [pypy-svn] r8876 - pypy/dist/pypy/objspace/std Message-ID: <20050204161424.DF02C27C37@code1.codespeak.net> Author: pedronis Date: Fri Feb 4 17:14:24 2005 New Revision: 8876 Modified: pypy/dist/pypy/objspace/std/fake.py Log: trying to fake SRE_Pattern and _Match Modified: pypy/dist/pypy/objspace/std/fake.py ============================================================================== --- pypy/dist/pypy/objspace/std/fake.py (original) +++ pypy/dist/pypy/objspace/std/fake.py Fri Feb 4 17:14:24 2005 @@ -41,9 +41,24 @@ "NOT_RPYTHON (not remotely so!)." debug_print('faking %r'%(cpy_type,)) kw = {} - for s, v in cpy_type.__dict__.items(): - if cpy_type is not unicode or s not in ['__add__', '__contains__']: - kw[s] = v + + if cpy_type.__name__ == 'SRE_Pattern': + import re + import __builtin__ + p = re.compile("foo") + for meth_name in p.__methods__: + kw[meth_name] = __builtin__.eval("lambda p,*args,**kwds: p.%s(*args,**kwds)" % meth_name) + elif cpy_type.__name__ == 'SRE_Match': + import re + import __builtin__ + m = re.compile("foo").match('foo') + for meth_name in m.__methods__: + kw[meth_name] = __builtin__.eval("lambda m,*args,**kwds: m.%s(*args,**kwds)" % meth_name) + else: + for s, v in cpy_type.__dict__.items(): + if cpy_type is not unicode or s not in ['__add__', '__contains__']: + kw[s] = v + def fake__new__(space, w_type, args_w): args = [space.unwrap(w_arg) for w_arg in args_w] try: From sanxiyn at codespeak.net Fri Feb 4 17:35:18 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Fri, 4 Feb 2005 17:35:18 +0100 (MET) Subject: [pypy-svn] r8877 - pypy/dist/pypy/lib Message-ID: <20050204163518.73A3627C3B@code1.codespeak.net> Author: sanxiyn Date: Fri Feb 4 17:35:18 2005 New Revision: 8877 Removed: pypy/dist/pypy/lib/sre_parse.py Modified: pypy/dist/pypy/lib/README.regex pypy/dist/pypy/lib/re.py Log: Hacks removed. Thanks pedronis! Modified: pypy/dist/pypy/lib/README.regex ============================================================================== --- pypy/dist/pypy/lib/README.regex (original) +++ pypy/dist/pypy/lib/README.regex Fri Feb 4 17:35:18 2005 @@ -19,10 +19,14 @@ plexre.py uses Plex module to implement regular expression. sre_adapt.py cheats and imports CPython _sre. +Following information is now out-of-date and incorrect: + +(fixed in r8876) Importing CPython _sre doesn't work currently, because C types are not succesfully faked. The reason seems to be the lack of __dict__. This is also why we have pure Python random.py from 2.2 in this directory. +(fixed in r8873) sre_parse.py is patched because it uses deprecated __getslice__ in a special way, and PyPy fails to interpret it correctly. Delete this file when this is fixed. Modified: pypy/dist/pypy/lib/re.py ============================================================================== --- pypy/dist/pypy/lib/re.py (original) +++ pypy/dist/pypy/lib/re.py Fri Feb 4 17:35:18 2005 @@ -1,4 +1,7 @@ -from dumbre import Pattern +from sre import * + +''' +# from dumbre import Pattern # from plexre import Pattern # from sre_adapt import Pattern @@ -37,3 +40,4 @@ def match(pattern, string, flags=0): return compile(pattern, flags).match(string) +''' Deleted: /pypy/dist/pypy/lib/sre_parse.py ============================================================================== --- /pypy/dist/pypy/lib/sre_parse.py Fri Feb 4 17:35:18 2005 +++ (empty file) @@ -1,742 +0,0 @@ -# -# Secret Labs' Regular Expression Engine -# -# convert re-style regular expression to sre pattern -# -# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. -# -# See the sre.py file for information on usage and redistribution. -# - -"""Internal support module for sre""" - -# XXX: show string offset and offending character for all errors - -# this module works under 1.5.2 and later. don't use string methods -import string, sys - -from sre_constants import * - -SPECIAL_CHARS = ".\\[{()*+?^$|" -REPEAT_CHARS = "*+?{" - -DIGITS = tuple("0123456789") - -OCTDIGITS = tuple("01234567") -HEXDIGITS = tuple("0123456789abcdefABCDEF") - -WHITESPACE = tuple(" \t\n\r\v\f") - -ESCAPES = { - r"\a": (LITERAL, ord("\a")), - r"\b": (LITERAL, ord("\b")), - r"\f": (LITERAL, ord("\f")), - r"\n": (LITERAL, ord("\n")), - r"\r": (LITERAL, ord("\r")), - r"\t": (LITERAL, ord("\t")), - r"\v": (LITERAL, ord("\v")), - r"\\": (LITERAL, ord("\\")) -} - -CATEGORIES = { - r"\A": (AT, AT_BEGINNING_STRING), # start of string - r"\b": (AT, AT_BOUNDARY), - r"\B": (AT, AT_NON_BOUNDARY), - r"\d": (IN, [(CATEGORY, CATEGORY_DIGIT)]), - r"\D": (IN, [(CATEGORY, CATEGORY_NOT_DIGIT)]), - r"\s": (IN, [(CATEGORY, CATEGORY_SPACE)]), - r"\S": (IN, [(CATEGORY, CATEGORY_NOT_SPACE)]), - r"\w": (IN, [(CATEGORY, CATEGORY_WORD)]), - r"\W": (IN, [(CATEGORY, CATEGORY_NOT_WORD)]), - r"\Z": (AT, AT_END_STRING), # end of string -} - -FLAGS = { - # standard flags - "i": SRE_FLAG_IGNORECASE, - "L": SRE_FLAG_LOCALE, - "m": SRE_FLAG_MULTILINE, - "s": SRE_FLAG_DOTALL, - "x": SRE_FLAG_VERBOSE, - # extensions - "t": SRE_FLAG_TEMPLATE, - "u": SRE_FLAG_UNICODE, -} - -# figure out best way to convert hex/octal numbers to integers -try: - int("10", 8) - atoi = int # 2.0 and later -except TypeError: - atoi = string.atoi # 1.5.2 - -class Pattern: - # master pattern object. keeps track of global attributes - def __init__(self): - self.flags = 0 - self.open = [] - self.groups = 1 - self.groupdict = {} - def opengroup(self, name=None): - gid = self.groups - self.groups = gid + 1 - if name is not None: - ogid = self.groupdict.get(name, None) - if ogid is not None: - raise error, ("redefinition of group name %s as group %d; " - "was group %d" % (repr(name), gid, ogid)) - self.groupdict[name] = gid - self.open.append(gid) - return gid - def closegroup(self, gid): - self.open.remove(gid) - def checkgroup(self, gid): - return gid < self.groups and gid not in self.open - -class SubPattern: - # a subpattern, in intermediate form - def __init__(self, pattern, data=None): - self.pattern = pattern - if data is None: - data = [] - self.data = data - self.width = None - def dump(self, level=0): - nl = 1 - for op, av in self.data: - print level*" " + op,; nl = 0 - if op == "in": - # member sublanguage - print; nl = 1 - for op, a in av: - print (level+1)*" " + op, a - elif op == "branch": - print; nl = 1 - i = 0 - for a in av[1]: - if i > 0: - print level*" " + "or" - a.dump(level+1); nl = 1 - i = i + 1 - elif type(av) in (type(()), type([])): - for a in av: - if isinstance(a, SubPattern): - if not nl: print - a.dump(level+1); nl = 1 - else: - print a, ; nl = 0 - else: - print av, ; nl = 0 - if not nl: print - def __repr__(self): - return repr(self.data) - def __len__(self): - return len(self.data) - def __iter__(self): - return iter(self.data) - def __delitem__(self, index): - del self.data[index] - def __getitem__(self, index): - if isinstance(index, slice): - return SubPattern(self.pattern, self.data[index]) - else: - return self.data[index] - def __setitem__(self, index, code): - self.data[index] = code - def insert(self, index, code): - self.data.insert(index, code) - def append(self, code): - self.data.append(code) - def getwidth(self): - # determine the width (min, max) for this subpattern - if self.width: - return self.width - lo = hi = 0L - for op, av in self.data: - if op is BRANCH: - i = sys.maxint - j = 0 - for av in av[1]: - l, h = av.getwidth() - i = min(i, l) - j = max(j, h) - lo = lo + i - hi = hi + j - elif op is CALL: - i, j = av.getwidth() - lo = lo + i - hi = hi + j - elif op is SUBPATTERN: - i, j = av[1].getwidth() - lo = lo + i - hi = hi + j - elif op in (MIN_REPEAT, MAX_REPEAT): - i, j = av[2].getwidth() - lo = lo + long(i) * av[0] - hi = hi + long(j) * av[1] - elif op in (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY): - lo = lo + 1 - hi = hi + 1 - elif op == SUCCESS: - break - self.width = int(min(lo, sys.maxint)), int(min(hi, sys.maxint)) - return self.width - -class Tokenizer: - def __init__(self, string): - self.string = string - self.index = 0 - self.__next() - def __next(self): - if self.index >= len(self.string): - self.next = None - return - char = self.string[self.index] - if char[0] == "\\": - try: - c = self.string[self.index + 1] - except IndexError: - raise error, "bogus escape (end of line)" - char = char + c - self.index = self.index + len(char) - self.next = char - def match(self, char, skip=1): - if char == self.next: - if skip: - self.__next() - return 1 - return 0 - def get(self): - this = self.next - self.__next() - return this - def tell(self): - return self.index, self.next - def seek(self, index): - self.index, self.next = index - -def isident(char): - return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_" - -def isdigit(char): - return "0" <= char <= "9" - -def isname(name): - # check that group name is a valid string - if not isident(name[0]): - return False - for char in name: - if not isident(char) and not isdigit(char): - return False - return True - -def _group(escape, groups): - # check if the escape string represents a valid group - try: - gid = atoi(escape[1:]) - if gid and gid < groups: - return gid - except ValueError: - pass - return None # not a valid group - -def _class_escape(source, escape): - # handle escape code inside character class - code = ESCAPES.get(escape) - if code: - return code - code = CATEGORIES.get(escape) - if code: - return code - try: - if escape[1:2] == "x": - # hexadecimal escape (exactly two digits) - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - escape = escape[2:] - if len(escape) != 2: - raise error, "bogus escape: %s" % repr("\\" + escape) - return LITERAL, atoi(escape, 16) & 0xff - elif escape[1:2] in OCTDIGITS: - # octal escape (up to three digits) - while source.next in OCTDIGITS and len(escape) < 5: - escape = escape + source.get() - escape = escape[1:] - return LITERAL, atoi(escape, 8) & 0xff - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _escape(source, escape, state): - # handle escape code in expression - code = CATEGORIES.get(escape) - if code: - return code - code = ESCAPES.get(escape) - if code: - return code - try: - if escape[1:2] == "x": - # hexadecimal escape - while source.next in HEXDIGITS and len(escape) < 4: - escape = escape + source.get() - if len(escape) != 4: - raise ValueError - return LITERAL, atoi(escape[2:], 16) & 0xff - elif escape[1:2] == "0": - # octal escape - while source.next in OCTDIGITS and len(escape) < 4: - escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - elif escape[1:2] in DIGITS: - # octal escape *or* decimal group reference (sigh) - if source.next in DIGITS: - escape = escape + source.get() - if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and - source.next in OCTDIGITS): - # got three octal digits; this is an octal escape - escape = escape + source.get() - return LITERAL, atoi(escape[1:], 8) & 0xff - # got at least one decimal digit; this is a group reference - group = _group(escape, state.groups) - if group: - if not state.checkgroup(group): - raise error, "cannot refer to open group" - return GROUPREF, group - raise ValueError - if len(escape) == 2: - return LITERAL, ord(escape[1]) - except ValueError: - pass - raise error, "bogus escape: %s" % repr(escape) - -def _parse_sub(source, state, nested=1): - # parse an alternation: a|b|c - - items = [] - while 1: - items.append(_parse(source, state)) - if source.match("|"): - continue - if not nested: - break - if not source.next or source.match(")", 0): - break - else: - raise error, "pattern not properly closed" - - if len(items) == 1: - return items[0] - - subpattern = SubPattern(state) - - # check if all items share a common prefix - while 1: - prefix = None - for item in items: - if not item: - break - if prefix is None: - prefix = item[0] - elif item[0] != prefix: - break - else: - # all subitems start with a common "prefix". - # move it out of the branch - for item in items: - del item[0] - subpattern.append(prefix) - continue # check next one - break - - # check if the branch can be replaced by a character set - for item in items: - if len(item) != 1 or item[0][0] != LITERAL: - break - else: - # we can store this as a character set instead of a - # branch (the compiler may optimize this even more) - set = [] - for item in items: - set.append(item[0]) - subpattern.append((IN, set)) - return subpattern - - subpattern.append((BRANCH, (None, items))) - return subpattern - -def _parse(source, state): - # parse a simple pattern - - subpattern = SubPattern(state) - - while 1: - - if source.next in ("|", ")"): - break # end of subpattern - this = source.get() - if this is None: - break # end of pattern - - if state.flags & SRE_FLAG_VERBOSE: - # skip whitespace and comments - if this in WHITESPACE: - continue - if this == "#": - while 1: - this = source.get() - if this in (None, "\n"): - break - continue - - if this and this[0] not in SPECIAL_CHARS: - subpattern.append((LITERAL, ord(this))) - - elif this == "[": - # character set - set = [] -## if source.match(":"): -## pass # handle character classes - if source.match("^"): - set.append((NEGATE, None)) - # check remaining characters - start = set[:] - while 1: - this = source.get() - if this == "]" and set != start: - break - elif this and this[0] == "\\": - code1 = _class_escape(source, this) - elif this: - code1 = LITERAL, ord(this) - else: - raise error, "unexpected end of regular expression" - if source.match("-"): - # potential range - this = source.get() - if this == "]": - if code1[0] is IN: - code1 = code1[1][0] - set.append(code1) - set.append((LITERAL, ord("-"))) - break - elif this: - if this[0] == "\\": - code2 = _class_escape(source, this) - else: - code2 = LITERAL, ord(this) - if code1[0] != LITERAL or code2[0] != LITERAL: - raise error, "bad character range" - lo = code1[1] - hi = code2[1] - if hi < lo: - raise error, "bad character range" - set.append((RANGE, (lo, hi))) - else: - raise error, "unexpected end of regular expression" - else: - if code1[0] is IN: - code1 = code1[1][0] - set.append(code1) - - # XXX: should move set optimization to compiler! - if len(set)==1 and set[0][0] is LITERAL: - subpattern.append(set[0]) # optimization - elif len(set)==2 and set[0][0] is NEGATE and set[1][0] is LITERAL: - subpattern.append((NOT_LITERAL, set[1][1])) # optimization - else: - # XXX: should add charmap optimization here - subpattern.append((IN, set)) - - elif this and this[0] in REPEAT_CHARS: - # repeat previous item - if this == "?": - min, max = 0, 1 - elif this == "*": - min, max = 0, MAXREPEAT - - elif this == "+": - min, max = 1, MAXREPEAT - elif this == "{": - here = source.tell() - min, max = 0, MAXREPEAT - lo = hi = "" - while source.next in DIGITS: - lo = lo + source.get() - if source.match(","): - while source.next in DIGITS: - hi = hi + source.get() - else: - hi = lo - if not source.match("}"): - subpattern.append((LITERAL, ord(this))) - source.seek(here) - continue - if lo: - min = atoi(lo) - if hi: - max = atoi(hi) - if max < min: - raise error, "bad repeat interval" - else: - raise error, "not supported" - # figure out which item to repeat - if subpattern: - item = subpattern[-1:] - else: - item = None - if not item or (len(item) == 1 and item[0][0] == AT): - raise error, "nothing to repeat" - if item[0][0] in (MIN_REPEAT, MAX_REPEAT): - raise error, "multiple repeat" - if source.match("?"): - subpattern[-1] = (MIN_REPEAT, (min, max, item)) - else: - subpattern[-1] = (MAX_REPEAT, (min, max, item)) - - elif this == ".": - subpattern.append((ANY, None)) - - elif this == "(": - group = 1 - name = None - if source.match("?"): - group = 0 - # options - if source.match("P"): - # python extensions - if source.match("<"): - # named group: skip forward to end of name - name = "" - while 1: - char = source.get() - if char is None: - raise error, "unterminated name" - if char == ">": - break - name = name + char - group = 1 - if not isname(name): - raise error, "bad character in group name" - elif source.match("="): - # named backreference - name = "" - while 1: - char = source.get() - if char is None: - raise error, "unterminated name" - if char == ")": - break - name = name + char - if not isname(name): - raise error, "bad character in group name" - gid = state.groupdict.get(name) - if gid is None: - raise error, "unknown group name" - subpattern.append((GROUPREF, gid)) - continue - else: - char = source.get() - if char is None: - raise error, "unexpected end of pattern" - raise error, "unknown specifier: ?P%s" % char - elif source.match(":"): - # non-capturing group - group = 2 - elif source.match("#"): - # comment - while 1: - if source.next is None or source.next == ")": - break - source.get() - if not source.match(")"): - raise error, "unbalanced parenthesis" - continue - elif source.next in ("=", "!", "<"): - # lookahead assertions - char = source.get() - dir = 1 - if char == "<": - if source.next not in ("=", "!"): - raise error, "syntax error" - dir = -1 # lookbehind - char = source.get() - p = _parse_sub(source, state) - if not source.match(")"): - raise error, "unbalanced parenthesis" - if char == "=": - subpattern.append((ASSERT, (dir, p))) - else: - subpattern.append((ASSERT_NOT, (dir, p))) - continue - else: - # flags - if not source.next in FLAGS: - raise error, "unexpected end of pattern" - while source.next in FLAGS: - state.flags = state.flags | FLAGS[source.get()] - if group: - # parse group contents - if group == 2: - # anonymous group - group = None - else: - group = state.opengroup(name) - p = _parse_sub(source, state) - if not source.match(")"): - raise error, "unbalanced parenthesis" - if group is not None: - state.closegroup(group) - subpattern.append((SUBPATTERN, (group, p))) - else: - while 1: - char = source.get() - if char is None: - raise error, "unexpected end of pattern" - if char == ")": - break - raise error, "unknown extension" - - elif this == "^": - subpattern.append((AT, AT_BEGINNING)) - - elif this == "$": - subpattern.append((AT, AT_END)) - - elif this and this[0] == "\\": - code = _escape(source, this, state) - subpattern.append(code) - - else: - raise error, "parser error" - - return subpattern - -def parse(str, flags=0, pattern=None): - # parse 're' pattern into list of (opcode, argument) tuples - - source = Tokenizer(str) - - if pattern is None: - pattern = Pattern() - pattern.flags = flags - pattern.str = str - - p = _parse_sub(source, pattern, 0) - - tail = source.get() - if tail == ")": - raise error, "unbalanced parenthesis" - elif tail: - raise error, "bogus characters at end of regular expression" - - if flags & SRE_FLAG_DEBUG: - p.dump() - - if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE: - # the VERBOSE flag was switched on inside the pattern. to be - # on the safe side, we'll parse the whole thing again... - return parse(str, p.pattern.flags) - - return p - -def parse_template(source, pattern): - # parse 're' replacement string into list of literals and - # group references - s = Tokenizer(source) - p = [] - a = p.append - def literal(literal, p=p): - if p and p[-1][0] is LITERAL: - p[-1] = LITERAL, p[-1][1] + literal - else: - p.append((LITERAL, literal)) - sep = source[:0] - if type(sep) is type(""): - makechar = chr - else: - makechar = unichr - while 1: - this = s.get() - if this is None: - break # end of replacement string - if this and this[0] == "\\": - # group - if this == "\\g": - name = "" - if s.match("<"): - while 1: - char = s.get() - if char is None: - raise error, "unterminated group name" - if char == ">": - break - name = name + char - if not name: - raise error, "bad group name" - try: - index = atoi(name) - except ValueError: - if not isname(name): - raise error, "bad character in group name" - try: - index = pattern.groupindex[name] - except KeyError: - raise IndexError, "unknown group name" - a((MARK, index)) - elif len(this) > 1 and this[1] in DIGITS: - code = None - while 1: - group = _group(this, pattern.groups+1) - if group: - if (s.next not in DIGITS or - not _group(this + s.next, pattern.groups+1)): - code = MARK, group - break - elif s.next in OCTDIGITS: - this = this + s.get() - else: - break - if not code: - this = this[1:] - code = LITERAL, makechar(atoi(this[-6:], 8) & 0xff) - if code[0] is LITERAL: - literal(code[1]) - else: - a(code) - else: - try: - this = makechar(ESCAPES[this][1]) - except KeyError: - pass - literal(this) - else: - literal(this) - # convert template to groups and literals lists - i = 0 - groups = [] - literals = [] - for c, s in p: - if c is MARK: - groups.append((i, s)) - literals.append(None) - else: - literals.append(s) - i = i + 1 - return groups, literals - -def expand_template(template, match): - g = match.group - sep = match.string[:0] - groups, literals = template - literals = literals[:] - try: - for index, group in groups: - literals[index] = s = g(group) - if s is None: - raise IndexError - except IndexError: - raise error, "empty group" - return string.join(literals, sep) From sanxiyn at codespeak.net Fri Feb 4 18:27:09 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Fri, 4 Feb 2005 18:27:09 +0100 (MET) Subject: [pypy-svn] r8878 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050204172709.901D527C3C@code1.codespeak.net> Author: sanxiyn Date: Fri Feb 4 18:27:09 2005 New Revision: 8878 Modified: pypy/dist/pypy/objspace/std/stringobject.py pypy/dist/pypy/objspace/std/stringtype.py pypy/dist/pypy/objspace/std/test/test_stringobject.py Log: Implements optional argument of string.startswith method Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Fri Feb 4 18:27:09 2005 @@ -642,16 +642,16 @@ return W_IntObject(space, found) -#[optional arguments not supported now] -def str_startswith__String_String(space, w_self, w_start): +def str_startswith__String_String_ANY(space, w_self, w_prefix, w_start): u_self = w_self._value - u_start = w_start._value + u_prefix = w_prefix._value + u_start = space.int_w(w_start) found = 0 - if u_start: - startlen = len(u_start) - if startlen <= len(u_self): - found = (u_start == u_self[:startlen]) + if u_prefix: + plen = len(u_prefix) + if u_start + plen <= len(u_self): + found = (u_prefix == u_self[u_start:u_start+plen]) else: found = 1 Modified: pypy/dist/pypy/objspace/std/stringtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringtype.py (original) +++ pypy/dist/pypy/objspace/std/stringtype.py Fri Feb 4 18:27:09 2005 @@ -33,7 +33,7 @@ str_endswith = MultiMethod('endswith', 2) #[optional arguments not supported now] str_expandtabs = MultiMethod('expandtabs', 2, defaults=(8,)) str_splitlines = MultiMethod('splitlines', 2, defaults=(0,)) -str_startswith = MultiMethod('startswith', 2) #[optional arguments not supported now] +str_startswith = MultiMethod('startswith', 3, defaults=(0,)) str_translate = MultiMethod('translate', 3, defaults=('',)) #unicode mimic not supported now str_decode = MultiMethod('decode', 3, defaults=(None, None)) Modified: pypy/dist/pypy/objspace/std/test/test_stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_stringobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_stringobject.py Fri Feb 4 18:27:09 2005 @@ -273,7 +273,11 @@ assert ''.startswith('a') == 0 assert 'x'.startswith('xx') == 0 assert 'y'.startswith('xx') == 0 - + + def test_startswith_more(self): + assert 'ab'.startswith('a', 0) == 1 + assert 'ab'.startswith('a', 1) == 0 + assert 'ab'.startswith('b', 1) == 1 def test_endswith(self): assert 'ab'.endswith('ab') == 1 From tismer at codespeak.net Fri Feb 4 18:35:55 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 4 Feb 2005 18:35:55 +0100 (MET) Subject: [pypy-svn] r8879 - pypy/dist/pypy/translator Message-ID: <20050204173555.93F8C27C40@code1.codespeak.net> Author: tismer Date: Fri Feb 4 18:35:55 2005 New Revision: 8879 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: changed the way the functions get into globals. And burnt myself while doing it. :-) Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Fri Feb 4 18:35:55 2005 @@ -892,6 +892,11 @@ fast_function_header = ('def %s(%s):' % (name, argstr)) + def install_func(f_name, name): + yield '' + yield '%s = %s' % (f_name, name) + yield 'del %s' % (name,) + print >> f, 'def %s(space, __args__):' % (name,) if docstr is not None: print >> f, docstr @@ -920,9 +925,11 @@ print >> f, ' %s__args__.parse(funcname, signature, def_w)' % ( tupassstr(fast_args),) print >> f, ' return %s(%s)' % (fast_name, ', '.join(["space"]+fast_args)) - print >> f, '%s = globals().pop("%s")' % (f_name, name) - print >> f + for line in install_func(f_name, name): + print >> f, line + + print >> f print >> f, fast_function_header if docstr is not None: print >> f, docstr @@ -939,7 +946,8 @@ # print the body for line in body: print >> f, line - print >> f, '%s = globals().pop("%s")' % (fast_name, name) + for line in install_func("fast"+f_name, name): + print >> f, line print >> f # print the PyMethodDef @@ -1067,7 +1075,7 @@ RPY_HEADER = '''#!/bin/env python # -*- coding: LATIN-1 -*- -from pypy.interpreter.argument import Arguments +from pypy.interpreter.error import OperationError ''' RPY_SEP = "#*************************************************************" @@ -1083,7 +1091,7 @@ ''' RPY_INIT_FOOTER = ''' -# entry point: %(entrypointname)s, %(entrypoint)s) +# entry point: %(entrypointname)s, %(entrypoint)s if __name__ == "__main__": from pypy.objspace.std import StdObjSpace from pypy.objspace.std.default import UnwrapError @@ -1256,6 +1264,24 @@ res.append(i) return res +def test_loop(): + res = [] + i = 0 + while 1: + i += 1 + res.append(i) + if i == 42: + break + res.append(-i) + return res + +def test_exc(a=5): + try: + b = 0 + return a / b + except ZeroDivisionError: + return 42 + def test_strutil(): from pypy.objspace.std import strutil return (strutil.string_to_int("42"), @@ -1308,12 +1334,14 @@ test_md5, test_join, test_iter, + test_loop, + test_exc, test_strutil, test_struct, test_exceptions_helper, make_class_instance_helper, all_entries) -entrypoint = entrypoints[-2] +entrypoint = entrypoints[-6] if __name__ == "__main__": import os, sys From arigo at codespeak.net Fri Feb 4 21:17:14 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 4 Feb 2005 21:17:14 +0100 (MET) Subject: [pypy-svn] r8880 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050204201714.EF8A827C47@code1.codespeak.net> Author: arigo Date: Fri Feb 4 21:17:14 2005 New Revision: 8880 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: 'test_operator.py' listed twice! I guess we need to check for duplicate entries as the list grow larger... Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Fri Feb 4 21:17:14 2005 @@ -31,7 +31,6 @@ 'test_bisect.py', 'test_call', 'test_codeop.py', -'test_operator.py', 'test_compile.py', 'test_operator.py', 'test_heapq.py', @@ -42,6 +41,13 @@ # well ) +# sanity check for when the above lists become long +assert len(dict.fromkeys(working_unittests)) == len(working_unittests), ( + "duplicate entry in working_unittests") +assert len(dict.fromkeys(working_outputtests)) == len(working_outputtests), ( + "duplicate entry in working_outputtests") + + def make_module(space, dottedname, filepath): #print "making module", dottedname, "from", filepath w_dottedname = space.wrap(dottedname) From tismer at codespeak.net Fri Feb 4 21:53:16 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 4 Feb 2005 21:53:16 +0100 (MET) Subject: [pypy-svn] r8881 - pypy/dist/pypy/interpreter/test Message-ID: <20050204205316.2860427C47@code1.codespeak.net> Author: tismer Date: Fri Feb 4 21:53:15 2005 New Revision: 8881 Modified: pypy/dist/pypy/interpreter/test/test_py.py Log: patched cmdexec.py for Win32: The problem is that there are very special rules for double quotes. Also had to patch the pypy tests: Single quotes are not recognized under Windows. This is a compromise, anyway. Modified: pypy/dist/pypy/interpreter/test/test_py.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_py.py (original) +++ pypy/dist/pypy/interpreter/test/test_py.py Fri Feb 4 21:53:15 2005 @@ -9,28 +9,28 @@ def test_executable(): """Ensures sys.executable points to the py.py script""" # TODO : watch out for spaces/special chars in pypath - output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.executable' ''' % pypath ) + output = py.process.cmdexec( '''"%s" -c "import sys;print sys.executable" ''' % pypath ) assert output.splitlines()[-1] == pypath def test_prefix(): """Make sure py.py sys.prefix and exec_prefix are the same as C Python's""" - output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.prefix' ''' % pypath ) + output = py.process.cmdexec( '''"%s" -c "import sys;print sys.prefix" ''' % pypath ) assert output.splitlines()[-1] == sys.prefix - output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.exec_prefix' ''' % pypath ) + output = py.process.cmdexec( '''"%s" -c "import sys;print sys.exec_prefix" ''' % pypath ) assert output.splitlines()[-1] == sys.exec_prefix def test_argv_command(): """Some tests on argv""" # test 1 : no arguments - output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.argv' ''' % pypath ) + output = py.process.cmdexec( '''"%s" -c "import sys;print sys.argv" ''' % pypath ) assert output.splitlines()[-1] == str(['-c']) # test 2 : some arguments after - output = py.process.cmdexec( '''"%s" -c 'import sys;print sys.argv' hello''' % pypath ) + output = py.process.cmdexec( '''"%s" -c "import sys;print sys.argv" hello''' % pypath ) assert output.splitlines()[-1] == str(['-c','hello']) # test 3 : additionnal pypy parameters - output = py.process.cmdexec( '''"%s" -O -c 'import sys;print sys.argv' hello''' % pypath ) + output = py.process.cmdexec( '''"%s" -O -c "import sys;print sys.argv" hello''' % pypath ) assert output.splitlines()[-1] == str(['-c','hello']) SCRIPT_1 = """ From pedronis at codespeak.net Fri Feb 4 23:47:38 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 4 Feb 2005 23:47:38 +0100 (MET) Subject: [pypy-svn] r8885 - pypy/dist/pypy/objspace/std Message-ID: <20050204224738.4F58827C48@code1.codespeak.net> Author: pedronis Date: Fri Feb 4 23:47:38 2005 New Revision: 8885 Modified: pypy/dist/pypy/objspace/std/typeobject.py pypy/dist/pypy/objspace/std/typetype.py Log: improved the logic to decide whether we need a __dict__ descr, starting point for adding slots support Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Fri Feb 4 23:47:38 2005 @@ -16,12 +16,13 @@ w_self.dict_w = dict_w w_self.ensure_static__new__() - w_self.mro_w = compute_C3_mro(space, w_self) if overridetypedef is not None: w_self.instancetypedef = overridetypedef + w_self.hasdict = overridetypedef.hasdict else: # find the most specific typedef instancetypedef = object_typedef + w_self.hasdict = False for w_base in bases_w: if not space.is_true(space.isinstance(w_base, space.w_type)): continue @@ -31,12 +32,11 @@ raise OperationError(space.w_TypeError, space.wrap("instance layout conflicts in " "multiple inheritance")) + w_self.hasdict = w_self.hasdict or w_base.hasdict w_self.instancetypedef = instancetypedef - # XXX - this w_self.lookup('__dict__') is why we precalculate a C3 mro - # even for instances that may override the mro. This probably is not - # a good thing to do. - if forcedict and not w_self.lookup('__dict__'): + if forcedict and not w_self.hasdict: w_self.dict_w['__dict__'] = space.wrap(std_dict_descr) + w_self.hasdict = True if overridetypedef is None: w_type = space.type(w_self) if not space.is_true(space.is_(w_type, space.w_type)): @@ -44,7 +44,11 @@ mro_func_args = Arguments(space, [w_self]) w_mro = space.call_args(mro_func, mro_func_args) w_self.mro_w = space.unpackiterable(w_mro) + return + w_self.mro_w = w_self.compute_mro() + def compute_mro(w_self): + return compute_C3_mro(w_self.space, w_self) def ensure_static__new__(w_self): # special-case __new__, as in CPython: Modified: pypy/dist/pypy/objspace/std/typetype.py ============================================================================== --- pypy/dist/pypy/objspace/std/typetype.py (original) +++ pypy/dist/pypy/objspace/std/typetype.py Fri Feb 4 23:47:38 2005 @@ -47,7 +47,7 @@ return space.newtuple(w_type.mro_w) def descr_mro(space, w_type): - return space.newlist(w_type.mro_w) + return space.newlist(w_type.compute_mro()) def descr__bases(space, w_type): return space.newtuple(w_type.bases_w) From pedronis at codespeak.net Sat Feb 5 00:14:27 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 5 Feb 2005 00:14:27 +0100 (MET) Subject: [pypy-svn] r8888 - pypy/dist/pypy/objspace/std Message-ID: <20050204231427.A248A27C48@code1.codespeak.net> Author: pedronis Date: Sat Feb 5 00:14:27 2005 New Revision: 8888 Modified: pypy/dist/pypy/objspace/std/stdtypedef.py pypy/dist/pypy/objspace/std/typeobject.py Log: streamline hasdict and type creation logic more Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Sat Feb 5 00:14:27 2005 @@ -101,7 +101,7 @@ dict_w[descrname] = w(descrvalue) return W_TypeObject(space, typedef.name, bases_w, dict_w, - overridetypedef=typedef, forcedict=False) + overridetypedef=typedef) def hack_out_multimethods(ns): "NOT_RPYTHON: initialization-time only." Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Sat Feb 5 00:14:27 2005 @@ -9,7 +9,7 @@ from pypy.objspace.std.typetype import type_typedef as typedef def __init__(w_self, space, name, bases_w, dict_w, - overridetypedef=None, forcedict=True): + overridetypedef=None): W_Object.__init__(w_self, space) w_self.name = name w_self.bases_w = bases_w @@ -34,10 +34,9 @@ "multiple inheritance")) w_self.hasdict = w_self.hasdict or w_base.hasdict w_self.instancetypedef = instancetypedef - if forcedict and not w_self.hasdict: - w_self.dict_w['__dict__'] = space.wrap(std_dict_descr) - w_self.hasdict = True - if overridetypedef is None: + if not w_self.hasdict: + w_self.dict_w['__dict__'] = space.wrap(std_dict_descr) + w_self.hasdict = True w_type = space.type(w_self) if not space.is_true(space.is_(w_type, space.w_type)): mro_func = w_type.lookup('mro') @@ -45,6 +44,7 @@ w_mro = space.call_args(mro_func, mro_func_args) w_self.mro_w = space.unpackiterable(w_mro) return + w_self.mro_w = w_self.compute_mro() def compute_mro(w_self): From arigo at codespeak.net Sat Feb 5 01:40:36 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 01:40:36 +0100 (MET) Subject: [pypy-svn] r8891 - pypy/dist/pypy/interpreter Message-ID: <20050205004036.8618127C2C@code1.codespeak.net> Author: arigo Date: Sat Feb 5 01:40:36 2005 New Revision: 8891 Modified: pypy/dist/pypy/interpreter/typedef.py Log: -- for slots. Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Sat Feb 5 01:40:36 2005 @@ -131,6 +131,34 @@ return GetSetProperty(fget) +class Member(Wrappable): + """For slots.""" + def __init__(self, index, name): # XXX ,cls later + self.index = index + self.name = name + + def descr_member_get(space, w_member, w_obj, w_cls=None): + if space.is_w(w_obj, space.w_None): + return w_member + else: + w_result = w_obj.slots_w[self.index] + if w_result is None: + raise OperationError(space.w_AttributeError, + space.wrap(self.name)) # XXX better message + return w_result + + def descr_member_set(space, w_member, w_obj, w_value): + w_obj.slots_w[self.index] = w_value + + def descr_member_del(space, w_member, w_obj): + w_obj.slots_w[self.index] = None + + typedef = TypeDef("member", + __get__ = interp2app(descr_member_get), + __set__ = interp2app(descr_member_set), + __delete__ = interp2app(descr_member_del), + ) + # ____________________________________________________________ # # Definition of the type's descriptors for all the internal types From arigo at codespeak.net Sat Feb 5 01:50:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 01:50:47 +0100 (MET) Subject: [pypy-svn] r8892 - pypy/dist/pypy/interpreter Message-ID: <20050205005047.7E47127C2C@code1.codespeak.net> Author: arigo Date: Sat Feb 5 01:50:47 2005 New Revision: 8892 Modified: pypy/dist/pypy/interpreter/typedef.py Log: Sending this code to Pedronis who sits besides me... Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Sat Feb 5 01:50:47 2005 @@ -141,6 +141,7 @@ if space.is_w(w_obj, space.w_None): return w_member else: + self = space.interpclass_w(w_member) w_result = w_obj.slots_w[self.index] if w_result is None: raise OperationError(space.w_AttributeError, @@ -148,9 +149,11 @@ return w_result def descr_member_set(space, w_member, w_obj, w_value): + self = space.interpclass_w(w_member) w_obj.slots_w[self.index] = w_value def descr_member_del(space, w_member, w_obj): + self = space.interpclass_w(w_member) w_obj.slots_w[self.index] = None typedef = TypeDef("member", From pedronis at codespeak.net Sat Feb 5 02:00:01 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 5 Feb 2005 02:00:01 +0100 (MET) Subject: [pypy-svn] r8893 - in pypy/dist/pypy: interpreter objspace/std Message-ID: <20050205010001.6241627C17@code1.codespeak.net> Author: pedronis Date: Sat Feb 5 02:00:01 2005 New Revision: 8893 Modified: pypy/dist/pypy/interpreter/typedef.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/objspace/std/stdtypedef.py pypy/dist/pypy/objspace/std/typeobject.py Log: slots! Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Sat Feb 5 02:00:01 2005 @@ -18,15 +18,25 @@ unique_interplevel_subclass_cache = Cache() -def get_unique_interplevel_subclass(cls): - return unique_interplevel_subclass_cache.getorbuild(cls, _buildusercls, None) +def get_unique_interplevel_subclass(cls, hasdict, wants_slots): + return unique_interplevel_subclass_cache.getorbuild((cls, hasdict, wants_slots), _buildusercls, None) -def _buildusercls(cls, ignored): +def _buildusercls((cls, hasdict, wants_slots), ignored): "NOT_RPYTHON: initialization-time only" typedef = cls.typedef - name = 'User' + cls.__name__ + name = ['User'] + if not hasdict: + name.append('NoDict') + if wants_slots: + name.append('WithSlots') + name.append(cls.__name__) + + name = ''.join(name) + body = {} + no_extra_dict = typedef.hasdict or not hasdict + class User_InsertNameHere(object): def getclass(self, space): @@ -39,10 +49,18 @@ def __del__(self): self.space.userdel(self) - if typedef.hasdict: - def user_setup(self, space, w_subtype): + if wants_slots: + def user_setup_slots(self, nslots): + self.slots_w = [None] * nslots + else: + def user_setup_slots(self, nslots): + assert nslots == 0 + + if no_extra_dict: + def user_setup(self, space, w_subtype, nslots): self.space = space self.w__class__ = w_subtype + self.user_setup_slots(nslots) else: def getdict(self): @@ -55,10 +73,11 @@ space.wrap("setting dictionary to a non-dict")) self.w__dict__ = w_dict - def user_setup(self, space, w_subtype): + def user_setup(self, space, w_subtype, nslots): self.space = space self.w__class__ = w_subtype self.w__dict__ = space.newdict([]) + self.user_setup_slots(nslots) body = dict([(key, value) for key, value in User_InsertNameHere.__dict__.items() Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Sat Feb 5 02:00:01 2005 @@ -354,9 +354,9 @@ return instantiate(cls) else: w_type.check_user_subclass(w_subtype) - subcls = get_unique_interplevel_subclass(cls) + subcls = get_unique_interplevel_subclass(cls, w_subtype.hasdict, w_subtype.nslots != 0) instance = instantiate(subcls) - instance.user_setup(self, w_subtype) + instance.user_setup(self, w_subtype, w_subtype.nslots) return instance def unpacktuple(self, w_tuple, expected_length=None): Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Sat Feb 5 02:00:01 2005 @@ -1,10 +1,10 @@ from pypy.interpreter import eval, function, gateway from pypy.interpreter.error import OperationError -from pypy.interpreter.typedef import TypeDef, GetSetProperty +from pypy.interpreter.typedef import TypeDef, GetSetProperty, Member from pypy.objspace.std.multimethod import MultiMethod, FailedToImplement __all__ = ['StdTypeDef', 'newmethod', 'gateway', - 'GetSetProperty', 'attrproperty', 'attrproperty_w', + 'GetSetProperty', 'Member', 'attrproperty', 'attrproperty_w', 'MultiMethod'] Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Sat Feb 5 02:00:01 2005 @@ -2,7 +2,7 @@ from pypy.interpreter.function import Function, StaticMethod from pypy.interpreter.argument import Arguments from pypy.interpreter import gateway -from pypy.objspace.std.stdtypedef import std_dict_descr, issubtypedef +from pypy.objspace.std.stdtypedef import std_dict_descr, issubtypedef, Member from pypy.objspace.std.objecttype import object_typedef class W_TypeObject(W_Object): @@ -15,6 +15,7 @@ w_self.bases_w = bases_w w_self.dict_w = dict_w w_self.ensure_static__new__() + w_self.nslots = 0 if overridetypedef is not None: w_self.instancetypedef = overridetypedef @@ -22,7 +23,6 @@ else: # find the most specific typedef instancetypedef = object_typedef - w_self.hasdict = False for w_base in bases_w: if not space.is_true(space.isinstance(w_base, space.w_type)): continue @@ -32,11 +32,59 @@ raise OperationError(space.w_TypeError, space.wrap("instance layout conflicts in " "multiple inheritance")) - w_self.hasdict = w_self.hasdict or w_base.hasdict w_self.instancetypedef = instancetypedef - if not w_self.hasdict: + w_self.hasdict = False + hasoldstylebase = False + w_most_derived_base_with_slots = None + for w_base in bases_w: + if not space.is_true(space.isinstance(w_base, space.w_type)): + hasoldstylebase = True + continue + if w_base.nslots != 0: + if w_base_with_slots is None: + w_base_with_slots = w_base + else: + if space.is_true(space.issubtype(w_base, w_most_derived_base_with_slots)): + w_most_derived_base_with_slots = w_base + elif not space.is_true(space.issubtype(w_most_derived_base_with_slots, w_base)): + raise OperationError(space.w_TypeError, + space.wrap("instance layout conflicts in " + "multiple inheritance")) + w_self.hasdict = w_self.hasdict or w_base.hasdict + if w_most_derived_base_with_slots: + nslots = w_most_derived_base_with_slots.nslots + else: + nslots = 0 + + wantdict = True + if '__slots__' in dict_w: + wantdict = False + + w_slots = dict_w['__slots__'] + if space.is_true(space.isinstance(w_slots, space.w_str)): + slot_names_w = [w_slots] + else: + slot_names_w = space.unpackiterable(w_slots) + for w_slot_name in slot_names_w: + slot_name = space.str_w(w_slot_name) + if slot_name == '__dict__': + if wantdict or w_self.hasdict: + raise OperationError(space.w_TypeError, + space.wrap("__dict__ slot disallowed: we already got one")) + wantdict = True + else: + # create member + w_self.dict_w[slot_name] = space.wrap(Member(nslots, slot_name)) + nslots += 1 + + w_self.nslots = nslots + + wantdict = wantdict or hasoldstylebase + + if wantdict and not w_self.hasdict: w_self.dict_w['__dict__'] = space.wrap(std_dict_descr) - w_self.hasdict = True + w_self.hasdict = True + w_type = space.type(w_self) if not space.is_true(space.is_(w_type, space.w_type)): mro_func = w_type.lookup('mro') From arigo at codespeak.net Sat Feb 5 15:29:43 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 15:29:43 +0100 (MET) Subject: [pypy-svn] r8900 - pypy/dist/pypy/translator Message-ID: <20050205142943.6F26927C1E@code1.codespeak.net> Author: arigo Date: Sat Feb 5 15:29:43 2005 New Revision: 8900 Modified: pypy/dist/pypy/translator/genc.py Log: Needed for unwrap__Slice(). Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Sat Feb 5 15:29:43 2005 @@ -353,6 +353,7 @@ file: '&PyFile_Type', type(None): 'Py_None->ob_type', CodeType: '&PyCode_Type', + slice: '&PySlice_Type', r_int: '&PyInt_Type', r_uint: '&PyInt_Type', From arigo at codespeak.net Sat Feb 5 15:29:51 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 15:29:51 +0100 (MET) Subject: [pypy-svn] r8901 - pypy/dist/pypy/objspace/std Message-ID: <20050205142951.E839E27C1E@code1.codespeak.net> Author: arigo Date: Sat Feb 5 15:29:51 2005 New Revision: 8901 Modified: pypy/dist/pypy/objspace/std/typeobject.py Log: Typos. Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Sat Feb 5 15:29:51 2005 @@ -41,8 +41,8 @@ hasoldstylebase = True continue if w_base.nslots != 0: - if w_base_with_slots is None: - w_base_with_slots = w_base + if w_most_derived_base_with_slots is None: + w_most_derived_base_with_slots = w_base else: if space.is_true(space.issubtype(w_base, w_most_derived_base_with_slots)): w_most_derived_base_with_slots = w_base From arigo at codespeak.net Sat Feb 5 15:34:10 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 15:34:10 +0100 (MET) Subject: [pypy-svn] r8902 - pypy/dist/pypy/interpreter Message-ID: <20050205143410.4C82827C1E@code1.codespeak.net> Author: arigo Date: Sat Feb 5 15:34:10 2005 New Revision: 8902 Modified: pypy/dist/pypy/interpreter/pycode.py Log: Use range() in preference to xrange(), to please genc.py. Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Sat Feb 5 15:34:10 2005 @@ -173,14 +173,14 @@ if not areEqual: return space.w_False - for i in xrange(len(self.co_consts_w)): + for i in range(len(self.co_consts_w)): if not space.eq_w(self.co_consts_w[i], other.co_consts_w[i]): return space.w_False if len(self.co_names_w) != len(other.co_names_w): return space.w_False - for i in xrange(len(self.co_names_w)): + for i in range(len(self.co_names_w)): if not space.eq_w(self.co_names_w[i], other.co_names_w[i]): return space.w_False if (self.co_varnames == other.co_varnames and From arigo at codespeak.net Sat Feb 5 15:37:36 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 15:37:36 +0100 (MET) Subject: [pypy-svn] r8903 - pypy/dist/pypy/objspace/std Message-ID: <20050205143736.275D727C1E@code1.codespeak.net> Author: arigo Date: Sat Feb 5 15:37:35 2005 New Revision: 8903 Modified: pypy/dist/pypy/objspace/std/listobject.py Log: Re-enabled the various version of setitem__List_Slice_Xxx(). Fixed a typo in the (now-commented-out) code. Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Sat Feb 5 15:37:35 2005 @@ -220,24 +220,21 @@ items[idx] = w_any return space.w_None -# XXX the following is disabled, so that 'setitem' can be a binary multimethod. -##def setitem__List_Slice_List(space, w_list, w_slice, w_list2): -## return _setitem_slice_helper(space, w_list, w_slice, w_list2.ob_item, w_list2.ob_size) - -##def setitem__List_Slice_Tuple(space, w_list, w_slice, w_tuple): -## t = w_tuple.wrappeditems -## return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) +def setitem__List_Slice_List(space, w_list, w_slice, w_list2): + return _setitem_slice_helper(space, w_list, w_slice, w_list2.ob_item, w_list2.ob_size) + +def setitem__List_Slice_Tuple(space, w_list, w_slice, w_tuple): + t = w_tuple.wrappeditems + return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) def setitem__List_Slice_ANY(space, w_list, w_slice, w_iterable): - # for performance, check for common cases of w_iterable - # (this used to be done by the disabled cases of 'setitem' above) - if isinstance(w_iterable, W_ListObject): - return _setitem_slice_helper(space, w_list, w_slice, - w_iterable.ob_item, w_iterable.ob_size) - if isinstance(w_iterable, W_TupleObject): - t = w_tuple.wrappeditems - else: - t = space.unpackiterable(w_iterable) +## if isinstance(w_iterable, W_ListObject): +## return _setitem_slice_helper(space, w_list, w_slice, +## w_iterable.ob_item, w_iterable.ob_size) +## if isinstance(w_iterable, W_TupleObject): +## t = w_iterable.wrappeditems +## else: + t = space.unpackiterable(w_iterable) return _setitem_slice_helper(space, w_list, w_slice, t, len(t)) def _setitem_slice_helper(space, w_list, w_slice, sequence2, len2): From arigo at codespeak.net Sat Feb 5 17:59:35 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 5 Feb 2005 17:59:35 +0100 (MET) Subject: [pypy-svn] r8904 - pypy/dist/pypy Message-ID: <20050205165935.2A8FA27C1E@code1.codespeak.net> Author: arigo Date: Sat Feb 5 17:59:35 2005 New Revision: 8904 Modified: pypy/dist/pypy/conftest.py Log: Remove unneeded import. Modified: pypy/dist/pypy/conftest.py ============================================================================== --- pypy/dist/pypy/conftest.py (original) +++ pypy/dist/pypy/conftest.py Sat Feb 5 17:59:35 2005 @@ -1,7 +1,6 @@ import py from pypy.interpreter.gateway import app2interp_temp from pypy.interpreter.error import OperationError -from pypy.objspace.std import StdObjSpace from pypy.tool import pytestsupport # From cfbolz at codespeak.net Sun Feb 6 17:45:52 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Sun, 6 Feb 2005 17:45:52 +0100 (MET) Subject: [pypy-svn] r8927 - in pypy/dist/pypy/translator/llvm: . test Message-ID: <20050206164552.3A81627BF4@code1.codespeak.net> Author: cfbolz Date: Sun Feb 6 17:45:51 2005 New Revision: 8927 Added: pypy/dist/pypy/translator/llvm/ (props changed) pypy/dist/pypy/translator/llvm/__init__.py (contents, props changed) pypy/dist/pypy/translator/llvm/autopath.py (contents, props changed) pypy/dist/pypy/translator/llvm/build_llvm_module.py (contents, props changed) pypy/dist/pypy/translator/llvm/genllvm.py (contents, props changed) pypy/dist/pypy/translator/llvm/list_template.ll pypy/dist/pypy/translator/llvm/llvm_gc.txt (contents, props changed) pypy/dist/pypy/translator/llvm/llvmbc.py (contents, props changed) pypy/dist/pypy/translator/llvm/operations.ll pypy/dist/pypy/translator/llvm/string.ll pypy/dist/pypy/translator/llvm/test/ (props changed) pypy/dist/pypy/translator/llvm/test.html pypy/dist/pypy/translator/llvm/test/__init__.py (contents, props changed) pypy/dist/pypy/translator/llvm/test/autopath.py (contents, props changed) pypy/dist/pypy/translator/llvm/test/llvmsnippet.py (contents, props changed) pypy/dist/pypy/translator/llvm/test/test_genllvm.py (contents, props changed) Log: initial chekin of the llvm backend Added: pypy/dist/pypy/translator/llvm/__init__.py ============================================================================== Added: pypy/dist/pypy/translator/llvm/autopath.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/autopath.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,114 @@ +""" +self cloning, automatic path configuration + +copy this into any subdirectory of pypy from which scripts need +to be run, typically all of the test subdirs. +The idea is that any such script simply issues + + import autopath + +and this will make sure that the parent directory containing "pypy" +is in sys.path. + +If you modify the master "autopath.py" version (in pypy/tool/autopath.py) +you can directly run it which will copy itself on all autopath.py files +it finds under the pypy root directory. + +This module always provides these attributes: + + pypydir pypy root directory path + this_dir directory where this autopath.py resides + +""" + + +def __dirinfo(part): + """ return (partdir, this_dir) and insert parent of partdir + into sys.path. If the parent directories don't have the part + an EnvironmentError is raised.""" + + import sys, os + try: + head = this_dir = os.path.realpath(os.path.dirname(__file__)) + except NameError: + head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) + + while head: + partdir = head + head, tail = os.path.split(head) + if tail == part: + break + else: + raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) + + checkpaths = sys.path[:] + pypy_root = os.path.join(head, '') + + while checkpaths: + orig = checkpaths.pop() + if os.path.join(os.path.realpath(orig), '').startswith(pypy_root): + sys.path.remove(orig) + sys.path.insert(0, head) + + munged = {} + for name, mod in sys.modules.items(): + fn = getattr(mod, '__file__', None) + if '.' in name or not isinstance(fn, str): + continue + newname = os.path.splitext(os.path.basename(fn))[0] + if not newname.startswith(part + '.'): + continue + path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') + if path.startswith(pypy_root) and newname != part: + modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) + if newname != '__init__': + modpaths.append(newname) + modpath = '.'.join(modpaths) + if modpath not in sys.modules: + munged[modpath] = mod + + for name, mod in munged.iteritems(): + if name not in sys.modules: + sys.modules[name] = mod + if '.' in name: + prename = name[:name.rfind('.')] + postname = name[len(prename)+1:] + if prename not in sys.modules: + __import__(prename) + if not hasattr(sys.modules[prename], postname): + setattr(sys.modules[prename], postname, mod) + + return partdir, this_dir + +def __clone(): + """ clone master version of autopath.py into all subdirs """ + from os.path import join, walk + if not this_dir.endswith(join('pypy','tool')): + raise EnvironmentError("can only clone master version " + "'%s'" % join(pypydir, 'tool',_myname)) + + + def sync_walker(arg, dirname, fnames): + if _myname in fnames: + fn = join(dirname, _myname) + f = open(fn, 'rwb+') + try: + if f.read() == arg: + print "checkok", fn + else: + print "syncing", fn + f = open(fn, 'w') + f.write(arg) + finally: + f.close() + s = open(join(pypydir, 'tool', _myname), 'rb').read() + walk(pypydir, sync_walker, s) + +_myname = 'autopath.py' + +# set guaranteed attributes + +pypydir, this_dir = __dirinfo('pypy') + +if __name__ == '__main__': + __clone() Added: pypy/dist/pypy/translator/llvm/build_llvm_module.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/build_llvm_module.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,73 @@ +""" +Build a pyrex module out of llvmfile +""" + +import autopath + +import os, sys, inspect, re, exceptions + +from py.process import cmdexec +from py import path + +from pypy.tool.udir import udir +from pypy.translator.genpyrex import GenPyrex +from pypy.translator.tool.buildpyxmodule import make_c_from_pyxfile +from pypy.translator.tool import stdoutcapture + +debug = 0 + +class CompileError(exceptions.Exception): + pass + +def system_trace(cmd): + print cmd + return old_system(cmd) + +old_system = os.system +os.system = system_trace + +def make_module_from_llvm(llvmfile, pyxfile): + include_dir = autopath.this_dir + dirpath = llvmfile.dirpath() + lastdir = path.local() + os.chdir(str(dirpath)) + modname = pyxfile.purebasename + ops1 = ["llvm-as %s -f" % llvmfile, + "llvmc -O3 %s.bc -o _%s.o" % (llvmfile.purebasename, modname), + "llc _%s.o.bc -f -o _%s.s" % (modname, modname), + "as _%s.s -o _%s.o" % (modname, modname)] + ops2 = ["gcc -c -fPIC -I/usr/include/python %s.c" % pyxfile.purebasename, + "gcc -shared %s.o _%s.o -o %s.so" % (pyxfile.purebasename, + modname, modname)] + try: + if debug: print "modname", modname + c = stdoutcapture.Capture(mixed_out_err = True) + if debug: print "working in", path.local() + try: + try: + for op in ops1: + cmdexec(op) + make_c_from_pyxfile(pyxfile) + for op in ops2: + cmdexec(op) + finally: + foutput, foutput = c.done() + except: + data = foutput.read() + fdump = open("%s.errors" % modname, "w") + fdump.write(data) + fdump.close() + print data + raise + # XXX do we need to do some check on fout/ferr? + # XXX not a nice way to import a module + if debug: print "inserting path to sys.path", dirpath + sys.path.insert(0, '.') + if debug: print "import %(modname)s as testmodule" % locals() + exec "import %(modname)s as testmodule" % locals() + sys.path.pop(0) + finally: + os.chdir(str(lastdir)) + #if not debug: + #dirpath.rmtree() + return testmodule Added: pypy/dist/pypy/translator/llvm/genllvm.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/genllvm.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,523 @@ +""" +Generate a llvm .ll file from an annotated flowgraph. +""" + +import autopath +import os, sys, exceptions, sets, StringIO + +from pypy.objspace.flow.model import Variable, Constant, SpaceOperation +from pypy.objspace.flow.model import FunctionGraph, Block, Link +from pypy.objspace.flow.model import last_exception, last_exc_value +from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph +from pypy.annotation import model as annmodel +from pypy.translator import transform +from pypy.translator.translator import Translator +from pypy.translator.llvm import llvmbc +from pypy.translator.llvm import build_llvm_module +from pypy.translator.test import snippet as test + + +INTRINSIC_OPS = ["lt", "le", "eq", "ne", "gt", "ge", "is", "is_true", "len", + "neg", "pos", "invert", "add", "sub", "mul", "truediv", + "floordiv", "div", "mod", "pow", "lshift", "rshift", "and", + "or", "xor", "inplace_add", "inplace_sub", "inplace_mul", + "inplace_truediv", "inplace_floordiv", "inplace_div", + "inplace_mod", "inplace_pow", "inplace_lshift", + "inplace_rshift", "inplace_and", "inplace_or", "inplace_xor", + "getitem", "setitem", "delitem", "contains", "newlist", + "alloc_and_set"] + +C_SIMPLE_TYPES = {annmodel.SomeChar: "char", + annmodel.SomeBool: "unsigned char", + annmodel.SomeInteger: "int"} + +debug = 0 + + +def llvmcompile(transl): + gen = LLVMGenerator(transl) + return gen.compile() + + +class CompileError(exceptions.Exception): + pass + +class LLVMGenerator(object): + def __init__(self, transl): + self.translator = transl + self.annotator = self.translator.annotator + self.global_count = 0 + self.repr_classes = [eval(s) + for s in dir(sys.modules.get(self.__module__)) + if "Repr" in s] + self.llvm_reprs = {} + self.l_entrypoint = self.get_repr(self.translator.functions[0]) + + def compile(self): + from pypy.tool.udir import udir + name = self.l_entrypoint.llvmname()[1:] + llvmfile = udir.join('%s.ll' % name) + f = llvmfile.open('w') + self.write(f) + f.close() + pyxfile = udir.join('%s_wrap.pyx' % name) + f = pyxfile.open('w') + f.write(self.l_entrypoint.get_pyrex_source()) + f.close() + mod = build_llvm_module.make_module_from_llvm(llvmfile, pyxfile) + return getattr(mod, "wrap_%s" % name) + + def get_global_tmp(self, used_by=None): + self.global_count += 1 + return "%%glb.%s.%i" % ((used_by or "unknown"), self.global_count) + + def get_repr(self, obj): + if debug: + print "looking for object", obj, type(obj).__name__, obj.__class__, + if obj in self.llvm_reprs: + if debug: + print "->exists already" + return self.llvm_reprs[obj] + for cl in self.repr_classes: + if debug: + print "trying", cl + g = cl.get(obj, self) + if g is not None: + self.llvm_reprs[obj] = g + return g + raise CompileError, "Can't get repr of %s, %s" % (obj, obj.__class__) + + def write(self, f): + f.write("\n\n; +-------+\n; |globals|\n; +-------+\n\n") + seen_reprs = sets.Set() + for l_repr in traverse_dependencies(self.l_entrypoint, seen_reprs): + s = l_repr.get_globals() + if s != "": + f.write(s + "\n") + f.write("\n\n; +---------+\n; |space_ops|\n; +---------+\n\n") + f1 = file(autopath.this_dir + "/operations.ll", "r") + s = f1.read() + f.write(s) + f1.close() + f.write("\n\n; +---------+\n; |functions|\n; +---------+\n\n") + seen_reprs = sets.Set() + for l_repr in traverse_dependencies(self.l_entrypoint, seen_reprs): + s = l_repr.get_functions() + if s != "": + f.write(s + "\n") + + def __str__(self): + f = StringIO.StringIO() + self.write(f) + return f.getvalue() + +def traverse_dependencies(l_repr, seen_reprs): + seen_reprs.add(l_repr) + for l_dep in l_repr.get_dependencies(): + if l_dep in seen_reprs: + continue + seen_reprs.add(l_dep) + for l_dep1 in traverse_dependencies(l_dep, seen_reprs): + yield l_dep1 + yield l_repr + +class LLVMRepr(object): + def get(obj, gen): + return None + get = staticmethod(get) + + def get_globals(self): + return "" + + def get_functions(self): + return "" + + def llvmname(self): + return "" + + def llvmtype(self): + return self.type.llvmname() + + def typed_name(self): + return self.llvmtype() + " " + self.llvmname() + + def get_dependencies(self): + try: + return self.dependencies + except exceptions.AttributeError: + return [] + +class SimpleRepr(LLVMRepr): + """Representation of values that are directly mapped to types in LLVM: +int, bool, char (string of length 1)""" + + LLVM_SIMPLE_TYPES = {annmodel.SomeInteger: "int", + annmodel.SomeChar: "sbyte", + annmodel.SomeBool: "bool"} + + def get(obj, gen): + if not isinstance(obj, Constant): + return None + type = gen.annotator.binding(obj) + if type.__class__ in SimpleRepr.LLVM_SIMPLE_TYPES: + llvmtype = SimpleRepr.LLVM_SIMPLE_TYPES[type.__class__] + l_repr = SimpleRepr(llvmtype, repr(obj.value), gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, type, llvmname, gen): + if debug: + print "SimpleRepr: %s, %s" % (type, llvmname) + self.type = type + if llvmname in ("False", "True"): + llvmname = llvmname.lower() + self.name = llvmname + self.gen = gen + + def llvmname(self): + return self.name + + def llvmtype(self): + return self.type + + +class VariableRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Variable): + return VariableRepr(obj, gen) + return None + get = staticmethod(get) + + def __init__(self, var, gen): + if debug: + print "VariableRepr: %s" % (var.name) + self.var = var + type = gen.annotator.binding(var) + self.type = gen.get_repr(type) + self.dependencies = [self.type] + + def llvmname(self): + return "%" + self.var.name + + +class StringRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Constant): + type = gen.annotator.binding(obj) + if type.__class__ is annmodel.SomeString: + l_repr = StringRepr(obj, gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, obj, gen): + if debug: + print "StringRepr: %s" % obj.value + self.s = obj.value + self.gen = gen + self.glvar1 = gen.get_global_tmp("StringRepr") + self.glvar2 = gen.get_global_tmp("StringRepr") + self.type = gen.get_repr(gen.annotator.binding(obj)) + self.dependencies = [self.type] + + def llvmname(self): + return self.glvar2 + + def get_globals(self): + d = {"len": len(self.s), "gv1": self.glvar1, "gv2": self.glvar2, + "type": self.type.llvmname_wo_pointer(), "string": self.s} + s = """%(gv1)s = internal constant [%(len)i x sbyte] c"%(string)s" +%(gv2)s = internal constant %(type)s {uint %(len)i,\ +sbyte* getelementptr ([%(len)i x sbyte]* %(gv1)s, uint 0, uint 0)}""" + return s % d + +class TypeRepr(LLVMRepr): + l_stringtype = None + def get(obj, gen): +## print "TypeRepr", obj + if obj.__class__ is annmodel.SomeString or obj is str: + if TypeRepr.l_stringtype is None: + l_repr = TypeRepr("%std.string", + "%std.string = type {uint, sbyte*}", + "string.ll", gen) + TypeRepr.l_stringtype = l_repr + return TypeRepr.l_stringtype + get = staticmethod(get) + + def __init__(self, llvmname, definition, includefile, gen): + if debug: + print "TypeRepr: %s, %s" % (llvmname, definition) + self.name = llvmname + self.definition = definition + self.gen = gen + self.includefile = includefile + + def get_globals(self): + try: + return self.definition + except exceptions.AttributeError: + return "" + + def get_functions(self): + if self.includefile != "": + f = file(autopath.this_dir + "/" + self.includefile, "r") + s = f.read() + f.close() + return s + return "" + + def llvmname(self): + return self.name + "*" + + def llvmname_wo_pointer(self): + return self.name + +class ListTypeRepr(TypeRepr): + l_listtypes = {} + def get(obj, gen): + if obj.__class__ is annmodel.SomeList: + if obj.s_item.__class__ in ListTypeRepr.l_listtypes: + return ListTypeRepr.l_listtypes[obj.s_item.__class__] + l_repr = ListTypeRepr(obj, gen) + ListTypeRepr.l_listtypes[obj.s_item.__class__] = l_repr + return l_repr + return None + get = staticmethod(get) + + def __init__(self, obj, gen): + if debug: + print "ListTypeRepr: %s, %s" % (obj, obj.s_item) + self.gen = gen + self.l_itemtype = gen.get_repr(obj.s_item) + self.dependencies = [self.l_itemtype] + itemtype = self.l_itemtype.llvmname() + self.name = "%%std.list.%s" % itemtype.strip("%") + self.definition = self.name + " = type {uint, %s*}" % itemtype + + def get_functions(self): + f = file(autopath.this_dir + "/list_template.ll", "r") + s = f.read() + f.close() + s = s.replace("%(item)s", self.l_itemtype.llvmname().strip("%")) + #XXX assuming every type consists of 4 bytes + s = s.replace("%(sizeof)i", str(4)) + return s + +class SimpleTypeRepr(TypeRepr): + def get(obj, gen): + if obj.__class__ in [annmodel.SomeInteger, int]: + l_repr = SimpleTypeRepr("int", gen) + return l_repr + elif obj.__class__ in [annmodel.SomeBool, bool]: + l_repr = SimpleTypeRepr("bool", gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, llvmname, gen): + if debug: + print "SimpleTypeRepr: %s" % llvmname + self.name = llvmname + self.gen = gen + self.definition = "" + self.includefile = "" + + def llvmname(self): + return self.name + +class ImpossibleValueRepr(TypeRepr): + def get(obj, gen): + if obj.__class__ is annmodel.SomeImpossibleValue: + return ImpossibleValueRepr() + return None + get = staticmethod(get) + + def __init__(self): + self.definition = "" + self.dependencies = [] + self.includefile = "" + + def llvmname(self): + return "void" + + def typed_name(self): + return self.llvmtype() + " " + self.llvmname() + +class BuiltinFunctionRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Constant) and \ + type(obj.value).__name__ == 'builtin_function_or_method': + l_repr = BuiltinFunctionRepr(obj.value, gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, bi, gen): + self.name = "%std." + bi.__name__ + self.gen = gen + + def llvmname(self): + return self.name + +class FunctionRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Constant) and \ + type(obj.value).__name__ == 'function': + name = obj.value.__name__ + l_repr = FunctionRepr(name, obj.value, gen) + return l_repr + elif type(obj).__name__ == 'function': + name = obj.__name__ + l_repr = FunctionRepr(name, obj, gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, name, function, gen): + if debug: + print "FunctionRepr: %s" % name + self.gen = gen + self.func = function + self.translator = gen.translator + self.translator.simplify() + self.name = "%" + name + self.graph = self.translator.getflowgraph(self.func) + self.annotator = gen.translator.annotator + transform.transform_allocate(self.annotator) + self.blocknum = {} + self.allblocks = [] + self.pyrex_source = "" + self.dependencies = sets.Set() + self.get_bbs() + self.build_bbs() + + def get_bbs(self): + def visit(node): + if isinstance(node, Block) and node not in self.blocknum: + self.allblocks.append(node) + self.blocknum[node] = len(self.blocknum) + traverse(visit, self.graph) + self.same_origin_block = [False] * len(self.allblocks) + + def build_bbs(self): + a = self.annotator + for number, pyblock in enumerate(self.allblocks): + lblock = llvmbc.BasicBlock("block%i" % number) + pyblock = self.allblocks[number] + if number == 0: + self.llvm_func = llvmbc.Function(self.llvmfuncdef(), lblock) + else: + self.llvm_func.basic_block(lblock) + #Create Phi nodes (but not for the first node) + incoming_links = [] + def visit(node): + if isinstance(node, Link) and node.target == pyblock: + incoming_links.append(node) + traverse(visit, self.graph) + #special case if the incoming links are from the same block + if len(incoming_links) == 2 and \ + incoming_links[0].prevblock == incoming_links[1].prevblock: + for i, arg in enumerate(pyblock.inputargs): + l_select = self.gen.get_repr( + incoming_links[0].prevblock.exitswitch) + l_arg = self.gen.get_repr(arg) + l_v1 = self.gen.get_repr(incoming_links[1].args[i]) + l_v2 = self.gen.get_repr(incoming_links[0].args[i]) + self.dependencies.update([l_arg, l_switch, l_v1, l_v2]) + lblock.select(l_arg, l_select, l_v1, l_v2) + elif len(incoming_links) != 0: + for i, arg in enumerate(pyblock.inputargs): + l_arg = self.gen.get_repr(arg) + l_values = [self.gen.get_repr(l.args[i]) + for l in incoming_links] + self.dependencies.add(l_arg) + self.dependencies.update(l_values) + lblock.phi(l_arg, l_values, + ["%%block%i" % self.blocknum[l.prevblock] + for l in incoming_links]) + #Create a function call for every operation in the block + for op in pyblock.operations: + if op.opname == "simple_call" and \ + isinstance(op.args[0], Constant) and \ + op.args[0].value == self.func: + l_args = [self] + \ + [self.gen.get_repr(arg) for arg in op.args[1:]] + else: + l_args = [self.gen.get_repr(arg) for arg in op.args] + l_target = self.gen.get_repr(op.result) + self.dependencies.update(l_args) + self.dependencies.add(l_target) + if op.opname in INTRINSIC_OPS: + lblock.spaceop(l_target, op.opname, l_args) + elif op.opname == "simple_call": + lblock.call(l_target, l_args[0], l_args[1:]) + else: + self.translator.view() + raise CompileError, "Unhandeled SpaceOp %s" % op.opname + #Create branches + if pyblock.exitswitch is None: + if pyblock.exits == (): + l_returnvalue = self.gen.get_repr(pyblock.inputargs[0]) + self.dependencies.add(l_returnvalue) + lblock.ret(l_returnvalue) + else: + lblock.uncond_branch( + "%%block%i" % self.blocknum[pyblock.exits[0].target]) + else: + assert isinstance(a.binding(pyblock.exitswitch), + annmodel.SomeBool) + l_switch = self.gen.get_repr(pyblock.exitswitch) + self.dependencies.add(l_switch) + lblock.cond_branch( + l_switch, + "%%block%i" % self.blocknum[pyblock.exits[1].target], + "%%block%i" % self.blocknum[pyblock.exits[0].target]) + + def cfuncdef(self): + a = self.translator.annotator + retv = self.graph.returnblock.inputargs[0] + rettype_c = C_SIMPLE_TYPES[a.binding(retv).__class__] + args = self.graph.startblock.inputargs + argtypes_c = [C_SIMPLE_TYPES[a.binding(v).__class__] for v in args] + fd = "%s %s(%s)" % (rettype_c, self.func.func_name, + ", ".join(argtypes_c)) + return fd + + def llvmfuncdef(self): + a = self.translator.annotator + l_retv = self.gen.get_repr(self.graph.returnblock.inputargs[0]) + l_args = [self.gen.get_repr(ar) + for ar in self.graph.startblock.inputargs] + self.dependencies.update(l_args) + self.dependencies.add(l_retv) + s = "%s %s(" % (l_retv.llvmtype(), self.name) + return s + ", ".join([a.typed_name() for a in l_args]) + ")" + return llvmbc.function(l_retv, self.name, l_args) + + def get_pyrex_source(self): + name = self.func.func_name + args = self.graph.startblock.inputargs + self.pyrex_source = ["cdef extern %s\n" % + (self.cfuncdef())] + self.pyrex_source += ["def wrap_%s(" % name] + t = [] + for i, a in enumerate(args): + t += ["%s" % a] + t = ", ".join(t) + self.pyrex_source += t + "):\n\treturn %s(%s)\n\n" % (name, t) + self.pyrex_source += "\ndef test(a):\n\treturn a + 1\n\n" + self.pyrex_source = "".join(self.pyrex_source) + return self.pyrex_source + + + def get_functions(self): + return str(self.llvm_func) + + def llvmname(self): + return self.name + + def llvmtype(self): + assert self.llvmfuncdef().count(self.name) == 1 + return self.llvmfuncdef().replace(self.name + "(", "(") + Added: pypy/dist/pypy/translator/llvm/list_template.ll ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/list_template.ll Sun Feb 6 17:45:51 2005 @@ -0,0 +1,57 @@ +;Template for lists + +internal uint %std.len(%std.list.%(item)s* %a) { + %p = getelementptr %std.list.%(item)s* %a, int 0, uint 0 + %length1 = load uint* %p + ret uint %length1 +} + +internal int %std.len(%std.list.%(item)s* %a) { + %length1 = call uint %std.len(%std.list.%(item)s* %a) + %length = cast uint %length1 to int + ret int %length +} + + +internal %std.list.%(item)s* %std.make(uint %len, %(item)s* %s) { + %ret = malloc %std.list.%(item)s, uint 1 + %lenp = getelementptr %std.list.%(item)s* %ret, int 0, uint 0 + %lsp = getelementptr %std.list.%(item)s* %ret, int 0, uint 1 + store uint %len, uint* %lenp + store %(item)s* %s, %(item)s** %lsp + ret %std.list.%(item)s* %ret +} + + +internal %std.list.%(item)s* %std.newlist(%(item)s %init) { + %nmem = malloc %(item)s, uint 1 + %ret = call %std.list.%(item)s* %std.make(uint 1, %(item)s* %nmem) + call void %std.setitem(%std.list.%(item)s* %ret, int 0, %(item)s %init) + ret %std.list.%(item)s* %ret +} + +internal %(item)s %std.getitem(%std.list.%(item)s* %s, int %p) { + %sp1 = getelementptr %std.list.%(item)s* %s, int 0, uint 1 + %s1 = load %(item)s** %sp1 + %len = call uint %std.len(%std.list.%(item)s* %s) + %ilen = cast uint %len to int + %negpos = add int %ilen, %p + %is_negative = setlt int %p, 0 + %usedpos = select bool %is_negative, int %negpos, int %p + %p_item = getelementptr %(item)s* %s1, int %usedpos + %value = load %(item)s* %p_item + ret %(item)s %value +} + +internal void %std.setitem(%std.list.%(item)s* %s, int %p, %(item)s %n) { + %sp1 = getelementptr %std.list.%(item)s* %s, int 0, uint 1 + %s1 = load %(item)s** %sp1 + %len = call uint %std.len(%std.list.%(item)s* %s) + %ilen = cast uint %len to int + %negpos = add int %ilen, %p + %is_negative = setlt int %p, 0 + %usedpos = select bool %is_negative, int %negpos, int %p + %itemp = getelementptr %(item)s* %s1, int %usedpos + store %(item)s %n, %(item)s* %itemp + ret void +} Added: pypy/dist/pypy/translator/llvm/llvm_gc.txt ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/llvm_gc.txt Sun Feb 6 17:45:51 2005 @@ -0,0 +1,206 @@ +From sabre at nondot.org Fri Oct 29 02:19:53 2004 +From: sabre at nondot.org (Chris Lattner) +Date: Fri Oct 29 02:01:46 2004 +Subject: [LLVMdev] Getting started with GC +In-Reply-To: <20041028223528.GA31467 at kwai.cs.uiuc.edu> +Message-ID: + +On Thu, 28 Oct 2004, Tom Brown wrote: + +> We have a few questions about the current state of GC. + +Ok. :) + +> We decided to start (and finish?) our work by finishing SemiSpace. + +Sounds good. + +> process_pointer is meant to move objects from CurSpace to OtherSpace. +> How can it find pointers to a moved object? + +This is entirely up to you, as you're basically implementing the semispace +collector in its entirety. See below. + +> How does it know the size of each object? + +I'm a big fan of starting simple. As such, I'd suggest using this scheme: + +When an object is allocated: add a size word on front of it. This size of +every object should be rounded up to a multiple of 4. When it is being +GC'd, replace the size with the forwarding pointer, but with the low bit +set. Because the low bit is set, you should be able to tell if an object +is forwarded or not. This allows you to do the simple, standard, in-place +depth-first traversal of the heap when you are GC'ing from one space to +the other. + +> Assuming we are writing a GC that will only work from llvm assembly our +> best option seems to be forcing the assembly code to follow a convention +> that identifies pointers. + +There are three issues: + +1. Object references from the stack +2. Object references from globals +3. Object references from the heap + +#1 is the hardest from the code generation standpoint, and it is what LLVM +provides direct support for. #2 is really a matter of convention, and +having the GC export and interface that can be used by langugage front-end +in question to register global pointers. #3 requires object descriptors +of some sort, produces by the front-end and consumed by the GC. See +below. + +> The SemiSpace code could keep a map from each allocated pointer to its +> size, similar to how I think malloc works. + +For this, I would suggest just putting a header word on the object, +containing the size. This is not optimal, but will be a good place to +start. Later this can be improved. + +> http://llvm.cs.uiuc.edu/docs/GarbageCollection.html (Which seems to be +> the inverse of out-of-date, whatever that is) +> Says that there is strong dependency between the frontend and GC +> implementations. + +Yes. The GC needs information from the front-end, in particular how it +lays out objects and where to find object references. + +> For example, it seems as though the frontend and GC need to agree on a +> structure for the Meta data and they may call each other during +> allocation and garbage collection. + +Yes. They don't actually need to 'agree', but there needs to be an API +provided by the language runtime and consumed by the GC, that is used to +encode the information. One way is to standardize maps, a more general +way is to expose API's to access the maps that the front-end produces +(allowing the front-end to produce them in any format it wants). + +> I imagine it would be good to decouple the frontend and GC as much as +> possible or one may need to be reimplemented when the other is changed. +> Do you have any intentions for the use of Meta in SemiSpace? + +I'm not sure what you mean by 'meta', but if you mean metadata, yes. + +> We could trample around and make something work but it seems as +> though you have built most of the support structure for GC. We are +> trying to follow that plan. + +Sounds good. This is what I envision. :) The 'vision' encompases many +langauges and different implementation strategies, but lets start with one +that you are likely to be familiar with. Anything you do here can be +extended to the full vision, if and when you find yourself with tons of +spare time at the end of your project. :) + +Lets imagine that you have a language like Java. All GC'd objects in Java +have vtables, and from this vtable a wealth of information about the +object is accessible (e.g. it's size, whether it's an array, GC map +information, etc). The layout of objects in Java might look something +something like this: + + +obj ptr --\ + | + v + [ vtable ptr ] ----> [ rtti info ] ----> ... + [ obj word 1 ] [ gc info ] ----> [ obj size ] + [ obj word 2 ] [ vf ptr #1 ] [ Flags ] -> is array, etc + ... ... [ gc map #1 ] + [ obj word N ] [ vf ptr #N ] [ gc map ...] + +In addition, there are some number of "globals" (really statics fields in +Java) that can contain references. Given this, it seems like your GC +needs the front-end to provide the following: + +1. A way of identifying/iterating all of the global references. It seems + reasonable for the GC to expose a function like "void gc_add_static_root(void**)" + which the front-end would emit calls to. Java has 'class initializers' + which are called to initialize static members of classes (and other + stuff), so the language front-end could easily insert calls to this + function in the initializer. +2. A way of getting the size of an object. Initially you can use a header + word on the object, but eventually, it would be nice if the front-end + runtime library would provide a function, say + "unsigned gc_fe_get_object_size(void *object)", which could be called + by the GC implementation to get this information. With the approach + above, if the object was a non-array, it would just get the object size + field from the GC info (using several pointer dereferences from + 'object'. If it's an array, the FE runtime would do something perhaps + more complex to get this info, but you wouldn't really care what it + was :). VM's like Java often specialize a number of other cases (like + strings) as well, and obviously the GC doesn't want to know the details + of this hackery. +3. A way of iterating over the (language specific) GC map information for + a heap object. In particular, you need a way to identify the + offsets of all of the outgoing pointers from the start of a heap object. + I'm not sure what the best way to do this is (or the best way to + encode this) but I'm sure you can come up with something. :) The most + naive and inefficient interface (always a good starting place) would be + to have the front-end provide a callback: + _Bool gc_fe_is_pointer(void *obj, unsigned offset) + that the GC can use to probe all of the words in the object to see if + they are pointers. This can obviously be improved. :) + +In a naive implementation, the result of these callbacks will be +extremely inefficient, as all of these functions are very small and will +be extremely frequently called when a GC happens. In practice, because +this is LLVM, we can do things a little bit smarter. :) + +In particular, when a source language's runtime library is built, it will +include two things: all of the GC hooks it is required to implement, and +an actual GC implementation, chosen from runtime/GC directory. When this +is linked together, the link-time optimizer will link all of the little +helper functions above into the GC, inlining and optimizing the result, +resulting in a no overhead solution. + + +As far as your class project, the following steps make sense to me: + +The first step is to get the alloc_loop testcase fully working, as it +doesn't require any of the fancy extra interfaces. This can be done +directly by adding the object header (I believe), and finishing semispace +as it stands today. This should be simple and get you started with the GC +interfaces. + +The next step in this is to flush out the interface between the GC and +the language runtime. The GC doesn't want to know anything about how the +FE lays out vtables and GC info, and the front-end doesn't want to know +anything about how the GC implements its algorithm. The +runtime/GC/GCInterface.h file is a start on this, but the callbacks +described above will also need to be added. + +The next step is to extend alloc_loop to use these interfaces. It might +be useful to translate it to C code, to make it easier to deal with. +>From there, you can add one feature at a time, iterating between adding +features (like global pointers or pointers in heap objects) to the +alloc_loop test, and adding features to the GC. Eventually you will have +the full set of features listed above. + +Note that (by hacking on alloc_loop and other testcases you write), you +are basically writing a file that would be generated by a garbage +collected language front-end. Because of this, you get to write all of +the vtables/GC info by hand, and can include the "language runtime" +callbacks directly in the program. + + +This is a somewhat big task, but can be done incrementally. Let me +emphasize this point: to do this successfully, it is pretty important that +you try to add one little step to the testcase, and add the corresponding +feature to the GC, working a step at a time. As you find that you need to +change the interfaces on either side, go ahead and do so. If you work +incrementally, you will always have something that *works*, and is better +than the previous step. If you add something that is completely horrible +and you decide is a bad idea, you can always revert to something close by +that is known good. For your course project, you obviously want to get +the most implemented possible (ideally all of the above), but if technical +difficulties or other unforseen problems come up, at least you will have +something working and some progress to show. + +If you have any questions, please feel free to ask here. I'm pretty busy +over these couple of weeks (so my answers may be a little slow), but I +really want you guys to be successful! + +-Chris + +-- +http://llvm.org/ +http://nondot.org/sabre/ \ No newline at end of file Added: pypy/dist/pypy/translator/llvm/llvmbc.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/llvmbc.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,81 @@ +""" +Some simple classes that output LLVM-assembler. +""" + +import autopath + +import exceptions + +from pypy.objspace.flow.model import Variable, Constant, SpaceOperation + + +class Function(object): + def __init__(self, funcdef, startbb): + self.funcdef = funcdef + self.startbb = startbb + self.blocks = {} + + def basic_block(self, block): + assert block.label != self.startbb.label, "Block has same label as startblock!" + self.blocks[block.label] = block + + def __str__(self): + r = [self.funcdef, " {\n", str(self.startbb)] + r += [str(bb) for bb in self.blocks.values()] + ["}\n\n"] + return "".join(r) + +class BasicBlock(object): + def __init__(self, label): + self.label = label + self.instructions = [] + + def instructions(self, instruction): #should not be used + self.instructions.append(instruction) + + def select(self, l_arg, l_select, l_v1, l_v2): + s = "%s = select bool %s, %s, %s" + s = s % (l_arg.llvmname(), l_select.llvmname(), l_v1.typed_name(), + l_v2.typed_name()) + self.instructions.append(s) + + def phi(self, l_arg, l_values, blocks): + assert len(l_values) == len(blocks) + vars_string = [] + fd = "" + "%s = phi %s " % (l_arg.llvmname(), l_arg.llvmtype()) + fd += ", ".join(["[%s, %s]" % (v.llvmname(), b) + for v, b in zip(l_values, blocks)]) + self.instructions.append(fd) + + def spaceop(self, l_target, opname, l_args): + if l_target.llvmtype() == "void": + s = "call void %%std.%s(" % opname + else: + s = "%s = call %s %%std.%s(" % (l_target.llvmname(), + l_target.llvmtype(), opname) + self.instructions.append(s + + ", ".join([a.typed_name() for a in l_args]) + ")") + + def call(self, l_target, l_func, l_args): + s = "%s = call %s %s(" % (l_target.llvmname(), l_target.llvmtype(), + l_func.llvmname()) + self.instructions.append(s + + ", ".join([a.typed_name() for a in l_args]) + ")") + + def ret(self, l_value): + self.instructions.append("ret %s" % l_value.typed_name()) + + def uncond_branch(self, block): + self.instructions.append("br label " + block) + + def cond_branch(self, l_switch, blocktrue, blockfalse): + s = "br %s, label %s, label %s" % (l_switch.typed_name(), + blocktrue, blockfalse) + self.instructions.append(s) + + + def __str__(self): + s = [self.label + ":\n"] + for ins in self.instructions: + s += ["\t%s\n" % ins] + return "".join(s) + Added: pypy/dist/pypy/translator/llvm/operations.ll ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/operations.ll Sun Feb 6 17:45:51 2005 @@ -0,0 +1,172 @@ +;implementation of space operations for simple types +implementation + +declare void %llvm.memmove(sbyte*, sbyte*, uint, uint) +declare void %llvm.memcpy(sbyte*, sbyte*, uint, uint) +declare void %llvm.memset(sbyte*, ubyte, uint, uint) + + +;Basic operations for ints +internal int %std.add(int %a, int %b) { + %r = add int %a, %b + ret int %r +} + +internal int %std.inplace_add(int %a, int %b) { + %r = add int %a, %b + ret int %r +} + +internal int %std.sub(int %a, int %b) { + %r = sub int %a, %b + ret int %r +} + +internal int %std.inplace_sub(int %a, int %b) { + %r = sub int %a, %b + ret int %r +} + +internal int %std.mul(int %a, int %b) { + %r = mul int %a, %b + ret int %r +} + +internal int %std.inplace_mul(int %a, int %b) { + %r = mul int %a, %b + ret int %r +} + +internal int %std.div(int %a, int %b) { + %r = div int %a, %b + ret int %r +} + +internal int %std.inplace_div(int %a, int %b) { + %r = div int %a, %b + ret int %r +} + +internal int %std.floordiv(int %a, int %b) { + %r = div int %a, %b + ret int %r +} + +internal int %std.inplace_floordiv(int %a, int %b) { + %r = div int %a, %b + ret int %r +} + +internal int %std.mod(int %a, int %b) { + %r = rem int %a, %b + ret int %r +} + +internal int %std.inplace_mod(int %a, int %b) { + %r = rem int %a, %b + ret int %r +} + + +;Basic comparisons for ints + +internal bool %std.is(int %a, int %b) { + %r = seteq int %a, %b + ret bool %r +} + +internal bool %std.is_true(int %a) { + %b = cast int %a to bool + ret bool %b +} + +internal bool %std.eq(int %a, int %b) { + %r = seteq int %a, %b + ret bool %r +} + +internal bool %std.neq(int %a, int %b) { + %r = seteq int %a, %b + %r1 = xor bool %r, true + ret bool %r1 +} + +internal bool %std.lt(int %a, int %b) { + %r = setlt int %a, %b + ret bool %r +} + +internal bool %std.gt(int %a, int %b) { + %r = setgt int %a, %b + ret bool %r +} + +internal bool %std.le(int %a, int %b) { + %r = setle int %a, %b + ret bool %r +} + +internal bool %std.ge(int %a, int %b) { + %r = setge int %a, %b + ret bool %r +} + +;Logical operations for ints +internal int %std.and(int %a, int %b) { + %r = and int %a, %b + ret int %r +} + +internal int %std.inplace_and(int %a, int %b) { + %r = and int %a, %b + ret int %r +} + +internal int %std.or(int %a, int %b) { + %r = or int %a, %b + ret int %r +} + +internal int %std.inplace_or(int %a, int %b) { + %r = or int %a, %b + ret int %r +} + +internal int %std.xor(int %a, int %b) { + %r = xor int %a, %b + ret int %r +} + +internal int %std.inplace_xor(int %a, int %b) { + %r = xor int %a, %b + ret int %r +} + +internal int %std.lshift(int %a, int %b) { + %shift = cast int %b to ubyte + %r = shl int %a, ubyte %shift + ret int %r +} + +internal int %std.rshift(int %a, int %b) { + %shift = cast int %b to ubyte + %r = shr int %a, ubyte %shift + ret int %r +} + + +;bools +internal bool %std.is_true(bool %a) { + ret bool %a +} + +internal bool %std.and(bool %a, bool %b) { + %r = and bool %a, %b + ret bool %r +} + +internal bool %std.or(bool %a, bool %b) { + %r = or bool %a, %b + ret bool %r +} + Added: pypy/dist/pypy/translator/llvm/string.ll ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/string.ll Sun Feb 6 17:45:51 2005 @@ -0,0 +1,49 @@ +internal uint %std.len(%std.string* %a) { + %p = getelementptr %std.string* %a, int 0, uint 0 + %length1 = load uint* %p + ret uint %length1 +} + +internal %std.string* %std.make(uint %len, sbyte* %s) { + %ret = malloc %std.string, uint 1 + %lenp = getelementptr %std.string* %ret, int 0, uint 0 + %lsp = getelementptr %std.string* %ret, int 0, uint 1 + store uint %len, uint* %lenp + store sbyte* %s, sbyte** %lsp + ret %std.string* %ret +} + + +internal %std.string* %std.add(%std.string* %a, %std.string* %b) { + %lena = call uint %std.len(%std.string* %a) + %lenb = call uint %std.len(%std.string* %b) + %totlen = add uint %lena, %lenb + %nmem1 = malloc sbyte, uint %totlen + %oldsp1 = getelementptr %std.string* %a, int 0, uint 1 + %oldsp2 = getelementptr %std.string* %b, int 0, uint 1 + %olds1 = load sbyte** %oldsp1 + %olds2 = load sbyte** %oldsp2 + %nposp = getelementptr sbyte* %nmem1, uint %lena + call void %llvm.memcpy(sbyte* %nmem1, sbyte* %olds1, uint %lena, uint 0) + call void %llvm.memcpy(sbyte* %nposp, sbyte* %olds2, uint %lenb, uint 0) + %ret = call %std.string* %std.make(uint %totlen, sbyte* %nmem1) + ret %std.string* %ret +} + + +internal sbyte %std.getitem(%std.string* %s, int %p) { + %sp1 = getelementptr %std.string* %s, int 0, uint 1 + %s1 = load sbyte** %sp1 + %len = call uint %std.len(%std.string* %s) + %ilen = cast uint %len to int + %negpos = add int %ilen, %p + %is_negative = setlt int %p, 0 + %usedpos = select bool %is_negative, int %negpos, int %p + %negusedpos = setlt int %usedpos, 0 + %posbig = setgt int %usedpos, %ilen + %wrongindex = or bool %negusedpos, %posbig + %charp = getelementptr sbyte* %s1, int %usedpos + %value = load sbyte* %charp + %ret = select bool %wrongindex, sbyte 33, sbyte %value + ret sbyte %value +} Added: pypy/dist/pypy/translator/llvm/test.html ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/test.html Sun Feb 6 17:45:51 2005 @@ -0,0 +1,52 @@ + + + + + + +Description of the llvm backend + + + +
+

Description of the llvm backend

+

The llvm backend ("genllvm") tries to generate llvm-assembly out of an +annotated flowgraph. The annotation has to be complete for genllvm to +work. The produced assembly can then be optimized and converted to native code +by llvm. A simple Pyrex wrapper for the entry function is then generated to be +able to use the llvm-compiled functions from Python.

+
+

How to use genllvm

+

To try it out use the function 'llvmcompile' in the module +pypy.translator.llvm.genllvm on an annotated flowgraph:

+
+%pypy/translator/llvm> python -i genllvm.py
+>>> t = Translator(test.my_gcd) 
+>>> a = t.annotate([int, int])
+>>> f = llvmcompile(t)
+>>> f(10, 2)
+2
+>>> f(14, 7)
+7
+
+
+
+

Structure

+

The llvm backend consists of several parts:

+
+
    +
  1. +
+
+
+

Things that work:

+
+
    +
  • ints, bools, function calls
  • +
+
+
+
+
+ + Added: pypy/dist/pypy/translator/llvm/test/__init__.py ============================================================================== Added: pypy/dist/pypy/translator/llvm/test/autopath.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/test/autopath.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,114 @@ +""" +self cloning, automatic path configuration + +copy this into any subdirectory of pypy from which scripts need +to be run, typically all of the test subdirs. +The idea is that any such script simply issues + + import autopath + +and this will make sure that the parent directory containing "pypy" +is in sys.path. + +If you modify the master "autopath.py" version (in pypy/tool/autopath.py) +you can directly run it which will copy itself on all autopath.py files +it finds under the pypy root directory. + +This module always provides these attributes: + + pypydir pypy root directory path + this_dir directory where this autopath.py resides + +""" + + +def __dirinfo(part): + """ return (partdir, this_dir) and insert parent of partdir + into sys.path. If the parent directories don't have the part + an EnvironmentError is raised.""" + + import sys, os + try: + head = this_dir = os.path.realpath(os.path.dirname(__file__)) + except NameError: + head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) + + while head: + partdir = head + head, tail = os.path.split(head) + if tail == part: + break + else: + raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) + + checkpaths = sys.path[:] + pypy_root = os.path.join(head, '') + + while checkpaths: + orig = checkpaths.pop() + if os.path.join(os.path.realpath(orig), '').startswith(pypy_root): + sys.path.remove(orig) + sys.path.insert(0, head) + + munged = {} + for name, mod in sys.modules.items(): + fn = getattr(mod, '__file__', None) + if '.' in name or not isinstance(fn, str): + continue + newname = os.path.splitext(os.path.basename(fn))[0] + if not newname.startswith(part + '.'): + continue + path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') + if path.startswith(pypy_root) and newname != part: + modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) + if newname != '__init__': + modpaths.append(newname) + modpath = '.'.join(modpaths) + if modpath not in sys.modules: + munged[modpath] = mod + + for name, mod in munged.iteritems(): + if name not in sys.modules: + sys.modules[name] = mod + if '.' in name: + prename = name[:name.rfind('.')] + postname = name[len(prename)+1:] + if prename not in sys.modules: + __import__(prename) + if not hasattr(sys.modules[prename], postname): + setattr(sys.modules[prename], postname, mod) + + return partdir, this_dir + +def __clone(): + """ clone master version of autopath.py into all subdirs """ + from os.path import join, walk + if not this_dir.endswith(join('pypy','tool')): + raise EnvironmentError("can only clone master version " + "'%s'" % join(pypydir, 'tool',_myname)) + + + def sync_walker(arg, dirname, fnames): + if _myname in fnames: + fn = join(dirname, _myname) + f = open(fn, 'rwb+') + try: + if f.read() == arg: + print "checkok", fn + else: + print "syncing", fn + f = open(fn, 'w') + f.write(arg) + finally: + f.close() + s = open(join(pypydir, 'tool', _myname), 'rb').read() + walk(pypydir, sync_walker, s) + +_myname = 'autopath.py' + +# set guaranteed attributes + +pypydir, this_dir = __dirinfo('pypy') + +if __name__ == '__main__': + __clone() Added: pypy/dist/pypy/translator/llvm/test/llvmsnippet.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/test/llvmsnippet.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,47 @@ +import autopath + +def simple1(): + return 1 + +def simple2(): + return False + +def simple3(): + c = "Hello, Stars!" + return c + +def simple4(): + return 3 + simple1() + +def simple5(b): + if b: + x = 12 + else: + x = 13 + return x + +def simple6(): + simple4() + return 1 + +def ackermann(n, m): + if n == 0: + return m + 1 + if m == 0: + return ackermann(n - 1, 1) + return ackermann(n - 1, ackermann(n, m - 1)) + + +def arraytestsimple(): + a = [42] + return a[0] + +def arraytestsimple1(): + a = [43] + return a[-1] + +def arraytestsetitem(i): + a = [43] + a[0] = i * 2 + return a[-1] + Added: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Sun Feb 6 17:45:51 2005 @@ -0,0 +1,164 @@ +import autopath +import py + +import StringIO + +from pypy.translator.translator import Translator +from pypy.translator.llvm.genllvm import LLVMGenerator +from pypy.translator.test import snippet as test +from pypy.objspace.flow.model import Constant, Variable + +from pypy.translator.llvm.test import llvmsnippet + +def setup_module(mod): + mod.llvm_found = is_on_path("llvm-as") + +def compile_function(function, annotate): + t = Translator(function) + a = t.annotate(annotate) + gen = LLVMGenerator(t) + return gen.compile() + +def is_on_path(name): + try: + py.path.local.sysfind(name) + except py.error.ENOENT: + return False + else: + return True + +class TestLLVMRepr(object): + def DONOT_test_simple1(self): + t = Translator(llvmsnippet.simple1) + a = t.annotate([]) + gen = LLVMGenerator(t) + l_repr = gen.get_repr(t.getflowgraph().startblock.exits[0].args[0]) + assert l_repr.llvmname() == "1" + assert l_repr.typed_name() == "int 1" + print gen.l_entrypoint.get_functions() + assert gen.l_entrypoint.get_functions() == """\ +int %simple1() { +block0: +\tbr label %block1 +block1: +\t%v0 = phi int [1, %block0] +\tret int %v0 +} + +""" + + def test_simple2(self): + t = Translator(llvmsnippet.simple2) + a = t.annotate([]) + gen = LLVMGenerator(t) + print gen + print t.getflowgraph().startblock.exits[0].args[0] + l_repr = gen.get_repr(t.getflowgraph().startblock.exits[0].args[0]) + assert l_repr.llvmname() == "false" + assert l_repr.typed_name() == "bool false" + + def test_typerepr(self): + t = Translator(llvmsnippet.simple1) + a = t.annotate([]) + gen = LLVMGenerator(t) + l_repr = gen.get_repr(str) + assert l_repr.llvmname() == "%std.string*" + + def test_stringrepr(self): + t = Translator(llvmsnippet.simple3) + a = t.annotate([]) + gen = LLVMGenerator(t) + l_repr1 = gen.get_repr(t.getflowgraph().startblock.exits[0].args[0]) + l_repr2 = gen.get_repr(t.getflowgraph().startblock.exits[0].args[0]) + assert l_repr1 is l_repr2 + assert l_repr1.typed_name() == "%std.string* %glb.StringRepr.2" + assert l_repr2.get_globals() == """%glb.StringRepr.1 = \ +internal constant [13 x sbyte] c"Hello, Stars!" +%glb.StringRepr.2 = internal constant %std.string {uint 13,\ +sbyte* getelementptr ([13 x sbyte]* %glb.StringRepr.1, uint 0, uint 0)}""" + +class TestGenLLVM(object): + def setup_method(self,method): + if not llvm_found: + py.test.skip("llvm-as not found on path") + + def test_simple1(self): + f = compile_function(llvmsnippet.simple1, []) + assert f() == 1 + + def test_simple2(self): + f = compile_function(llvmsnippet.simple2, []) + assert f() == 0 + + def test_simple4(self): + f = compile_function(llvmsnippet.simple4, []) + assert f() == 4 + + def test_simple5(self): + f = compile_function(llvmsnippet.simple5, [int]) + assert f(1) == 12 + assert f(0) == 13 + + def test_ackermann(self): + f = compile_function(llvmsnippet.ackermann, [int, int]) + for i in range(10): + assert f(0, i) == i + 1 + assert f(1, i) == i + 2 + assert f(2, i) == 2 * i + 3 + assert f(3, i) == 2 ** (i + 3) - 3 + +class TestLLVMArray(object): + def setup_method(self, method): + if not llvm_found: + py.test.skip("llvm-as not found on path.") + + def test_simplearray(self): + f = compile_function(llvmsnippet.arraytestsimple, []) + assert f() == 42 + + def test_simplearray1(self): + f = compile_function(llvmsnippet.arraytestsimple1, []) + assert f() == 43 + + def test_simplearray_setitem(self): + f = compile_function(llvmsnippet.arraytestsetitem, [int]) + assert f(32) == 64 + +class TestSnippet(object): + def setup_method(self, method): + if not llvm_found: + py.test.skip("llvm-as not found on path.") + + def test_if_then_else(self): + f = compile_function(test.if_then_else, [int, int, int]) + assert f(0, 12, 13) == 13 + assert f(13, 12, 13) == 12 + + def test_my_gcd(self): + f = compile_function(test.my_gcd, [int, int]) + assert f(15, 5) == 5 + assert f(18, 42) == 6 + + def test_is_perfect_number(self): + f = compile_function(test.is_perfect_number, [int]) + assert f(28) == 1 + assert f(123) == 0 + assert f(496) == 1 + + def test_my_bool(self): + f = compile_function(test.my_bool, [int]) + assert f(10) == 1 + assert f(1) == 1 + assert f(0) == 0 + + def test_while_func(self): + while_func = compile_function(test.while_func, [int]) + assert while_func(10) == 55 + + def test_factorial2(self): + factorial2 = compile_function(test.factorial2, [int]) + assert factorial2(5) == 120 + + def test_factorial(self): + factorial = compile_function(test.factorial, [int]) + assert factorial(5) == 120 From arigo at codespeak.net Sun Feb 6 20:47:13 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 6 Feb 2005 20:47:13 +0100 (MET) Subject: [pypy-svn] r8931 - pypy/branch/dist-simpler-multimethods/pypy/objspace/std Message-ID: <20050206194713.5B6B727BFB@code1.codespeak.net> Author: arigo Date: Sun Feb 6 20:47:13 2005 New Revision: 8931 Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py Log: typo Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py Sun Feb 6 20:47:13 2005 @@ -39,7 +39,7 @@ def init__List(space, w_list, __args__): - w_iterable, __args__.parse('list', + w_iterable, = __args__.parse('list', (['sequence'], None, None), # signature [W_ListObject(space, [])]) # default argument w_list.ob_size = 0 # XXX think about it later From arigo at codespeak.net Sun Feb 6 20:50:35 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 6 Feb 2005 20:50:35 +0100 (MET) Subject: [pypy-svn] r8932 - pypy/branch/dist-simpler-multimethods/pypy/objspace/std Message-ID: <20050206195035.E073727BFB@code1.codespeak.net> Author: arigo Date: Sun Feb 6 20:50:35 2005 New Revision: 8932 Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py Log: more typos. remove debugging prints. Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py Sun Feb 6 20:50:35 2005 @@ -43,7 +43,6 @@ (['sequence'], None, None), # signature [W_ListObject(space, [])]) # default argument w_list.ob_size = 0 # XXX think about it later - w_iterable = args[0] w_iterator = space.iter(w_iterable) while True: try: Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py Sun Feb 6 20:50:35 2005 @@ -167,7 +167,6 @@ return prefix, list_of_typeorders def typeerrormsg(space, operatorsymbol, args_w): - print "AAAARGH", operatorsymbol, args_w return space.wrap("XXX insert message here") def wrap_func_in_trampoline(func, multimethod, selfindex=0): @@ -220,12 +219,10 @@ w_res = perform_call(space, %s) except FailedToImplement, e: if e.args: - w_type = e.args[0] - w_value = e.args[1] + raise OperationError(e.args[0], e.args[1]) else: - w_value = typeerrormsg(space, %r, [%s]) - w_type = space.w_TypeError - raise OperationError(w_type, w_value) + raise OperationError(space.w_TypeError, + typeerrormsg(space, %r, [%s])) if w_res is None: w_res = space.w_None return w_res From arigo at codespeak.net Sun Feb 6 20:38:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 6 Feb 2005 20:38:09 +0100 (MET) Subject: [pypy-svn] r8930 - in pypy/branch/dist-simpler-multimethods: . pypy pypy/interpreter pypy/module pypy/objspace/std pypy/objspace/std/test pypy/translator Message-ID: <20050206193809.4856E27BFB@code1.codespeak.net> Author: arigo Date: Sun Feb 6 20:38:08 2005 New Revision: 8930 Added: pypy/branch/dist-simpler-multimethods/ - copied from r8897, pypy/dist/ pypy/branch/dist-simpler-multimethods/pypy/conftest.py - copied unchanged from r8904, pypy/dist/pypy/conftest.py pypy/branch/dist-simpler-multimethods/pypy/interpreter/pycode.py - copied unchanged from r8902, pypy/dist/pypy/interpreter/pycode.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py - copied, changed from r8903, pypy/dist/pypy/objspace/std/listobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py (contents, props changed) pypy/branch/dist-simpler-multimethods/pypy/objspace/std/typeobject.py - copied, changed from r8901, pypy/dist/pypy/objspace/std/typeobject.py pypy/branch/dist-simpler-multimethods/pypy/translator/genc.py - copied unchanged from r8900, pypy/dist/pypy/translator/genc.py Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py pypy/branch/dist-simpler-multimethods/pypy/module/__builtin__interp.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/boolobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/booltype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/default.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dictobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/fake.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/floatobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/floattype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/intobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/inttype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/itertype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longtype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/noneobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/register_all.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/sliceobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringtype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupletype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/unicodeobject.py Log: A probably short-lived branch to check in the intermediate steps of simplifying multimethods. Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py Sun Feb 6 20:38:08 2005 @@ -20,6 +20,8 @@ from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache +NoneNotWrapped = object() + class Signature: def __init__(self, func=None, argnames=None, varargname=None, kwargname=None, name = None): @@ -457,6 +459,7 @@ raise ValueError, ("function name must start with 'app_'; " "%r does not" % app.func_name) app_name = app.func_name[4:] + self.__name__ = app.func_name self.name = app_name self._staticcode = app.func_code self._staticglobals = app.func_globals @@ -516,6 +519,7 @@ self._code = BuiltinCode(f, ismethod=ismethod, spacearg=spacearg, unwrap_spec=unwrap_spec) + self.__name__ = f.func_name self.name = app_name self._staticdefs = list(f.func_defaults or ()) #if self._staticdefs: @@ -529,8 +533,8 @@ "NOT_RPYTHON" defs_w = [] for val in self._staticdefs: - if val is None: - defs_w.append(val) + if val is NoneNotWrapped: + defs_w.append(None) else: defs_w.append(space.wrap(val)) return defs_w Modified: pypy/branch/dist-simpler-multimethods/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/module/__builtin__interp.py Sun Feb 6 20:38:08 2005 @@ -5,6 +5,7 @@ from pypy.interpreter.pycode import PyCode from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import BaseWrappable, W_Root +from pypy.interpreter.gateway import NoneNotWrapped import __builtin__ as cpy_builtin @@ -225,7 +226,7 @@ compile.unwrap_spec = [str,str,str,int,int] -def eval(w_source, w_globals=None, w_locals=None): +def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): w = space.wrap if space.is_true(space.isinstance(w_source, space.w_str)): @@ -259,7 +260,7 @@ space.delattr(w_object, w_name) return space.w_None -def getattr(w_object, w_name, w_defvalue=None): +def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): try: return space.getattr(w_object, w_name) except OperationError, e: @@ -278,9 +279,7 @@ def hex(w_val): return space.hex(w_val) -def round(w_val, w_n=None): - if w_n is None: - w_n = space.wrap(0) +def round(w_val, w_n=0): return space.round(w_val, w_n) def id(w_object): @@ -295,7 +294,7 @@ def _issubtype(w_cls1, w_cls2): return space.issubtype(w_cls1, w_cls2) -def iter(w_collection_or_callable, w_sentinel=None): +def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): if w_sentinel is None: return space.iter(w_collection_or_callable) else: @@ -308,8 +307,6 @@ return space.ord(w_val) def pow(w_base, w_exponent, w_modulus=None): - if w_modulus is None: - w_modulus = space.w_None return space.pow(w_base, w_exponent, w_modulus) def repr(w_object): Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/boolobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/boolobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/boolobject.py Sun Feb 6 20:38:08 2005 @@ -16,22 +16,20 @@ """ representation for debugging purposes """ return "%s(%s)" % (w_self.__class__.__name__, w_self.boolval) + def unwrap(w_self): + return w_self.boolval + registerimplementation(W_BoolObject) # bool-to-int delegation requires translating the .boolvar attribute # to an .intval one -def delegate__Bool(space, w_bool): - return intobject.W_IntObject(space, int(w_bool.boolval)) -delegate__Bool.result_class = intobject.W_IntObject -delegate__Bool.priority = PRIORITY_PARENT_TYPE +def delegate_Bool2Int(w_bool): + return intobject.W_IntObject(w_bool.space, int(w_bool.boolval)) def nonzero__Bool(space, w_bool): return w_bool -def unwrap__Bool(space, w_bool): - return w_bool.boolval - def repr__Bool(space, w_bool): if w_bool.boolval: return space.wrap('True') Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/booltype.py ============================================================================== --- pypy/dist/pypy/objspace/std/booltype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/booltype.py Sun Feb 6 20:38:08 2005 @@ -5,7 +5,7 @@ def descr__new__(space, w_booltype, w_obj=None): - if w_obj is not None and space.is_true(w_obj): + if space.is_true(w_obj): return space.w_True else: return space.w_False Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/default.py ============================================================================== --- pypy/dist/pypy/objspace/std/default.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/default.py Sun Feb 6 20:38:08 2005 @@ -13,7 +13,7 @@ # __init__ should succeed if called internally as a multimethod -def init__ANY(space, w_obj, w_args, w_kwds): +def init__ANY(space, w_obj, __args__): pass @@ -216,9 +216,6 @@ # ugh -class UnwrapError(Exception): - pass - def typed_unwrap_error_msg(space, expected, w_obj): w = space.wrap type_name = space.str_w(space.getattr(space.type(w_obj),w("__name__"))) @@ -236,11 +233,5 @@ raise OperationError(space.w_TypeError, typed_unwrap_error_msg(space, "float", w_obj)) -def unwrap__ANY(space, w_obj): - if isinstance(w_obj, BaseWrappable): - return w_obj - else: - raise UnwrapError, 'cannot unwrap %r' % (w_obj,) - register_all(vars()) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dictobject.py Sun Feb 6 20:38:08 2005 @@ -98,40 +98,40 @@ freeslot = entry perturb >>= 5 -registerimplementation(W_DictObject) + def unwrap(w_dict): + space = w_dict.space + result = {} + for entry in w_dict.non_empties(): + # XXX generic mixed types unwrap + result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) + return result +registerimplementation(W_DictObject) -def unwrap__Dict(space, w_dict): - result = {} - for entry in w_dict.non_empties(): - result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) # XXX generic mixed types unwrap - return result -def init__Dict(space, w_dict, w_args, w_kwds): +def init__Dict(space, w_dict, __args__): + w_src, w_kwds = __args__.parse('dict', + (['seq_or_map'], None, 'kwargs'), # signature + [W_DictObject(space, [])]) # default argument dict_clear__Dict(space, w_dict) - args = space.unpackiterable(w_args) - if len(args) == 0: - pass - elif len(args) == 1: - # XXX do dict({...}) with dict_update__Dict_Dict() - try: - space.getattr(args[0], space.wrap("keys")) - except OperationError: - list_of_w_pairs = space.unpackiterable(args[0]) - for w_pair in list_of_w_pairs: - pair = space.unpackiterable(w_pair) - if len(pair)!=2: - raise OperationError(space.w_ValueError, - space.wrap("dict() takes a sequence of pairs")) - w_k, w_v = pair - setitem__Dict_ANY_ANY(space, w_dict, w_k, w_v) - else: - from pypy.objspace.std.dicttype import dict_update__ANY_ANY - dict_update__ANY_ANY(space, w_dict, args[0]) + # XXX do dict({...}) with dict_update__Dict_Dict() + try: + space.getattr(w_src, space.wrap("keys")) + except OperationError: + list_of_w_pairs = space.unpackiterable(w_src) + for w_pair in list_of_w_pairs: + pair = space.unpackiterable(w_pair) + if len(pair)!=2: + raise OperationError(space.w_ValueError, + space.wrap("dict() takes a sequence of pairs")) + w_k, w_v = pair + setitem__Dict_ANY_ANY(space, w_dict, w_k, w_v) else: - raise OperationError(space.w_TypeError, - space.wrap("dict() takes at most 1 argument")) - space.call_method(w_dict, 'update', w_kwds) + if space.is_true(w_src): + from pypy.objspace.std.dicttype import dict_update__ANY_ANY + dict_update__ANY_ANY(space, w_dict, w_src) + if space.is_true(w_kwds): + space.call_method(w_dict, 'update', w_kwds) def getitem__Dict_ANY(space, w_dict, w_lookup): entry = w_dict.lookdict(w_dict.hash(w_lookup), w_lookup) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/fake.py ============================================================================== --- pypy/dist/pypy/objspace/std/fake.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/fake.py Sun Feb 6 20:38:08 2005 @@ -4,7 +4,7 @@ from pypy.interpreter.function import Function from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.objspace import W_Object, StdObjSpace -from pypy.objspace.std.default import UnwrapError +from pypy.objspace.std.model import UnwrapError from pypy.tool.cache import Cache # this file automatically generates non-reimplementations of CPython @@ -83,13 +83,12 @@ def __init__(w_self, space, val): W_Object.__init__(w_self, space) w_self.val = val + def unwrap(w_self): + return w_self.val # cannot write to W_Fake.__name__ in Python 2.2! W_Fake = type(W_Object)('W_Fake%s'%(cpy_type.__name__.capitalize()), (W_Object,), dict(W_Fake.__dict__.items())) - def fake_unwrap(space, w_obj): - return w_obj.val - StdObjSpace.unwrap.register(fake_unwrap, W_Fake) W_Fake.typedef.fakedcpytype = cpy_type return W_Fake Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/floatobject.py Sun Feb 6 20:38:08 2005 @@ -21,14 +21,19 @@ W_Object.__init__(w_self, space) w_self.floatval = floatval + def unwrap(w_self): + return w_self.floatval + registerimplementation(W_FloatObject) +# bool-to-float delegation +def delegate_Bool2Float(w_bool): + return W_FloatObject(w_bool.space, float(w_bool.boolval)) + # int-to-float delegation -def delegate__Int(space, w_intobj): - return W_FloatObject(space, float(w_intobj.intval)) -delegate__Int.result_class = W_FloatObject -delegate__Int.priority = PRIORITY_CHANGE_TYPE +def delegate_Int2Float(w_intobj): + return W_FloatObject(w_intobj.space, float(w_intobj.intval)) # float__Float is supposed to do nothing, unless it has @@ -49,9 +54,6 @@ def float_w__Float(space, w_float): return w_float.floatval -def unwrap__Float(space, w_float): - return w_float.floatval - def app_repr__Float(f): r = "%.17g"%f for c in r: Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/floattype.py ============================================================================== --- pypy/dist/pypy/objspace/std/floattype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/floattype.py Sun Feb 6 20:38:08 2005 @@ -1,11 +1,9 @@ from pypy.objspace.std.stdtypedef import * from pypy.interpreter.error import OperationError -def descr__new__(space, w_floattype, w_value=None): +def descr__new__(space, w_floattype, w_value=0.0): from pypy.objspace.std.floatobject import W_FloatObject - if w_value is None: - value = 0.0 - elif space.is_true(space.isinstance(w_value, space.w_str)): + if space.is_true(space.isinstance(w_value, space.w_str)): try: value = float(space.str_w(w_value)) except ValueError, e: Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/intobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/intobject.py Sun Feb 6 20:38:08 2005 @@ -28,6 +28,9 @@ """ representation for debugging purposes """ return "%s(%d)" % (w_self.__class__.__name__, w_self.intval) + def unwrap(w_self): + return int(w_self.intval) + registerimplementation(W_IntObject) @@ -43,9 +46,6 @@ def int_w__Int(space, w_int1): return int(w_int1.intval) -def unwrap__Int(space, w_int1): - return int(w_int1.intval) - def repr__Int(space, w_int1): a = w_int1.intval res = str(a) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/inttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/inttype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/inttype.py Sun Feb 6 20:38:08 2005 @@ -1,14 +1,13 @@ from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.strutil import string_to_int from pypy.interpreter.error import OperationError +from pypy.interpreter.gateway import NoneNotWrapped -def descr__new__(space, w_inttype, w_value=None, w_base=None): +def descr__new__(space, w_inttype, w_value=0, w_base=NoneNotWrapped): from pypy.objspace.std.intobject import W_IntObject if w_base is None: # check for easy cases - if w_value is None: - value = 0 - elif isinstance(w_value, W_IntObject): + if isinstance(w_value, W_IntObject): value = w_value.intval elif space.is_true(space.isinstance(w_value, space.w_str)): try: Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/itertype.py ============================================================================== --- pypy/dist/pypy/objspace/std/itertype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/itertype.py Sun Feb 6 20:38:08 2005 @@ -2,5 +2,5 @@ # ____________________________________________________________ -iter_typedef = StdTypeDef("sequence-iterator", +iter_typedef = StdTypeDef("sequenceiterator", ) Copied: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py (from r8903, pypy/dist/pypy/objspace/std/listobject.py) ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py Sun Feb 6 20:38:08 2005 @@ -29,36 +29,30 @@ reprlist = [repr(w_item) for w_item in w_self.ob_item[:w_self.ob_size]] return "%s(%s)" % (w_self.__class__.__name__, ', '.join(reprlist)) + def unwrap(w_list): + space = w_list.space + items = [space.unwrap(w_item) for w_item in w_list.ob_item[:w_list.ob_size]]# XXX generic mixed types unwrap + return list(items) + registerimplementation(W_ListObject) -def unwrap__List(space, w_list): - items = [space.unwrap(w_item) for w_item in w_list.ob_item[:w_list.ob_size]]# XXX generic mixed types unwrap - return list(items) - -def init__List(space, w_list, w_args, w_kwds): - if space.is_true(w_kwds): - raise OperationError(space.w_TypeError, - space.wrap("no keyword arguments expected")) +def init__List(space, w_list, __args__): + w_iterable, __args__.parse('list', + (['sequence'], None, None), # signature + [W_ListObject(space, [])]) # default argument w_list.ob_size = 0 # XXX think about it later - args = space.unpackiterable(w_args) - if len(args) == 0: - pass # empty list - elif len(args) == 1: - w_iterable = args[0] - w_iterator = space.iter(w_iterable) - while True: - try: - w_item = space.next(w_iterator) - except OperationError, e: - if not e.match(space, space.w_StopIteration): - raise - break # done - _ins1(w_list, w_list.ob_size, w_item) - else: - raise OperationError(space.w_TypeError, - space.wrap("list() takes at most 1 argument")) + w_iterable = args[0] + w_iterator = space.iter(w_iterable) + while True: + try: + w_item = space.next(w_iterator) + except OperationError, e: + if not e.match(space, space.w_StopIteration): + raise + break # done + _ins1(w_list, w_list.ob_size, w_item) def len__List(space, w_list): result = w_list.ob_size Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py Sun Feb 6 20:38:08 2005 @@ -17,9 +17,25 @@ assert isinstance(longval, long) w_self.longval = longval + def unwrap(w_self): + return w_self.longval + registerimplementation(W_LongObject) +# bool-to-long +def delegate_Bool2Long(w_bool): + return W_LongObject(w_bool.space, long(w_bool.boolval)) + +# int-to-long delegation +def delegate_Int2Long(w_intobj): + return W_LongObject(w_intobj.space, long(w_intobj.intval)) + +# long-to-float delegation +def delegate_Long2Float(w_longobj): + return W_FloatObject(w_longobj.space, float(w_longobj.longval)) + + # long__Long is supposed to do nothing, unless it has # a derived long object, where it should return # an exact one. @@ -56,9 +72,6 @@ raise OperationError(space.w_OverflowError, space.wrap("long int too large to convert to int")) -def unwrap__Long(space, w_long): - return w_long.longval - def repr__Long(space, w_long): return space.wrap(repr(w_long.longval)) @@ -222,36 +235,3 @@ register_all(vars()) - -# delegations must be registered manually because we have more than one -# long-to-something delegation - -# int-to-long delegation -def delegate_from_int(space, w_intobj): - return W_LongObject(space, long(w_intobj.intval)) -delegate_from_int.result_class = W_LongObject -delegate_from_int.priority = PRIORITY_CHANGE_TYPE - -StdObjSpace.delegate.register(delegate_from_int, W_IntObject) - -# long-to-int delegation -def delegate_to_int(space, w_longobj): - if -sys.maxint-1 <= w_longobj.longval <= sys.maxint: - return W_IntObject(space, int(w_longobj.longval)) - else: - # note the 'return' here -- hack - return FailedToImplement(space.w_OverflowError, - space.wrap("long int too large to convert to int")) -delegate_to_int.result_class = W_IntObject -delegate_to_int.priority = PRIORITY_CHANGE_TYPE -delegate_to_int.can_fail = True - -StdObjSpace.delegate.register(delegate_to_int, W_LongObject) - -# long-to-float delegation -def delegate_to_float(space, w_longobj): - return W_FloatObject(space, float(w_longobj.longval)) -delegate_to_float.result_class = W_FloatObject -delegate_to_float.priority = PRIORITY_CHANGE_TYPE - -StdObjSpace.delegate.register(delegate_to_float, W_LongObject) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/longtype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longtype.py Sun Feb 6 20:38:08 2005 @@ -2,14 +2,13 @@ from pypy.objspace.std.strutil import string_to_long from pypy.interpreter.error import OperationError from pypy.objspace.std.inttype import int_typedef +from pypy.interpreter.gateway import NoneNotWrapped -def descr__new__(space, w_longtype, w_value=None, w_base=None): +def descr__new__(space, w_longtype, w_value=0, w_base=NoneNotWrapped): from pypy.objspace.std.longobject import W_LongObject if w_base is None: # check for easy cases - if w_value is None: - value = 0L - elif isinstance(w_value, W_LongObject): + if isinstance(w_value, W_LongObject): value = w_value.longval elif space.is_true(space.isinstance(w_value, space.w_str)): try: Added: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py ============================================================================== --- (empty file) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py Sun Feb 6 20:38:08 2005 @@ -0,0 +1,150 @@ +""" +The full list of which Python types and which implementation we want +to provide in this version of PyPy, along with conversion rules. +""" + +from pypy.objspace.std.multimethod import MultiMethodTable, FailedToImplement +from pypy.interpreter.baseobjspace import W_Root, ObjSpace + + +class StdTypeModel: + + def __init__(self): + # All the Python types that we want to provide in this StdObjSpace + class result: + from pypy.objspace.std.objecttype import object_typedef + from pypy.objspace.std.booltype import bool_typedef + from pypy.objspace.std.inttype import int_typedef + from pypy.objspace.std.floattype import float_typedef + from pypy.objspace.std.tupletype import tuple_typedef + from pypy.objspace.std.listtype import list_typedef + from pypy.objspace.std.dicttype import dict_typedef + from pypy.objspace.std.basestringtype import basestring_typedef + from pypy.objspace.std.stringtype import str_typedef + from pypy.objspace.std.typetype import type_typedef + from pypy.objspace.std.slicetype import slice_typedef + from pypy.objspace.std.longtype import long_typedef + from pypy.objspace.std.unicodetype import unicode_typedef + self.pythontypes = [value for key, value in result.__dict__.items() + if not key.startswith('_')] # don't look + + # The object implementations that we want to 'link' into PyPy must be + # imported here. This registers them into the multimethod tables, + # *before* the type objects are built from these multimethod tables. + from pypy.objspace.std import objectobject + from pypy.objspace.std import boolobject + from pypy.objspace.std import intobject + from pypy.objspace.std import floatobject + from pypy.objspace.std import tupleobject + from pypy.objspace.std import listobject + from pypy.objspace.std import dictobject + from pypy.objspace.std import stringobject + from pypy.objspace.std import typeobject + from pypy.objspace.std import sliceobject + from pypy.objspace.std import longobject + from pypy.objspace.std import noneobject + from pypy.objspace.std import iterobject + from pypy.objspace.std import unicodeobject + from pypy.objspace.std import fake + import pypy.objspace.std.default # register a few catch-all multimethods + + # the set of implementation types + self.typeorder = { + objectobject.W_ObjectObject: [], + boolobject.W_BoolObject: [], + intobject.W_IntObject: [], + floatobject.W_FloatObject: [], + tupleobject.W_TupleObject: [], + listobject.W_ListObject: [], + dictobject.W_DictObject: [], + stringobject.W_StringObject: [], + typeobject.W_TypeObject: [], + sliceobject.W_SliceObject: [], + longobject.W_LongObject: [], + noneobject.W_NoneObject: [], + iterobject.W_SeqIterObject: [], + unicodeobject.W_UnicodeObject: [], + } + for type in self.typeorder: + self.typeorder[type].append((type, None)) + + # register the order in which types are converted into each others + # when trying to dispatch multimethods. + # XXX build these lists a bit more automatically later + self.typeorder[boolobject.W_BoolObject] += [ + (intobject.W_IntObject, boolobject.delegate_Bool2Int), + (longobject.W_LongObject, longobject.delegate_Bool2Long), + (floatobject.W_FloatObject, floatobject.delegate_Bool2Float), + ] + self.typeorder[intobject.W_IntObject] += [ + (longobject.W_LongObject, longobject.delegate_Int2Long), + (floatobject.W_FloatObject, floatobject.delegate_Int2Float), + ] + self.typeorder[longobject.W_LongObject] += [ + (floatobject.W_FloatObject, longobject.delegate_Long2Float), + ] + self.typeorder[stringobject.W_StringObject] += [ + (unicodeobject.W_UnicodeObject, unicodeobject.delegate_String2Unicode), + ] + + # put W_Root everywhere + self.typeorder[W_Root] = [] + for type in self.typeorder: + self.typeorder[type].append((W_Root, None)) + + +# ____________________________________________________________ + +W_ANY = W_Root + +class W_Object(W_Root, object): + "Parent base class for wrapped objects." + typedef = None + + def __init__(w_self, space): + w_self.space = space # XXX not sure this is ever used any more + + def __repr__(self): + s = '%s(%s)' % ( + self.__class__.__name__, + #', '.join(['%s=%r' % keyvalue for keyvalue in self.__dict__.items()]) + getattr(self, 'name', '') + ) + if hasattr(self, 'w__class__'): + s += ' instance of %s' % self.w__class__ + return '<%s>' % s + + def unwrap(w_self): + raise UnwrapError, 'cannot unwrap %r' % (w_self,) + +class UnwrapError(Exception): + pass + + +class MultiMethod(MultiMethodTable): + + def __init__(self, operatorsymbol, arity, specialnames=None, **extras): + """NOT_RPYTHON: cannot create new multimethods dynamically. + """ + MultiMethodTable.__init__(self, arity, W_ANY, + argnames_before = ['space']) + self.operatorsymbol = operatorsymbol + if specialnames is None: + specialnames = [operatorsymbol] + self.specialnames = specialnames # e.g. ['__xxx__', '__rxxx__'] + self.extras = extras + self.unbound_versions = {} + # transform '+' => 'add' etc. + for line in ObjSpace.MethodTable: + realname, symbolname = line[:2] + if symbolname == operatorsymbol: + self.name = realname + break + else: + self.name = operatorsymbol + if extras.get('general__args__', False): + self.argnames_after = ['__args__'] + + def install_not_sliced(self, typeorder): + return self.install(prefix = '__mm_' + self.name, + list_of_typeorders = [typeorder]*self.arity) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py Sun Feb 6 20:38:08 2005 @@ -1,507 +1,226 @@ -from pypy.interpreter.baseobjspace import OperationError -from pypy.tool.cache import Cache -class FailedToImplement(Exception): - "Signals the dispatcher to try harder." - -class W_ANY: - "Catch-all in case multimethods don't find anything else." - typedef = None - - -# This file defines three major classes: -# -# MultiMethod is the class you instantiate explicitly. -# It is essentially just a collection of registered functions. -# If xxx is a MultiMethod, StdObjSpace.xxx is xxx again, -# and space.xxx is a BoundMultiMethod. -# -# UnboundMultiMethod is a MultiMethod on which one argument -# (typically the first one) has been restricted to be of some -# statically known type. It is obtained by the syntax -# W_XxxType.yyy, where W_XxxType is the static type class, -# or explicitly by calling 'xxx.slice(typeclass, arg_position)'. -# Its dispatch table is always a subset of the original MultiMethod's -# dispatch table. -# -# The registration of a new function to a MultiMethod will be propagated -# to all of its matching UnboundMultiMethod instances. The registration of -# a function directly to an UnboundMultiMethod will register the function -# to its base MultiMethod and invoke the same behavior. -# -# BoundMultiMethod is a MultiMethod or UnboundMultiMethod which -# has been bound to a specific object space. It is obtained by -# 'space.xxx' or explicitly by calling 'xxx.get(space)'. - -class AbstractMultiMethod(object): - """Abstract base class for MultiMethod and UnboundMultiMethod - i.e. the classes that are not bound to a specific space instance.""" - - def __init__(self, operatorsymbol, arity): - "NOT_RPYTHON: cannot create new multimethods dynamically" - self.arity = arity - self.operatorsymbol = operatorsymbol - self.dispatch_table = {} - self.cache_table = Cache() - self.compilation_cache_table = {} - self.cache_delegator_key = None - self.dispatch_arity = 0 - - def __repr__(self): - return '<%s %s>' % (self.__class__.__name__, self.operatorsymbol) - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - assert len(types) == self.arity - functions = self.dispatch_table.setdefault(types, []) - if function in functions: - return False - functions.append(function) - self.cache_table.clear() - self.compilation_cache_table.clear() - self.adjust_dispatch_arity(types) - return True - - def adjust_dispatch_arity(self, types): - "NOT_RPYTHON" - width = len(types) - while width > self.dispatch_arity and types[width-1] is W_ANY: - width -= 1 - self.dispatch_arity = width - - def compile_calllist(self, argclasses, delegate): - """Compile a list of calls to try for the given classes of the - arguments. Return a function that should be called with the - actual arguments.""" - if delegate.key is not self.cache_delegator_key: - self.cache_table.clear() - self.compilation_cache_table.clear() - self.cache_delegator_key = delegate.key - return self.cache_table.getorbuild(argclasses, - self.do_compile_calllist, - delegate) - - def do_compile_calllist(self, argclasses, delegate): - "NOT_RPYTHON" - calllist = [] - self.internal_buildcalllist(argclasses, delegate, calllist) - calllist = tuple(calllist) - try: - result = self.compilation_cache_table[calllist] - except KeyError: - result = self.internal_compilecalllist(calllist) - self.compilation_cache_table[calllist] = result - return result - def internal_compilecalllist(self, calllist): - "NOT_RPYTHON" - source, glob = self.internal_sourcecalllist(calllist) - # compile the function - exec source in glob - return glob['do'] - - def internal_sourcecalllist(self, calllist): - """NOT_RPYTHON - Translate a call list into the source of a Python function - which is optimized and doesn't do repeated conversions on the - same arguments.""" - if len(calllist) == 1: - fn, conversions = calllist[0] - if conversions == ((),) * len(conversions): - # no conversion, just calling a single function: return - # that function directly - return '', {'do': fn} - - #print '**** compile **** ', self.operatorsymbol, [ - # t.__name__ for t in argclasses] - arglist = ['a%d'%i for i in range(self.dispatch_arity)] + ['*extraargs'] - source = ['def do(space,%s):' % ','.join(arglist)] - converted = [{(): ('a%d'%i, False)} for i in range(self.dispatch_arity)] - - def make_conversion(argi, convtuple): - if convtuple in converted[argi]: - return converted[argi][convtuple] - else: - prev, can_fail = make_conversion(argi, convtuple[:-1]) - new = '%s_%d' % (prev, len(converted[argi])) - fname = all_functions.setdefault(convtuple[-1], - 'd%d' % len(all_functions)) - if can_fail: - source.append(' if isinstance(%s, FailedToImplement):' % prev) - source.append(' %s = %s' % (new, prev)) - source.append(' else:') - indent = ' ' - else: - indent = ' ' - source.append('%s%s = %s(space,%s)' % (indent, new, fname, prev)) - can_fail = can_fail or getattr(convtuple[-1], 'can_fail', False) - converted[argi][convtuple] = new, can_fail - return new, can_fail - - all_functions = {} - has_firstfailure = False - for fn, conversions in calllist: - # make the required conversions - fname = all_functions.setdefault(fn, 'f%d' % len(all_functions)) - arglist = [] - failcheck = [] - for i in range(self.dispatch_arity): - argname, can_fail = make_conversion(i, conversions[i]) - arglist.append(argname) - if can_fail: - failcheck.append(argname) - arglist.append('*extraargs') - source.append( ' try:') - for argname in failcheck: - source.append(' if isinstance(%s, FailedToImplement):' % argname) - source.append(' raise %s' % argname) - source.append( ' return %s(space,%s)' % ( - fname, ','.join(arglist))) - if has_firstfailure: - source.append(' except FailedToImplement:') - else: - source.append(' except FailedToImplement, firstfailure:') - has_firstfailure = True - source.append( ' pass') - - # complete exhaustion - if has_firstfailure: - source.append(' raise firstfailure') - else: - source.append(' raise FailedToImplement()') - source.append('') - - glob = {'FailedToImplement': FailedToImplement} - for fn, fname in all_functions.items(): - glob[fname] = fn - return '\n'.join(source), glob - - def internal_buildcalllist(self, argclasses, delegate, calllist): - """NOT_RPYTHON - Build a list of calls to try for the given classes of the - arguments. The list contains 'calls' of the following form: - (function-to-call, list-of-list-of-converters) - The list of converters contains a list of converter functions per - argument, with [] meaning that no conversion is needed for - that argument.""" - # look for an exact match first - arity = self.dispatch_arity - assert arity == len(argclasses) - dispatchclasses = tuple([(c,) for c in argclasses]) - choicelist = self.buildchoices(dispatchclasses) - seen_functions = {} - no_conversion = [()] * arity - for signature, function in choicelist: - calllist.append((function, tuple(no_conversion))) - seen_functions[function] = 1 - - # proceed by expanding the last argument by delegation, step by step - # until no longer possible, and then the previous argument, and so on. - expanded_args = () - expanded_dispcls = () - - for argi in range(arity-1, -1, -1): - # growing tuple of dispatch classes we can delegate to - curdispcls = dispatchclasses[argi] - assert len(curdispcls) == 1 - # maps each dispatch class to a list of converters - curargs = {curdispcls[0]: []} - # reduce dispatchclasses to the arguments before this one - # (on which no delegation has been tried yet) - dispatchclasses = dispatchclasses[:argi] - no_conversion = no_conversion[:argi] - - while 1: - choicelist = delegate.buildchoices((curdispcls,)) - # the list is sorted by priority - progress = False - for (t,), function in choicelist: - if function is None: - # this marks a decrease in the priority. - # Don't try delegators with lower priority if - # we have already progressed. - if progress: - break - else: - assert hasattr(function, 'result_class'), ( - "delegator %r must have a result_class" % function) - nt = function.result_class - if nt not in curargs: - curdispcls += (nt,) - srcconvs = curargs[t] - if not getattr(function, 'trivial_delegation',False): - srcconvs = srcconvs + [function] - curargs[nt] = srcconvs - progress = True - else: - if not progress: - break # no progress, and delegators list exhausted - - # progress: try again to dispatch with this new set of types - choicelist = self.buildchoices( - dispatchclasses + (curdispcls,) + expanded_dispcls) - for signature, function in choicelist: - if function not in seen_functions: - seen_functions[function] = 1 - # collect arguments: arguments after position argi... - after_argi = [tuple(expanded_args[j][signature[j]]) - for j in range(argi+1-arity, 0)] # nb. j<0 - # collect arguments: argument argi... - arg_argi = tuple(curargs[signature[argi]]) - # collect all arguments - newargs = no_conversion + [arg_argi] + after_argi - # record the call - calllist.append((function, tuple(newargs))) - # end of while 1: try on delegating the same argument i - - # proceed to the next argument - expanded_args = (curargs,) + expanded_args - expanded_dispcls = (curdispcls,) + expanded_dispcls - - def buildchoices(self, allowedtypes): - """NOT_RPYTHON - Build a list of all possible implementations we can dispatch to, - sorted best-first, ignoring delegation.""" - # 'types' is a tuple of tuples of classes, one tuple of classes per - # argument. (After delegation, we need to call buildchoice() with - # more than one possible class for a single argument.) - result = [] - self.internal_buildchoices(allowedtypes, (), result) - self.postprocessresult(allowedtypes, result) - #print self.operatorsymbol, allowedtypes, result - # the result is a list a tuples (function, signature). - return result +class FailedToImplement(Exception): + pass - def postprocessresult(self, allowedtypes, result): - "NOT_RPYTHON" - def internal_buildchoices(self, initialtypes, currenttypes, result): - "NOT_RPYTHON" - if len(currenttypes) == self.dispatch_arity: - currenttypes += (W_ANY,) * (self.arity - self.dispatch_arity) - for func in self.dispatch_table.get(currenttypes, []): - if func not in result: # ignore duplicates - result.append((currenttypes, func)) - else: - classtuple = initialtypes[len(currenttypes)] - for nexttype in classtuple: - self.internal_buildchoices(initialtypes, - currenttypes + (nexttype,), - result) +def well_just_complain(*args): + raise FailedToImplement - def is_empty(self): - return not self.dispatch_table +class MultiMethodTable: -class MultiMethod(AbstractMultiMethod): - - def __init__(self, operatorsymbol, arity, specialnames=None, **extras): + def __init__(self, arity, root_class, argnames_before=[], argnames_after=[]): """NOT_RPYTHON: cannot create new multimethods dynamically. - MultiMethod dispatching on the first 'arity' arguments. + MultiMethod-maker dispatching on exactly 'arity' arguments. """ - AbstractMultiMethod.__init__(self, operatorsymbol, arity) if arity < 1: raise ValueError, "multimethods cannot dispatch on nothing" - if specialnames is None: - specialnames = [operatorsymbol] - self.specialnames = specialnames # e.g. ['__xxx__', '__rxxx__'] - self.extras = extras - self.unbound_versions = {} - + self.arity = arity + self.root_class = root_class + self.dispatch_tree = {} + self.argnames_before = argnames_before + self.argnames_after = argnames_after - def __get__(self, space, cls=None): - if space is None: - return self + def register(self, function, *types, **kwds): + try: + order = kwds.pop('order') + except KeyError: + order = 0 + assert not kwds + assert len(types) == self.arity + node = self.dispatch_tree + for type in types[:-1]: + node = node.setdefault(type, {}) + lst = node.setdefault(types[-1], []) + if order >= len(lst): + lst += [None] * (order+1 - len(lst)) + assert lst[order] is None, "duplicate function for %r@%d" % ( + types, order) + lst[order] = function + + def install(self, prefix, list_of_typeorders): + "NOT_RPYTHON: initialization-time only" + assert len(list_of_typeorders) == self.arity + installer = Installer(self, prefix, list_of_typeorders) + if installer.is_empty(): + return well_just_complain else: - return BoundMultiMethod(space, self) + return installer.install() + + # ____________________________________________________________ + # limited dict-like interface to the dispatch table - get = __get__ + def getfunctions(self, types): + assert len(types) == self.arity + node = self.dispatch_tree + for type in types: + node = node[type] + return [fn for fn in node if fn is not None] - def slice(self, typeclass, bound_position=0): - "NOT_RPYTHON" + def has_signature(self, types): try: - return self.unbound_versions[typeclass, bound_position] + self.getfunctions(types) except KeyError: - m = UnboundMultiMethod(self, typeclass, bound_position) - self.unbound_versions[typeclass, bound_position] = m - return m - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - if not AbstractMultiMethod.register(self, function, *types): return False - # register the function into unbound versions that match - for m in self.unbound_versions.values(): - if m.match(types): - AbstractMultiMethod.register(m, function, *types) - return True - - -class DelegateMultiMethod(MultiMethod): - - def __init__(self): - "NOT_RPYTHON: cannot create new multimethods dynamically." - MultiMethod.__init__(self, 'delegate', 1, []) - self.key = object() - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - if not AbstractMultiMethod.register(self, function, *types): - return False - self.key = object() # change the key to force recomputation - return True - - def postprocessresult(self, allowedtypes, result): - "NOT_RPYTHON" - # add delegation from a class to the *first* immediate parent class - # and to W_ANY - arg1types, = allowedtypes - for t in arg1types: - if t.__bases__: - base = t.__bases__[0] - def delegate_to_parent_class(space, a): - return a - delegate_to_parent_class.trivial_delegation = True - delegate_to_parent_class.result_class = base - delegate_to_parent_class.priority = 0 - # hard-wire it at priority 0 - result.append(((t,), delegate_to_parent_class)) - - def delegate_to_any(space, a): - return a - delegate_to_any.trivial_delegation = True - delegate_to_any.result_class = W_ANY - delegate_to_any.priority = -999 - # hard-wire it at priority -999 - result.append(((t,), delegate_to_any)) - - # sort the results in priority order, and insert None marks - # between jumps in the priority values. Higher priority values - # first. - by_priority = {} # classify delegators by priority - for signature, function in result: - assert hasattr(function, 'priority'), ( - "delegator %r must have a priority" % function) - sublist = by_priority.setdefault(function.priority, []) - sublist.append((signature, function)) - delegators = by_priority.items() - delegators.sort() - delegators.reverse() - del result[:] - for priority, sublist in delegators: - if result: - result.append(((None,), None)) - result += sublist - - -class UnboundMultiMethod(AbstractMultiMethod): - - def __init__(self, basemultimethod, typeclass, bound_position=0): - "NOT_RPYTHON: cannot create new multimethods dynamically." - AbstractMultiMethod.__init__(self, - basemultimethod.operatorsymbol, - basemultimethod.arity) - self.basemultimethod = basemultimethod - self.typeclass = typeclass - self.bound_position = bound_position - # get all the already-registered matching functions from parent - for types, functions in basemultimethod.dispatch_table.iteritems(): - if self.match(types): - self.dispatch_table[types] = functions - self.adjust_dispatch_arity(types) - #print basemultimethod.operatorsymbol, typeclass, self.dispatch_table - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - if not AbstractMultiMethod.register(self, function, *types): - return False - # propagate the function registeration to the base multimethod - # and possibly other UnboundMultiMethods - self.basemultimethod.register(function, *types) - return True - - def match(self, types): - "NOT_RPYTHON" - # check if the 'types' signature statically corresponds to the - # restriction of the present UnboundMultiMethod. - # Only accept an exact match; having merely subclass should - # be taken care of by the general look-up rules. - t = types[self.bound_position].typedef - return t is self.typeclass or ( - getattr(t, 'could_also_match', None) is self.typeclass) - - def __get__(self, space, cls=None): - if space is None: - return self else: - return BoundMultiMethod(space, self) + return True - get = __get__ + def signatures(self): + result = [] + def enum_keys(types_so_far, node): + for type, subnode in node.items(): + next_types = types_so_far+(type,) + if isinstance(subnode, dict): + enum_keys(next_types, subnode) + else: + assert len(next_types) == self.arity + result.append(next_types) + enum_keys((), self.dispatch_tree) + return result -class BoundMultiMethod: - ASSERT_BASE_TYPE = object +# ____________________________________________________________ - def __init__(self, space, multimethod): - self.space = space - self.multimethod = multimethod +class Installer: - def __eq__(self, other): - return (self.__class__ == other.__class__ and - self.space == other.space and - self.multimethod == other.multimethod) - - def __ne__(self, other): - return self != other - - def __hash__(self): - return hash((self.__class__, self.space, self.multimethod)) - - def __call__(self, *args): - if len(args) < self.multimethod.arity: - raise TypeError, ("multimethod needs at least %d arguments" % - self.multimethod.arity) - try: - return self.perform_call(*args) - except FailedToImplement, e: - if e.args: - raise OperationError(e.args[0], e.args[1]) - else: - # raise a TypeError for a FailedToImplement - initialtypes = [a.__class__ - for a in args[:self.multimethod.dispatch_arity]] - if len(initialtypes) <= 1: - plural = "" - else: - plural = "s" - debugtypenames = [t.__name__ for t in initialtypes] - message = "unsupported operand type%s for %s (%s)" % ( - plural, self.multimethod.operatorsymbol, - ', '.join(debugtypenames)) - w_value = self.space.wrap(message) - raise OperationError(self.space.w_TypeError, w_value) - - def perform_call(self, *args): - for a in args: - assert isinstance(a, self.ASSERT_BASE_TYPE), ( - "'%s' multimethod got a non-wrapped argument: %r" % ( - self.multimethod.operatorsymbol, a)) - arity = self.multimethod.dispatch_arity - argclasses = tuple([a.__class__ for a in args[:arity]]) - delegate = self.space.delegate.multimethod - fn = self.multimethod.compile_calllist(argclasses, delegate) - return fn(self.space, *args) + def __init__(self, multimethod, prefix, list_of_typeorders): + self.multimethod = multimethod + self.prefix = prefix + self.list_of_typeorders = list_of_typeorders + self.subtree_cache = {} + self.to_install = [] + self.non_empty = self.build_tree([], multimethod.dispatch_tree) + if self.non_empty: + self.perform_call = self.build_function(None, prefix+'perform_call', + None, + [(None, prefix, 0)]) + else: + self.perform_call = well_just_complain def is_empty(self): - return self.multimethod.is_empty() + return not self.non_empty - def __repr__(self): - return ''%(self.multimethod,) + def install(self): + #f = open('LOGFILE', 'a') + #print >> f, '_'*60 + #import pprint + #pprint.pprint(self.list_of_typeorders, f) + for target, funcname, func, source in self.to_install: + if target is not None: + if hasattr(target, funcname) and func is well_just_complain: + continue + #print >> f, target.__name__, funcname + #if source: + # print >> f, source + #else: + # print >> f, '*\n' + setattr(target, funcname, func) + #f.close() + return self.perform_call + + def build_tree(self, types_so_far, dispatch_node): + key = tuple(types_so_far) + if key in self.subtree_cache: + return self.subtree_cache[key] + non_empty = False + typeorder = self.list_of_typeorders[len(types_so_far)] + for next_type in typeorder: + if self.build_single_method(typeorder, types_so_far, next_type, + dispatch_node): + non_empty = True + self.subtree_cache[key] = non_empty + return non_empty + + def build_single_method(self, typeorder, types_so_far, next_type, + dispatch_node): + funcname = '__'.join([self.prefix] + [t.__name__ for t in types_so_far]) + + order = typeorder[next_type] + #order = [(next_type, None)] + order + + things_to_call = [] + for type, conversion in order: + if type not in dispatch_node: + # there is no possible completion of types_so_far+[type] + # that could lead to a registered function. + continue + match = dispatch_node[type] + if isinstance(match, dict): + if self.build_tree(types_so_far+[type], match): + call = funcname + '__' + type.__name__ + call_selfarg_index = len(types_so_far) + 1 + things_to_call.append((conversion, call, + call_selfarg_index)) + else: + for func in match: # list of functions + if func is not None: + things_to_call.append((conversion, func, None)) + + if things_to_call: + funcname = intern(funcname) + self.build_function(next_type, funcname, len(types_so_far), + things_to_call) + return True + else: + return False + def build_function(self, target, funcname, func_selfarg_index, + things_to_call): + # support for inventing names for the entries in things_to_call + # which are real function objects instead of strings + miniglobals = {'FailedToImplement': FailedToImplement} + def invent_name(obj): + if isinstance(obj, str): + return obj + name = obj.__name__ + n = 1 + while name in miniglobals: + n += 1 + name = '%s%d' % (obj.__name__, n) + miniglobals[name] = obj + return name + + funcargs = ['arg%d' % i for i in range(self.multimethod.arity)] + + bodylines = [] + for conversion, call, call_selfarg_index in things_to_call: + callargs = funcargs[:] + if conversion is not None: + to_convert = func_selfarg_index + callargs[to_convert] = '%s(%s)' % ( + invent_name(conversion), callargs[to_convert]) + callname = invent_name(call) + if call_selfarg_index is not None: + self.to_install.append((self.multimethod.root_class, + callname, + well_just_complain, + None)) + callname = '%s.%s' % (callargs.pop(call_selfarg_index), callname) + callargs = (self.multimethod.argnames_before + + callargs + self.multimethod.argnames_after) + bodylines.append('return %s(%s)' % (callname, ', '.join(callargs))) + + # protect all lines apart from the last one by a try:except: + for i in range(len(bodylines)-2, -1, -1): + bodylines[i:i+1] = ['try:', + ' ' + bodylines[i], + 'except FailedToImplement:', + ' pass'] -class error(Exception): - "Thrown to you when you do something wrong with multimethods." + # indent mode + bodylines = [' ' + line for line in bodylines] + + if func_selfarg_index is not None: + selfargs = [funcargs.pop(func_selfarg_index)] + else: + selfargs = [] + funcargs = (selfargs + self.multimethod.argnames_before + + funcargs + self.multimethod.argnames_after) + bodylines.insert(0, 'def %s(%s):' % (funcname, ', '.join(funcargs))) + bodylines.append('') + source = '\n'.join(bodylines) + exec source in miniglobals + func = miniglobals[funcname] + self.to_install.append((target, funcname, func, source)) + return func Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/noneobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/noneobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/noneobject.py Sun Feb 6 20:38:08 2005 @@ -8,10 +8,11 @@ class W_NoneObject(W_Object): from pypy.objspace.std.nonetype import none_typedef as typedef -registerimplementation(W_NoneObject) -def unwrap__None(space, w_none): - return None + def unwrap(w_self): + return None + +registerimplementation(W_NoneObject) def nonzero__None(space, w_none): return space.w_False Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py Sun Feb 6 20:38:08 2005 @@ -1,36 +1,15 @@ from pypy.objspace.std.register_all import register_all -from pypy.interpreter.baseobjspace import * +from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable +from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import get_unique_interplevel_subclass from pypy.interpreter.typedef import instantiate from pypy.tool.cache import Cache -from pypy.objspace.std.multimethod import * +from pypy.objspace.std.model import W_Object, W_ANY, MultiMethod, StdTypeModel +from pypy.objspace.std.multimethod import FailedToImplement from pypy.objspace.descroperation import DescrOperation from pypy.objspace.std import stdtypedef import types -class W_Object(W_Root, object): - "Parent base class for wrapped objects." - typedef = None - - def __init__(w_self, space): - w_self.space = space # XXX not sure this is ever used any more - - def __repr__(self): - s = '%s(%s)' % ( - self.__class__.__name__, - #', '.join(['%s=%r' % keyvalue for keyvalue in self.__dict__.items()]) - getattr(self, 'name', '') - ) - if hasattr(self, 'w__class__'): - s += ' instance of %s' % self.w__class__ - return '<%s>' % s - -# delegation priorities -PRIORITY_SAME_TYPE = 2 # converting between several impls of the same type -PRIORITY_PARENT_TYPE = 1 # converting to a base type (e.g. bool -> int) -PRIORITY_PARENT_IMPL = 0 # hard-wired in multimethod.py (W_IntObject->W_Object) -PRIORITY_CHANGE_TYPE = -1 # changing type altogether (e.g. int -> float) -PRIORITY_ANY = -999 # hard-wired in multimethod.py (... -> W_ANY) def registerimplementation(implcls): # this function should ultimately register the implementation class somewhere @@ -47,139 +26,25 @@ PACKAGE_PATH = 'objspace.std' - def standard_types(self): - "NOT_RPYTHON: only for initializing the space." - class result: - "Import here the types you want to have appear in __builtin__." - - from pypy.objspace.std.objecttype import object_typedef - from pypy.objspace.std.booltype import bool_typedef - from pypy.objspace.std.inttype import int_typedef - from pypy.objspace.std.floattype import float_typedef - from pypy.objspace.std.tupletype import tuple_typedef - from pypy.objspace.std.listtype import list_typedef - from pypy.objspace.std.dicttype import dict_typedef - from pypy.objspace.std.basestringtype import basestring_typedef - from pypy.objspace.std.stringtype import str_typedef - from pypy.objspace.std.typetype import type_typedef - from pypy.objspace.std.slicetype import slice_typedef - from pypy.objspace.std.longtype import long_typedef - from pypy.objspace.std.unicodetype import unicode_typedef - return [value for key, value in result.__dict__.items() - if not key.startswith('_')] # don't look - - def clone_exception_hierarchy(self): - "NOT_RPYTHON: only for initializing the space." - from pypy.objspace.std.typeobject import W_TypeObject - from pypy.interpreter import gateway - w = self.wrap - def app___init__(self, *args): - self.args = args - w_init = w(gateway.app2interp(app___init__)) - def app___str__(self): - l = len(self.args) - if l == 0: - return '' - elif l == 1: - return str(self.args[0]) - else: - return str(self.args) - w_str = w(gateway.app2interp(app___str__)) - import exceptions - - # to create types, we should call the standard type object; - # but being able to do that depends on the existence of some - # of the exceptions... - - self.w_Exception = W_TypeObject( - self, - 'Exception', - [self.w_object], - {'__init__': w_init, - '__str__': w_str}, - ) - done = {'Exception': self.w_Exception} - - # some of the complexity of the following is due to the fact - # that we need to create the tree root first, but the only - # connections we have go in the inconvenient direction... - - for k in dir(exceptions): - if k not in done: - v = getattr(exceptions, k) - if not isinstance(v, type(Exception)): - continue - if not issubclass(v, Exception): - continue - stack = [k] - while stack: - next = stack[-1] - if next not in done: - v = getattr(exceptions, next) - b = v.__bases__[0] - if b.__name__ not in done: - stack.append(b.__name__) - continue - else: - base = done[b.__name__] - newtype = W_TypeObject( - self, - next, - [base], - {}, - ) - setattr(self, - 'w_' + next, - newtype) - done[next] = newtype - stack.pop() - else: - stack.pop() - return done - def initialize(self): "NOT_RPYTHON: only for initializing the space." self._typecache = Cache() - # The object implementations that we want to 'link' into PyPy must be - # imported here. This registers them into the multimethod tables, - # *before* the type objects are built from these multimethod tables. - from pypy.objspace.std import objectobject - from pypy.objspace.std import boolobject - from pypy.objspace.std import intobject - from pypy.objspace.std import floatobject - from pypy.objspace.std import tupleobject - from pypy.objspace.std import listobject - from pypy.objspace.std import dictobject - from pypy.objspace.std import stringobject - from pypy.objspace.std import typeobject - from pypy.objspace.std import sliceobject - from pypy.objspace.std import longobject - from pypy.objspace.std import noneobject - from pypy.objspace.std import iterobject - from pypy.objspace.std import unicodeobject - from pypy.objspace.std import fake + # Import all the object types and implementations + self.model = StdTypeModel() + + # install all the MultiMethods into the space instance + for name, mm in self.MM.__dict__.items(): + if isinstance(mm, MultiMethod) and not hasattr(self, name): + func = mm.install_not_sliced(self.model.typeorder) + # e.g. add(space, w_x, w_y) + boundmethod = func.__get__(self) # bind the 'space' argument + setattr(self, name, boundmethod) # store into 'space' instance + # hack to avoid imports in the time-critical functions below - global W_ObjectObject, W_BoolObject, W_IntObject, W_FloatObject - global W_TupleObject, W_ListObject, W_DictObject, W_StringObject - global W_TypeObject, W_SliceObject, W_LongObject, W_NoneObject - global W_SeqIterObject, W_UnicodeObject, fake_type - W_ObjectObject = objectobject.W_ObjectObject - W_BoolObject = boolobject.W_BoolObject - W_IntObject = intobject.W_IntObject - W_FloatObject = floatobject.W_FloatObject - W_TupleObject = tupleobject.W_TupleObject - W_ListObject = listobject.W_ListObject - W_DictObject = dictobject.W_DictObject - W_StringObject = stringobject.W_StringObject - W_TypeObject = typeobject.W_TypeObject - W_SliceObject = sliceobject.W_SliceObject - W_LongObject = longobject.W_LongObject - W_NoneObject = noneobject.W_NoneObject - W_SeqIterObject = iterobject.W_SeqIterObject - W_UnicodeObject = unicodeobject.W_UnicodeObject - fake_type = fake.fake_type - # end of hacks + for cls in self.model.typeorder: + globals()[cls.__name__] = cls + # singletons self.w_None = W_NoneObject(self) self.w_False = W_BoolObject(self, False) @@ -193,12 +58,11 @@ "None" : self.w_None, "NotImplemented": self.w_NotImplemented, "Ellipsis": self.w_Ellipsis, -# "long": self.wrap(long), # XXX temporary } # types self.types_w = {} - for typedef in self.standard_types(): + for typedef in self.model.pythontypes: w_type = self.gettypeobject(typedef) setattr(self, 'w_' + typedef.name, w_type) for_builtins[typedef.name] = w_type @@ -206,9 +70,17 @@ # dummy old-style classes types self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {}) self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {}) - + # exceptions - ##for_builtins.update(self.clone_exception_hierarchy()) + mod = self.setup_exceptions(for_builtins) + + # install things in the __builtin__ module + self.make_builtins(for_builtins) + + w_exceptions = self.wrap(mod) + self.sys.setbuiltinmodule(w_exceptions, 'exceptions') + + def setup_exceptions(self, for_builtins): ## hacking things in from pypy.module import exceptionsinterp as ex def call(w_type, w_args): @@ -237,15 +109,10 @@ self.setitem(w_dic, self.wrap("__doc__"), ex.__doc__) finally: del self.call # revert to the class' method - - self.make_builtins(for_builtins) # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module - - m = Module(self, self.wrap("exceptions"), w_dic) - w_exceptions = self.wrap(m) - self.sys.setbuiltinmodule(w_exceptions, 'exceptions') + return Module(self, self.wrap("exceptions"), w_dic) def gettypeobject(self, typedef): # types_w maps each StdTypeDef instance to its @@ -298,7 +165,8 @@ if hasattr(self, 'w_' + x.__name__): w_result = getattr(self, 'w_' + x.__name__) assert isinstance(w_result, W_TypeObject) - return w_result + return w_result + from fake import fake_type if isinstance(x, type): ft = fake_type(x) return self.gettypeobject(ft.typedef) @@ -306,6 +174,11 @@ return ft(self, x) wrap._specialize_ = "argtypes" + def unwrap(self, w_obj): + if isinstance(w_obj, BaseWrappable): + return w_obj + return w_obj.unwrap() + def newint(self, intval): return W_IntObject(self, intval) @@ -367,31 +240,6 @@ len(t), expected_length) return t - - class MM: - "Container for multimethods." - #is_data_descr = MultiMethod('is_data_descr', 1, []) # returns an unwrapped bool - #getdict = MultiMethod('getdict', 1, []) # get '.__dict__' attribute - next = MultiMethod('next', 1, ['next']) # iterator interface - call = MultiMethod('call', 1, ['__call__'], varargs=True, keywords=True) - #getattribute = MultiMethod('getattr', 2, ['__getattribute__']) # XXX hack - # special visible multimethods - delegate = DelegateMultiMethod() # delegators - int_w = MultiMethod('int_w', 1, []) # returns an unwrapped int - str_w = MultiMethod('str_w', 1, []) # returns an unwrapped string - float_w = MultiMethod('float_w', 1, []) # returns an unwrapped float - unwrap = MultiMethod('unwrap', 1, []) # returns an unwrapped object - issubtype = MultiMethod('issubtype', 2, []) - id = MultiMethod('id', 1, []) - init = MultiMethod('__init__', 1, varargs=True, keywords=True) - - int_w = MM.int_w - str_w = MM.str_w - float_w = MM.float_w - unwrap = MM.unwrap - delegate = MM.delegate - #is_true = MM.is_true - def is_(self, w_one, w_two): # XXX a bit of hacking to gain more speed if w_one is w_two: @@ -405,20 +253,21 @@ else: return DescrOperation.is_true(self, w_obj) -# add all regular multimethods to StdObjSpace -for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: - if not hasattr(StdObjSpace.MM, _name): - if _name == 'pow': - mm = MultiMethod(_symbol, _arity, _specialnames, defaults=(None,)) - else: - mm = MultiMethod(_symbol, _arity, _specialnames) - setattr(StdObjSpace.MM, _name, mm) - if not hasattr(StdObjSpace, _name): - setattr(StdObjSpace, _name, getattr(StdObjSpace.MM, _name)) - -# import the common base W_ObjectObject as well as -# default implementations of some multimethods for all objects -# that don't explicitly override them or that raise FailedToImplement -from pypy.objspace.std.register_all import register_all -import pypy.objspace.std.objectobject -import pypy.objspace.std.default + + class MM: + "Container for multimethods." + call = MultiMethod('call', 1, ['__call__'], general__args__=True) + init = MultiMethod('__init__', 1, general__args__=True) + # special visible multimethods + int_w = MultiMethod('int_w', 1, []) # returns an unwrapped int + str_w = MultiMethod('str_w', 1, []) # returns an unwrapped string + float_w = MultiMethod('float_w', 1, []) # returns an unwrapped float + + # add all regular multimethods here + for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: + if _name not in locals(): + mm = MultiMethod(_symbol, _arity, _specialnames) + locals()[_name] = mm + del mm + + pow.extras['defaults'] = (None,) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/register_all.py ============================================================================== --- pypy/dist/pypy/objspace/std/register_all.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/register_all.py Sun Feb 6 20:38:08 2005 @@ -74,17 +74,17 @@ def op_negated(function): - def op(space, w_1, w_2, function=function): + def op(space, w_1, w_2): return space.not_(function(space, w_1, w_2)) return op def op_swapped(function): - def op(space, w_1, w_2, function=function): + def op(space, w_1, w_2): return function(space, w_2, w_1) return op def op_swapped_negated(function): - def op(space, w_1, w_2, function=function): + def op(space, w_1, w_2): return space.not_(function(space, w_2, w_1)) return op @@ -110,16 +110,17 @@ table, thus favouring swapping the arguments over negating the result. """ from pypy.objspace.std.objspace import StdObjSpace, W_ANY - originaltable = {} + originalentries = {} for op in OPERATORS: - originaltable[op] = getattr(StdObjSpace.MM, op).dispatch_table.copy() + originalentries[op] = getattr(StdObjSpace.MM, op).signatures() for op1, op2, correspondance in OP_CORRESPONDANCES: mirrorfunc = getattr(StdObjSpace.MM, op2) - for types, functions in originaltable[op1].iteritems(): + for types in originalentries[op1]: t1, t2 = types if t1 is t2: - if types not in mirrorfunc.dispatch_table: + if not mirrorfunc.has_signature(types): + functions = getattr(StdObjSpace.MM, op1).getfunctions(types) assert len(functions) == 1, ('Automatic' ' registration of comparison functions' ' only work when there is a single method for' Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/sliceobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/sliceobject.py Sun Feb 6 20:38:08 2005 @@ -18,6 +18,10 @@ w_self.w_stop = w_stop w_self.w_step = w_step + def unwrap(w_slice): + space = w_slice.space + return slice(space.unwrap(w_slice.w_start), space.unwrap(w_slice.w_stop), space.unwrap(w_slice.w_step)) + registerimplementation(W_SliceObject) def app_repr__Slice(aslice): @@ -43,7 +47,4 @@ raise OperationError(space.w_TypeError, space.wrap("unhashable type")) -def unwrap__Slice(space, w_slice): - return slice(space.unwrap(w_slice.w_start), space.unwrap(w_slice.w_stop), space.unwrap(w_slice.w_step)) - register_all(vars()) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py Sun Feb 6 20:38:08 2005 @@ -1,7 +1,8 @@ from pypy.interpreter import eval, function, gateway from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import TypeDef, GetSetProperty, Member -from pypy.objspace.std.multimethod import MultiMethod, FailedToImplement +from pypy.objspace.std.model import MultiMethod, FailedToImplement +from pypy.objspace.std.multimethod import well_just_complain __all__ = ['StdTypeDef', 'newmethod', 'gateway', 'GetSetProperty', 'Member', 'attrproperty', 'attrproperty_w', @@ -24,9 +25,9 @@ if b is object_typedef: return True while a is not b: - a = a.base if a is None: return False + a = a.base return True def attrproperty(name): @@ -77,16 +78,11 @@ if isinstance(typedef, StdTypeDef): # get all the sliced multimethods - multimethods = slicemultimethods(space.__class__, typedef) - for name, code in multimethods.items(): - # compute the slice and ignore the multimethod if empty - if not code.computeslice(space): - continue - # create a Function around the sliced multimethod code - fn = function.Function(space, code, defs_w=code.getdefaults(space)) + multimethods = slicemultimethods(space, typedef) + for name, gateway in multimethods.items(): assert name not in rawdict, 'name clash: %s in %s_typedef' % ( name, typedef.name) - rawdict[name] = fn + rawdict[name] = gateway # compute the bases if typedef is object_typedef: @@ -111,150 +107,244 @@ result.append(value) return result -def make_frameclass_for_arity(arity, varargs, keywords, isspecial): - argnames = [] - for i in range(arity): - argnames.append('arg%dof%d'%(i+1, arity)) - if varargs: - argnames.append('var_args') - if keywords: - argnames.append('kw_args') - self_args_assigning = [] - for i in range(len(argnames)): - self_args_assigning.append(' self.%s = args[%i]'%(argnames[i], i)) - self_args_assigning = "\n".join(self_args_assigning) - self_args = ", ".join(['self.'+ a for a in argnames]) - name = 'MmFrameOfArity%d'%arity - if varargs: - name += "Var" - if keywords: - name += "KW" - if isspecial: - name = "Special" + name - d = locals() - template = mmtemplate - if isspecial: - template += specialmmruntemplate +##def make_frameclass_for_arity(arity, varargs, keywords, isspecial): +## argnames = [] +## for i in range(arity): +## argnames.append('arg%dof%d'%(i+1, arity)) +## if varargs: +## argnames.append('var_args') +## if keywords: +## argnames.append('kw_args') +## self_args_assigning = [] +## for i in range(len(argnames)): +## self_args_assigning.append(' self.%s = args[%i]'%(argnames[i], i)) +## self_args_assigning = "\n".join(self_args_assigning) +## self_args = ", ".join(['self.'+ a for a in argnames]) +## name = 'MmFrameOfArity%d'%arity +## if varargs: +## name += "Var" +## if keywords: +## name += "KW" +## if isspecial: +## name = "Special" + name +## d = locals() +## template = mmtemplate +## if isspecial: +## template += specialmmruntemplate +## else: +## template += mmruntemplate +### print template%d +## exec template%d in globals(), d +## return d[name] +## +##_frameclass_for_arity_cache = {} +##def frameclass_for_arity(arity, varargs, keywords, isspecial): +## try: +## return _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] +## except KeyError: +## r = _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] = \ +## make_frameclass_for_arity(arity, varargs, keywords, isspecial) +## return r + + +def sliced_typeorders(typeorder, multimethod, typedef, i): + list_of_typeorders = [typeorder] * multimethod.arity + prefix = '__mm_' + multimethod.name + if typedef is not None: + # slice + sliced_typeorder = {} + for type, order in typeorder.items(): + thistypedef = getattr(type, 'typedef', None) + if issubtypedef(thistypedef, typedef): + lst = [] + for target_type, conversion in order: + targettypedef = getattr(target_type, 'typedef', None) + if targettypedef == typedef: + lst.append((target_type, conversion)) + sliced_typeorder[type] = lst + list_of_typeorders[i] = sliced_typeorder + prefix += '_%sS%d' % (typedef.name, i) + return prefix, list_of_typeorders + +def typeerrormsg(space, operatorsymbol, args_w): + print "AAAARGH", operatorsymbol, args_w + return space.wrap("XXX insert message here") + +def wrap_func_in_trampoline(func, multimethod, selfindex=0): + # mess to figure out how to put a gateway around 'func' + argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] + explicit_argnames = multimethod.extras.get('argnames', []) + argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames + # XXX do something about __call__ and __init__ which still use + # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w + solid_arglist = ['w_'+name for name in argnames] + wrapper_arglist = solid_arglist[:] + if multimethod.extras.get('varargs', False): + wrapper_arglist.append('args_w') + if multimethod.extras.get('keywords', False): + raise Exception, "no longer supported, use __args__" + if multimethod.extras.get('general__args__', False): + wrapper_arglist.append('__args__') + + miniglobals = {'perform_call': func, + 'OperationError': OperationError, + 'FailedToImplement': FailedToImplement, + 'typeerrormsg': typeerrormsg} + app_defaults = multimethod.extras.get('defaults', ()) + i = len(argnames) - len(app_defaults) + wrapper_signature = wrapper_arglist[:] + for app_default in app_defaults: + name = wrapper_signature[i] + wrapper_signature[i] = '%s=%s' % (name, name) + miniglobals[name] = app_default + i += 1 + + wrapper_signature.insert(0, wrapper_signature.pop(selfindex)) + wrapper_sig = ', '.join(wrapper_signature) + wrapper_args = ', '.join(wrapper_arglist) + if len(multimethod.specialnames) > 1: + # turn FailedToImplement into NotImplemented + code = """def trampoline(space, %s): + try: + return perform_call(space, %s) + except FailedToImplement, e: + if e.args: + raise OperationError(e.args[0], e.args[1]) + else: + return space.w_NotImplemented +""" % (wrapper_sig, wrapper_args) else: - template += mmruntemplate -# print template%d - exec template%d in globals(), d - return d[name] - -_frameclass_for_arity_cache = {} -def frameclass_for_arity(arity, varargs, keywords, isspecial): - try: - return _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] - except KeyError: - r = _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] = \ - make_frameclass_for_arity(arity, varargs, keywords, isspecial) - return r + # turn FailedToImplement into nice TypeErrors + code = """def trampoline(space, %s): + try: + w_res = perform_call(space, %s) + except FailedToImplement, e: + if e.args: + w_type = e.args[0] + w_value = e.args[1] + else: + w_value = typeerrormsg(space, %r, [%s]) + w_type = space.w_TypeError + raise OperationError(w_type, w_value) + if w_res is None: + w_res = space.w_None + return w_res +""" % (wrapper_sig, wrapper_args, + multimethod.operatorsymbol, ', '.join(solid_arglist)) + exec code in miniglobals + return miniglobals['trampoline'] + +def wrap_trampoline_in_gateway(func, methname, multimethod): + unwrap_spec = [gateway.ObjSpace] + [gateway.W_Root]*multimethod.arity + if multimethod.extras.get('varargs', False): + unwrap_spec.append('args_w') + if multimethod.extras.get('general__args__', False): + unwrap_spec.append(gateway.Arguments) + return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) -def slicemultimethod(multimethod, typeclass, result): +def slicemultimethod(space, multimethod, typedef, result): + from pypy.objspace.std.objecttype import object_typedef for i in range(len(multimethod.specialnames)): # each MultimethodCode embeds a multimethod - name = multimethod.specialnames[i] - if name in result: + methname = multimethod.specialnames[i] + if methname in result: # conflict between e.g. __lt__ and # __lt__-as-reversed-version-of-__gt__ - code = result[name] - if code.bound_position < i: + gw = result[methname] + if gw.bound_position < i: continue - mmframeclass = frameclass_for_arity(multimethod.arity, - multimethod.extras.get('varargs', False), - multimethod.extras.get('keywords', False), - len(multimethod.specialnames) > 1) - code = MultimethodCode(multimethod, mmframeclass, typeclass, i) - result[name] = code -def slicemultimethods(spaceclass, typeclass): + prefix, list_of_typeorders = sliced_typeorders( + space.model.typeorder, multimethod, typedef, i) + func = multimethod.install(prefix, list_of_typeorders) + if func is well_just_complain: + continue # skip empty multimethods + trampoline = wrap_func_in_trampoline(func, multimethod, i) + gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) + gw.bound_position = i # for the check above + result[methname] = gw + +def slicemultimethods(space, typedef): result = {} # import and slice all multimethods of the space.MM container - for multimethod in hack_out_multimethods(spaceclass.MM.__dict__): - slicemultimethod(multimethod, typeclass, result) + for multimethod in hack_out_multimethods(space.MM.__dict__): + slicemultimethod(space, multimethod, typedef, result) # import all multimethods defined directly on the type without slicing - for multimethod in typeclass.local_multimethods: - slicemultimethod(multimethod, None, result) + for multimethod in typedef.local_multimethods: + slicemultimethod(space, multimethod, None, result) return result -class MultimethodCode(eval.Code): - """A code object that invokes a multimethod.""" +##class MultimethodCode(eval.Code): +## """A code object that invokes a multimethod.""" - def __init__(self, multimethod, framecls, typeclass, bound_position=0): - "NOT_RPYTHON: initialization-time only." - eval.Code.__init__(self, multimethod.operatorsymbol) - self.basemultimethod = multimethod - self.typeclass = typeclass - self.bound_position = bound_position - self.framecls = framecls - argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] - explicit_argnames = multimethod.extras.get('argnames', []) - argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames - varargname = kwargname = None - # XXX do something about __call__ and __init__ which still use - # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w - if multimethod.extras.get('varargs', False): - varargname = 'args' - if multimethod.extras.get('keywords', False): - kwargname = 'keywords' - self.sig = argnames, varargname, kwargname - - def computeslice(self, space): - "NOT_RPYTHON: initialization-time only." - if self.typeclass is None: - slice = self.basemultimethod - else: - slice = self.basemultimethod.slice(self.typeclass, - self.bound_position) - if slice.is_empty(): - return False - else: - self.mm = slice.get(space) - return True - - def signature(self): - return self.sig - - def getdefaults(self, space): - return [space.wrap(x) - for x in self.basemultimethod.extras.get('defaults', ())] - - def create_frame(self, space, w_globals, closure=None): - return self.framecls(space, self) - -mmtemplate = """ -class %(name)s(eval.Frame): - - def setfastscope(self, scope_w): - args = list(scope_w) - args.insert(0, args.pop(self.code.bound_position)) -%(self_args_assigning)s - - def getfastscope(self): - raise OperationError(self.space.w_TypeError, - self.space.wrap("cannot get fastscope of a MmFrame")) -""" - -mmruntemplate = """ - def run(self): - "Call the multimethod, raising a TypeError if not implemented." - w_result = self.code.mm(%(self_args)s) - # we accept a real None from operations with no return value - if w_result is None: - w_result = self.space.w_None - return w_result -""" - -specialmmruntemplate = """ - - def run(self): - "Call the multimethods, possibly returning a NotImplemented." - try: - return self.code.mm.perform_call(%(self_args)s) - except FailedToImplement, e: - if e.args: - raise OperationError(e.args[0], e.args[1]) - else: - return self.space.w_NotImplemented +## def __init__(self, multimethod, framecls, typeclass, bound_position=0): +## "NOT_RPYTHON: initialization-time only." +## eval.Code.__init__(self, multimethod.operatorsymbol) +## self.basemultimethod = multimethod +## self.typeclass = typeclass +## self.bound_position = bound_position +## self.framecls = framecls +## argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] +## explicit_argnames = multimethod.extras.get('argnames', []) +## argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames +## varargname = kwargname = None +## # XXX do something about __call__ and __init__ which still use +## # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w +## if multimethod.extras.get('varargs', False): +## varargname = 'args' +## if multimethod.extras.get('keywords', False): +## kwargname = 'keywords' +## self.sig = argnames, varargname, kwargname + +## def computeslice(self, space): +## "NOT_RPYTHON: initialization-time only." +## self.mm = self.basemultimethod.__get__(space, slice=( +## self.typeclass, self.bound_position)) +## return not self.mm.is_empty() + +## def signature(self): +## return self.sig + +## def getdefaults(self, space): +## return [space.wrap(x) +## for x in self.basemultimethod.extras.get('defaults', ())] + +## def create_frame(self, space, w_globals, closure=None): +## return self.framecls(space, self) + +##mmtemplate = """ +##class %(name)s(eval.Frame): + +## def setfastscope(self, scope_w): +## args = list(scope_w) +## args.insert(0, args.pop(self.code.bound_position)) +##%(self_args_assigning)s + +## def getfastscope(self): +## raise OperationError(self.space.w_TypeError, +## self.space.wrap("cannot get fastscope of a MmFrame")) +##""" + +##mmruntemplate = """ +## def run(self): +## "Call the multimethod, raising a TypeError if not implemented." +## w_result = self.code.mm(%(self_args)s) +## # we accept a real None from operations with no return value +## if w_result is None: +## w_result = self.space.w_None +## return w_result +##""" + +##specialmmruntemplate = """ + +## def run(self): +## "Call the multimethods, possibly returning a NotImplemented." +## try: +## return self.code.mm.perform_call(%(self_args)s) +## except FailedToImplement, e: +## if e.args: +## raise OperationError(e.args[0], e.args[1]) +## else: +## return self.space.w_NotImplemented -""" +##""" Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py Sun Feb 6 20:38:08 2005 @@ -14,7 +14,6 @@ def ord__String(space, w_str): def string_richcompare(space, w_str1, w_str2, op): def str_w__String(space, w_str): - def unwrap__String(space, w_str): __add__ def add__String_String(space, w_left, w_right): __class__ __contains__ @@ -100,6 +99,9 @@ """ representation for debugging purposes """ return "%s(%r)" % (w_self.__class__.__name__, w_self._value) + def unwrap(w_self): + return w_self._value + registerimplementation(W_StringObject) @@ -767,9 +769,6 @@ def str_w__String(space, w_str): return w_str._value - -def unwrap__String(space, w_str): - return w_str._value def hash__String(space, w_str): w_hash = w_str.w_hash Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringtype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringtype.py Sun Feb 6 20:38:08 2005 @@ -39,15 +39,12 @@ # ____________________________________________________________ -def descr__new__(space, w_stringtype, w_obj=None): +def descr__new__(space, w_stringtype, w_obj=''): from pypy.objspace.std.stringobject import W_StringObject - if w_obj is None: - value = '' - else: - w_obj = space.str(w_obj) - if space.is_true(space.is_(w_stringtype, space.w_str)): - return w_obj # XXX might be reworked when space.str() typechecks - value = space.str_w(w_obj) + w_obj = space.str(w_obj) + if space.is_true(space.is_(w_stringtype, space.w_str)): + return w_obj # XXX might be reworked when space.str() typechecks + value = space.str_w(w_obj) w_obj = space.allocate_instance(W_StringObject, w_stringtype) w_obj.__init__(space, value) return w_obj Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_multimethod.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py Sun Feb 6 20:38:08 2005 @@ -1,145 +1,65 @@ import autopath +from py.test import raises from pypy.objspace.std.multimethod import * -BoundMultiMethod.ASSERT_BASE_TYPE = object +class W_Root(object): + pass -objspacename = 'std' +class W_IntObject(W_Root): + pass -class X: - def __init__(self, value): - self.value = value - def __repr__(self): - return '' % self.value - -def from_y_to_x(space, yinstance): - return X(yinstance) - -from_y_to_x.result_class = X -from_y_to_x.priority = 2 - -def from_x_to_str(space, xinstance): - #if xinstance.value: - return w('!' + repr(xinstance.value)) - #else: - # return [] - -from_x_to_str.result_class = str -from_x_to_str.priority = 2 - - -class Y: - def __init__(self, value): - self.value = value - def __repr__(self): - return '' % self.value - def __nonzero__(self): - return self.value != 666 - - -def add_x_x(space, x1, x2): - return "add_x_x", x1, x2 - -def add_x_y(space, x1, y2): - if x1.value < 0: - raise FailedToImplement(ValueError, 'not good') - return "add_x_y", x1, y2 - -def add_y_y(space, y1, y2): - return "add_y_y", y1, y2 - -def add_string_string(space, x, y): - return "add_string_string", x, y - -def add_int_string(space, x, y): - return "add_int_string", x, y - -def add_int_any(space, y1, o2): - return "add_int_any", y1, o2 - -class FakeObjSpace: - add = MultiMethod('+', 2, []) - add.register(add_x_x, X, X) - add.register(add_x_y, X, Y) - add.register(add_y_y, Y, Y) - add.register(add_string_string, str, str) - add.register(add_int_string, int, str) - add.register(add_int_any, int, object) - - delegate = DelegateMultiMethod() - delegate.register(from_y_to_x, Y) - delegate.register(from_x_to_str, X) - - def wrap(self, x): - return '' % (x,) - w_TypeError = 'w_TypeError' - -##def w(x, cache={}): -## if type(x) in cache: -## Stub = cache[type(x)] -## else: -## Stub = type(type(x))('%s_stub' % type(x).__name__, (type(x),), {}) -## Stub.dispatchclass = Stub -## cache[type(x)] = Stub -## return Stub(x) - -##X.dispatchclass = X -##Y.dispatchclass = Y - -def w(x): - return x - - -class TestMultiMethod: - def setup_method(self,method): - # only run when testing stdobjectspace - #XXX removed: self.space - self.space = FakeObjSpace() - - def test_non_delegate(self): - space = self.space - - r = space.add(X(2), X(5)) - assert repr(r) == "('add_x_x', , )" - - r = space.add(X(3), Y(4)) - assert repr(r) == "('add_x_y', , )" - - r = space.add(Y(0), Y(20)) - assert repr(r) == "('add_y_y', , )" - - r = space.add(w(-3), w([7,6,5])) - assert repr(r) == "('add_int_any', -3, [7, 6, 5])" - - r = space.add(w(5), w("test")) - assert repr(r) == "('add_int_string', 5, 'test')" - - r = space.add(w("x"), w("y")) - assert repr(r) == "('add_string_string', 'x', 'y')" - - def test_delegate_y_to_x(self): - space = self.space - r = space.add(Y(-1), X(7)) - assert repr(r) == "('add_x_x', >, )" - - r = space.add(Y(1), X(7)) - assert repr(r) == "('add_x_x', >, )" - - r = space.add(X(-3), Y(20)) - assert repr(r) == "('add_x_x', , >)" - - def test_no_operation_defined(self): - space = self.space - raises(OperationError, space.add, w([3]), w(4)) - raises(OperationError, space.add, w(3.0), w('bla')) - #raises(OperationError, space.add, X(0), w("spam")) - #raises(OperationError, space.add, Y(666), w("egg")) - - def test_delegate_x_to_str(self): - space = self.space - r = space.add(X(42), w("spam")) - assert repr(r) == "('add_string_string', '!42', 'spam')" +class W_BoolObject(W_Root): + pass - r = space.add(Y(20), w("egg")) - assert repr(r) == "('add_string_string', '!', 'egg')" +class W_StringObject(W_Root): + pass + +def delegate_b2i(w_x): + assert isinstance(w_x, W_BoolObject) + return W_IntObject() + +add = MultiMethodTable(2, root_class=W_Root, argnames_before=['space']) + +def add__Int_Int(space, w_x, w_y): + assert space == 'space' + assert isinstance(w_x, W_IntObject) + assert isinstance(w_y, W_IntObject) + return 'fine' + +add.register(add__Int_Int, W_IntObject, W_IntObject) + + +def setup_module(mod): + typeorder = { + W_IntObject: [(W_IntObject, None)], + W_BoolObject: [(W_BoolObject, None), (W_IntObject, delegate_b2i)], + W_StringObject: [(W_StringObject, None)], + } + mod.add1 = add.install('__add', [typeorder, typeorder]) + + +def test_simple(): + space = 'space' + w_x = W_IntObject() + w_y = W_IntObject() + assert add1(space, w_x, w_y) == 'fine' + +def test_failtoimplement(): + space = 'space' + w_x = W_IntObject() + w_s = W_StringObject() + raises(FailedToImplement, "add1(space, w_x, w_s)") + raises(FailedToImplement, "add1(space, w_s, w_x)") + +def test_delegate(): + space = 'space' + w_x = W_IntObject() + w_s = W_StringObject() + w_b = W_BoolObject() + assert add1(space, w_x, w_b) == 'fine' + assert add1(space, w_b, w_x) == 'fine' + assert add1(space, w_b, w_b) == 'fine' + raises(FailedToImplement, "add1(space, w_b, w_s)") + raises(FailedToImplement, "add1(space, w_s, w_b)") Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupleobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py Sun Feb 6 20:38:08 2005 @@ -16,13 +16,14 @@ reprlist = [repr(w_item) for w_item in w_self.wrappeditems] return "%s(%s)" % (w_self.__class__.__name__, ', '.join(reprlist)) + def unwrap(w_tuple): + space = w_tuple.space + items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems] # XXX generic mixed types unwrap + return tuple(items) -registerimplementation(W_TupleObject) +registerimplementation(W_TupleObject) -def unwrap__Tuple(space, w_tuple): - items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems] # XXX generic mixed types unwrap - return tuple(items) def len__Tuple(space, w_tuple): result = len(w_tuple.wrappeditems) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupletype.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupletype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupletype.py Sun Feb 6 20:38:08 2005 @@ -1,7 +1,7 @@ from pypy.objspace.std.stdtypedef import * +from pypy.interpreter.gateway import NoneNotWrapped - -def descr__new__(space, w_tupletype, w_items=None): +def descr__new__(space, w_tupletype, w_items=NoneNotWrapped): from pypy.objspace.std.tupleobject import W_TupleObject if w_items is None: tuple_w = [] Copied: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/typeobject.py (from r8901, pypy/dist/pypy/objspace/std/typeobject.py) ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/typeobject.py Sun Feb 6 20:38:08 2005 @@ -170,24 +170,29 @@ space.wrap("attribute '__dict__' of type objects " "is not writable")) + def unwrap(w_self): + if hasattr(w_self.instancetypedef, 'fakedcpytype'): + return w_self.instancetypedef.fakedcpytype + from pypy.objspace.std.model import UnwrapError + raise UnwrapError(w_self) -def call__Type(space, w_type, w_args, w_kwds): - args = Arguments.frompacked(space, w_args, w_kwds) + +def call__Type(space, w_type, __args__): # special case for type(x) if space.is_true(space.is_(w_type, space.w_type)): try: - w_obj, = args.fixedunpack(1) + w_obj, = __args__.fixedunpack(1) except ValueError: pass else: return space.type(w_obj) # invoke the __new__ of the type w_newfunc = space.getattr(w_type, space.wrap('__new__')) - w_newobject = space.call_args(w_newfunc, args.prepend(w_type)) + w_newobject = space.call_args(w_newfunc, __args__.prepend(w_type)) # maybe invoke the __init__ of the type if space.is_true(space.isinstance(w_newobject, w_type)): w_descr = space.lookup(w_newobject, '__init__') - space.get_and_call_args(w_descr, w_newobject, args) + space.get_and_call_args(w_descr, w_newobject, __args__) return w_newobject def issubtype__Type_Type(space, w_type1, w_type2): @@ -229,11 +234,6 @@ # XXX __delattr__ # XXX __hash__ ?? -def unwrap__Type(space, w_type): - if hasattr(w_type.instancetypedef, 'fakedcpytype'): - return w_type.instancetypedef.fakedcpytype - raise FailedToImplement - # ____________________________________________________________ Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/unicodeobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/unicodeobject.py Sun Feb 6 20:38:08 2005 @@ -5,10 +5,10 @@ W_UnicodeObject = fake_type(unicode) # string-to-unicode delegation -def delegate__String(space, w_str): +def delegate_String2Unicode(w_str): + space = w_str.space return W_UnicodeObject(space, unicode(space.str_w(w_str))) -delegate__String.result_class = W_UnicodeObject -delegate__String.priority = PRIORITY_CHANGE_TYPE + def eq__Unicode_ANY(space, w_uni, w_other): try: From arigo at codespeak.net Sun Feb 6 21:06:13 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sun, 6 Feb 2005 21:06:13 +0100 (MET) Subject: [pypy-svn] r8935 - pypy/branch/dist-simpler-multimethods/pypy/interpreter Message-ID: <20050206200613.EF52827BFB@code1.codespeak.net> Author: arigo Date: Sun Feb 6 21:06:13 2005 New Revision: 8935 Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py pypy/branch/dist-simpler-multimethods/pypy/interpreter/pycode.py Log: working... Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py Sun Feb 6 21:06:13 2005 @@ -14,7 +14,7 @@ from pypy.tool import hack from pypy.interpreter.error import OperationError -from pypy.interpreter import eval, pycode +from pypy.interpreter import eval from pypy.interpreter.function import Function, Method from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable from pypy.interpreter.argument import Arguments @@ -261,6 +261,7 @@ # str,int,float: unwrap argument as such type # First extract the signature from the (CPython-level) code object + from pypy.interpreter import pycode argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) if unwrap_spec is None: @@ -467,6 +468,7 @@ def getcode(self, space): "NOT_RPYTHON" + from pypy.interpreter import pycode code = pycode.PyCode(space) code._from_code(self._staticcode) return code Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/interpreter/pycode.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/interpreter/pycode.py Sun Feb 6 21:06:13 2005 @@ -6,6 +6,7 @@ import dis from pypy.interpreter import eval +from pypy.interpreter.gateway import NoneNotWrapped from pypy.tool.cache import Cache # helper @@ -194,7 +195,8 @@ w_argcount, w_nlocals, w_stacksize, w_flags, w_codestring, w_constants, w_names, w_varnames, w_filename, w_name, w_firstlineno, - w_lnotab, w_freevars=None, w_cellvars=None): + w_lnotab, w_freevars=NoneNotWrapped, + w_cellvars=NoneNotWrapped): code = space.allocate_instance(PyCode, w_subtype) code.__init__(space) # XXX typechecking everywhere! From pedronis at codespeak.net Mon Feb 7 00:13:28 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 7 Feb 2005 00:13:28 +0100 (MET) Subject: [pypy-svn] r8939 - pypy/branch/dist-simpler-multimethods/pypy/objspace/std Message-ID: <20050206231328.6EEF727C3E@code1.codespeak.net> Author: pedronis Date: Mon Feb 7 00:13:28 2005 New Revision: 8939 Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py Log: install ops for int overflow -> long switching Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/longobject.py Mon Feb 7 00:13:28 2005 @@ -235,3 +235,48 @@ register_all(vars()) + +# register implementations of ops that recover int op overflows + +# binary ops +for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod']: + exec """ +def %(opname)s_ovr__Int_Int(space, w_int1, w_int2): + w_long1 = delegate_Int2Long(w_int1) + w_long2 = delegate_Int2Long(w_int2) + return %(opname)s__Long_Long(space, w_long1, w_long2) +""" % {'opname': opname} + + getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int_Int' %opname], W_IntObject, W_IntObject, order=1) + +# unary ops +for opname in ['neg', 'abs']: + exec """ +def %(opname)s_ovr__Int(space, w_int1): + w_long1 = delegate_Int2Long(w_int1) + return %(opname)s__Long(space, w_long1) +""" % {'opname': opname} + + getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int' %opname], W_IntObject, order=1) + +# lshift +def lshift_ovr__Int_Int(space, w_int1, w_cnt): + w_long1 = delegate_Int2Long(w_int1) + return lshift__Long_Int(space, w_long1, w_cnt) + +StdObjSpace.MM.lshift.register(lshift_ovr__Int_Int, W_IntObject, W_IntObject, order=1) + +# pow +def pow_ovr__Int_Int_None(space, w_int1, w_int2, w_none3): + w_long1 = delegate_Int2Long(w_int1) + w_long2 = delegate_Int2Long(w_int2) + return pow__Long_Long_None(space, w_long1, w_long2, w_none3) + +def pow_ovr__Int_Int_Int(space, w_int1, w_int2, w_int3): + w_long1 = delegate_Int2Long(w_int1) + w_long2 = delegate_Int2Long(w_int2) + w_long3 = delegate_Int2Long(w_int3) + return pow__Long_Long_Long(space, w_long1, w_long2, w_long3) + +StdObjSpace.MM.pow.register(pow_ovr__Int_Int_None, W_IntObject, W_IntObject, W_NoneObject, order=1) +StdObjSpace.MM.pow.register(pow_ovr__Int_Int_Int , W_IntObject, W_IntObject, W_IntObject, order=1) From cfbolz at codespeak.net Mon Feb 7 01:32:43 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Mon, 7 Feb 2005 01:32:43 +0100 (MET) Subject: [pypy-svn] r8940 - pypy/dist/pypy/translator/llvm Message-ID: <20050207003243.E7E6627C29@code1.codespeak.net> Author: cfbolz Date: Mon Feb 7 01:32:43 2005 New Revision: 8940 Modified: pypy/dist/pypy/translator/llvm/build_llvm_module.py pypy/dist/pypy/translator/llvm/genllvm.py Log: Added some debug output and a way to turn off LLVM-optimization. Modified: pypy/dist/pypy/translator/llvm/build_llvm_module.py ============================================================================== --- pypy/dist/pypy/translator/llvm/build_llvm_module.py (original) +++ pypy/dist/pypy/translator/llvm/build_llvm_module.py Mon Feb 7 01:32:43 2005 @@ -14,7 +14,7 @@ from pypy.translator.tool.buildpyxmodule import make_c_from_pyxfile from pypy.translator.tool import stdoutcapture -debug = 0 +debug = 1 class CompileError(exceptions.Exception): pass @@ -26,18 +26,26 @@ old_system = os.system os.system = system_trace -def make_module_from_llvm(llvmfile, pyxfile): +def make_module_from_llvm(llvmfile, pyxfile, optimize=True): include_dir = autopath.this_dir dirpath = llvmfile.dirpath() lastdir = path.local() os.chdir(str(dirpath)) modname = pyxfile.purebasename - ops1 = ["llvm-as %s -f" % llvmfile, - "llvmc -O3 %s.bc -o _%s.o" % (llvmfile.purebasename, modname), - "llc _%s.o.bc -f -o _%s.s" % (modname, modname), - "as _%s.s -o _%s.o" % (modname, modname)] + ops1 = ["llvm-as %s -f -o %s.bc" % (llvmfile, llvmfile.purebasename), + "llvmc -f -O3 %s.bc -o %s_optimized.o" % (llvmfile.purebasename, + llvmfile.purebasename), + "llc %s_optimized.o.bc -f -o %s.s" % (llvmfile.purebasename, + llvmfile.purebasename), + "as %s.s -o %s.o" % (llvmfile.purebasename, llvmfile.purebasename)] + if not optimize: + ops1 = ["llvm-as %s -f" % llvmfile, + "llc %s.bc -f -o %s.s" % (llvmfile.purebasename, + llvmfile.purebasename), + "as %s.s -o %s.o" % (llvmfile.purebasename, + llvmfile.purebasename)] ops2 = ["gcc -c -fPIC -I/usr/include/python %s.c" % pyxfile.purebasename, - "gcc -shared %s.o _%s.o -o %s.so" % (pyxfile.purebasename, + "gcc -shared %s.o %s.o -o %s.so" % (llvmfile.purebasename, modname, modname)] try: if debug: print "modname", modname @@ -46,9 +54,11 @@ try: try: for op in ops1: + print op cmdexec(op) make_c_from_pyxfile(pyxfile) for op in ops2: + print op cmdexec(op) finally: foutput, foutput = c.done() Modified: pypy/dist/pypy/translator/llvm/genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/genllvm.py Mon Feb 7 01:32:43 2005 @@ -34,9 +34,9 @@ debug = 0 -def llvmcompile(transl): +def llvmcompile(transl, optimize=True): gen = LLVMGenerator(transl) - return gen.compile() + return gen.compile(optimize) class CompileError(exceptions.Exception): @@ -53,7 +53,7 @@ self.llvm_reprs = {} self.l_entrypoint = self.get_repr(self.translator.functions[0]) - def compile(self): + def compile(self, optimize=True): from pypy.tool.udir import udir name = self.l_entrypoint.llvmname()[1:] llvmfile = udir.join('%s.ll' % name) @@ -64,7 +64,8 @@ f = pyxfile.open('w') f.write(self.l_entrypoint.get_pyrex_source()) f.close() - mod = build_llvm_module.make_module_from_llvm(llvmfile, pyxfile) + mod = build_llvm_module.make_module_from_llvm(llvmfile, pyxfile, + optimize) return getattr(mod, "wrap_%s" % name) def get_global_tmp(self, used_by=None): From sanxiyn at codespeak.net Mon Feb 7 06:10:58 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Mon, 7 Feb 2005 06:10:58 +0100 (MET) Subject: [pypy-svn] r8941 - in pypy/dist/pypy: module translator Message-ID: <20050207051058.4368627B34@code1.codespeak.net> Author: sanxiyn Date: Mon Feb 7 06:10:57 2005 New Revision: 8941 Modified: pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: exceptionsinterp.py regenerated. To regenerate, run geninterplevel.py and copy /tmp/look.py to the tree. Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Mon Feb 7 06:10:57 2005 @@ -1,6 +1,9 @@ #!/bin/env python # -*- coding: LATIN-1 -*- +from pypy.interpreter.error import OperationError + + """Python's standard exception class hierarchy. Before Python 1.5, the standard exceptions were all simple string objects. @@ -91,18 +94,19 @@ +-- FutureWarning""" ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__getitem__' ## firstlineno 94 ##SECTION## -def __getitem__(space, *args_w): - kwlist = ["self", "idx"] - _args_w = args_w - defaults_w = () +def __getitem__(space, __args__): funcname = "__getitem__" - w_self, w_idx = PyArg_ParseMini(space, funcname, 2, 2, _args_w, defaults_w) + signature = ['self', 'idx'], None, None + def_w = [] + w_self, w_idx = __args__.parse(funcname, signature, def_w) return fastf_Exception___getitem__(space, w_self, w_idx) -f_Exception___getitem__ = globals().pop("__getitem__") + +f_Exception___getitem__ = __getitem__ +del __getitem__ def __getitem__(space, w_self, w_idx): @@ -119,22 +123,24 @@ if goto == 2: return w_4 -fastf_Exception___getitem__ = globals().pop("__getitem__") + +fastf_Exception___getitem__ = __getitem__ +del __getitem__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 98 ##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_Exception___init__(space, w_self, w_args) -f_Exception___init__ = globals().pop("__init__") + +f_Exception___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -150,10 +156,12 @@ if goto == 2: return w_3 -fastf_Exception___init__ = globals().pop("__init__") + +fastf_Exception___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 102 ##SECTION## @@ -162,14 +170,15 @@ # global object gi_0 # global object gi_1 -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_Exception___str__(space, w_self) -f_Exception___str__ = globals().pop("__str__") + +f_Exception___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -205,23 +214,23 @@ if goto == 3: w_8 = space.getitem(w_args_2, gi_0) - _tup = space.newtuple([w_8]) - w_9 = space.call(space.w_str, _tup) + w_9 = space.call_function(space.w_str, w_8) w_5 = w_9 goto = 5 if goto == 4: - _tup = space.newtuple([w_args_3]) - w_10 = space.call(space.w_str, _tup) + w_10 = space.call_function(space.w_str, w_args_3) w_5 = w_10 goto = 5 if goto == 5: return w_5 -fastf_Exception___str__ = globals().pop("__str__") + +fastf_Exception___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 131 ##SECTION## @@ -230,15 +239,15 @@ # global object gi_2 # global object gi_3 -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_UnicodeTranslateError___init__(space, w_self, w_args) -f_UnicodeTranslateError___init__ = globals().pop("__init__") + +f_UnicodeTranslateError___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -275,10 +284,12 @@ if goto == 3: return w_6 -fastf_UnicodeTranslateError___init__ = globals().pop("__init__") + +fastf_UnicodeTranslateError___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 141 ##SECTION## @@ -296,14 +307,15 @@ # global object gs__ # global object gs_join -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_UnicodeTranslateError___str__(space, w_self) -f_UnicodeTranslateError___str__ = globals().pop("__str__") + +f_UnicodeTranslateError___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -315,48 +327,45 @@ if goto == 1: w_0 = space.getattr(w_self, gs_start, space.w_None) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) + w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_start_, w_2) w_4 = space.getattr(w_self, gs_reason, space.w_None) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) + w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_reason_, w_5) w_7 = space.getattr(w_self, gs_args, space.w_None) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) + w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_args_, w_8) w_10 = space.getattr(w_self, gs_end, space.w_None) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) + w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_end_, w_11) w_13 = space.getattr(w_self, gs_object, space.w_None) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) + w_14 = space.call_function(space.w_str, w_13) w_15 = space.add(gs_object_, w_14) w_16 = space.newlist([w_3, w_6, w_9, w_12, w_15]) - _tup = space.newtuple([w_16]) - w_res = space.call(gbltinmethod_join, _tup) + w_res = space.call_function(gbltinmethod_join, w_16) w_18 = w_res goto = 2 if goto == 2: return w_18 -fastf_UnicodeTranslateError___str__ = globals().pop("__str__") + +fastf_UnicodeTranslateError___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 159 ##SECTION## -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_KeyError___str__(space, w_self) -f_KeyError___str__ = globals().pop("__str__") + +f_KeyError___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -397,29 +406,30 @@ goto = 5 if goto == 4: - _tup = space.newtuple([w_args_3]) - w_10 = space.call(space.w_str, _tup) + w_10 = space.call_function(space.w_str, w_args_3) w_5 = w_10 goto = 5 if goto == 5: return w_5 -fastf_KeyError___str__ = globals().pop("__str__") + +fastf_KeyError___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 185 ##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_EnvironmentError___init__(space, w_self, w_args) -f_EnvironmentError___init__ = globals().pop("__init__") + +f_EnvironmentError___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -494,10 +504,12 @@ if goto == 7: return w_18 -fastf_EnvironmentError___init__ = globals().pop("__init__") + +fastf_EnvironmentError___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 199 ##SECTION## @@ -508,14 +520,15 @@ # global object gs_strerror_ # global object gs_filename_ -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_EnvironmentError___str__(space, w_self) -f_EnvironmentError___str__ = globals().pop("__str__") + +f_EnvironmentError___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -527,48 +540,45 @@ if goto == 1: w_0 = space.getattr(w_self, gs_errno, space.w_None) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) + w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_errno_, w_2) w_4 = space.getattr(w_self, gs_args, space.w_None) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) + w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_args_, w_5) w_7 = space.getattr(w_self, gs_strerror, space.w_None) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) + w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_strerror_, w_8) w_10 = space.getattr(w_self, gs_filename, space.w_None) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) + w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_filename_, w_11) w_13 = space.newlist([w_3, w_6, w_9, w_12]) - _tup = space.newtuple([w_13]) - w_res = space.call(gbltinmethod_join, _tup) + w_res = space.call_function(gbltinmethod_join, w_13) w_15 = w_res goto = 2 if goto == 2: return w_15 -fastf_EnvironmentError___str__ = globals().pop("__str__") + +fastf_EnvironmentError___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 219 ##SECTION## # global declaration # global object gi_5 -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_UnicodeEncodeError___init__(space, w_self, w_args) -f_UnicodeEncodeError___init__ = globals().pop("__init__") + +f_UnicodeEncodeError___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -607,10 +617,12 @@ if goto == 3: return w_6 -fastf_UnicodeEncodeError___init__ = globals().pop("__init__") + +fastf_UnicodeEncodeError___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 230 ##SECTION## @@ -618,14 +630,15 @@ # global object gs_encoding # global object gs_encoding_ -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_UnicodeEncodeError___str__(space, w_self) -f_UnicodeEncodeError___str__ = globals().pop("__str__") + +f_UnicodeEncodeError___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -637,53 +650,48 @@ if goto == 1: w_0 = space.getattr(w_self, gs_object, space.w_None) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) + w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_object_, w_2) w_4 = space.getattr(w_self, gs_end, space.w_None) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) + w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_end_, w_5) w_7 = space.getattr(w_self, gs_encoding, space.w_None) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) + w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_encoding_, w_8) w_10 = space.getattr(w_self, gs_args, space.w_None) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) + w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_args_, w_11) w_13 = space.getattr(w_self, gs_start, space.w_None) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) + w_14 = space.call_function(space.w_str, w_13) w_15 = space.add(gs_start_, w_14) w_16 = space.getattr(w_self, gs_reason, space.w_None) - _tup = space.newtuple([w_16]) - w_17 = space.call(space.w_str, _tup) + w_17 = space.call_function(space.w_str, w_16) w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) - _tup = space.newtuple([w_19]) - w_res = space.call(gbltinmethod_join, _tup) + w_res = space.call_function(gbltinmethod_join, w_19) w_21 = w_res goto = 2 if goto == 2: return w_21 -fastf_UnicodeEncodeError___str__ = globals().pop("__str__") + +fastf_UnicodeEncodeError___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 270 ##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_SyntaxError___init__(space, w_self, w_args) -f_SyntaxError___init__ = globals().pop("__init__") + +f_SyntaxError___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -742,21 +750,24 @@ if goto == 5: return w_10 -fastf_SyntaxError___init__ = globals().pop("__init__") + +fastf_SyntaxError___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 282 ##SECTION## -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_SyntaxError___str__(space, w_self) -f_SyntaxError___str__ = globals().pop("__str__") + +f_SyntaxError___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -767,36 +778,36 @@ if goto == 1: w_0 = space.getattr(w_self, gs_args, space.w_None) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) + w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_args_, w_2) w_4 = space.newlist([w_3]) - _tup = space.newtuple([w_4]) - w_res = space.call(gbltinmethod_join, _tup) + w_res = space.call_function(gbltinmethod_join, w_4) w_6 = w_res goto = 2 if goto == 2: return w_6 -fastf_SyntaxError___str__ = globals().pop("__str__") + +fastf_SyntaxError___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 296 ##SECTION## # global declaration # global object gs_code -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_SystemExit___init__(space, w_self, w_args) -f_SystemExit___init__ = globals().pop("__init__") + +f_SystemExit___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -860,22 +871,24 @@ if goto == 7: return w_13 -fastf_SystemExit___init__ = globals().pop("__init__") + +fastf_SystemExit___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 331 ##SECTION## -def __init__(space, *args_w): - kwlist = ["self"] - w_args = space.newtuple(list(args_w[1:])) - _args_w = args_w[:1] - defaults_w = () +def __init__(space, __args__): funcname = "__init__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], 'args', None + def_w = [] + w_self, w_args = __args__.parse(funcname, signature, def_w) return fastf_UnicodeDecodeError___init__(space, w_self, w_args) -f_UnicodeDecodeError___init__ = globals().pop("__init__") + +f_UnicodeDecodeError___init__ = __init__ +del __init__ def __init__(space, w_self, w_args): @@ -914,21 +927,24 @@ if goto == 3: return w_6 -fastf_UnicodeDecodeError___init__ = globals().pop("__init__") + +fastf_UnicodeDecodeError___init__ = __init__ +del __init__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\lib\\_exceptions.py' +## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 342 ##SECTION## -def __str__(space, *args_w): - kwlist = ["self"] - _args_w = args_w - defaults_w = () +def __str__(space, __args__): funcname = "__str__" - w_self, = PyArg_ParseMini(space, funcname, 1, 1, _args_w, defaults_w) + signature = ['self'], None, None + def_w = [] + w_self, = __args__.parse(funcname, signature, def_w) return fastf_UnicodeDecodeError___str__(space, w_self) -f_UnicodeDecodeError___str__ = globals().pop("__str__") + +f_UnicodeDecodeError___str__ = __str__ +del __str__ def __str__(space, w_self): @@ -940,43 +956,38 @@ if goto == 1: w_0 = space.getattr(w_self, gs_object, space.w_None) - _tup = space.newtuple([w_0]) - w_2 = space.call(space.w_str, _tup) + w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_object_, w_2) w_4 = space.getattr(w_self, gs_end, space.w_None) - _tup = space.newtuple([w_4]) - w_5 = space.call(space.w_str, _tup) + w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_end_, w_5) w_7 = space.getattr(w_self, gs_encoding, space.w_None) - _tup = space.newtuple([w_7]) - w_8 = space.call(space.w_str, _tup) + w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_encoding_, w_8) w_10 = space.getattr(w_self, gs_args, space.w_None) - _tup = space.newtuple([w_10]) - w_11 = space.call(space.w_str, _tup) + w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_args_, w_11) w_13 = space.getattr(w_self, gs_start, space.w_None) - _tup = space.newtuple([w_13]) - w_14 = space.call(space.w_str, _tup) + w_14 = space.call_function(space.w_str, w_13) w_15 = space.add(gs_start_, w_14) w_16 = space.getattr(w_self, gs_reason, space.w_None) - _tup = space.newtuple([w_16]) - w_17 = space.call(space.w_str, _tup) + w_17 = space.call_function(space.w_str, w_16) w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) - _tup = space.newtuple([w_19]) - w_res = space.call(gbltinmethod_join, _tup) + w_res = space.call_function(gbltinmethod_join, w_19) w_21 = w_res goto = 2 if goto == 2: return w_21 -fastf_UnicodeDecodeError___str__ = globals().pop("__str__") + +fastf_UnicodeDecodeError___str__ = __str__ +del __str__ ##SECTION## -## filename 'D:\\pypy\\dist\\pypy\\translator\\geninterplevel.py' +## filename 'geninterplevel.py' ## function 'test_exceptions' -## firstlineno 1272 +## firstlineno 1306 ##SECTION## # global declarations # global object gfunc_test_exceptions @@ -984,17 +995,19 @@ # global object g47dict # global object gs_keys -def test_exceptions(space, *args_w): +def test_exceptions(space, __args__): """ enumerate all exceptions """ - kwlist = [] - _args_w = args_w - defaults_w = () + funcname = "test_exceptions" - PyArg_ParseMini(space, funcname, 0, 0, _args_w, defaults_w) - return fastf_test_exceptions(space, ) -f_test_exceptions = globals().pop("test_exceptions") + signature = [], None, None + def_w = [] + __args__.parse(funcname, signature, def_w) + return fastf_test_exceptions(space) + +f_test_exceptions = test_exceptions +del test_exceptions -def test_exceptions(space, ): +def test_exceptions(space): """ enumerate all exceptions """ w_0=w_1=None @@ -1003,14 +1016,15 @@ while True: if goto == 1: - _tup = space.newtuple([]) - w_0 = space.call(gbltinmethod_keys, _tup) + w_0 = space.call_function(gbltinmethod_keys, ) w_1 = w_0 goto = 2 if goto == 2: return w_1 -fastf_test_exceptions = globals().pop("test_exceptions") + +fastf_test_exceptions = test_exceptions +del test_exceptions # global declarations # global object gs_MemoryError @@ -1149,38 +1163,6 @@ m.g47dict = space.newdict([]) m.gs_keys = space.wrap('keys') m.gbltinmethod_keys = space.getattr(g47dict, gs_keys) - def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): - err = None - if len(args_w) < minargs: - txt = "%s() takes at least %d argument%s (%d given)" - plural = ['s', ''][minargs == 1] - err = (name, minargs, plural, len(args_w)) - if len(args_w) > maxargs: - plural = ['s', ''][maxargs == 1] - if minargs == maxargs: - if minargs == 0: - txt = '%s() takes no arguments (%d given)' - err = (name, len(args_w)) - elif minargs == 1: - txt = '%s() takes exactly %d argument%s (%d given)' - err = (name, maxargs, plural, len(args_w)) - else: - txt = '%s() takes at most %d argument%s (%d given)' - err = (name, maxargs, plural, len(args_w)) - if err: - w_txt = space.wrap(txt) - w_tup = space.wrap(err) - w_txt = space.mod(w_txt, w_tup) - raise OperationError(space.w_TypeError, w_txt) - - # finally, we create the result ;-) - res_w = args_w + defaults_w[len(args_w) - minargs:] - assert len(res_w) == maxargs - return res_w - - m.PyArg_ParseMini = PyArg_ParseMini - from pypy.interpreter.error import OperationError - m.OperationError = OperationError m.gs_MemoryError = space.wrap('MemoryError') _dic = space.newdict([]) m.gs___module__ = space.wrap('__module__') @@ -1669,11 +1651,16 @@ m.gs_encoding_ = space.wrap('encoding=') m.gi_5 = space.newint(5) -# entry point: test_exceptions, gfunc_test_exceptions) +# entry point: test_exceptions, gfunc_test_exceptions if __name__ == "__main__": from pypy.objspace.std import StdObjSpace + from pypy.objspace.std.default import UnwrapError space = StdObjSpace() inittest_exceptions_1(space) - print space.unwrap(space.call( - gfunc_test_exceptions, space.newtuple([]))) + ret = space.call(gfunc_test_exceptions, space.newtuple([])) + try: + print space.unwrap(ret) + except UnwrapError: + print "cannot unwrap, here the wrapped result:" + print ret Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 7 06:10:57 2005 @@ -1344,6 +1344,13 @@ entrypoint = entrypoints[-6] if __name__ == "__main__": + dic, entrypoint = test_exceptions_helper() + t = Translator(entrypoint, verbose=False, simplifying=True) + gen = GenRpy(t) + gen.use_fast_call = True + gen.moddict = dic + gen.gen_source('/tmp/look.py') + ''' import os, sys from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) @@ -1364,6 +1371,7 @@ ftmpname = "/tmp/look.py" fname = os.path.join(pth, gen.modname+".py") gen.gen_source(fname, ftmpname) + ''' def crazy_test(): """ this thingy is generating the whole interpreter in itself""" From sanxiyn at codespeak.net Mon Feb 7 06:24:26 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Mon, 7 Feb 2005 06:24:26 +0100 (MET) Subject: [pypy-svn] r8942 - in pypy/dist/pypy: interpreter objspace/std Message-ID: <20050207052426.E2E7727C42@code1.codespeak.net> Author: sanxiyn Date: Mon Feb 7 06:24:26 2005 New Revision: 8942 Modified: pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/objspace/std/listtype.py Log: Be 2.2-compatible again. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 7 06:24:26 2005 @@ -73,6 +73,8 @@ #"print scope_w" ] + setfastscope setfastscope = '\n '.join(setfastscope) + # Python 2.2 SyntaxError without newline: Bug #501622 + setfastscope += '\n' d = {} exec setfastscope in globals(),d exec """ Modified: pypy/dist/pypy/objspace/std/listtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/listtype.py (original) +++ pypy/dist/pypy/objspace/std/listtype.py Mon Feb 7 06:24:26 2005 @@ -1,3 +1,4 @@ +from __future__ import generators from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.register_all import register_all from sys import maxint From sanxiyn at codespeak.net Mon Feb 7 08:58:50 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Mon, 7 Feb 2005 08:58:50 +0100 (MET) Subject: [pypy-svn] r8946 - pypy/dist/pypy/objspace Message-ID: <20050207075850.A5DE327C58@code1.codespeak.net> Author: sanxiyn Date: Mon Feb 7 08:58:50 2005 New Revision: 8946 Modified: pypy/dist/pypy/objspace/trivial.py Log: Pointless fix to TrivialObjSpace to run. Modified: pypy/dist/pypy/objspace/trivial.py ============================================================================== --- pypy/dist/pypy/objspace/trivial.py (original) +++ pypy/dist/pypy/objspace/trivial.py Mon Feb 7 08:58:50 2005 @@ -98,6 +98,10 @@ self.w_False = False self.w_NotImplemented = NotImplemented self.w_Ellipsis = Ellipsis + + self.w_classobj = types.ClassType + self.w_instance = types.InstanceType + newstuff = {"False": self.w_False, "True" : self.w_True, "NotImplemented" : self.w_NotImplemented, From ac at codespeak.net Mon Feb 7 13:00:37 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 7 Feb 2005 13:00:37 +0100 (MET) Subject: [pypy-svn] r8947 - pypy/dist/pypy/module Message-ID: <20050207120037.4F2FB27C5D@code1.codespeak.net> Author: ac Date: Mon Feb 7 13:00:37 2005 New Revision: 8947 Modified: pypy/dist/pypy/module/__builtin__interp.py Log: Ignore leading whitespace in eval. Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Mon Feb 7 13:00:37 2005 @@ -229,7 +229,7 @@ w = space.wrap if space.is_true(space.isinstance(w_source, space.w_str)): - w_codeobj = compile(space.str_w(w_source), "", "eval") + w_codeobj = compile(space.str_w(w_source).lstrip(' \t'), "", "eval") elif isinstance(space.interpclass_w(w_source), PyCode): w_codeobj = w_source else: From ac at codespeak.net Mon Feb 7 13:01:25 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 7 Feb 2005 13:01:25 +0100 (MET) Subject: [pypy-svn] r8948 - pypy/dist/pypy/module Message-ID: <20050207120125.36EE727C5D@code1.codespeak.net> Author: ac Date: Mon Feb 7 13:01:25 2005 New Revision: 8948 Modified: pypy/dist/pypy/module/__builtin__module.py Log: Special case str/unicode argument to filter as per cpython. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Mon Feb 7 13:01:25 2005 @@ -122,7 +122,24 @@ """construct a list of those elements of collection for which function is True. If function is None, then return the items in the sequence which are True.""" - + str_type = None + if isinstance(collection, str): + str_type = str + elif isinstance(collection, unicode): + str_type = unicode + + if str_type is not None: + if function is None and type(collection) is str_type: + return collection + res = [] + for i in xrange(len(collection)): + c = collection[i] + if function is None or function(c): + if not isinstance(c, str_type): + raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) + res.append(c) + return str_type().join(res) + if function is None: res = [item for item in collection if item] else: @@ -130,8 +147,6 @@ if type(collection) is tuple: return tuple(res) - elif type(collection) is str: - return "".join(res) else: return res From pedronis at codespeak.net Mon Feb 7 13:03:33 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 7 Feb 2005 13:03:33 +0100 (MET) Subject: [pypy-svn] r8949 - in pypy/branch/dist-simpler-multimethods/pypy: interpreter objspace/std Message-ID: <20050207120333.9E06927C5D@code1.codespeak.net> Author: pedronis Date: Mon Feb 7 13:03:33 2005 New Revision: 8949 Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dicttype.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py Log: {}.pop works again Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py Mon Feb 7 13:03:33 2005 @@ -127,7 +127,16 @@ assert new_sig.varargname is None,( "built-in function %r has conflicting rest args specs" % orig_sig.func) new_sig.varargname = argname[:-2] - + +def unwrap_spec_check_w_args(orig_sig, new_sig): + argname = orig_sig.next() + assert argname.startswith('w_'), ( + "rest arguments arg %s of built-in function %r should start 'w_'" % + (argname, orig_sig.func)) + assert new_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + new_sig.varargname = argname[2:] + # recipes for checking interp2app func argumes wrt unwrap_spec unwrap_spec_checks = { ObjSpace: unwrap_spec_check_space, @@ -136,6 +145,7 @@ Arguments: unwrap_spec_check_arguments, '*': unwrap_spec_check_starargs, 'args_w': unwrap_spec_check_args_w, + 'w_args': unwrap_spec_check_w_args, } def unwrap_spec_emit_space(orig_sig, new_sig): @@ -178,6 +188,13 @@ (new_sig.through_scope_w)) new_sig.through_scope_w += 1 new_sig.run_args.append("self.args_w") + +def unwrap_spec_emit_w_args(orig_sig, new_sig): + cur = new_sig.through_scope_w + new_sig.setfastscope.append( + "self.w_args = scope_w[%d]" % cur) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.w_args") # recipes for emitting unwrapping code for arguments of a interp2app func # wrt a unwrap_spec @@ -188,6 +205,7 @@ Arguments: unwrap_spec_emit_arguments, '*': unwrap_spec_emit_starargs, 'args_w': unwrap_spec_emit_args_w, + 'w_args': unwrap_spec_emit_w_args, } # unwrap_spec_check/emit for str,int,float Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dicttype.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dicttype.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/dicttype.py Mon Feb 7 13:03:33 2005 @@ -8,7 +8,7 @@ dict_has_key = MultiMethod('has_key', 2) dict_clear = MultiMethod('clear', 1) dict_get = MultiMethod('get', 3, defaults=(None,)) -dict_pop = MultiMethod('pop', 2, varargs=True) +dict_pop = MultiMethod('pop', 2, w_varargs=True) dict_popitem = MultiMethod('popitem', 1) dict_setdefault = MultiMethod('setdefault', 3, defaults=(None,)) dict_update = MultiMethod('update', 2) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py Mon Feb 7 13:03:33 2005 @@ -144,6 +144,10 @@ self.name = operatorsymbol if extras.get('general__args__', False): self.argnames_after = ['__args__'] + if extras.get('w_varargs', False): + self.argnames_after = ['w_args'] + if extras.get('varargs_w', False): + self.argnames_after = ['args_w'] def install_not_sliced(self, typeorder): return self.install(prefix = '__mm_' + self.name, Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py Mon Feb 7 13:03:33 2005 @@ -178,8 +178,10 @@ # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w solid_arglist = ['w_'+name for name in argnames] wrapper_arglist = solid_arglist[:] - if multimethod.extras.get('varargs', False): + if multimethod.extras.get('varargs_w', False): wrapper_arglist.append('args_w') + if multimethod.extras.get('w_varargs', False): + wrapper_arglist.append('w_args') if multimethod.extras.get('keywords', False): raise Exception, "no longer supported, use __args__" if multimethod.extras.get('general__args__', False): @@ -233,8 +235,10 @@ def wrap_trampoline_in_gateway(func, methname, multimethod): unwrap_spec = [gateway.ObjSpace] + [gateway.W_Root]*multimethod.arity - if multimethod.extras.get('varargs', False): + if multimethod.extras.get('varargs_w', False): unwrap_spec.append('args_w') + if multimethod.extras.get('w_varargs', False): + unwrap_spec.append('w_args') if multimethod.extras.get('general__args__', False): unwrap_spec.append(gateway.Arguments) return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) From ac at codespeak.net Mon Feb 7 13:08:36 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 7 Feb 2005 13:08:36 +0100 (MET) Subject: [pypy-svn] r8950 - pypy/dist/pypy/module/test Message-ID: <20050207120836.7505F27C4D@code1.codespeak.net> Author: ac Date: Mon Feb 7 13:08:36 2005 New Revision: 8950 Modified: pypy/dist/pypy/module/test/test_builtin.py Log: Test for leading whitespace in eval. Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Mon Feb 7 13:08:36 2005 @@ -293,6 +293,7 @@ def test_eval(self): assert eval("1+2") == 3 + assert eval(" \t1+2\n") == 3 def test_compile(self): co = compile('1+2', '?', 'eval') From pedronis at codespeak.net Mon Feb 7 13:08:57 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 7 Feb 2005 13:08:57 +0100 (MET) Subject: [pypy-svn] r8951 - pypy/branch/dist-simpler-multimethods/pypy/interpreter Message-ID: <20050207120857.AF31227C4D@code1.codespeak.net> Author: pedronis Date: Mon Feb 7 13:08:57 2005 New Revision: 8951 Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py Log: updated comment Modified: pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/interpreter/gateway.py Mon Feb 7 13:08:57 2005 @@ -275,7 +275,8 @@ # 'self' is used to specify a self method argument # baseobjspace.W_Root is for wrapped arguments to keep wrapped # argument.Arguments is for a final rest arguments Arguments object - # 'args_w' for unpacktuple applied rest arguments + # 'args_w' for unpacktuple applied to rest arguments + # 'w_args' for rest arguments passed as wrapped tuple # str,int,float: unwrap argument as such type # First extract the signature from the (CPython-level) code object From ac at codespeak.net Mon Feb 7 16:29:56 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 7 Feb 2005 16:29:56 +0100 (MET) Subject: [pypy-svn] r8954 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050207152956.B747A27C59@code1.codespeak.net> Author: ac Date: Mon Feb 7 16:29:56 2005 New Revision: 8954 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: Add tests as per Seo Sanghyeon and run testmodules in alphabetic order. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Mon Feb 7 16:29:56 2005 @@ -25,16 +25,21 @@ mydir = py.magic.autopath().dirpath() working_unittests = ( -'test_urlparse.py', 'test_base64.py', 'test_binop.py', 'test_bisect.py', 'test_call', 'test_codeop.py', 'test_compile.py', -'test_operator.py', 'test_heapq.py', +'test_htmllib.py', +'test_htmlparser.py', +'test_operator.py', +'test_pprint.py', +'test_sgmllib.py', 'test_sys.py', +'test_textwrap.py', +'test_urlparse.py', ) working_outputtests = ( @@ -62,10 +67,14 @@ class Directory(py.test.collect.Directory): def __iter__(self): + all_tests = [] for test in self.fspath.listdir('test_*.py'): if test.basename not in working_outputtests and \ test.basename not in working_unittests: continue + all_tests.append(test) + all_tests.sort() + for test in all_tests: yield Module(test) def app_list_testmethods(mod, testcaseclass): @@ -150,7 +159,7 @@ class AppTestCaseMethod(py.test.Item): def __init__(self, fspath, space, w_name, w_method, w_setup, w_teardown): self.space = space - name = space.str_w(w_name) + self.name = name = space.str_w(w_name) extpy = py.path.extpy(fspath, name) super(AppTestCaseMethod, self).__init__(extpy) self.w_method = w_method From pedronis at codespeak.net Mon Feb 7 16:39:25 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 7 Feb 2005 16:39:25 +0100 (MET) Subject: [pypy-svn] r8955 - in pypy/branch/dist-simpler-multimethods/pypy/objspace/std: . test Message-ID: <20050207153925.B582427C59@code1.codespeak.net> Author: pedronis Date: Mon Feb 7 16:39:25 2005 New Revision: 8955 Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py Log: - code to get just an expression source string instead of a function from multimethod installing - wrap also space installed mm with FailToImplement -> TypeError conversion - don't use a function with *args as the catch-all fallback - both multimethod level and stdtypedef level code to avoid mm prefix clashes which can lead to confusing (dispatch) bugs Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py Mon Feb 7 16:39:25 2005 @@ -142,6 +142,7 @@ break else: self.name = operatorsymbol + if extras.get('general__args__', False): self.argnames_after = ['__args__'] if extras.get('w_varargs', False): @@ -149,6 +150,7 @@ if extras.get('varargs_w', False): self.argnames_after = ['args_w'] - def install_not_sliced(self, typeorder): + def install_not_sliced(self, typeorder, baked_perform_call=True): return self.install(prefix = '__mm_' + self.name, - list_of_typeorders = [typeorder]*self.arity) + list_of_typeorders = [typeorder]*self.arity, + baked_perform_call=baked_perform_call) Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/multimethod.py Mon Feb 7 16:39:25 2005 @@ -4,7 +4,7 @@ pass -def well_just_complain(*args): +def raiseFailedToImplement(): raise FailedToImplement @@ -39,14 +39,23 @@ types, order) lst[order] = function - def install(self, prefix, list_of_typeorders): + def install(self, prefix, list_of_typeorders, baked_perform_call=True): + "NOT_RPYTHON: initialization-time only" + assert len(list_of_typeorders) == self.arity + installer = Installer(self, prefix, list_of_typeorders, + baked_perform_call=baked_perform_call) + return installer.install() + + def install_if_not_empty(self, prefix, list_of_typeorders): "NOT_RPYTHON: initialization-time only" assert len(list_of_typeorders) == self.arity installer = Installer(self, prefix, list_of_typeorders) if installer.is_empty(): - return well_just_complain + return None else: - return installer.install() + return installer.install() + + # ____________________________________________________________ # limited dict-like interface to the dispatch table @@ -84,19 +93,32 @@ class Installer: - def __init__(self, multimethod, prefix, list_of_typeorders): + prefix_memo = {} + + def __init__(self, multimethod, prefix, list_of_typeorders, baked_perform_call=True): self.multimethod = multimethod + # avoid prefix clashes, user code should supply different prefixes + # itself for nice names in tracebacks + n = 1 + while prefix in self.prefix_memo: + n += 1 + prefix = "%s%d" % (prefix,n) self.prefix = prefix + self.prefix_memo[prefix] = 1 self.list_of_typeorders = list_of_typeorders self.subtree_cache = {} self.to_install = [] self.non_empty = self.build_tree([], multimethod.dispatch_tree) + + self.baked_perform_call = baked_perform_call + if self.non_empty: - self.perform_call = self.build_function(None, prefix+'perform_call', - None, - [(None, prefix, 0)]) + perform = [(None, prefix, 0)] else: - self.perform_call = well_just_complain + perform = [] + + self.perform_call = self.build_function(None, prefix+'_perform_call', + None, perform) def is_empty(self): return not self.non_empty @@ -106,9 +128,9 @@ #print >> f, '_'*60 #import pprint #pprint.pprint(self.list_of_typeorders, f) - for target, funcname, func, source in self.to_install: + for target, funcname, func, source, fallback in self.to_install: if target is not None: - if hasattr(target, funcname) and func is well_just_complain: + if hasattr(target, funcname) and fallback: continue #print >> f, target.__name__, funcname #if source: @@ -192,15 +214,21 @@ invent_name(conversion), callargs[to_convert]) callname = invent_name(call) if call_selfarg_index is not None: - self.to_install.append((self.multimethod.root_class, - callname, - well_just_complain, - None)) + # fallback on root_class + self.build_function(self.multimethod.root_class, + callname, call_selfarg_index, []) callname = '%s.%s' % (callargs.pop(call_selfarg_index), callname) callargs = (self.multimethod.argnames_before + callargs + self.multimethod.argnames_after) bodylines.append('return %s(%s)' % (callname, ', '.join(callargs))) + fallback = False + if not bodylines: + miniglobals['raiseFailedToImplement'] = raiseFailedToImplement + bodylines = ['return raiseFailedToImplement()'] + fallback = True + + # protect all lines apart from the last one by a try:except: for i in range(len(bodylines)-2, -1, -1): bodylines[i:i+1] = ['try:', @@ -208,19 +236,25 @@ 'except FailedToImplement:', ' pass'] - # indent mode - bodylines = [' ' + line for line in bodylines] - if func_selfarg_index is not None: selfargs = [funcargs.pop(func_selfarg_index)] else: selfargs = [] funcargs = (selfargs + self.multimethod.argnames_before + funcargs + self.multimethod.argnames_after) + + if target is None and not self.baked_perform_call: + return funcargs, bodylines[0][len('return '):], miniglobals, fallback + + # indent mode + bodylines = [' ' + line for line in bodylines] + bodylines.insert(0, 'def %s(%s):' % (funcname, ', '.join(funcargs))) bodylines.append('') source = '\n'.join(bodylines) + #print source + #print "*"*60 exec source in miniglobals func = miniglobals[funcname] - self.to_install.append((target, funcname, func, source)) + self.to_install.append((target, funcname, func, source, fallback)) return func Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/objspace.py Mon Feb 7 16:39:25 2005 @@ -36,7 +36,13 @@ # install all the MultiMethods into the space instance for name, mm in self.MM.__dict__.items(): if isinstance(mm, MultiMethod) and not hasattr(self, name): - func = mm.install_not_sliced(self.model.typeorder) + exprargs, expr, miniglobals, fallback = ( + mm.install_not_sliced(self.model.typeorder, baked_perform_call=False)) + + func = stdtypedef.make_perform_trampoline('__mm_'+name, + exprargs, expr, miniglobals, + mm) + # e.g. add(space, w_x, w_y) boundmethod = func.__get__(self) # bind the 'space' argument setattr(self, name, boundmethod) # store into 'space' instance Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stdtypedef.py Mon Feb 7 16:39:25 2005 @@ -2,7 +2,6 @@ from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import TypeDef, GetSetProperty, Member from pypy.objspace.std.model import MultiMethod, FailedToImplement -from pypy.objspace.std.multimethod import well_just_complain __all__ = ['StdTypeDef', 'newmethod', 'gateway', 'GetSetProperty', 'Member', 'attrproperty', 'attrproperty_w', @@ -147,10 +146,10 @@ ## return r -def sliced_typeorders(typeorder, multimethod, typedef, i): +def sliced_typeorders(typeorder, multimethod, typedef, i, local=False): list_of_typeorders = [typeorder] * multimethod.arity - prefix = '__mm_' + multimethod.name - if typedef is not None: + prefix = '_mm_' + multimethod.name + if not local: # slice sliced_typeorder = {} for type, order in typeorder.items(): @@ -164,18 +163,27 @@ sliced_typeorder[type] = lst list_of_typeorders[i] = sliced_typeorder prefix += '_%sS%d' % (typedef.name, i) + else: + prefix = typedef.name +'_mth'+prefix return prefix, list_of_typeorders def typeerrormsg(space, operatorsymbol, args_w): - return space.wrap("XXX insert message here") - -def wrap_func_in_trampoline(func, multimethod, selfindex=0): - # mess to figure out how to put a gateway around 'func' + type_names = [ space.type(w_arg).name for w_arg in args_w ] + if len(args_w) > 1: + plural = 's' + else: + plural = '' + msg = "unsupported operand type%s for %s (%s)" % ( + plural, operatorsymbol, + ', '.join(type_names)) + return space.wrap(msg) + +def make_perform_trampoline(prefix, exprargs, expr, miniglobals, multimethod, selfindex=0, + allow_NotImplemented_results=False): + # mess to figure out how to put a gateway around executing expr argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] explicit_argnames = multimethod.extras.get('argnames', []) argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames - # XXX do something about __call__ and __init__ which still use - # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w solid_arglist = ['w_'+name for name in argnames] wrapper_arglist = solid_arglist[:] if multimethod.extras.get('varargs_w', False): @@ -187,10 +195,9 @@ if multimethod.extras.get('general__args__', False): wrapper_arglist.append('__args__') - miniglobals = {'perform_call': func, - 'OperationError': OperationError, - 'FailedToImplement': FailedToImplement, - 'typeerrormsg': typeerrormsg} + miniglobals.update({ 'OperationError': OperationError, + 'typeerrormsg': typeerrormsg}) + app_defaults = multimethod.extras.get('defaults', ()) i = len(argnames) - len(app_defaults) wrapper_signature = wrapper_arglist[:] @@ -202,23 +209,33 @@ wrapper_signature.insert(0, wrapper_signature.pop(selfindex)) wrapper_sig = ', '.join(wrapper_signature) - wrapper_args = ', '.join(wrapper_arglist) - if len(multimethod.specialnames) > 1: + + src = [] + dest = [] + for wrapper_arg,expr_arg in zip(['space']+wrapper_arglist, exprargs): + if wrapper_arg != expr_arg: + src.append(wrapper_arg) + dest.append(expr_arg) + renaming = ', '.join(dest) +" = "+', '.join(src) + + if allow_NotImplemented_results and len(multimethod.specialnames) > 1: # turn FailedToImplement into NotImplemented - code = """def trampoline(space, %s): + code = """def %s_perform_call(space, %s): + %s try: - return perform_call(space, %s) + return %s except FailedToImplement, e: if e.args: raise OperationError(e.args[0], e.args[1]) else: return space.w_NotImplemented -""" % (wrapper_sig, wrapper_args) +""" % (prefix, wrapper_sig, renaming, expr) else: # turn FailedToImplement into nice TypeErrors - code = """def trampoline(space, %s): + code = """def %s_perform_call(space, %s): + %s try: - w_res = perform_call(space, %s) + w_res = %s except FailedToImplement, e: if e.args: raise OperationError(e.args[0], e.args[1]) @@ -228,10 +245,10 @@ if w_res is None: w_res = space.w_None return w_res -""" % (wrapper_sig, wrapper_args, +""" % (prefix, wrapper_sig, renaming, expr, multimethod.operatorsymbol, ', '.join(solid_arglist)) exec code in miniglobals - return miniglobals['trampoline'] + return miniglobals["%s_perform_call" % prefix] def wrap_trampoline_in_gateway(func, methname, multimethod): unwrap_spec = [gateway.ObjSpace] + [gateway.W_Root]*multimethod.arity @@ -243,7 +260,7 @@ unwrap_spec.append(gateway.Arguments) return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) -def slicemultimethod(space, multimethod, typedef, result): +def slicemultimethod(space, multimethod, typedef, result, local=False): from pypy.objspace.std.objecttype import object_typedef for i in range(len(multimethod.specialnames)): # each MultimethodCode embeds a multimethod @@ -256,11 +273,14 @@ continue prefix, list_of_typeorders = sliced_typeorders( - space.model.typeorder, multimethod, typedef, i) - func = multimethod.install(prefix, list_of_typeorders) - if func is well_just_complain: + space.model.typeorder, multimethod, typedef, i, local=local) + exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, + baked_perform_call=False) + if fallback: continue # skip empty multimethods - trampoline = wrap_func_in_trampoline(func, multimethod, i) + trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals, + multimethod, i, + allow_NotImplemented_results=True) gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) gw.bound_position = i # for the check above result[methname] = gw @@ -272,7 +292,7 @@ slicemultimethod(space, multimethod, typedef, result) # import all multimethods defined directly on the type without slicing for multimethod in typedef.local_multimethods: - slicemultimethod(space, multimethod, None, result) + slicemultimethod(space, multimethod, typedef, result, local=True) return result ##class MultimethodCode(eval.Code): Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/test/test_multimethod.py Mon Feb 7 16:39:25 2005 @@ -37,6 +37,7 @@ W_BoolObject: [(W_BoolObject, None), (W_IntObject, delegate_b2i)], W_StringObject: [(W_StringObject, None)], } + mod.typeorder = typeorder mod.add1 = add.install('__add', [typeorder, typeorder]) @@ -63,3 +64,31 @@ assert add1(space, w_b, w_b) == 'fine' raises(FailedToImplement, "add1(space, w_b, w_s)") raises(FailedToImplement, "add1(space, w_s, w_b)") + +def test_not_baked(): + add2 = add.install('__add2', [typeorder, typeorder],baked_perform_call=False) + assert add2[0] == ['space', 'arg0', 'arg1'] + assert add2[1] == 'arg0.__add2(space, arg1)' + assert isinstance(add2[2], dict) + assert not add2[3] + +def test_empty(): + add3_installer = Installer(add, '__add3', [{},{}]) + assert add3_installer.is_empty() + assert len(add3_installer.to_install) == 1 + assert add3_installer.to_install[0][0] is None + +def test_empty_direct(): + assert not add.install_if_not_empty('__add4', [{},{}]) + + +def test_empty_not_baked(): + add5_installer = Installer(add, '__add5', [{},{}], baked_perform_call=False) + assert add5_installer.is_empty() + assert len(add5_installer.to_install) == 0 + add5 = add5_installer.install() + assert add5[0] == ['space', 'arg0', 'arg1'] + assert add5[1] == 'raiseFailedToImplement()' + assert isinstance(add5[2], dict) + assert add5[3] + From pedronis at codespeak.net Mon Feb 7 17:47:06 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 7 Feb 2005 17:47:06 +0100 (MET) Subject: [pypy-svn] r8958 - pypy/branch/dist-simpler-multimethods/pypy/objspace/std Message-ID: <20050207164706.AD2C727C51@code1.codespeak.net> Author: pedronis Date: Mon Feb 7 17:47:06 2005 New Revision: 8958 Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py Log: let again seqs mul and seqs getitem etc work with longs too Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/listobject.py Mon Feb 7 17:47:06 2005 @@ -57,9 +57,9 @@ result = w_list.ob_size return W_IntObject(space, result) -def getitem__List_Int(space, w_list, w_index): +def getitem__List_ANY(space, w_list, w_index): items = w_list.ob_item - idx = w_index.intval + idx = space.int_w(w_index) if idx < 0: idx += w_list.ob_size if idx < 0 or idx >= w_list.ob_size: @@ -114,9 +114,8 @@ list_extend__List_ANY(space, w_list1, w_iterable2) return w_list1 -def mul__List_Int(space, w_list, w_int): +def mul_list_times(space, w_list, times): w_res = W_ListObject(space, []) - times = w_int.intval src = w_list.ob_item size = w_list.ob_size newlen = size * times # XXX check overflow @@ -130,8 +129,11 @@ w_res.ob_size = p return w_res -def mul__Int_List(space, w_int, w_list): - return mul__List_Int(space, w_list, w_int) +def mul__List_ANY(space, w_list, w_times): + return mul_list_times(space, w_list, space.int_w(w_times)) + +def mul__ANY_List(space, w_times, w_list): + return mul_list_times(space, w_list, space.int_w(w_times)) def eq__List_List(space, w_list1, w_list2): items1 = w_list1.ob_item @@ -173,8 +175,8 @@ # upto here, lists are nearly identical to tuples, despite the # fact that we now support over-allocation! -def delitem__List_Int(space, w_list, w_idx): - i = w_idx.intval +def delitem__List_ANY(space, w_list, w_idx): + i = space.int_w(w_idx) if i < 0: i += w_list.ob_size if i < 0 or i >= w_list.ob_size: @@ -202,9 +204,9 @@ _del_slice(w_list, i, i+1) return space.w_None -def setitem__List_Int_ANY(space, w_list, w_index, w_any): +def setitem__List_ANY_ANY(space, w_list, w_index, w_any): items = w_list.ob_item - idx = w_index.intval + idx = space.int_w(w_index) if idx < 0: idx += w_list.ob_size if idx < 0 or idx >= w_list.ob_size: Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/stringobject.py Mon Feb 7 17:47:06 2005 @@ -22,7 +22,7 @@ __eq__ def eq__String_String(space, w_str1, w_str2): __ge__ def ge__String_String(space, w_str1, w_str2): __getattribute__ -__getitem__ def getitem__String_Int(space, w_str, w_int): def getitem__String_Slice(space, w_str, w_slice): +__getitem__ def getitem__String_ANY(space, w_str, w_int): def getitem__String_Slice(space, w_str, w_slice): __getslice__ __gt__ def gt__String_String(space, w_str1, w_str2): __hash__ def hash__String(space, w_str): @@ -39,12 +39,12 @@ __setattr__ __str__ def str__String(space, w_str): capitalize def str_capitalize__String(space, w_self): -center def str_center__String_Int(space, w_self): -count def str_count__String_String_Int_Int(space, w_self): [optional arguments not supported now] +center def str_center__String_ANY(space, w_self): +count def str_count__String_String_ANY_ANY(space, w_self): [optional arguments not supported now] decode !Unicode not supported now encode !Unicode not supported now endswith str_endswith__String_String [optional arguments not supported now] -expandtabs str_expandtabs__String_Int +expandtabs str_expandtabs__String_ANY find OK index OK isalnum def str_isalnum__String(space, w_self): def _isalnum(ch): @@ -63,7 +63,7 @@ rindex OK rjust def str_rjust__String_ANY(space, w_self, w_arg): rstrip def str_rstrip__String_String(space, w_self, w_chars): -split def str_split__String_None_Int(space, w_self, w_none, w_maxsplit=-1):def str_split__String_String_Int(space, w_self, w_by, w_maxsplit=-1): +split def str_split__String_None_ANY(space, w_self, w_none, w_maxsplit=-1):def str_split__String_String_ANY(space, w_self, w_by, w_maxsplit=-1): splitlines def str_splitlines__String_String(space, w_self, w_keepends): startswith str_startswith__String_String [optional arguments not supported now] strip def str_strip__String_String(space, w_self, w_chars): @@ -890,8 +890,8 @@ else: return space.w_False -def getitem__String_Int(space, w_str, w_int): - ival = space.int_w(w_int) +def getitem__String_ANY(space, w_str, w_index): + ival = space.int_w(w_index) str = w_str._value slen = len(str) if ival < 0: @@ -912,9 +912,8 @@ w_empty = space.newstring([]) return str_join__String_ANY(space, w_empty, w_r) -def mul__String_Int(space, w_str, w_mul): +def mul_string_times(space, w_str, mul): input = w_str._value - mul = space.int_w(w_mul) if mul < 0: return space.wrap("") input_len = len(input) @@ -931,8 +930,11 @@ return space.wrap("".join(buffer)) -def mul__Int_String(space, w_mul, w_str): - return mul__String_Int(space, w_str, w_mul) +def mul__String_ANY(space, w_str, w_times): + return mul_string_times(space, w_str, space.int_w(w_times)) + +def mul__ANY_String(space, w_mul, w_str): + return mul_string_times(space, w_str, space.int_w(w_times)) def add__String_String(space, w_left, w_right): right = w_right._value Modified: pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py (original) +++ pypy/branch/dist-simpler-multimethods/pypy/objspace/std/tupleobject.py Mon Feb 7 17:47:06 2005 @@ -29,10 +29,10 @@ result = len(w_tuple.wrappeditems) return W_IntObject(space, result) -def getitem__Tuple_Int(space, w_tuple, w_index): +def getitem__Tuple_ANY(space, w_tuple, w_index): items = w_tuple.wrappeditems try: - w_item = items[w_index.intval] + w_item = items[space.int_w(w_index)] except IndexError: raise OperationError(space.w_IndexError, space.wrap("tuple index out of range")) @@ -64,14 +64,15 @@ items2 = w_tuple2.wrappeditems return W_TupleObject(space, items1 + items2) -def mul__Tuple_Int(space, w_tuple, w_int): +def mul_tuple_times(space, w_tuple, times): items = w_tuple.wrappeditems - times = w_int.intval - return W_TupleObject(space, items * times) + return W_TupleObject(space, items * times) +def mul__Tuple_ANY(space, w_tuple, w_times): + return mul_tuple_times(space, w_tuple, space.int_w(w_times)) -def mul__Int_Tuple(space, w_int, w_tuple): - return mul__Tuple_Int(space, w_tuple, w_int) +def mul__ANY_Tuple(space, w_times, w_tuple): + return mul_tuple_times(space, w_tuple, space.int_w(w_times)) def eq__Tuple_Tuple(space, w_tuple1, w_tuple2): items1 = w_tuple1.wrappeditems From ac at codespeak.net Mon Feb 7 18:07:19 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 7 Feb 2005 18:07:19 +0100 (MET) Subject: [pypy-svn] r8960 - pypy/dist/pypy/objspace/std Message-ID: <20050207170719.1ED4027C51@code1.codespeak.net> Author: ac Date: Mon Feb 7 18:07:18 2005 New Revision: 8960 Modified: pypy/dist/pypy/objspace/std/listobject.py Log: Make it possible to run (but with failing tests) cpythons test_builtins Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Mon Feb 7 18:07:18 2005 @@ -47,6 +47,14 @@ pass # empty list elif len(args) == 1: w_iterable = args[0] + length = 0 + try: + length = space.int_w(space.len(w_iterable)) + if length < 0: + length = 8 + except OperationError, e: + pass # for now + _list_resize(w_list, length) w_iterator = space.iter(w_iterable) while True: try: From cfbolz at codespeak.net Mon Feb 7 19:02:05 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Mon, 7 Feb 2005 19:02:05 +0100 (MET) Subject: [pypy-svn] r8962 - pypy/dist/pypy/translator/llvm Message-ID: <20050207180205.4F9FF27C5C@code1.codespeak.net> Author: cfbolz Date: Mon Feb 7 19:02:05 2005 New Revision: 8962 Removed: pypy/dist/pypy/translator/llvm/llvm_gc.txt pypy/dist/pypy/translator/llvm/test.html Log: Removed two files I accidentally added. Deleted: /pypy/dist/pypy/translator/llvm/llvm_gc.txt ============================================================================== --- /pypy/dist/pypy/translator/llvm/llvm_gc.txt Mon Feb 7 19:02:05 2005 +++ (empty file) @@ -1,206 +0,0 @@ -From sabre at nondot.org Fri Oct 29 02:19:53 2004 -From: sabre at nondot.org (Chris Lattner) -Date: Fri Oct 29 02:01:46 2004 -Subject: [LLVMdev] Getting started with GC -In-Reply-To: <20041028223528.GA31467 at kwai.cs.uiuc.edu> -Message-ID: - -On Thu, 28 Oct 2004, Tom Brown wrote: - -> We have a few questions about the current state of GC. - -Ok. :) - -> We decided to start (and finish?) our work by finishing SemiSpace. - -Sounds good. - -> process_pointer is meant to move objects from CurSpace to OtherSpace. -> How can it find pointers to a moved object? - -This is entirely up to you, as you're basically implementing the semispace -collector in its entirety. See below. - -> How does it know the size of each object? - -I'm a big fan of starting simple. As such, I'd suggest using this scheme: - -When an object is allocated: add a size word on front of it. This size of -every object should be rounded up to a multiple of 4. When it is being -GC'd, replace the size with the forwarding pointer, but with the low bit -set. Because the low bit is set, you should be able to tell if an object -is forwarded or not. This allows you to do the simple, standard, in-place -depth-first traversal of the heap when you are GC'ing from one space to -the other. - -> Assuming we are writing a GC that will only work from llvm assembly our -> best option seems to be forcing the assembly code to follow a convention -> that identifies pointers. - -There are three issues: - -1. Object references from the stack -2. Object references from globals -3. Object references from the heap - -#1 is the hardest from the code generation standpoint, and it is what LLVM -provides direct support for. #2 is really a matter of convention, and -having the GC export and interface that can be used by langugage front-end -in question to register global pointers. #3 requires object descriptors -of some sort, produces by the front-end and consumed by the GC. See -below. - -> The SemiSpace code could keep a map from each allocated pointer to its -> size, similar to how I think malloc works. - -For this, I would suggest just putting a header word on the object, -containing the size. This is not optimal, but will be a good place to -start. Later this can be improved. - -> http://llvm.cs.uiuc.edu/docs/GarbageCollection.html (Which seems to be -> the inverse of out-of-date, whatever that is) -> Says that there is strong dependency between the frontend and GC -> implementations. - -Yes. The GC needs information from the front-end, in particular how it -lays out objects and where to find object references. - -> For example, it seems as though the frontend and GC need to agree on a -> structure for the Meta data and they may call each other during -> allocation and garbage collection. - -Yes. They don't actually need to 'agree', but there needs to be an API -provided by the language runtime and consumed by the GC, that is used to -encode the information. One way is to standardize maps, a more general -way is to expose API's to access the maps that the front-end produces -(allowing the front-end to produce them in any format it wants). - -> I imagine it would be good to decouple the frontend and GC as much as -> possible or one may need to be reimplemented when the other is changed. -> Do you have any intentions for the use of Meta in SemiSpace? - -I'm not sure what you mean by 'meta', but if you mean metadata, yes. - -> We could trample around and make something work but it seems as -> though you have built most of the support structure for GC. We are -> trying to follow that plan. - -Sounds good. This is what I envision. :) The 'vision' encompases many -langauges and different implementation strategies, but lets start with one -that you are likely to be familiar with. Anything you do here can be -extended to the full vision, if and when you find yourself with tons of -spare time at the end of your project. :) - -Lets imagine that you have a language like Java. All GC'd objects in Java -have vtables, and from this vtable a wealth of information about the -object is accessible (e.g. it's size, whether it's an array, GC map -information, etc). The layout of objects in Java might look something -something like this: - - -obj ptr --\ - | - v - [ vtable ptr ] ----> [ rtti info ] ----> ... - [ obj word 1 ] [ gc info ] ----> [ obj size ] - [ obj word 2 ] [ vf ptr #1 ] [ Flags ] -> is array, etc - ... ... [ gc map #1 ] - [ obj word N ] [ vf ptr #N ] [ gc map ...] - -In addition, there are some number of "globals" (really statics fields in -Java) that can contain references. Given this, it seems like your GC -needs the front-end to provide the following: - -1. A way of identifying/iterating all of the global references. It seems - reasonable for the GC to expose a function like "void gc_add_static_root(void**)" - which the front-end would emit calls to. Java has 'class initializers' - which are called to initialize static members of classes (and other - stuff), so the language front-end could easily insert calls to this - function in the initializer. -2. A way of getting the size of an object. Initially you can use a header - word on the object, but eventually, it would be nice if the front-end - runtime library would provide a function, say - "unsigned gc_fe_get_object_size(void *object)", which could be called - by the GC implementation to get this information. With the approach - above, if the object was a non-array, it would just get the object size - field from the GC info (using several pointer dereferences from - 'object'. If it's an array, the FE runtime would do something perhaps - more complex to get this info, but you wouldn't really care what it - was :). VM's like Java often specialize a number of other cases (like - strings) as well, and obviously the GC doesn't want to know the details - of this hackery. -3. A way of iterating over the (language specific) GC map information for - a heap object. In particular, you need a way to identify the - offsets of all of the outgoing pointers from the start of a heap object. - I'm not sure what the best way to do this is (or the best way to - encode this) but I'm sure you can come up with something. :) The most - naive and inefficient interface (always a good starting place) would be - to have the front-end provide a callback: - _Bool gc_fe_is_pointer(void *obj, unsigned offset) - that the GC can use to probe all of the words in the object to see if - they are pointers. This can obviously be improved. :) - -In a naive implementation, the result of these callbacks will be -extremely inefficient, as all of these functions are very small and will -be extremely frequently called when a GC happens. In practice, because -this is LLVM, we can do things a little bit smarter. :) - -In particular, when a source language's runtime library is built, it will -include two things: all of the GC hooks it is required to implement, and -an actual GC implementation, chosen from runtime/GC directory. When this -is linked together, the link-time optimizer will link all of the little -helper functions above into the GC, inlining and optimizing the result, -resulting in a no overhead solution. - - -As far as your class project, the following steps make sense to me: - -The first step is to get the alloc_loop testcase fully working, as it -doesn't require any of the fancy extra interfaces. This can be done -directly by adding the object header (I believe), and finishing semispace -as it stands today. This should be simple and get you started with the GC -interfaces. - -The next step in this is to flush out the interface between the GC and -the language runtime. The GC doesn't want to know anything about how the -FE lays out vtables and GC info, and the front-end doesn't want to know -anything about how the GC implements its algorithm. The -runtime/GC/GCInterface.h file is a start on this, but the callbacks -described above will also need to be added. - -The next step is to extend alloc_loop to use these interfaces. It might -be useful to translate it to C code, to make it easier to deal with. ->From there, you can add one feature at a time, iterating between adding -features (like global pointers or pointers in heap objects) to the -alloc_loop test, and adding features to the GC. Eventually you will have -the full set of features listed above. - -Note that (by hacking on alloc_loop and other testcases you write), you -are basically writing a file that would be generated by a garbage -collected language front-end. Because of this, you get to write all of -the vtables/GC info by hand, and can include the "language runtime" -callbacks directly in the program. - - -This is a somewhat big task, but can be done incrementally. Let me -emphasize this point: to do this successfully, it is pretty important that -you try to add one little step to the testcase, and add the corresponding -feature to the GC, working a step at a time. As you find that you need to -change the interfaces on either side, go ahead and do so. If you work -incrementally, you will always have something that *works*, and is better -than the previous step. If you add something that is completely horrible -and you decide is a bad idea, you can always revert to something close by -that is known good. For your course project, you obviously want to get -the most implemented possible (ideally all of the above), but if technical -difficulties or other unforseen problems come up, at least you will have -something working and some progress to show. - -If you have any questions, please feel free to ask here. I'm pretty busy -over these couple of weeks (so my answers may be a little slow), but I -really want you guys to be successful! - --Chris - --- -http://llvm.org/ -http://nondot.org/sabre/ \ No newline at end of file Deleted: /pypy/dist/pypy/translator/llvm/test.html ============================================================================== --- /pypy/dist/pypy/translator/llvm/test.html Mon Feb 7 19:02:05 2005 +++ (empty file) @@ -1,52 +0,0 @@ - - - - - - -Description of the llvm backend - - - -
-

Description of the llvm backend

-

The llvm backend ("genllvm") tries to generate llvm-assembly out of an -annotated flowgraph. The annotation has to be complete for genllvm to -work. The produced assembly can then be optimized and converted to native code -by llvm. A simple Pyrex wrapper for the entry function is then generated to be -able to use the llvm-compiled functions from Python.

-
-

How to use genllvm

-

To try it out use the function 'llvmcompile' in the module -pypy.translator.llvm.genllvm on an annotated flowgraph:

-
-%pypy/translator/llvm> python -i genllvm.py
->>> t = Translator(test.my_gcd) 
->>> a = t.annotate([int, int])
->>> f = llvmcompile(t)
->>> f(10, 2)
-2
->>> f(14, 7)
-7
-
-
-
-

Structure

-

The llvm backend consists of several parts:

-
-
    -
  1. -
-
-
-

Things that work:

-
-
    -
  • ints, bools, function calls
  • -
-
-
-
-
- - From tismer at codespeak.net Mon Feb 7 19:54:19 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 7 Feb 2005 19:54:19 +0100 (MET) Subject: [pypy-svn] r8966 - pypy/dist/pypy/interpreter Message-ID: <20050207185419.B0C9927C5F@code1.codespeak.net> Author: tismer Date: Mon Feb 7 19:54:19 2005 New Revision: 8966 Modified: pypy/dist/pypy/interpreter/function.py Log: fixed a small bug where closure is not set to a sequence. In accordance to CPython, this returns w_None. Modified: pypy/dist/pypy/interpreter/function.py ============================================================================== --- pypy/dist/pypy/interpreter/function.py (original) +++ pypy/dist/pypy/interpreter/function.py Mon Feb 7 19:54:19 2005 @@ -125,7 +125,10 @@ def fget_func_closure(space, w_self): self = space.interpclass_w(w_self) - w_res = space.newtuple( [ space.wrap(i) for i in self.closure ] ) + if self.closure is not None: + w_res = space.newtuple( [ space.wrap(i) for i in self.closure ] ) + else: + w_res= space.w_None return w_res From tismer at codespeak.net Mon Feb 7 19:58:04 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 7 Feb 2005 19:58:04 +0100 (MET) Subject: [pypy-svn] r8967 - in pypy/dist/pypy: lib tool Message-ID: <20050207185804.6021B27C63@code1.codespeak.net> Author: tismer Date: Mon Feb 7 19:58:04 2005 New Revision: 8967 Modified: pypy/dist/pypy/lib/_classobj.py pypy/dist/pypy/tool/sourcetools.py Log: added class NiceTranslate for compilation of dynamically generated methods, see _classobj.py . The generated code objects have correct source info instead of just "" Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Mon Feb 7 19:58:04 2005 @@ -1,5 +1,9 @@ import sys, operator +# producing nicer code objects by exec +from pypy.tool.sourcetools import NiceCompile +_compile = NiceCompile(globals()) + def coerce(left, right): # XXX this is just a surrogate for now # XXX the builtin coerce needs to be implemented by PyPy @@ -345,50 +349,59 @@ # unary operators for op in "neg pos abs invert int long float oct hex".split(): - exec (""" -def __%(op)s__(self): - return instance_getattr1(self, '__%(op)s__')() -""") % {"op": op} + exec _compile(""" + + def __%(op)s__(self): + return instance_getattr1(self, '__%(op)s__')() + +""", {"op": op}) del op # binary operators for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split(): - exec(""" -def __%(op)s__(self, other): - coerced = coerce(self, other) - if coerced is None or coerced[0] is self: - func = instance_getattr1(self, '__%(op)s__', False) - if func: - return func(other) - return NotImplemented - else: - return %(module)s%(op2)s(self, other) + opref = op + if op in ['and', 'or']: + opref = op + '_' + if op not in ['divmod']: + opref = 'operator.' + opref + exec _compile(""" -def __r%(op)s__(self, other): - coerced = coerce(self, other) - if coerced is None or coerced[0] is self: - func = instance_getattr1(self, '__r%(op)s__', False) - if func: - return func(other) - return NotImplemented - else: - return %(module)s%(op2)s(other, self) -""") % {"op": op, "op2": (op, op+'_')[op in ('and', 'or', 'not')], - "module": ('operator.', '')[op == 'divmod']} - del op + def __%(op)s__(self, other): + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__%(op)s__', False) + if func: + return func(other) + return NotImplemented + else: + return %(opref)s(self, other) + + def __r%(op)s__(self, other): + coerced = coerce(self, other) + if coerced is None or coerced[0] is self: + func = instance_getattr1(self, '__r%(op)s__', False) + if func: + return func(other) + return NotImplemented + else: + return %(opref)s(other, self) + +""", {"op": op, "opref": opref}) + del op, opref # inplace operators for op in 'mod and pow truediv lshift xor rshift floordiv div sub mul add or'.split(): - exec (""" -def __i%(op)s__(self, other): - func = instance_getattr1(self, '__i%(op)s__', False) - if func: - return func(other) - return NotImplemented + exec _compile(""" -""") % {"op": op} + def __i%(op)s__(self, other): + func = instance_getattr1(self, '__i%(op)s__', False) + if func: + return func(other) + return NotImplemented + +""", {"op": op}) del op @@ -451,14 +464,15 @@ # rich comparison operations for op in 'eq ne gt lt ge le'.split(): - exec (""" -def __%(op)s__(self, other): + exec _compile(""" + + def __%(op)s__(self, other): try: return instance_getattr1(self, '__%(op)s__')(other) except AttributeError: return NotImplemented -""") % {"op": op} +""", {"op": op}) del op @@ -517,3 +531,4 @@ raise TypeError,"__cmp__ must return int" return NotImplemented +del _compile, NiceCompile Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Mon Feb 7 19:58:04 2005 @@ -1,12 +1,15 @@ # a couple of support functions which # help with generating Python source. +import sys, os + def render_docstr(func, indent_str='', closing_str=''): """ Render a docstring as a string of lines. The argument is either a docstring or an object. Note that we don't use a sequence, since we want - the docstring to line up left, reagrdless of - indentation.""" + the docstring to line up left, regardless of + indentation. The shorter triple quotes are + choosen automatically.""" if type(func) is not str: doc = func.__doc__ else: @@ -22,3 +25,49 @@ return doc +class NiceCompile(object): + """ Compiling parameterized strings in a way that debuggers + are happy. We provide correct line numbers and a real + __file__ attribute. + """ + def __init__(self, namespace): + srcname = namespace.get('__file__') + if not srcname: + # assume the module was executed from the + # command line. + srcname = os.path.abspath(sys.argv[-1]) + self.srcname = srcname + if srcname.endswith('.pyc') or srcname.endswith('.pyo'): + srcname = srcname[:-1] + if os.path.exists(srcname): + self.srcname = srcname + self.srctext = file(srcname).read() + else: + # missing source, what to do? + self.srctext = None + + def __call__(self, src, args): + """ instance NiceCompile (src, args) -- formats src with args + and returns a code object ready for exec. Instead of , + the code object has correct co_filename and line numbers. + Note that this is meant for function definitions, only. + The statemens may be left aligned. + """ + if self.srctext: + p = self.srctext.index(src) + prelines = self.srctext[:p].count("\n") + 1 + else: + prelines = 0 + # adjust indented def + for line in src.split('\n'): + content = line.strip() + if content and not content.startswith('#'): + break + # see if firstline is indented + if line and line[0].isspace(): + # fake a block + prelines -= 1 + src = 'if 1:\n' + src + src = '\n' * prelines + src % args + c = compile(src, self.srcname, "exec") + return c From tismer at codespeak.net Mon Feb 7 20:21:21 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 7 Feb 2005 20:21:21 +0100 (MET) Subject: [pypy-svn] r8968 - in pypy/dist/pypy: interpreter translator Message-ID: <20050207192121.3C2CA27C63@code1.codespeak.net> Author: tismer Date: Mon Feb 7 20:21:21 2005 New Revision: 8968 Modified: pypy/dist/pypy/interpreter/function.py pypy/dist/pypy/translator/geninterplevel.py Log: better initialization code, helper for special types via eval_helper, still no cmd line interface. Modified: pypy/dist/pypy/interpreter/function.py ============================================================================== --- pypy/dist/pypy/interpreter/function.py (original) +++ pypy/dist/pypy/interpreter/function.py Mon Feb 7 20:21:21 2005 @@ -128,7 +128,7 @@ if self.closure is not None: w_res = space.newtuple( [ space.wrap(i) for i in self.closure ] ) else: - w_res= space.w_None + w_res = space.w_None return w_res Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 7 20:21:21 2005 @@ -24,7 +24,7 @@ """ from __future__ import generators -import autopath, os, sys, exceptions, inspect +import autopath, os, sys, exceptions, inspect, types from pypy.objspace.flow.model import Variable, Constant, SpaceOperation from pypy.objspace.flow.model import FunctionGraph, Block, Link from pypy.objspace.flow.model import last_exception, last_exc_value @@ -32,7 +32,7 @@ from pypy.translator.simplify import remove_direct_loops from pypy.interpreter.pycode import CO_VARARGS, CO_VARKEYWORDS from pypy.annotation import model as annmodel -from types import FunctionType, CodeType +from types import FunctionType, CodeType, ModuleType from pypy.interpreter.error import OperationError from pypy.interpreter.argument import Arguments from pypy.objspace.std.restricted_int import r_int, r_uint @@ -100,6 +100,18 @@ "always append" list.append(self, arg) +def eval_helper(self, typename, expr): + name = self.uniquename("gtype_%s" % typename) + bltinsname = self.nameof('__builtins__') + self.initcode.append( + 'def eval_helper(expr):\n' + ' import types\n' + ' dic = space.newdict([(%s, space.w_builtins)])\n' + ' space.exec_("import types", dic, dic)\n' + ' return space.eval(expr, dic, dic)' % bltinsname) + self.initcode.append('m.%s = eval_helper(%r)' % (name, expr)) + return name + class GenRpy: def __init__(self, translator, modname=None): self.translator = translator @@ -319,12 +331,14 @@ def nameof_object(self, value): if type(value) is not object: - #raise Exception, "nameof(%r) in %r" % (value, self.currentfunc) - name = self.uniquename('g_unknown_%r' % value) - self.initcode.append('# cannot build %s as %r' % (name, object)) + # try to just wrap it? + name = self.uniquename('g_%sinst_%r' % (type(value).__name__, value)) + self.initcode.append('m.%s = space.wrap(%r)' % (name, value)) return name name = self.uniquename('g_object') - self.initcode.append('m.%s = object()'%name) + self.initcode.appendnew('_tup= space.newtuple([])\n' + 'm.%s = space.call(space.w_object, _tup)' + % name) return name def nameof_module(self, value): @@ -400,6 +414,14 @@ self.initcode.append('# build func %s' % name) return name + def skipped_class(self, cls): + # debugging only! Generates a placeholder for missing classes + # that raises an exception when called. + name = self.uniquename('gskippedclass_' + cls.__name__) + self.globaldecl.append('# global decl %s' % (name, )) + self.initcode.append('# build class %s' % name) + return name + def trans_funcname(self, s): return s.translate(C_IDENTIFIER) @@ -474,7 +496,7 @@ yield 'space.setattr(%s, %s, %s)' % ( name, self.nameof(key), self.nameof(value)) except: - print >>sys.stderr, "Problem while generating %s of %r" % ( + print >> sys.stderr, "Problem while generating %s of %r" % ( name, instance) raise if isinstance(instance, Exception): @@ -523,8 +545,11 @@ return name def nameof_classobj(self, cls): + printable_name = cls.__name__ if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): - raise Exception, "%r should never be reached" % (cls,) + #raise Exception, "%r should never be reached" % (cls,) + print "skipped class", printable_name + return self.skipped_class(cls) metaclass = "space.w_type" name = self.uniquename('gcls_' + cls.__name__) @@ -559,8 +584,6 @@ if key in ['__module__', '__doc__', '__dict__', '__weakref__', '__repr__', '__metaclass__']: continue - # XXX some __NAMES__ are important... nicer solution sought - #raise Exception, "unexpected name %r in class %s"%(key, cls) # redirect value through class interface, in order to # get methods instead of functions. @@ -620,39 +643,43 @@ type: 'space.w_type', complex:'space.wrap(types.ComplexType)', unicode:'space.w_unicode', - file: 'space.wrap(file)', - type(None): 'space.wrap(types.NoneType)', - CodeType: 'space.wrap(types.CodeType)', + file: (eval_helper, 'file', 'file'), + type(None): (eval_helper, 'NoneType', 'types.NoneType'), + CodeType: (eval_helper, 'code', 'types.CodeType'), + ModuleType: (eval_helper, 'ModuleType', 'types.ModuleType'), + xrange: (eval_helper, 'xrange', 'types.XRangeType'), ##r_int: 'space.w_int', ##r_uint: 'space.w_int', - # XXX we leak 5 references here, but that's the least of the - # problems with this section of code - # type 'builtin_function_or_method': - type(len): 'space.wrap(types.FunctionType)', + type(len): (eval_helper, 'FunctionType', 'types.FunctionType'), # type 'method_descriptor': # XXX small problem here: # XXX with space.eval, we get # XXX but with wrap, we get - type(list.append): 'eval_helper(space, "list.append")', + type(list.append): (eval_helper, "method_descriptor", "list.append"), # type 'wrapper_descriptor': - type(type(None).__repr__): 'eval_helper(space, ".type(None).__repr__")', + type(type(None).__repr__): (eval_helper, "wrapper_descriptor", + "type(type(None).__repr__)"), # type 'getset_descriptor': # XXX here we get , # while eval gives us - type(type.__dict__['__dict__']): 'eval_helper(space,'\ - ' "type(type.__dict__[\'__dict__\'])")', + type(type.__dict__['__dict__']): (eval_helper, "getset_descriptor", '\ + ' "type(type.__dict__[\'__dict__\'])"), # type 'member_descriptor': # XXX this does not work in eval! # type(type.__dict__['__basicsize__']): "cannot eval type(type.__dict__['__basicsize__'])", # XXX there seems to be no working support for member descriptors ??? - type(type.__dict__['__basicsize__']): "space.wrap(type(type.__dict__['__basicsize__']))", - } + type(types.GeneratorType.gi_frame): + (eval_helper, "member_descriptor", 'type(types.GeneratorType.gi_frame)') + } def nameof_type(self, cls): if cls in self.typename_mapping: - return self.typename_mapping[cls] + ret = self.typename_mapping[cls] + if type(ret) is tuple: + ret = ret[0](self, ret[1], ret[2]) + return ret assert cls.__module__ != '__builtin__', \ "built-in class %r not found in typename_mapping" % (cls,) return self.nameof_classobj(cls) @@ -755,7 +782,8 @@ for line in txt.split("\n"): ign, name, value = line.split(None, 2) dic[name] = eval(value) - key = dic["filename"], dic["firstlineno"], uniqueno + key = (dic["filename"], dic["firstlineno"], + dic["function"], uniqueno) return key order_sections(fname) @@ -770,6 +798,7 @@ self.translator.functions[0].__name__), 'entrypoint': self.nameof(self.translator.functions[0]), } + self.entrypoint = info['entrypoint'] # header print >> f, self.RPY_HEADER print >> f @@ -895,7 +924,12 @@ def install_func(f_name, name): yield '' yield '%s = %s' % (f_name, name) - yield 'del %s' % (name,) + import __builtin__ + dic = __builtin__.__dict__ + if dic.get(name): + yield 'del %s # hiding a builtin!' % name + else: + self.initcode.append('del m.%s' % (name,)) print >> f, 'def %s(space, __args__):' % (name,) if docstr is not None: @@ -920,9 +954,9 @@ signature = ", ".join([signature, repr(varargname), repr(varkwname)]) print >> f, signature - print >> f, ' def_w = [%s]' % ", ".join(name_of_defaults) + print >> f, ' defaults_w = [%s]' % ", ".join(name_of_defaults) - print >> f, ' %s__args__.parse(funcname, signature, def_w)' % ( + print >> f, ' %s__args__.parse(funcname, signature, defaults_w)' % ( tupassstr(fast_args),) print >> f, ' return %s(%s)' % (fast_name, ', '.join(["space"]+fast_args)) @@ -1112,36 +1146,6 @@ 'A' <= chr(i) <= 'Z') and chr(i) or '_') for i in range(256)]) -# temporary arg parsing -# what about keywords? Gateway doesn't support it. -def PyArg_ParseMini(space, name, minargs, maxargs, args_w, defaults_w): - err = None - if len(args_w) < minargs: - txt = "%s() takes at least %d argument%s (%d given)" - plural = ['s', ''][minargs == 1] - err = (name, minargs, plural, len(args_w)) - if len(args_w) > maxargs: - plural = ['s', ''][maxargs == 1] - if minargs == maxargs: - if minargs == 0: - txt = '%s() takes no arguments (%d given)' - err = (name, len(args_w)) - elif minargs == 1: - txt = '%s() takes exactly %d argument%s (%d given)' - err = (name, maxargs, plural, len(args_w)) - else: - txt = '%s() takes at most %d argument%s (%d given)' - err = (name, maxargs, plural, len(args_w)) - if err: - w_txt = space.wrap(txt) - w_tup = space.wrap(err) - w_txt = space.mod(w_txt, w_tup) - raise OperationError(space.w_TypeError, w_txt) - - # finally, we create the result ;-) - res_w = args_w + defaults_w[len(args_w) - minargs:] - assert len(res_w) == maxargs - return res_w # _____________________________________________________________________ ## this should go into some test file @@ -1294,7 +1298,7 @@ res2 = struct.unpack('f', struct.pack('f',1.23)) return res1, res2 -def test_exceptions_helper(): +def exceptions_helper(): import pypy prefix = os.path.dirname(pypy.__file__) libdir = os.path.join(prefix, "lib") @@ -1320,6 +1324,12 @@ def make_class_instance(): return _classobj.classobj, _classobj.instance return None, make_class_instance + +def test_complex(): + return 1j + +def test_NoneType(): + return types.NoneType def all_entries(): res = [func() for func in entrypoints[:-1]] @@ -1338,19 +1348,25 @@ test_exc, test_strutil, test_struct, - test_exceptions_helper, + exceptions_helper, make_class_instance_helper, + test_complex, + test_NoneType, all_entries) -entrypoint = entrypoints[-6] +entrypoint = entrypoints[-2] if __name__ == "__main__": - dic, entrypoint = test_exceptions_helper() + # XXX TODO: + # extract certain stuff like a general module maker + # and put this into tools/compile_exceptions, maybe??? + dic, entrypoint = exceptions_helper() t = Translator(entrypoint, verbose=False, simplifying=True) gen = GenRpy(t) gen.use_fast_call = True gen.moddict = dic gen.gen_source('/tmp/look.py') - ''' + + _oldcodetogointotestcases = ''' import os, sys from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) @@ -1375,22 +1391,13 @@ def crazy_test(): """ this thingy is generating the whole interpreter in itself""" - # but doesn't work, my goto's give a problem for flow space dic = {"__builtins__": __builtins__, "__name__": "__main__"} execfile("/tmp/look.py", dic) - + + entrypoint = dic[gen.entrypoint] def test(): - f_ff(space, 2, 3) - test = type(test)(test.func_code, dic) + entrypoint() t = Translator(test, verbose=False, simplifying=True) - gen = GenRpy(t) - gen.gen_source("/tmp/look2.py") - -##>>> def f_foo(space, __args__): -##... signature = ["a", "b"], "args", "kwds" -##... defaults_w = space.w_int(42) # is this the default for b? -##... w_a, w_b, w_args, w_kwds = __args__.parse("foo", signature, defaults_w) -##... return fastf_foo(w_a, w_b, w_args, w_kwds) -##... # args/kwds can be None. -##... # then I don't receive w_xxx for them as well. + gen2 = GenRpy(t) + gen2.gen_source("/tmp/look2.py") From pedronis at codespeak.net Mon Feb 7 20:26:08 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 7 Feb 2005 20:26:08 +0100 (MET) Subject: [pypy-svn] r8969 - in pypy/dist/pypy: interpreter module objspace/std objspace/std/test Message-ID: <20050207192608.5054C27C63@code1.codespeak.net> Author: pedronis Date: Mon Feb 7 20:26:07 2005 New Revision: 8969 Added: pypy/dist/pypy/objspace/std/model.py (props changed) - copied unchanged from r8967, pypy/branch/dist-simpler-multimethods/pypy/objspace/std/model.py Modified: pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/interpreter/pycode.py pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/objspace/std/boolobject.py pypy/dist/pypy/objspace/std/booltype.py pypy/dist/pypy/objspace/std/default.py pypy/dist/pypy/objspace/std/dictobject.py pypy/dist/pypy/objspace/std/dicttype.py pypy/dist/pypy/objspace/std/fake.py pypy/dist/pypy/objspace/std/floatobject.py pypy/dist/pypy/objspace/std/floattype.py pypy/dist/pypy/objspace/std/intobject.py pypy/dist/pypy/objspace/std/inttype.py pypy/dist/pypy/objspace/std/itertype.py pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/longobject.py pypy/dist/pypy/objspace/std/longtype.py pypy/dist/pypy/objspace/std/multimethod.py pypy/dist/pypy/objspace/std/noneobject.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/objspace/std/register_all.py pypy/dist/pypy/objspace/std/sliceobject.py pypy/dist/pypy/objspace/std/stdtypedef.py pypy/dist/pypy/objspace/std/stringobject.py pypy/dist/pypy/objspace/std/stringtype.py pypy/dist/pypy/objspace/std/test/test_multimethod.py pypy/dist/pypy/objspace/std/tupleobject.py pypy/dist/pypy/objspace/std/tupletype.py pypy/dist/pypy/objspace/std/typeobject.py pypy/dist/pypy/objspace/std/unicodeobject.py Log: merged dist-simpler-multimethods branch. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 7 20:26:07 2005 @@ -14,12 +14,14 @@ from pypy.tool import hack from pypy.interpreter.error import OperationError -from pypy.interpreter import eval, pycode +from pypy.interpreter import eval from pypy.interpreter.function import Function, Method from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache +NoneNotWrapped = object() + class Signature: def __init__(self, func=None, argnames=None, varargname=None, kwargname=None, name = None): @@ -127,7 +129,16 @@ assert new_sig.varargname is None,( "built-in function %r has conflicting rest args specs" % orig_sig.func) new_sig.varargname = argname[:-2] - + +def unwrap_spec_check_w_args(orig_sig, new_sig): + argname = orig_sig.next() + assert argname.startswith('w_'), ( + "rest arguments arg %s of built-in function %r should start 'w_'" % + (argname, orig_sig.func)) + assert new_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + new_sig.varargname = argname[2:] + # recipes for checking interp2app func argumes wrt unwrap_spec unwrap_spec_checks = { ObjSpace: unwrap_spec_check_space, @@ -136,6 +147,7 @@ Arguments: unwrap_spec_check_arguments, '*': unwrap_spec_check_starargs, 'args_w': unwrap_spec_check_args_w, + 'w_args': unwrap_spec_check_w_args, } def unwrap_spec_emit_space(orig_sig, new_sig): @@ -178,6 +190,13 @@ (new_sig.through_scope_w)) new_sig.through_scope_w += 1 new_sig.run_args.append("self.args_w") + +def unwrap_spec_emit_w_args(orig_sig, new_sig): + cur = new_sig.through_scope_w + new_sig.setfastscope.append( + "self.w_args = scope_w[%d]" % cur) + new_sig.through_scope_w += 1 + new_sig.run_args.append("self.w_args") # recipes for emitting unwrapping code for arguments of a interp2app func # wrt a unwrap_spec @@ -188,6 +207,7 @@ Arguments: unwrap_spec_emit_arguments, '*': unwrap_spec_emit_starargs, 'args_w': unwrap_spec_emit_args_w, + 'w_args': unwrap_spec_emit_w_args, } # unwrap_spec_check/emit for str,int,float @@ -257,10 +277,12 @@ # 'self' is used to specify a self method argument # baseobjspace.W_Root is for wrapped arguments to keep wrapped # argument.Arguments is for a final rest arguments Arguments object - # 'args_w' for unpacktuple applied rest arguments + # 'args_w' for unpacktuple applied to rest arguments + # 'w_args' for rest arguments passed as wrapped tuple # str,int,float: unwrap argument as such type # First extract the signature from the (CPython-level) code object + from pypy.interpreter import pycode argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) if unwrap_spec is None: @@ -459,6 +481,7 @@ raise ValueError, ("function name must start with 'app_'; " "%r does not" % app.func_name) app_name = app.func_name[4:] + self.__name__ = app.func_name self.name = app_name self._staticcode = app.func_code self._staticglobals = app.func_globals @@ -466,6 +489,7 @@ def getcode(self, space): "NOT_RPYTHON" + from pypy.interpreter import pycode code = pycode.PyCode(space) code._from_code(self._staticcode) return code @@ -518,6 +542,7 @@ self._code = BuiltinCode(f, ismethod=ismethod, spacearg=spacearg, unwrap_spec=unwrap_spec) + self.__name__ = f.func_name self.name = app_name self._staticdefs = list(f.func_defaults or ()) #if self._staticdefs: @@ -531,8 +556,8 @@ "NOT_RPYTHON" defs_w = [] for val in self._staticdefs: - if val is None: - defs_w.append(val) + if val is NoneNotWrapped: + defs_w.append(None) else: defs_w.append(space.wrap(val)) return defs_w Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Mon Feb 7 20:26:07 2005 @@ -6,6 +6,7 @@ import dis from pypy.interpreter import eval +from pypy.interpreter.gateway import NoneNotWrapped from pypy.tool.cache import Cache # helper @@ -194,7 +195,8 @@ w_argcount, w_nlocals, w_stacksize, w_flags, w_codestring, w_constants, w_names, w_varnames, w_filename, w_name, w_firstlineno, - w_lnotab, w_freevars=None, w_cellvars=None): + w_lnotab, w_freevars=NoneNotWrapped, + w_cellvars=NoneNotWrapped): code = space.allocate_instance(PyCode, w_subtype) code.__init__(space) # XXX typechecking everywhere! Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Mon Feb 7 20:26:07 2005 @@ -5,6 +5,7 @@ from pypy.interpreter.pycode import PyCode from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import BaseWrappable, W_Root +from pypy.interpreter.gateway import NoneNotWrapped import __builtin__ as cpy_builtin @@ -225,7 +226,7 @@ compile.unwrap_spec = [str,str,str,int,int] -def eval(w_source, w_globals=None, w_locals=None): +def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): w = space.wrap if space.is_true(space.isinstance(w_source, space.w_str)): @@ -259,7 +260,7 @@ space.delattr(w_object, w_name) return space.w_None -def getattr(w_object, w_name, w_defvalue=None): +def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): try: return space.getattr(w_object, w_name) except OperationError, e: @@ -278,9 +279,7 @@ def hex(w_val): return space.hex(w_val) -def round(w_val, w_n=None): - if w_n is None: - w_n = space.wrap(0) +def round(w_val, w_n=0): return space.round(w_val, w_n) def id(w_object): @@ -295,7 +294,7 @@ def _issubtype(w_cls1, w_cls2): return space.issubtype(w_cls1, w_cls2) -def iter(w_collection_or_callable, w_sentinel=None): +def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): if w_sentinel is None: return space.iter(w_collection_or_callable) else: @@ -308,8 +307,6 @@ return space.ord(w_val) def pow(w_base, w_exponent, w_modulus=None): - if w_modulus is None: - w_modulus = space.w_None return space.pow(w_base, w_exponent, w_modulus) def repr(w_object): Modified: pypy/dist/pypy/objspace/std/boolobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/boolobject.py (original) +++ pypy/dist/pypy/objspace/std/boolobject.py Mon Feb 7 20:26:07 2005 @@ -16,22 +16,20 @@ """ representation for debugging purposes """ return "%s(%s)" % (w_self.__class__.__name__, w_self.boolval) + def unwrap(w_self): + return w_self.boolval + registerimplementation(W_BoolObject) # bool-to-int delegation requires translating the .boolvar attribute # to an .intval one -def delegate__Bool(space, w_bool): - return intobject.W_IntObject(space, int(w_bool.boolval)) -delegate__Bool.result_class = intobject.W_IntObject -delegate__Bool.priority = PRIORITY_PARENT_TYPE +def delegate_Bool2Int(w_bool): + return intobject.W_IntObject(w_bool.space, int(w_bool.boolval)) def nonzero__Bool(space, w_bool): return w_bool -def unwrap__Bool(space, w_bool): - return w_bool.boolval - def repr__Bool(space, w_bool): if w_bool.boolval: return space.wrap('True') Modified: pypy/dist/pypy/objspace/std/booltype.py ============================================================================== --- pypy/dist/pypy/objspace/std/booltype.py (original) +++ pypy/dist/pypy/objspace/std/booltype.py Mon Feb 7 20:26:07 2005 @@ -5,7 +5,7 @@ def descr__new__(space, w_booltype, w_obj=None): - if w_obj is not None and space.is_true(w_obj): + if space.is_true(w_obj): return space.w_True else: return space.w_False Modified: pypy/dist/pypy/objspace/std/default.py ============================================================================== --- pypy/dist/pypy/objspace/std/default.py (original) +++ pypy/dist/pypy/objspace/std/default.py Mon Feb 7 20:26:07 2005 @@ -13,7 +13,7 @@ # __init__ should succeed if called internally as a multimethod -def init__ANY(space, w_obj, w_args, w_kwds): +def init__ANY(space, w_obj, __args__): pass @@ -216,9 +216,6 @@ # ugh -class UnwrapError(Exception): - pass - def typed_unwrap_error_msg(space, expected, w_obj): w = space.wrap type_name = space.str_w(space.getattr(space.type(w_obj),w("__name__"))) @@ -236,11 +233,5 @@ raise OperationError(space.w_TypeError, typed_unwrap_error_msg(space, "float", w_obj)) -def unwrap__ANY(space, w_obj): - if isinstance(w_obj, BaseWrappable): - return w_obj - else: - raise UnwrapError, 'cannot unwrap %r' % (w_obj,) - register_all(vars()) Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Mon Feb 7 20:26:07 2005 @@ -98,40 +98,40 @@ freeslot = entry perturb >>= 5 -registerimplementation(W_DictObject) + def unwrap(w_dict): + space = w_dict.space + result = {} + for entry in w_dict.non_empties(): + # XXX generic mixed types unwrap + result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) + return result +registerimplementation(W_DictObject) -def unwrap__Dict(space, w_dict): - result = {} - for entry in w_dict.non_empties(): - result[space.unwrap(entry.w_key)] = space.unwrap(entry.w_value) # XXX generic mixed types unwrap - return result -def init__Dict(space, w_dict, w_args, w_kwds): +def init__Dict(space, w_dict, __args__): + w_src, w_kwds = __args__.parse('dict', + (['seq_or_map'], None, 'kwargs'), # signature + [W_DictObject(space, [])]) # default argument dict_clear__Dict(space, w_dict) - args = space.unpackiterable(w_args) - if len(args) == 0: - pass - elif len(args) == 1: - # XXX do dict({...}) with dict_update__Dict_Dict() - try: - space.getattr(args[0], space.wrap("keys")) - except OperationError: - list_of_w_pairs = space.unpackiterable(args[0]) - for w_pair in list_of_w_pairs: - pair = space.unpackiterable(w_pair) - if len(pair)!=2: - raise OperationError(space.w_ValueError, - space.wrap("dict() takes a sequence of pairs")) - w_k, w_v = pair - setitem__Dict_ANY_ANY(space, w_dict, w_k, w_v) - else: - from pypy.objspace.std.dicttype import dict_update__ANY_ANY - dict_update__ANY_ANY(space, w_dict, args[0]) + # XXX do dict({...}) with dict_update__Dict_Dict() + try: + space.getattr(w_src, space.wrap("keys")) + except OperationError: + list_of_w_pairs = space.unpackiterable(w_src) + for w_pair in list_of_w_pairs: + pair = space.unpackiterable(w_pair) + if len(pair)!=2: + raise OperationError(space.w_ValueError, + space.wrap("dict() takes a sequence of pairs")) + w_k, w_v = pair + setitem__Dict_ANY_ANY(space, w_dict, w_k, w_v) else: - raise OperationError(space.w_TypeError, - space.wrap("dict() takes at most 1 argument")) - space.call_method(w_dict, 'update', w_kwds) + if space.is_true(w_src): + from pypy.objspace.std.dicttype import dict_update__ANY_ANY + dict_update__ANY_ANY(space, w_dict, w_src) + if space.is_true(w_kwds): + space.call_method(w_dict, 'update', w_kwds) def getitem__Dict_ANY(space, w_dict, w_lookup): entry = w_dict.lookdict(w_dict.hash(w_lookup), w_lookup) Modified: pypy/dist/pypy/objspace/std/dicttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/dicttype.py (original) +++ pypy/dist/pypy/objspace/std/dicttype.py Mon Feb 7 20:26:07 2005 @@ -8,7 +8,7 @@ dict_has_key = MultiMethod('has_key', 2) dict_clear = MultiMethod('clear', 1) dict_get = MultiMethod('get', 3, defaults=(None,)) -dict_pop = MultiMethod('pop', 2, varargs=True) +dict_pop = MultiMethod('pop', 2, w_varargs=True) dict_popitem = MultiMethod('popitem', 1) dict_setdefault = MultiMethod('setdefault', 3, defaults=(None,)) dict_update = MultiMethod('update', 2) Modified: pypy/dist/pypy/objspace/std/fake.py ============================================================================== --- pypy/dist/pypy/objspace/std/fake.py (original) +++ pypy/dist/pypy/objspace/std/fake.py Mon Feb 7 20:26:07 2005 @@ -4,7 +4,7 @@ from pypy.interpreter.function import Function from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.objspace import W_Object, StdObjSpace -from pypy.objspace.std.default import UnwrapError +from pypy.objspace.std.model import UnwrapError from pypy.tool.cache import Cache # this file automatically generates non-reimplementations of CPython @@ -83,13 +83,12 @@ def __init__(w_self, space, val): W_Object.__init__(w_self, space) w_self.val = val + def unwrap(w_self): + return w_self.val # cannot write to W_Fake.__name__ in Python 2.2! W_Fake = type(W_Object)('W_Fake%s'%(cpy_type.__name__.capitalize()), (W_Object,), dict(W_Fake.__dict__.items())) - def fake_unwrap(space, w_obj): - return w_obj.val - StdObjSpace.unwrap.register(fake_unwrap, W_Fake) W_Fake.typedef.fakedcpytype = cpy_type return W_Fake Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Mon Feb 7 20:26:07 2005 @@ -21,14 +21,19 @@ W_Object.__init__(w_self, space) w_self.floatval = floatval + def unwrap(w_self): + return w_self.floatval + registerimplementation(W_FloatObject) +# bool-to-float delegation +def delegate_Bool2Float(w_bool): + return W_FloatObject(w_bool.space, float(w_bool.boolval)) + # int-to-float delegation -def delegate__Int(space, w_intobj): - return W_FloatObject(space, float(w_intobj.intval)) -delegate__Int.result_class = W_FloatObject -delegate__Int.priority = PRIORITY_CHANGE_TYPE +def delegate_Int2Float(w_intobj): + return W_FloatObject(w_intobj.space, float(w_intobj.intval)) # float__Float is supposed to do nothing, unless it has @@ -49,9 +54,6 @@ def float_w__Float(space, w_float): return w_float.floatval -def unwrap__Float(space, w_float): - return w_float.floatval - def app_repr__Float(f): r = "%.17g"%f for c in r: Modified: pypy/dist/pypy/objspace/std/floattype.py ============================================================================== --- pypy/dist/pypy/objspace/std/floattype.py (original) +++ pypy/dist/pypy/objspace/std/floattype.py Mon Feb 7 20:26:07 2005 @@ -1,11 +1,9 @@ from pypy.objspace.std.stdtypedef import * from pypy.interpreter.error import OperationError -def descr__new__(space, w_floattype, w_value=None): +def descr__new__(space, w_floattype, w_value=0.0): from pypy.objspace.std.floatobject import W_FloatObject - if w_value is None: - value = 0.0 - elif space.is_true(space.isinstance(w_value, space.w_str)): + if space.is_true(space.isinstance(w_value, space.w_str)): try: value = float(space.str_w(w_value)) except ValueError, e: Modified: pypy/dist/pypy/objspace/std/intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/intobject.py (original) +++ pypy/dist/pypy/objspace/std/intobject.py Mon Feb 7 20:26:07 2005 @@ -28,6 +28,9 @@ """ representation for debugging purposes """ return "%s(%d)" % (w_self.__class__.__name__, w_self.intval) + def unwrap(w_self): + return int(w_self.intval) + registerimplementation(W_IntObject) @@ -43,9 +46,6 @@ def int_w__Int(space, w_int1): return int(w_int1.intval) -def unwrap__Int(space, w_int1): - return int(w_int1.intval) - def repr__Int(space, w_int1): a = w_int1.intval res = str(a) Modified: pypy/dist/pypy/objspace/std/inttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/inttype.py (original) +++ pypy/dist/pypy/objspace/std/inttype.py Mon Feb 7 20:26:07 2005 @@ -1,14 +1,13 @@ from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.strutil import string_to_int from pypy.interpreter.error import OperationError +from pypy.interpreter.gateway import NoneNotWrapped -def descr__new__(space, w_inttype, w_value=None, w_base=None): +def descr__new__(space, w_inttype, w_value=0, w_base=NoneNotWrapped): from pypy.objspace.std.intobject import W_IntObject if w_base is None: # check for easy cases - if w_value is None: - value = 0 - elif isinstance(w_value, W_IntObject): + if isinstance(w_value, W_IntObject): value = w_value.intval elif space.is_true(space.isinstance(w_value, space.w_str)): try: Modified: pypy/dist/pypy/objspace/std/itertype.py ============================================================================== --- pypy/dist/pypy/objspace/std/itertype.py (original) +++ pypy/dist/pypy/objspace/std/itertype.py Mon Feb 7 20:26:07 2005 @@ -2,5 +2,5 @@ # ____________________________________________________________ -iter_typedef = StdTypeDef("sequence-iterator", +iter_typedef = StdTypeDef("sequenceiterator", ) Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Mon Feb 7 20:26:07 2005 @@ -29,52 +29,47 @@ reprlist = [repr(w_item) for w_item in w_self.ob_item[:w_self.ob_size]] return "%s(%s)" % (w_self.__class__.__name__, ', '.join(reprlist)) + def unwrap(w_list): + space = w_list.space + items = [space.unwrap(w_item) for w_item in w_list.ob_item[:w_list.ob_size]]# XXX generic mixed types unwrap + return list(items) + registerimplementation(W_ListObject) -def unwrap__List(space, w_list): - items = [space.unwrap(w_item) for w_item in w_list.ob_item[:w_list.ob_size]]# XXX generic mixed types unwrap - return list(items) - -def init__List(space, w_list, w_args, w_kwds): - if space.is_true(w_kwds): - raise OperationError(space.w_TypeError, - space.wrap("no keyword arguments expected")) +def init__List(space, w_list, __args__): + w_iterable, = __args__.parse('list', + (['sequence'], None, None), # signature + [W_ListObject(space, [])]) # default argument w_list.ob_size = 0 # XXX think about it later - args = space.unpackiterable(w_args) - if len(args) == 0: - pass # empty list - elif len(args) == 1: - w_iterable = args[0] - length = 0 + + length = 0 + try: + length = space.int_w(space.len(w_iterable)) + if length < 0: + length = 8 + except OperationError, e: + pass # for now + _list_resize(w_list, length) + w_iterator = space.iter(w_iterable) + while True: try: - length = space.int_w(space.len(w_iterable)) - if length < 0: - length = 8 + w_item = space.next(w_iterator) except OperationError, e: - pass # for now - _list_resize(w_list, length) - w_iterator = space.iter(w_iterable) - while True: - try: - w_item = space.next(w_iterator) - except OperationError, e: - if not e.match(space, space.w_StopIteration): - raise - break # done - _ins1(w_list, w_list.ob_size, w_item) - else: - raise OperationError(space.w_TypeError, - space.wrap("list() takes at most 1 argument")) + if not e.match(space, space.w_StopIteration): + raise + break # done + _ins1(w_list, w_list.ob_size, w_item) + def len__List(space, w_list): result = w_list.ob_size return W_IntObject(space, result) -def getitem__List_Int(space, w_list, w_index): +def getitem__List_ANY(space, w_list, w_index): items = w_list.ob_item - idx = w_index.intval + idx = space.int_w(w_index) if idx < 0: idx += w_list.ob_size if idx < 0 or idx >= w_list.ob_size: @@ -129,9 +124,8 @@ list_extend__List_ANY(space, w_list1, w_iterable2) return w_list1 -def mul__List_Int(space, w_list, w_int): +def mul_list_times(space, w_list, times): w_res = W_ListObject(space, []) - times = w_int.intval src = w_list.ob_item size = w_list.ob_size newlen = size * times # XXX check overflow @@ -145,8 +139,11 @@ w_res.ob_size = p return w_res -def mul__Int_List(space, w_int, w_list): - return mul__List_Int(space, w_list, w_int) +def mul__List_ANY(space, w_list, w_times): + return mul_list_times(space, w_list, space.int_w(w_times)) + +def mul__ANY_List(space, w_times, w_list): + return mul_list_times(space, w_list, space.int_w(w_times)) def eq__List_List(space, w_list1, w_list2): items1 = w_list1.ob_item @@ -188,8 +185,8 @@ # upto here, lists are nearly identical to tuples, despite the # fact that we now support over-allocation! -def delitem__List_Int(space, w_list, w_idx): - i = w_idx.intval +def delitem__List_ANY(space, w_list, w_idx): + i = space.int_w(w_idx) if i < 0: i += w_list.ob_size if i < 0 or i >= w_list.ob_size: @@ -217,9 +214,9 @@ _del_slice(w_list, i, i+1) return space.w_None -def setitem__List_Int_ANY(space, w_list, w_index, w_any): +def setitem__List_ANY_ANY(space, w_list, w_index, w_any): items = w_list.ob_item - idx = w_index.intval + idx = space.int_w(w_index) if idx < 0: idx += w_list.ob_size if idx < 0 or idx >= w_list.ob_size: Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Mon Feb 7 20:26:07 2005 @@ -17,9 +17,25 @@ assert isinstance(longval, long) w_self.longval = longval + def unwrap(w_self): + return w_self.longval + registerimplementation(W_LongObject) +# bool-to-long +def delegate_Bool2Long(w_bool): + return W_LongObject(w_bool.space, long(w_bool.boolval)) + +# int-to-long delegation +def delegate_Int2Long(w_intobj): + return W_LongObject(w_intobj.space, long(w_intobj.intval)) + +# long-to-float delegation +def delegate_Long2Float(w_longobj): + return W_FloatObject(w_longobj.space, float(w_longobj.longval)) + + # long__Long is supposed to do nothing, unless it has # a derived long object, where it should return # an exact one. @@ -56,9 +72,6 @@ raise OperationError(space.w_OverflowError, space.wrap("long int too large to convert to int")) -def unwrap__Long(space, w_long): - return w_long.longval - def repr__Long(space, w_long): return space.wrap(repr(w_long.longval)) @@ -223,35 +236,47 @@ register_all(vars()) -# delegations must be registered manually because we have more than one -# long-to-something delegation +# register implementations of ops that recover int op overflows -# int-to-long delegation -def delegate_from_int(space, w_intobj): - return W_LongObject(space, long(w_intobj.intval)) -delegate_from_int.result_class = W_LongObject -delegate_from_int.priority = PRIORITY_CHANGE_TYPE - -StdObjSpace.delegate.register(delegate_from_int, W_IntObject) - -# long-to-int delegation -def delegate_to_int(space, w_longobj): - if -sys.maxint-1 <= w_longobj.longval <= sys.maxint: - return W_IntObject(space, int(w_longobj.longval)) - else: - # note the 'return' here -- hack - return FailedToImplement(space.w_OverflowError, - space.wrap("long int too large to convert to int")) -delegate_to_int.result_class = W_IntObject -delegate_to_int.priority = PRIORITY_CHANGE_TYPE -delegate_to_int.can_fail = True - -StdObjSpace.delegate.register(delegate_to_int, W_LongObject) - -# long-to-float delegation -def delegate_to_float(space, w_longobj): - return W_FloatObject(space, float(w_longobj.longval)) -delegate_to_float.result_class = W_FloatObject -delegate_to_float.priority = PRIORITY_CHANGE_TYPE +# binary ops +for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod']: + exec """ +def %(opname)s_ovr__Int_Int(space, w_int1, w_int2): + w_long1 = delegate_Int2Long(w_int1) + w_long2 = delegate_Int2Long(w_int2) + return %(opname)s__Long_Long(space, w_long1, w_long2) +""" % {'opname': opname} + + getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int_Int' %opname], W_IntObject, W_IntObject, order=1) + +# unary ops +for opname in ['neg', 'abs']: + exec """ +def %(opname)s_ovr__Int(space, w_int1): + w_long1 = delegate_Int2Long(w_int1) + return %(opname)s__Long(space, w_long1) +""" % {'opname': opname} + + getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int' %opname], W_IntObject, order=1) + +# lshift +def lshift_ovr__Int_Int(space, w_int1, w_cnt): + w_long1 = delegate_Int2Long(w_int1) + return lshift__Long_Int(space, w_long1, w_cnt) + +StdObjSpace.MM.lshift.register(lshift_ovr__Int_Int, W_IntObject, W_IntObject, order=1) + +# pow +def pow_ovr__Int_Int_None(space, w_int1, w_int2, w_none3): + w_long1 = delegate_Int2Long(w_int1) + w_long2 = delegate_Int2Long(w_int2) + return pow__Long_Long_None(space, w_long1, w_long2, w_none3) + +def pow_ovr__Int_Int_Int(space, w_int1, w_int2, w_int3): + w_long1 = delegate_Int2Long(w_int1) + w_long2 = delegate_Int2Long(w_int2) + w_long3 = delegate_Int2Long(w_int3) + return pow__Long_Long_Long(space, w_long1, w_long2, w_long3) -StdObjSpace.delegate.register(delegate_to_float, W_LongObject) +StdObjSpace.MM.pow.register(pow_ovr__Int_Int_None, W_IntObject, W_IntObject, W_NoneObject, order=1) +StdObjSpace.MM.pow.register(pow_ovr__Int_Int_Int , W_IntObject, W_IntObject, W_IntObject, order=1) Modified: pypy/dist/pypy/objspace/std/longtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/longtype.py (original) +++ pypy/dist/pypy/objspace/std/longtype.py Mon Feb 7 20:26:07 2005 @@ -2,14 +2,13 @@ from pypy.objspace.std.strutil import string_to_long from pypy.interpreter.error import OperationError from pypy.objspace.std.inttype import int_typedef +from pypy.interpreter.gateway import NoneNotWrapped -def descr__new__(space, w_longtype, w_value=None, w_base=None): +def descr__new__(space, w_longtype, w_value=0, w_base=NoneNotWrapped): from pypy.objspace.std.longobject import W_LongObject if w_base is None: # check for easy cases - if w_value is None: - value = 0L - elif isinstance(w_value, W_LongObject): + if isinstance(w_value, W_LongObject): value = w_value.longval elif space.is_true(space.isinstance(w_value, space.w_str)): try: Modified: pypy/dist/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/dist/pypy/objspace/std/multimethod.py Mon Feb 7 20:26:07 2005 @@ -1,507 +1,260 @@ -from pypy.interpreter.baseobjspace import OperationError -from pypy.tool.cache import Cache -class FailedToImplement(Exception): - "Signals the dispatcher to try harder." - -class W_ANY: - "Catch-all in case multimethods don't find anything else." - typedef = None - - -# This file defines three major classes: -# -# MultiMethod is the class you instantiate explicitly. -# It is essentially just a collection of registered functions. -# If xxx is a MultiMethod, StdObjSpace.xxx is xxx again, -# and space.xxx is a BoundMultiMethod. -# -# UnboundMultiMethod is a MultiMethod on which one argument -# (typically the first one) has been restricted to be of some -# statically known type. It is obtained by the syntax -# W_XxxType.yyy, where W_XxxType is the static type class, -# or explicitly by calling 'xxx.slice(typeclass, arg_position)'. -# Its dispatch table is always a subset of the original MultiMethod's -# dispatch table. -# -# The registration of a new function to a MultiMethod will be propagated -# to all of its matching UnboundMultiMethod instances. The registration of -# a function directly to an UnboundMultiMethod will register the function -# to its base MultiMethod and invoke the same behavior. -# -# BoundMultiMethod is a MultiMethod or UnboundMultiMethod which -# has been bound to a specific object space. It is obtained by -# 'space.xxx' or explicitly by calling 'xxx.get(space)'. - -class AbstractMultiMethod(object): - """Abstract base class for MultiMethod and UnboundMultiMethod - i.e. the classes that are not bound to a specific space instance.""" - def __init__(self, operatorsymbol, arity): - "NOT_RPYTHON: cannot create new multimethods dynamically" - self.arity = arity - self.operatorsymbol = operatorsymbol - self.dispatch_table = {} - self.cache_table = Cache() - self.compilation_cache_table = {} - self.cache_delegator_key = None - self.dispatch_arity = 0 - - def __repr__(self): - return '<%s %s>' % (self.__class__.__name__, self.operatorsymbol) - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - assert len(types) == self.arity - functions = self.dispatch_table.setdefault(types, []) - if function in functions: - return False - functions.append(function) - self.cache_table.clear() - self.compilation_cache_table.clear() - self.adjust_dispatch_arity(types) - return True - - def adjust_dispatch_arity(self, types): - "NOT_RPYTHON" - width = len(types) - while width > self.dispatch_arity and types[width-1] is W_ANY: - width -= 1 - self.dispatch_arity = width - - def compile_calllist(self, argclasses, delegate): - """Compile a list of calls to try for the given classes of the - arguments. Return a function that should be called with the - actual arguments.""" - if delegate.key is not self.cache_delegator_key: - self.cache_table.clear() - self.compilation_cache_table.clear() - self.cache_delegator_key = delegate.key - return self.cache_table.getorbuild(argclasses, - self.do_compile_calllist, - delegate) - - def do_compile_calllist(self, argclasses, delegate): - "NOT_RPYTHON" - calllist = [] - self.internal_buildcalllist(argclasses, delegate, calllist) - calllist = tuple(calllist) - try: - result = self.compilation_cache_table[calllist] - except KeyError: - result = self.internal_compilecalllist(calllist) - self.compilation_cache_table[calllist] = result - return result - - def internal_compilecalllist(self, calllist): - "NOT_RPYTHON" - source, glob = self.internal_sourcecalllist(calllist) - # compile the function - exec source in glob - return glob['do'] - - def internal_sourcecalllist(self, calllist): - """NOT_RPYTHON - Translate a call list into the source of a Python function - which is optimized and doesn't do repeated conversions on the - same arguments.""" - if len(calllist) == 1: - fn, conversions = calllist[0] - if conversions == ((),) * len(conversions): - # no conversion, just calling a single function: return - # that function directly - return '', {'do': fn} - - #print '**** compile **** ', self.operatorsymbol, [ - # t.__name__ for t in argclasses] - arglist = ['a%d'%i for i in range(self.dispatch_arity)] + ['*extraargs'] - source = ['def do(space,%s):' % ','.join(arglist)] - converted = [{(): ('a%d'%i, False)} for i in range(self.dispatch_arity)] - - def make_conversion(argi, convtuple): - if convtuple in converted[argi]: - return converted[argi][convtuple] - else: - prev, can_fail = make_conversion(argi, convtuple[:-1]) - new = '%s_%d' % (prev, len(converted[argi])) - fname = all_functions.setdefault(convtuple[-1], - 'd%d' % len(all_functions)) - if can_fail: - source.append(' if isinstance(%s, FailedToImplement):' % prev) - source.append(' %s = %s' % (new, prev)) - source.append(' else:') - indent = ' ' - else: - indent = ' ' - source.append('%s%s = %s(space,%s)' % (indent, new, fname, prev)) - can_fail = can_fail or getattr(convtuple[-1], 'can_fail', False) - converted[argi][convtuple] = new, can_fail - return new, can_fail - - all_functions = {} - has_firstfailure = False - for fn, conversions in calllist: - # make the required conversions - fname = all_functions.setdefault(fn, 'f%d' % len(all_functions)) - arglist = [] - failcheck = [] - for i in range(self.dispatch_arity): - argname, can_fail = make_conversion(i, conversions[i]) - arglist.append(argname) - if can_fail: - failcheck.append(argname) - arglist.append('*extraargs') - source.append( ' try:') - for argname in failcheck: - source.append(' if isinstance(%s, FailedToImplement):' % argname) - source.append(' raise %s' % argname) - source.append( ' return %s(space,%s)' % ( - fname, ','.join(arglist))) - if has_firstfailure: - source.append(' except FailedToImplement:') - else: - source.append(' except FailedToImplement, firstfailure:') - has_firstfailure = True - source.append( ' pass') - - # complete exhaustion - if has_firstfailure: - source.append(' raise firstfailure') - else: - source.append(' raise FailedToImplement()') - source.append('') - - glob = {'FailedToImplement': FailedToImplement} - for fn, fname in all_functions.items(): - glob[fname] = fn - return '\n'.join(source), glob - - def internal_buildcalllist(self, argclasses, delegate, calllist): - """NOT_RPYTHON - Build a list of calls to try for the given classes of the - arguments. The list contains 'calls' of the following form: - (function-to-call, list-of-list-of-converters) - The list of converters contains a list of converter functions per - argument, with [] meaning that no conversion is needed for - that argument.""" - # look for an exact match first - arity = self.dispatch_arity - assert arity == len(argclasses) - dispatchclasses = tuple([(c,) for c in argclasses]) - choicelist = self.buildchoices(dispatchclasses) - seen_functions = {} - no_conversion = [()] * arity - for signature, function in choicelist: - calllist.append((function, tuple(no_conversion))) - seen_functions[function] = 1 - - # proceed by expanding the last argument by delegation, step by step - # until no longer possible, and then the previous argument, and so on. - expanded_args = () - expanded_dispcls = () - - for argi in range(arity-1, -1, -1): - # growing tuple of dispatch classes we can delegate to - curdispcls = dispatchclasses[argi] - assert len(curdispcls) == 1 - # maps each dispatch class to a list of converters - curargs = {curdispcls[0]: []} - # reduce dispatchclasses to the arguments before this one - # (on which no delegation has been tried yet) - dispatchclasses = dispatchclasses[:argi] - no_conversion = no_conversion[:argi] - - while 1: - choicelist = delegate.buildchoices((curdispcls,)) - # the list is sorted by priority - progress = False - for (t,), function in choicelist: - if function is None: - # this marks a decrease in the priority. - # Don't try delegators with lower priority if - # we have already progressed. - if progress: - break - else: - assert hasattr(function, 'result_class'), ( - "delegator %r must have a result_class" % function) - nt = function.result_class - if nt not in curargs: - curdispcls += (nt,) - srcconvs = curargs[t] - if not getattr(function, 'trivial_delegation',False): - srcconvs = srcconvs + [function] - curargs[nt] = srcconvs - progress = True - else: - if not progress: - break # no progress, and delegators list exhausted - - # progress: try again to dispatch with this new set of types - choicelist = self.buildchoices( - dispatchclasses + (curdispcls,) + expanded_dispcls) - for signature, function in choicelist: - if function not in seen_functions: - seen_functions[function] = 1 - # collect arguments: arguments after position argi... - after_argi = [tuple(expanded_args[j][signature[j]]) - for j in range(argi+1-arity, 0)] # nb. j<0 - # collect arguments: argument argi... - arg_argi = tuple(curargs[signature[argi]]) - # collect all arguments - newargs = no_conversion + [arg_argi] + after_argi - # record the call - calllist.append((function, tuple(newargs))) - # end of while 1: try on delegating the same argument i - - # proceed to the next argument - expanded_args = (curargs,) + expanded_args - expanded_dispcls = (curdispcls,) + expanded_dispcls - - def buildchoices(self, allowedtypes): - """NOT_RPYTHON - Build a list of all possible implementations we can dispatch to, - sorted best-first, ignoring delegation.""" - # 'types' is a tuple of tuples of classes, one tuple of classes per - # argument. (After delegation, we need to call buildchoice() with - # more than one possible class for a single argument.) - result = [] - self.internal_buildchoices(allowedtypes, (), result) - self.postprocessresult(allowedtypes, result) - #print self.operatorsymbol, allowedtypes, result - # the result is a list a tuples (function, signature). - return result - - def postprocessresult(self, allowedtypes, result): - "NOT_RPYTHON" +class FailedToImplement(Exception): + pass - def internal_buildchoices(self, initialtypes, currenttypes, result): - "NOT_RPYTHON" - if len(currenttypes) == self.dispatch_arity: - currenttypes += (W_ANY,) * (self.arity - self.dispatch_arity) - for func in self.dispatch_table.get(currenttypes, []): - if func not in result: # ignore duplicates - result.append((currenttypes, func)) - else: - classtuple = initialtypes[len(currenttypes)] - for nexttype in classtuple: - self.internal_buildchoices(initialtypes, - currenttypes + (nexttype,), - result) - def is_empty(self): - return not self.dispatch_table +def raiseFailedToImplement(): + raise FailedToImplement -class MultiMethod(AbstractMultiMethod): +class MultiMethodTable: - def __init__(self, operatorsymbol, arity, specialnames=None, **extras): + def __init__(self, arity, root_class, argnames_before=[], argnames_after=[]): """NOT_RPYTHON: cannot create new multimethods dynamically. - MultiMethod dispatching on the first 'arity' arguments. + MultiMethod-maker dispatching on exactly 'arity' arguments. """ - AbstractMultiMethod.__init__(self, operatorsymbol, arity) if arity < 1: raise ValueError, "multimethods cannot dispatch on nothing" - if specialnames is None: - specialnames = [operatorsymbol] - self.specialnames = specialnames # e.g. ['__xxx__', '__rxxx__'] - self.extras = extras - self.unbound_versions = {} - + self.arity = arity + self.root_class = root_class + self.dispatch_tree = {} + self.argnames_before = argnames_before + self.argnames_after = argnames_after - def __get__(self, space, cls=None): - if space is None: - return self + def register(self, function, *types, **kwds): + try: + order = kwds.pop('order') + except KeyError: + order = 0 + assert not kwds + assert len(types) == self.arity + node = self.dispatch_tree + for type in types[:-1]: + node = node.setdefault(type, {}) + lst = node.setdefault(types[-1], []) + if order >= len(lst): + lst += [None] * (order+1 - len(lst)) + assert lst[order] is None, "duplicate function for %r@%d" % ( + types, order) + lst[order] = function + + def install(self, prefix, list_of_typeorders, baked_perform_call=True): + "NOT_RPYTHON: initialization-time only" + assert len(list_of_typeorders) == self.arity + installer = Installer(self, prefix, list_of_typeorders, + baked_perform_call=baked_perform_call) + return installer.install() + + def install_if_not_empty(self, prefix, list_of_typeorders): + "NOT_RPYTHON: initialization-time only" + assert len(list_of_typeorders) == self.arity + installer = Installer(self, prefix, list_of_typeorders) + if installer.is_empty(): + return None else: - return BoundMultiMethod(space, self) + return installer.install() + + + + # ____________________________________________________________ + # limited dict-like interface to the dispatch table - get = __get__ + def getfunctions(self, types): + assert len(types) == self.arity + node = self.dispatch_tree + for type in types: + node = node[type] + return [fn for fn in node if fn is not None] - def slice(self, typeclass, bound_position=0): - "NOT_RPYTHON" + def has_signature(self, types): try: - return self.unbound_versions[typeclass, bound_position] + self.getfunctions(types) except KeyError: - m = UnboundMultiMethod(self, typeclass, bound_position) - self.unbound_versions[typeclass, bound_position] = m - return m - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - if not AbstractMultiMethod.register(self, function, *types): return False - # register the function into unbound versions that match - for m in self.unbound_versions.values(): - if m.match(types): - AbstractMultiMethod.register(m, function, *types) - return True - - -class DelegateMultiMethod(MultiMethod): - - def __init__(self): - "NOT_RPYTHON: cannot create new multimethods dynamically." - MultiMethod.__init__(self, 'delegate', 1, []) - self.key = object() - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - if not AbstractMultiMethod.register(self, function, *types): - return False - self.key = object() # change the key to force recomputation - return True - - def postprocessresult(self, allowedtypes, result): - "NOT_RPYTHON" - # add delegation from a class to the *first* immediate parent class - # and to W_ANY - arg1types, = allowedtypes - for t in arg1types: - if t.__bases__: - base = t.__bases__[0] - def delegate_to_parent_class(space, a): - return a - delegate_to_parent_class.trivial_delegation = True - delegate_to_parent_class.result_class = base - delegate_to_parent_class.priority = 0 - # hard-wire it at priority 0 - result.append(((t,), delegate_to_parent_class)) - - def delegate_to_any(space, a): - return a - delegate_to_any.trivial_delegation = True - delegate_to_any.result_class = W_ANY - delegate_to_any.priority = -999 - # hard-wire it at priority -999 - result.append(((t,), delegate_to_any)) - - # sort the results in priority order, and insert None marks - # between jumps in the priority values. Higher priority values - # first. - by_priority = {} # classify delegators by priority - for signature, function in result: - assert hasattr(function, 'priority'), ( - "delegator %r must have a priority" % function) - sublist = by_priority.setdefault(function.priority, []) - sublist.append((signature, function)) - delegators = by_priority.items() - delegators.sort() - delegators.reverse() - del result[:] - for priority, sublist in delegators: - if result: - result.append(((None,), None)) - result += sublist - - -class UnboundMultiMethod(AbstractMultiMethod): - - def __init__(self, basemultimethod, typeclass, bound_position=0): - "NOT_RPYTHON: cannot create new multimethods dynamically." - AbstractMultiMethod.__init__(self, - basemultimethod.operatorsymbol, - basemultimethod.arity) - self.basemultimethod = basemultimethod - self.typeclass = typeclass - self.bound_position = bound_position - # get all the already-registered matching functions from parent - for types, functions in basemultimethod.dispatch_table.iteritems(): - if self.match(types): - self.dispatch_table[types] = functions - self.adjust_dispatch_arity(types) - #print basemultimethod.operatorsymbol, typeclass, self.dispatch_table - - def register(self, function, *types): - """NOT_RPYTHON: cannot register new multimethod - implementations dynamically""" - if not AbstractMultiMethod.register(self, function, *types): - return False - # propagate the function registeration to the base multimethod - # and possibly other UnboundMultiMethods - self.basemultimethod.register(function, *types) - return True - - def match(self, types): - "NOT_RPYTHON" - # check if the 'types' signature statically corresponds to the - # restriction of the present UnboundMultiMethod. - # Only accept an exact match; having merely subclass should - # be taken care of by the general look-up rules. - t = types[self.bound_position].typedef - return t is self.typeclass or ( - getattr(t, 'could_also_match', None) is self.typeclass) - - def __get__(self, space, cls=None): - if space is None: - return self else: - return BoundMultiMethod(space, self) + return True + + def signatures(self): + result = [] + def enum_keys(types_so_far, node): + for type, subnode in node.items(): + next_types = types_so_far+(type,) + if isinstance(subnode, dict): + enum_keys(next_types, subnode) + else: + assert len(next_types) == self.arity + result.append(next_types) + enum_keys((), self.dispatch_tree) + return result + - get = __get__ +# ____________________________________________________________ +class Installer: -class BoundMultiMethod: - ASSERT_BASE_TYPE = object + prefix_memo = {} - def __init__(self, space, multimethod): - self.space = space + def __init__(self, multimethod, prefix, list_of_typeorders, baked_perform_call=True): self.multimethod = multimethod + # avoid prefix clashes, user code should supply different prefixes + # itself for nice names in tracebacks + n = 1 + while prefix in self.prefix_memo: + n += 1 + prefix = "%s%d" % (prefix,n) + self.prefix = prefix + self.prefix_memo[prefix] = 1 + self.list_of_typeorders = list_of_typeorders + self.subtree_cache = {} + self.to_install = [] + self.non_empty = self.build_tree([], multimethod.dispatch_tree) - def __eq__(self, other): - return (self.__class__ == other.__class__ and - self.space == other.space and - self.multimethod == other.multimethod) - - def __ne__(self, other): - return self != other - - def __hash__(self): - return hash((self.__class__, self.space, self.multimethod)) - - def __call__(self, *args): - if len(args) < self.multimethod.arity: - raise TypeError, ("multimethod needs at least %d arguments" % - self.multimethod.arity) - try: - return self.perform_call(*args) - except FailedToImplement, e: - if e.args: - raise OperationError(e.args[0], e.args[1]) - else: - # raise a TypeError for a FailedToImplement - initialtypes = [a.__class__ - for a in args[:self.multimethod.dispatch_arity]] - if len(initialtypes) <= 1: - plural = "" - else: - plural = "s" - debugtypenames = [t.__name__ for t in initialtypes] - message = "unsupported operand type%s for %s (%s)" % ( - plural, self.multimethod.operatorsymbol, - ', '.join(debugtypenames)) - w_value = self.space.wrap(message) - raise OperationError(self.space.w_TypeError, w_value) - - def perform_call(self, *args): - for a in args: - assert isinstance(a, self.ASSERT_BASE_TYPE), ( - "'%s' multimethod got a non-wrapped argument: %r" % ( - self.multimethod.operatorsymbol, a)) - arity = self.multimethod.dispatch_arity - argclasses = tuple([a.__class__ for a in args[:arity]]) - delegate = self.space.delegate.multimethod - fn = self.multimethod.compile_calllist(argclasses, delegate) - return fn(self.space, *args) + self.baked_perform_call = baked_perform_call + + if self.non_empty: + perform = [(None, prefix, 0)] + else: + perform = [] + + self.perform_call = self.build_function(None, prefix+'_perform_call', + None, perform) def is_empty(self): - return self.multimethod.is_empty() + return not self.non_empty - def __repr__(self): - return ''%(self.multimethod,) + def install(self): + #f = open('LOGFILE', 'a') + #print >> f, '_'*60 + #import pprint + #pprint.pprint(self.list_of_typeorders, f) + for target, funcname, func, source, fallback in self.to_install: + if target is not None: + if hasattr(target, funcname) and fallback: + continue + #print >> f, target.__name__, funcname + #if source: + # print >> f, source + #else: + # print >> f, '*\n' + setattr(target, funcname, func) + #f.close() + return self.perform_call + + def build_tree(self, types_so_far, dispatch_node): + key = tuple(types_so_far) + if key in self.subtree_cache: + return self.subtree_cache[key] + non_empty = False + typeorder = self.list_of_typeorders[len(types_so_far)] + for next_type in typeorder: + if self.build_single_method(typeorder, types_so_far, next_type, + dispatch_node): + non_empty = True + self.subtree_cache[key] = non_empty + return non_empty + + def build_single_method(self, typeorder, types_so_far, next_type, + dispatch_node): + funcname = '__'.join([self.prefix] + [t.__name__ for t in types_so_far]) + + order = typeorder[next_type] + #order = [(next_type, None)] + order + + things_to_call = [] + for type, conversion in order: + if type not in dispatch_node: + # there is no possible completion of types_so_far+[type] + # that could lead to a registered function. + continue + match = dispatch_node[type] + if isinstance(match, dict): + if self.build_tree(types_so_far+[type], match): + call = funcname + '__' + type.__name__ + call_selfarg_index = len(types_so_far) + 1 + things_to_call.append((conversion, call, + call_selfarg_index)) + else: + for func in match: # list of functions + if func is not None: + things_to_call.append((conversion, func, None)) + + if things_to_call: + funcname = intern(funcname) + self.build_function(next_type, funcname, len(types_so_far), + things_to_call) + return True + else: + return False + def build_function(self, target, funcname, func_selfarg_index, + things_to_call): + # support for inventing names for the entries in things_to_call + # which are real function objects instead of strings + miniglobals = {'FailedToImplement': FailedToImplement} + def invent_name(obj): + if isinstance(obj, str): + return obj + name = obj.__name__ + n = 1 + while name in miniglobals: + n += 1 + name = '%s%d' % (obj.__name__, n) + miniglobals[name] = obj + return name + + funcargs = ['arg%d' % i for i in range(self.multimethod.arity)] + + bodylines = [] + for conversion, call, call_selfarg_index in things_to_call: + callargs = funcargs[:] + if conversion is not None: + to_convert = func_selfarg_index + callargs[to_convert] = '%s(%s)' % ( + invent_name(conversion), callargs[to_convert]) + callname = invent_name(call) + if call_selfarg_index is not None: + # fallback on root_class + self.build_function(self.multimethod.root_class, + callname, call_selfarg_index, []) + callname = '%s.%s' % (callargs.pop(call_selfarg_index), callname) + callargs = (self.multimethod.argnames_before + + callargs + self.multimethod.argnames_after) + bodylines.append('return %s(%s)' % (callname, ', '.join(callargs))) + + fallback = False + if not bodylines: + miniglobals['raiseFailedToImplement'] = raiseFailedToImplement + bodylines = ['return raiseFailedToImplement()'] + fallback = True + + + # protect all lines apart from the last one by a try:except: + for i in range(len(bodylines)-2, -1, -1): + bodylines[i:i+1] = ['try:', + ' ' + bodylines[i], + 'except FailedToImplement:', + ' pass'] -class error(Exception): - "Thrown to you when you do something wrong with multimethods." + if func_selfarg_index is not None: + selfargs = [funcargs.pop(func_selfarg_index)] + else: + selfargs = [] + funcargs = (selfargs + self.multimethod.argnames_before + + funcargs + self.multimethod.argnames_after) + + if target is None and not self.baked_perform_call: + return funcargs, bodylines[0][len('return '):], miniglobals, fallback + + # indent mode + bodylines = [' ' + line for line in bodylines] + + bodylines.insert(0, 'def %s(%s):' % (funcname, ', '.join(funcargs))) + bodylines.append('') + source = '\n'.join(bodylines) + #print source + #print "*"*60 + exec source in miniglobals + func = miniglobals[funcname] + self.to_install.append((target, funcname, func, source, fallback)) + return func Modified: pypy/dist/pypy/objspace/std/noneobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/noneobject.py (original) +++ pypy/dist/pypy/objspace/std/noneobject.py Mon Feb 7 20:26:07 2005 @@ -8,10 +8,11 @@ class W_NoneObject(W_Object): from pypy.objspace.std.nonetype import none_typedef as typedef -registerimplementation(W_NoneObject) -def unwrap__None(space, w_none): - return None + def unwrap(w_self): + return None + +registerimplementation(W_NoneObject) def nonzero__None(space, w_none): return space.w_False Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Mon Feb 7 20:26:07 2005 @@ -1,36 +1,15 @@ from pypy.objspace.std.register_all import register_all -from pypy.interpreter.baseobjspace import * +from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable +from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import get_unique_interplevel_subclass from pypy.interpreter.typedef import instantiate from pypy.tool.cache import Cache -from pypy.objspace.std.multimethod import * +from pypy.objspace.std.model import W_Object, W_ANY, MultiMethod, StdTypeModel +from pypy.objspace.std.multimethod import FailedToImplement from pypy.objspace.descroperation import DescrOperation from pypy.objspace.std import stdtypedef import types -class W_Object(W_Root, object): - "Parent base class for wrapped objects." - typedef = None - - def __init__(w_self, space): - w_self.space = space # XXX not sure this is ever used any more - - def __repr__(self): - s = '%s(%s)' % ( - self.__class__.__name__, - #', '.join(['%s=%r' % keyvalue for keyvalue in self.__dict__.items()]) - getattr(self, 'name', '') - ) - if hasattr(self, 'w__class__'): - s += ' instance of %s' % self.w__class__ - return '<%s>' % s - -# delegation priorities -PRIORITY_SAME_TYPE = 2 # converting between several impls of the same type -PRIORITY_PARENT_TYPE = 1 # converting to a base type (e.g. bool -> int) -PRIORITY_PARENT_IMPL = 0 # hard-wired in multimethod.py (W_IntObject->W_Object) -PRIORITY_CHANGE_TYPE = -1 # changing type altogether (e.g. int -> float) -PRIORITY_ANY = -999 # hard-wired in multimethod.py (... -> W_ANY) def registerimplementation(implcls): # this function should ultimately register the implementation class somewhere @@ -47,139 +26,31 @@ PACKAGE_PATH = 'objspace.std' - def standard_types(self): - "NOT_RPYTHON: only for initializing the space." - class result: - "Import here the types you want to have appear in __builtin__." - - from pypy.objspace.std.objecttype import object_typedef - from pypy.objspace.std.booltype import bool_typedef - from pypy.objspace.std.inttype import int_typedef - from pypy.objspace.std.floattype import float_typedef - from pypy.objspace.std.tupletype import tuple_typedef - from pypy.objspace.std.listtype import list_typedef - from pypy.objspace.std.dicttype import dict_typedef - from pypy.objspace.std.basestringtype import basestring_typedef - from pypy.objspace.std.stringtype import str_typedef - from pypy.objspace.std.typetype import type_typedef - from pypy.objspace.std.slicetype import slice_typedef - from pypy.objspace.std.longtype import long_typedef - from pypy.objspace.std.unicodetype import unicode_typedef - return [value for key, value in result.__dict__.items() - if not key.startswith('_')] # don't look - - def clone_exception_hierarchy(self): - "NOT_RPYTHON: only for initializing the space." - from pypy.objspace.std.typeobject import W_TypeObject - from pypy.interpreter import gateway - w = self.wrap - def app___init__(self, *args): - self.args = args - w_init = w(gateway.app2interp(app___init__)) - def app___str__(self): - l = len(self.args) - if l == 0: - return '' - elif l == 1: - return str(self.args[0]) - else: - return str(self.args) - w_str = w(gateway.app2interp(app___str__)) - import exceptions - - # to create types, we should call the standard type object; - # but being able to do that depends on the existence of some - # of the exceptions... - - self.w_Exception = W_TypeObject( - self, - 'Exception', - [self.w_object], - {'__init__': w_init, - '__str__': w_str}, - ) - done = {'Exception': self.w_Exception} - - # some of the complexity of the following is due to the fact - # that we need to create the tree root first, but the only - # connections we have go in the inconvenient direction... - - for k in dir(exceptions): - if k not in done: - v = getattr(exceptions, k) - if not isinstance(v, type(Exception)): - continue - if not issubclass(v, Exception): - continue - stack = [k] - while stack: - next = stack[-1] - if next not in done: - v = getattr(exceptions, next) - b = v.__bases__[0] - if b.__name__ not in done: - stack.append(b.__name__) - continue - else: - base = done[b.__name__] - newtype = W_TypeObject( - self, - next, - [base], - {}, - ) - setattr(self, - 'w_' + next, - newtype) - done[next] = newtype - stack.pop() - else: - stack.pop() - return done - def initialize(self): "NOT_RPYTHON: only for initializing the space." self._typecache = Cache() - # The object implementations that we want to 'link' into PyPy must be - # imported here. This registers them into the multimethod tables, - # *before* the type objects are built from these multimethod tables. - from pypy.objspace.std import objectobject - from pypy.objspace.std import boolobject - from pypy.objspace.std import intobject - from pypy.objspace.std import floatobject - from pypy.objspace.std import tupleobject - from pypy.objspace.std import listobject - from pypy.objspace.std import dictobject - from pypy.objspace.std import stringobject - from pypy.objspace.std import typeobject - from pypy.objspace.std import sliceobject - from pypy.objspace.std import longobject - from pypy.objspace.std import noneobject - from pypy.objspace.std import iterobject - from pypy.objspace.std import unicodeobject - from pypy.objspace.std import fake + # Import all the object types and implementations + self.model = StdTypeModel() + + # install all the MultiMethods into the space instance + for name, mm in self.MM.__dict__.items(): + if isinstance(mm, MultiMethod) and not hasattr(self, name): + exprargs, expr, miniglobals, fallback = ( + mm.install_not_sliced(self.model.typeorder, baked_perform_call=False)) + + func = stdtypedef.make_perform_trampoline('__mm_'+name, + exprargs, expr, miniglobals, + mm) + + # e.g. add(space, w_x, w_y) + boundmethod = func.__get__(self) # bind the 'space' argument + setattr(self, name, boundmethod) # store into 'space' instance + # hack to avoid imports in the time-critical functions below - global W_ObjectObject, W_BoolObject, W_IntObject, W_FloatObject - global W_TupleObject, W_ListObject, W_DictObject, W_StringObject - global W_TypeObject, W_SliceObject, W_LongObject, W_NoneObject - global W_SeqIterObject, W_UnicodeObject, fake_type - W_ObjectObject = objectobject.W_ObjectObject - W_BoolObject = boolobject.W_BoolObject - W_IntObject = intobject.W_IntObject - W_FloatObject = floatobject.W_FloatObject - W_TupleObject = tupleobject.W_TupleObject - W_ListObject = listobject.W_ListObject - W_DictObject = dictobject.W_DictObject - W_StringObject = stringobject.W_StringObject - W_TypeObject = typeobject.W_TypeObject - W_SliceObject = sliceobject.W_SliceObject - W_LongObject = longobject.W_LongObject - W_NoneObject = noneobject.W_NoneObject - W_SeqIterObject = iterobject.W_SeqIterObject - W_UnicodeObject = unicodeobject.W_UnicodeObject - fake_type = fake.fake_type - # end of hacks + for cls in self.model.typeorder: + globals()[cls.__name__] = cls + # singletons self.w_None = W_NoneObject(self) self.w_False = W_BoolObject(self, False) @@ -193,12 +64,11 @@ "None" : self.w_None, "NotImplemented": self.w_NotImplemented, "Ellipsis": self.w_Ellipsis, -# "long": self.wrap(long), # XXX temporary } # types self.types_w = {} - for typedef in self.standard_types(): + for typedef in self.model.pythontypes: w_type = self.gettypeobject(typedef) setattr(self, 'w_' + typedef.name, w_type) for_builtins[typedef.name] = w_type @@ -206,9 +76,17 @@ # dummy old-style classes types self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {}) self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {}) - + # exceptions - ##for_builtins.update(self.clone_exception_hierarchy()) + mod = self.setup_exceptions(for_builtins) + + # install things in the __builtin__ module + self.make_builtins(for_builtins) + + w_exceptions = self.wrap(mod) + self.sys.setbuiltinmodule(w_exceptions, 'exceptions') + + def setup_exceptions(self, for_builtins): ## hacking things in from pypy.module import exceptionsinterp as ex def call(w_type, w_args): @@ -237,15 +115,10 @@ self.setitem(w_dic, self.wrap("__doc__"), ex.__doc__) finally: del self.call # revert to the class' method - - self.make_builtins(for_builtins) # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module - - m = Module(self, self.wrap("exceptions"), w_dic) - w_exceptions = self.wrap(m) - self.sys.setbuiltinmodule(w_exceptions, 'exceptions') + return Module(self, self.wrap("exceptions"), w_dic) def gettypeobject(self, typedef): # types_w maps each StdTypeDef instance to its @@ -298,7 +171,8 @@ if hasattr(self, 'w_' + x.__name__): w_result = getattr(self, 'w_' + x.__name__) assert isinstance(w_result, W_TypeObject) - return w_result + return w_result + from fake import fake_type if isinstance(x, type): ft = fake_type(x) return self.gettypeobject(ft.typedef) @@ -306,6 +180,11 @@ return ft(self, x) wrap._specialize_ = "argtypes" + def unwrap(self, w_obj): + if isinstance(w_obj, BaseWrappable): + return w_obj + return w_obj.unwrap() + def newint(self, intval): return W_IntObject(self, intval) @@ -367,31 +246,6 @@ len(t), expected_length) return t - - class MM: - "Container for multimethods." - #is_data_descr = MultiMethod('is_data_descr', 1, []) # returns an unwrapped bool - #getdict = MultiMethod('getdict', 1, []) # get '.__dict__' attribute - next = MultiMethod('next', 1, ['next']) # iterator interface - call = MultiMethod('call', 1, ['__call__'], varargs=True, keywords=True) - #getattribute = MultiMethod('getattr', 2, ['__getattribute__']) # XXX hack - # special visible multimethods - delegate = DelegateMultiMethod() # delegators - int_w = MultiMethod('int_w', 1, []) # returns an unwrapped int - str_w = MultiMethod('str_w', 1, []) # returns an unwrapped string - float_w = MultiMethod('float_w', 1, []) # returns an unwrapped float - unwrap = MultiMethod('unwrap', 1, []) # returns an unwrapped object - issubtype = MultiMethod('issubtype', 2, []) - id = MultiMethod('id', 1, []) - init = MultiMethod('__init__', 1, varargs=True, keywords=True) - - int_w = MM.int_w - str_w = MM.str_w - float_w = MM.float_w - unwrap = MM.unwrap - delegate = MM.delegate - #is_true = MM.is_true - def is_(self, w_one, w_two): # XXX a bit of hacking to gain more speed if w_one is w_two: @@ -405,20 +259,21 @@ else: return DescrOperation.is_true(self, w_obj) -# add all regular multimethods to StdObjSpace -for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: - if not hasattr(StdObjSpace.MM, _name): - if _name == 'pow': - mm = MultiMethod(_symbol, _arity, _specialnames, defaults=(None,)) - else: - mm = MultiMethod(_symbol, _arity, _specialnames) - setattr(StdObjSpace.MM, _name, mm) - if not hasattr(StdObjSpace, _name): - setattr(StdObjSpace, _name, getattr(StdObjSpace.MM, _name)) - -# import the common base W_ObjectObject as well as -# default implementations of some multimethods for all objects -# that don't explicitly override them or that raise FailedToImplement -from pypy.objspace.std.register_all import register_all -import pypy.objspace.std.objectobject -import pypy.objspace.std.default + + class MM: + "Container for multimethods." + call = MultiMethod('call', 1, ['__call__'], general__args__=True) + init = MultiMethod('__init__', 1, general__args__=True) + # special visible multimethods + int_w = MultiMethod('int_w', 1, []) # returns an unwrapped int + str_w = MultiMethod('str_w', 1, []) # returns an unwrapped string + float_w = MultiMethod('float_w', 1, []) # returns an unwrapped float + + # add all regular multimethods here + for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable: + if _name not in locals(): + mm = MultiMethod(_symbol, _arity, _specialnames) + locals()[_name] = mm + del mm + + pow.extras['defaults'] = (None,) Modified: pypy/dist/pypy/objspace/std/register_all.py ============================================================================== --- pypy/dist/pypy/objspace/std/register_all.py (original) +++ pypy/dist/pypy/objspace/std/register_all.py Mon Feb 7 20:26:07 2005 @@ -74,17 +74,17 @@ def op_negated(function): - def op(space, w_1, w_2, function=function): + def op(space, w_1, w_2): return space.not_(function(space, w_1, w_2)) return op def op_swapped(function): - def op(space, w_1, w_2, function=function): + def op(space, w_1, w_2): return function(space, w_2, w_1) return op def op_swapped_negated(function): - def op(space, w_1, w_2, function=function): + def op(space, w_1, w_2): return space.not_(function(space, w_2, w_1)) return op @@ -110,16 +110,17 @@ table, thus favouring swapping the arguments over negating the result. """ from pypy.objspace.std.objspace import StdObjSpace, W_ANY - originaltable = {} + originalentries = {} for op in OPERATORS: - originaltable[op] = getattr(StdObjSpace.MM, op).dispatch_table.copy() + originalentries[op] = getattr(StdObjSpace.MM, op).signatures() for op1, op2, correspondance in OP_CORRESPONDANCES: mirrorfunc = getattr(StdObjSpace.MM, op2) - for types, functions in originaltable[op1].iteritems(): + for types in originalentries[op1]: t1, t2 = types if t1 is t2: - if types not in mirrorfunc.dispatch_table: + if not mirrorfunc.has_signature(types): + functions = getattr(StdObjSpace.MM, op1).getfunctions(types) assert len(functions) == 1, ('Automatic' ' registration of comparison functions' ' only work when there is a single method for' Modified: pypy/dist/pypy/objspace/std/sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/sliceobject.py Mon Feb 7 20:26:07 2005 @@ -18,6 +18,10 @@ w_self.w_stop = w_stop w_self.w_step = w_step + def unwrap(w_slice): + space = w_slice.space + return slice(space.unwrap(w_slice.w_start), space.unwrap(w_slice.w_stop), space.unwrap(w_slice.w_step)) + registerimplementation(W_SliceObject) def app_repr__Slice(aslice): @@ -43,7 +47,4 @@ raise OperationError(space.w_TypeError, space.wrap("unhashable type")) -def unwrap__Slice(space, w_slice): - return slice(space.unwrap(w_slice.w_start), space.unwrap(w_slice.w_stop), space.unwrap(w_slice.w_step)) - register_all(vars()) Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Mon Feb 7 20:26:07 2005 @@ -1,7 +1,7 @@ from pypy.interpreter import eval, function, gateway from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import TypeDef, GetSetProperty, Member -from pypy.objspace.std.multimethod import MultiMethod, FailedToImplement +from pypy.objspace.std.model import MultiMethod, FailedToImplement __all__ = ['StdTypeDef', 'newmethod', 'gateway', 'GetSetProperty', 'Member', 'attrproperty', 'attrproperty_w', @@ -24,9 +24,9 @@ if b is object_typedef: return True while a is not b: - a = a.base if a is None: return False + a = a.base return True def attrproperty(name): @@ -77,16 +77,11 @@ if isinstance(typedef, StdTypeDef): # get all the sliced multimethods - multimethods = slicemultimethods(space.__class__, typedef) - for name, code in multimethods.items(): - # compute the slice and ignore the multimethod if empty - if not code.computeslice(space): - continue - # create a Function around the sliced multimethod code - fn = function.Function(space, code, defs_w=code.getdefaults(space)) + multimethods = slicemultimethods(space, typedef) + for name, gateway in multimethods.items(): assert name not in rawdict, 'name clash: %s in %s_typedef' % ( name, typedef.name) - rawdict[name] = fn + rawdict[name] = gateway # compute the bases if typedef is object_typedef: @@ -111,150 +106,266 @@ result.append(value) return result -def make_frameclass_for_arity(arity, varargs, keywords, isspecial): - argnames = [] - for i in range(arity): - argnames.append('arg%dof%d'%(i+1, arity)) - if varargs: - argnames.append('var_args') - if keywords: - argnames.append('kw_args') - self_args_assigning = [] - for i in range(len(argnames)): - self_args_assigning.append(' self.%s = args[%i]'%(argnames[i], i)) - self_args_assigning = "\n".join(self_args_assigning) - self_args = ", ".join(['self.'+ a for a in argnames]) - name = 'MmFrameOfArity%d'%arity - if varargs: - name += "Var" - if keywords: - name += "KW" - if isspecial: - name = "Special" + name - d = locals() - template = mmtemplate - if isspecial: - template += specialmmruntemplate +##def make_frameclass_for_arity(arity, varargs, keywords, isspecial): +## argnames = [] +## for i in range(arity): +## argnames.append('arg%dof%d'%(i+1, arity)) +## if varargs: +## argnames.append('var_args') +## if keywords: +## argnames.append('kw_args') +## self_args_assigning = [] +## for i in range(len(argnames)): +## self_args_assigning.append(' self.%s = args[%i]'%(argnames[i], i)) +## self_args_assigning = "\n".join(self_args_assigning) +## self_args = ", ".join(['self.'+ a for a in argnames]) +## name = 'MmFrameOfArity%d'%arity +## if varargs: +## name += "Var" +## if keywords: +## name += "KW" +## if isspecial: +## name = "Special" + name +## d = locals() +## template = mmtemplate +## if isspecial: +## template += specialmmruntemplate +## else: +## template += mmruntemplate +### print template%d +## exec template%d in globals(), d +## return d[name] +## +##_frameclass_for_arity_cache = {} +##def frameclass_for_arity(arity, varargs, keywords, isspecial): +## try: +## return _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] +## except KeyError: +## r = _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] = \ +## make_frameclass_for_arity(arity, varargs, keywords, isspecial) +## return r + + +def sliced_typeorders(typeorder, multimethod, typedef, i, local=False): + list_of_typeorders = [typeorder] * multimethod.arity + prefix = '_mm_' + multimethod.name + if not local: + # slice + sliced_typeorder = {} + for type, order in typeorder.items(): + thistypedef = getattr(type, 'typedef', None) + if issubtypedef(thistypedef, typedef): + lst = [] + for target_type, conversion in order: + targettypedef = getattr(target_type, 'typedef', None) + if targettypedef == typedef: + lst.append((target_type, conversion)) + sliced_typeorder[type] = lst + list_of_typeorders[i] = sliced_typeorder + prefix += '_%sS%d' % (typedef.name, i) + else: + prefix = typedef.name +'_mth'+prefix + return prefix, list_of_typeorders + +def typeerrormsg(space, operatorsymbol, args_w): + type_names = [ space.type(w_arg).name for w_arg in args_w ] + if len(args_w) > 1: + plural = 's' else: - template += mmruntemplate -# print template%d - exec template%d in globals(), d - return d[name] + plural = '' + msg = "unsupported operand type%s for %s (%s)" % ( + plural, operatorsymbol, + ', '.join(type_names)) + return space.wrap(msg) + +def make_perform_trampoline(prefix, exprargs, expr, miniglobals, multimethod, selfindex=0, + allow_NotImplemented_results=False): + # mess to figure out how to put a gateway around executing expr + argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] + explicit_argnames = multimethod.extras.get('argnames', []) + argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames + solid_arglist = ['w_'+name for name in argnames] + wrapper_arglist = solid_arglist[:] + if multimethod.extras.get('varargs_w', False): + wrapper_arglist.append('args_w') + if multimethod.extras.get('w_varargs', False): + wrapper_arglist.append('w_args') + if multimethod.extras.get('keywords', False): + raise Exception, "no longer supported, use __args__" + if multimethod.extras.get('general__args__', False): + wrapper_arglist.append('__args__') + + miniglobals.update({ 'OperationError': OperationError, + 'typeerrormsg': typeerrormsg}) -_frameclass_for_arity_cache = {} -def frameclass_for_arity(arity, varargs, keywords, isspecial): - try: - return _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] - except KeyError: - r = _frameclass_for_arity_cache[(arity, varargs, keywords, isspecial)] = \ - make_frameclass_for_arity(arity, varargs, keywords, isspecial) - return r + app_defaults = multimethod.extras.get('defaults', ()) + i = len(argnames) - len(app_defaults) + wrapper_signature = wrapper_arglist[:] + for app_default in app_defaults: + name = wrapper_signature[i] + wrapper_signature[i] = '%s=%s' % (name, name) + miniglobals[name] = app_default + i += 1 + + wrapper_signature.insert(0, wrapper_signature.pop(selfindex)) + wrapper_sig = ', '.join(wrapper_signature) + + src = [] + dest = [] + for wrapper_arg,expr_arg in zip(['space']+wrapper_arglist, exprargs): + if wrapper_arg != expr_arg: + src.append(wrapper_arg) + dest.append(expr_arg) + renaming = ', '.join(dest) +" = "+', '.join(src) + + if allow_NotImplemented_results and len(multimethod.specialnames) > 1: + # turn FailedToImplement into NotImplemented + code = """def %s_perform_call(space, %s): + %s + try: + return %s + except FailedToImplement, e: + if e.args: + raise OperationError(e.args[0], e.args[1]) + else: + return space.w_NotImplemented +""" % (prefix, wrapper_sig, renaming, expr) + else: + # turn FailedToImplement into nice TypeErrors + code = """def %s_perform_call(space, %s): + %s + try: + w_res = %s + except FailedToImplement, e: + if e.args: + raise OperationError(e.args[0], e.args[1]) + else: + raise OperationError(space.w_TypeError, + typeerrormsg(space, %r, [%s])) + if w_res is None: + w_res = space.w_None + return w_res +""" % (prefix, wrapper_sig, renaming, expr, + multimethod.operatorsymbol, ', '.join(solid_arglist)) + exec code in miniglobals + return miniglobals["%s_perform_call" % prefix] + +def wrap_trampoline_in_gateway(func, methname, multimethod): + unwrap_spec = [gateway.ObjSpace] + [gateway.W_Root]*multimethod.arity + if multimethod.extras.get('varargs_w', False): + unwrap_spec.append('args_w') + if multimethod.extras.get('w_varargs', False): + unwrap_spec.append('w_args') + if multimethod.extras.get('general__args__', False): + unwrap_spec.append(gateway.Arguments) + return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) -def slicemultimethod(multimethod, typeclass, result): +def slicemultimethod(space, multimethod, typedef, result, local=False): + from pypy.objspace.std.objecttype import object_typedef for i in range(len(multimethod.specialnames)): # each MultimethodCode embeds a multimethod - name = multimethod.specialnames[i] - if name in result: + methname = multimethod.specialnames[i] + if methname in result: # conflict between e.g. __lt__ and # __lt__-as-reversed-version-of-__gt__ - code = result[name] - if code.bound_position < i: + gw = result[methname] + if gw.bound_position < i: continue - mmframeclass = frameclass_for_arity(multimethod.arity, - multimethod.extras.get('varargs', False), - multimethod.extras.get('keywords', False), - len(multimethod.specialnames) > 1) - code = MultimethodCode(multimethod, mmframeclass, typeclass, i) - result[name] = code -def slicemultimethods(spaceclass, typeclass): + prefix, list_of_typeorders = sliced_typeorders( + space.model.typeorder, multimethod, typedef, i, local=local) + exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, + baked_perform_call=False) + if fallback: + continue # skip empty multimethods + trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals, + multimethod, i, + allow_NotImplemented_results=True) + gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) + gw.bound_position = i # for the check above + result[methname] = gw + +def slicemultimethods(space, typedef): result = {} # import and slice all multimethods of the space.MM container - for multimethod in hack_out_multimethods(spaceclass.MM.__dict__): - slicemultimethod(multimethod, typeclass, result) + for multimethod in hack_out_multimethods(space.MM.__dict__): + slicemultimethod(space, multimethod, typedef, result) # import all multimethods defined directly on the type without slicing - for multimethod in typeclass.local_multimethods: - slicemultimethod(multimethod, None, result) + for multimethod in typedef.local_multimethods: + slicemultimethod(space, multimethod, typedef, result, local=True) return result -class MultimethodCode(eval.Code): - """A code object that invokes a multimethod.""" +##class MultimethodCode(eval.Code): +## """A code object that invokes a multimethod.""" - def __init__(self, multimethod, framecls, typeclass, bound_position=0): - "NOT_RPYTHON: initialization-time only." - eval.Code.__init__(self, multimethod.operatorsymbol) - self.basemultimethod = multimethod - self.typeclass = typeclass - self.bound_position = bound_position - self.framecls = framecls - argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] - explicit_argnames = multimethod.extras.get('argnames', []) - argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames - varargname = kwargname = None - # XXX do something about __call__ and __init__ which still use - # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w - if multimethod.extras.get('varargs', False): - varargname = 'args' - if multimethod.extras.get('keywords', False): - kwargname = 'keywords' - self.sig = argnames, varargname, kwargname - - def computeslice(self, space): - "NOT_RPYTHON: initialization-time only." - if self.typeclass is None: - slice = self.basemultimethod - else: - slice = self.basemultimethod.slice(self.typeclass, - self.bound_position) - if slice.is_empty(): - return False - else: - self.mm = slice.get(space) - return True - - def signature(self): - return self.sig - - def getdefaults(self, space): - return [space.wrap(x) - for x in self.basemultimethod.extras.get('defaults', ())] - - def create_frame(self, space, w_globals, closure=None): - return self.framecls(space, self) - -mmtemplate = """ -class %(name)s(eval.Frame): - - def setfastscope(self, scope_w): - args = list(scope_w) - args.insert(0, args.pop(self.code.bound_position)) -%(self_args_assigning)s - - def getfastscope(self): - raise OperationError(self.space.w_TypeError, - self.space.wrap("cannot get fastscope of a MmFrame")) -""" - -mmruntemplate = """ - def run(self): - "Call the multimethod, raising a TypeError if not implemented." - w_result = self.code.mm(%(self_args)s) - # we accept a real None from operations with no return value - if w_result is None: - w_result = self.space.w_None - return w_result -""" - -specialmmruntemplate = """ - - def run(self): - "Call the multimethods, possibly returning a NotImplemented." - try: - return self.code.mm.perform_call(%(self_args)s) - except FailedToImplement, e: - if e.args: - raise OperationError(e.args[0], e.args[1]) - else: - return self.space.w_NotImplemented +## def __init__(self, multimethod, framecls, typeclass, bound_position=0): +## "NOT_RPYTHON: initialization-time only." +## eval.Code.__init__(self, multimethod.operatorsymbol) +## self.basemultimethod = multimethod +## self.typeclass = typeclass +## self.bound_position = bound_position +## self.framecls = framecls +## argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] +## explicit_argnames = multimethod.extras.get('argnames', []) +## argnames[len(argnames)-len(explicit_argnames):] = explicit_argnames +## varargname = kwargname = None +## # XXX do something about __call__ and __init__ which still use +## # XXX packed arguments: w_args, w_kwds instead of *args_w, **kwds_w +## if multimethod.extras.get('varargs', False): +## varargname = 'args' +## if multimethod.extras.get('keywords', False): +## kwargname = 'keywords' +## self.sig = argnames, varargname, kwargname + +## def computeslice(self, space): +## "NOT_RPYTHON: initialization-time only." +## self.mm = self.basemultimethod.__get__(space, slice=( +## self.typeclass, self.bound_position)) +## return not self.mm.is_empty() + +## def signature(self): +## return self.sig + +## def getdefaults(self, space): +## return [space.wrap(x) +## for x in self.basemultimethod.extras.get('defaults', ())] + +## def create_frame(self, space, w_globals, closure=None): +## return self.framecls(space, self) + +##mmtemplate = """ +##class %(name)s(eval.Frame): + +## def setfastscope(self, scope_w): +## args = list(scope_w) +## args.insert(0, args.pop(self.code.bound_position)) +##%(self_args_assigning)s + +## def getfastscope(self): +## raise OperationError(self.space.w_TypeError, +## self.space.wrap("cannot get fastscope of a MmFrame")) +##""" + +##mmruntemplate = """ +## def run(self): +## "Call the multimethod, raising a TypeError if not implemented." +## w_result = self.code.mm(%(self_args)s) +## # we accept a real None from operations with no return value +## if w_result is None: +## w_result = self.space.w_None +## return w_result +##""" + +##specialmmruntemplate = """ + +## def run(self): +## "Call the multimethods, possibly returning a NotImplemented." +## try: +## return self.code.mm.perform_call(%(self_args)s) +## except FailedToImplement, e: +## if e.args: +## raise OperationError(e.args[0], e.args[1]) +## else: +## return self.space.w_NotImplemented -""" +##""" Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Mon Feb 7 20:26:07 2005 @@ -14,7 +14,6 @@ def ord__String(space, w_str): def string_richcompare(space, w_str1, w_str2, op): def str_w__String(space, w_str): - def unwrap__String(space, w_str): __add__ def add__String_String(space, w_left, w_right): __class__ __contains__ @@ -23,7 +22,7 @@ __eq__ def eq__String_String(space, w_str1, w_str2): __ge__ def ge__String_String(space, w_str1, w_str2): __getattribute__ -__getitem__ def getitem__String_Int(space, w_str, w_int): def getitem__String_Slice(space, w_str, w_slice): +__getitem__ def getitem__String_ANY(space, w_str, w_int): def getitem__String_Slice(space, w_str, w_slice): __getslice__ __gt__ def gt__String_String(space, w_str1, w_str2): __hash__ def hash__String(space, w_str): @@ -40,12 +39,12 @@ __setattr__ __str__ def str__String(space, w_str): capitalize def str_capitalize__String(space, w_self): -center def str_center__String_Int(space, w_self): -count def str_count__String_String_Int_Int(space, w_self): [optional arguments not supported now] +center def str_center__String_ANY(space, w_self): +count def str_count__String_String_ANY_ANY(space, w_self): [optional arguments not supported now] decode !Unicode not supported now encode !Unicode not supported now endswith str_endswith__String_String [optional arguments not supported now] -expandtabs str_expandtabs__String_Int +expandtabs str_expandtabs__String_ANY find OK index OK isalnum def str_isalnum__String(space, w_self): def _isalnum(ch): @@ -64,7 +63,7 @@ rindex OK rjust def str_rjust__String_ANY(space, w_self, w_arg): rstrip def str_rstrip__String_String(space, w_self, w_chars): -split def str_split__String_None_Int(space, w_self, w_none, w_maxsplit=-1):def str_split__String_String_Int(space, w_self, w_by, w_maxsplit=-1): +split def str_split__String_None_ANY(space, w_self, w_none, w_maxsplit=-1):def str_split__String_String_ANY(space, w_self, w_by, w_maxsplit=-1): splitlines def str_splitlines__String_String(space, w_self, w_keepends): startswith str_startswith__String_String [optional arguments not supported now] strip def str_strip__String_String(space, w_self, w_chars): @@ -100,6 +99,9 @@ """ representation for debugging purposes """ return "%s(%r)" % (w_self.__class__.__name__, w_self._value) + def unwrap(w_self): + return w_self._value + registerimplementation(W_StringObject) @@ -767,9 +769,6 @@ def str_w__String(space, w_str): return w_str._value - -def unwrap__String(space, w_str): - return w_str._value def hash__String(space, w_str): w_hash = w_str.w_hash @@ -891,8 +890,8 @@ else: return space.w_False -def getitem__String_Int(space, w_str, w_int): - ival = space.int_w(w_int) +def getitem__String_ANY(space, w_str, w_index): + ival = space.int_w(w_index) str = w_str._value slen = len(str) if ival < 0: @@ -913,9 +912,8 @@ w_empty = space.newstring([]) return str_join__String_ANY(space, w_empty, w_r) -def mul__String_Int(space, w_str, w_mul): +def mul_string_times(space, w_str, mul): input = w_str._value - mul = space.int_w(w_mul) if mul < 0: return space.wrap("") input_len = len(input) @@ -932,8 +930,11 @@ return space.wrap("".join(buffer)) -def mul__Int_String(space, w_mul, w_str): - return mul__String_Int(space, w_str, w_mul) +def mul__String_ANY(space, w_str, w_times): + return mul_string_times(space, w_str, space.int_w(w_times)) + +def mul__ANY_String(space, w_mul, w_str): + return mul_string_times(space, w_str, space.int_w(w_times)) def add__String_String(space, w_left, w_right): right = w_right._value Modified: pypy/dist/pypy/objspace/std/stringtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringtype.py (original) +++ pypy/dist/pypy/objspace/std/stringtype.py Mon Feb 7 20:26:07 2005 @@ -39,15 +39,12 @@ # ____________________________________________________________ -def descr__new__(space, w_stringtype, w_obj=None): +def descr__new__(space, w_stringtype, w_obj=''): from pypy.objspace.std.stringobject import W_StringObject - if w_obj is None: - value = '' - else: - w_obj = space.str(w_obj) - if space.is_true(space.is_(w_stringtype, space.w_str)): - return w_obj # XXX might be reworked when space.str() typechecks - value = space.str_w(w_obj) + w_obj = space.str(w_obj) + if space.is_true(space.is_(w_stringtype, space.w_str)): + return w_obj # XXX might be reworked when space.str() typechecks + value = space.str_w(w_obj) w_obj = space.allocate_instance(W_StringObject, w_stringtype) w_obj.__init__(space, value) return w_obj Modified: pypy/dist/pypy/objspace/std/test/test_multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_multimethod.py (original) +++ pypy/dist/pypy/objspace/std/test/test_multimethod.py Mon Feb 7 20:26:07 2005 @@ -1,145 +1,94 @@ import autopath +from py.test import raises from pypy.objspace.std.multimethod import * -BoundMultiMethod.ASSERT_BASE_TYPE = object +class W_Root(object): + pass -objspacename = 'std' +class W_IntObject(W_Root): + pass -class X: - def __init__(self, value): - self.value = value - def __repr__(self): - return '' % self.value +class W_BoolObject(W_Root): + pass -def from_y_to_x(space, yinstance): - return X(yinstance) - -from_y_to_x.result_class = X -from_y_to_x.priority = 2 - -def from_x_to_str(space, xinstance): - #if xinstance.value: - return w('!' + repr(xinstance.value)) - #else: - # return [] - -from_x_to_str.result_class = str -from_x_to_str.priority = 2 - - -class Y: - def __init__(self, value): - self.value = value - def __repr__(self): - return '' % self.value - def __nonzero__(self): - return self.value != 666 - - -def add_x_x(space, x1, x2): - return "add_x_x", x1, x2 - -def add_x_y(space, x1, y2): - if x1.value < 0: - raise FailedToImplement(ValueError, 'not good') - return "add_x_y", x1, y2 - -def add_y_y(space, y1, y2): - return "add_y_y", y1, y2 - -def add_string_string(space, x, y): - return "add_string_string", x, y - -def add_int_string(space, x, y): - return "add_int_string", x, y - -def add_int_any(space, y1, o2): - return "add_int_any", y1, o2 - -class FakeObjSpace: - add = MultiMethod('+', 2, []) - add.register(add_x_x, X, X) - add.register(add_x_y, X, Y) - add.register(add_y_y, Y, Y) - add.register(add_string_string, str, str) - add.register(add_int_string, int, str) - add.register(add_int_any, int, object) - - delegate = DelegateMultiMethod() - delegate.register(from_y_to_x, Y) - delegate.register(from_x_to_str, X) +class W_StringObject(W_Root): + pass + +def delegate_b2i(w_x): + assert isinstance(w_x, W_BoolObject) + return W_IntObject() + +add = MultiMethodTable(2, root_class=W_Root, argnames_before=['space']) + +def add__Int_Int(space, w_x, w_y): + assert space == 'space' + assert isinstance(w_x, W_IntObject) + assert isinstance(w_y, W_IntObject) + return 'fine' + +add.register(add__Int_Int, W_IntObject, W_IntObject) + + +def setup_module(mod): + typeorder = { + W_IntObject: [(W_IntObject, None)], + W_BoolObject: [(W_BoolObject, None), (W_IntObject, delegate_b2i)], + W_StringObject: [(W_StringObject, None)], + } + mod.typeorder = typeorder + mod.add1 = add.install('__add', [typeorder, typeorder]) + + +def test_simple(): + space = 'space' + w_x = W_IntObject() + w_y = W_IntObject() + assert add1(space, w_x, w_y) == 'fine' + +def test_failtoimplement(): + space = 'space' + w_x = W_IntObject() + w_s = W_StringObject() + raises(FailedToImplement, "add1(space, w_x, w_s)") + raises(FailedToImplement, "add1(space, w_s, w_x)") + +def test_delegate(): + space = 'space' + w_x = W_IntObject() + w_s = W_StringObject() + w_b = W_BoolObject() + assert add1(space, w_x, w_b) == 'fine' + assert add1(space, w_b, w_x) == 'fine' + assert add1(space, w_b, w_b) == 'fine' + raises(FailedToImplement, "add1(space, w_b, w_s)") + raises(FailedToImplement, "add1(space, w_s, w_b)") + +def test_not_baked(): + add2 = add.install('__add2', [typeorder, typeorder],baked_perform_call=False) + assert add2[0] == ['space', 'arg0', 'arg1'] + assert add2[1] == 'arg0.__add2(space, arg1)' + assert isinstance(add2[2], dict) + assert not add2[3] + +def test_empty(): + add3_installer = Installer(add, '__add3', [{},{}]) + assert add3_installer.is_empty() + assert len(add3_installer.to_install) == 1 + assert add3_installer.to_install[0][0] is None + +def test_empty_direct(): + assert not add.install_if_not_empty('__add4', [{},{}]) + + +def test_empty_not_baked(): + add5_installer = Installer(add, '__add5', [{},{}], baked_perform_call=False) + assert add5_installer.is_empty() + assert len(add5_installer.to_install) == 0 + add5 = add5_installer.install() + assert add5[0] == ['space', 'arg0', 'arg1'] + assert add5[1] == 'raiseFailedToImplement()' + assert isinstance(add5[2], dict) + assert add5[3] - def wrap(self, x): - return '' % (x,) - w_TypeError = 'w_TypeError' - -##def w(x, cache={}): -## if type(x) in cache: -## Stub = cache[type(x)] -## else: -## Stub = type(type(x))('%s_stub' % type(x).__name__, (type(x),), {}) -## Stub.dispatchclass = Stub -## cache[type(x)] = Stub -## return Stub(x) - -##X.dispatchclass = X -##Y.dispatchclass = Y - -def w(x): - return x - - -class TestMultiMethod: - def setup_method(self,method): - # only run when testing stdobjectspace - #XXX removed: self.space - self.space = FakeObjSpace() - - def test_non_delegate(self): - space = self.space - - r = space.add(X(2), X(5)) - assert repr(r) == "('add_x_x', , )" - - r = space.add(X(3), Y(4)) - assert repr(r) == "('add_x_y', , )" - - r = space.add(Y(0), Y(20)) - assert repr(r) == "('add_y_y', , )" - - r = space.add(w(-3), w([7,6,5])) - assert repr(r) == "('add_int_any', -3, [7, 6, 5])" - - r = space.add(w(5), w("test")) - assert repr(r) == "('add_int_string', 5, 'test')" - - r = space.add(w("x"), w("y")) - assert repr(r) == "('add_string_string', 'x', 'y')" - - def test_delegate_y_to_x(self): - space = self.space - r = space.add(Y(-1), X(7)) - assert repr(r) == "('add_x_x', >, )" - - r = space.add(Y(1), X(7)) - assert repr(r) == "('add_x_x', >, )" - - r = space.add(X(-3), Y(20)) - assert repr(r) == "('add_x_x', , >)" - - def test_no_operation_defined(self): - space = self.space - raises(OperationError, space.add, w([3]), w(4)) - raises(OperationError, space.add, w(3.0), w('bla')) - #raises(OperationError, space.add, X(0), w("spam")) - #raises(OperationError, space.add, Y(666), w("egg")) - - def test_delegate_x_to_str(self): - space = self.space - r = space.add(X(42), w("spam")) - assert repr(r) == "('add_string_string', '!42', 'spam')" - - r = space.add(Y(20), w("egg")) - assert repr(r) == "('add_string_string', '!', 'egg')" Modified: pypy/dist/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupleobject.py (original) +++ pypy/dist/pypy/objspace/std/tupleobject.py Mon Feb 7 20:26:07 2005 @@ -16,22 +16,23 @@ reprlist = [repr(w_item) for w_item in w_self.wrappeditems] return "%s(%s)" % (w_self.__class__.__name__, ', '.join(reprlist)) + def unwrap(w_tuple): + space = w_tuple.space + items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems] # XXX generic mixed types unwrap + return tuple(items) -registerimplementation(W_TupleObject) +registerimplementation(W_TupleObject) -def unwrap__Tuple(space, w_tuple): - items = [space.unwrap(w_item) for w_item in w_tuple.wrappeditems] # XXX generic mixed types unwrap - return tuple(items) def len__Tuple(space, w_tuple): result = len(w_tuple.wrappeditems) return W_IntObject(space, result) -def getitem__Tuple_Int(space, w_tuple, w_index): +def getitem__Tuple_ANY(space, w_tuple, w_index): items = w_tuple.wrappeditems try: - w_item = items[w_index.intval] + w_item = items[space.int_w(w_index)] except IndexError: raise OperationError(space.w_IndexError, space.wrap("tuple index out of range")) @@ -63,14 +64,15 @@ items2 = w_tuple2.wrappeditems return W_TupleObject(space, items1 + items2) -def mul__Tuple_Int(space, w_tuple, w_int): +def mul_tuple_times(space, w_tuple, times): items = w_tuple.wrappeditems - times = w_int.intval - return W_TupleObject(space, items * times) + return W_TupleObject(space, items * times) +def mul__Tuple_ANY(space, w_tuple, w_times): + return mul_tuple_times(space, w_tuple, space.int_w(w_times)) -def mul__Int_Tuple(space, w_int, w_tuple): - return mul__Tuple_Int(space, w_tuple, w_int) +def mul__ANY_Tuple(space, w_times, w_tuple): + return mul_tuple_times(space, w_tuple, space.int_w(w_times)) def eq__Tuple_Tuple(space, w_tuple1, w_tuple2): items1 = w_tuple1.wrappeditems Modified: pypy/dist/pypy/objspace/std/tupletype.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupletype.py (original) +++ pypy/dist/pypy/objspace/std/tupletype.py Mon Feb 7 20:26:07 2005 @@ -1,7 +1,7 @@ from pypy.objspace.std.stdtypedef import * +from pypy.interpreter.gateway import NoneNotWrapped - -def descr__new__(space, w_tupletype, w_items=None): +def descr__new__(space, w_tupletype, w_items=NoneNotWrapped): from pypy.objspace.std.tupleobject import W_TupleObject if w_items is None: tuple_w = [] Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Mon Feb 7 20:26:07 2005 @@ -170,24 +170,29 @@ space.wrap("attribute '__dict__' of type objects " "is not writable")) + def unwrap(w_self): + if hasattr(w_self.instancetypedef, 'fakedcpytype'): + return w_self.instancetypedef.fakedcpytype + from pypy.objspace.std.model import UnwrapError + raise UnwrapError(w_self) -def call__Type(space, w_type, w_args, w_kwds): - args = Arguments.frompacked(space, w_args, w_kwds) + +def call__Type(space, w_type, __args__): # special case for type(x) if space.is_true(space.is_(w_type, space.w_type)): try: - w_obj, = args.fixedunpack(1) + w_obj, = __args__.fixedunpack(1) except ValueError: pass else: return space.type(w_obj) # invoke the __new__ of the type w_newfunc = space.getattr(w_type, space.wrap('__new__')) - w_newobject = space.call_args(w_newfunc, args.prepend(w_type)) + w_newobject = space.call_args(w_newfunc, __args__.prepend(w_type)) # maybe invoke the __init__ of the type if space.is_true(space.isinstance(w_newobject, w_type)): w_descr = space.lookup(w_newobject, '__init__') - space.get_and_call_args(w_descr, w_newobject, args) + space.get_and_call_args(w_descr, w_newobject, __args__) return w_newobject def issubtype__Type_Type(space, w_type1, w_type2): @@ -229,11 +234,6 @@ # XXX __delattr__ # XXX __hash__ ?? -def unwrap__Type(space, w_type): - if hasattr(w_type.instancetypedef, 'fakedcpytype'): - return w_type.instancetypedef.fakedcpytype - raise FailedToImplement - # ____________________________________________________________ Modified: pypy/dist/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/unicodeobject.py (original) +++ pypy/dist/pypy/objspace/std/unicodeobject.py Mon Feb 7 20:26:07 2005 @@ -5,10 +5,10 @@ W_UnicodeObject = fake_type(unicode) # string-to-unicode delegation -def delegate__String(space, w_str): +def delegate_String2Unicode(w_str): + space = w_str.space return W_UnicodeObject(space, unicode(space.str_w(w_str))) -delegate__String.result_class = W_UnicodeObject -delegate__String.priority = PRIORITY_CHANGE_TYPE + def eq__Unicode_ANY(space, w_uni, w_other): try: From sanxiyn at codespeak.net Tue Feb 8 05:18:32 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 8 Feb 2005 05:18:32 +0100 (MET) Subject: [pypy-svn] r8970 - pypy/dist/pypy/translator/test Message-ID: <20050208041832.E7C6727BDB@code1.codespeak.net> Author: sanxiyn Date: Tue Feb 8 05:18:32 2005 New Revision: 8970 Modified: pypy/dist/pypy/translator/test/snippet.py Log: docstring update Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Feb 8 05:18:32 2005 @@ -3,31 +3,13 @@ This module holds various snippets, to be used by translator unittests. -TODO, or sanxiyn's plan: - -Each snippet should know about suitable arguments to test it. -(Otherwise, there's a duplcation!) Should the result also be -stored? It can computed by CPython if we don't store it. - -In case of typed translation test, we can give input_arg_types -by actually trying type() on arguments. - -Each unittest should define a list of functions which it is able -to translate correctly, and import the list for tests. When -a translator can handle more, simply adding a function to the -list should suffice. - -But for now, none of the above applies. +We define argument types as default arguments to the snippet +functions. """ -# we define the starting types in the snippet -# function's default arguments. the following -# definitions denote to the "test-generator" -# the possible types that can be passed to -# the specific snippet. -numtype = (int, float, ) +numtype = (int, float) anytype = (int, float, str) -seqtype = (list, tuple) +seqtype = (list, tuple) def if_then_else(cond=anytype, x=anytype, y=anytype): if cond: From sanxiyn at codespeak.net Tue Feb 8 05:28:41 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 8 Feb 2005 05:28:41 +0100 (MET) Subject: [pypy-svn] r8971 - pypy/dist/pypy/translator/llvm/test Message-ID: <20050208042841.A754D27BEA@code1.codespeak.net> Author: sanxiyn Date: Tue Feb 8 05:28:41 2005 New Revision: 8971 Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py Log: Skip LLVM tests until llvmc problem is fixed. Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/test_genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Tue Feb 8 05:28:41 2005 @@ -11,7 +11,7 @@ from pypy.translator.llvm.test import llvmsnippet def setup_module(mod): - mod.llvm_found = is_on_path("llvm-as") + mod.llvm_found = 0 #is_on_path("llvm-as") def compile_function(function, annotate): t = Translator(function) From sanxiyn at codespeak.net Tue Feb 8 05:36:04 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Tue, 8 Feb 2005 05:36:04 +0100 (MET) Subject: [pypy-svn] r8972 - in pypy/dist/pypy/translator: . test Message-ID: <20050208043604.B6E3D27BEA@code1.codespeak.net> Author: sanxiyn Date: Tue Feb 8 05:36:04 2005 New Revision: 8972 Modified: pypy/dist/pypy/translator/genpyrex.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_pyrextrans.py Log: Implement op_contains for Pyrex generator. Modified: pypy/dist/pypy/translator/genpyrex.py ============================================================================== --- pypy/dist/pypy/translator/genpyrex.py (original) +++ pypy/dist/pypy/translator/genpyrex.py Tue Feb 8 05:36:04 2005 @@ -63,6 +63,10 @@ args = self.argnames return "%s = %s.next()" % (self.resultname, args[0]) + def op_contains(self): + args = self.argnames + return "%s = %s in %s" % (self.resultname, args[1], args[0]) + def op_getitem(self): direct = "%s = %s[%s]" % ((self.resultname,) + tuple(self.argnames)) w_sequence, w_index = self.op.args Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Feb 8 05:36:04 2005 @@ -37,6 +37,9 @@ def my_bool(x=int): return not not x +def my_contains(seq=seqtype, elem=anytype): + return elem in seq + def two_plus_two(): """Array test""" array = [0] * 3 Modified: pypy/dist/pypy/translator/test/test_pyrextrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_pyrextrans.py (original) +++ pypy/dist/pypy/translator/test/test_pyrextrans.py Tue Feb 8 05:36:04 2005 @@ -41,6 +41,10 @@ assert nested_whiles(111, 114) == ( '...!...!...!...!...!') + def test_my_contains(self): + my_contains = self.build_cfunc(snippet.my_contains) + assert my_contains([1, 2, 3], 1) + def test_poor_man_range(self): poor_man_range = self.build_cfunc(snippet.poor_man_range) assert poor_man_range(10) == range(10) From tismer at codespeak.net Tue Feb 8 09:50:32 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 8 Feb 2005 09:50:32 +0100 (MET) Subject: [pypy-svn] r8973 - pypy/dist/pypy/tool Message-ID: <20050208085032.0064827BEB@code1.codespeak.net> Author: tismer Date: Tue Feb 8 09:50:32 2005 New Revision: 8973 Modified: pypy/dist/pypy/tool/sourcetools.py Log: NiceCompile is probably not limited to functions any longer, but should compile everything. Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Tue Feb 8 09:50:32 2005 @@ -50,8 +50,7 @@ """ instance NiceCompile (src, args) -- formats src with args and returns a code object ready for exec. Instead of , the code object has correct co_filename and line numbers. - Note that this is meant for function definitions, only. - The statemens may be left aligned. + Indentation is automatically corrected. """ if self.srctext: p = self.srctext.index(src) @@ -63,7 +62,7 @@ content = line.strip() if content and not content.startswith('#'): break - # see if firstline is indented + # see if first line is indented if line and line[0].isspace(): # fake a block prelines -= 1 From pedronis at codespeak.net Tue Feb 8 11:44:29 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 11:44:29 +0100 (MET) Subject: [pypy-svn] r8979 - pypy/dist/pypy/lib/test2 Message-ID: <20050208104429.A417927C4D@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 11:44:29 2005 New Revision: 8979 Modified: pypy/dist/pypy/lib/test2/test_class.py Log: make this temp test and the use of NiceCompile in _classobj mutually non fragile Modified: pypy/dist/pypy/lib/test2/test_class.py ============================================================================== --- pypy/dist/pypy/lib/test2/test_class.py (original) +++ pypy/dist/pypy/lib/test2/test_class.py Tue Feb 8 11:44:29 2005 @@ -8,14 +8,16 @@ # incorporated into the core after translation, # this test file should really vanish! -import pypy, os +import pypy, os, new prefix = os.path.dirname(pypy.__file__) libdir = os.path.join(prefix, "lib") fname = "_classobj.py" fpath = os.path.join(libdir, fname) -execfile(fpath) +mod = new.module("_classobj") +mod.__file__ = fpath +execfile(fpath, mod.__dict__) -__metaclass__ = classobj +__metaclass__ = mod.classobj # HACK END From cfbolz at codespeak.net Tue Feb 8 12:17:48 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Tue, 8 Feb 2005 12:17:48 +0100 (MET) Subject: [pypy-svn] r8980 - pypy/dist/pypy/translator/llvm Message-ID: <20050208111748.61AFC27C64@code1.codespeak.net> Author: cfbolz Date: Tue Feb 8 12:17:48 2005 New Revision: 8980 Modified: pypy/dist/pypy/translator/llvm/build_llvm_module.py pypy/dist/pypy/translator/llvm/genllvm.py Log: Removed the usage of llvmc. Modified: pypy/dist/pypy/translator/llvm/build_llvm_module.py ============================================================================== --- pypy/dist/pypy/translator/llvm/build_llvm_module.py (original) +++ pypy/dist/pypy/translator/llvm/build_llvm_module.py Tue Feb 8 12:17:48 2005 @@ -19,34 +19,30 @@ class CompileError(exceptions.Exception): pass -def system_trace(cmd): - print cmd - return old_system(cmd) +OPTIMIZATION_SWITCHES = "-simplifycfg -mem2reg -instcombine -dce -inline" -old_system = os.system -os.system = system_trace - -def make_module_from_llvm(llvmfile, pyxfile, optimize=True): +def make_module_from_llvm(llvmfile, pyxfile, optimize=False): include_dir = autopath.this_dir dirpath = llvmfile.dirpath() lastdir = path.local() os.chdir(str(dirpath)) modname = pyxfile.purebasename ops1 = ["llvm-as %s -f -o %s.bc" % (llvmfile, llvmfile.purebasename), - "llvmc -f -O3 %s.bc -o %s_optimized.o" % (llvmfile.purebasename, - llvmfile.purebasename), - "llc %s_optimized.o.bc -f -o %s.s" % (llvmfile.purebasename, - llvmfile.purebasename), + "opt %s -f %s.bc -o %s_optimized.bc" % (OPTIMIZATION_SWITCHES, + llvmfile.purebasename, + llvmfile.purebasename), + "llc %s_optimized.bc -f -o %s.s" % (llvmfile.purebasename, + llvmfile.purebasename), "as %s.s -o %s.o" % (llvmfile.purebasename, llvmfile.purebasename)] if not optimize: ops1 = ["llvm-as %s -f" % llvmfile, "llc %s.bc -f -o %s.s" % (llvmfile.purebasename, llvmfile.purebasename), "as %s.s -o %s.o" % (llvmfile.purebasename, - llvmfile.purebasename)] + llvmfile.purebasename)] ops2 = ["gcc -c -fPIC -I/usr/include/python %s.c" % pyxfile.purebasename, "gcc -shared %s.o %s.o -o %s.so" % (llvmfile.purebasename, - modname, modname)] + modname, modname)] try: if debug: print "modname", modname c = stdoutcapture.Capture(mixed_out_err = True) Modified: pypy/dist/pypy/translator/llvm/genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/genllvm.py Tue Feb 8 12:17:48 2005 @@ -34,7 +34,7 @@ debug = 0 -def llvmcompile(transl, optimize=True): +def llvmcompile(transl, optimize=False): gen = LLVMGenerator(transl) return gen.compile(optimize) @@ -53,7 +53,7 @@ self.llvm_reprs = {} self.l_entrypoint = self.get_repr(self.translator.functions[0]) - def compile(self, optimize=True): + def compile(self, optimize=False): from pypy.tool.udir import udir name = self.l_entrypoint.llvmname()[1:] llvmfile = udir.join('%s.ll' % name) From pedronis at codespeak.net Tue Feb 8 12:20:14 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 12:20:14 +0100 (MET) Subject: [pypy-svn] r8981 - pypy/dist/pypy/lib Message-ID: <20050208112014.5600F27C64@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 12:20:14 2005 New Revision: 8981 Modified: pypy/dist/pypy/lib/_classobj.py Log: use hidden away slots in app-level implemented old-style classes to avoid abusing __dict__ to store __class__ __bases__ and __name__ special attributes . Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Tue Feb 8 12:20:14 2005 @@ -21,13 +21,22 @@ v += 1 return v & MASK +# we use slots that we remove from type __dict__ for special attributes +# +# for classobj they are __bases__ and __name__ (classobj_bases_slot, classobj_name_slot) +# for instance it's __class__ (instance_class_slot) + + +# ____________________________________________________________ +# classobj def + def type_err(arg, expected, v): return TypeError("argument %s must be %s, not %s" % (arg, expected, type(v).__name__)) def set_name(cls, name): if not isinstance(name, str): raise TypeError, "__name__ must be a string object" - obj_setattr(cls, '__name__', name) + classobj_name_slot.__set__(cls, name) def set_bases(cls, bases): if not isinstance(bases, tuple): @@ -35,14 +44,11 @@ for b in bases: if not isinstance(b, classobj): raise TypeError, "__bases__ items must be classes" - obj_setattr(cls, '__bases__', bases) + classobj_bases_slot.__set__(cls, bases) def set_dict(cls, dic): if not isinstance(dic, dict): raise TypeError, "__dict__ must be a dictionary object" - # preserved __name__ and __bases__ - dic['__name__'] = cls.__name__ - dic['__bases__'] = cls.__bases__ obj_setattr(cls, '__dict__', dic) def retrieve(obj, attr): @@ -58,7 +64,7 @@ v = retrieve(cls, attr) return v, cls except AttributeError: - for b in obj_getattribute(cls, '__bases__'): + for b in classobj_bases_slot.__get__(cls): v, found = lookup(b, attr) if found: return v, found @@ -95,6 +101,8 @@ class classobj(object): + __slots__ = ('_name', '_bases', '__dict__') + def __new__(subtype, name, bases, dic): if not isinstance(name, str): raise type_err('name', 'string', name) @@ -135,8 +143,8 @@ new_class = object.__new__(classobj) obj_setattr(new_class, '__dict__', dic) - obj_setattr(new_class, '__name__', name) - obj_setattr(new_class, '__bases__', bases) + classobj_name_slot.__set__(new_class, name) + classobj_bases_slot.__set__(new_class, bases) return new_class @@ -160,11 +168,14 @@ def __getattribute__(self, attr): if attr == '__dict__': return obj_getattribute(self, '__dict__') + if attr == '__name__': + return classobj_name_slot.__get__(self) + if attr == '__bases__': + return classobj_bases_slot.__get__(self) + v, found = lookup(self, attr) if not found: raise AttributeError, "class %s has no attribute %s" % (self.__name__, attr) - if attr in ('__name__', '__bases__'): - return v descr_get = mro_lookup(v, '__get__') if descr_get is None: @@ -185,7 +196,7 @@ def __call__(self, *args, **kwds): inst = object.__new__(instance) dic = inst.__dict__ - dic['__class__'] = self + instance_class_slot.__set__(inst, self) init = instance_getattr1(inst,'__init__', False) if init: ret = init(*args, **kwds) @@ -193,21 +204,25 @@ raise TypeError("__init__() should return None") return inst -# first we use the object's dict for the instance dict. -# with a little more effort, it should be possible -# to provide a clean extra dict with no other attributes -# in it. +# capture _name, _bases slots for usage and then hide them! + +classobj_name_slot = classobj._name +classobj_bases_slot = classobj._bases + +del classobj._name, classobj._bases + +# ____________________________________________________________ +# instance def def instance_getattr1(inst, name, exc=True): if name == "__dict__": return obj_getattribute(inst, name) elif name == "__class__": - # for now, it lives in the instance dict - return retrieve(inst, name) + return instance_class_slot.__get__(inst) try: return retrieve(inst, name) except AttributeError: - cls = retrieve(inst, "__class__") + cls = instance_class_slot.__get__(inst) v, found = lookup(cls, name) if not found: if exc: @@ -220,6 +235,9 @@ return descr_get(v, inst, cls) class instance(object): + + __slots__ = ('_class', '__dict__') + def __getattribute__(self, name): try: return instance_getattr1(self, name) @@ -238,7 +256,7 @@ elif not isinstance(dic, dict): raise TypeError("instance() second arg must be dictionary or None") inst = object.__new__(instance) - dic['__class__'] = klass + instance_class_slot.__set__(inst, klass) obj_setattr(inst, '__dict__', dic) return inst @@ -246,14 +264,11 @@ if name == '__dict__': if not isinstance(value, dict): raise TypeError("__dict__ must be set to a dictionary") - # for now, we need to copy things, because we are using - # the __dict__for our class as well. This will vanish! - value['__class__'] = self.__class__ obj_setattr(self, '__dict__', value) elif name == '__class__': if not isinstance(value, classobj): raise TypeError("__class__ must be set to a class") - self.__dict__['__class__'] = value + instance_class_slot.__set__(inst, value) else: setattr = instance_getattr1(self, '__setattr__', exc=False) if setattr is not None: @@ -530,5 +545,9 @@ return 0 raise TypeError,"__cmp__ must return int" return NotImplemented + +# capture _class slot for usage and then hide them! +instance_class_slot = instance._class +del instance._class del _compile, NiceCompile From arigo at codespeak.net Tue Feb 8 12:41:15 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 8 Feb 2005 12:41:15 +0100 (MET) Subject: [pypy-svn] r8982 - pypy/dist/pypy/objspace/std Message-ID: <20050208114115.6A79327C1B@code1.codespeak.net> Author: arigo Date: Tue Feb 8 12:41:15 2005 New Revision: 8982 Modified: pypy/dist/pypy/objspace/std/longobject.py Log: turned lshift__Long_Int() into lshift__Long_Long() for now, to simplify conversion and slicing nightmares (2L<<3L no longer worked). Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Tue Feb 8 12:41:15 2005 @@ -189,18 +189,22 @@ def invert__Long(space, w_long): return W_LongObject(space, ~w_long.longval) -def lshift__Long_Int(space, w_long1, w_int2): +def lshift__Long_Long(space, w_long1, w_long2): a = w_long1.longval - b = w_int2.intval + b = w_long2.longval if b < 0: raise OperationError(space.w_ValueError, space.wrap("negative shift count")) - res = a << b + try: + res = a << b + except OverflowError: # b too big + raise OperationError(space.w_OverflowError, + space.wrap("shift count too large")) return W_LongObject(space, res) -def rshift__Long_Int(space, w_long1, w_int2): +def rshift__Long_Long(space, w_long1, w_long2): a = w_long1.longval - b = w_int2.intval + b = w_long2.longval if b < 0: raise OperationError(space.w_ValueError, space.wrap("negative shift count")) @@ -239,7 +243,7 @@ # register implementations of ops that recover int op overflows # binary ops -for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod']: +for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod', 'lshift']: exec """ def %(opname)s_ovr__Int_Int(space, w_int1, w_int2): w_long1 = delegate_Int2Long(w_int1) @@ -259,13 +263,6 @@ getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int' %opname], W_IntObject, order=1) -# lshift -def lshift_ovr__Int_Int(space, w_int1, w_cnt): - w_long1 = delegate_Int2Long(w_int1) - return lshift__Long_Int(space, w_long1, w_cnt) - -StdObjSpace.MM.lshift.register(lshift_ovr__Int_Int, W_IntObject, W_IntObject, order=1) - # pow def pow_ovr__Int_Int_None(space, w_int1, w_int2, w_none3): w_long1 = delegate_Int2Long(w_int1) From pedronis at codespeak.net Tue Feb 8 14:02:44 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 14:02:44 +0100 (MET) Subject: [pypy-svn] r8983 - in pypy/dist/pypy: interpreter module module/test objspace objspace/std Message-ID: <20050208130244.A42DD27C66@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 14:02:44 2005 New Revision: 8983 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/test/test_builtin.py pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/floatobject.py pypy/dist/pypy/objspace/std/intobject.py pypy/dist/pypy/objspace/std/longobject.py Log: coerce impl for numeric types Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Tue Feb 8 14:02:44 2005 @@ -344,6 +344,7 @@ ('gt', '>', 2, ['__gt__', '__lt__']), ('ge', '>=', 2, ['__ge__', '__le__']), ('cmp', 'cmp', 2, ['__cmp__']), # rich cmps preferred + ('coerce', 'coerce', 2, ['__coerce__', '__coerce__']), ('contains', 'contains', 2, ['__contains__']), ('iter', 'iter', 1, ['__iter__']), ('next', 'next', 1, ['next']), Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Tue Feb 8 14:02:44 2005 @@ -289,6 +289,15 @@ """return 0 when x == y, -1 when x < y and 1 when x > y """ return space.cmp(w_x, w_y) +def coerce(w_x, w_y): + """coerce(x, y) -> (x1, y1) + + Return a tuple consisting of the two numeric arguments converted to + a common type, using the same rules as used by arithmetic operations. + If coercion is not possible, raise TypeError.""" + return space.coerce(w_x, w_y) + + #XXX works only for new-style classes. #So we have to fix it, when we add support for old-style classes def _issubtype(w_cls1, w_cls2): Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Tue Feb 8 14:02:44 2005 @@ -466,7 +466,7 @@ __interplevel__execfile('__builtin__interp.py') from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp +from __interplevel__ import hash, oct, hex, round, cmp, coerce from __interplevel__ import getattr, setattr, delattr, iter, hash, id from __interplevel__ import _issubtype from __interplevel__ import compile, eval Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Tue Feb 8 14:02:44 2005 @@ -248,6 +248,17 @@ c2 = C() raises(RuntimeError, cmp, c1, c2) + def test_coerce(self): + assert coerce(1, 1) == (1, 1) + assert coerce(1L, 1L) == (1L, 1L) + assert coerce(1, 1L) == (1L, 1L) + assert coerce(1L, 1) == (1L, 1L) + assert coerce(1, 1.0) == (1.0, 1.0) + assert coerce(1.0, 1L) == (1.0, 1.0) + assert coerce(1L, 1.0) == (1.0, 1.0) + raises(TypeError,coerce, 1 , 'a') + raises(TypeError,coerce, u'a' , 'a') + def test_return_None(self): class X: pass x = X() Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Feb 8 14:02:44 2005 @@ -293,6 +293,28 @@ else: return space.wrap(1) + def coerce(space, w_obj1, w_obj2): + w_typ1 = space.type(w_obj1) + w_typ2 = space.type(w_obj2) + w_left_impl = space.lookup(w_obj1, '__coerce__') + if space.is_true(space.is_(w_typ1, w_typ2)): + w_right_impl = None + else: + w_right_impl = space.lookup(w_obj2, '__coerce__') + if space.is_true(space.issubtype(w_typ1, w_typ2)): + w_obj1, w_obj2 = w_obj2, w_obj1 + w_left_impl, w_right_impl = w_right_impl, w_left_impl + + w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2) + if w_res is not None and not space.is_w(w_res, space.w_None): + return w_res + w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1) + if w_res is not None and not space.is_w(w_res, space.w_None): + return w_res + raise OperationError(space.w_TypeError, + space.wrap("coercion failed")) + + # xxx round, ord Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Tue Feb 8 14:02:44 2005 @@ -138,6 +138,11 @@ # real Implementation should be taken from _Py_HashDouble in object.c return space.wrap(hash(w_value.floatval)) +# coerce +def coerce__Float_Float(space, w_float1, w_float2): + return space.newtuple([w_float1, w_float2]) + + def add__Float_Float(space, w_float1, w_float2): x = w_float1.floatval y = w_float2.floatval Modified: pypy/dist/pypy/objspace/std/intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/intobject.py (original) +++ pypy/dist/pypy/objspace/std/intobject.py Tue Feb 8 14:02:44 2005 @@ -125,6 +125,11 @@ else: return _hash_liberal(space, w_int1) +# coerce +def coerce__Int_Int(space, w_int1, w_int2): + return space.newtuple([w_int1, w_int2]) + + def add__Int_Int(space, w_int1, w_int2): x = w_int1.intval y = w_int2.intval Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Tue Feb 8 14:02:44 2005 @@ -93,6 +93,11 @@ # real Implementation should be taken from _Py_HashDouble in object.c return space.wrap(hash(w_value.longval)) +# coerce +def coerce__Long_Long(space, w_long1, w_long2): + return space.newtuple([w_long1, w_long2]) + + def add__Long_Long(space, w_long1, w_long2): x = w_long1.longval y = w_long2.longval From pedronis at codespeak.net Tue Feb 8 14:20:45 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 14:20:45 +0100 (MET) Subject: [pypy-svn] r8986 - pypy/dist/pypy/lib Message-ID: <20050208132045.7D9CC27C66@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 14:20:45 2005 New Revision: 8986 Modified: pypy/dist/pypy/lib/_classobj.py Log: use now impl coerce in _classobj and old-style __coerce__ support Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Tue Feb 8 14:20:45 2005 @@ -4,10 +4,11 @@ from pypy.tool.sourcetools import NiceCompile _compile = NiceCompile(globals()) -def coerce(left, right): - # XXX this is just a surrogate for now - # XXX the builtin coerce needs to be implemented by PyPy - return None +def _coerce(left, right): + try: + return coerce(left, right) + except TypeError: + return None obj_setattr = object.__setattr__ obj_getattribute = object.__getattribute__ @@ -372,6 +373,13 @@ """, {"op": op}) del op + # coerce + def __coerce__(self, other): + func = instance_getattr1(self, '__coerce__', False) + if func: + return func(other) + return NotImplemented + # binary operators for op in "or and xor lshift rshift add sub mul div mod divmod floordiv truediv".split(): @@ -383,7 +391,7 @@ exec _compile(""" def __%(op)s__(self, other): - coerced = coerce(self, other) + coerced = _coerce(self, other) if coerced is None or coerced[0] is self: func = instance_getattr1(self, '__%(op)s__', False) if func: @@ -393,7 +401,7 @@ return %(opref)s(self, other) def __r%(op)s__(self, other): - coerced = coerce(self, other) + coerced = _coerce(self, other) if coerced is None or coerced[0] is self: func = instance_getattr1(self, '__r%(op)s__', False) if func: @@ -422,7 +430,7 @@ def __pow__(self, other, modulo=None): if modulo is None: - coerced = coerce(self, other) + coerced = _coerce(self, other) if coerced is None or coerced[0] is self: func = instance_getattr1(self, '__pow__', False) if func: @@ -440,7 +448,7 @@ def __rpow__(self, other, modulo=None): if modulo is None: - coerced = coerce(self, other) + coerced = _coerce(self, other) if coerced is None or coerced[0] is self: func = instance_getattr1(self, '__rpow__', False) if func: @@ -513,7 +521,7 @@ return func() def __cmp__(self, other): # do all the work here like CPython - coerced = coerce(self, other) + coerced = _coerce(self, other) if coerced is None: v = self w = other From pedronis at codespeak.net Tue Feb 8 14:58:51 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 14:58:51 +0100 (MET) Subject: [pypy-svn] r8988 - pypy/dist/pypy/objspace Message-ID: <20050208135851.EC4EE27C66@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 14:58:51 2005 New Revision: 8988 Modified: pypy/dist/pypy/objspace/descroperation.py Log: checking __coerce__ return values Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Feb 8 14:58:51 2005 @@ -306,13 +306,17 @@ w_left_impl, w_right_impl = w_right_impl, w_left_impl w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2) - if w_res is not None and not space.is_w(w_res, space.w_None): - return w_res - w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1) - if w_res is not None and not space.is_w(w_res, space.w_None): - return w_res - raise OperationError(space.w_TypeError, - space.wrap("coercion failed")) + if w_res is None or space.is_w(w_res, space.w_None): + w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1) + if w_res is None or space.is_w(w_res, space.w_None): + raise OperationError(space.w_TypeError, + space.wrap("coercion failed")) + if (not space.is_true(space.isinstance(w_res, space.w_tuple)) or + space.int_w(space.len(w_res)) != 2): + raise OperationError(space.w_TypeError, + space.wrap("coercion should return None or 2-tuple")) + return w_res + # xxx round, ord From pedronis at codespeak.net Tue Feb 8 15:35:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 15:35:54 +0100 (MET) Subject: [pypy-svn] r8992 - pypy/dist/pypy/objspace/std Message-ID: <20050208143554.9A4E327BF3@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 15:35:54 2005 New Revision: 8992 Modified: pypy/dist/pypy/objspace/std/stringobject.py Log: small fix Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Tue Feb 8 15:35:54 2005 @@ -933,7 +933,7 @@ def mul__String_ANY(space, w_str, w_times): return mul_string_times(space, w_str, space.int_w(w_times)) -def mul__ANY_String(space, w_mul, w_str): +def mul__ANY_String(space, w_times, w_str): return mul_string_times(space, w_str, space.int_w(w_times)) def add__String_String(space, w_left, w_right): From pedronis at codespeak.net Tue Feb 8 16:20:21 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 8 Feb 2005 16:20:21 +0100 (MET) Subject: [pypy-svn] r8993 - pypy/dist/pypy/objspace/std Message-ID: <20050208152021.7B3DE27BBA@code1.codespeak.net> Author: pedronis Date: Tue Feb 8 16:20:21 2005 New Revision: 8993 Modified: pypy/dist/pypy/objspace/std/model.py pypy/dist/pypy/objspace/std/multimethod.py pypy/dist/pypy/objspace/std/objspace.py Log: make translate_pypy -no-a answer 42 again after the multimethod code changes. There are probably more things not used at runtime that could be marked NOT_RPYTHON. These are the minimal stuff that was needed to make translate_pypy -no-a complete again. Modified: pypy/dist/pypy/objspace/std/model.py ============================================================================== --- pypy/dist/pypy/objspace/std/model.py (original) +++ pypy/dist/pypy/objspace/std/model.py Tue Feb 8 16:20:21 2005 @@ -10,6 +10,7 @@ class StdTypeModel: def __init__(self): + """NOT_RPYTHON: inititialization only""" # All the Python types that we want to provide in this StdObjSpace class result: from pypy.objspace.std.objecttype import object_typedef Modified: pypy/dist/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/dist/pypy/objspace/std/multimethod.py Tue Feb 8 16:20:21 2005 @@ -76,6 +76,7 @@ return True def signatures(self): + """NOT_RPYTHON""" result = [] def enum_keys(types_so_far, node): for type, subnode in node.items(): Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Tue Feb 8 16:20:21 2005 @@ -87,6 +87,7 @@ self.sys.setbuiltinmodule(w_exceptions, 'exceptions') def setup_exceptions(self, for_builtins): + """NOT_RPYTHON""" ## hacking things in from pypy.module import exceptionsinterp as ex def call(w_type, w_args): From ac at codespeak.net Wed Feb 9 11:29:19 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 9 Feb 2005 11:29:19 +0100 (MET) Subject: [pypy-svn] r9023 - pypy/dist/pypy/objspace/std Message-ID: <20050209102919.28FD727B75@code1.codespeak.net> Author: ac Date: Wed Feb 9 11:29:19 2005 New Revision: 9023 Modified: pypy/dist/pypy/objspace/std/tupletype.py Log: Optimize creation of a tuple from annother tuple. Modified: pypy/dist/pypy/objspace/std/tupletype.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupletype.py (original) +++ pypy/dist/pypy/objspace/std/tupletype.py Wed Feb 9 11:29:19 2005 @@ -5,6 +5,9 @@ from pypy.objspace.std.tupleobject import W_TupleObject if w_items is None: tuple_w = [] + elif (space.is_w(w_tupletype, space.w_tuple) and + space.is_w(space.type(w_items), space.w_tuple)): + return w_items else: tuple_w = space.unpackiterable(w_items) w_obj = space.allocate_instance(W_TupleObject, w_tupletype) From ac at codespeak.net Wed Feb 9 11:32:27 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 9 Feb 2005 11:32:27 +0100 (MET) Subject: [pypy-svn] r9024 - pypy/dist/pypy/module Message-ID: <20050209103227.CE6D427B75@code1.codespeak.net> Author: ac Date: Wed Feb 9 11:32:27 2005 New Revision: 9024 Modified: pypy/dist/pypy/module/__builtin__module.py Log: - Accept an argument to input(). - Test for correct types of arguments in range. - Tweak the specialcasing of tuples in filter. - implement reload. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Feb 9 11:32:27 2005 @@ -49,8 +49,8 @@ raise EOFError return line -def input(): - return eval(raw_input()) +def input(prompt=None): + return eval(raw_input(prompt)) def sum(sequence, total=0): @@ -145,7 +145,7 @@ else: res = [item for item in collection if function(item)] - if type(collection) is tuple: + if isinstance(collection, tuple): return tuple(res) else: return res @@ -233,6 +233,7 @@ to zero) to stop - 1 by step (defaults to 1). Use a negative step to get a list in decending order.""" + if y is None: start = 0 stop = x @@ -240,6 +241,13 @@ start = x stop = y + if not isinstance(start, (int, long)): + raise TypeError('range() interger start argument expected, got %s' % type(start)) + if not isinstance(stop, (int, long)): + raise TypeError('range() interger stop argument expected, got %s' % type(stop)) + if not isinstance(step, (int, long)): + raise TypeError('range() interger step argument expected, got %s' % type(step)) + if step == 0: raise ValueError, 'range() arg 3 must not be zero' @@ -656,7 +664,7 @@ x = x.__get__(d['__self__'], type(d['__self__'])) return x return object.__getattribute__(self, attr) # fall-back - + class complex(object): """complex(real[, imag]) -> complex number @@ -985,6 +993,39 @@ yield local_iterable[index] return reversed_gen(seq) +def reload(module): + import imp, sys, errno + + if type(module) not in (type(imp), type(errno)): + raise TypeError("reload() argument must be module") + + name = module.__name__ + if module is not sys.modules[name]: + raise ImportError("reload(): module %.200s not in sys.modules" % name) + + namepath = name.split('.') + subname = namepath[-1] + parent_name = '.'.join(namepath[:-1]) + parent = None + path = None + if parent_name: + try: + parent = sys.modules[parent_name] + except KeyError: + raise ImportError("reload(): parent %.200s not in sys.modules" % + parent_name) + path = parent.__path__ + + f, filename, description = imp.find_module(subname, path) + try: + new_module = imp.load_module(name, f, filename, description) + finally: + sys.modules[name] = module + if f is not None: + f.close() + + return new_module + #from _file import file #open = file From pedronis at codespeak.net Wed Feb 9 13:08:23 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 9 Feb 2005 13:08:23 +0100 (MET) Subject: [pypy-svn] r9025 - pypy/dist/pypy/lib Message-ID: <20050209120823.7673627BE1@code1.codespeak.net> Author: pedronis Date: Wed Feb 9 13:08:23 2005 New Revision: 9025 Modified: pypy/dist/pypy/lib/_classobj.py Log: small fix (bug uncovered by geninterplevel) Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Wed Feb 9 13:08:23 2005 @@ -269,7 +269,7 @@ elif name == '__class__': if not isinstance(value, classobj): raise TypeError("__class__ must be set to a class") - instance_class_slot.__set__(inst, value) + instance_class_slot.__set__(self, value) else: setattr = instance_getattr1(self, '__setattr__', exc=False) if setattr is not None: From pedronis at codespeak.net Wed Feb 9 13:10:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 9 Feb 2005 13:10:54 +0100 (MET) Subject: [pypy-svn] r9026 - pypy/dist/pypy/objspace/flow Message-ID: <20050209121054.5850727BE1@code1.codespeak.net> Author: pedronis Date: Wed Feb 9 13:10:54 2005 New Revision: 9026 Modified: pypy/dist/pypy/objspace/flow/objspace.py Log: avoid method-wrappers to appear as constant in a flow graph and during its contruction, - construction time problem is that they compare by identity and replaying will produce mismatching ops because of this - problem for translation tools down the chain is that method-wrappers offer very poor introspectio, so it hard to build code to (re)construct them Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Wed Feb 9 13:10:54 2005 @@ -11,6 +11,13 @@ class UnwrapException(Exception): "Attempted to unwrap a Variable." +class WrapException(Exception): + """Attempted wrapping of a type that cannot sanely appear in flow graph or during its construction""" + +# method-wrappers +method_wrapper = type(complex.real.__get__) + + # ______________________________________________________________________ class FlowObjSpace(ObjSpace): """NOT_RPYTHON. @@ -97,6 +104,10 @@ def wrap(self, obj): if isinstance(obj, (Variable, Constant)) and obj is not UNDEFINED: raise TypeError("already wrapped: " + repr(obj)) + # method-wrapper have ill-defined comparison and introspection + # to appear in a flow graph + if type(obj) is method_wrapper: + raise WrapException return Constant(obj) def int_w(self, w_obj): @@ -391,7 +402,12 @@ raise flowcontext.OperationThatShouldNotBePropagatedError( self.wrap(etype), self.wrap(msg)) else: - return self.wrap(result) + try: + return self.wrap(result) + except WrapException: + # type cannot sanely appear in flow graph, + # store operation with variable result instead + pass #print >> sys.stderr, 'Variable operation', name, args_w w_result = self.do_operation(name, *args_w) From pedronis at codespeak.net Wed Feb 9 13:26:29 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 9 Feb 2005 13:26:29 +0100 (MET) Subject: [pypy-svn] r9027 - pypy/dist/pypy/translator Message-ID: <20050209122629.862C527BFF@code1.codespeak.net> Author: pedronis Date: Wed Feb 9 13:26:29 2005 New Revision: 9027 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: - UnwrapError moved - don't prevent slots creation Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Wed Feb 9 13:26:29 2005 @@ -582,7 +582,7 @@ for key, value in content: if key.startswith('__'): if key in ['__module__', '__doc__', '__dict__', - '__weakref__', '__repr__', '__metaclass__']: + '__weakref__', '__repr__', '__metaclass__', '__slots__']: continue # redirect value through class interface, in order to @@ -603,7 +603,7 @@ self.initcode.appendnew('_dic = space.newdict([])') for key, value in cls.__dict__.items(): if key.startswith('__'): - if key in ['__module__', '__metaclass__']: + if key in ['__module__', '__metaclass__', '__slots__']: keyname = self.nameof(key) valname = self.nameof(value) self.initcode.appendnew("space.setitem(_dic, %s, %s)" % ( @@ -1128,7 +1128,7 @@ # entry point: %(entrypointname)s, %(entrypoint)s if __name__ == "__main__": from pypy.objspace.std import StdObjSpace - from pypy.objspace.std.default import UnwrapError + from pypy.objspace.std.model import UnwrapError space = StdObjSpace() init%(modname)s(space) ret = space.call(gfunc_%(entrypointname)s, space.newtuple([])) From pedronis at codespeak.net Wed Feb 9 14:00:32 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 9 Feb 2005 14:00:32 +0100 (MET) Subject: [pypy-svn] r9028 - pypy/dist/pypy/translator Message-ID: <20050209130032.B62EB27BDA@code1.codespeak.net> Author: pedronis Date: Wed Feb 9 14:00:32 2005 New Revision: 9028 Modified: pypy/dist/pypy/translator/translator.py Log: do not force to specify an entrypoint up front Modified: pypy/dist/pypy/translator/translator.py ============================================================================== --- pypy/dist/pypy/translator/translator.py (original) +++ pypy/dist/pypy/translator/translator.py Wed Feb 9 14:00:32 2005 @@ -45,7 +45,7 @@ class Translator: - def __init__(self, func, verbose=False, simplifying=False): + def __init__(self, func=None, verbose=False, simplifying=False): self.entrypoint = func self.verbose = verbose self.simplifying = simplifying @@ -58,7 +58,8 @@ self.functions = [] # the keys of self.flowgraphs, in creation order self.callgraph = {} # {opaque_tag: (caller, callee)} self.frozen = False # when frozen, no more flowgraphs can be generated - self.getflowgraph() + if self.entrypoint: + self.getflowgraph() def getflowgraph(self, func=None, called_by=None, call_tag=None): """Get the flow graph for a function (default: the entry point).""" From ac at codespeak.net Wed Feb 9 14:35:20 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 9 Feb 2005 14:35:20 +0100 (MET) Subject: [pypy-svn] r9029 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050209133520.2649127BDA@code1.codespeak.net> Author: ac Date: Wed Feb 9 14:35:19 2005 New Revision: 9029 Modified: pypy/dist/pypy/objspace/std/dictobject.py pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/test/test_dictobject.py pypy/dist/pypy/objspace/std/test/test_listobject.py Log: Handle str/repr on lists and dicts containing themselves. Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Wed Feb 9 14:35:19 2005 @@ -247,10 +247,21 @@ # multimethod lookup mapping str to StdObjSpace.str # This cannot happen until multimethods are fixed. See dicttype.py def app_str__Dict(d): - items = [] - for k, v in d.iteritems(): - items.append(repr(k) + ": " + repr(v)) - return "{" + ', '.join(items) + "}" + global _currently_in_repr + if len(d) == 0: + return '{}' + if '_currently_in_repr' not in globals(): + _currently_in_repr = [] + if id(d) in _currently_in_repr: + return '{...}' + try: + _currently_in_repr.append(id(d)) + items = [] + for k, v in d.iteritems(): + items.append(repr(k) + ": " + repr(v)) + return "{" + ', '.join(items) + "}" + finally: + _currently_in_repr.remove(id(d)) repr__Dict = str__Dict = gateway.app2interp(app_str__Dict) from pypy.objspace.std import dicttype Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Wed Feb 9 14:35:19 2005 @@ -279,7 +279,18 @@ return space.w_None def app_repr__List(l): - return "[" + ", ".join([repr(x) for x in l]) + ']' + global _currently_in_repr + if len(l) == 0: + return '[]' + if '_currently_in_repr' not in globals(): + _currently_in_repr = [] + if id(l) in _currently_in_repr: + return '[...]' + try: + _currently_in_repr.append(id(l)) + return "[" + ", ".join([repr(x) for x in l]) + ']' + finally: + _currently_in_repr.remove(id(l)) def hash__List(space,w_list): raise OperationError(space.w_TypeError,space.wrap("list objects are unhashable")) Modified: pypy/dist/pypy/objspace/std/test/test_dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_dictobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_dictobject.py Wed Feb 9 14:35:19 2005 @@ -267,6 +267,12 @@ assert '{1: 2}' == repr({1: 2}) assert "{'ba': 'bo'}" == repr({'ba': 'bo'}) assert str({1: 2, 'ba': 'bo'}) in ok_reprs + + # Now test self-containing dict + d = {} + d[0] = d + assert str(d) == '{0: {...}}' + def test_new(self): d = dict() Modified: pypy/dist/pypy/objspace/std/test/test_listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_listobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_listobject.py Wed Feb 9 14:35:19 2005 @@ -375,3 +375,10 @@ l = range(6) l[1:3] = 'abc' assert l == [0, 'a', 'b', 'c', 3, 4, 5] + + def test_recursive_repr(self): + l = [] + assert repr(l) == '[]' + l.append(l) + assert repr(l) == '[[...]]' + From pedronis at codespeak.net Wed Feb 9 15:07:44 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 9 Feb 2005 15:07:44 +0100 (MET) Subject: [pypy-svn] r9030 - pypy/dist/pypy/translator Message-ID: <20050209140744.AEF7627B85@code1.codespeak.net> Author: pedronis Date: Wed Feb 9 15:07:44 2005 New Revision: 9030 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: - small changes to interface GenRpy: can take an entrypoint and reiceive a entrypoint-less Translator - it should be possible to use entrypoints that are not functions to start the process - hook (gen_trailer) for the final final part of the generated file Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Wed Feb 9 15:07:44 2005 @@ -113,10 +113,13 @@ return name class GenRpy: - def __init__(self, translator, modname=None): + def __init__(self, translator, entrypoint=None, modname=None): self.translator = translator + if entrypoint is None: + entrypoint = translator.entrypoint + self.entrypoint = entrypoint self.modname = self.trans_funcname(modname or - uniquemodulename(translator.functions[0].__name__)) + uniquemodulename(entrypoint)) self.moddict = None # the dict if we translate a module self.rpynames = {Constant(None).key: 'space.w_None', Constant(False).key: 'space.w_False', @@ -794,11 +797,9 @@ f = self.f info = { 'modname': self.modname, - 'entrypointname': self.trans_funcname( - self.translator.functions[0].__name__), - 'entrypoint': self.nameof(self.translator.functions[0]), + # the side-effects of this kick-start the process + 'entrypoint': self.nameof(self.entrypoint), } - self.entrypoint = info['entrypoint'] # header print >> f, self.RPY_HEADER print >> f @@ -814,10 +815,11 @@ self.seennames["__doc__"] = 1 self.initcode.append("m.__doc__ = space.wrap(m.__doc__)") # function implementations - while self.pendingfunctions: - func = self.pendingfunctions.pop() - self.currentfunc = func - self.gen_rpyfunction(func) + while self.pendingfunctions or self.latercode: + if self.pendingfunctions: + func = self.pendingfunctions.pop() + self.currentfunc = func + self.gen_rpyfunction(func) # collect more of the latercode after each function while self.latercode: gen, self.debugstack = self.latercode.pop() @@ -829,7 +831,7 @@ # set the final splitter print >> f, "##SECTION##" - # footer + # footer, init code print >> f, self.RPY_INIT_HEADER % info for codelines in self.initcode: # keep docstrings unindented @@ -842,9 +844,15 @@ codelines = codelines.split("\n") for codeline in codelines: print >> f, indent + codeline - print >> f, self.RPY_INIT_FOOTER % info + + self.gen_trailer(info, " ") + f.close() + def gen_trailer(self, info, indent): + info['entrypointname'] = self.trans_funcname(self.entrypoint.__name__) + print >> self.f, self.RPY_INIT_FOOTER % info + def gen_global_declarations(self): g = self.globaldecl if g: @@ -1131,7 +1139,7 @@ from pypy.objspace.std.model import UnwrapError space = StdObjSpace() init%(modname)s(space) - ret = space.call(gfunc_%(entrypointname)s, space.newtuple([])) + ret = space.call(%(entrypoint)s, space.newtuple([])) try: print space.unwrap(ret) except UnwrapError: @@ -1360,8 +1368,8 @@ # extract certain stuff like a general module maker # and put this into tools/compile_exceptions, maybe??? dic, entrypoint = exceptions_helper() - t = Translator(entrypoint, verbose=False, simplifying=True) - gen = GenRpy(t) + t = Translator(None, verbose=False, simplifying=True) + gen = GenRpy(t, entrypoint) gen.use_fast_call = True gen.moddict = dic gen.gen_source('/tmp/look.py') From ac at codespeak.net Wed Feb 9 15:30:47 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 9 Feb 2005 15:30:47 +0100 (MET) Subject: [pypy-svn] r9032 - pypy/dist/pypy/objspace Message-ID: <20050209143047.E248F27BBC@code1.codespeak.net> Author: ac Date: Wed Feb 9 15:30:47 2005 New Revision: 9032 Modified: pypy/dist/pypy/objspace/descroperation.py Log: Fix ordering in result from coerce. Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Wed Feb 9 15:30:47 2005 @@ -311,7 +311,12 @@ if w_res is None or space.is_w(w_res, space.w_None): raise OperationError(space.w_TypeError, space.wrap("coercion failed")) - if (not space.is_true(space.isinstance(w_res, space.w_tuple)) or + if (not space.is_true(space.isinstance(w_res, space.w_tuple)) or + space.int_w(space.len(w_res)) != 2): + raise OperationError(space.w_TypeError, + space.wrap("coercion should return None or 2-tuple")) + w_res = space.newtuple([space.getitem(w_res, space.wrap(1)), space.getitem(w_res, space.wrap(0))]) + elif (not space.is_true(space.isinstance(w_res, space.w_tuple)) or space.int_w(space.len(w_res)) != 2): raise OperationError(space.w_TypeError, space.wrap("coercion should return None or 2-tuple")) From ac at codespeak.net Wed Feb 9 15:31:46 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 9 Feb 2005 15:31:46 +0100 (MET) Subject: [pypy-svn] r9034 - pypy/dist/pypy/objspace/std Message-ID: <20050209143146.9C7C027BBC@code1.codespeak.net> Author: ac Date: Wed Feb 9 15:31:46 2005 New Revision: 9034 Modified: pypy/dist/pypy/objspace/std/longobject.py Log: Take proper care of Overflow when converting long -> float. Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Wed Feb 9 15:31:46 2005 @@ -33,7 +33,11 @@ # long-to-float delegation def delegate_Long2Float(w_longobj): - return W_FloatObject(w_longobj.space, float(w_longobj.longval)) + try: + return W_FloatObject(w_longobj.space, float(w_longobj.longval)) + except OverflowError: + raise OperationError(w_longobj.space.w_OverflowError, + w_longobj.space.wrap("long int too large to convert to float")) # long__Long is supposed to do nothing, unless it has From alastair at codespeak.net Wed Feb 9 16:11:07 2005 From: alastair at codespeak.net (alastair at codespeak.net) Date: Wed, 9 Feb 2005 16:11:07 +0100 (MET) Subject: [pypy-svn] r9035 - pypy/funding/negotiations Message-ID: <20050209151107.F073427BB9@code1.codespeak.net> Author: alastair Date: Wed Feb 9 16:11:07 2005 New Revision: 9035 Modified: pypy/funding/negotiations/pypy-consortium-contract.sxw Log: Added page per partner for signing. Modified: pypy/funding/negotiations/pypy-consortium-contract.sxw ============================================================================== Binary files. No diff available. From arigo at codespeak.net Wed Feb 9 16:47:26 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 9 Feb 2005 16:47:26 +0100 (MET) Subject: [pypy-svn] r9037 - pypy/dist/pypy/objspace/std Message-ID: <20050209154726.DA63327BDA@code1.codespeak.net> Author: arigo Date: Wed Feb 9 16:47:26 2005 New Revision: 9037 Modified: pypy/dist/pypy/objspace/std/dictobject.py pypy/dist/pypy/objspace/std/listobject.py Log: Use a dictionary instead of a list to store the id's during detection of recursive lists and dicts. Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Wed Feb 9 16:47:26 2005 @@ -251,17 +251,17 @@ if len(d) == 0: return '{}' if '_currently_in_repr' not in globals(): - _currently_in_repr = [] + _currently_in_repr = {} if id(d) in _currently_in_repr: return '{...}' try: - _currently_in_repr.append(id(d)) + _currently_in_repr[id(d)] = 1 items = [] for k, v in d.iteritems(): items.append(repr(k) + ": " + repr(v)) return "{" + ', '.join(items) + "}" finally: - _currently_in_repr.remove(id(d)) + del _currently_in_repr[id(d)] repr__Dict = str__Dict = gateway.app2interp(app_str__Dict) from pypy.objspace.std import dicttype Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Wed Feb 9 16:47:26 2005 @@ -283,14 +283,14 @@ if len(l) == 0: return '[]' if '_currently_in_repr' not in globals(): - _currently_in_repr = [] + _currently_in_repr = {} if id(l) in _currently_in_repr: return '[...]' try: - _currently_in_repr.append(id(l)) + _currently_in_repr[id(l)] = 1 return "[" + ", ".join([repr(x) for x in l]) + ']' finally: - _currently_in_repr.remove(id(l)) + del _currently_in_repr[id(l)] def hash__List(space,w_list): raise OperationError(space.w_TypeError,space.wrap("list objects are unhashable")) From arigo at codespeak.net Wed Feb 9 16:47:43 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 9 Feb 2005 16:47:43 +0100 (MET) Subject: [pypy-svn] r9038 - pypy/dist/pypy/module/test Message-ID: <20050209154743.9713327BDA@code1.codespeak.net> Author: arigo Date: Wed Feb 9 16:47:43 2005 New Revision: 9038 Modified: pypy/dist/pypy/module/test/test_builtin.py Log: Improved the tests for coerce(). Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Wed Feb 9 16:47:43 2005 @@ -249,13 +249,13 @@ raises(RuntimeError, cmp, c1, c2) def test_coerce(self): - assert coerce(1, 1) == (1, 1) - assert coerce(1L, 1L) == (1L, 1L) - assert coerce(1, 1L) == (1L, 1L) - assert coerce(1L, 1) == (1L, 1L) - assert coerce(1, 1.0) == (1.0, 1.0) - assert coerce(1.0, 1L) == (1.0, 1.0) - assert coerce(1L, 1.0) == (1.0, 1.0) + assert coerce(1, 2) == (1, 2) + assert coerce(1L, 2L) == (1L, 2L) + assert coerce(1, 2L) == (1L, 2L) + assert coerce(1L, 2) == (1L, 2L) + assert coerce(1, 2.0) == (1.0, 2.0) + assert coerce(1.0, 2L) == (1.0, 2.0) + assert coerce(1L, 2.0) == (1.0, 2.0) raises(TypeError,coerce, 1 , 'a') raises(TypeError,coerce, u'a' , 'a') From jacob at codespeak.net Wed Feb 9 17:05:12 2005 From: jacob at codespeak.net (jacob at codespeak.net) Date: Wed, 9 Feb 2005 17:05:12 +0100 (MET) Subject: [pypy-svn] r9039 - pypy/funding/negotiations Message-ID: <20050209160512.0658C27BD8@code1.codespeak.net> Author: jacob Date: Wed Feb 9 17:05:12 2005 New Revision: 9039 Added: pypy/funding/negotiations/pypy-association-agreement.sxw (contents, props changed) Log: First draft of association agreement. Added: pypy/funding/negotiations/pypy-association-agreement.sxw ============================================================================== Binary file. No diff available. From jacob at codespeak.net Wed Feb 9 17:24:06 2005 From: jacob at codespeak.net (jacob at codespeak.net) Date: Wed, 9 Feb 2005 17:24:06 +0100 (MET) Subject: [pypy-svn] r9040 - pypy/funding/negotiations Message-ID: <20050209162406.DF51827BD8@code1.codespeak.net> Author: jacob Date: Wed Feb 9 17:24:06 2005 New Revision: 9040 Modified: pypy/funding/negotiations/pypy-association-agreement.sxw Log: Added clause preventing double compenstion. Modified: pypy/funding/negotiations/pypy-association-agreement.sxw ============================================================================== Binary files. No diff available. From ac at codespeak.net Wed Feb 9 19:14:16 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Wed, 9 Feb 2005 19:14:16 +0100 (MET) Subject: [pypy-svn] r9041 - pypy/dist/pypy/module Message-ID: <20050209181416.D75F227BCB@code1.codespeak.net> Author: ac Date: Wed Feb 9 19:14:16 2005 New Revision: 9041 Modified: pypy/dist/pypy/module/__builtin__module.py Log: make raw_input conform closer to cpython. Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Wed Feb 9 19:14:16 2005 @@ -41,12 +41,27 @@ def raw_input(prompt=None): import sys + try: + sys.stdin + except AttributeError: + raise RuntimeError("[raw_]input: lost sys.stdin"); + try: + sys.stdout + except AttributeError: + raise RuntimeError("[raw_]input: lost sys.stdout"); if prompt is not None: sys.stdout.write(prompt) - sys.stdout.flush() + try: + flush = sys.stdout.flush + except AttributeError: + pass + else: + flush() line = sys.stdin.readline() if not line: # inputting an empty line gives line == '\n' raise EOFError + if line[-1] == '\n': + return line[:-1] return line def input(prompt=None): From pedronis at codespeak.net Thu Feb 10 13:56:04 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 13:56:04 +0100 (MET) Subject: [pypy-svn] r9043 - in pypy/dist/pypy: module objspace/std translator/tool Message-ID: <20050210125604.7845E27C0E@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 13:56:04 2005 New Revision: 9043 Added: pypy/dist/pypy/translator/tool/tointerplevel.py (contents, props changed) Modified: pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/objspace/std/objspace.py Log: * tointerplevel.py: simple tool wrapping GenRpy functionality usage: tointerplevel.py [options] module-file obj-name... options: -h, --help show this help message and exit --import-as=AS import module-file with this name -oOUTPUT, --out=OUTPUT output file --modname=MODNAME modname to be used by GenRpy from a module it creates an interp-level version with an init func that returns a specified set of objects from the module * version of exceptionsinterp.py obtained with: tointerplevel.py --modname=exceptions --out module/exceptionsinterp.py lib/_exceptions.py __dict__ Changed glue in objspace to work with it Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Thu Feb 10 13:56:04 2005 @@ -93,20 +93,141 @@ +-- RuntimeWarning +-- FutureWarning""" +# global declarations +# global object g47dict +# global object gs_MemoryError +# global object gcls_MemoryError +# global object gcls_StandardError +# global object gcls_Exception +# global object gs___module__ +# global object gs__exceptions +# global object gs___doc__ +# global object gs_Exception +# global object gs_StandardError +# global object gs_ImportError +# global object gcls_ImportError +# global object gs_RuntimeError +# global object gcls_RuntimeError +# global object gs_UnicodeTranslateError +# global object gcls_UnicodeTranslateError +# global object gcls_UnicodeError +# global object gcls_ValueError +# global object gs_ValueError +# global object gs_UnicodeError +# global object gs_KeyError +# global object gcls_KeyError +# global object gcls_LookupError +# global object gs_LookupError +# global object gs_TaskletExit +# global object gcls_TaskletExit +# global object gcls_SystemExit +# global object gs_SystemExit +# global object gs_StopIteration +# global object gcls_StopIteration +# global object gs_PendingDeprecationWarning +# global object gcls_PendingDeprecationWarning +# global object gcls_Warning +# global object gs_Warning +# global object gs_EnvironmentError +# global object gcls_EnvironmentError +# global object gs_OSError +# global object gcls_OSError +# global object gs_DeprecationWarning +# global object gcls_DeprecationWarning +# global object gs_FloatingPointError +# global object gcls_FloatingPointError +# global object gcls_ArithmeticError +# global object gs_ArithmeticError +# global object gs_AttributeError +# global object gcls_AttributeError +# global object gs_IndentationError +# global object gcls_IndentationError +# global object gcls_SyntaxError +# global object gs_SyntaxError +# global object gs_NameError +# global object gcls_NameError +# global object gs_OverflowWarning +# global object gcls_OverflowWarning +# global object gs_IOError +# global object gcls_IOError +# global object gs_FutureWarning +# global object gcls_FutureWarning +# global object gs_ZeroDivisionError +# global object gcls_ZeroDivisionError +# global object gs_EOFError +# global object gcls_EOFError +# global object gs_TabError +# global object gcls_TabError +# global object gs_UnicodeEncodeError +# global object gcls_UnicodeEncodeError +# global object gs_UnboundLocalError +# global object gcls_UnboundLocalError +# global object gs___name__ +# global object gs_ReferenceError +# global object gcls_ReferenceError +# global object gs_AssertionError +# global object gcls_AssertionError +# global object gs_UnicodeDecodeError +# global object gcls_UnicodeDecodeError +# global object gs_TypeError +# global object gcls_TypeError +# global object gs_IndexError +# global object gcls_IndexError +# global object gs_RuntimeWarning +# global object gcls_RuntimeWarning +# global object gs_KeyboardInterrupt +# global object gcls_KeyboardInterrupt +# global object gs_UserWarning +# global object gcls_UserWarning +# global object gs_SyntaxWarning +# global object gcls_SyntaxWarning +# global object gs_NotImplementedError +# global object gcls_NotImplementedError +# global object gs_SystemError +# global object gcls_SystemError +# global object gs_OverflowError +# global object gcls_OverflowError +# global object gs_WindowsError +# global object gcls_WindowsError +# global object gs___init__ +# global object gfunc_UnicodeDecodeError___init__ +# global object gs___str__ +# global object gfunc_UnicodeDecodeError___str__ +# global object gfunc_UnicodeEncodeError___init__ +# global object gfunc_UnicodeEncodeError___str__ +# global object gfunc_SyntaxError___init__ +# global object gfunc_SyntaxError___str__ +# global object gs_filename +# global object gs_lineno +# global object gs_msg +# global object gs__emptystr_ +# global object gs_offset +# global object gs_print_file_and_line +# global object gs_text +# global object gfunc_EnvironmentError___init__ +# global object gfunc_EnvironmentError___str__ +# global object gfunc_SystemExit___init__ +# global object gfunc_KeyError___str__ +# global object gfunc_UnicodeTranslateError___init__ +# global object gfunc_UnicodeTranslateError___str__ +# global object gs___getitem__ +# global object gfunc_Exception___getitem__ +# global object gfunc_Exception___init__ +# global object gfunc_Exception___str__ + ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__getitem__' ## firstlineno 94 ##SECTION## def __getitem__(space, __args__): funcname = "__getitem__" signature = ['self', 'idx'], None, None - def_w = [] - w_self, w_idx = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_idx = __args__.parse(funcname, signature, defaults_w) return fastf_Exception___getitem__(space, w_self, w_idx) f_Exception___getitem__ = __getitem__ -del __getitem__ def __getitem__(space, w_self, w_idx): @@ -125,22 +246,20 @@ return w_4 fastf_Exception___getitem__ = __getitem__ -del __getitem__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 98 ##SECTION## def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_Exception___init__(space, w_self, w_args) f_Exception___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -158,10 +277,9 @@ return w_3 fastf_Exception___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 102 ##SECTION## @@ -173,12 +291,11 @@ def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_Exception___str__(space, w_self) f_Exception___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -227,10 +344,9 @@ return w_5 fastf_Exception___str__ = __str__ -del __str__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 131 ##SECTION## @@ -242,12 +358,11 @@ def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_UnicodeTranslateError___init__(space, w_self, w_args) f_UnicodeTranslateError___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -286,10 +401,9 @@ return w_6 fastf_UnicodeTranslateError___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 141 ##SECTION## @@ -310,12 +424,11 @@ def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_UnicodeTranslateError___str__(space, w_self) f_UnicodeTranslateError___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -350,22 +463,20 @@ return w_18 fastf_UnicodeTranslateError___str__ = __str__ -del __str__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 159 ##SECTION## def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_KeyError___str__(space, w_self) f_KeyError___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -414,22 +525,20 @@ return w_5 fastf_KeyError___str__ = __str__ -del __str__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 185 ##SECTION## def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_EnvironmentError___init__(space, w_self, w_args) f_EnvironmentError___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -506,10 +615,9 @@ return w_18 fastf_EnvironmentError___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 199 ##SECTION## @@ -523,12 +631,11 @@ def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_EnvironmentError___str__(space, w_self) f_EnvironmentError___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -560,10 +667,9 @@ return w_15 fastf_EnvironmentError___str__ = __str__ -del __str__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 219 ##SECTION## @@ -573,12 +679,11 @@ def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_UnicodeEncodeError___init__(space, w_self, w_args) f_UnicodeEncodeError___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -619,10 +724,9 @@ return w_6 fastf_UnicodeEncodeError___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 230 ##SECTION## @@ -633,12 +737,11 @@ def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_UnicodeEncodeError___str__(space, w_self) f_UnicodeEncodeError___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -676,22 +779,20 @@ return w_21 fastf_UnicodeEncodeError___str__ = __str__ -del __str__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 270 ##SECTION## def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_SyntaxError___init__(space, w_self, w_args) f_SyntaxError___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -752,22 +853,20 @@ return w_10 fastf_SyntaxError___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 282 ##SECTION## def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_SyntaxError___str__(space, w_self) f_SyntaxError___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -789,10 +888,9 @@ return w_6 fastf_SyntaxError___str__ = __str__ -del __str__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 296 ##SECTION## @@ -802,12 +900,11 @@ def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_SystemExit___init__(space, w_self, w_args) f_SystemExit___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -873,22 +970,20 @@ return w_13 fastf_SystemExit___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__init__' ## firstlineno 331 ##SECTION## def __init__(space, __args__): funcname = "__init__" signature = ['self'], 'args', None - def_w = [] - w_self, w_args = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, w_args = __args__.parse(funcname, signature, defaults_w) return fastf_UnicodeDecodeError___init__(space, w_self, w_args) f_UnicodeDecodeError___init__ = __init__ -del __init__ def __init__(space, w_self, w_args): @@ -929,22 +1024,20 @@ return w_6 fastf_UnicodeDecodeError___init__ = __init__ -del __init__ ##SECTION## -## filename '/home/tinuviel/pypy/pypy/lib/_exceptions.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' ## function '__str__' ## firstlineno 342 ##SECTION## def __str__(space, __args__): funcname = "__str__" signature = ['self'], None, None - def_w = [] - w_self, = __args__.parse(funcname, signature, def_w) + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) return fastf_UnicodeDecodeError___str__(space, w_self) f_UnicodeDecodeError___str__ = __str__ -del __str__ def __str__(space, w_self): @@ -982,192 +1075,24 @@ return w_21 fastf_UnicodeDecodeError___str__ = __str__ -del __str__ - -##SECTION## -## filename 'geninterplevel.py' -## function 'test_exceptions' -## firstlineno 1306 -##SECTION## -# global declarations -# global object gfunc_test_exceptions -# global object gbltinmethod_keys -# global object g47dict -# global object gs_keys - -def test_exceptions(space, __args__): - """ enumerate all exceptions """ - - funcname = "test_exceptions" - signature = [], None, None - def_w = [] - __args__.parse(funcname, signature, def_w) - return fastf_test_exceptions(space) - -f_test_exceptions = test_exceptions -del test_exceptions - -def test_exceptions(space): - """ enumerate all exceptions """ - - w_0=w_1=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.call_function(gbltinmethod_keys, ) - w_1 = w_0 - goto = 2 - - if goto == 2: - return w_1 - -fastf_test_exceptions = test_exceptions -del test_exceptions - -# global declarations -# global object gs_MemoryError -# global object gcls_MemoryError -# global object gcls_StandardError -# global object gcls_Exception -# global object gs___module__ -# global object gs_exceptions -# global object gs___doc__ -# global object gs_Exception -# global object gs_StandardError -# global object gs_ImportError -# global object gcls_ImportError -# global object gs_RuntimeError -# global object gcls_RuntimeError -# global object gs_UnicodeTranslateError -# global object gcls_UnicodeTranslateError -# global object gcls_UnicodeError -# global object gcls_ValueError -# global object gs_ValueError -# global object gs_UnicodeError -# global object gs_KeyError -# global object gcls_KeyError -# global object gcls_LookupError -# global object gs_LookupError -# global object gs_TaskletExit -# global object gcls_TaskletExit -# global object gcls_SystemExit -# global object gs_SystemExit -# global object gs_StopIteration -# global object gcls_StopIteration -# global object gs_PendingDeprecationWarning -# global object gcls_PendingDeprecationWarning -# global object gcls_Warning -# global object gs_Warning -# global object gs_EnvironmentError -# global object gcls_EnvironmentError -# global object gs_OSError -# global object gcls_OSError -# global object gs_DeprecationWarning -# global object gcls_DeprecationWarning -# global object gs_FloatingPointError -# global object gcls_FloatingPointError -# global object gcls_ArithmeticError -# global object gs_ArithmeticError -# global object gs_AttributeError -# global object gcls_AttributeError -# global object gs_IndentationError -# global object gcls_IndentationError -# global object gcls_SyntaxError -# global object gs_SyntaxError -# global object gs_NameError -# global object gcls_NameError -# global object gs_OverflowWarning -# global object gcls_OverflowWarning -# global object gs_IOError -# global object gcls_IOError -# global object gs_FutureWarning -# global object gcls_FutureWarning -# global object gs_ZeroDivisionError -# global object gcls_ZeroDivisionError -# global object gs_EOFError -# global object gcls_EOFError -# global object gs_TabError -# global object gcls_TabError -# global object gs_UnicodeEncodeError -# global object gcls_UnicodeEncodeError -# global object gs_UnboundLocalError -# global object gcls_UnboundLocalError -# global object gs___name__ -# global object gs_ReferenceError -# global object gcls_ReferenceError -# global object gs_AssertionError -# global object gcls_AssertionError -# global object gs_UnicodeDecodeError -# global object gcls_UnicodeDecodeError -# global object gs_TypeError -# global object gcls_TypeError -# global object gs_IndexError -# global object gcls_IndexError -# global object gs_RuntimeWarning -# global object gcls_RuntimeWarning -# global object gs_KeyboardInterrupt -# global object gcls_KeyboardInterrupt -# global object gs_UserWarning -# global object gcls_UserWarning -# global object gs_SyntaxWarning -# global object gcls_SyntaxWarning -# global object gs_NotImplementedError -# global object gcls_NotImplementedError -# global object gs_SystemError -# global object gcls_SystemError -# global object gs_OverflowError -# global object gcls_OverflowError -# global object gs_WindowsError -# global object gcls_WindowsError -# global object gs___init__ -# global object gfunc_UnicodeDecodeError___init__ -# global object gs___str__ -# global object gfunc_UnicodeDecodeError___str__ -# global object gfunc_UnicodeEncodeError___init__ -# global object gfunc_UnicodeEncodeError___str__ -# global object gfunc_SyntaxError___init__ -# global object gfunc_SyntaxError___str__ -# global object gs_filename -# global object gs_lineno -# global object gs_msg -# global object gs__emptystr_ -# global object gs_offset -# global object gs_print_file_and_line -# global object gs_text -# global object gfunc_EnvironmentError___init__ -# global object gfunc_EnvironmentError___str__ -# global object gfunc_SystemExit___init__ -# global object gfunc_KeyError___str__ -# global object gfunc_UnicodeTranslateError___init__ -# global object gfunc_UnicodeTranslateError___str__ -# global object gs___getitem__ -# global object gfunc_Exception___getitem__ -# global object gfunc_Exception___init__ -# global object gfunc_Exception___str__ ##SECTION## #************************************************************* -def inittest_exceptions_1(space): +def initexceptions(space): """NOT_RPYTHON""" class m: pass # fake module m.__dict__ = globals() # make sure that this function is run only once: - m.inittest_exceptions_1 = lambda *ign:True + m.initexceptions = lambda *ign:True - from pypy.interpreter.gateway import interp2app - m.gfunc_test_exceptions = space.wrap(interp2app(f_test_exceptions)) - m.__doc__ = space.wrap(m.__doc__) m.g47dict = space.newdict([]) - m.gs_keys = space.wrap('keys') - m.gbltinmethod_keys = space.getattr(g47dict, gs_keys) + m.__doc__ = space.wrap(m.__doc__) m.gs_MemoryError = space.wrap('MemoryError') _dic = space.newdict([]) m.gs___module__ = space.wrap('__module__') - m.gs_exceptions = space.wrap('exceptions') - space.setitem(_dic, gs___module__, gs_exceptions) + m.gs__exceptions = space.wrap('_exceptions') + space.setitem(_dic, gs___module__, gs__exceptions) m.gs___doc__ = space.wrap('__doc__') _doc = space.wrap("""Common base class for all exceptions.""") space.setitem(_dic, gs___doc__, _doc) @@ -1176,7 +1101,7 @@ _args = space.newtuple([gs_Exception, _bases, _dic]) m.gcls_Exception = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for all standard Python exceptions.""") space.setitem(_dic, gs___doc__, _doc) m.gs_StandardError = space.wrap('StandardError') @@ -1184,7 +1109,7 @@ _args = space.newtuple([gs_StandardError, _bases, _dic]) m.gcls_StandardError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Out of memory.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1193,7 +1118,7 @@ space.setitem(g47dict, gs_MemoryError, gcls_MemoryError) m.gs_ImportError = space.wrap('ImportError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Import can't find module, or can't find name in module.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1202,7 +1127,7 @@ space.setitem(g47dict, gs_ImportError, gcls_ImportError) m.gs_RuntimeError = space.wrap('RuntimeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Unspecified run-time error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1211,7 +1136,7 @@ space.setitem(g47dict, gs_RuntimeError, gcls_RuntimeError) m.gs_UnicodeTranslateError = space.wrap('UnicodeTranslateError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Inappropriate argument value (of correct type).""") space.setitem(_dic, gs___doc__, _doc) m.gs_ValueError = space.wrap('ValueError') @@ -1219,7 +1144,7 @@ _args = space.newtuple([gs_ValueError, _bases, _dic]) m.gcls_ValueError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Unicode related error.""") space.setitem(_dic, gs___doc__, _doc) m.gs_UnicodeError = space.wrap('UnicodeError') @@ -1227,7 +1152,7 @@ _args = space.newtuple([gs_UnicodeError, _bases, _dic]) m.gcls_UnicodeError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Unicode translation error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_UnicodeError]) @@ -1236,7 +1161,7 @@ space.setitem(g47dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) m.gs_KeyError = space.wrap('KeyError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for lookup errors.""") space.setitem(_dic, gs___doc__, _doc) m.gs_LookupError = space.wrap('LookupError') @@ -1244,7 +1169,7 @@ _args = space.newtuple([gs_LookupError, _bases, _dic]) m.gcls_LookupError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Mapping key not found.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_LookupError]) @@ -1253,7 +1178,7 @@ space.setitem(g47dict, gs_KeyError, gcls_KeyError) m.gs_TaskletExit = space.wrap('TaskletExit') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Request to exit from the interpreter.""") space.setitem(_dic, gs___doc__, _doc) m.gs_SystemExit = space.wrap('SystemExit') @@ -1261,7 +1186,7 @@ _args = space.newtuple([gs_SystemExit, _bases, _dic]) m.gcls_SystemExit = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Request to exit from a tasklet.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_SystemExit]) @@ -1270,7 +1195,7 @@ space.setitem(g47dict, gs_TaskletExit, gcls_TaskletExit) m.gs_StopIteration = space.wrap('StopIteration') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Signal the end from iterator.next().""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Exception]) @@ -1279,7 +1204,7 @@ space.setitem(g47dict, gs_StopIteration, gcls_StopIteration) m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warning categories.""") space.setitem(_dic, gs___doc__, _doc) m.gs_Warning = space.wrap('Warning') @@ -1287,7 +1212,7 @@ _args = space.newtuple([gs_Warning, _bases, _dic]) m.gcls_Warning = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings about features which will be deprecated in the future.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1296,7 +1221,7 @@ space.setitem(g47dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) m.gs_EnvironmentError = space.wrap('EnvironmentError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for I/O related errors.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1306,7 +1231,7 @@ space.setitem(g47dict, gs_LookupError, gcls_LookupError) m.gs_OSError = space.wrap('OSError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""OS system call failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_EnvironmentError]) @@ -1315,7 +1240,7 @@ space.setitem(g47dict, gs_OSError, gcls_OSError) m.gs_DeprecationWarning = space.wrap('DeprecationWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings about deprecated features.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1325,7 +1250,7 @@ space.setitem(g47dict, gs_UnicodeError, gcls_UnicodeError) m.gs_FloatingPointError = space.wrap('FloatingPointError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for arithmetic errors.""") space.setitem(_dic, gs___doc__, _doc) m.gs_ArithmeticError = space.wrap('ArithmeticError') @@ -1333,7 +1258,7 @@ _args = space.newtuple([gs_ArithmeticError, _bases, _dic]) m.gcls_ArithmeticError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Floating point operation failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_ArithmeticError]) @@ -1342,7 +1267,7 @@ space.setitem(g47dict, gs_FloatingPointError, gcls_FloatingPointError) m.gs_AttributeError = space.wrap('AttributeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Attribute not found.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1351,7 +1276,7 @@ space.setitem(g47dict, gs_AttributeError, gcls_AttributeError) m.gs_IndentationError = space.wrap('IndentationError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Invalid syntax.""") space.setitem(_dic, gs___doc__, _doc) m.gs_SyntaxError = space.wrap('SyntaxError') @@ -1359,7 +1284,7 @@ _args = space.newtuple([gs_SyntaxError, _bases, _dic]) m.gcls_SyntaxError = space.call(space.w_type, _args) _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Improper indentation.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_SyntaxError]) @@ -1368,7 +1293,7 @@ space.setitem(g47dict, gs_IndentationError, gcls_IndentationError) m.gs_NameError = space.wrap('NameError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Name not found globally.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1377,7 +1302,7 @@ space.setitem(g47dict, gs_NameError, gcls_NameError) m.gs_OverflowWarning = space.wrap('OverflowWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings about numeric overflow.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1386,7 +1311,7 @@ space.setitem(g47dict, gs_OverflowWarning, gcls_OverflowWarning) m.gs_IOError = space.wrap('IOError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""I/O operation failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_EnvironmentError]) @@ -1396,7 +1321,7 @@ space.setitem(g47dict, gs_ValueError, gcls_ValueError) m.gs_FutureWarning = space.wrap('FutureWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings about constructs that will change semantically in the future.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1405,7 +1330,7 @@ space.setitem(g47dict, gs_FutureWarning, gcls_FutureWarning) m.gs_ZeroDivisionError = space.wrap('ZeroDivisionError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Second argument to a division or modulo operation was zero.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_ArithmeticError]) @@ -1416,7 +1341,7 @@ space.setitem(g47dict, gs_Exception, gcls_Exception) m.gs_EOFError = space.wrap('EOFError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Read beyond end of file.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1426,7 +1351,7 @@ space.setitem(g47dict, gs_StandardError, gcls_StandardError) m.gs_TabError = space.wrap('TabError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Improper mixture of spaces and tabs.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_IndentationError]) @@ -1436,7 +1361,7 @@ space.setitem(g47dict, gs_SyntaxError, gcls_SyntaxError) m.gs_UnicodeEncodeError = space.wrap('UnicodeEncodeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Unicode encoding error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_UnicodeError]) @@ -1445,7 +1370,7 @@ space.setitem(g47dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) m.gs_UnboundLocalError = space.wrap('UnboundLocalError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Local name referenced but not bound to a value.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_NameError]) @@ -1453,10 +1378,10 @@ m.gcls_UnboundLocalError = space.call(space.w_type, _args) space.setitem(g47dict, gs_UnboundLocalError, gcls_UnboundLocalError) m.gs___name__ = space.wrap('__name__') - space.setitem(g47dict, gs___name__, gs_exceptions) + space.setitem(g47dict, gs___name__, gs__exceptions) m.gs_ReferenceError = space.wrap('ReferenceError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Weak ref proxy used after referent went away.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1465,7 +1390,7 @@ space.setitem(g47dict, gs_ReferenceError, gcls_ReferenceError) m.gs_AssertionError = space.wrap('AssertionError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Assertion failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1474,7 +1399,7 @@ space.setitem(g47dict, gs_AssertionError, gcls_AssertionError) m.gs_UnicodeDecodeError = space.wrap('UnicodeDecodeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Unicode decoding error.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_UnicodeError]) @@ -1483,7 +1408,7 @@ space.setitem(g47dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) m.gs_TypeError = space.wrap('TypeError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Inappropriate argument type.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1492,7 +1417,7 @@ space.setitem(g47dict, gs_TypeError, gcls_TypeError) m.gs_IndexError = space.wrap('IndexError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Sequence index out of range.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_LookupError]) @@ -1501,7 +1426,7 @@ space.setitem(g47dict, gs_IndexError, gcls_IndexError) m.gs_RuntimeWarning = space.wrap('RuntimeWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings about dubious runtime behavior.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1510,7 +1435,7 @@ space.setitem(g47dict, gs_RuntimeWarning, gcls_RuntimeWarning) m.gs_KeyboardInterrupt = space.wrap('KeyboardInterrupt') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Program interrupted by user.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_StandardError]) @@ -1519,7 +1444,7 @@ space.setitem(g47dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) m.gs_UserWarning = space.wrap('UserWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings generated by user code.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1528,7 +1453,7 @@ space.setitem(g47dict, gs_UserWarning, gcls_UserWarning) m.gs_SyntaxWarning = space.wrap('SyntaxWarning') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Base class for warnings about dubious syntax.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_Warning]) @@ -1540,7 +1465,7 @@ space.setitem(g47dict, gs_Warning, gcls_Warning) m.gs_NotImplementedError = space.wrap('NotImplementedError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Method or function hasn't been implemented yet.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_RuntimeError]) @@ -1549,7 +1474,7 @@ space.setitem(g47dict, gs_NotImplementedError, gcls_NotImplementedError) m.gs_SystemError = space.wrap('SystemError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Internal error in the Python interpreter. Please report this to the Python maintainer, along with the traceback, @@ -1561,7 +1486,7 @@ space.setitem(g47dict, gs_SystemError, gcls_SystemError) m.gs_OverflowError = space.wrap('OverflowError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""Result too large to be represented.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_ArithmeticError]) @@ -1570,7 +1495,7 @@ space.setitem(g47dict, gs_OverflowError, gcls_OverflowError) m.gs_WindowsError = space.wrap('WindowsError') _dic = space.newdict([]) - space.setitem(_dic, gs___module__, gs_exceptions) + space.setitem(_dic, gs___module__, gs__exceptions) _doc = space.wrap("""MS-Windows OS system call failed.""") space.setitem(_dic, gs___doc__, _doc) _bases = space.newtuple([gcls_OSError]) @@ -1578,6 +1503,7 @@ m.gcls_WindowsError = space.call(space.w_type, _args) space.setitem(g47dict, gs_WindowsError, gcls_WindowsError) m.gs___init__ = space.wrap('__init__') + from pypy.interpreter.gateway import interp2app m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) space.setattr(gcls_UnicodeDecodeError, gs___init__, gfunc_UnicodeDecodeError___init__) m.gs___str__ = space.wrap('__str__') @@ -1626,6 +1552,9 @@ m.gs_args = space.wrap('args') m.gi_0 = space.newint(0) m.gi_1 = space.newint(1) + del m.__str__ + del m.__init__ + del m.__getitem__ m.gs_start = space.wrap('start') m.gs_start_ = space.wrap('start=') m.gs_reason = space.wrap('reason') @@ -1650,17 +1579,5 @@ m.gs_encoding = space.wrap('encoding') m.gs_encoding_ = space.wrap('encoding=') m.gi_5 = space.newint(5) - -# entry point: test_exceptions, gfunc_test_exceptions -if __name__ == "__main__": - from pypy.objspace.std import StdObjSpace - from pypy.objspace.std.default import UnwrapError - space = StdObjSpace() - inittest_exceptions_1(space) - ret = space.call(gfunc_test_exceptions, space.newtuple([])) - try: - print space.unwrap(ret) - except UnwrapError: - print "cannot unwrap, here the wrapped result:" - print ret + return g47dict Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Thu Feb 10 13:56:04 2005 @@ -102,20 +102,27 @@ bases = [space.w_object] res = W_TypeObject(space, name, bases, dic) return res - w_dic = self.newdict([]) try: # note that we hide the real call method by an instance variable! self.call = call - ex.inittest_exceptions_1(self) - for name, w_obj in ex.__dict__.items(): - if name.startswith("gcls_"): - excname = name[5:] - setattr(self, "w_"+excname, w_obj) # into space - for_builtins[excname] = w_obj # into builtins - self.setitem(w_dic, self.wrap(excname), w_obj) # into exc - self.setitem(w_dic, self.wrap("__doc__"), ex.__doc__) + w_dic = ex.initexceptions(self) + + self.w_IndexError = self.getitem(w_dic, self.wrap("IndexError")) + self.w_StopIteration = self.getitem(w_dic, self.wrap("StopIteration")) finally: - del self.call # revert to the class' method + del self.call # revert + + names_w = self.unpackiterable(self.call_function(self.getattr(w_dic, self.wrap("keys")))) + + for w_name in names_w: + name = self.str_w(w_name) + if not name.startswith('__'): + excname = name + w_exc = self.getitem(w_dic, w_name) + setattr(self, "w_"+excname, w_exc) + + for_builtins[excname] = w_exc + # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module Added: pypy/dist/pypy/translator/tool/tointerplevel.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/tool/tointerplevel.py Thu Feb 10 13:56:04 2005 @@ -0,0 +1,73 @@ +import autopath +import sys +import optparse +import os +import new + +from pypy.translator.translator import Translator +from pypy.translator.geninterplevel import GenRpy + +def main(): + opt_parser = optparse.OptionParser(usage="usage: %prog [options] module-file obj-name...") + opt_parser.add_option("--import-as", dest="as", type="string", + help="import module-file with this name") + opt_parser.add_option("-o","--out",dest="output",type="string", help="output file") + opt_parser.add_option("--modname",dest="modname", type="string", help="modname to be used by GenRpy") + + options, args = opt_parser.parse_args() + + if len(args) < 2: + opt_parser.error("missing module-file and at least one obj-name") + + modfile = os.path.abspath(args[0]) + + name = os.path.splitext(os.path.basename(modfile))[0] + + as = options.as or name + + mod = new.module(as) + execfile(modfile, mod.__dict__) + + del mod.__dict__['__builtins__'] + + modname = options.modname or name + + objs = [] + + for objname in args[1:]: + try: + objs.append(getattr(mod, objname)) + except AttributeError, e: + raise Exception,"module has no object '%s'" % name + + if len(objs) == 1: + entrypoint = objs[0] + else: + entrypoint = tuple(objs) + + t = Translator(None, verbose=False, simplifying=True) + gen = GenRpy(t, entrypoint, modname) + def gen_trailer(info, indent): + print >>gen.f, indent + "return %s" % gen.nameof(entrypoint) + print >>gen.f + + gen.use_fast_call = True + gen.moddict = mod.__dict__ # xxx control this + gen.gen_trailer = gen_trailer + + output = options.output or modname + "interp.py" + + print "generating %s..." % output + + gen.gen_source(output) + + + +if __name__ == "__main__": + main() + + + + + + From hpk at codespeak.net Thu Feb 10 14:41:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 14:41:50 +0100 (MET) Subject: [pypy-svn] r9044 - pypy/dist/pypy/interpreter Message-ID: <20050210134150.9465A27C06@code1.codespeak.net> Author: hpk Date: Thu Feb 10 14:41:50 2005 New Revision: 9044 Modified: pypy/dist/pypy/interpreter/baseobjspace.py Log: a new highly experimental approach for executing code at application level, which may help to subtitute gateway.app2interp at some point. current example usage: w_result = space.exec_with("""if 1: x = 6*x __return__ = x """, x=space.wrap(7)) so you provide explicit name-bindings and there is no function invocation/argument parsing involved for such internal interp/app interaction. Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Thu Feb 10 14:41:50 2005 @@ -276,6 +276,33 @@ raise TypeError, 'space.exec_(): expected a string, code or PyCode object' return statement.exec_code(self, w_globals, w_locals) + def exec_with(self, source, **kwargs_w): + """ execute given source at applevel with given name=wrapped value + parameters as its starting scope. Note: EXPERIMENTAL. + """ + space = self + pypyco = getpypycode(space, source) + + # XXX use the fastscope version of Frames? + w_glob = space.newdict([]) + for name, w_value in kwargs_w.items(): + space.setitem(w_glob, space.wrap(name), w_value) + pypyco.exec_code(self, w_glob, w_glob) + w_result = space.getitem(w_glob, space.wrap('__return__')) + return w_result + +pypycodecache = {} +def getpypycode(space, source): + try: + return pypycodecache[(space, source)] + except KeyError: + # NOT_RPYTHON + # XXX hack a bit to allow for 'return' statements? + from pypy.interpreter.pycode import PyCode + co = compile(source, '', 'exec') + pypyco = PyCode(space)._from_code(co) + pypycodecache[(space, co)] = pypyco + return pypyco ## Table describing the regular part of the interface of object spaces, ## namely all methods which only take w_ arguments and return a w_ result From hpk at codespeak.net Thu Feb 10 15:38:56 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 15:38:56 +0100 (MET) Subject: [pypy-svn] r9045 - in pypy/dist/pypy/interpreter: . test Message-ID: <20050210143856.56CCB27BF6@code1.codespeak.net> Author: hpk Date: Thu Feb 10 15:38:56 2005 New Revision: 9045 Added: pypy/dist/pypy/interpreter/test/test_appinterp.py Modified: pypy/dist/pypy/interpreter/baseobjspace.py Log: improved exec_with() hack that goes directly at fast scope and allows for "return" statements within the applevel code definition. Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Thu Feb 10 15:38:56 2005 @@ -277,32 +277,38 @@ return statement.exec_code(self, w_globals, w_locals) def exec_with(self, source, **kwargs_w): - """ execute given source at applevel with given name=wrapped value - parameters as its starting scope. Note: EXPERIMENTAL. + """ return value from executing given source at applevel with + given name=wrapped value parameters as its starting scope. + Note: EXPERIMENTAL. """ space = self - pypyco = getpypycode(space, source) - - # XXX use the fastscope version of Frames? + pypyco,name2index = pypycodecache.getorbuild((space,source), + buildpypycode, kwargs_w) w_glob = space.newdict([]) + frame = pypyco.create_frame(space, w_glob) for name, w_value in kwargs_w.items(): - space.setitem(w_glob, space.wrap(name), w_value) - pypyco.exec_code(self, w_glob, w_glob) - w_result = space.getitem(w_glob, space.wrap('__return__')) - return w_result - -pypycodecache = {} -def getpypycode(space, source): - try: - return pypycodecache[(space, source)] - except KeyError: - # NOT_RPYTHON - # XXX hack a bit to allow for 'return' statements? - from pypy.interpreter.pycode import PyCode - co = compile(source, '', 'exec') - pypyco = PyCode(space)._from_code(co) - pypycodecache[(space, co)] = pypyco - return pypyco + i = name2index[name] + frame.fastlocals_w[i] = w_value + return frame.run() + +pypycodecache = Cache() +def buildpypycode((space, source), kwargs_w): + """ NOT_RPYTHON """ + # XXX will change once we have our own compiler + from pypy.interpreter.pycode import PyCode + from pypy.tool.pytestsupport import py # aehem + names = kwargs_w.keys() + source = py.code.Source(source) + source = source.putaround("def anon(%s):" % ", ".join(kwargs_w.keys())) + d = {} + exec source.compile() in d + newco = d['anon'].func_code + pypyco = PyCode(space)._from_code(newco) + varnames = list(pypyco.getvarnames()) + name2index = {} + for name, w_value in kwargs_w.items(): + name2index[name] = varnames.index(name) + return pypyco, name2index ## Table describing the regular part of the interface of object spaces, ## namely all methods which only take w_ arguments and return a w_ result Added: pypy/dist/pypy/interpreter/test/test_appinterp.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/interpreter/test/test_appinterp.py Thu Feb 10 15:38:56 2005 @@ -0,0 +1,24 @@ + +import py + +def test_execwith_novars(space): + val = space.exec_with(""" + return 42 + """) + assert space.eq_w(val, space.wrap(42)) + +def test_execwith_withvars(space): + val = space.exec_with(""" + y = 6 * x + return y + """, x = space.wrap(7)) + assert space.eq_w(val, space.wrap(42)) + + +def test_execwith_compile_error(space): + excinfo = py.test.raises(SyntaxError, space.exec_with, """ + y y + """) + assert str(excinfo).find('y y') != -1 + + From arigo at codespeak.net Thu Feb 10 15:52:23 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 10 Feb 2005 15:52:23 +0100 (MET) Subject: [pypy-svn] r9046 - pypy/branch/dist-simpler-multimethods Message-ID: <20050210145223.6BB2927BE8@code1.codespeak.net> Author: arigo Date: Thu Feb 10 15:52:23 2005 New Revision: 9046 Removed: pypy/branch/dist-simpler-multimethods/ Log: Remove merged branch. From pedronis at codespeak.net Thu Feb 10 16:18:38 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 16:18:38 +0100 (MET) Subject: [pypy-svn] r9047 - pypy/dist/pypy/objspace/flow Message-ID: <20050210151838.722EC27BF6@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 16:18:38 2005 New Revision: 9047 Modified: pypy/dist/pypy/objspace/flow/objspace.py Log: let have control over builtins can raise exceptions (I'm not sure whether we could simply change the default) (needed for geninterplevel of _classobj) Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Thu Feb 10 16:18:38 2005 @@ -29,6 +29,8 @@ full_exceptions = False resolve_constants = True # used by the appflowspace + + builtins_can_raise_exceptions = False def initialize(self): import __builtin__ @@ -290,7 +292,8 @@ c = w_callable.value if isinstance(c, (types.BuiltinFunctionType, types.BuiltinMethodType)): - exceptions = None + if not self.builtins_can_raise_exceptions: + exceptions = None elif (isinstance(c, (type, types.ClassType)) and c.__module__ in ['__builtin__', 'exceptions']): exceptions = None From pedronis at codespeak.net Thu Feb 10 16:46:06 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 16:46:06 +0100 (MET) Subject: [pypy-svn] r9048 - in pypy/dist/pypy/translator: . tool Message-ID: <20050210154606.93FF427C10@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 16:46:06 2005 New Revision: 9048 Modified: pypy/dist/pypy/translator/geninterplevel.py pypy/dist/pypy/translator/tool/tointerplevel.py Log: - enable to exceptions raised by builtins support (needed by _classobj.py) - be lazy accessing sys.* __bultin__.* stuff - allow __new__ to be staticmethod-ified by the type ctr - don't discard __repr__ in geninterplevel case - NotImplemented support Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 10 16:46:06 2005 @@ -332,6 +332,9 @@ else: return self.uniquelocalname('%s_%d' % (basename, n), seennames) + def nameof_NotImplementedType(self, value): + return "space.w_NotImplemented" + def nameof_object(self, value): if type(value) is not object: # try to just wrap it? @@ -533,11 +536,18 @@ break else: raise Exception, '%r not found in any built-in module' % (func,) - name = self.uniquename('gbltin_' + func.__name__) if modname == '__builtin__': - self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( - name, self.nameof(func.__name__))) + #self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( + # name, self.nameof(func.__name__))) + # be lazy + return "(space.getattr(space.w_builtin, %s))" % self.nameof(func.__name__) + elif modname == 'sys': + # be lazy + return "(space.getattr(space.w_sys, %s))" % self.nameof(func.__name__) else: + print ("WARNING: accessing builtin modules different from sys or __builtin__" + " is likely producing non-sense") + name = self.uniquename('gbltin_' + func.__name__) self.initcode.append('m.%s = space.getattr(%s, %s)' % ( name, self.nameof(module), self.nameof(func.__name__))) else: @@ -585,7 +595,7 @@ for key, value in content: if key.startswith('__'): if key in ['__module__', '__doc__', '__dict__', - '__weakref__', '__repr__', '__metaclass__', '__slots__']: + '__weakref__', '__metaclass__', '__slots__','__new__']: continue # redirect value through class interface, in order to @@ -606,7 +616,7 @@ self.initcode.appendnew('_dic = space.newdict([])') for key, value in cls.__dict__.items(): if key.startswith('__'): - if key in ['__module__', '__metaclass__', '__slots__']: + if key in ['__module__', '__metaclass__', '__slots__','__new__']: keyname = self.nameof(key) valname = self.nameof(value) self.initcode.appendnew("space.setitem(_dic, %s, %s)" % ( @@ -1118,6 +1128,7 @@ # -*- coding: LATIN-1 -*- from pypy.interpreter.error import OperationError +from pypy.interpreter.argument import Arguments ''' RPY_SEP = "#*************************************************************" Modified: pypy/dist/pypy/translator/tool/tointerplevel.py ============================================================================== --- pypy/dist/pypy/translator/tool/tointerplevel.py (original) +++ pypy/dist/pypy/translator/tool/tointerplevel.py Thu Feb 10 16:46:06 2005 @@ -4,9 +4,13 @@ import os import new +from pypy.objspace.flow.objspace import FlowObjSpace from pypy.translator.translator import Translator from pypy.translator.geninterplevel import GenRpy +# change default +FlowObjSpace.bultins_can_raise_exceptions = True + def main(): opt_parser = optparse.OptionParser(usage="usage: %prog [options] module-file obj-name...") opt_parser.add_option("--import-as", dest="as", type="string", From hpk at codespeak.net Thu Feb 10 16:54:13 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 16:54:13 +0100 (MET) Subject: [pypy-svn] r9049 - in pypy/dist/pypy/interpreter: . test Message-ID: <20050210155413.5842327C10@code1.codespeak.net> Author: hpk Date: Thu Feb 10 16:54:13 2005 New Revision: 9049 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/interpreter/test/test_appinterp.py Log: revised hack and name. it now works like this: space.appexec([w_value1, w_value2, ...], """ (value1, value2, ...): ... return ... """) so 'appexec' becomes what app2interp should have been from the beginning: a way for interp-level to quickly do some work at applevel. Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Thu Feb 10 16:54:13 2005 @@ -276,39 +276,34 @@ raise TypeError, 'space.exec_(): expected a string, code or PyCode object' return statement.exec_code(self, w_globals, w_locals) - def exec_with(self, source, **kwargs_w): + def appexec(self, posargs, source): """ return value from executing given source at applevel with given name=wrapped value parameters as its starting scope. Note: EXPERIMENTAL. """ space = self - pypyco,name2index = pypycodecache.getorbuild((space,source), - buildpypycode, kwargs_w) + pypyco = pypycodecache.getorbuild((space,source), buildpypycode, posargs) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) - for name, w_value in kwargs_w.items(): - i = name2index[name] - frame.fastlocals_w[i] = w_value + frame.setfastscope(posargs) return frame.run() pypycodecache = Cache() -def buildpypycode((space, source), kwargs_w): +def buildpypycode((space, source), posargs): """ NOT_RPYTHON """ # XXX will change once we have our own compiler from pypy.interpreter.pycode import PyCode from pypy.tool.pytestsupport import py # aehem - names = kwargs_w.keys() + argdecl, source = source.split(':', 1) + argdecl = argdecl.strip() + if not argdecl.startswith('(') or not argdecl.endswith(')'): + raise SyntaxError("incorrect exec_with header\n%s" % source) source = py.code.Source(source) - source = source.putaround("def anon(%s):" % ", ".join(kwargs_w.keys())) + source = source.putaround("def anon%s:" % argdecl) d = {} exec source.compile() in d newco = d['anon'].func_code - pypyco = PyCode(space)._from_code(newco) - varnames = list(pypyco.getvarnames()) - name2index = {} - for name, w_value in kwargs_w.items(): - name2index[name] = varnames.index(name) - return pypyco, name2index + return PyCode(space)._from_code(newco) ## Table describing the regular part of the interface of object spaces, ## namely all methods which only take w_ arguments and return a w_ result Modified: pypy/dist/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/dist/pypy/interpreter/test/test_appinterp.py Thu Feb 10 16:54:13 2005 @@ -2,21 +2,23 @@ import py def test_execwith_novars(space): - val = space.exec_with(""" - return 42 + val = space.appexec([], """ + (): + return 42 """) assert space.eq_w(val, space.wrap(42)) def test_execwith_withvars(space): - val = space.exec_with(""" + val = space.appexec([space.wrap(7)], """ + (x): y = 6 * x return y - """, x = space.wrap(7)) + """) assert space.eq_w(val, space.wrap(42)) - def test_execwith_compile_error(space): - excinfo = py.test.raises(SyntaxError, space.exec_with, """ + excinfo = py.test.raises(SyntaxError, space.appexec, [], """ + (): y y """) assert str(excinfo).find('y y') != -1 From pedronis at codespeak.net Thu Feb 10 17:01:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 17:01:54 +0100 (MET) Subject: [pypy-svn] r9050 - in pypy/dist/pypy: lib module Message-ID: <20050210160154.9401B27C10@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 17:01:54 2005 New Revision: 9050 Added: pypy/dist/pypy/module/classobjinterp.py (contents, props changed) Modified: pypy/dist/pypy/lib/_classobj.py Log: - slight change to _classobj to have it work both under CPython and app-level and in the geninterplevel-ed form (could use the globals identity itself as marker perhaps?) - purify function to be called when using the geninterplevel code to redo the removals that are lost because they are at global level - classobjinterp obtained from _classobj with: translator/tool/tointerplevel.py --modname=classobj --out module/classobjinterp.py lib/_classobj.py classobj instance purify Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 10 17:01:54 2005 @@ -100,6 +100,8 @@ return i += 1 +OLD_STYLE_CLASSES_IMPL = object() + class classobj(object): __slots__ = ('_name', '_bases', '__dict__') @@ -126,7 +128,12 @@ dic['__module__'] except KeyError: try: - g = sys._getframe(1).f_globals + i = 0 + while 1: + g = sys._getframe(i).f_globals + if not g.get('OLD_STYLE_CLASSES_IMPL',None) is OLD_STYLE_CLASSES_IMPL: + break + i += 1 except ValueError: pass else: @@ -557,5 +564,13 @@ # capture _class slot for usage and then hide them! instance_class_slot = instance._class del instance._class + +def purify(): # to use in geninterplevel case, because global side-effects are lost + del classobj._name + del classobj._bases + del classobj.__slots__ + del instance._class + del instance.__slots__ + del _compile, NiceCompile Added: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/module/classobjinterp.py Thu Feb 10 17:01:54 2005 @@ -0,0 +1,7635 @@ +#!/bin/env python +# -*- coding: LATIN-1 -*- + +from pypy.interpreter.error import OperationError +from pypy.interpreter.argument import Arguments + + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '_coerce' +## firstlineno 7 +##SECTION## +def _coerce(space, __args__): + funcname = "_coerce" + signature = ['left', 'right'], None, None + defaults_w = [] + w_left, w_right = __args__.parse(funcname, signature, defaults_w) + return fastf__coerce(space, w_left, w_right) + +f__coerce = _coerce + +def _coerce(space, w_left, w_right): + + w_0=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.coerce(w_left, w_right) + w_3 = w_0 + goto = 2 + + if goto == 2: + return w_3 + +fastf__coerce = _coerce + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'uid' +## firstlineno 18 +##SECTION## +# global declarations +# global object gi_0 +# global object glong_0xffffffffL +# global object gi_1 + +def uid(space, __args__): + funcname = "uid" + signature = ['o'], None, None + defaults_w = [] + w_o, = __args__.parse(funcname, signature, defaults_w) + return fastf_uid(space, w_o) + +f_uid = uid + +def uid(space, w_o): + + w_v=w_2=v3=w_v_2=w_4=w_5=w_v_1=w_v_3=w_v_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_v = space.id(w_o) + w_2 = space.lt(w_v, gi_0) + v3 = space.is_true(w_2) + if v3 == True: + w_v_1 = w_v + goto = 2 + else: + assert v3 == False + w_v_2 = w_v + goto = 3 + + if goto == 2: + w_v_3 = space.inplace_add(w_v_1, glong_0xffffffffL) + w_v_4 = space.inplace_add(w_v_3, gi_1) + w_v_2 = w_v_4 + goto = 3 + + if goto == 3: + w_4 = space.and_(w_v_2, glong_0xffffffffL) + w_5 = w_4 + goto = 4 + + if goto == 4: + return w_5 + +fastf_uid = uid + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'type_err' +## firstlineno 34 +##SECTION## +# global declaration +# global object gs_argument__s_must_be__s__not__s + +def type_err(space, __args__): + funcname = "type_err" + signature = ['arg', 'expected', 'v'], None, None + defaults_w = [] + w_arg, w_expected, w_v = __args__.parse(funcname, signature, defaults_w) + return fastf_type_err(space, w_arg, w_expected, w_v) + +f_type_err = type_err + +def type_err(space, w_arg, w_expected, w_v): + + w_0=w_2=w_3=w_6=w_7=w_8=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(space.w_type, w_v) + w_2 = space.getattr(w_0, gs___name__) + w_3 = space.newtuple([w_arg, w_expected, w_2]) + w_6 = space.mod(gs_argument__s_must_be__s__not__s, w_3) + w_7 = space.call_function(gcls_TypeError, w_6) + w_8 = w_7 + goto = 2 + + if goto == 2: + return w_8 + +fastf_type_err = type_err + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'set_name' +## firstlineno 37 +##SECTION## +# global declarations +# global object gs___name___must_be_a_string_object +# global object gdescriptor_classobj__name + +def set_name(space, __args__): + funcname = "set_name" + signature = ['cls', 'name'], None, None + defaults_w = [] + w_cls, w_name = __args__.parse(funcname, signature, defaults_w) + return fastf_set_name(space, w_cls, w_name) + +f_set_name = set_name + +def set_name(space, w_cls, w_name): + + w_0=v2=w_etype=w_evalue=w_cls_1=w_name_1=w_6=w_7=w_8=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_name, space.w_str) + v2 = space.is_true(w_0) + if v2 == True: + w_cls_1, w_name_1 = w_cls, w_name + goto = 2 + else: + assert v2 == False + (w_etype, w_evalue) = (gcls_TypeError, + gs___name___must_be_a_string_object) + goto = 3 + + if goto == 2: + w_6 = space.getattr(gdescriptor_classobj__name, gs___set__) + w_7 = space.call_function(w_6, w_cls_1, w_name_1) + w_8 = space.w_None + goto = 4 + + if goto == 3: + raise OperationError(w_etype, w_evalue) + + if goto == 4: + return w_8 + +fastf_set_name = set_name + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'set_bases' +## firstlineno 42 +##SECTION## +# global declarations +# global object gs___bases___must_be_a_tuple_object +# global object gcls_StopIteration +# global object gs___bases___items_must_be_classes +# global object gdescriptor_classobj__bases +# global object gs___set__ + +def set_bases(space, __args__): + funcname = "set_bases" + signature = ['cls', 'bases'], None, None + defaults_w = [] + w_cls, w_bases = __args__.parse(funcname, signature, defaults_w) + return fastf_set_bases(space, w_cls, w_bases) + +f_set_bases = set_bases + +def set_bases(space, w_cls, w_bases): + + w_0=v2=w_etype=w_evalue=w_cls_1=w_bases_1=w_6=w_cls_2=w_bases_2=None + w_7=w_b=w_cls_3=w_bases_3=w_9=w_b_1=w_10=v11=w_cls_4=w_bases_4=None + w_12=w_13=w_14=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_bases, space.w_tuple) + v2 = space.is_true(w_0) + if v2 == True: + w_cls_1, w_bases_1 = w_cls, w_bases + goto = 2 + else: + assert v2 == False + (w_etype, w_evalue) = (gcls_TypeError, + gs___bases___must_be_a_tuple_object) + goto = 6 + + if goto == 2: + w_6 = space.iter(w_bases_1) + w_cls_2, w_bases_2, w_7 = w_cls_1, w_bases_1, w_6 + goto = 3 + + if goto == 3: + try: + w_b = space.next(w_7) + w_cls_3, w_bases_3, w_9, w_b_1 = w_cls_2, w_bases_2, w_7, w_b + goto = 4 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): + w_cls_4, w_bases_4 = w_cls_2, w_bases_2 + goto = 5 + else:raise # unhandled case, should not happen + + if goto == 4: + w_10 = space.isinstance(w_b_1, gcls_classobj) + v11 = space.is_true(w_10) + if v11 == True: + w_cls_2, w_bases_2, w_7 = w_cls_3, w_bases_3, w_9 + goto = 3 + continue + else: + assert v11 == False + (w_etype, w_evalue) = (gcls_TypeError, + gs___bases___items_must_be_classes) + goto = 6 + + if goto == 5: + w_12 = space.getattr(gdescriptor_classobj__bases, gs___set__) + w_13 = space.call_function(w_12, w_cls_4, w_bases_4) + w_14 = space.w_None + goto = 7 + + if goto == 6: + raise OperationError(w_etype, w_evalue) + + if goto == 7: + return w_14 + +fastf_set_bases = set_bases + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'set_dict' +## firstlineno 50 +##SECTION## +# global declarations +# global object gcls_TypeError +# global object gs___dict___must_be_a_dictionary_ob + +def set_dict(space, __args__): + funcname = "set_dict" + signature = ['cls', 'dic'], None, None + defaults_w = [] + w_cls, w_dic = __args__.parse(funcname, signature, defaults_w) + return fastf_set_dict(space, w_cls, w_dic) + +f_set_dict = set_dict + +def set_dict(space, w_cls, w_dic): + + w_0=v2=w_etype=w_evalue=w_cls_1=w_dic_1=w_6=w_7=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_dic, space.w_dict) + v2 = space.is_true(w_0) + if v2 == True: + w_cls_1, w_dic_1 = w_cls, w_dic + goto = 2 + else: + assert v2 == False + (w_etype, w_evalue) = (gcls_TypeError, + gs___dict___must_be_a_dictionary_ob) + goto = 3 + + if goto == 2: + w_6 = space.call_function(gdescriptor_object___setattr__, w_cls_1, gs___dict__, w_dic_1) + w_7 = space.w_None + goto = 4 + + if goto == 3: + raise OperationError(w_etype, w_evalue) + + if goto == 4: + return w_7 + +fastf_set_dict = set_dict + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'retrieve' +## firstlineno 55 +##SECTION## +# global declarations +# global object gdescriptor_object___getattribute__ +# global object gcls_IndexError +# global object gcls_KeyError + +def retrieve(space, __args__): + funcname = "retrieve" + signature = ['obj', 'attr'], None, None + defaults_w = [] + w_obj, w_attr = __args__.parse(funcname, signature, defaults_w) + return fastf_retrieve(space, w_obj, w_attr) + +f_retrieve = retrieve + +def retrieve(space, w_obj, w_attr): + + w_dic=w_2=w_4=w_attr_1=w_5=w_6=w_7=w_8=v9=w_attr_2=w_12=w_13=None + w_14=w_15=v16=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_dic = space.call_function(gdescriptor_object___getattribute__, w_obj, gs___dict__) + try: + w_2 = space.getitem(w_dic, w_attr) + w_4 = w_2 + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): + (w_attr_1, w_5, w_6, w_7) = (w_attr, space.w_IndexError, + e.w_value, space.w_IndexError) + goto = 2 + elif space.is_true(space.issubtype(e.w_type, space.w_KeyError)): + (w_attr_1, w_5, w_6, w_7) = (w_attr, space.w_KeyError, e.w_value, + space.w_KeyError) + goto = 2 + else:raise # unhandled case, should not happen + + if goto == 2: + w_8 = space.is_(w_7, space.w_KeyError) + v9 = space.is_true(w_8) + if v9 == True: + w_etype, w_evalue = gcls_AttributeError, w_attr_1 + goto = 4 + else: + assert v9 == False + w_attr_2, w_12, w_13, w_14 = w_attr_1, w_5, w_6, w_7 + goto = 3 + + if goto == 3: + w_15 = space.issubtype(w_14, space.w_KeyError) + v16 = space.is_true(w_15) + if v16 == True: + w_etype, w_evalue = gcls_AttributeError, w_attr_2 + goto = 4 + else: + assert v16 == False + w_etype, w_evalue = w_12, w_13 + goto = 4 + + if goto == 4: + raise OperationError(w_etype, w_evalue) + + if goto == 5: + return w_4 + +fastf_retrieve = retrieve + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'lookup' +## firstlineno 62 +##SECTION## +# global declaration +# global object g2tuple_1 + +def lookup(space, __args__): + funcname = "lookup" + signature = ['cls', 'attr'], None, None + defaults_w = [] + w_cls, w_attr = __args__.parse(funcname, signature, defaults_w) + return fastf_lookup(space, w_cls, w_attr) + +f_lookup = lookup + +def lookup(space, w_cls, w_attr): + + w_v=w_cls_1=w_v_1=w_6=w_7=w_cls_2=w_attr_1=w_3=w_4=w_5=w_8=v9=None + w_cls_4=w_attr_3=w_10=w_11=w_12=w_13=v14=w_etype=w_evalue=w_cls_5=None + w_attr_4=w_17=w_18=w_19=w_attr_5=w_20=w_b=w_attr_6=w_25=w_b_1=None + w_26=w_27=w_28=v29=w_attr_7=w_30=w_31=w_v_2=w_found=v33=w_v_3=None + w_found_1=w_34=w_cls_3=w_attr_2=w_21=w_22=w_23=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_v = fastf_retrieve(space, w_cls, w_attr) + w_cls_1, w_v_1 = w_cls, w_v + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + (w_cls_2, w_attr_1, w_3, w_4, w_5) = (w_cls, w_attr, e.w_type, + e.w_value, e.w_type) + goto = 3 + else:raise # unhandled case, should not happen + + if goto == 2: + w_6 = space.newtuple([w_v_1, w_cls_1]) + w_7 = w_6 + goto = 12 + + if goto == 3: + w_8 = space.is_(w_5, gcls_AttributeError) + v9 = space.is_true(w_8) + if v9 == True: + w_cls_3, w_attr_2 = w_cls_2, w_attr_1 + goto = 6 + else: + assert v9 == False + (w_cls_4, w_attr_3, w_10, w_11, w_12) = (w_cls_2, w_attr_1, w_3, + w_4, w_5) + goto = 4 + + if goto == 4: + w_13 = space.issubtype(w_12, gcls_AttributeError) + v14 = space.is_true(w_13) + if v14 == True: + w_cls_5, w_attr_4 = w_cls_4, w_attr_3 + goto = 5 + else: + assert v14 == False + w_etype, w_evalue = w_10, w_11 + goto = 11 + + if goto == 5: + w_17 = space.getattr(gdescriptor_classobj__bases, gs___get__) + w_18 = space.call_function(w_17, w_cls_5) + w_19 = space.iter(w_18) + w_attr_5, w_20 = w_attr_4, w_19 + goto = 7 + + if goto == 6: + w_21 = space.getattr(gdescriptor_classobj__bases, gs___get__) + w_22 = space.call_function(w_21, w_cls_3) + w_23 = space.iter(w_22) + w_attr_5, w_20 = w_attr_2, w_23 + goto = 7 + + if goto == 7: + try: + w_b = space.next(w_20) + w_attr_6, w_25, w_b_1 = w_attr_5, w_20, w_b + goto = 8 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): + w_7 = g2tuple_1 + goto = 12 + else:raise # unhandled case, should not happen + + if goto == 8: + w_26 = fastf_lookup(space, w_b_1, w_attr_6) + w_27 = space.len(w_26) + w_28 = space.eq(w_27, gi_2) + v29 = space.is_true(w_28) + if v29 == True: + w_attr_7, w_30, w_31 = w_attr_6, w_25, w_26 + goto = 9 + else: + assert v29 == False + w_etype, w_evalue = space.w_ValueError, space.w_None + goto = 11 + + if goto == 9: + w_v_2 = space.getitem(w_31, gi_0) + w_found = space.getitem(w_31, gi_1) + v33 = space.is_true(w_found) + if v33 == True: + w_v_3, w_found_1 = w_v_2, w_found + goto = 10 + else: + assert v33 == False + w_attr_5, w_20 = w_attr_7, w_30 + goto = 7 + continue + + if goto == 10: + w_34 = space.newtuple([w_v_3, w_found_1]) + w_7 = w_34 + goto = 12 + + if goto == 11: + raise OperationError(w_etype, w_evalue) + + if goto == 12: + return w_7 + +fastf_lookup = lookup + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'get_class_module' +## firstlineno 74 +##SECTION## +# global declarations +# global object gfunc_retrieve +# global object gcls_Exception +# global object gcls_AttributeError + +def get_class_module(space, __args__): + funcname = "get_class_module" + signature = ['cls'], None, None + defaults_w = [] + w_cls, = __args__.parse(funcname, signature, defaults_w) + return fastf_get_class_module(space, w_cls) + +f_get_class_module = get_class_module + +def get_class_module(space, w_cls): + + w_mod=w_mod_1=w_10=v11=w_12=w_2=w_3=w_4=w_5=v6=w_7=w_8=w_9=w_13=None + v14=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_mod = fastf_retrieve(space, w_cls, gs___module__) + w_mod_1 = w_mod + goto = 3 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_2, w_3, w_4 = e.w_type, e.w_value, e.w_type + goto = 2 + else:raise # unhandled case, should not happen + + if goto == 2: + w_5 = space.is_(w_4, gcls_AttributeError) + v6 = space.is_true(w_5) + if v6 == True: + w_mod_1 = space.w_None + goto = 3 + else: + assert v6 == False + w_7, w_8, w_9 = w_2, w_3, w_4 + goto = 4 + + if goto == 3: + w_10 = space.isinstance(w_mod_1, space.w_str) + v11 = space.is_true(w_10) + if v11 == True: + w_12 = w_mod_1 + goto = 6 + else: + assert v11 == False + w_12 = gs__ + goto = 6 + + if goto == 4: + w_13 = space.issubtype(w_9, gcls_AttributeError) + v14 = space.is_true(w_13) + if v14 == True: + w_mod_1 = space.w_None + goto = 3 + continue + else: + assert v14 == False + w_etype, w_evalue = w_7, w_8 + goto = 5 + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_12 + +fastf_get_class_module = get_class_module + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'mro_lookup' +## firstlineno 83 +##SECTION## +# global declaration +# global object gs___mro__ + +def mro_lookup(space, __args__): + funcname = "mro_lookup" + signature = ['v', 'name'], None, None + defaults_w = [] + w_v, w_name = __args__.parse(funcname, signature, defaults_w) + return fastf_mro_lookup(space, w_v, w_name) + +f_mro_lookup = mro_lookup + +def mro_lookup(space, w_v, w_name): + + w_0=w_mro=w_name_1=w_mro_1=w_5=w_name_2=w_6=w_x=w_name_3=w_8=None + w_x_1=w_9=w_10=v11=w_name_4=w_x_2=w_12=w_13=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(space.w_type, w_v) + try: + w_mro = space.getattr(w_0, gs___mro__) + w_name_1, w_mro_1 = w_name, w_mro + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + w_4 = space.w_None + goto = 6 + else:raise # unhandled case, should not happen + + if goto == 2: + w_5 = space.iter(w_mro_1) + w_name_2, w_6 = w_name_1, w_5 + goto = 3 + + if goto == 3: + try: + w_x = space.next(w_6) + w_name_3, w_8, w_x_1 = w_name_2, w_6, w_x + goto = 4 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): + w_4 = space.w_None + goto = 6 + else:raise # unhandled case, should not happen + + if goto == 4: + w_9 = space.getattr(w_x_1, gs___dict__) + w_10 = space.contains(w_9, w_name_3) + v11 = space.is_true(w_10) + if v11 == True: + w_name_4, w_x_2 = w_name_3, w_x_1 + goto = 5 + else: + assert v11 == False + w_name_2, w_6 = w_name_3, w_8 + goto = 3 + continue + + if goto == 5: + w_12 = space.getattr(w_x_2, gs___dict__) + w_13 = space.getitem(w_12, w_name_4) + w_4 = w_13 + goto = 6 + + if goto == 6: + return w_4 + +fastf_mro_lookup = mro_lookup + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'seqiter' +## firstlineno 93 +##SECTION## +def seqiter(space, __args__): + funcname = "seqiter" + signature = ['func'], None, None + defaults_w = [] + w_func, = __args__.parse(funcname, signature, defaults_w) + return fastf_seqiter(space, w_func) + +f_seqiter = seqiter + +def seqiter(space, w_func): + + w_1=w_2=w_3=w_4=w_5=w_6=v7=w_10=w_11=w_12=w_13=v14=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_1 = space.call_function(w_func, gi_0) + w_2 = w_1 + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_3, w_4, w_5 = e.w_type, e.w_value, e.w_type + goto = 2 + else:raise # unhandled case, should not happen + + if goto == 2: + w_6 = space.is_(w_5, space.w_IndexError) + v7 = space.is_true(w_6) + if v7 == True: + w_etype, w_evalue = space.w_StopIteration, space.w_None + goto = 4 + else: + assert v7 == False + w_10, w_11, w_12 = w_3, w_4, w_5 + goto = 3 + + if goto == 3: + w_13 = space.issubtype(w_12, space.w_IndexError) + v14 = space.is_true(w_13) + if v14 == True: + w_etype, w_evalue = space.w_StopIteration, space.w_None + goto = 4 + else: + assert v14 == False + w_etype, w_evalue = w_10, w_11 + goto = 4 + + if goto == 4: + raise OperationError(w_etype, w_evalue) + + if goto == 5: + return w_2 + +fastf_seqiter = seqiter + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__new__' +## firstlineno 109 +##SECTION## +# global declarations +# global object gfunc_type_err +# global object gs_name +# global object gs_string +# global object g0tuple +# global object gs_bases +# global object gs_tuple +# global object gs_dict +# global object gs___doc__ +# global object gs__getframe +# global object gs_f_globals +# global object gs_get +# global object gs_OLD_STYLE_CLASSES_IMPL +# global object g_object +# global object gcls_OverflowError +# global object gcls_FloatingPointError +# global object gs_callable +# global object gs_base_must_be_class + +def __new__(space, __args__): + funcname = "__new__" + signature = ['subtype', 'name', 'bases', 'dic'], None, None + defaults_w = [] + w_subtype, w_name, w_bases, w_dic = __args__.parse(funcname, signature, defaults_w) + return fastf___new__(space, w_subtype, w_name, w_bases, w_dic) + +f___new__ = __new__ + +def __new__(space, w_subtype, w_name, w_bases, w_dic): + + w_0=v2=w_name_2=w_5=w_6=w_etype=w_evalue=w_name_1=w_bases_1=w_dic_1=None + w_9=v10=w_name_3=w_bases_2=w_dic_2=w_11=v12=w_bases_4=w_13=w_14=None + w_name_4=w_bases_3=w_dic_3=w_15=v16=w_dic_5=w_17=w_18=w_name_5=None + w_bases_5=w_dic_4=w_19=w_name_6=w_bases_6=w_dic_6=w_30=w_name_11=None + w_bases_11=w_dic_11=w_65=w_name_23=w_bases_23=w_dic_23=w_66=w_b=None + w_name_24=w_bases_24=w_dic_24=w_68=w_b_1=w_71=v72=w_name_26=w_bases_26=None + w_dic_26=w_b_2=w_73=w_74=v75=w_name_27=w_bases_27=w_dic_27=w_b_3=None + w_76=w_77=w_78=w_name_25=w_bases_25=w_dic_25=w_new_class=w_80=None + w_81=w_82=w_83=w_84=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None + w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_69=v70=None + w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_g=w_name_15=w_bases_15=None + w_dic_15=w_i_1=w_g_1=w_47=w_name_17=w_bases_17=w_dic_17=w_i_2=None + w_g_2=w_48=w_49=w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_3=w_50=None + w_51=v52=w_name_20=w_bases_20=w_dic_20=w_g_4=w_60=w_modname=w_62=None + v63=w_name_22=w_bases_22=w_dic_22=w_modname_1=w_64=w_name_19=None + w_bases_19=w_dic_19=w_i_4=w_i_5=w_name_16=w_bases_16=w_dic_16=None + w_44=w_45=w_46=w_58=v59=w_name_21=w_bases_21=w_dic_21=w_56=w_57=None + w_54=w_53=v55=w_name_7=w_bases_7=w_dic_7=w_20=w_21=w_22=w_23=None + v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=w_40=v41=w_name_10=None + w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=w_dic_8=w_29=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_name, space.w_str) + v2 = space.is_true(w_0) + if v2 == True: + w_name_1, w_bases_1, w_dic_1 = w_name, w_bases, w_dic + goto = 3 + else: + assert v2 == False + w_name_2 = w_name + goto = 2 + + if goto == 2: + w_5 = fastf_type_err(space, gs_name, gs_string, w_name_2) + w_6 = space.type(w_5) + w_etype, w_evalue = w_6, w_5 + goto = 31 + + if goto == 3: + w_9 = space.is_(w_bases_1, space.w_None) + v10 = space.is_true(w_9) + if v10 == True: + w_name_3, w_bases_2, w_dic_2 = w_name_1, g0tuple, w_dic_1 + goto = 4 + else: + assert v10 == False + w_name_3, w_bases_2, w_dic_2 = w_name_1, w_bases_1, w_dic_1 + goto = 4 + + if goto == 4: + w_11 = space.isinstance(w_bases_2, space.w_tuple) + v12 = space.is_true(w_11) + if v12 == True: + w_name_4, w_bases_3, w_dic_3 = w_name_3, w_bases_2, w_dic_2 + goto = 6 + else: + assert v12 == False + w_bases_4 = w_bases_2 + goto = 5 + + if goto == 5: + w_13 = fastf_type_err(space, gs_bases, gs_tuple, w_bases_4) + w_14 = space.type(w_13) + w_etype, w_evalue = w_14, w_13 + goto = 31 + + if goto == 6: + w_15 = space.isinstance(w_dic_3, space.w_dict) + v16 = space.is_true(w_15) + if v16 == True: + w_name_5, w_bases_5, w_dic_4 = w_name_4, w_bases_3, w_dic_3 + goto = 8 + else: + assert v16 == False + w_dic_5 = w_dic_3 + goto = 7 + + if goto == 7: + w_17 = fastf_type_err(space, gs_dict, gs_dict, w_dic_5) + w_18 = space.type(w_17) + w_etype, w_evalue = w_18, w_17 + goto = 31 + + if goto == 8: + try: + w_19 = space.getitem(w_dic_4, gs___doc__) + w_name_6, w_bases_6, w_dic_6 = w_name_5, w_bases_5, w_dic_4 + goto = 12 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): + (w_name_7, w_bases_7, w_dic_7, w_20, w_21, w_22) = (w_name_5, + w_bases_5, w_dic_4, space.w_IndexError, e.w_value, + space.w_IndexError) + goto = 9 + elif space.is_true(space.issubtype(e.w_type, space.w_KeyError)): + (w_name_7, w_bases_7, w_dic_7, w_20, w_21, w_22) = (w_name_5, + w_bases_5, w_dic_4, space.w_KeyError, e.w_value, + space.w_KeyError) + goto = 9 + else:raise # unhandled case, should not happen + + if goto == 9: + w_23 = space.is_(w_22, space.w_KeyError) + v24 = space.is_true(w_23) + if v24 == True: + w_name_8, w_bases_8, w_dic_8 = w_name_7, w_bases_7, w_dic_7 + goto = 11 + else: + assert v24 == False + (w_name_9, w_bases_9, w_dic_9, w_25, w_26, w_27) = (w_name_7, + w_bases_7, w_dic_7, w_20, w_21, w_22) + goto = 14 + + if goto == 10: + w_28 = space.setitem(w_dic_10, gs___doc__, space.w_None) + w_name_6, w_bases_6, w_dic_6 = w_name_10, w_bases_10, w_dic_10 + goto = 12 + + if goto == 11: + w_29 = space.setitem(w_dic_8, gs___doc__, space.w_None) + w_name_6, w_bases_6, w_dic_6 = w_name_8, w_bases_8, w_dic_8 + goto = 12 + + if goto == 12: + try: + w_30 = space.getitem(w_dic_6, gs___module__) + w_name_11, w_bases_11, w_dic_11 = w_name_6, w_bases_6, w_dic_6 + goto = 24 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): + (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) = (w_name_6, + w_bases_6, w_dic_6, space.w_IndexError, e.w_value, + space.w_IndexError) + goto = 13 + elif space.is_true(space.issubtype(e.w_type, space.w_KeyError)): + (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) = (w_name_6, + w_bases_6, w_dic_6, space.w_KeyError, e.w_value, + space.w_KeyError) + goto = 13 + else:raise # unhandled case, should not happen + + if goto == 13: + w_34 = space.is_(w_33, space.w_KeyError) + v35 = space.is_true(w_34) + if v35 == True: + (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_12, w_bases_12, + w_dic_12, gi_0) + goto = 15 + else: + assert v35 == False + (w_name_14, w_bases_14, w_dic_14, w_37, w_38, w_39) = (w_name_12, + w_bases_12, w_dic_12, w_31, w_32, w_33) + goto = 26 + + if goto == 14: + w_40 = space.issubtype(w_27, space.w_KeyError) + v41 = space.is_true(w_40) + if v41 == True: + w_name_10, w_bases_10, w_dic_10 = w_name_9, w_bases_9, w_dic_9 + goto = 10 + continue + else: + assert v41 == False + w_etype, w_evalue = w_25, w_26 + goto = 31 + + if goto == 15: + w_42 = space.call_function((space.getattr(space.w_sys, gs__getframe)), w_i) + try: + w_g = space.getattr(w_42, gs_f_globals) + (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1) = (w_name_13, + w_bases_13, w_dic_13, w_i, w_g) + goto = 16 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_13, + w_bases_13, w_dic_13, gcls_AttributeError, e.w_value, + gcls_AttributeError) + goto = 21 + else:raise # unhandled case, should not happen + + if goto == 16: + try: + w_47 = space.getattr(w_g_1, gs_get) + (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, + w_48) = (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1, w_47) + goto = 17 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_15, + w_bases_15, w_dic_15, gcls_AttributeError, e.w_value, + gcls_AttributeError) + goto = 21 + else:raise # unhandled case, should not happen + + if goto == 17: + try: + w_49 = space.call_function(w_48, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) + (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_3, + w_50) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, w_49) + goto = 18 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_17, + w_bases_17, w_dic_17, e.w_type, e.w_value, e.w_type) + goto = 21 + else:raise # unhandled case, should not happen + + if goto == 18: + w_51 = space.is_(w_50, g_object) + v52 = space.is_true(w_51) + if v52 == True: + (w_name_19, w_bases_19, w_dic_19, w_i_4) = (w_name_18, w_bases_18, + w_dic_18, w_i_3) + goto = 19 + else: + assert v52 == False + (w_name_20, w_bases_20, w_dic_20, w_g_4) = (w_name_18, w_bases_18, + w_dic_18, w_g_3) + goto = 22 + + if goto == 19: + try: + w_i_5 = space.inplace_add(w_i_4, gi_1) + (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_19, w_bases_19, + w_dic_19, w_i_5) + goto = 15 + continue + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_OverflowError)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, + w_bases_19, w_dic_19, gcls_OverflowError, e.w_value, + gcls_OverflowError) + goto = 21 + elif space.is_true(space.issubtype(e.w_type, gcls_FloatingPointError)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, + w_bases_19, w_dic_19, gcls_FloatingPointError, e.w_value, + gcls_FloatingPointError) + goto = 21 + else:raise # unhandled case, should not happen + + if goto == 20: + w_53 = space.issubtype(w_54, space.w_ValueError) + v55 = space.is_true(w_53) + if v55 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 + goto = 24 + else: + assert v55 == False + w_etype, w_evalue = w_56, w_57 + goto = 31 + + if goto == 21: + w_58 = space.is_(w_46, space.w_ValueError) + v59 = space.is_true(w_58) + if v59 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_16, w_bases_16, w_dic_16 + goto = 24 + else: + assert v59 == False + (w_name_21, w_bases_21, w_dic_21, w_56, w_57, w_54) = (w_name_16, + w_bases_16, w_dic_16, w_44, w_45, w_46) + goto = 20 + continue + + if goto == 22: + w_60 = space.getattr(w_g_4, gs_get) + w_modname = space.call_function(w_60, gs___name__, space.w_None) + w_62 = space.is_(w_modname, space.w_None) + v63 = space.is_true(w_62) + if v63 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_20, w_bases_20, w_dic_20 + goto = 24 + else: + assert v63 == False + (w_name_22, w_bases_22, w_dic_22, w_modname_1) = (w_name_20, + w_bases_20, w_dic_20, w_modname) + goto = 23 + + if goto == 23: + w_64 = space.setitem(w_dic_22, gs___module__, w_modname_1) + w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 + goto = 24 + + if goto == 24: + w_65 = space.iter(w_bases_11) + (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_11, w_bases_11, + w_dic_11, w_65) + goto = 25 + + if goto == 25: + try: + w_b = space.next(w_66) + (w_name_24, w_bases_24, w_dic_24, w_68, w_b_1) = (w_name_23, + w_bases_23, w_dic_23, w_66, w_b) + goto = 27 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): + w_name_25, w_bases_25, w_dic_25 = w_name_23, w_bases_23, w_dic_23 + goto = 30 + else:raise # unhandled case, should not happen + + if goto == 26: + w_69 = space.issubtype(w_39, space.w_KeyError) + v70 = space.is_true(w_69) + if v70 == True: + (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_14, w_bases_14, + w_dic_14, gi_0) + goto = 15 + continue + else: + assert v70 == False + w_etype, w_evalue = w_37, w_38 + goto = 31 + + if goto == 27: + w_71 = space.isinstance(w_b_1, gcls_classobj) + v72 = space.is_true(w_71) + if v72 == True: + (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_24, w_bases_24, + w_dic_24, w_68) + goto = 25 + continue + else: + assert v72 == False + (w_name_26, w_bases_26, w_dic_26, w_b_2) = (w_name_24, w_bases_24, + w_dic_24, w_b_1) + goto = 28 + + if goto == 28: + w_73 = space.call_function(space.w_type, w_b_2) + w_74 = space.call_function((space.getattr(space.w_builtin, gs_callable)), w_73) + v75 = space.is_true(w_74) + if v75 == True: + (w_name_27, w_bases_27, w_dic_27, w_b_3) = (w_name_26, w_bases_26, + w_dic_26, w_b_2) + goto = 29 + else: + assert v75 == False + w_etype, w_evalue = gcls_TypeError, gs_base_must_be_class + goto = 31 + + if goto == 29: + w_76 = space.call_function(space.w_type, w_b_3) + w_77 = space.call_function(w_76, w_name_27, w_bases_27, w_dic_27) + w_78 = w_77 + goto = 32 + + if goto == 30: + w_new_class = space.call_function(gbltinmethod___new__, gcls_classobj) + w_80 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_25) + w_81 = space.getattr(gdescriptor_classobj__name, gs___set__) + w_82 = space.call_function(w_81, w_new_class, w_name_25) + w_83 = space.getattr(gdescriptor_classobj__bases, gs___set__) + w_84 = space.call_function(w_83, w_new_class, w_bases_25) + w_78 = w_new_class + goto = 32 + + if goto == 31: + raise OperationError(w_etype, w_evalue) + + if goto == 32: + return w_78 + +fastf___new__ = __new__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__setattr__' +## firstlineno 159 +##SECTION## +# global declarations +# global object gfunc_set_name +# global object gs___bases__ +# global object gfunc_set_bases +# global object gfunc_set_dict +# global object gdescriptor_object___setattr__ + +def __setattr__(space, __args__): + funcname = "__setattr__" + signature = ['self', 'attr', 'value'], None, None + defaults_w = [] + w_self, w_attr, w_value = __args__.parse(funcname, signature, defaults_w) + return fastf_classobj___setattr__(space, w_self, w_attr, w_value) + +f_classobj___setattr__ = __setattr__ + +def __setattr__(space, w_self, w_attr, w_value): + + w_0=v2=w_self_2=w_attr_1=w_value_2=w_7=v8=w_self_4=w_attr_2=w_value_4=None + w_10=v11=w_self_6=w_attr_3=w_value_6=w_13=w_6=w_self_5=w_value_5=None + w_12=w_self_3=w_value_3=w_9=w_self_1=w_value_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.eq(w_attr, gs___name__) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_value_1 = w_self, w_value + goto = 2 + else: + assert v2 == False + w_self_2, w_attr_1, w_value_2 = w_self, w_attr, w_value + goto = 3 + + if goto == 2: + w_5 = fastf_set_name(space, w_self_1, w_value_1) + w_6 = space.w_None + goto = 8 + + if goto == 3: + w_7 = space.eq(w_attr_1, gs___bases__) + v8 = space.is_true(w_7) + if v8 == True: + w_self_3, w_value_3 = w_self_2, w_value_2 + goto = 4 + else: + assert v8 == False + w_self_4, w_attr_2, w_value_4 = w_self_2, w_attr_1, w_value_2 + goto = 5 + + if goto == 4: + w_9 = fastf_set_bases(space, w_self_3, w_value_3) + w_6 = space.w_None + goto = 8 + + if goto == 5: + w_10 = space.eq(w_attr_2, gs___dict__) + v11 = space.is_true(w_10) + if v11 == True: + w_self_5, w_value_5 = w_self_4, w_value_4 + goto = 6 + else: + assert v11 == False + w_self_6, w_attr_3, w_value_6 = w_self_4, w_attr_2, w_value_4 + goto = 7 + + if goto == 6: + w_12 = fastf_set_dict(space, w_self_5, w_value_5) + w_6 = space.w_None + goto = 8 + + if goto == 7: + w_13 = space.call_function(gdescriptor_object___setattr__, w_self_6, w_attr_3, w_value_6) + w_6 = space.w_None + goto = 8 + + if goto == 8: + return w_6 + +fastf_classobj___setattr__ = __setattr__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__delattr__' +## firstlineno 169 +##SECTION## +# global declarations +# global object g3tuple_2 +# global object gdescriptor_object___delattr__ + +def __delattr__(space, __args__): + funcname = "__delattr__" + signature = ['self', 'attr'], None, None + defaults_w = [] + w_self, w_attr = __args__.parse(funcname, signature, defaults_w) + return fastf_classobj___delattr__(space, w_self, w_attr) + +f_classobj___delattr__ = __delattr__ + +def __delattr__(space, w_self, w_attr): + + w_0=v2=w_self_2=w_attr_2=w_6=w_5=w_self_1=w_attr_1=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.contains(g3tuple_2, w_attr) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_attr_1 = w_self, w_attr + goto = 2 + else: + assert v2 == False + w_self_2, w_attr_2 = w_self, w_attr + goto = 3 + + if goto == 2: + w_4 = fastf_classobj___setattr__(space, w_self_1, w_attr_1, space.w_None) + w_5 = space.w_None + goto = 4 + + if goto == 3: + w_6 = space.call_function(gdescriptor_object___delattr__, w_self_2, w_attr_2) + w_5 = space.w_None + goto = 4 + + if goto == 4: + return w_5 + +fastf_classobj___delattr__ = __delattr__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__getattribute__' +## firstlineno 176 +##SECTION## +# global declarations +# global object gs___get__ +# global object gfunc_lookup +# global object gi_2 +# global object gcls_ValueError +# global object gs_class__s_has_no_attribute__s +# global object gfunc_mro_lookup + +def __getattribute__(space, __args__): + funcname = "__getattribute__" + signature = ['self', 'attr'], None, None + defaults_w = [] + w_self, w_attr = __args__.parse(funcname, signature, defaults_w) + return fastf_classobj___getattribute__(space, w_self, w_attr) + +f_classobj___getattribute__ = __getattribute__ + +def __getattribute__(space, w_self, w_attr): + + w_0=v2=w_self_2=w_attr_1=w_6=v7=w_self_4=w_attr_2=w_14=v15=w_self_9=None + w_attr_5=w_18=w_19=w_20=v21=w_etype=w_evalue=w_self_5=w_attr_3=None + w_11=w_v=w_found=v13=w_self_7=w_attr_4=w_24=w_25=w_26=w_self_6=None + w_v_1=w_descr_get=w_28=v29=w_self_10=w_descr_get_1=w_v_2=w_30=None + w_5=w_self_8=w_16=w_17=w_self_3=w_8=w_9=w_self_1=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.eq(w_attr, gs___dict__) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1 = w_self + goto = 2 + else: + assert v2 == False + w_self_2, w_attr_1 = w_self, w_attr + goto = 3 + + if goto == 2: + w_4 = space.call_function(gdescriptor_object___getattribute__, w_self_1, gs___dict__) + w_5 = w_4 + goto = 13 + + if goto == 3: + w_6 = space.eq(w_attr_1, gs___name__) + v7 = space.is_true(w_6) + if v7 == True: + w_self_3 = w_self_2 + goto = 4 + else: + assert v7 == False + w_self_4, w_attr_2 = w_self_2, w_attr_1 + goto = 6 + + if goto == 4: + w_8 = space.getattr(gdescriptor_classobj__name, gs___get__) + w_9 = space.call_function(w_8, w_self_3) + w_5 = w_9 + goto = 13 + + if goto == 5: + w_v = space.getitem(w_11, gi_0) + w_found = space.getitem(w_11, gi_1) + v13 = space.is_true(w_found) + if v13 == True: + w_self_6, w_v_1 = w_self_5, w_v + goto = 10 + else: + assert v13 == False + w_self_7, w_attr_4 = w_self_5, w_attr_3 + goto = 9 + + if goto == 6: + w_14 = space.eq(w_attr_2, gs___bases__) + v15 = space.is_true(w_14) + if v15 == True: + w_self_8 = w_self_4 + goto = 7 + else: + assert v15 == False + w_self_9, w_attr_5 = w_self_4, w_attr_2 + goto = 8 + + if goto == 7: + w_16 = space.getattr(gdescriptor_classobj__bases, gs___get__) + w_17 = space.call_function(w_16, w_self_8) + w_5 = w_17 + goto = 13 + + if goto == 8: + w_18 = fastf_lookup(space, w_self_9, w_attr_5) + w_19 = space.len(w_18) + w_20 = space.eq(w_19, gi_2) + v21 = space.is_true(w_20) + if v21 == True: + w_self_5, w_attr_3, w_11 = w_self_9, w_attr_5, w_18 + goto = 5 + continue + else: + assert v21 == False + w_etype, w_evalue = space.w_ValueError, space.w_None + goto = 12 + + if goto == 9: + w_24 = space.getattr(w_self_7, gs___name__) + w_25 = space.newtuple([w_24, w_attr_4]) + w_26 = space.mod(gs_class__s_has_no_attribute__s, w_25) + w_etype, w_evalue = gcls_AttributeError, w_26 + goto = 12 + + if goto == 10: + w_descr_get = fastf_mro_lookup(space, w_v_1, gs___get__) + w_28 = space.is_(w_descr_get, space.w_None) + v29 = space.is_true(w_28) + if v29 == True: + w_5 = w_v_1 + goto = 13 + else: + assert v29 == False + w_self_10, w_descr_get_1, w_v_2 = w_self_6, w_descr_get, w_v_1 + goto = 11 + + if goto == 11: + w_30 = space.call_function(w_descr_get_1, w_v_2, space.w_None, w_self_10) + w_5 = w_30 + goto = 13 + + if goto == 12: + raise OperationError(w_etype, w_evalue) + + if goto == 13: + return w_5 + +fastf_classobj___getattribute__ = __getattribute__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__repr__' +## firstlineno 193 +##SECTION## +# global declarations +# global object gfunc_uid +# global object gs__class__s__s_at_0x_x_ + +def __repr__(space, __args__): + funcname = "__repr__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_classobj___repr__(space, w_self) + +f_classobj___repr__ = __repr__ + +def __repr__(space, w_self): + + w_mod=w_2=w_3=w_4=w_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_mod = fastf_get_class_module(space, w_self) + w_2 = space.getattr(w_self, gs___name__) + w_3 = fastf_uid(space, w_self) + w_4 = space.newtuple([w_mod, w_2, w_3]) + w_5 = space.mod(gs__class__s__s_at_0x_x_, w_4) + w_6 = w_5 + goto = 2 + + if goto == 2: + return w_6 + +fastf_classobj___repr__ = __repr__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__str__' +## firstlineno 197 +##SECTION## +# global declarations +# global object gfunc_get_class_module +# global object gs__ +# global object gs___name__ +# global object gs__s__s + +def __str__(space, __args__): + funcname = "__str__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_classobj___str__(space, w_self) + +f_classobj___str__ = __str__ + +def __str__(space, w_self): + + w_mod=w_2=v3=w_self_2=w_mod_1=w_6=w_7=w_8=w_5=w_self_1=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_mod = fastf_get_class_module(space, w_self) + w_2 = space.eq(w_mod, gs__) + v3 = space.is_true(w_2) + if v3 == True: + w_self_1 = w_self + goto = 2 + else: + assert v3 == False + w_self_2, w_mod_1 = w_self, w_mod + goto = 3 + + if goto == 2: + w_4 = space.getattr(w_self_1, gs___name__) + w_5 = w_4 + goto = 4 + + if goto == 3: + w_6 = space.getattr(w_self_2, gs___name__) + w_7 = space.newtuple([w_mod_1, w_6]) + w_8 = space.mod(gs__s__s, w_7) + w_5 = w_8 + goto = 4 + + if goto == 4: + return w_5 + +fastf_classobj___str__ = __str__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__call__' +## firstlineno 204 +##SECTION## +# global declarations +# global object gbltinmethod___new__ +# global object gdescriptor_instance__class +# global object gfunc_instance_getattr1 +# global object gs___init__ +# global object gs___init_____should_return_None + +def __call__(space, __args__): + funcname = "__call__" + signature = ['self'], 'args', 'kwds' + defaults_w = [] + w_self, w_args, w_kwds = __args__.parse(funcname, signature, defaults_w) + return fastf_classobj___call__(space, w_self, w_args, w_kwds) + +f_classobj___call__ = __call__ + +def __call__(space, w_self, w_args, w_kwds): + + w_inst=w_dic=w_2=w_3=w_init=v6=w_9=w_args_1=w_kwds_1=w_inst_1=None + w_init_1=w_ret=w_11=v12=w_13=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_inst = space.call_function(gbltinmethod___new__, gcls_instance) + w_dic = space.getattr(w_inst, gs___dict__) + w_2 = space.getattr(gdescriptor_instance__class, gs___set__) + w_3 = space.call_function(w_2, w_inst, w_self) + w_init = space.call_function(gfunc_instance_getattr1, w_inst, gs___init__, space.w_False) + v6 = space.is_true(w_init) + if v6 == True: + (w_args_1, w_kwds_1, w_inst_1, w_init_1) = (w_args, w_kwds, + w_inst, w_init) + goto = 2 + else: + assert v6 == False + w_9 = w_inst + goto = 5 + + if goto == 2: + _args = Arguments.fromshape(space, (0, (), True, True), [w_args_1, w_kwds_1]) + w_ret = space.call_args(w_init_1, _args) + w_11 = space.is_(w_ret, space.w_None) + v12 = space.is_true(w_11) + if v12 == True: + w_9 = w_inst_1 + goto = 5 + else: + assert v12 == False + goto = 3 + + if goto == 3: + w_13 = space.call_function(gcls_TypeError, gs___init_____should_return_None) + w_etype, w_evalue = gcls_TypeError, w_13 + goto = 4 + + if goto == 4: + raise OperationError(w_etype, w_evalue) + + if goto == 5: + return w_9 + +fastf_classobj___call__ = __call__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'instance_getattr1' +## firstlineno 225 +##SECTION## +# global declarations +# global object gs___class__ +# global object gs__s_instance_has_no_attribute__s + +def instance_getattr1(space, __args__): + funcname = "instance_getattr1" + signature = ['inst', 'name', 'exc'], None, None + defaults_w = [space.w_True] + w_inst, w_name, w_exc = __args__.parse(funcname, signature, defaults_w) + return fastf_instance_getattr1(space, w_inst, w_name, w_exc) + +f_instance_getattr1 = instance_getattr1 + +def instance_getattr1(space, w_inst, w_name, w_exc): + + w_0=v2=w_inst_2=w_name_2=w_exc_1=w_7=v8=w_inst_4=w_name_3=w_exc_2=None + w_18=w_6=w_inst_7=w_name_6=w_exc_5=w_19=w_20=w_21=w_22=v23=w_inst_5=None + w_name_4=w_exc_3=w_14=w_16=w_12=w_11=v13=w_etype=w_evalue=w_inst_6=None + w_name_5=w_exc_4=w_24=w_cls=w_26=w_27=w_28=v29=w_inst_9=w_name_8=None + w_exc_7=w_cls_1=w_30=w_v_2=w_found_1=v40=w_name_11=w_exc_10=w_cls_6=None + v41=w_name_12=w_cls_7=w_43=w_44=w_45=w_inst_11=w_v_1=w_cls_4=None + w_descr_get=w_50=v51=w_inst_12=w_descr_get_1=w_v_3=w_cls_9=w_52=None + w_inst_8=w_name_7=w_exc_6=w_31=w_cls_2=w_32=w_33=w_34=v35=w_inst_10=None + w_name_9=w_exc_8=w_cls_3=w_36=w_v=w_found=v39=w_name_10=w_exc_9=None + w_cls_5=v42=w_name_13=w_cls_8=w_46=w_47=w_48=w_inst_3=w_9=w_10=None + w_inst_1=w_name_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.eq(w_name, gs___dict__) + v2 = space.is_true(w_0) + if v2 == True: + w_inst_1, w_name_1 = w_inst, w_name + goto = 2 + else: + assert v2 == False + w_inst_2, w_name_2, w_exc_1 = w_inst, w_name, w_exc + goto = 3 + + if goto == 2: + w_5 = space.call_function(gdescriptor_object___getattribute__, w_inst_1, w_name_1) + w_6 = w_5 + goto = 19 + + if goto == 3: + w_7 = space.eq(w_name_2, gs___class__) + v8 = space.is_true(w_7) + if v8 == True: + w_inst_3 = w_inst_2 + goto = 4 + else: + assert v8 == False + w_inst_4, w_name_3, w_exc_2 = w_inst_2, w_name_2, w_exc_1 + goto = 6 + + if goto == 4: + w_9 = space.getattr(gdescriptor_instance__class, gs___get__) + w_10 = space.call_function(w_9, w_inst_3) + w_6 = w_10 + goto = 19 + + if goto == 5: + w_11 = space.issubtype(w_12, gcls_AttributeError) + v13 = space.is_true(w_11) + if v13 == True: + w_inst_6, w_name_5, w_exc_4 = w_inst_5, w_name_4, w_exc_3 + goto = 8 + else: + assert v13 == False + w_etype, w_evalue = w_14, w_16 + goto = 18 + + if goto == 6: + try: + w_18 = fastf_retrieve(space, w_inst_4, w_name_3) + w_6 = w_18 + goto = 19 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + (w_inst_7, w_name_6, w_exc_5, w_19, w_20, w_21) = (w_inst_4, + w_name_3, w_exc_2, e.w_type, e.w_value, e.w_type) + goto = 7 + else:raise # unhandled case, should not happen + + if goto == 7: + w_22 = space.is_(w_21, gcls_AttributeError) + v23 = space.is_true(w_22) + if v23 == True: + w_inst_8, w_name_7, w_exc_6 = w_inst_7, w_name_6, w_exc_5 + goto = 9 + else: + assert v23 == False + (w_inst_5, w_name_4, w_exc_3, w_14, w_16, w_12) = (w_inst_7, + w_name_6, w_exc_5, w_19, w_20, w_21) + goto = 5 + continue + + if goto == 8: + w_24 = space.getattr(gdescriptor_instance__class, gs___get__) + w_cls = space.call_function(w_24, w_inst_6) + w_26 = fastf_lookup(space, w_cls, w_name_5) + w_27 = space.len(w_26) + w_28 = space.eq(w_27, gi_2) + v29 = space.is_true(w_28) + if v29 == True: + (w_inst_9, w_name_8, w_exc_7, w_cls_1, w_30) = (w_inst_6, + w_name_5, w_exc_4, w_cls, w_26) + goto = 11 + else: + assert v29 == False + w_etype, w_evalue = space.w_ValueError, space.w_None + goto = 18 + + if goto == 9: + w_31 = space.getattr(gdescriptor_instance__class, gs___get__) + w_cls_2 = space.call_function(w_31, w_inst_8) + w_32 = fastf_lookup(space, w_cls_2, w_name_7) + w_33 = space.len(w_32) + w_34 = space.eq(w_33, gi_2) + v35 = space.is_true(w_34) + if v35 == True: + (w_inst_10, w_name_9, w_exc_8, w_cls_3, w_36) = (w_inst_8, + w_name_7, w_exc_6, w_cls_2, w_32) + goto = 10 + else: + assert v35 == False + w_etype, w_evalue = space.w_ValueError, space.w_None + goto = 18 + + if goto == 10: + w_v = space.getitem(w_36, gi_0) + w_found = space.getitem(w_36, gi_1) + v39 = space.is_true(w_found) + if v39 == True: + w_inst_11, w_v_1, w_cls_4 = w_inst_10, w_v, w_cls_3 + goto = 16 + else: + assert v39 == False + w_name_10, w_exc_9, w_cls_5 = w_name_9, w_exc_8, w_cls_3 + goto = 13 + + if goto == 11: + w_v_2 = space.getitem(w_30, gi_0) + w_found_1 = space.getitem(w_30, gi_1) + v40 = space.is_true(w_found_1) + if v40 == True: + w_inst_11, w_v_1, w_cls_4 = w_inst_9, w_v_2, w_cls_1 + goto = 16 + else: + assert v40 == False + w_name_11, w_exc_10, w_cls_6 = w_name_8, w_exc_7, w_cls_1 + goto = 12 + + if goto == 12: + v41 = space.is_true(w_exc_10) + if v41 == True: + w_name_12, w_cls_7 = w_name_11, w_cls_6 + goto = 14 + else: + assert v41 == False + w_6 = space.w_None + goto = 19 + + if goto == 13: + v42 = space.is_true(w_exc_9) + if v42 == True: + w_name_13, w_cls_8 = w_name_10, w_cls_5 + goto = 15 + else: + assert v42 == False + w_6 = space.w_None + goto = 19 + + if goto == 14: + w_43 = space.getattr(w_cls_7, gs___name__) + w_44 = space.newtuple([w_43, w_name_12]) + w_45 = space.mod(gs__s_instance_has_no_attribute__s, w_44) + w_etype, w_evalue = gcls_AttributeError, w_45 + goto = 18 + + if goto == 15: + w_46 = space.getattr(w_cls_8, gs___name__) + w_47 = space.newtuple([w_46, w_name_13]) + w_48 = space.mod(gs__s_instance_has_no_attribute__s, w_47) + w_etype, w_evalue = gcls_AttributeError, w_48 + goto = 18 + + if goto == 16: + w_descr_get = fastf_mro_lookup(space, w_v_1, gs___get__) + w_50 = space.is_(w_descr_get, space.w_None) + v51 = space.is_true(w_50) + if v51 == True: + w_6 = w_v_1 + goto = 19 + else: + assert v51 == False + (w_inst_12, w_descr_get_1, w_v_3, w_cls_9) = (w_inst_11, + w_descr_get, w_v_1, w_cls_4) + goto = 17 + + if goto == 17: + w_52 = space.call_function(w_descr_get_1, w_v_3, w_inst_12, w_cls_9) + w_6 = w_52 + goto = 19 + + if goto == 18: + raise OperationError(w_etype, w_evalue) + + if goto == 19: + return w_6 + +fastf_instance_getattr1 = instance_getattr1 + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__getattribute__' +## firstlineno 249 +##SECTION## +# global declaration +# global object gs___getattr__ + +def __getattribute__(space, __args__): + funcname = "__getattribute__" + signature = ['self', 'name'], None, None + defaults_w = [] + w_self, w_name = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___getattribute__(space, w_self, w_name) + +f_instance___getattribute__ = __getattribute__ + +def __getattribute__(space, w_self, w_name): + + w_0=w_3=w_self_1=w_name_1=w_4=w_5=w_6=w_7=w_8=w_9=v10=w_self_3=None + w_name_3=w_13=w_14=w_15=w_16=w_17=w_18=v19=w_etype=w_evalue=w_self_4=None + w_name_4=w_20=w_21=w_getattr=w_25=v26=w_name_5=w_getattr_1=w_29=None + w_self_2=w_name_2=w_11=w_12=w_getattr_2=w_27=v28=w_name_6=w_getattr_3=None + w_30=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, w_name) + w_3 = w_0 + goto = 9 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + (w_self_1, w_name_1, w_4, w_5, w_6, w_7, w_8) = (w_self, w_name, + e.w_type, e.w_value, e.w_type, e.w_type, e.w_value) + goto = 2 + else:raise # unhandled case, should not happen + + if goto == 2: + w_9 = space.is_(w_6, gcls_AttributeError) + v10 = space.is_true(w_9) + if v10 == True: + w_self_2, w_name_2, w_11, w_12 = w_self_1, w_name_1, w_7, w_8 + goto = 5 + else: + assert v10 == False + (w_self_3, w_name_3, w_13, w_14, w_15, w_16, w_17) = (w_self_1, + w_name_1, w_4, w_5, w_6, w_7, w_8) + goto = 3 + + if goto == 3: + w_18 = space.issubtype(w_15, gcls_AttributeError) + v19 = space.is_true(w_18) + if v19 == True: + w_self_4, w_name_4, w_20, w_21 = w_self_3, w_name_3, w_16, w_17 + goto = 4 + else: + assert v19 == False + w_etype, w_evalue = w_13, w_14 + goto = 8 + + if goto == 4: + _args = Arguments.fromshape(space, (2, ('exc',), False, False), [w_self_4, gs___getattr__, space.w_False]) + w_getattr = space.call_args(gfunc_instance_getattr1, _args) + w_25 = space.is_(w_getattr, space.w_None) + v26 = space.is_true(w_25) + if v26 == True: + w_etype, w_evalue = w_20, w_21 + goto = 8 + else: + assert v26 == False + w_name_5, w_getattr_1 = w_name_4, w_getattr + goto = 6 + + if goto == 5: + _args = Arguments.fromshape(space, (2, ('exc',), False, False), [w_self_2, gs___getattr__, space.w_False]) + w_getattr_2 = space.call_args(gfunc_instance_getattr1, _args) + w_27 = space.is_(w_getattr_2, space.w_None) + v28 = space.is_true(w_27) + if v28 == True: + w_etype, w_evalue = w_11, w_12 + goto = 8 + else: + assert v28 == False + w_name_6, w_getattr_3 = w_name_2, w_getattr_2 + goto = 7 + + if goto == 6: + w_29 = space.call_function(w_getattr_1, w_name_5) + w_3 = w_29 + goto = 9 + + if goto == 7: + w_30 = space.call_function(w_getattr_3, w_name_6) + w_3 = w_30 + goto = 9 + + if goto == 8: + raise OperationError(w_etype, w_evalue) + + if goto == 9: + return w_3 + +fastf_instance___getattribute__ = __getattribute__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__new__' +## firstlineno 258 +##SECTION## +# global declarations +# global object gs_instance___first_arg_must_be_cla +# global object gs_instance___second_arg_must_be_di + +def __new__(space, __args__): + funcname = "__new__" + signature = ['typ', 'klass', 'dic'], None, None + defaults_w = [space.w_None] + w_typ, w_klass, w_dic = __args__.parse(funcname, signature, defaults_w) + return fastf___new___1(space, w_typ, w_klass, w_dic) + +f___new___1 = __new__ + +def __new__(space, w_typ, w_klass, w_dic): + + w_0=v2=w_4=w_etype=w_evalue=w_klass_1=w_dic_1=w_7=v8=w_klass_3=None + w_dic_2=w_9=v10=w_11=w_klass_4=w_dic_4=w_inst=w_13=w_14=w_15=None + w_16=w_klass_2=w_dic_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_klass, gcls_classobj) + v2 = space.is_true(w_0) + if v2 == True: + w_klass_1, w_dic_1 = w_klass, w_dic + goto = 3 + else: + assert v2 == False + goto = 2 + + if goto == 2: + w_4 = space.call_function(gcls_TypeError, gs_instance___first_arg_must_be_cla) + w_etype, w_evalue = gcls_TypeError, w_4 + goto = 8 + + if goto == 3: + w_7 = space.is_(w_dic_1, space.w_None) + v8 = space.is_true(w_7) + if v8 == True: + w_klass_2 = w_klass_1 + goto = 4 + else: + assert v8 == False + w_klass_3, w_dic_2 = w_klass_1, w_dic_1 + goto = 5 + + if goto == 4: + w_dic_3 = space.newdict([]) + w_klass_4, w_dic_4 = w_klass_2, w_dic_3 + goto = 7 + + if goto == 5: + w_9 = space.isinstance(w_dic_2, space.w_dict) + v10 = space.is_true(w_9) + if v10 == True: + w_klass_4, w_dic_4 = w_klass_3, w_dic_2 + goto = 7 + else: + assert v10 == False + goto = 6 + + if goto == 6: + w_11 = space.call_function(gcls_TypeError, gs_instance___second_arg_must_be_di) + w_etype, w_evalue = gcls_TypeError, w_11 + goto = 8 + + if goto == 7: + w_inst = space.call_function(gbltinmethod___new__, gcls_instance) + w_13 = space.getattr(gdescriptor_instance__class, gs___set__) + w_14 = space.call_function(w_13, w_inst, w_klass_4) + w_15 = space.call_function(gdescriptor_object___setattr__, w_inst, gs___dict__, w_dic_4) + w_16 = w_inst + goto = 9 + + if goto == 8: + raise OperationError(w_etype, w_evalue) + + if goto == 9: + return w_16 + +fastf___new___1 = __new__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__setattr__' +## firstlineno 271 +##SECTION## +# global declarations +# global object gs___dict___must_be_set_to_a_dictio +# global object gs___class___must_be_set_to_a_class + +def __setattr__(space, __args__): + funcname = "__setattr__" + signature = ['self', 'name', 'value'], None, None + defaults_w = [] + w_self, w_name, w_value = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___setattr__(space, w_self, w_name, w_value) + +f_instance___setattr__ = __setattr__ + +def __setattr__(space, w_self, w_name, w_value): + + w_0=v2=w_self_2=w_name_1=w_value_2=w_12=v13=w_self_5=w_name_2=None + w_value_5=w_setattr=w_20=v21=w_name_4=w_value_8=w_setattr_1=w_22=None + w_11=w_self_7=w_name_3=w_value_7=w_23=w_24=w_self_4=w_value_4=None + w_14=v15=w_16=w_etype=w_evalue=w_self_6=w_value_6=w_17=w_18=w_self_1=None + w_value_1=w_5=v6=w_7=w_self_3=w_value_3=w_10=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.eq(w_name, gs___dict__) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_value_1 = w_self, w_value + goto = 2 + else: + assert v2 == False + w_self_2, w_name_1, w_value_2 = w_self, w_name, w_value + goto = 5 + + if goto == 2: + w_5 = space.isinstance(w_value_1, space.w_dict) + v6 = space.is_true(w_5) + if v6 == True: + w_self_3, w_value_3 = w_self_1, w_value_1 + goto = 4 + else: + assert v6 == False + goto = 3 + + if goto == 3: + w_7 = space.call_function(gcls_TypeError, gs___dict___must_be_set_to_a_dictio) + w_etype, w_evalue = gcls_TypeError, w_7 + goto = 12 + + if goto == 4: + w_10 = space.call_function(gdescriptor_object___setattr__, w_self_3, gs___dict__, w_value_3) + w_11 = space.w_None + goto = 13 + + if goto == 5: + w_12 = space.eq(w_name_1, gs___class__) + v13 = space.is_true(w_12) + if v13 == True: + w_self_4, w_value_4 = w_self_2, w_value_2 + goto = 6 + else: + assert v13 == False + w_self_5, w_name_2, w_value_5 = w_self_2, w_name_1, w_value_2 + goto = 9 + + if goto == 6: + w_14 = space.isinstance(w_value_4, gcls_classobj) + v15 = space.is_true(w_14) + if v15 == True: + w_self_6, w_value_6 = w_self_4, w_value_4 + goto = 8 + else: + assert v15 == False + goto = 7 + + if goto == 7: + w_16 = space.call_function(gcls_TypeError, gs___class___must_be_set_to_a_class) + w_etype, w_evalue = gcls_TypeError, w_16 + goto = 12 + + if goto == 8: + w_17 = space.getattr(gdescriptor_instance__class, gs___set__) + w_18 = space.call_function(w_17, w_self_6, w_value_6) + w_11 = space.w_None + goto = 13 + + if goto == 9: + _args = Arguments.fromshape(space, (2, ('exc',), False, False), [w_self_5, gs___setattr__, space.w_False]) + w_setattr = space.call_args(gfunc_instance_getattr1, _args) + w_20 = space.is_(w_setattr, space.w_None) + v21 = space.is_true(w_20) + if v21 == True: + w_self_7, w_name_3, w_value_7 = w_self_5, w_name_2, w_value_5 + goto = 11 + else: + assert v21 == False + w_name_4, w_value_8, w_setattr_1 = w_name_2, w_value_5, w_setattr + goto = 10 + + if goto == 10: + w_22 = space.call_function(w_setattr_1, w_name_4, w_value_8) + w_11 = space.w_None + goto = 13 + + if goto == 11: + w_23 = space.getattr(w_self_7, gs___dict__) + w_24 = space.setitem(w_23, w_name_3, w_value_7) + w_11 = space.w_None + goto = 13 + + if goto == 12: + raise OperationError(w_etype, w_evalue) + + if goto == 13: + return w_11 + +fastf_instance___setattr__ = __setattr__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__delattr__' +## firstlineno 287 +##SECTION## +# global declarations +# global object g2tuple_2 +# global object gs__s_instance_has_no_attribute___s + +def __delattr__(space, __args__): + funcname = "__delattr__" + signature = ['self', 'name'], None, None + defaults_w = [] + w_self, w_name = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___delattr__(space, w_self, w_name) + +f_instance___delattr__ = __delattr__ + +def __delattr__(space, w_self, w_name): + + w_0=v2=w_self_2=w_name_2=w_delattr=w_7=v8=w_name_4=w_delattr_1=None + w_9=w_5=w_self_3=w_name_3=w_10=w_self_4=w_name_5=w_11=w_15=w_self_5=None + w_name_6=w_12=w_13=w_14=w_23=v24=w_self_6=w_name_7=w_19=w_21=None + w_17=w_16=v18=w_etype=w_evalue=w_self_7=w_name_8=w_25=w_26=w_27=None + w_28=w_29=w_self_8=w_name_9=w_30=w_31=w_32=w_33=w_34=w_self_1=None + w_name_1=w_4=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.contains(g2tuple_2, w_name) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_name_1 = w_self, w_name + goto = 2 + else: + assert v2 == False + w_self_2, w_name_2 = w_self, w_name + goto = 3 + + if goto == 2: + w_4 = fastf_instance___setattr__(space, w_self_1, w_name_1, space.w_None) + w_5 = space.w_None + goto = 12 + + if goto == 3: + _args = Arguments.fromshape(space, (2, ('exc',), False, False), [w_self_2, gs___delattr__, space.w_False]) + w_delattr = space.call_args(gfunc_instance_getattr1, _args) + w_7 = space.is_(w_delattr, space.w_None) + v8 = space.is_true(w_7) + if v8 == True: + w_self_3, w_name_3 = w_self_2, w_name_2 + goto = 5 + else: + assert v8 == False + w_name_4, w_delattr_1 = w_name_2, w_delattr + goto = 4 + + if goto == 4: + w_9 = space.call_function(w_delattr_1, w_name_4) + w_5 = space.w_None + goto = 12 + + if goto == 5: + try: + w_10 = space.getattr(w_self_3, gs___dict__) + w_self_4, w_name_5, w_11 = w_self_3, w_name_3, w_10 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + (w_self_5, w_name_6, w_12, w_13, w_14) = (w_self_3, w_name_3, + gcls_AttributeError, e.w_value, gcls_AttributeError) + goto = 8 + else:raise # unhandled case, should not happen + + if goto == 6: + try: + w_15 = space.delitem(w_11, w_name_5) + w_5 = space.w_None + goto = 12 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): + (w_self_5, w_name_6, w_12, w_13, w_14) = (w_self_4, w_name_5, + space.w_IndexError, e.w_value, space.w_IndexError) + goto = 8 + elif space.is_true(space.issubtype(e.w_type, space.w_KeyError)): + (w_self_5, w_name_6, w_12, w_13, w_14) = (w_self_4, w_name_5, + space.w_KeyError, e.w_value, space.w_KeyError) + goto = 8 + else:raise # unhandled case, should not happen + + if goto == 7: + w_16 = space.issubtype(w_17, space.w_KeyError) + v18 = space.is_true(w_16) + if v18 == True: + w_self_7, w_name_8 = w_self_6, w_name_7 + goto = 9 + else: + assert v18 == False + w_etype, w_evalue = w_19, w_21 + goto = 11 + + if goto == 8: + w_23 = space.is_(w_14, space.w_KeyError) + v24 = space.is_true(w_23) + if v24 == True: + w_self_8, w_name_9 = w_self_5, w_name_6 + goto = 10 + else: + assert v24 == False + (w_self_6, w_name_7, w_19, w_21, w_17) = (w_self_5, w_name_6, + w_12, w_13, w_14) + goto = 7 + continue + + if goto == 9: + w_25 = space.getattr(w_self_7, gs___class__) + w_26 = space.getattr(w_25, gs___name__) + w_27 = space.newtuple([w_26, w_name_8]) + w_28 = space.mod(gs__s_instance_has_no_attribute___s, w_27) + w_29 = space.call_function(gcls_AttributeError, w_28) + w_etype, w_evalue = gcls_AttributeError, w_29 + goto = 11 + + if goto == 10: + w_30 = space.getattr(w_self_8, gs___class__) + w_31 = space.getattr(w_30, gs___name__) + w_32 = space.newtuple([w_31, w_name_9]) + w_33 = space.mod(gs__s_instance_has_no_attribute___s, w_32) + w_34 = space.call_function(gcls_AttributeError, w_33) + w_etype, w_evalue = gcls_AttributeError, w_34 + goto = 11 + + if goto == 11: + raise OperationError(w_etype, w_evalue) + + if goto == 12: + return w_5 + +fastf_instance___delattr__ = __delattr__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__repr__' +## firstlineno 303 +##SECTION## +# global declaration +# global object gs___s__s_instance_at_0x_x_ + +def __repr__(space, __args__): + funcname = "__repr__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___repr__(space, w_self) + +f_instance___repr__ = __repr__ + +def __repr__(space, w_self): + + w_func=w_func_1=w_21=w_16=w_self_1=w_2=w_3=w_4=w_5=v6=w_self_3=None + w_7=w_8=w_9=w_22=v23=w_etype=w_evalue=w_self_4=w_klass=w_mod=None + w_12=w_13=w_14=w_15=w_self_2=w_klass_1=w_mod_1=w_17=w_18=w_19=None + w_20=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___repr__) + w_func_1 = w_func + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_self_1, w_2, w_3, w_4 = w_self, e.w_type, e.w_value, e.w_type + goto = 2 + else:raise # unhandled case, should not happen + + if goto == 2: + w_5 = space.is_(w_4, gcls_AttributeError) + v6 = space.is_true(w_5) + if v6 == True: + w_self_2 = w_self_1 + goto = 4 + else: + assert v6 == False + w_self_3, w_7, w_8, w_9 = w_self_1, w_2, w_3, w_4 + goto = 6 + + if goto == 3: + w_klass = space.getattr(w_self_4, gs___class__) + w_mod = fastf_get_class_module(space, w_klass) + w_12 = space.getattr(w_klass, gs___name__) + w_13 = fastf_uid(space, w_self_4) + w_14 = space.newtuple([w_mod, w_12, w_13]) + w_15 = space.mod(gs___s__s_instance_at_0x_x_, w_14) + w_16 = w_15 + goto = 8 + + if goto == 4: + w_klass_1 = space.getattr(w_self_2, gs___class__) + w_mod_1 = fastf_get_class_module(space, w_klass_1) + w_17 = space.getattr(w_klass_1, gs___name__) + w_18 = fastf_uid(space, w_self_2) + w_19 = space.newtuple([w_mod_1, w_17, w_18]) + w_20 = space.mod(gs___s__s_instance_at_0x_x_, w_19) + w_16 = w_20 + goto = 8 + + if goto == 5: + w_21 = space.call_function(w_func_1, ) + w_16 = w_21 + goto = 8 + + if goto == 6: + w_22 = space.issubtype(w_9, gcls_AttributeError) + v23 = space.is_true(w_22) + if v23 == True: + w_self_4 = w_self_3 + goto = 3 + continue + else: + assert v23 == False + w_etype, w_evalue = w_7, w_8 + goto = 7 + + if goto == 7: + raise OperationError(w_etype, w_evalue) + + if goto == 8: + return w_16 + +fastf_instance___repr__ = __repr__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__str__' +## firstlineno 312 +##SECTION## +def __str__(space, __args__): + funcname = "__str__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___str__(space, w_self) + +f_instance___str__ = __str__ + +def __str__(space, w_self): + + w_func=w_func_1=w_13=w_11=w_self_1=w_2=w_3=w_4=w_5=v6=w_self_3=None + w_7=w_8=w_9=w_14=v15=w_etype=w_evalue=w_self_4=w_10=w_self_2=None + w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___str__) + w_func_1 = w_func + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_self_1, w_2, w_3, w_4 = w_self, e.w_type, e.w_value, e.w_type + goto = 2 + else:raise # unhandled case, should not happen + + if goto == 2: + w_5 = space.is_(w_4, gcls_AttributeError) + v6 = space.is_true(w_5) + if v6 == True: + w_self_2 = w_self_1 + goto = 4 + else: + assert v6 == False + w_self_3, w_7, w_8, w_9 = w_self_1, w_2, w_3, w_4 + goto = 6 + + if goto == 3: + w_10 = fastf_instance___repr__(space, w_self_4) + w_11 = w_10 + goto = 8 + + if goto == 4: + w_12 = fastf_instance___repr__(space, w_self_2) + w_11 = w_12 + goto = 8 + + if goto == 5: + w_13 = space.call_function(w_func_1, ) + w_11 = w_13 + goto = 8 + + if goto == 6: + w_14 = space.issubtype(w_9, gcls_AttributeError) + v15 = space.is_true(w_14) + if v15 == True: + w_self_4 = w_self_3 + goto = 3 + continue + else: + assert v15 == False + w_etype, w_evalue = w_7, w_8 + goto = 7 + + if goto == 7: + raise OperationError(w_etype, w_evalue) + + if goto == 8: + return w_11 + +fastf_instance___str__ = __str__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__hash__' +## firstlineno 319 +##SECTION## +# global declarations +# global object gs_unhashable_instance +# global object gs___hash_____should_return_an_int + +def __hash__(space, __args__): + funcname = "__hash__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___hash__(space, w_self) + +f_instance___hash__ = __hash__ + +def __hash__(space, w_self): + + w__eq=w__cmp=w__hash=v4=w_self_1=w__hash_1=w_5=v6=w_self_3=w__hash_3=None + w_7=v9=w_self_4=w__hash_4=v13=w_self_5=w_19=w_17=w__hash_5=w_ret=None + w_15=v16=w_18=w_etype=w_evalue=w_10=w_self_2=w__hash_2=v8=None + + goto = 1 # startblock + while True: + + if goto == 1: + w__eq = space.call_function(gfunc_instance_getattr1, w_self, gs___eq__, space.w_False) + w__cmp = space.call_function(gfunc_instance_getattr1, w_self, gs___cmp__, space.w_False) + w__hash = space.call_function(gfunc_instance_getattr1, w_self, gs___hash__, space.w_False) + v4 = space.is_true(w__eq) + if v4 == True: + w_self_1, w__hash_1, w_5 = w_self, w__hash, w__eq + goto = 2 + else: + assert v4 == False + w_self_1, w__hash_1, w_5 = w_self, w__hash, w__cmp + goto = 2 + + if goto == 2: + v6 = space.is_true(w_5) + if v6 == True: + w_self_2, w__hash_2 = w_self_1, w__hash_1 + goto = 3 + else: + assert v6 == False + w_self_3, w__hash_3, w_7 = w_self_1, w__hash_1, w_5 + goto = 4 + + if goto == 3: + v8 = space.is_true(w__hash_2) + if v8 == True: + w_self_3, w__hash_3, w_7 = w_self_2, w__hash_2, space.w_False + goto = 4 + else: + assert v8 == False + w_self_3, w__hash_3, w_7 = w_self_2, w__hash_2, space.w_True + goto = 4 + + if goto == 4: + v9 = space.is_true(w_7) + if v9 == True: + goto = 5 + else: + assert v9 == False + w_self_4, w__hash_4 = w_self_3, w__hash_3 + goto = 6 + + if goto == 5: + w_10 = space.call_function(gcls_TypeError, gs_unhashable_instance) + w_etype, w_evalue = gcls_TypeError, w_10 + goto = 10 + + if goto == 6: + v13 = space.is_true(w__hash_4) + if v13 == True: + w__hash_5 = w__hash_4 + goto = 7 + else: + assert v13 == False + w_self_5 = w_self_4 + goto = 9 + + if goto == 7: + w_ret = space.call_function(w__hash_5, ) + w_15 = space.isinstance(w_ret, space.w_int) + v16 = space.is_true(w_15) + if v16 == True: + w_17 = w_ret + goto = 11 + else: + assert v16 == False + goto = 8 + + if goto == 8: + w_18 = space.call_function(gcls_TypeError, gs___hash_____should_return_an_int) + w_etype, w_evalue = gcls_TypeError, w_18 + goto = 10 + + if goto == 9: + w_19 = space.id(w_self_5) + w_17 = w_19 + goto = 11 + + if goto == 10: + raise OperationError(w_etype, w_evalue) + + if goto == 11: + return w_17 + +fastf_instance___hash__ = __hash__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__len__' +## firstlineno 333 +##SECTION## +# global declarations +# global object gs___len_____should_return____0 +# global object gs___len_____should_return_an_int + +def __len__(space, __args__): + funcname = "__len__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___len__(space, w_self) + +f_instance___len__ = __len__ + +def __len__(space, w_self): + + w_0=w_ret=w_3=v4=w_11=w_etype=w_evalue=w_ret_1=w_5=v6=w_7=w_8=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___len__) + w_ret = space.call_function(w_0, ) + w_3 = space.isinstance(w_ret, space.w_int) + v4 = space.is_true(w_3) + if v4 == True: + w_ret_1 = w_ret + goto = 2 + else: + assert v4 == False + goto = 4 + + if goto == 2: + w_5 = space.lt(w_ret_1, gi_0) + v6 = space.is_true(w_5) + if v6 == True: + goto = 3 + else: + assert v6 == False + w_7 = w_ret_1 + goto = 6 + + if goto == 3: + w_8 = space.call_function(space.w_ValueError, gs___len_____should_return____0) + w_etype, w_evalue = space.w_ValueError, w_8 + goto = 5 + + if goto == 4: + w_11 = space.call_function(gcls_TypeError, gs___len_____should_return_an_int) + w_etype, w_evalue = gcls_TypeError, w_11 + goto = 5 + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_7 + +fastf_instance___len__ = __len__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__getitem__' +## firstlineno 342 +##SECTION## +# global declaration +# global object gs___getslice__ + +def __getitem__(space, __args__): + funcname = "__getitem__" + signature = ['self', 'key'], None, None + defaults_w = [] + w_self, w_key = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___getitem__(space, w_self, w_key) + +f_instance___getitem__ = __getitem__ + +def __getitem__(space, w_self, w_key): + + w_0=v2=w_self_2=w_key_2=w_4=v7=w_self_4=w_key_4=w_14=w_15=w_13=None + w_self_3=w_key_3=w_func=v9=w_key_5=w_func_1=w_10=w_11=w_12=w_self_1=None + w_key_1=w_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_key, space.w_slice) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_key_1 = w_self, w_key + goto = 2 + else: + assert v2 == False + w_self_2, w_key_2, w_4 = w_self, w_key, w_0 + goto = 3 + + if goto == 2: + w_5 = space.getattr(w_key_1, gs_step) + w_6 = space.is_(w_5, space.w_None) + w_self_2, w_key_2, w_4 = w_self_1, w_key_1, w_6 + goto = 3 + + if goto == 3: + v7 = space.is_true(w_4) + if v7 == True: + w_self_3, w_key_3 = w_self_2, w_key_2 + goto = 4 + else: + assert v7 == False + w_self_4, w_key_4 = w_self_2, w_key_2 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___getslice__, space.w_False) + v9 = space.is_true(w_func) + if v9 == True: + w_key_5, w_func_1 = w_key_3, w_func + goto = 5 + else: + assert v9 == False + w_self_4, w_key_4 = w_self_3, w_key_3 + goto = 6 + + if goto == 5: + w_10 = space.getattr(w_key_5, gs_start) + w_11 = space.getattr(w_key_5, gs_stop) + w_12 = space.call_function(w_func_1, w_10, w_11) + w_13 = w_12 + goto = 7 + + if goto == 6: + w_14 = space.call_function(gfunc_instance_getattr1, w_self_4, gs___getitem__) + w_15 = space.call_function(w_14, w_key_4) + w_13 = w_15 + goto = 7 + + if goto == 7: + return w_13 + +fastf_instance___getitem__ = __getitem__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__setitem__' +## firstlineno 349 +##SECTION## +# global declarations +# global object gs_step +# global object gs___setslice__ +# global object gs_start +# global object gs_stop + +def __setitem__(space, __args__): + funcname = "__setitem__" + signature = ['self', 'key', 'value'], None, None + defaults_w = [] + w_self, w_key, w_value = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___setitem__(space, w_self, w_key, w_value) + +f_instance___setitem__ = __setitem__ + +def __setitem__(space, w_self, w_key, w_value): + + w_0=v2=w_self_2=w_key_2=w_value_2=w_5=v8=w_self_4=w_key_4=w_value_4=None + w_14=w_15=w_16=w_self_3=w_key_3=w_value_3=w_func=v10=w_self_5=None + w_key_5=w_value_5=w_func_1=w_11=w_12=w_13=w_self_1=w_key_1=w_value_1=None + w_6=w_7=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_key, space.w_slice) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_key_1, w_value_1 = w_self, w_key, w_value + goto = 2 + else: + assert v2 == False + w_self_2, w_key_2, w_value_2, w_5 = w_self, w_key, w_value, w_0 + goto = 3 + + if goto == 2: + w_6 = space.getattr(w_key_1, gs_step) + w_7 = space.is_(w_6, space.w_None) + (w_self_2, w_key_2, w_value_2, w_5) = (w_self_1, w_key_1, + w_value_1, w_7) + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_key_3, w_value_3 = w_self_2, w_key_2, w_value_2 + goto = 4 + else: + assert v8 == False + w_self_4, w_key_4, w_value_4 = w_self_2, w_key_2, w_value_2 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___setslice__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + (w_self_5, w_key_5, w_value_5, w_func_1) = (w_self_3, w_key_3, + w_value_3, w_func) + goto = 5 + else: + assert v10 == False + w_self_4, w_key_4, w_value_4 = w_self_3, w_key_3, w_value_3 + goto = 6 + + if goto == 5: + w_11 = space.getattr(w_key_5, gs_start) + w_12 = space.getattr(w_key_5, gs_stop) + w_13 = space.call_function(w_func_1, w_11, w_12, w_value_5) + w_self_4, w_key_4, w_value_4 = w_self_5, w_key_5, w_value_5 + goto = 6 + + if goto == 6: + w_14 = space.call_function(gfunc_instance_getattr1, w_self_4, gs___setitem__) + w_15 = space.call_function(w_14, w_key_4, w_value_4) + w_16 = space.w_None + goto = 7 + + if goto == 7: + return w_16 + +fastf_instance___setitem__ = __setitem__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__delitem__' +## firstlineno 356 +##SECTION## +# global declaration +# global object gs___delslice__ + +def __delitem__(space, __args__): + funcname = "__delitem__" + signature = ['self', 'key'], None, None + defaults_w = [] + w_self, w_key = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___delitem__(space, w_self, w_key) + +f_instance___delitem__ = __delitem__ + +def __delitem__(space, w_self, w_key): + + w_0=v2=w_self_2=w_key_2=w_4=v7=w_self_4=w_key_4=w_13=w_14=w_15=None + w_self_3=w_key_3=w_func=v9=w_self_5=w_key_5=w_func_1=w_10=w_11=None + w_12=w_self_1=w_key_1=w_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.isinstance(w_key, space.w_slice) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_key_1 = w_self, w_key + goto = 2 + else: + assert v2 == False + w_self_2, w_key_2, w_4 = w_self, w_key, w_0 + goto = 3 + + if goto == 2: + w_5 = space.getattr(w_key_1, gs_step) + w_6 = space.is_(w_5, space.w_None) + w_self_2, w_key_2, w_4 = w_self_1, w_key_1, w_6 + goto = 3 + + if goto == 3: + v7 = space.is_true(w_4) + if v7 == True: + w_self_3, w_key_3 = w_self_2, w_key_2 + goto = 4 + else: + assert v7 == False + w_self_4, w_key_4 = w_self_2, w_key_2 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___delslice__, space.w_False) + v9 = space.is_true(w_func) + if v9 == True: + w_self_5, w_key_5, w_func_1 = w_self_3, w_key_3, w_func + goto = 5 + else: + assert v9 == False + w_self_4, w_key_4 = w_self_3, w_key_3 + goto = 6 + + if goto == 5: + w_10 = space.getattr(w_key_5, gs_start) + w_11 = space.getattr(w_key_5, gs_stop) + w_12 = space.call_function(w_func_1, w_10, w_11) + w_self_4, w_key_4 = w_self_5, w_key_5 + goto = 6 + + if goto == 6: + w_13 = space.call_function(gfunc_instance_getattr1, w_self_4, gs___delitem__) + w_14 = space.call_function(w_13, w_key_4) + w_15 = space.w_None + goto = 7 + + if goto == 7: + return w_15 + +fastf_instance___delitem__ = __delitem__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__contains__' +## firstlineno 363 +##SECTION## +def __contains__(space, __args__): + funcname = "__contains__" + signature = ['self', 'obj'], None, None + defaults_w = [] + w_self, w_obj = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___contains__(space, w_self, w_obj) + +f_instance___contains__ = __contains__ + +def __contains__(space, w_self, w_obj): + + w_func=v2=w_self_1=w_obj_2=w_7=w_obj_3=w_8=w_x=w_obj_4=w_10=w_x_1=None + w_11=v12=w_6=w_obj_1=w_func_1=w_4=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___contains__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_obj_1, w_func_1 = w_obj, w_func + goto = 2 + else: + assert v2 == False + w_self_1, w_obj_2 = w_self, w_obj + goto = 3 + + if goto == 2: + w_4 = space.call_function(w_func_1, w_obj_1) + w_5 = space.call_function(space.w_bool, w_4) + w_6 = w_5 + goto = 6 + + if goto == 3: + w_7 = space.iter(w_self_1) + w_obj_3, w_8 = w_obj_2, w_7 + goto = 4 + + if goto == 4: + try: + w_x = space.next(w_8) + w_obj_4, w_10, w_x_1 = w_obj_3, w_8, w_x + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): + w_6 = space.w_False + goto = 6 + else:raise # unhandled case, should not happen + + if goto == 5: + w_11 = space.eq(w_x_1, w_obj_4) + v12 = space.is_true(w_11) + if v12 == True: + w_6 = space.w_True + goto = 6 + else: + assert v12 == False + w_obj_3, w_8 = w_obj_4, w_10 + goto = 4 + continue + + if goto == 6: + return w_6 + +fastf_instance___contains__ = __contains__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__coerce__' +## firstlineno 384 +##SECTION## +def __coerce__(space, __args__): + funcname = "__coerce__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___coerce__(space, w_self, w_other) + +f_instance___coerce__ = __coerce__ + +def __coerce__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___coerce__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___coerce__ = __coerce__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__pow__' +## firstlineno 438 +##SECTION## +def __pow__(space, __args__): + funcname = "__pow__" + signature = ['self', 'other', 'modulo'], None, None + defaults_w = [space.w_None] + w_self, w_other, w_modulo = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___pow__(space, w_self, w_other, w_modulo) + +f_instance___pow__ = __pow__ + +def __pow__(space, w_self, w_other, w_modulo): + + w_0=v2=w_self_2=w_other_2=w_modulo_1=w_func_2=v17=w_14=w_other_8=None + w_modulo_2=w_func_3=w_18=w_self_1=w_other_1=w_coerced=w_6=v7=None + w_self_4=w_other_4=w_coerced_1=w_9=w_10=w_self_3=w_other_3=w_8=None + v11=w_self_6=w_other_6=w_16=w_self_5=w_other_5=w_func=v13=w_other_7=None + w_func_1=w_15=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.is_(w_modulo, space.w_None) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_other_1 = w_self, w_other + goto = 2 + else: + assert v2 == False + w_self_2, w_other_2, w_modulo_1 = w_self, w_other, w_modulo + goto = 8 + + if goto == 2: + w_coerced = fastf__coerce(space, w_self_1, w_other_1) + w_6 = space.is_(w_coerced, space.w_None) + v7 = space.is_true(w_6) + if v7 == True: + w_self_3, w_other_3, w_8 = w_self_1, w_other_1, w_6 + goto = 4 + else: + assert v7 == False + w_self_4, w_other_4, w_coerced_1 = w_self_1, w_other_1, w_coerced + goto = 3 + + if goto == 3: + w_9 = space.getitem(w_coerced_1, gi_0) + w_10 = space.is_(w_9, w_self_4) + w_self_3, w_other_3, w_8 = w_self_4, w_other_4, w_10 + goto = 4 + + if goto == 4: + v11 = space.is_true(w_8) + if v11 == True: + w_self_5, w_other_5 = w_self_3, w_other_3 + goto = 5 + else: + assert v11 == False + w_self_6, w_other_6 = w_self_3, w_other_3 + goto = 7 + + if goto == 5: + w_func = space.call_function(gfunc_instance_getattr1, w_self_5, gs___pow__, space.w_False) + v13 = space.is_true(w_func) + if v13 == True: + w_other_7, w_func_1 = w_other_5, w_func + goto = 6 + else: + assert v13 == False + w_14 = space.w_NotImplemented + goto = 10 + + if goto == 6: + w_15 = space.call_function(w_func_1, w_other_7) + w_14 = w_15 + goto = 10 + + if goto == 7: + w_16 = space.pow(w_self_6, w_other_6) + w_14 = w_16 + goto = 10 + + if goto == 8: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_2, gs___pow__, space.w_False) + v17 = space.is_true(w_func_2) + if v17 == True: + w_other_8, w_modulo_2, w_func_3 = w_other_2, w_modulo_1, w_func_2 + goto = 9 + else: + assert v17 == False + w_14 = space.w_NotImplemented + goto = 10 + + if goto == 9: + w_18 = space.call_function(w_func_3, w_other_8, w_modulo_2) + w_14 = w_18 + goto = 10 + + if goto == 10: + return w_14 + +fastf_instance___pow__ = __pow__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__rpow__' +## firstlineno 456 +##SECTION## +def __rpow__(space, __args__): + funcname = "__rpow__" + signature = ['self', 'other', 'modulo'], None, None + defaults_w = [space.w_None] + w_self, w_other, w_modulo = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rpow__(space, w_self, w_other, w_modulo) + +f_instance___rpow__ = __rpow__ + +def __rpow__(space, w_self, w_other, w_modulo): + + w_0=v2=w_self_2=w_other_2=w_modulo_1=w_func_2=v17=w_14=w_other_8=None + w_modulo_2=w_func_3=w_18=w_self_1=w_other_1=w_coerced=w_6=v7=None + w_self_4=w_other_4=w_coerced_1=w_9=w_10=w_self_3=w_other_3=w_8=None + v11=w_self_6=w_other_6=w_16=w_self_5=w_other_5=w_func=v13=w_other_7=None + w_func_1=w_15=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.is_(w_modulo, space.w_None) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_other_1 = w_self, w_other + goto = 2 + else: + assert v2 == False + w_self_2, w_other_2, w_modulo_1 = w_self, w_other, w_modulo + goto = 8 + + if goto == 2: + w_coerced = fastf__coerce(space, w_self_1, w_other_1) + w_6 = space.is_(w_coerced, space.w_None) + v7 = space.is_true(w_6) + if v7 == True: + w_self_3, w_other_3, w_8 = w_self_1, w_other_1, w_6 + goto = 4 + else: + assert v7 == False + w_self_4, w_other_4, w_coerced_1 = w_self_1, w_other_1, w_coerced + goto = 3 + + if goto == 3: + w_9 = space.getitem(w_coerced_1, gi_0) + w_10 = space.is_(w_9, w_self_4) + w_self_3, w_other_3, w_8 = w_self_4, w_other_4, w_10 + goto = 4 + + if goto == 4: + v11 = space.is_true(w_8) + if v11 == True: + w_self_5, w_other_5 = w_self_3, w_other_3 + goto = 5 + else: + assert v11 == False + w_self_6, w_other_6 = w_self_3, w_other_3 + goto = 7 + + if goto == 5: + w_func = space.call_function(gfunc_instance_getattr1, w_self_5, gs___rpow__, space.w_False) + v13 = space.is_true(w_func) + if v13 == True: + w_other_7, w_func_1 = w_other_5, w_func + goto = 6 + else: + assert v13 == False + w_14 = space.w_NotImplemented + goto = 10 + + if goto == 6: + w_15 = space.call_function(w_func_1, w_other_7) + w_14 = w_15 + goto = 10 + + if goto == 7: + w_16 = space.pow(w_other_6, w_self_6) + w_14 = w_16 + goto = 10 + + if goto == 8: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_2, gs___rpow__, space.w_False) + v17 = space.is_true(w_func_2) + if v17 == True: + w_other_8, w_modulo_2, w_func_3 = w_other_2, w_modulo_1, w_func_2 + goto = 9 + else: + assert v17 == False + w_14 = space.w_NotImplemented + goto = 10 + + if goto == 9: + w_18 = space.call_function(w_func_3, w_other_8, w_modulo_2) + w_14 = w_18 + goto = 10 + + if goto == 10: + return w_14 + +fastf_instance___rpow__ = __rpow__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__nonzero__' +## firstlineno 474 +##SECTION## +# global declarations +# global object gs___nonzero_____should_return____0 +# global object gs___nonzero_____should_return_an_i + +def __nonzero__(space, __args__): + funcname = "__nonzero__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___nonzero__(space, w_self) + +f_instance___nonzero__ = __nonzero__ + +def __nonzero__(space, w_self): + + w_func=v2=w_self_1=w_func_2=v3=w_4=w_func_1=w_ret=w_6=v7=w_14=None + w_etype=w_evalue=w_ret_1=w_8=v9=w_ret_2=w_13=w_10=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___nonzero__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_func_1 = w_func + goto = 3 + else: + assert v2 == False + w_self_1 = w_self + goto = 2 + + if goto == 2: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___nonzero__, space.w_False) + v3 = space.is_true(w_func_2) + if v3 == True: + w_func_1 = w_func_2 + goto = 3 + else: + assert v3 == False + w_4 = space.w_True + goto = 9 + + if goto == 3: + w_ret = space.call_function(w_func_1, ) + w_6 = space.isinstance(w_ret, space.w_int) + v7 = space.is_true(w_6) + if v7 == True: + w_ret_1 = w_ret + goto = 4 + else: + assert v7 == False + goto = 7 + + if goto == 4: + w_8 = space.lt(w_ret_1, gi_0) + v9 = space.is_true(w_8) + if v9 == True: + goto = 5 + else: + assert v9 == False + w_ret_2 = w_ret_1 + goto = 6 + + if goto == 5: + w_10 = space.call_function(space.w_ValueError, gs___nonzero_____should_return____0) + w_etype, w_evalue = space.w_ValueError, w_10 + goto = 8 + + if goto == 6: + w_13 = space.gt(w_ret_2, gi_0) + w_4 = w_13 + goto = 9 + + if goto == 7: + w_14 = space.call_function(gcls_TypeError, gs___nonzero_____should_return_an_i) + w_etype, w_evalue = gcls_TypeError, w_14 + goto = 8 + + if goto == 8: + raise OperationError(w_etype, w_evalue) + + if goto == 9: + return w_4 + +fastf_instance___nonzero__ = __nonzero__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__call__' +## firstlineno 489 +##SECTION## +# global declaration +# global object gs__s_instance_has_no___call___meth + +def __call__(space, __args__): + funcname = "__call__" + signature = ['self'], 'args', 'kwds' + defaults_w = [] + w_self, w_args, w_kwds = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___call__(space, w_self, w_args, w_kwds) + +f_instance___call__ = __call__ + +def __call__(space, w_self, w_args, w_kwds): + + w_func=v2=w_self_1=w_5=w_6=w_7=w_etype=w_evalue=w_args_1=w_kwds_1=None + w_func_1=w_10=w_11=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___call__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_args_1, w_kwds_1, w_func_1 = w_args, w_kwds, w_func + goto = 3 + else: + assert v2 == False + w_self_1 = w_self + goto = 2 + + if goto == 2: + w_5 = space.getattr(w_self_1, gs___class__) + w_6 = space.getattr(w_5, gs___name__) + w_7 = space.mod(gs__s_instance_has_no___call___meth, w_6) + w_etype, w_evalue = gcls_AttributeError, w_7 + goto = 4 + + if goto == 3: + _args = Arguments.fromshape(space, (0, (), True, True), [w_args_1, w_kwds_1]) + w_10 = space.call_args(w_func_1, _args) + w_11 = w_10 + goto = 5 + + if goto == 4: + raise OperationError(w_etype, w_evalue) + + if goto == 5: + return w_11 + +fastf_instance___call__ = __call__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__iter__' +## firstlineno 509 +##SECTION## +# global declarations +# global object gs___iter___returned_non_iterator_o +# global object gs_iteration_over_non_sequence +# global object gfunc_seqiter + +def __iter__(space, __args__): + funcname = "__iter__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___iter__(space, w_self) + +f_instance___iter__ = __iter__ + +def __iter__(space, w_self): + + w_func=v2=w_self_1=w_func_2=v12=w_etype=w_evalue=w_func_3=w_13=None + w_6=w_func_1=w_ret=w_4=v5=w_ret_1=w_7=w_8=w_9=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iter__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_func_1 = w_func + goto = 2 + else: + assert v2 == False + w_self_1 = w_self + goto = 4 + + if goto == 2: + w_ret = space.call_function(w_func_1, ) + w_4 = fastf_mro_lookup(space, w_ret, gs_next) + v5 = space.is_true(w_4) + if v5 == True: + w_6 = w_ret + goto = 7 + else: + assert v5 == False + w_ret_1 = w_ret + goto = 3 + + if goto == 3: + w_7 = space.call_function(space.w_type, w_ret_1) + w_8 = space.getattr(w_7, gs___name__) + w_9 = space.mod(gs___iter___returned_non_iterator_o, w_8) + w_etype, w_evalue = gcls_TypeError, w_9 + goto = 6 + + if goto == 4: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___getitem__, space.w_False) + v12 = space.is_true(w_func_2) + if v12 == True: + w_func_3 = w_func_2 + goto = 5 + else: + assert v12 == False + (w_etype, w_evalue) = (gcls_TypeError, + gs_iteration_over_non_sequence) + goto = 6 + + if goto == 5: + w_13 = fastf_seqiter(space, w_func_3) + w_6 = w_13 + goto = 7 + + if goto == 6: + raise OperationError(w_etype, w_evalue) + + if goto == 7: + return w_6 + +fastf_instance___iter__ = __iter__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'next' +## firstlineno 524 +##SECTION## +# global declaration +# global object gs_instance_has_no_next___method + +def next(space, __args__): + funcname = "next" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance_next(space, w_self) + +f_instance_next = next + +def next(space, w_self): + + w_func=v2=w_etype=w_evalue=w_func_1=w_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs_next, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_func_1 = w_func + goto = 2 + else: + assert v2 == False + (w_etype, w_evalue) = (gcls_TypeError, + gs_instance_has_no_next___method) + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, ) + w_6 = w_5 + goto = 4 + + if goto == 3: + raise OperationError(w_etype, w_evalue) + + if goto == 4: + return w_6 + +fastf_instance_next = next + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function '__cmp__' +## firstlineno 530 +##SECTION## +# global declarations +# global object gs___cmp___must_return_int +# global object gi_minus_1 + +def __cmp__(space, __args__): + funcname = "__cmp__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___cmp__(space, w_self, w_other) + +f_instance___cmp__ = __cmp__ + +def __cmp__(space, w_self, w_other): + + w_coerced=w_3=v4=w_coerced_1=w_v_1=w_w_1=w_7=v8=w_v_3=w_w_3=w_10=None + v11=w_w_2=w_v_2=w_9=v12=w_w=w_v=w_15=v16=w_w_6=w_v_6=w_28=v29=None + w_14=w_v_7=w_func_2=v30=w_v_8=w_func_3=w_res_3=w_31=v32=w_etype=None + w_evalue=w_res_4=w_33=v34=w_res_5=w_35=v36=w_w_5=w_v_5=w_func=None + v18=w_w_7=w_func_1=w_res=w_20=v21=w_res_1=w_24=v25=w_res_2=w_26=None + v27=w_w_4=w_v_4=w_13=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_w, w_v = w_other, w_self + goto = 6 + else: + assert v4 == False + w_coerced_1 = w_coerced + goto = 2 + + if goto == 2: + w_v_1 = space.getitem(w_coerced_1, gi_0) + w_w_1 = space.getitem(w_coerced_1, gi_1) + w_7 = space.isinstance(w_v_1, gcls_instance) + v8 = space.is_true(w_7) + if v8 == True: + w_w_2, w_v_2, w_9 = w_w_1, w_v_1, space.w_False + goto = 4 + else: + assert v8 == False + w_v_3, w_w_3 = w_v_1, w_w_1 + goto = 3 + + if goto == 3: + w_10 = space.isinstance(w_w_3, gcls_instance) + v11 = space.is_true(w_10) + if v11 == True: + w_w_2, w_v_2, w_9 = w_w_3, w_v_3, space.w_False + goto = 4 + else: + assert v11 == False + w_w_2, w_v_2, w_9 = w_w_3, w_v_3, space.w_True + goto = 4 + + if goto == 4: + v12 = space.is_true(w_9) + if v12 == True: + w_w_4, w_v_4 = w_w_2, w_v_2 + goto = 5 + else: + assert v12 == False + w_w, w_v = w_w_2, w_v_2 + goto = 6 + + if goto == 5: + w_13 = space.cmp(w_v_4, w_w_4) + w_14 = w_13 + goto = 17 + + if goto == 6: + w_15 = space.isinstance(w_v, gcls_instance) + v16 = space.is_true(w_15) + if v16 == True: + w_w_5, w_v_5 = w_w, w_v + goto = 7 + else: + assert v16 == False + w_w_6, w_v_6 = w_w, w_v + goto = 11 + + if goto == 7: + w_func = space.call_function(gfunc_instance_getattr1, w_v_5, gs___cmp__, space.w_False) + v18 = space.is_true(w_func) + if v18 == True: + w_w_7, w_func_1 = w_w_5, w_func + goto = 8 + else: + assert v18 == False + w_w_6, w_v_6 = w_w_5, w_v_5 + goto = 11 + + if goto == 8: + w_res = space.call_function(w_func_1, w_w_7) + w_20 = space.isinstance(w_res, space.w_int) + v21 = space.is_true(w_20) + if v21 == True: + w_res_1 = w_res + goto = 9 + else: + assert v21 == False + w_etype, w_evalue = gcls_TypeError, gs___cmp___must_return_int + goto = 16 + + if goto == 9: + w_24 = space.gt(w_res_1, gi_0) + v25 = space.is_true(w_24) + if v25 == True: + w_14 = gi_1 + goto = 17 + else: + assert v25 == False + w_res_2 = w_res_1 + goto = 10 + + if goto == 10: + w_26 = space.lt(w_res_2, gi_0) + v27 = space.is_true(w_26) + if v27 == True: + w_14 = gi_minus_1 + goto = 17 + else: + assert v27 == False + w_14 = gi_0 + goto = 17 + + if goto == 11: + w_28 = space.isinstance(w_w_6, gcls_instance) + v29 = space.is_true(w_28) + if v29 == True: + w_v_7 = w_v_6 + goto = 12 + else: + assert v29 == False + w_14 = space.w_NotImplemented + goto = 17 + + if goto == 12: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_v_7, gs___cmp__, space.w_False) + v30 = space.is_true(w_func_2) + if v30 == True: + w_v_8, w_func_3 = w_v_7, w_func_2 + goto = 13 + else: + assert v30 == False + w_14 = space.w_NotImplemented + goto = 17 + + if goto == 13: + w_res_3 = space.call_function(w_func_3, w_v_8) + w_31 = space.isinstance(w_res_3, space.w_int) + v32 = space.is_true(w_31) + if v32 == True: + w_res_4 = w_res_3 + goto = 14 + else: + assert v32 == False + w_etype, w_evalue = gcls_TypeError, gs___cmp___must_return_int + goto = 16 + + if goto == 14: + w_33 = space.gt(w_res_4, gi_0) + v34 = space.is_true(w_33) + if v34 == True: + w_14 = gi_1 + goto = 17 + else: + assert v34 == False + w_res_5 = w_res_4 + goto = 15 + + if goto == 15: + w_35 = space.lt(w_res_5, gi_0) + v36 = space.is_true(w_35) + if v36 == True: + w_14 = gi_minus_1 + goto = 17 + else: + assert v36 == False + w_14 = gi_0 + goto = 17 + + if goto == 16: + raise OperationError(w_etype, w_evalue) + + if goto == 17: + return w_14 + +fastf_instance___cmp__ = __cmp__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## function 'purify' +## firstlineno 568 +##SECTION## +# global declarations +# global object g3tuple +# global object gcls_classobj +# global object gs___module__ +# global object gs__classobj +# global object gs___new__ +# global object gsm___new__ +# global object gfunc___new__ +# global object gs___slots__ +# global object g3tuple_1 +# global object gs__name +# global object gs__bases +# global object gs___dict__ +# global object gs_classobj +# global object gcls_instance +# global object gsm___new___1 +# global object gfunc___new___1 +# global object g2tuple +# global object gs__class +# global object gs_instance +# global object gfunc_purify + +def purify(space, __args__): + funcname = "purify" + signature = [], None, None + defaults_w = [] + __args__.parse(funcname, signature, defaults_w) + return fastf_purify(space) + +f_purify = purify + +def purify(space): + + w_0=w_1=w_2=w_3=w_4=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.delattr(gcls_classobj, gs__name) + w_1 = space.delattr(gcls_classobj, gs__bases) + w_2 = space.delattr(gcls_classobj, gs___slots__) + w_3 = space.delattr(gcls_instance, gs__class) + w_4 = space.delattr(gcls_instance, gs___slots__) + w_5 = space.w_None + goto = 2 + + if goto == 2: + return w_5 + +fastf_purify = purify + +# global declarations +# global object gs___abs__ +# global object gfunc_instance___abs__ +# global object gs___add__ +# global object gfunc_instance___add__ +# global object gs___and__ +# global object gfunc_instance___and__ +# global object gs___call__ +# global object gfunc_instance___call__ +# global object gs___cmp__ +# global object gfunc_instance___cmp__ +# global object gs___coerce__ +# global object gfunc_instance___coerce__ +# global object gs___contains__ +# global object gfunc_instance___contains__ +# global object gs___delattr__ +# global object gfunc_instance___delattr__ +# global object gs___delitem__ +# global object gfunc_instance___delitem__ +# global object gs___div__ +# global object gfunc_instance___div__ +# global object gs___divmod__ +# global object gfunc_instance___divmod__ +# global object gs___eq__ +# global object gfunc_instance___eq__ +# global object gs___float__ +# global object gfunc_instance___float__ +# global object gs___floordiv__ +# global object gfunc_instance___floordiv__ +# global object gs___ge__ +# global object gfunc_instance___ge__ +# global object gs___getattribute__ +# global object gfunc_instance___getattribute__ +# global object gs___getitem__ +# global object gfunc_instance___getitem__ +# global object gs___gt__ +# global object gfunc_instance___gt__ +# global object gs___hash__ +# global object gfunc_instance___hash__ +# global object gs___hex__ +# global object gfunc_instance___hex__ +# global object gs___iadd__ +# global object gfunc_instance___iadd__ +# global object gs___iand__ +# global object gfunc_instance___iand__ +# global object gs___idiv__ +# global object gfunc_instance___idiv__ +# global object gs___ifloordiv__ +# global object gfunc_instance___ifloordiv__ +# global object gs___ilshift__ +# global object gfunc_instance___ilshift__ +# global object gs___imod__ +# global object gfunc_instance___imod__ +# global object gs___imul__ +# global object gfunc_instance___imul__ +# global object gs___int__ +# global object gfunc_instance___int__ +# global object gs___invert__ +# global object gfunc_instance___invert__ +# global object gs___ior__ +# global object gfunc_instance___ior__ +# global object gs___ipow__ +# global object gfunc_instance___ipow__ +# global object gs___irshift__ +# global object gfunc_instance___irshift__ +# global object gs___isub__ +# global object gfunc_instance___isub__ +# global object gs___iter__ +# global object gfunc_instance___iter__ +# global object gs___itruediv__ +# global object gfunc_instance___itruediv__ +# global object gs___ixor__ +# global object gfunc_instance___ixor__ +# global object gs___le__ +# global object gfunc_instance___le__ +# global object gs___len__ +# global object gfunc_instance___len__ +# global object gs___long__ +# global object gfunc_instance___long__ +# global object gs___lshift__ +# global object gfunc_instance___lshift__ +# global object gs___lt__ +# global object gfunc_instance___lt__ +# global object gs___mod__ +# global object gfunc_instance___mod__ +# global object gs___mul__ +# global object gfunc_instance___mul__ +# global object gs___ne__ +# global object gfunc_instance___ne__ +# global object gs___neg__ +# global object gfunc_instance___neg__ +# global object gs___nonzero__ +# global object gfunc_instance___nonzero__ +# global object gs___oct__ +# global object gfunc_instance___oct__ +# global object gs___or__ +# global object gfunc_instance___or__ +# global object gs___pos__ +# global object gfunc_instance___pos__ +# global object gs___pow__ +# global object gfunc_instance___pow__ +# global object gs___radd__ +# global object gfunc_instance___radd__ +# global object gs___rand__ +# global object gfunc_instance___rand__ +# global object gs___rdiv__ +# global object gfunc_instance___rdiv__ +# global object gs___rdivmod__ +# global object gfunc_instance___rdivmod__ +# global object gs___repr__ +# global object gfunc_instance___repr__ +# global object gs___rfloordiv__ +# global object gfunc_instance___rfloordiv__ +# global object gs___rlshift__ +# global object gfunc_instance___rlshift__ +# global object gs___rmod__ +# global object gfunc_instance___rmod__ +# global object gs___rmul__ +# global object gfunc_instance___rmul__ +# global object gs___ror__ +# global object gfunc_instance___ror__ +# global object gs___rpow__ +# global object gfunc_instance___rpow__ +# global object gs___rrshift__ +# global object gfunc_instance___rrshift__ +# global object gs___rshift__ +# global object gfunc_instance___rshift__ +# global object gs___rsub__ +# global object gfunc_instance___rsub__ +# global object gs___rtruediv__ +# global object gfunc_instance___rtruediv__ +# global object gs___rxor__ +# global object gfunc_instance___rxor__ +# global object gs___setattr__ +# global object gfunc_instance___setattr__ +# global object gs___setitem__ +# global object gfunc_instance___setitem__ +# global object gs___str__ +# global object gfunc_instance___str__ +# global object gs___sub__ +# global object gfunc_instance___sub__ +# global object gs___truediv__ +# global object gfunc_instance___truediv__ +# global object gs___xor__ +# global object gfunc_instance___xor__ +# global object gs_next +# global object gfunc_instance_next +# global object gfunc_classobj___call__ +# global object gfunc_classobj___delattr__ +# global object gfunc_classobj___getattribute__ +# global object gfunc_classobj___repr__ +# global object gfunc_classobj___setattr__ +# global object gfunc_classobj___str__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__abs__' +## firstlineno 4 +##SECTION## +def __abs__(space, __args__): + funcname = "__abs__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___abs__(space, w_self) + +f_instance___abs__ = __abs__ + +def __abs__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___abs__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___abs__ = __abs__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__add__' +## firstlineno 4 +##SECTION## +def __add__(space, __args__): + funcname = "__add__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___add__(space, w_self, w_other) + +f_instance___add__ = __add__ + +def __add__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___add__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.add(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___add__ = __add__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__and__' +## firstlineno 4 +##SECTION## +def __and__(space, __args__): + funcname = "__and__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___and__(space, w_self, w_other) + +f_instance___and__ = __and__ + +def __and__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___and__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.and_(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___and__ = __and__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__div__' +## firstlineno 4 +##SECTION## +def __div__(space, __args__): + funcname = "__div__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___div__(space, w_self, w_other) + +f_instance___div__ = __div__ + +def __div__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___div__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.div(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___div__ = __div__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__divmod__' +## firstlineno 4 +##SECTION## +def __divmod__(space, __args__): + funcname = "__divmod__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___divmod__(space, w_self, w_other) + +f_instance___divmod__ = __divmod__ + +def __divmod__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___divmod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.divmod(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___divmod__ = __divmod__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__eq__' +## firstlineno 4 +##SECTION## +def __eq__(space, __args__): + funcname = "__eq__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___eq__(space, w_self, w_other) + +f_instance___eq__ = __eq__ + +def __eq__(space, w_self, w_other): + + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___eq__) + w_other_1, w_3 = w_other, w_0 + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 2: + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 3: + w_9 = space.issubtype(w_10, gcls_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 + + if goto == 4: + w_16 = space.is_(w_6, gcls_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___eq__ = __eq__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__float__' +## firstlineno 4 +##SECTION## +def __float__(space, __args__): + funcname = "__float__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___float__(space, w_self) + +f_instance___float__ = __float__ + +def __float__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___float__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___float__ = __float__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__floordiv__' +## firstlineno 4 +##SECTION## +def __floordiv__(space, __args__): + funcname = "__floordiv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___floordiv__(space, w_self, w_other) + +f_instance___floordiv__ = __floordiv__ + +def __floordiv__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___floordiv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.floordiv(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___floordiv__ = __floordiv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ge__' +## firstlineno 4 +##SECTION## +def __ge__(space, __args__): + funcname = "__ge__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ge__(space, w_self, w_other) + +f_instance___ge__ = __ge__ + +def __ge__(space, w_self, w_other): + + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___ge__) + w_other_1, w_3 = w_other, w_0 + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 2: + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 3: + w_9 = space.issubtype(w_10, gcls_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 + + if goto == 4: + w_16 = space.is_(w_6, gcls_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___ge__ = __ge__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__gt__' +## firstlineno 4 +##SECTION## +def __gt__(space, __args__): + funcname = "__gt__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___gt__(space, w_self, w_other) + +f_instance___gt__ = __gt__ + +def __gt__(space, w_self, w_other): + + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___gt__) + w_other_1, w_3 = w_other, w_0 + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 2: + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 3: + w_9 = space.issubtype(w_10, gcls_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 + + if goto == 4: + w_16 = space.is_(w_6, gcls_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___gt__ = __gt__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__hex__' +## firstlineno 4 +##SECTION## +def __hex__(space, __args__): + funcname = "__hex__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___hex__(space, w_self) + +f_instance___hex__ = __hex__ + +def __hex__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___hex__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___hex__ = __hex__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__iadd__' +## firstlineno 4 +##SECTION## +def __iadd__(space, __args__): + funcname = "__iadd__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___iadd__(space, w_self, w_other) + +f_instance___iadd__ = __iadd__ + +def __iadd__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iadd__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___iadd__ = __iadd__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__iand__' +## firstlineno 4 +##SECTION## +def __iand__(space, __args__): + funcname = "__iand__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___iand__(space, w_self, w_other) + +f_instance___iand__ = __iand__ + +def __iand__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iand__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___iand__ = __iand__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__idiv__' +## firstlineno 4 +##SECTION## +def __idiv__(space, __args__): + funcname = "__idiv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___idiv__(space, w_self, w_other) + +f_instance___idiv__ = __idiv__ + +def __idiv__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___idiv__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___idiv__ = __idiv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ifloordiv__' +## firstlineno 4 +##SECTION## +def __ifloordiv__(space, __args__): + funcname = "__ifloordiv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ifloordiv__(space, w_self, w_other) + +f_instance___ifloordiv__ = __ifloordiv__ + +def __ifloordiv__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ifloordiv__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___ifloordiv__ = __ifloordiv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ilshift__' +## firstlineno 4 +##SECTION## +def __ilshift__(space, __args__): + funcname = "__ilshift__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ilshift__(space, w_self, w_other) + +f_instance___ilshift__ = __ilshift__ + +def __ilshift__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ilshift__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___ilshift__ = __ilshift__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__imod__' +## firstlineno 4 +##SECTION## +def __imod__(space, __args__): + funcname = "__imod__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___imod__(space, w_self, w_other) + +f_instance___imod__ = __imod__ + +def __imod__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___imod__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___imod__ = __imod__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__imul__' +## firstlineno 4 +##SECTION## +def __imul__(space, __args__): + funcname = "__imul__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___imul__(space, w_self, w_other) + +f_instance___imul__ = __imul__ + +def __imul__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___imul__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___imul__ = __imul__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__int__' +## firstlineno 4 +##SECTION## +def __int__(space, __args__): + funcname = "__int__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___int__(space, w_self) + +f_instance___int__ = __int__ + +def __int__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___int__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___int__ = __int__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__invert__' +## firstlineno 4 +##SECTION## +def __invert__(space, __args__): + funcname = "__invert__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___invert__(space, w_self) + +f_instance___invert__ = __invert__ + +def __invert__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___invert__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___invert__ = __invert__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ior__' +## firstlineno 4 +##SECTION## +def __ior__(space, __args__): + funcname = "__ior__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ior__(space, w_self, w_other) + +f_instance___ior__ = __ior__ + +def __ior__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ior__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___ior__ = __ior__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ipow__' +## firstlineno 4 +##SECTION## +def __ipow__(space, __args__): + funcname = "__ipow__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ipow__(space, w_self, w_other) + +f_instance___ipow__ = __ipow__ + +def __ipow__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ipow__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___ipow__ = __ipow__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__irshift__' +## firstlineno 4 +##SECTION## +def __irshift__(space, __args__): + funcname = "__irshift__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___irshift__(space, w_self, w_other) + +f_instance___irshift__ = __irshift__ + +def __irshift__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___irshift__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___irshift__ = __irshift__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__isub__' +## firstlineno 4 +##SECTION## +def __isub__(space, __args__): + funcname = "__isub__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___isub__(space, w_self, w_other) + +f_instance___isub__ = __isub__ + +def __isub__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___isub__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___isub__ = __isub__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__itruediv__' +## firstlineno 4 +##SECTION## +def __itruediv__(space, __args__): + funcname = "__itruediv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___itruediv__(space, w_self, w_other) + +f_instance___itruediv__ = __itruediv__ + +def __itruediv__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___itruediv__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___itruediv__ = __itruediv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ixor__' +## firstlineno 4 +##SECTION## +def __ixor__(space, __args__): + funcname = "__ixor__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ixor__(space, w_self, w_other) + +f_instance___ixor__ = __ixor__ + +def __ixor__(space, w_self, w_other): + + w_func=v2=w_4=w_other_1=w_func_1=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ixor__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 + + if goto == 3: + return w_4 + +fastf_instance___ixor__ = __ixor__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__le__' +## firstlineno 4 +##SECTION## +def __le__(space, __args__): + funcname = "__le__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___le__(space, w_self, w_other) + +f_instance___le__ = __le__ + +def __le__(space, w_self, w_other): + + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___le__) + w_other_1, w_3 = w_other, w_0 + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 2: + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 3: + w_9 = space.issubtype(w_10, gcls_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 + + if goto == 4: + w_16 = space.is_(w_6, gcls_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___le__ = __le__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__long__' +## firstlineno 4 +##SECTION## +def __long__(space, __args__): + funcname = "__long__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___long__(space, w_self) + +f_instance___long__ = __long__ + +def __long__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___long__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___long__ = __long__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__lshift__' +## firstlineno 4 +##SECTION## +def __lshift__(space, __args__): + funcname = "__lshift__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___lshift__(space, w_self, w_other) + +f_instance___lshift__ = __lshift__ + +def __lshift__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___lshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.lshift(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___lshift__ = __lshift__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__lt__' +## firstlineno 4 +##SECTION## +def __lt__(space, __args__): + funcname = "__lt__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___lt__(space, w_self, w_other) + +f_instance___lt__ = __lt__ + +def __lt__(space, w_self, w_other): + + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___lt__) + w_other_1, w_3 = w_other, w_0 + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 2: + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 3: + w_9 = space.issubtype(w_10, gcls_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 + + if goto == 4: + w_16 = space.is_(w_6, gcls_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___lt__ = __lt__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__mod__' +## firstlineno 4 +##SECTION## +def __mod__(space, __args__): + funcname = "__mod__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___mod__(space, w_self, w_other) + +f_instance___mod__ = __mod__ + +def __mod__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___mod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.mod(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___mod__ = __mod__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__mul__' +## firstlineno 4 +##SECTION## +def __mul__(space, __args__): + funcname = "__mul__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___mul__(space, w_self, w_other) + +f_instance___mul__ = __mul__ + +def __mul__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___mul__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.mul(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___mul__ = __mul__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ne__' +## firstlineno 4 +##SECTION## +def __ne__(space, __args__): + funcname = "__ne__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ne__(space, w_self, w_other) + +f_instance___ne__ = __ne__ + +def __ne__(space, w_self, w_other): + + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None + + goto = 1 # startblock + while True: + + if goto == 1: + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___ne__) + w_other_1, w_3 = w_other, w_0 + goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 2: + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen + + if goto == 3: + w_9 = space.issubtype(w_10, gcls_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 + + if goto == 4: + w_16 = space.is_(w_6, gcls_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 + else: + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___ne__ = __ne__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__neg__' +## firstlineno 4 +##SECTION## +def __neg__(space, __args__): + funcname = "__neg__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___neg__(space, w_self) + +f_instance___neg__ = __neg__ + +def __neg__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___neg__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___neg__ = __neg__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__oct__' +## firstlineno 4 +##SECTION## +def __oct__(space, __args__): + funcname = "__oct__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___oct__(space, w_self) + +f_instance___oct__ = __oct__ + +def __oct__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___oct__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___oct__ = __oct__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__or__' +## firstlineno 4 +##SECTION## +def __or__(space, __args__): + funcname = "__or__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___or__(space, w_self, w_other) + +f_instance___or__ = __or__ + +def __or__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___or__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.or_(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___or__ = __or__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__pos__' +## firstlineno 4 +##SECTION## +def __pos__(space, __args__): + funcname = "__pos__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___pos__(space, w_self) + +f_instance___pos__ = __pos__ + +def __pos__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___pos__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___pos__ = __pos__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rshift__' +## firstlineno 4 +##SECTION## +def __rshift__(space, __args__): + funcname = "__rshift__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rshift__(space, w_self, w_other) + +f_instance___rshift__ = __rshift__ + +def __rshift__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.rshift(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rshift__ = __rshift__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__sub__' +## firstlineno 4 +##SECTION## +def __sub__(space, __args__): + funcname = "__sub__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___sub__(space, w_self, w_other) + +f_instance___sub__ = __sub__ + +def __sub__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___sub__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.sub(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___sub__ = __sub__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__truediv__' +## firstlineno 4 +##SECTION## +def __truediv__(space, __args__): + funcname = "__truediv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___truediv__(space, w_self, w_other) + +f_instance___truediv__ = __truediv__ + +def __truediv__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___truediv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.truediv(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___truediv__ = __truediv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__xor__' +## firstlineno 4 +##SECTION## +# global declaration +# global object gfunc__coerce + +def __xor__(space, __args__): + funcname = "__xor__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___xor__(space, w_self, w_other) + +f_instance___xor__ = __xor__ + +def __xor__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___xor__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.xor(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___xor__ = __xor__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__radd__' +## firstlineno 14 +##SECTION## +def __radd__(space, __args__): + funcname = "__radd__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___radd__(space, w_self, w_other) + +f_instance___radd__ = __radd__ + +def __radd__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___radd__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.add(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___radd__ = __radd__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rand__' +## firstlineno 14 +##SECTION## +def __rand__(space, __args__): + funcname = "__rand__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rand__(space, w_self, w_other) + +f_instance___rand__ = __rand__ + +def __rand__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rand__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.and_(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rand__ = __rand__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rdiv__' +## firstlineno 14 +##SECTION## +def __rdiv__(space, __args__): + funcname = "__rdiv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rdiv__(space, w_self, w_other) + +f_instance___rdiv__ = __rdiv__ + +def __rdiv__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rdiv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.div(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rdiv__ = __rdiv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rdivmod__' +## firstlineno 14 +##SECTION## +def __rdivmod__(space, __args__): + funcname = "__rdivmod__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rdivmod__(space, w_self, w_other) + +f_instance___rdivmod__ = __rdivmod__ + +def __rdivmod__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rdivmod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.divmod(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rdivmod__ = __rdivmod__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rfloordiv__' +## firstlineno 14 +##SECTION## +def __rfloordiv__(space, __args__): + funcname = "__rfloordiv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rfloordiv__(space, w_self, w_other) + +f_instance___rfloordiv__ = __rfloordiv__ + +def __rfloordiv__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rfloordiv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.floordiv(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rfloordiv__ = __rfloordiv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rlshift__' +## firstlineno 14 +##SECTION## +def __rlshift__(space, __args__): + funcname = "__rlshift__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rlshift__(space, w_self, w_other) + +f_instance___rlshift__ = __rlshift__ + +def __rlshift__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rlshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.lshift(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rlshift__ = __rlshift__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rmod__' +## firstlineno 14 +##SECTION## +def __rmod__(space, __args__): + funcname = "__rmod__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rmod__(space, w_self, w_other) + +f_instance___rmod__ = __rmod__ + +def __rmod__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rmod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.mod(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rmod__ = __rmod__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rmul__' +## firstlineno 14 +##SECTION## +def __rmul__(space, __args__): + funcname = "__rmul__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rmul__(space, w_self, w_other) + +f_instance___rmul__ = __rmul__ + +def __rmul__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rmul__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.mul(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rmul__ = __rmul__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__ror__' +## firstlineno 14 +##SECTION## +def __ror__(space, __args__): + funcname = "__ror__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ror__(space, w_self, w_other) + +f_instance___ror__ = __ror__ + +def __ror__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___ror__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.or_(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___ror__ = __ror__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rrshift__' +## firstlineno 14 +##SECTION## +def __rrshift__(space, __args__): + funcname = "__rrshift__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rrshift__(space, w_self, w_other) + +f_instance___rrshift__ = __rrshift__ + +def __rrshift__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rrshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.rshift(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rrshift__ = __rrshift__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rsub__' +## firstlineno 14 +##SECTION## +def __rsub__(space, __args__): + funcname = "__rsub__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rsub__(space, w_self, w_other) + +f_instance___rsub__ = __rsub__ + +def __rsub__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rsub__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.sub(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rsub__ = __rsub__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rtruediv__' +## firstlineno 14 +##SECTION## +def __rtruediv__(space, __args__): + funcname = "__rtruediv__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rtruediv__(space, w_self, w_other) + +f_instance___rtruediv__ = __rtruediv__ + +def __rtruediv__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rtruediv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.truediv(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rtruediv__ = __rtruediv__ + +##SECTION## +## filename '/u/pedronis/PyPy/dist/pypy/purify' +## function '__rxor__' +## firstlineno 14 +##SECTION## +def __rxor__(space, __args__): + funcname = "__rxor__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rxor__(space, w_self, w_other) + +f_instance___rxor__ = __rxor__ + +def __rxor__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rxor__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.xor(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rxor__ = __rxor__ + +##SECTION## +#************************************************************* + +def initclassobj(space): + """NOT_RPYTHON""" + class m: pass # fake module + m.__dict__ = globals() + # make sure that this function is run only once: + m.initclassobj = lambda *ign:True + + _dic = space.newdict([]) + m.gs___module__ = space.wrap('__module__') + m.gs__classobj = space.wrap('_classobj') + space.setitem(_dic, gs___module__, gs__classobj) + m.gs___new__ = space.wrap('__new__') + from pypy.interpreter.gateway import interp2app + m.gfunc___new__ = space.wrap(interp2app(f___new__)) + m.gsm___new__ = space.wrap(gfunc___new__) + space.setitem(_dic, gs___new__, gsm___new__) + m.gs___slots__ = space.wrap('__slots__') + m.gs__name = space.wrap('_name') + m.gs__bases = space.wrap('_bases') + m.gs___dict__ = space.wrap('__dict__') + m.g3tuple_1 = space.newtuple([gs__name, gs__bases, gs___dict__]) + space.setitem(_dic, gs___slots__, g3tuple_1) + m.gs_classobj = space.wrap('classobj') + _bases = space.newtuple([space.w_object]) + _args = space.newtuple([gs_classobj, _bases, _dic]) + m.gcls_classobj = space.call(space.w_type, _args) + _dic = space.newdict([]) + space.setitem(_dic, gs___module__, gs__classobj) + m.gfunc___new___1 = space.wrap(interp2app(f___new___1)) + m.gsm___new___1 = space.wrap(gfunc___new___1) + space.setitem(_dic, gs___new__, gsm___new___1) + m.gs__class = space.wrap('_class') + m.g2tuple = space.newtuple([gs__class, gs___dict__]) + space.setitem(_dic, gs___slots__, g2tuple) + m.gs_instance = space.wrap('instance') + _bases = space.newtuple([space.w_object]) + _args = space.newtuple([gs_instance, _bases, _dic]) + m.gcls_instance = space.call(space.w_type, _args) + m.gfunc_purify = space.wrap(interp2app(f_purify)) + m.g3tuple = space.newtuple([gcls_classobj, gcls_instance, gfunc_purify]) + del m.purify + m.gs___abs__ = space.wrap('__abs__') + m.gfunc_instance___abs__ = space.wrap(interp2app(f_instance___abs__)) + space.setattr(gcls_instance, gs___abs__, gfunc_instance___abs__) + m.gs___add__ = space.wrap('__add__') + m.gfunc_instance___add__ = space.wrap(interp2app(f_instance___add__)) + space.setattr(gcls_instance, gs___add__, gfunc_instance___add__) + m.gs___and__ = space.wrap('__and__') + m.gfunc_instance___and__ = space.wrap(interp2app(f_instance___and__)) + space.setattr(gcls_instance, gs___and__, gfunc_instance___and__) + m.gs___call__ = space.wrap('__call__') + m.gfunc_instance___call__ = space.wrap(interp2app(f_instance___call__)) + space.setattr(gcls_instance, gs___call__, gfunc_instance___call__) + m.gs___cmp__ = space.wrap('__cmp__') + m.gfunc_instance___cmp__ = space.wrap(interp2app(f_instance___cmp__)) + space.setattr(gcls_instance, gs___cmp__, gfunc_instance___cmp__) + m.gs___coerce__ = space.wrap('__coerce__') + m.gfunc_instance___coerce__ = space.wrap(interp2app(f_instance___coerce__)) + space.setattr(gcls_instance, gs___coerce__, gfunc_instance___coerce__) + m.gs___contains__ = space.wrap('__contains__') + m.gfunc_instance___contains__ = space.wrap(interp2app(f_instance___contains__)) + space.setattr(gcls_instance, gs___contains__, gfunc_instance___contains__) + m.gs___delattr__ = space.wrap('__delattr__') + m.gfunc_instance___delattr__ = space.wrap(interp2app(f_instance___delattr__)) + space.setattr(gcls_instance, gs___delattr__, gfunc_instance___delattr__) + m.gs___delitem__ = space.wrap('__delitem__') + m.gfunc_instance___delitem__ = space.wrap(interp2app(f_instance___delitem__)) + space.setattr(gcls_instance, gs___delitem__, gfunc_instance___delitem__) + m.gs___div__ = space.wrap('__div__') + m.gfunc_instance___div__ = space.wrap(interp2app(f_instance___div__)) + space.setattr(gcls_instance, gs___div__, gfunc_instance___div__) + m.gs___divmod__ = space.wrap('__divmod__') + m.gfunc_instance___divmod__ = space.wrap(interp2app(f_instance___divmod__)) + space.setattr(gcls_instance, gs___divmod__, gfunc_instance___divmod__) + m.gs___eq__ = space.wrap('__eq__') + m.gfunc_instance___eq__ = space.wrap(interp2app(f_instance___eq__)) + space.setattr(gcls_instance, gs___eq__, gfunc_instance___eq__) + m.gs___float__ = space.wrap('__float__') + m.gfunc_instance___float__ = space.wrap(interp2app(f_instance___float__)) + space.setattr(gcls_instance, gs___float__, gfunc_instance___float__) + m.gs___floordiv__ = space.wrap('__floordiv__') + m.gfunc_instance___floordiv__ = space.wrap(interp2app(f_instance___floordiv__)) + space.setattr(gcls_instance, gs___floordiv__, gfunc_instance___floordiv__) + m.gs___ge__ = space.wrap('__ge__') + m.gfunc_instance___ge__ = space.wrap(interp2app(f_instance___ge__)) + space.setattr(gcls_instance, gs___ge__, gfunc_instance___ge__) + m.gs___getattribute__ = space.wrap('__getattribute__') + m.gfunc_instance___getattribute__ = space.wrap(interp2app(f_instance___getattribute__)) + space.setattr(gcls_instance, gs___getattribute__, gfunc_instance___getattribute__) + m.gs___getitem__ = space.wrap('__getitem__') + m.gfunc_instance___getitem__ = space.wrap(interp2app(f_instance___getitem__)) + space.setattr(gcls_instance, gs___getitem__, gfunc_instance___getitem__) + m.gs___gt__ = space.wrap('__gt__') + m.gfunc_instance___gt__ = space.wrap(interp2app(f_instance___gt__)) + space.setattr(gcls_instance, gs___gt__, gfunc_instance___gt__) + m.gs___hash__ = space.wrap('__hash__') + m.gfunc_instance___hash__ = space.wrap(interp2app(f_instance___hash__)) + space.setattr(gcls_instance, gs___hash__, gfunc_instance___hash__) + m.gs___hex__ = space.wrap('__hex__') + m.gfunc_instance___hex__ = space.wrap(interp2app(f_instance___hex__)) + space.setattr(gcls_instance, gs___hex__, gfunc_instance___hex__) + m.gs___iadd__ = space.wrap('__iadd__') + m.gfunc_instance___iadd__ = space.wrap(interp2app(f_instance___iadd__)) + space.setattr(gcls_instance, gs___iadd__, gfunc_instance___iadd__) + m.gs___iand__ = space.wrap('__iand__') + m.gfunc_instance___iand__ = space.wrap(interp2app(f_instance___iand__)) + space.setattr(gcls_instance, gs___iand__, gfunc_instance___iand__) + m.gs___idiv__ = space.wrap('__idiv__') + m.gfunc_instance___idiv__ = space.wrap(interp2app(f_instance___idiv__)) + space.setattr(gcls_instance, gs___idiv__, gfunc_instance___idiv__) + m.gs___ifloordiv__ = space.wrap('__ifloordiv__') + m.gfunc_instance___ifloordiv__ = space.wrap(interp2app(f_instance___ifloordiv__)) + space.setattr(gcls_instance, gs___ifloordiv__, gfunc_instance___ifloordiv__) + m.gs___ilshift__ = space.wrap('__ilshift__') + m.gfunc_instance___ilshift__ = space.wrap(interp2app(f_instance___ilshift__)) + space.setattr(gcls_instance, gs___ilshift__, gfunc_instance___ilshift__) + m.gs___imod__ = space.wrap('__imod__') + m.gfunc_instance___imod__ = space.wrap(interp2app(f_instance___imod__)) + space.setattr(gcls_instance, gs___imod__, gfunc_instance___imod__) + m.gs___imul__ = space.wrap('__imul__') + m.gfunc_instance___imul__ = space.wrap(interp2app(f_instance___imul__)) + space.setattr(gcls_instance, gs___imul__, gfunc_instance___imul__) + m.gs___int__ = space.wrap('__int__') + m.gfunc_instance___int__ = space.wrap(interp2app(f_instance___int__)) + space.setattr(gcls_instance, gs___int__, gfunc_instance___int__) + m.gs___invert__ = space.wrap('__invert__') + m.gfunc_instance___invert__ = space.wrap(interp2app(f_instance___invert__)) + space.setattr(gcls_instance, gs___invert__, gfunc_instance___invert__) + m.gs___ior__ = space.wrap('__ior__') + m.gfunc_instance___ior__ = space.wrap(interp2app(f_instance___ior__)) + space.setattr(gcls_instance, gs___ior__, gfunc_instance___ior__) + m.gs___ipow__ = space.wrap('__ipow__') + m.gfunc_instance___ipow__ = space.wrap(interp2app(f_instance___ipow__)) + space.setattr(gcls_instance, gs___ipow__, gfunc_instance___ipow__) + m.gs___irshift__ = space.wrap('__irshift__') + m.gfunc_instance___irshift__ = space.wrap(interp2app(f_instance___irshift__)) + space.setattr(gcls_instance, gs___irshift__, gfunc_instance___irshift__) + m.gs___isub__ = space.wrap('__isub__') + m.gfunc_instance___isub__ = space.wrap(interp2app(f_instance___isub__)) + space.setattr(gcls_instance, gs___isub__, gfunc_instance___isub__) + m.gs___iter__ = space.wrap('__iter__') + m.gfunc_instance___iter__ = space.wrap(interp2app(f_instance___iter__)) + space.setattr(gcls_instance, gs___iter__, gfunc_instance___iter__) + m.gs___itruediv__ = space.wrap('__itruediv__') + m.gfunc_instance___itruediv__ = space.wrap(interp2app(f_instance___itruediv__)) + space.setattr(gcls_instance, gs___itruediv__, gfunc_instance___itruediv__) + m.gs___ixor__ = space.wrap('__ixor__') + m.gfunc_instance___ixor__ = space.wrap(interp2app(f_instance___ixor__)) + space.setattr(gcls_instance, gs___ixor__, gfunc_instance___ixor__) + m.gs___le__ = space.wrap('__le__') + m.gfunc_instance___le__ = space.wrap(interp2app(f_instance___le__)) + space.setattr(gcls_instance, gs___le__, gfunc_instance___le__) + m.gs___len__ = space.wrap('__len__') + m.gfunc_instance___len__ = space.wrap(interp2app(f_instance___len__)) + space.setattr(gcls_instance, gs___len__, gfunc_instance___len__) + m.gs___long__ = space.wrap('__long__') + m.gfunc_instance___long__ = space.wrap(interp2app(f_instance___long__)) + space.setattr(gcls_instance, gs___long__, gfunc_instance___long__) + m.gs___lshift__ = space.wrap('__lshift__') + m.gfunc_instance___lshift__ = space.wrap(interp2app(f_instance___lshift__)) + space.setattr(gcls_instance, gs___lshift__, gfunc_instance___lshift__) + m.gs___lt__ = space.wrap('__lt__') + m.gfunc_instance___lt__ = space.wrap(interp2app(f_instance___lt__)) + space.setattr(gcls_instance, gs___lt__, gfunc_instance___lt__) + m.gs___mod__ = space.wrap('__mod__') + m.gfunc_instance___mod__ = space.wrap(interp2app(f_instance___mod__)) + space.setattr(gcls_instance, gs___mod__, gfunc_instance___mod__) + m.gs___mul__ = space.wrap('__mul__') + m.gfunc_instance___mul__ = space.wrap(interp2app(f_instance___mul__)) + space.setattr(gcls_instance, gs___mul__, gfunc_instance___mul__) + m.gs___ne__ = space.wrap('__ne__') + m.gfunc_instance___ne__ = space.wrap(interp2app(f_instance___ne__)) + space.setattr(gcls_instance, gs___ne__, gfunc_instance___ne__) + m.gs___neg__ = space.wrap('__neg__') + m.gfunc_instance___neg__ = space.wrap(interp2app(f_instance___neg__)) + space.setattr(gcls_instance, gs___neg__, gfunc_instance___neg__) + m.gs___nonzero__ = space.wrap('__nonzero__') + m.gfunc_instance___nonzero__ = space.wrap(interp2app(f_instance___nonzero__)) + space.setattr(gcls_instance, gs___nonzero__, gfunc_instance___nonzero__) + m.gs___oct__ = space.wrap('__oct__') + m.gfunc_instance___oct__ = space.wrap(interp2app(f_instance___oct__)) + space.setattr(gcls_instance, gs___oct__, gfunc_instance___oct__) + m.gs___or__ = space.wrap('__or__') + m.gfunc_instance___or__ = space.wrap(interp2app(f_instance___or__)) + space.setattr(gcls_instance, gs___or__, gfunc_instance___or__) + m.gs___pos__ = space.wrap('__pos__') + m.gfunc_instance___pos__ = space.wrap(interp2app(f_instance___pos__)) + space.setattr(gcls_instance, gs___pos__, gfunc_instance___pos__) + m.gs___pow__ = space.wrap('__pow__') + m.gfunc_instance___pow__ = space.wrap(interp2app(f_instance___pow__)) + space.setattr(gcls_instance, gs___pow__, gfunc_instance___pow__) + m.gs___radd__ = space.wrap('__radd__') + m.gfunc_instance___radd__ = space.wrap(interp2app(f_instance___radd__)) + space.setattr(gcls_instance, gs___radd__, gfunc_instance___radd__) + m.gs___rand__ = space.wrap('__rand__') + m.gfunc_instance___rand__ = space.wrap(interp2app(f_instance___rand__)) + space.setattr(gcls_instance, gs___rand__, gfunc_instance___rand__) + m.gs___rdiv__ = space.wrap('__rdiv__') + m.gfunc_instance___rdiv__ = space.wrap(interp2app(f_instance___rdiv__)) + space.setattr(gcls_instance, gs___rdiv__, gfunc_instance___rdiv__) + m.gs___rdivmod__ = space.wrap('__rdivmod__') + m.gfunc_instance___rdivmod__ = space.wrap(interp2app(f_instance___rdivmod__)) + space.setattr(gcls_instance, gs___rdivmod__, gfunc_instance___rdivmod__) + m.gs___repr__ = space.wrap('__repr__') + m.gfunc_instance___repr__ = space.wrap(interp2app(f_instance___repr__)) + space.setattr(gcls_instance, gs___repr__, gfunc_instance___repr__) + m.gs___rfloordiv__ = space.wrap('__rfloordiv__') + m.gfunc_instance___rfloordiv__ = space.wrap(interp2app(f_instance___rfloordiv__)) + space.setattr(gcls_instance, gs___rfloordiv__, gfunc_instance___rfloordiv__) + m.gs___rlshift__ = space.wrap('__rlshift__') + m.gfunc_instance___rlshift__ = space.wrap(interp2app(f_instance___rlshift__)) + space.setattr(gcls_instance, gs___rlshift__, gfunc_instance___rlshift__) + m.gs___rmod__ = space.wrap('__rmod__') + m.gfunc_instance___rmod__ = space.wrap(interp2app(f_instance___rmod__)) + space.setattr(gcls_instance, gs___rmod__, gfunc_instance___rmod__) + m.gs___rmul__ = space.wrap('__rmul__') + m.gfunc_instance___rmul__ = space.wrap(interp2app(f_instance___rmul__)) + space.setattr(gcls_instance, gs___rmul__, gfunc_instance___rmul__) + m.gs___ror__ = space.wrap('__ror__') + m.gfunc_instance___ror__ = space.wrap(interp2app(f_instance___ror__)) + space.setattr(gcls_instance, gs___ror__, gfunc_instance___ror__) + m.gs___rpow__ = space.wrap('__rpow__') + m.gfunc_instance___rpow__ = space.wrap(interp2app(f_instance___rpow__)) + space.setattr(gcls_instance, gs___rpow__, gfunc_instance___rpow__) + m.gs___rrshift__ = space.wrap('__rrshift__') + m.gfunc_instance___rrshift__ = space.wrap(interp2app(f_instance___rrshift__)) + space.setattr(gcls_instance, gs___rrshift__, gfunc_instance___rrshift__) + m.gs___rshift__ = space.wrap('__rshift__') + m.gfunc_instance___rshift__ = space.wrap(interp2app(f_instance___rshift__)) + space.setattr(gcls_instance, gs___rshift__, gfunc_instance___rshift__) + m.gs___rsub__ = space.wrap('__rsub__') + m.gfunc_instance___rsub__ = space.wrap(interp2app(f_instance___rsub__)) + space.setattr(gcls_instance, gs___rsub__, gfunc_instance___rsub__) + m.gs___rtruediv__ = space.wrap('__rtruediv__') + m.gfunc_instance___rtruediv__ = space.wrap(interp2app(f_instance___rtruediv__)) + space.setattr(gcls_instance, gs___rtruediv__, gfunc_instance___rtruediv__) + m.gs___rxor__ = space.wrap('__rxor__') + m.gfunc_instance___rxor__ = space.wrap(interp2app(f_instance___rxor__)) + space.setattr(gcls_instance, gs___rxor__, gfunc_instance___rxor__) + m.gs___setattr__ = space.wrap('__setattr__') + m.gfunc_instance___setattr__ = space.wrap(interp2app(f_instance___setattr__)) + space.setattr(gcls_instance, gs___setattr__, gfunc_instance___setattr__) + m.gs___setitem__ = space.wrap('__setitem__') + m.gfunc_instance___setitem__ = space.wrap(interp2app(f_instance___setitem__)) + space.setattr(gcls_instance, gs___setitem__, gfunc_instance___setitem__) + m.gs___str__ = space.wrap('__str__') + m.gfunc_instance___str__ = space.wrap(interp2app(f_instance___str__)) + space.setattr(gcls_instance, gs___str__, gfunc_instance___str__) + m.gs___sub__ = space.wrap('__sub__') + m.gfunc_instance___sub__ = space.wrap(interp2app(f_instance___sub__)) + space.setattr(gcls_instance, gs___sub__, gfunc_instance___sub__) + m.gs___truediv__ = space.wrap('__truediv__') + m.gfunc_instance___truediv__ = space.wrap(interp2app(f_instance___truediv__)) + space.setattr(gcls_instance, gs___truediv__, gfunc_instance___truediv__) + m.gs___xor__ = space.wrap('__xor__') + m.gfunc_instance___xor__ = space.wrap(interp2app(f_instance___xor__)) + space.setattr(gcls_instance, gs___xor__, gfunc_instance___xor__) + m.gs_next = space.wrap('next') + m.gfunc_instance_next = space.wrap(interp2app(f_instance_next)) + space.setattr(gcls_instance, gs_next, gfunc_instance_next) + m.gfunc_classobj___call__ = space.wrap(interp2app(f_classobj___call__)) + space.setattr(gcls_classobj, gs___call__, gfunc_classobj___call__) + m.gfunc_classobj___delattr__ = space.wrap(interp2app(f_classobj___delattr__)) + space.setattr(gcls_classobj, gs___delattr__, gfunc_classobj___delattr__) + m.gfunc_classobj___getattribute__ = space.wrap(interp2app(f_classobj___getattribute__)) + space.setattr(gcls_classobj, gs___getattribute__, gfunc_classobj___getattribute__) + m.gfunc_classobj___repr__ = space.wrap(interp2app(f_classobj___repr__)) + space.setattr(gcls_classobj, gs___repr__, gfunc_classobj___repr__) + m.gfunc_classobj___setattr__ = space.wrap(interp2app(f_classobj___setattr__)) + space.setattr(gcls_classobj, gs___setattr__, gfunc_classobj___setattr__) + m.gfunc_classobj___str__ = space.wrap(interp2app(f_classobj___str__)) + space.setattr(gcls_classobj, gs___str__, gfunc_classobj___str__) + m.gfunc_get_class_module = space.wrap(interp2app(f_get_class_module)) + m.gs__ = space.wrap('?') + m.gs___name__ = space.wrap('__name__') + m.gs__s__s = space.wrap('%s.%s') + del m.__str__ + m.gfunc_retrieve = space.wrap(interp2app(f_retrieve)) + m.gcls_Exception = space.wrap(Exception) + m.gcls_AttributeError = space.wrap(AttributeError) + del m.get_class_module + m.gdescriptor_object___getattribute__ = space.getattr(space.w_object, gs___getattribute__) + del m.retrieve + m.gfunc_set_name = space.wrap(interp2app(f_set_name)) + m.gs___bases__ = space.wrap('__bases__') + m.gfunc_set_bases = space.wrap(interp2app(f_set_bases)) + m.gfunc_set_dict = space.wrap(interp2app(f_set_dict)) + m.gdescriptor_object___setattr__ = space.getattr(space.w_object, gs___setattr__) + del m.__setattr__ + m.gcls_TypeError = space.wrap(TypeError) + m.gs___dict___must_be_a_dictionary_ob = space.wrap('__dict__ must be a dictionary object') + del m.set_dict + m.gs___bases___must_be_a_tuple_object = space.wrap('__bases__ must be a tuple object') + m.gs___bases___items_must_be_classes = space.wrap('__bases__ items must be classes') + m.gdescriptor_classobj__bases = space.getattr(gcls_classobj, gs__bases) + m.gs___set__ = space.wrap('__set__') + del m.set_bases + m.gs___name___must_be_a_string_object = space.wrap('__name__ must be a string object') + m.gdescriptor_classobj__name = space.getattr(gcls_classobj, gs__name) + del m.set_name + m.gfunc_uid = space.wrap(interp2app(f_uid)) + m.gs__class__s__s_at_0x_x_ = space.wrap('') + del m.__repr__ + m.gi_0 = space.newint(0) + m.glong_0xffffffffL = space.wrap(0xffffffffL) # XXX implement long! + m.gi_1 = space.newint(1) + del m.uid + m.gs___get__ = space.wrap('__get__') + m.gfunc_lookup = space.wrap(interp2app(f_lookup)) + m.gi_2 = space.newint(2) + m.gs_class__s_has_no_attribute__s = space.wrap('class %s has no attribute %s') + m.gfunc_mro_lookup = space.wrap(interp2app(f_mro_lookup)) + del m.__getattribute__ + m.gs___mro__ = space.wrap('__mro__') + del m.mro_lookup + m.g2tuple_1 = space.newtuple([space.w_None, space.w_None]) + del m.lookup + m.g3tuple_2 = space.newtuple([gs___name__, gs___bases__, gs___dict__]) + m.gdescriptor_object___delattr__ = space.getattr(space.w_object, gs___delattr__) + del m.__delattr__ + m.gbltinmethod___new__ = space.getattr(space.w_object, gs___new__) + m.gdescriptor_instance__class = space.getattr(gcls_instance, gs__class) + m.gfunc_instance_getattr1 = space.wrap(interp2app(f_instance_getattr1)) + m.gs___init__ = space.wrap('__init__') + m.gs___init_____should_return_None = space.wrap('__init__() should return None') + del m.__call__ + m.gs___class__ = space.wrap('__class__') + m.gs__s_instance_has_no_attribute__s = space.wrap('%s instance has no attribute %s') + del m.instance_getattr1 + m.gs_instance_has_no_next___method = space.wrap('instance has no next() method') + del m.next + m.gfunc__coerce = space.wrap(interp2app(f__coerce)) + del m.__xor__ + del m._coerce + del m.__truediv__ + del m.__sub__ + m.gs_step = space.wrap('step') + m.gs___setslice__ = space.wrap('__setslice__') + m.gs_start = space.wrap('start') + m.gs_stop = space.wrap('stop') + del m.__setitem__ + m.gs___dict___must_be_set_to_a_dictio = space.wrap('__dict__ must be set to a dictionary') + m.gs___class___must_be_set_to_a_class = space.wrap('__class__ must be set to a class') + del m.__rxor__ + del m.__rtruediv__ + del m.__rsub__ + del m.__rshift__ + del m.__rrshift__ + del m.__rpow__ + del m.__ror__ + del m.__rmul__ + del m.__rmod__ + del m.__rlshift__ + del m.__rfloordiv__ + m.gs___s__s_instance_at_0x_x_ = space.wrap('<%s.%s instance at 0x%x>') + del m.__rdivmod__ + del m.__rdiv__ + del m.__rand__ + del m.__radd__ + del m.__pow__ + del m.__pos__ + del m.__or__ + del m.__oct__ + m.gs___nonzero_____should_return____0 = space.wrap('__nonzero__() should return >= 0') + m.gs___nonzero_____should_return_an_i = space.wrap('__nonzero__() should return an int') + del m.__nonzero__ + del m.__neg__ + del m.__ne__ + del m.__mul__ + del m.__mod__ + del m.__lt__ + del m.__lshift__ + del m.__long__ + m.gs___len_____should_return____0 = space.wrap('__len__() should return >= 0') + m.gs___len_____should_return_an_int = space.wrap('__len__() should return an int') + del m.__len__ + del m.__le__ + del m.__ixor__ + del m.__itruediv__ + m.gs___iter___returned_non_iterator_o = space.wrap('__iter__ returned non-iterator of type %s') + m.gs_iteration_over_non_sequence = space.wrap('iteration over non-sequence') + m.gfunc_seqiter = space.wrap(interp2app(f_seqiter)) + del m.__iter__ + del m.seqiter + del m.__isub__ + del m.__irshift__ + del m.__ipow__ + del m.__ior__ + del m.__invert__ + del m.__int__ + del m.__imul__ + del m.__imod__ + del m.__ilshift__ + del m.__ifloordiv__ + del m.__idiv__ + del m.__iand__ + del m.__iadd__ + del m.__hex__ + m.gs_unhashable_instance = space.wrap('unhashable instance') + m.gs___hash_____should_return_an_int = space.wrap('__hash__() should return an int') + del m.__hash__ + del m.__gt__ + m.gs___getslice__ = space.wrap('__getslice__') + del m.__getitem__ + m.gs___getattr__ = space.wrap('__getattr__') + del m.__ge__ + del m.__floordiv__ + del m.__float__ + del m.__eq__ + del m.__divmod__ + del m.__div__ + m.gs___delslice__ = space.wrap('__delslice__') + del m.__delitem__ + m.g2tuple_2 = space.newtuple([gs___dict__, gs___class__]) + m.gs__s_instance_has_no_attribute___s = space.wrap("%s instance has no attribute '%s'") + del m.__contains__ + del m.__coerce__ + m.gs___cmp___must_return_int = space.wrap('__cmp__ must return int') + m.gi_minus_1 = space.newint(-1) + del m.__cmp__ + m.gs__s_instance_has_no___call___meth = space.wrap('%s instance has no __call__ method') + del m.__and__ + del m.__add__ + del m.__abs__ + m.gs_instance___first_arg_must_be_cla = space.wrap('instance() first arg must be class') + m.gs_instance___second_arg_must_be_di = space.wrap('instance() second arg must be dictionary or None') + del m.__new__ + m.gfunc_type_err = space.wrap(interp2app(f_type_err)) + m.gs_name = space.wrap('name') + m.gs_string = space.wrap('string') + m.g0tuple = space.newtuple([]) + m.gs_bases = space.wrap('bases') + m.gs_tuple = space.wrap('tuple') + m.gs_dict = space.wrap('dict') + m.gs___doc__ = space.wrap('__doc__') + m.gs__getframe = space.wrap('_getframe') + m.gs_f_globals = space.wrap('f_globals') + m.gs_get = space.wrap('get') + m.gs_OLD_STYLE_CLASSES_IMPL = space.wrap('OLD_STYLE_CLASSES_IMPL') + _tup= space.newtuple([]) + m.g_object = space.call(space.w_object, _tup) + m.gcls_OverflowError = space.wrap(OverflowError) + m.gcls_FloatingPointError = space.wrap(FloatingPointError) + m.gs_callable = space.wrap('callable') + m.gs_base_must_be_class = space.wrap('base must be class') + m.gs_argument__s_must_be__s__not__s = space.wrap('argument %s must be %s, not %s') + del m.type_err + return g3tuple + From pedronis at codespeak.net Thu Feb 10 17:10:37 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 17:10:37 +0100 (MET) Subject: [pypy-svn] r9052 - pypy/dist/pypy/objspace/std Message-ID: <20050210161037.5BC0027BCB@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 17:10:37 2005 New Revision: 9052 Modified: pypy/dist/pypy/objspace/std/objspace.py Log: glue to load old-style classes impl from classobjinterp (for now disabled) when enabled (cwd = lib-python-2.3.4/test) : >>> __metaclass__ = _classobj >>> execfile("test_class.py") runs slowly but fine up to a bug in divmod builtin. Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Thu Feb 10 17:10:37 2005 @@ -80,12 +80,24 @@ # exceptions mod = self.setup_exceptions(for_builtins) + # old-style classes + #self.setup_old_style_classes() + # install things in the __builtin__ module self.make_builtins(for_builtins) w_exceptions = self.wrap(mod) self.sys.setbuiltinmodule(w_exceptions, 'exceptions') + def setup_old_style_classes(self): + """NOT_RPYTHON""" + from pypy.module import classobjinterp + w_setup = classobjinterp.initclassobj(self) + w_classobj, w_instance, w_purify = self.unpackiterable(w_setup) + self.call_function(w_purify) + self.w_classobj = w_classobj + self.w_instance = w_instance + def setup_exceptions(self, for_builtins): """NOT_RPYTHON""" ## hacking things in From hpk at codespeak.net Thu Feb 10 18:47:23 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 18:47:23 +0100 (MET) Subject: [pypy-svn] r9053 - pypy/branch/dist-interpapp Message-ID: <20050210174723.9E39327BE7@code1.codespeak.net> Author: hpk Date: Thu Feb 10 18:47:23 2005 New Revision: 9053 Added: pypy/branch/dist-interpapp/ Log: opening a fresh branch dedicated to refactorings related to interpreter/applevel interactions. From hpk at codespeak.net Thu Feb 10 18:48:31 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 18:48:31 +0100 (MET) Subject: [pypy-svn] r9054 - pypy/branch/dist-interpapp Message-ID: <20050210174831.392FE27BE7@code1.codespeak.net> Author: hpk Date: Thu Feb 10 18:48:31 2005 New Revision: 9054 Removed: pypy/branch/dist-interpapp/ Log: ok, forgot to actually branch :-) From hpk at codespeak.net Thu Feb 10 18:49:32 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 18:49:32 +0100 (MET) Subject: [pypy-svn] r9055 - pypy/branch/dist-interpapp Message-ID: <20050210174932.0A95227BE7@code1.codespeak.net> Author: hpk Date: Thu Feb 10 18:49:31 2005 New Revision: 9055 Added: pypy/branch/dist-interpapp/ - copied from r9054, pypy/dist/ Log: now it is really a branch aimed at refactoring interp/app level interaction From pedronis at codespeak.net Thu Feb 10 19:11:15 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 19:11:15 +0100 (MET) Subject: [pypy-svn] r9056 - in pypy/dist/pypy/translator: . tool Message-ID: <20050210181115.8F17A27BE7@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 19:11:15 2005 New Revision: 9056 Modified: pypy/dist/pypy/translator/geninterplevel.py pypy/dist/pypy/translator/tool/tointerplevel.py Log: - typo - use exceptions types from space Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 10 19:11:15 2005 @@ -566,17 +566,13 @@ metaclass = "space.w_type" name = self.uniquename('gcls_' + cls.__name__) + if issubclass(cls, Exception): if cls.__module__ == 'exceptions': - if hasattr(self.space, "w_%s" % cls.__name__): - return 'space.w_%s'%cls.__name__ - else: - self.initcode.append('m.%s = space.wrap(%s)' % ( - name, cls.__name__)) - return name - #else: - # # exceptions must be old-style classes (grr!) - # metaclass = "&PyClass_Type" + # exception are defined on the space + return 'space.w_%s'%cls.__name__ + + # For the moment, use old-style classes exactly when the # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): Modified: pypy/dist/pypy/translator/tool/tointerplevel.py ============================================================================== --- pypy/dist/pypy/translator/tool/tointerplevel.py (original) +++ pypy/dist/pypy/translator/tool/tointerplevel.py Thu Feb 10 19:11:15 2005 @@ -9,7 +9,7 @@ from pypy.translator.geninterplevel import GenRpy # change default -FlowObjSpace.bultins_can_raise_exceptions = True +FlowObjSpace.builtins_can_raise_exceptions = True def main(): opt_parser = optparse.OptionParser(usage="usage: %prog [options] module-file obj-name...") From pedronis at codespeak.net Thu Feb 10 19:14:15 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 19:14:15 +0100 (MET) Subject: [pypy-svn] r9057 - pypy/dist/pypy/module Message-ID: <20050210181415.6B9E027BE7@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 19:14:15 2005 New Revision: 9057 Modified: pypy/dist/pypy/module/classobjinterp.py Log: oops, now code should be really generated to catch exceptions from builtins Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Thu Feb 10 19:14:15 2005 @@ -21,17 +21,48 @@ def _coerce(space, w_left, w_right): - w_0=w_3=None + w_0=w_3=w_4=w_5=w_6=w_7=v8=w_9=w_10=w_11=w_12=v13=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.coerce(w_left, w_right) - w_3 = w_0 - goto = 2 + try: + w_0 = space.coerce(w_left, w_right) + w_3 = w_0 + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 2 + else:raise # unhandled case, should not happen if goto == 2: + w_7 = space.is_(w_6, space.w_TypeError) + v8 = space.is_true(w_7) + if v8 == True: + w_3 = space.w_None + goto = 5 + else: + assert v8 == False + w_9, w_10, w_11 = w_4, w_5, w_6 + goto = 3 + + if goto == 3: + w_12 = space.issubtype(w_11, space.w_TypeError) + v13 = space.is_true(w_12) + if v13 == True: + w_3 = space.w_None + goto = 5 + else: + assert v13 == False + w_etype, w_evalue = w_9, w_10 + goto = 4 + + if goto == 4: + raise OperationError(w_etype, w_evalue) + + if goto == 5: return w_3 fastf__coerce = _coerce @@ -119,7 +150,7 @@ w_2 = space.getattr(w_0, gs___name__) w_3 = space.newtuple([w_arg, w_expected, w_2]) w_6 = space.mod(gs_argument__s_must_be__s__not__s, w_3) - w_7 = space.call_function(gcls_TypeError, w_6) + w_7 = space.call_function(space.w_TypeError, w_6) w_8 = w_7 goto = 2 @@ -161,7 +192,7 @@ goto = 2 else: assert v2 == False - (w_etype, w_evalue) = (gcls_TypeError, + (w_etype, w_evalue) = (space.w_TypeError, gs___name___must_be_a_string_object) goto = 3 @@ -217,7 +248,7 @@ goto = 2 else: assert v2 == False - (w_etype, w_evalue) = (gcls_TypeError, + (w_etype, w_evalue) = (space.w_TypeError, gs___bases___must_be_a_tuple_object) goto = 6 @@ -246,7 +277,7 @@ continue else: assert v11 == False - (w_etype, w_evalue) = (gcls_TypeError, + (w_etype, w_evalue) = (space.w_TypeError, gs___bases___items_must_be_classes) goto = 6 @@ -297,7 +328,7 @@ goto = 2 else: assert v2 == False - (w_etype, w_evalue) = (gcls_TypeError, + (w_etype, w_evalue) = (space.w_TypeError, gs___dict___must_be_a_dictionary_ob) goto = 3 @@ -362,7 +393,7 @@ w_8 = space.is_(w_7, space.w_KeyError) v9 = space.is_true(w_8) if v9 == True: - w_etype, w_evalue = gcls_AttributeError, w_attr_1 + w_etype, w_evalue = space.w_AttributeError, w_attr_1 goto = 4 else: assert v9 == False @@ -373,7 +404,7 @@ w_15 = space.issubtype(w_14, space.w_KeyError) v16 = space.is_true(w_15) if v16 == True: - w_etype, w_evalue = gcls_AttributeError, w_attr_2 + w_etype, w_evalue = space.w_AttributeError, w_attr_2 goto = 4 else: assert v16 == False @@ -422,7 +453,7 @@ w_cls_1, w_v_1 = w_cls, w_v goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): (w_cls_2, w_attr_1, w_3, w_4, w_5) = (w_cls, w_attr, e.w_type, e.w_value, e.w_type) goto = 3 @@ -434,7 +465,7 @@ goto = 12 if goto == 3: - w_8 = space.is_(w_5, gcls_AttributeError) + w_8 = space.is_(w_5, space.w_AttributeError) v9 = space.is_true(w_8) if v9 == True: w_cls_3, w_attr_2 = w_cls_2, w_attr_1 @@ -446,7 +477,7 @@ goto = 4 if goto == 4: - w_13 = space.issubtype(w_12, gcls_AttributeError) + w_13 = space.issubtype(w_12, space.w_AttributeError) v14 = space.is_true(w_13) if v14 == True: w_cls_5, w_attr_4 = w_cls_4, w_attr_3 @@ -553,13 +584,13 @@ w_mod_1 = w_mod goto = 3 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_2, w_3, w_4 = e.w_type, e.w_value, e.w_type goto = 2 else:raise # unhandled case, should not happen if goto == 2: - w_5 = space.is_(w_4, gcls_AttributeError) + w_5 = space.is_(w_4, space.w_AttributeError) v6 = space.is_true(w_5) if v6 == True: w_mod_1 = space.w_None @@ -581,7 +612,7 @@ goto = 6 if goto == 4: - w_13 = space.issubtype(w_9, gcls_AttributeError) + w_13 = space.issubtype(w_9, space.w_AttributeError) v14 = space.is_true(w_13) if v14 == True: w_mod_1 = space.w_None @@ -632,7 +663,7 @@ w_name_1, w_mro_1 = w_name, w_mro goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): w_4 = space.w_None goto = 6 else:raise # unhandled case, should not happen @@ -704,7 +735,7 @@ w_2 = w_1 goto = 5 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_3, w_4, w_5 = e.w_type, e.w_value, e.w_type goto = 2 else:raise # unhandled case, should not happen @@ -778,22 +809,23 @@ w_9=v10=w_name_3=w_bases_2=w_dic_2=w_11=v12=w_bases_4=w_13=w_14=None w_name_4=w_bases_3=w_dic_3=w_15=v16=w_dic_5=w_17=w_18=w_name_5=None w_bases_5=w_dic_4=w_19=w_name_6=w_bases_6=w_dic_6=w_30=w_name_11=None - w_bases_11=w_dic_11=w_65=w_name_23=w_bases_23=w_dic_23=w_66=w_b=None - w_name_24=w_bases_24=w_dic_24=w_68=w_b_1=w_71=v72=w_name_26=w_bases_26=None - w_dic_26=w_b_2=w_73=w_74=v75=w_name_27=w_bases_27=w_dic_27=w_b_3=None - w_76=w_77=w_78=w_name_25=w_bases_25=w_dic_25=w_new_class=w_80=None - w_81=w_82=w_83=w_84=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None - w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_69=v70=None - w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_g=w_name_15=w_bases_15=None - w_dic_15=w_i_1=w_g_1=w_47=w_name_17=w_bases_17=w_dic_17=w_i_2=None - w_g_2=w_48=w_49=w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_3=w_50=None - w_51=v52=w_name_20=w_bases_20=w_dic_20=w_g_4=w_60=w_modname=w_62=None - v63=w_name_22=w_bases_22=w_dic_22=w_modname_1=w_64=w_name_19=None - w_bases_19=w_dic_19=w_i_4=w_i_5=w_name_16=w_bases_16=w_dic_16=None - w_44=w_45=w_46=w_58=v59=w_name_21=w_bases_21=w_dic_21=w_56=w_57=None - w_54=w_53=v55=w_name_7=w_bases_7=w_dic_7=w_20=w_21=w_22=w_23=None - v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=w_40=v41=w_name_10=None - w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=w_dic_8=w_29=None + w_bases_11=w_dic_11=w_66=w_name_24=w_bases_24=w_dic_24=w_67=w_b=None + w_name_25=w_bases_25=w_dic_25=w_69=w_b_1=w_72=v73=w_name_27=w_bases_27=None + w_dic_27=w_b_2=w_74=w_75=v76=w_name_28=w_bases_28=w_dic_28=w_b_3=None + w_77=w_78=w_79=w_name_26=w_bases_26=w_dic_26=w_new_class=w_81=None + w_82=w_83=w_84=w_85=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None + w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_70=v71=None + w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_name_15=w_bases_15=w_dic_15=None + w_i_1=w_43=w_g=w_name_17=w_bases_17=w_dic_17=w_i_2=w_g_1=w_48=None + w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_2=w_49=w_50=w_name_19=None + w_bases_19=w_dic_19=w_i_4=w_g_3=w_51=w_52=v53=w_name_21=w_bases_21=None + w_dic_21=w_g_4=w_61=w_modname=w_63=v64=w_name_23=w_bases_23=w_dic_23=None + w_modname_1=w_65=w_name_20=w_bases_20=w_dic_20=w_i_5=w_i_6=w_name_16=None + w_bases_16=w_dic_16=w_44=w_45=w_46=w_59=v60=w_name_22=w_bases_22=None + w_dic_22=w_57=w_58=w_55=w_54=v56=w_name_7=w_bases_7=w_dic_7=w_20=None + w_21=w_22=w_23=v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=None + w_40=v41=w_name_10=w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=None + w_dic_8=w_29=None goto = 1 # startblock while True: @@ -813,7 +845,7 @@ w_5 = fastf_type_err(space, gs_name, gs_string, w_name_2) w_6 = space.type(w_5) w_etype, w_evalue = w_6, w_5 - goto = 31 + goto = 32 if goto == 3: w_9 = space.is_(w_bases_1, space.w_None) @@ -841,7 +873,7 @@ w_13 = fastf_type_err(space, gs_bases, gs_tuple, w_bases_4) w_14 = space.type(w_13) w_etype, w_evalue = w_14, w_13 - goto = 31 + goto = 32 if goto == 6: w_15 = space.isinstance(w_dic_3, space.w_dict) @@ -858,7 +890,7 @@ w_17 = fastf_type_err(space, gs_dict, gs_dict, w_dic_5) w_18 = space.type(w_17) w_etype, w_evalue = w_18, w_17 - goto = 31 + goto = 32 if goto == 8: try: @@ -904,7 +936,7 @@ try: w_30 = space.getitem(w_dic_6, gs___module__) w_name_11, w_bases_11, w_dic_11 = w_name_6, w_bases_6, w_dic_6 - goto = 24 + goto = 25 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) = (w_name_6, @@ -929,7 +961,7 @@ assert v35 == False (w_name_14, w_bases_14, w_dic_14, w_37, w_38, w_39) = (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) - goto = 26 + goto = 27 if goto == 14: w_40 = space.issubtype(w_27, space.w_KeyError) @@ -941,205 +973,217 @@ else: assert v41 == False w_etype, w_evalue = w_25, w_26 - goto = 31 + goto = 32 if goto == 15: - w_42 = space.call_function((space.getattr(space.w_sys, gs__getframe)), w_i) try: - w_g = space.getattr(w_42, gs_f_globals) - (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1) = (w_name_13, - w_bases_13, w_dic_13, w_i, w_g) + w_42 = space.call_function((space.getattr(space.w_sys, gs__getframe)), w_i) + (w_name_15, w_bases_15, w_dic_15, w_i_1, w_43) = (w_name_13, + w_bases_13, w_dic_13, w_i, w_42) goto = 16 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_13, - w_bases_13, w_dic_13, gcls_AttributeError, e.w_value, - gcls_AttributeError) - goto = 21 + w_bases_13, w_dic_13, e.w_type, e.w_value, e.w_type) + goto = 22 else:raise # unhandled case, should not happen if goto == 16: try: - w_47 = space.getattr(w_g_1, gs_get) - (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, - w_48) = (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1, w_47) + w_g = space.getattr(w_43, gs_f_globals) + (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_1) = (w_name_15, + w_bases_15, w_dic_15, w_i_1, w_g) goto = 17 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_15, - w_bases_15, w_dic_15, gcls_AttributeError, e.w_value, - gcls_AttributeError) - goto = 21 + w_bases_15, w_dic_15, space.w_AttributeError, e.w_value, + space.w_AttributeError) + goto = 22 else:raise # unhandled case, should not happen if goto == 17: try: - w_49 = space.call_function(w_48, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) - (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_3, - w_50) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, w_49) + w_48 = space.getattr(w_g_1, gs_get) + (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_2, + w_49) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_1, w_48) goto = 18 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_17, - w_bases_17, w_dic_17, e.w_type, e.w_value, e.w_type) - goto = 21 + w_bases_17, w_dic_17, space.w_AttributeError, e.w_value, + space.w_AttributeError) + goto = 22 else:raise # unhandled case, should not happen if goto == 18: - w_51 = space.is_(w_50, g_object) - v52 = space.is_true(w_51) - if v52 == True: - (w_name_19, w_bases_19, w_dic_19, w_i_4) = (w_name_18, w_bases_18, - w_dic_18, w_i_3) + try: + w_50 = space.call_function(w_49, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) + (w_name_19, w_bases_19, w_dic_19, w_i_4, w_g_3, + w_51) = (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_2, w_50) goto = 19 - else: - assert v52 == False - (w_name_20, w_bases_20, w_dic_20, w_g_4) = (w_name_18, w_bases_18, - w_dic_18, w_g_3) - goto = 22 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_18, + w_bases_18, w_dic_18, e.w_type, e.w_value, e.w_type) + goto = 22 + else:raise # unhandled case, should not happen if goto == 19: + w_52 = space.is_(w_51, g_object) + v53 = space.is_true(w_52) + if v53 == True: + (w_name_20, w_bases_20, w_dic_20, w_i_5) = (w_name_19, w_bases_19, + w_dic_19, w_i_4) + goto = 20 + else: + assert v53 == False + (w_name_21, w_bases_21, w_dic_21, w_g_4) = (w_name_19, w_bases_19, + w_dic_19, w_g_3) + goto = 23 + + if goto == 20: try: - w_i_5 = space.inplace_add(w_i_4, gi_1) - (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_19, w_bases_19, - w_dic_19, w_i_5) + w_i_6 = space.inplace_add(w_i_5, gi_1) + (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_20, w_bases_20, + w_dic_20, w_i_6) goto = 15 continue except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_OverflowError)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, - w_bases_19, w_dic_19, gcls_OverflowError, e.w_value, - gcls_OverflowError) - goto = 21 - elif space.is_true(space.issubtype(e.w_type, gcls_FloatingPointError)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, - w_bases_19, w_dic_19, gcls_FloatingPointError, e.w_value, - gcls_FloatingPointError) - goto = 21 + if space.is_true(space.issubtype(e.w_type, space.w_OverflowError)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_20, + w_bases_20, w_dic_20, space.w_OverflowError, e.w_value, + space.w_OverflowError) + goto = 22 + elif space.is_true(space.issubtype(e.w_type, space.w_FloatingPointError)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_20, + w_bases_20, w_dic_20, space.w_FloatingPointError, e.w_value, + space.w_FloatingPointError) + goto = 22 else:raise # unhandled case, should not happen - if goto == 20: - w_53 = space.issubtype(w_54, space.w_ValueError) - v55 = space.is_true(w_53) - if v55 == True: - w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 - goto = 24 + if goto == 21: + w_54 = space.issubtype(w_55, space.w_ValueError) + v56 = space.is_true(w_54) + if v56 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 + goto = 25 else: - assert v55 == False - w_etype, w_evalue = w_56, w_57 - goto = 31 + assert v56 == False + w_etype, w_evalue = w_57, w_58 + goto = 32 - if goto == 21: - w_58 = space.is_(w_46, space.w_ValueError) - v59 = space.is_true(w_58) - if v59 == True: + if goto == 22: + w_59 = space.is_(w_46, space.w_ValueError) + v60 = space.is_true(w_59) + if v60 == True: w_name_11, w_bases_11, w_dic_11 = w_name_16, w_bases_16, w_dic_16 - goto = 24 + goto = 25 else: - assert v59 == False - (w_name_21, w_bases_21, w_dic_21, w_56, w_57, w_54) = (w_name_16, + assert v60 == False + (w_name_22, w_bases_22, w_dic_22, w_57, w_58, w_55) = (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) - goto = 20 + goto = 21 continue - if goto == 22: - w_60 = space.getattr(w_g_4, gs_get) - w_modname = space.call_function(w_60, gs___name__, space.w_None) - w_62 = space.is_(w_modname, space.w_None) - v63 = space.is_true(w_62) - if v63 == True: - w_name_11, w_bases_11, w_dic_11 = w_name_20, w_bases_20, w_dic_20 - goto = 24 - else: - assert v63 == False - (w_name_22, w_bases_22, w_dic_22, w_modname_1) = (w_name_20, - w_bases_20, w_dic_20, w_modname) - goto = 23 - if goto == 23: - w_64 = space.setitem(w_dic_22, gs___module__, w_modname_1) - w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 - goto = 24 + w_61 = space.getattr(w_g_4, gs_get) + w_modname = space.call_function(w_61, gs___name__, space.w_None) + w_63 = space.is_(w_modname, space.w_None) + v64 = space.is_true(w_63) + if v64 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 + goto = 25 + else: + assert v64 == False + (w_name_23, w_bases_23, w_dic_23, w_modname_1) = (w_name_21, + w_bases_21, w_dic_21, w_modname) + goto = 24 if goto == 24: - w_65 = space.iter(w_bases_11) - (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_11, w_bases_11, - w_dic_11, w_65) + w_65 = space.setitem(w_dic_23, gs___module__, w_modname_1) + w_name_11, w_bases_11, w_dic_11 = w_name_23, w_bases_23, w_dic_23 goto = 25 if goto == 25: + w_66 = space.iter(w_bases_11) + (w_name_24, w_bases_24, w_dic_24, w_67) = (w_name_11, w_bases_11, + w_dic_11, w_66) + goto = 26 + + if goto == 26: try: - w_b = space.next(w_66) - (w_name_24, w_bases_24, w_dic_24, w_68, w_b_1) = (w_name_23, - w_bases_23, w_dic_23, w_66, w_b) - goto = 27 + w_b = space.next(w_67) + (w_name_25, w_bases_25, w_dic_25, w_69, w_b_1) = (w_name_24, + w_bases_24, w_dic_24, w_67, w_b) + goto = 28 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): - w_name_25, w_bases_25, w_dic_25 = w_name_23, w_bases_23, w_dic_23 - goto = 30 + w_name_26, w_bases_26, w_dic_26 = w_name_24, w_bases_24, w_dic_24 + goto = 31 else:raise # unhandled case, should not happen - if goto == 26: - w_69 = space.issubtype(w_39, space.w_KeyError) - v70 = space.is_true(w_69) - if v70 == True: + if goto == 27: + w_70 = space.issubtype(w_39, space.w_KeyError) + v71 = space.is_true(w_70) + if v71 == True: (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_14, w_bases_14, w_dic_14, gi_0) goto = 15 continue else: - assert v70 == False + assert v71 == False w_etype, w_evalue = w_37, w_38 - goto = 31 + goto = 32 - if goto == 27: - w_71 = space.isinstance(w_b_1, gcls_classobj) - v72 = space.is_true(w_71) - if v72 == True: - (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_24, w_bases_24, - w_dic_24, w_68) - goto = 25 + if goto == 28: + w_72 = space.isinstance(w_b_1, gcls_classobj) + v73 = space.is_true(w_72) + if v73 == True: + (w_name_24, w_bases_24, w_dic_24, w_67) = (w_name_25, w_bases_25, + w_dic_25, w_69) + goto = 26 continue else: - assert v72 == False - (w_name_26, w_bases_26, w_dic_26, w_b_2) = (w_name_24, w_bases_24, - w_dic_24, w_b_1) - goto = 28 - - if goto == 28: - w_73 = space.call_function(space.w_type, w_b_2) - w_74 = space.call_function((space.getattr(space.w_builtin, gs_callable)), w_73) - v75 = space.is_true(w_74) - if v75 == True: - (w_name_27, w_bases_27, w_dic_27, w_b_3) = (w_name_26, w_bases_26, - w_dic_26, w_b_2) + assert v73 == False + (w_name_27, w_bases_27, w_dic_27, w_b_2) = (w_name_25, w_bases_25, + w_dic_25, w_b_1) goto = 29 - else: - assert v75 == False - w_etype, w_evalue = gcls_TypeError, gs_base_must_be_class - goto = 31 if goto == 29: - w_76 = space.call_function(space.w_type, w_b_3) - w_77 = space.call_function(w_76, w_name_27, w_bases_27, w_dic_27) - w_78 = w_77 - goto = 32 + w_74 = space.call_function(space.w_type, w_b_2) + w_75 = space.call_function((space.getattr(space.w_builtin, gs_callable)), w_74) + v76 = space.is_true(w_75) + if v76 == True: + (w_name_28, w_bases_28, w_dic_28, w_b_3) = (w_name_27, w_bases_27, + w_dic_27, w_b_2) + goto = 30 + else: + assert v76 == False + w_etype, w_evalue = space.w_TypeError, gs_base_must_be_class + goto = 32 if goto == 30: - w_new_class = space.call_function(gbltinmethod___new__, gcls_classobj) - w_80 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_25) - w_81 = space.getattr(gdescriptor_classobj__name, gs___set__) - w_82 = space.call_function(w_81, w_new_class, w_name_25) - w_83 = space.getattr(gdescriptor_classobj__bases, gs___set__) - w_84 = space.call_function(w_83, w_new_class, w_bases_25) - w_78 = w_new_class - goto = 32 + w_77 = space.call_function(space.w_type, w_b_3) + w_78 = space.call_function(w_77, w_name_28, w_bases_28, w_dic_28) + w_79 = w_78 + goto = 33 if goto == 31: - raise OperationError(w_etype, w_evalue) + w_new_class = space.call_function(gbltinmethod___new__, gcls_classobj) + w_81 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_26) + w_82 = space.getattr(gdescriptor_classobj__name, gs___set__) + w_83 = space.call_function(w_82, w_new_class, w_name_26) + w_84 = space.getattr(gdescriptor_classobj__bases, gs___set__) + w_85 = space.call_function(w_84, w_new_class, w_bases_26) + w_79 = w_new_class + goto = 33 if goto == 32: - return w_78 + raise OperationError(w_etype, w_evalue) + + if goto == 33: + return w_79 fastf___new__ = __new__ @@ -1395,7 +1439,7 @@ w_24 = space.getattr(w_self_7, gs___name__) w_25 = space.newtuple([w_24, w_attr_4]) w_26 = space.mod(gs_class__s_has_no_attribute__s, w_25) - w_etype, w_evalue = gcls_AttributeError, w_26 + w_etype, w_evalue = space.w_AttributeError, w_26 goto = 12 if goto == 10: @@ -1576,8 +1620,8 @@ goto = 3 if goto == 3: - w_13 = space.call_function(gcls_TypeError, gs___init_____should_return_None) - w_etype, w_evalue = gcls_TypeError, w_13 + w_13 = space.call_function(space.w_TypeError, gs___init_____should_return_None) + w_etype, w_evalue = space.w_TypeError, w_13 goto = 4 if goto == 4: @@ -1657,7 +1701,7 @@ goto = 19 if goto == 5: - w_11 = space.issubtype(w_12, gcls_AttributeError) + w_11 = space.issubtype(w_12, space.w_AttributeError) v13 = space.is_true(w_11) if v13 == True: w_inst_6, w_name_5, w_exc_4 = w_inst_5, w_name_4, w_exc_3 @@ -1673,14 +1717,14 @@ w_6 = w_18 goto = 19 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): (w_inst_7, w_name_6, w_exc_5, w_19, w_20, w_21) = (w_inst_4, w_name_3, w_exc_2, e.w_type, e.w_value, e.w_type) goto = 7 else:raise # unhandled case, should not happen if goto == 7: - w_22 = space.is_(w_21, gcls_AttributeError) + w_22 = space.is_(w_21, space.w_AttributeError) v23 = space.is_true(w_22) if v23 == True: w_inst_8, w_name_7, w_exc_6 = w_inst_7, w_name_6, w_exc_5 @@ -1772,14 +1816,14 @@ w_43 = space.getattr(w_cls_7, gs___name__) w_44 = space.newtuple([w_43, w_name_12]) w_45 = space.mod(gs__s_instance_has_no_attribute__s, w_44) - w_etype, w_evalue = gcls_AttributeError, w_45 + w_etype, w_evalue = space.w_AttributeError, w_45 goto = 18 if goto == 15: w_46 = space.getattr(w_cls_8, gs___name__) w_47 = space.newtuple([w_46, w_name_13]) w_48 = space.mod(gs__s_instance_has_no_attribute__s, w_47) - w_etype, w_evalue = gcls_AttributeError, w_48 + w_etype, w_evalue = space.w_AttributeError, w_48 goto = 18 if goto == 16: @@ -1842,14 +1886,14 @@ w_3 = w_0 goto = 9 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): (w_self_1, w_name_1, w_4, w_5, w_6, w_7, w_8) = (w_self, w_name, e.w_type, e.w_value, e.w_type, e.w_type, e.w_value) goto = 2 else:raise # unhandled case, should not happen if goto == 2: - w_9 = space.is_(w_6, gcls_AttributeError) + w_9 = space.is_(w_6, space.w_AttributeError) v10 = space.is_true(w_9) if v10 == True: w_self_2, w_name_2, w_11, w_12 = w_self_1, w_name_1, w_7, w_8 @@ -1861,7 +1905,7 @@ goto = 3 if goto == 3: - w_18 = space.issubtype(w_15, gcls_AttributeError) + w_18 = space.issubtype(w_15, space.w_AttributeError) v19 = space.is_true(w_18) if v19 == True: w_self_4, w_name_4, w_20, w_21 = w_self_3, w_name_3, w_16, w_17 @@ -1953,8 +1997,8 @@ goto = 2 if goto == 2: - w_4 = space.call_function(gcls_TypeError, gs_instance___first_arg_must_be_cla) - w_etype, w_evalue = gcls_TypeError, w_4 + w_4 = space.call_function(space.w_TypeError, gs_instance___first_arg_must_be_cla) + w_etype, w_evalue = space.w_TypeError, w_4 goto = 8 if goto == 3: @@ -1984,8 +2028,8 @@ goto = 6 if goto == 6: - w_11 = space.call_function(gcls_TypeError, gs_instance___second_arg_must_be_di) - w_etype, w_evalue = gcls_TypeError, w_11 + w_11 = space.call_function(space.w_TypeError, gs_instance___second_arg_must_be_di) + w_etype, w_evalue = space.w_TypeError, w_11 goto = 8 if goto == 7: @@ -2055,8 +2099,8 @@ goto = 3 if goto == 3: - w_7 = space.call_function(gcls_TypeError, gs___dict___must_be_set_to_a_dictio) - w_etype, w_evalue = gcls_TypeError, w_7 + w_7 = space.call_function(space.w_TypeError, gs___dict___must_be_set_to_a_dictio) + w_etype, w_evalue = space.w_TypeError, w_7 goto = 12 if goto == 4: @@ -2086,8 +2130,8 @@ goto = 7 if goto == 7: - w_16 = space.call_function(gcls_TypeError, gs___class___must_be_set_to_a_class) - w_etype, w_evalue = gcls_TypeError, w_16 + w_16 = space.call_function(space.w_TypeError, gs___class___must_be_set_to_a_class) + w_etype, w_evalue = space.w_TypeError, w_16 goto = 12 if goto == 8: @@ -2198,9 +2242,9 @@ w_self_4, w_name_5, w_11 = w_self_3, w_name_3, w_10 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_AttributeError)): + if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_self_5, w_name_6, w_12, w_13, w_14) = (w_self_3, w_name_3, - gcls_AttributeError, e.w_value, gcls_AttributeError) + space.w_AttributeError, e.w_value, space.w_AttributeError) goto = 8 else:raise # unhandled case, should not happen @@ -2249,8 +2293,8 @@ w_26 = space.getattr(w_25, gs___name__) w_27 = space.newtuple([w_26, w_name_8]) w_28 = space.mod(gs__s_instance_has_no_attribute___s, w_27) - w_29 = space.call_function(gcls_AttributeError, w_28) - w_etype, w_evalue = gcls_AttributeError, w_29 + w_29 = space.call_function(space.w_AttributeError, w_28) + w_etype, w_evalue = space.w_AttributeError, w_29 goto = 11 if goto == 10: @@ -2258,8 +2302,8 @@ w_31 = space.getattr(w_30, gs___name__) w_32 = space.newtuple([w_31, w_name_9]) w_33 = space.mod(gs__s_instance_has_no_attribute___s, w_32) - w_34 = space.call_function(gcls_AttributeError, w_33) - w_etype, w_evalue = gcls_AttributeError, w_34 + w_34 = space.call_function(space.w_AttributeError, w_33) + w_etype, w_evalue = space.w_AttributeError, w_34 goto = 11 if goto == 11: @@ -2303,13 +2347,13 @@ w_func_1 = w_func goto = 5 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_self_1, w_2, w_3, w_4 = w_self, e.w_type, e.w_value, e.w_type goto = 2 else:raise # unhandled case, should not happen if goto == 2: - w_5 = space.is_(w_4, gcls_AttributeError) + w_5 = space.is_(w_4, space.w_AttributeError) v6 = space.is_true(w_5) if v6 == True: w_self_2 = w_self_1 @@ -2345,7 +2389,7 @@ goto = 8 if goto == 6: - w_22 = space.issubtype(w_9, gcls_AttributeError) + w_22 = space.issubtype(w_9, space.w_AttributeError) v23 = space.is_true(w_22) if v23 == True: w_self_4 = w_self_3 @@ -2393,13 +2437,13 @@ w_func_1 = w_func goto = 5 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_self_1, w_2, w_3, w_4 = w_self, e.w_type, e.w_value, e.w_type goto = 2 else:raise # unhandled case, should not happen if goto == 2: - w_5 = space.is_(w_4, gcls_AttributeError) + w_5 = space.is_(w_4, space.w_AttributeError) v6 = space.is_true(w_5) if v6 == True: w_self_2 = w_self_1 @@ -2425,7 +2469,7 @@ goto = 8 if goto == 6: - w_14 = space.issubtype(w_9, gcls_AttributeError) + w_14 = space.issubtype(w_9, space.w_AttributeError) v15 = space.is_true(w_14) if v15 == True: w_self_4 = w_self_3 @@ -2514,8 +2558,8 @@ goto = 6 if goto == 5: - w_10 = space.call_function(gcls_TypeError, gs_unhashable_instance) - w_etype, w_evalue = gcls_TypeError, w_10 + w_10 = space.call_function(space.w_TypeError, gs_unhashable_instance) + w_etype, w_evalue = space.w_TypeError, w_10 goto = 10 if goto == 6: @@ -2540,8 +2584,8 @@ goto = 8 if goto == 8: - w_18 = space.call_function(gcls_TypeError, gs___hash_____should_return_an_int) - w_etype, w_evalue = gcls_TypeError, w_18 + w_18 = space.call_function(space.w_TypeError, gs___hash_____should_return_an_int) + w_etype, w_evalue = space.w_TypeError, w_18 goto = 10 if goto == 9: @@ -2610,8 +2654,8 @@ goto = 5 if goto == 4: - w_11 = space.call_function(gcls_TypeError, gs___len_____should_return_an_int) - w_etype, w_evalue = gcls_TypeError, w_11 + w_11 = space.call_function(space.w_TypeError, gs___len_____should_return_an_int) + w_etype, w_evalue = space.w_TypeError, w_11 goto = 5 if goto == 5: @@ -3280,8 +3324,8 @@ goto = 9 if goto == 7: - w_14 = space.call_function(gcls_TypeError, gs___nonzero_____should_return_an_i) - w_etype, w_evalue = gcls_TypeError, w_14 + w_14 = space.call_function(space.w_TypeError, gs___nonzero_____should_return_an_i) + w_etype, w_evalue = space.w_TypeError, w_14 goto = 8 if goto == 8: @@ -3332,7 +3376,7 @@ w_5 = space.getattr(w_self_1, gs___class__) w_6 = space.getattr(w_5, gs___name__) w_7 = space.mod(gs__s_instance_has_no___call___meth, w_6) - w_etype, w_evalue = gcls_AttributeError, w_7 + w_etype, w_evalue = space.w_AttributeError, w_7 goto = 4 if goto == 3: @@ -3403,7 +3447,7 @@ w_7 = space.call_function(space.w_type, w_ret_1) w_8 = space.getattr(w_7, gs___name__) w_9 = space.mod(gs___iter___returned_non_iterator_o, w_8) - w_etype, w_evalue = gcls_TypeError, w_9 + w_etype, w_evalue = space.w_TypeError, w_9 goto = 6 if goto == 4: @@ -3414,7 +3458,7 @@ goto = 5 else: assert v12 == False - (w_etype, w_evalue) = (gcls_TypeError, + (w_etype, w_evalue) = (space.w_TypeError, gs_iteration_over_non_sequence) goto = 6 @@ -3463,7 +3507,7 @@ goto = 2 else: assert v2 == False - (w_etype, w_evalue) = (gcls_TypeError, + (w_etype, w_evalue) = (space.w_TypeError, gs_instance_has_no_next___method) goto = 3 @@ -3592,7 +3636,7 @@ goto = 9 else: assert v21 == False - w_etype, w_evalue = gcls_TypeError, gs___cmp___must_return_int + w_etype, w_evalue = space.w_TypeError, gs___cmp___must_return_int goto = 16 if goto == 9: @@ -3648,7 +3692,7 @@ goto = 14 else: assert v32 == False - w_etype, w_evalue = gcls_TypeError, gs___cmp___must_return_int + w_etype, w_evalue = space.w_TypeError, gs___cmp___must_return_int goto = 16 if goto == 14: @@ -4260,7 +4304,7 @@ w_other_1, w_3 = w_other, w_0 goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen @@ -4271,13 +4315,13 @@ w_8 = w_7 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen if goto == 3: - w_9 = space.issubtype(w_10, gcls_AttributeError) + w_9 = space.issubtype(w_10, space.w_AttributeError) v11 = space.is_true(w_9) if v11 == True: w_8 = space.w_NotImplemented @@ -4288,7 +4332,7 @@ goto = 5 if goto == 4: - w_16 = space.is_(w_6, gcls_AttributeError) + w_16 = space.is_(w_6, space.w_AttributeError) v17 = space.is_true(w_16) if v17 == True: w_8 = space.w_NotImplemented @@ -4444,7 +4488,7 @@ w_other_1, w_3 = w_other, w_0 goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen @@ -4455,13 +4499,13 @@ w_8 = w_7 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen if goto == 3: - w_9 = space.issubtype(w_10, gcls_AttributeError) + w_9 = space.issubtype(w_10, space.w_AttributeError) v11 = space.is_true(w_9) if v11 == True: w_8 = space.w_NotImplemented @@ -4472,7 +4516,7 @@ goto = 5 if goto == 4: - w_16 = space.is_(w_6, gcls_AttributeError) + w_16 = space.is_(w_6, space.w_AttributeError) v17 = space.is_true(w_16) if v17 == True: w_8 = space.w_NotImplemented @@ -4519,7 +4563,7 @@ w_other_1, w_3 = w_other, w_0 goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen @@ -4530,13 +4574,13 @@ w_8 = w_7 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen if goto == 3: - w_9 = space.issubtype(w_10, gcls_AttributeError) + w_9 = space.issubtype(w_10, space.w_AttributeError) v11 = space.is_true(w_9) if v11 == True: w_8 = space.w_NotImplemented @@ -4547,7 +4591,7 @@ goto = 5 if goto == 4: - w_16 = space.is_(w_6, gcls_AttributeError) + w_16 = space.is_(w_6, space.w_AttributeError) v17 = space.is_true(w_16) if v17 == True: w_8 = space.w_NotImplemented @@ -5236,7 +5280,7 @@ w_other_1, w_3 = w_other, w_0 goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen @@ -5247,13 +5291,13 @@ w_8 = w_7 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen if goto == 3: - w_9 = space.issubtype(w_10, gcls_AttributeError) + w_9 = space.issubtype(w_10, space.w_AttributeError) v11 = space.is_true(w_9) if v11 == True: w_8 = space.w_NotImplemented @@ -5264,7 +5308,7 @@ goto = 5 if goto == 4: - w_16 = space.is_(w_6, gcls_AttributeError) + w_16 = space.is_(w_6, space.w_AttributeError) v17 = space.is_true(w_16) if v17 == True: w_8 = space.w_NotImplemented @@ -5420,7 +5464,7 @@ w_other_1, w_3 = w_other, w_0 goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen @@ -5431,13 +5475,13 @@ w_8 = w_7 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen if goto == 3: - w_9 = space.issubtype(w_10, gcls_AttributeError) + w_9 = space.issubtype(w_10, space.w_AttributeError) v11 = space.is_true(w_9) if v11 == True: w_8 = space.w_NotImplemented @@ -5448,7 +5492,7 @@ goto = 5 if goto == 4: - w_16 = space.is_(w_6, gcls_AttributeError) + w_16 = space.is_(w_6, space.w_AttributeError) v17 = space.is_true(w_16) if v17 == True: w_8 = space.w_NotImplemented @@ -5649,7 +5693,7 @@ w_other_1, w_3 = w_other, w_0 goto = 2 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen @@ -5660,13 +5704,13 @@ w_8 = w_7 goto = 6 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, gcls_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type goto = 4 else:raise # unhandled case, should not happen if goto == 3: - w_9 = space.issubtype(w_10, gcls_AttributeError) + w_9 = space.issubtype(w_10, space.w_AttributeError) v11 = space.is_true(w_9) if v11 == True: w_8 = space.w_NotImplemented @@ -5677,7 +5721,7 @@ goto = 5 if goto == 4: - w_16 = space.is_(w_6, gcls_AttributeError) + w_16 = space.is_(w_6, space.w_AttributeError) v17 = space.is_true(w_16) if v17 == True: w_8 = space.w_NotImplemented @@ -7462,8 +7506,6 @@ m.gs__s__s = space.wrap('%s.%s') del m.__str__ m.gfunc_retrieve = space.wrap(interp2app(f_retrieve)) - m.gcls_Exception = space.wrap(Exception) - m.gcls_AttributeError = space.wrap(AttributeError) del m.get_class_module m.gdescriptor_object___getattribute__ = space.getattr(space.w_object, gs___getattribute__) del m.retrieve @@ -7473,7 +7515,6 @@ m.gfunc_set_dict = space.wrap(interp2app(f_set_dict)) m.gdescriptor_object___setattr__ = space.getattr(space.w_object, gs___setattr__) del m.__setattr__ - m.gcls_TypeError = space.wrap(TypeError) m.gs___dict___must_be_a_dictionary_ob = space.wrap('__dict__ must be a dictionary object') del m.set_dict m.gs___bases___must_be_a_tuple_object = space.wrap('__bases__ must be a tuple object') @@ -7625,8 +7666,6 @@ m.gs_OLD_STYLE_CLASSES_IMPL = space.wrap('OLD_STYLE_CLASSES_IMPL') _tup= space.newtuple([]) m.g_object = space.call(space.w_object, _tup) - m.gcls_OverflowError = space.wrap(OverflowError) - m.gcls_FloatingPointError = space.wrap(FloatingPointError) m.gs_callable = space.wrap('callable') m.gs_base_must_be_class = space.wrap('base must be class') m.gs_argument__s_must_be__s__not__s = space.wrap('argument %s must be %s, not %s') From pedronis at codespeak.net Thu Feb 10 19:51:40 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 19:51:40 +0100 (MET) Subject: [pypy-svn] r9060 - in pypy/dist/pypy: . objspace/std tool Message-ID: <20050210185140.D1F6127BCE@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 19:51:40 2005 New Revision: 9060 Modified: pypy/dist/pypy/conftest.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/tool/option.py Log: Aadded --oldstyle option tp py.py and tests to enable to run with old-style classes as the default most of our own tests passes with --oldstyle but seqiter in _classobj needs to be changed from being a generator to survive geninterplevel! Modified: pypy/dist/pypy/conftest.py ============================================================================== --- pypy/dist/pypy/conftest.py (original) +++ pypy/dist/pypy/conftest.py Thu Feb 10 19:51:40 2005 @@ -11,7 +11,9 @@ options = ('pypy options', [ Option('-o', '--objspace', action="store", default=None, type="string", dest="objspacename", - help="object space to run tests on."), + help="object space to run tests on."), + Option('--oldstyle', action="store_true",dest="oldstyle", default=False, + help="enable oldstyle classes as default metaclass (std objspace only)"), ]) @@ -32,6 +34,8 @@ module = __import__("pypy.objspace.%s" % name, None, None, ["Space"]) space = module.Space() _spacecache[name] = space + if name == 'std' and py.test.config.option.oldstyle: + space.enable_old_style_classes_as_default_metaclass() if name != 'flow': # not sensible for flow objspace case space.setitem(space.w_builtins, space.wrap('AssertionError'), pytestsupport.build_pytest_assertion(space)) Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Thu Feb 10 19:51:40 2005 @@ -81,7 +81,7 @@ mod = self.setup_exceptions(for_builtins) # old-style classes - #self.setup_old_style_classes() + self.setup_old_style_classes() # install things in the __builtin__ module self.make_builtins(for_builtins) @@ -89,6 +89,9 @@ w_exceptions = self.wrap(mod) self.sys.setbuiltinmodule(w_exceptions, 'exceptions') + def enable_old_style_classes_as_default_metaclass(self): + self.setitem(self.builtin.w_dict, self.wrap('__metaclass__'), self.w_classobj) + def setup_old_style_classes(self): """NOT_RPYTHON""" from pypy.module import classobjinterp Modified: pypy/dist/pypy/tool/option.py ============================================================================== --- pypy/dist/pypy/tool/option.py (original) +++ pypy/dist/pypy/tool/option.py Thu Feb 10 19:51:40 2005 @@ -5,6 +5,7 @@ class Options: showwarning = 0 spaces = [] + oldstyle = 0 def run_tb_server(option, opt, value, parser): from pypy.tool import tb_server @@ -21,6 +22,9 @@ callback=objspace_callback, callback_args=("std",), help="run in std object space")) options.append(make_option( + '--oldstyle', action="store_true",dest="oldstyle", + help="enable oldstyle classes as default metaclass (std objspace only)")) + options.append(make_option( '-T', action="callback", callback=objspace_callback, callback_args=("trivial",), help="run in trivial object space")) @@ -60,4 +64,7 @@ except KeyError: module = __import__("pypy.objspace.%s" % name, None, None, ["Space"]) Space = module.Space - return _spacecache.setdefault(name, Space()) + space = Space() + if name == 'std' and Options.oldstyle: + space.enable_old_style_classes_as_default_metaclass() + return _spacecache.setdefault(name, space) From hpk at codespeak.net Thu Feb 10 19:56:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 10 Feb 2005 19:56:17 +0100 (MET) Subject: [pypy-svn] r9061 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050210185617.382BE27BCE@code1.codespeak.net> Author: hpk Date: Thu Feb 10 19:56:17 2005 New Revision: 9061 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Log: added a another way to do applevel the new way: app = gateway.appdef("app(x,y)", """ return x + y """) w_result = app(space, space.wrap(41), space.wrap(1)) now the question is whether we want to support default args :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Thu Feb 10 19:56:17 2005 @@ -641,3 +641,52 @@ "NOT_RPYTHON" def getcache(self, space): return self.__dict__.setdefault(space, Cache()) + + +# and now for something completly different ... +# +# the following function might just go away +#def preparesource(source): +# from pypy.tool.pytestsupport import py # aehem +# argdecl, source = source.split(':', 1) +# argdecl = argdecl.strip() +# if not argdecl.startswith('(') or not argdecl.endswith(')'): +# raise SyntaxError("incorrect exec_with header\n%s" % source) +# +# newco = peparesource_funcdecl(source, argdecl+'(') +# argnames = argdecl[1:-1].strip().split(',') +# return newco, argnames + + +def preparesource(source, funcdecl): + from pypy.tool.pytestsupport import py + source = py.code.Source(source) + source = source.putaround("def %s:" % funcdecl) + d = {} + exec source.compile() in d + i = funcdecl.find('(') + assert i != -1 + return d[funcdecl[:i]].func_code + +def appdef(funcdecl, source): + from pypy.tool.pytestsupport import py + from pypy.interpreter.pycode import PyCode + newco = preparesource(source, funcdecl) + funcname, decl = funcdecl.split('(', 1) + decl = decl.strip()[:-1] + wargnames = ["w_%s" % x.strip() for x in decl[:-1].split(',')] + wdecl = ", ".join(wargnames) + source = py.code.Source(""" + def %s(space, %s): + pypyco = PyCode(space)._from_code(newco) + w_glob = space.newdict([]) + frame = pypyco.create_frame(space, w_glob) + frame.setfastscope([%s]) + return frame.run() + """ % (funcname, wdecl, wdecl)) + glob = { + 'newco' : newco, + 'PyCode': PyCode, + } + exec source.compile() in glob + return glob[funcname] Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Thu Feb 10 19:56:17 2005 @@ -1,5 +1,6 @@ import py +from pypy.interpreter.gateway import appdef def test_execwith_novars(space): val = space.appexec([], """ @@ -23,4 +24,10 @@ """) assert str(excinfo).find('y y') != -1 - +def test_simple_applevel(space): + app = appdef("app(x,y)", """ + return x + y + """) + assert app.func_name == 'app' + w_result = app(space, space.wrap(41), space.wrap(1)) + assert space.eq_w(w_result, space.wrap(42)) From pedronis at codespeak.net Thu Feb 10 21:27:30 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 21:27:30 +0100 (MET) Subject: [pypy-svn] r9089 - pypy/dist/pypy/module Message-ID: <20050210202730.7DC5727BE6@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 21:27:30 2005 New Revision: 9089 Modified: pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/module/__builtin__module.py Log: let expose sequence iterator creation to app-level Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Thu Feb 10 21:27:30 2005 @@ -312,6 +312,9 @@ space.wrap('iter(v, w): w must be callable')) return _iter_generator(w_collection_or_callable, w_sentinel) +def _seqiter(w_obj): + return space.newseqiter(w_obj) + def ord(w_val): return space.ord(w_val) Modified: pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/dist/pypy/module/__builtin__module.py Thu Feb 10 21:27:30 2005 @@ -491,7 +491,7 @@ from __interplevel__ import abs, chr, len, ord, pow, repr from __interplevel__ import hash, oct, hex, round, cmp, coerce from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype +from __interplevel__ import _issubtype, _seqiter from __interplevel__ import compile, eval from __interplevel__ import globals, locals, _caller_globals, _caller_locals From pedronis at codespeak.net Thu Feb 10 22:00:35 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 10 Feb 2005 22:00:35 +0100 (MET) Subject: [pypy-svn] r9093 - in pypy/dist/pypy: lib module translator Message-ID: <20050210210035.8E01C27BE6@code1.codespeak.net> Author: pedronis Date: Thu Feb 10 22:00:35 2005 New Revision: 9093 Modified: pypy/dist/pypy/lib/_classobj.py pypy/dist/pypy/module/classobjinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: - give the possibility to override a function with an expression of our own accord when geninterpelevel-ing - use this, to have the geninterplevel-ed _classobj.py use the new in __builtin__ exposed _seqiter - test_all.py --oldstyle wholly passes Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Thu Feb 10 22:00:35 2005 @@ -89,9 +89,9 @@ if name in x.__dict__: return x.__dict__[name] return None - -def seqiter(func): # XXX may want to access and instatiate the internal - # sequence-iterator type instead + +def _seqiter(obj): + func = obj.__getitem__ i = 0 while 1: try: @@ -99,6 +99,8 @@ except IndexError: return i += 1 +# let geninterplevel retrieve the PyPy builtin instead +_seqiter.geninterplevel_name = lambda gen: "(space.getattr(space.w_builtin, %s))" % gen.nameof('_seqiter') OLD_STYLE_CLASSES_IMPL = object() @@ -519,7 +521,7 @@ raise TypeError, "iteration over non-sequence" # moved sequiter away from here: # flow space cannot handle nested functions. - return seqiter(func) + return _seqiter(self) def next(self): func = instance_getattr1(self, 'next', False) Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Thu Feb 10 22:00:35 2005 @@ -6,7 +6,7 @@ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '_coerce' ## firstlineno 7 ##SECTION## @@ -68,7 +68,7 @@ fastf__coerce = _coerce ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'uid' ## firstlineno 18 ##SECTION## @@ -122,7 +122,7 @@ fastf_uid = uid ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'type_err' ## firstlineno 34 ##SECTION## @@ -160,7 +160,7 @@ fastf_type_err = type_err ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'set_name' ## firstlineno 37 ##SECTION## @@ -211,7 +211,7 @@ fastf_set_name = set_name ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'set_bases' ## firstlineno 42 ##SECTION## @@ -296,7 +296,7 @@ fastf_set_bases = set_bases ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'set_dict' ## firstlineno 50 ##SECTION## @@ -346,7 +346,7 @@ fastf_set_dict = set_dict ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'retrieve' ## firstlineno 55 ##SECTION## @@ -420,7 +420,7 @@ fastf_retrieve = retrieve ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'lookup' ## firstlineno 62 ##SECTION## @@ -552,7 +552,7 @@ fastf_lookup = lookup ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'get_class_module' ## firstlineno 74 ##SECTION## @@ -632,7 +632,7 @@ fastf_get_class_module = get_class_module ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'mro_lookup' ## firstlineno 83 ##SECTION## @@ -709,71 +709,9 @@ fastf_mro_lookup = mro_lookup ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function 'seqiter' -## firstlineno 93 -##SECTION## -def seqiter(space, __args__): - funcname = "seqiter" - signature = ['func'], None, None - defaults_w = [] - w_func, = __args__.parse(funcname, signature, defaults_w) - return fastf_seqiter(space, w_func) - -f_seqiter = seqiter - -def seqiter(space, w_func): - - w_1=w_2=w_3=w_4=w_5=w_6=v7=w_10=w_11=w_12=w_13=v14=w_etype=w_evalue=None - - goto = 1 # startblock - while True: - - if goto == 1: - try: - w_1 = space.call_function(w_func, gi_0) - w_2 = w_1 - goto = 5 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_3, w_4, w_5 = e.w_type, e.w_value, e.w_type - goto = 2 - else:raise # unhandled case, should not happen - - if goto == 2: - w_6 = space.is_(w_5, space.w_IndexError) - v7 = space.is_true(w_6) - if v7 == True: - w_etype, w_evalue = space.w_StopIteration, space.w_None - goto = 4 - else: - assert v7 == False - w_10, w_11, w_12 = w_3, w_4, w_5 - goto = 3 - - if goto == 3: - w_13 = space.issubtype(w_12, space.w_IndexError) - v14 = space.is_true(w_13) - if v14 == True: - w_etype, w_evalue = space.w_StopIteration, space.w_None - goto = 4 - else: - assert v14 == False - w_etype, w_evalue = w_10, w_11 - goto = 4 - - if goto == 4: - raise OperationError(w_etype, w_evalue) - - if goto == 5: - return w_2 - -fastf_seqiter = seqiter - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__new__' -## firstlineno 109 +## firstlineno 111 ##SECTION## # global declarations # global object gfunc_type_err @@ -1188,9 +1126,9 @@ fastf___new__ = __new__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__setattr__' -## firstlineno 159 +## firstlineno 161 ##SECTION## # global declarations # global object gfunc_set_name @@ -1276,9 +1214,9 @@ fastf_classobj___setattr__ = __setattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__delattr__' -## firstlineno 169 +## firstlineno 171 ##SECTION## # global declarations # global object g3tuple_2 @@ -1327,9 +1265,9 @@ fastf_classobj___delattr__ = __delattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__getattribute__' -## firstlineno 176 +## firstlineno 178 ##SECTION## # global declarations # global object gs___get__ @@ -1468,9 +1406,9 @@ fastf_classobj___getattribute__ = __getattribute__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__repr__' -## firstlineno 193 +## firstlineno 195 ##SECTION## # global declarations # global object gfunc_uid @@ -1507,9 +1445,9 @@ fastf_classobj___repr__ = __repr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__str__' -## firstlineno 197 +## firstlineno 199 ##SECTION## # global declarations # global object gfunc_get_class_module @@ -1563,9 +1501,9 @@ fastf_classobj___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__call__' -## firstlineno 204 +## firstlineno 206 ##SECTION## # global declarations # global object gbltinmethod___new__ @@ -1633,9 +1571,9 @@ fastf_classobj___call__ = __call__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'instance_getattr1' -## firstlineno 225 +## firstlineno 227 ##SECTION## # global declarations # global object gs___class__ @@ -1853,9 +1791,9 @@ fastf_instance_getattr1 = instance_getattr1 ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__getattribute__' -## firstlineno 249 +## firstlineno 251 ##SECTION## # global declaration # global object gs___getattr__ @@ -1960,9 +1898,9 @@ fastf_instance___getattribute__ = __getattribute__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__new__' -## firstlineno 258 +## firstlineno 260 ##SECTION## # global declarations # global object gs_instance___first_arg_must_be_cla @@ -2049,9 +1987,9 @@ fastf___new___1 = __new__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__setattr__' -## firstlineno 271 +## firstlineno 273 ##SECTION## # global declarations # global object gs___dict___must_be_set_to_a_dictio @@ -2173,9 +2111,9 @@ fastf_instance___setattr__ = __setattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__delattr__' -## firstlineno 287 +## firstlineno 289 ##SECTION## # global declarations # global object g2tuple_2 @@ -2315,9 +2253,9 @@ fastf_instance___delattr__ = __delattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__repr__' -## firstlineno 303 +## firstlineno 305 ##SECTION## # global declaration # global object gs___s__s_instance_at_0x_x_ @@ -2409,9 +2347,9 @@ fastf_instance___repr__ = __repr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__str__' -## firstlineno 312 +## firstlineno 314 ##SECTION## def __str__(space, __args__): funcname = "__str__" @@ -2489,9 +2427,9 @@ fastf_instance___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__hash__' -## firstlineno 319 +## firstlineno 321 ##SECTION## # global declarations # global object gs_unhashable_instance @@ -2602,9 +2540,9 @@ fastf_instance___hash__ = __hash__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__len__' -## firstlineno 333 +## firstlineno 335 ##SECTION## # global declarations # global object gs___len_____should_return____0 @@ -2667,9 +2605,9 @@ fastf_instance___len__ = __len__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__getitem__' -## firstlineno 342 +## firstlineno 344 ##SECTION## # global declaration # global object gs___getslice__ @@ -2749,9 +2687,9 @@ fastf_instance___getitem__ = __getitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__setitem__' -## firstlineno 349 +## firstlineno 351 ##SECTION## # global declarations # global object gs_step @@ -2837,9 +2775,9 @@ fastf_instance___setitem__ = __setitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__delitem__' -## firstlineno 356 +## firstlineno 358 ##SECTION## # global declaration # global object gs___delslice__ @@ -2919,9 +2857,9 @@ fastf_instance___delitem__ = __delitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__contains__' -## firstlineno 363 +## firstlineno 365 ##SECTION## def __contains__(space, __args__): funcname = "__contains__" @@ -2991,9 +2929,9 @@ fastf_instance___contains__ = __contains__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__coerce__' -## firstlineno 384 +## firstlineno 386 ##SECTION## def __coerce__(space, __args__): funcname = "__coerce__" @@ -3033,9 +2971,9 @@ fastf_instance___coerce__ = __coerce__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__pow__' -## firstlineno 438 +## firstlineno 440 ##SECTION## def __pow__(space, __args__): funcname = "__pow__" @@ -3139,9 +3077,9 @@ fastf_instance___pow__ = __pow__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__rpow__' -## firstlineno 456 +## firstlineno 458 ##SECTION## def __rpow__(space, __args__): funcname = "__rpow__" @@ -3245,9 +3183,9 @@ fastf_instance___rpow__ = __rpow__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__nonzero__' -## firstlineno 474 +## firstlineno 476 ##SECTION## # global declarations # global object gs___nonzero_____should_return____0 @@ -3337,9 +3275,9 @@ fastf_instance___nonzero__ = __nonzero__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__call__' -## firstlineno 489 +## firstlineno 491 ##SECTION## # global declaration # global object gs__s_instance_has_no___call___meth @@ -3394,14 +3332,14 @@ fastf_instance___call__ = __call__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__iter__' -## firstlineno 509 +## firstlineno 511 ##SECTION## # global declarations # global object gs___iter___returned_non_iterator_o # global object gs_iteration_over_non_sequence -# global object gfunc_seqiter +# global object gs__seqiter def __iter__(space, __args__): funcname = "__iter__" @@ -3414,7 +3352,7 @@ def __iter__(space, w_self): - w_func=v2=w_self_1=w_func_2=v12=w_etype=w_evalue=w_func_3=w_13=None + w_func=v2=w_self_1=w_func_2=v12=w_etype=w_evalue=w_self_2=w_13=None w_6=w_func_1=w_ret=w_4=v5=w_ret_1=w_7=w_8=w_9=None goto = 1 # startblock @@ -3454,7 +3392,7 @@ w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___getitem__, space.w_False) v12 = space.is_true(w_func_2) if v12 == True: - w_func_3 = w_func_2 + w_self_2 = w_self_1 goto = 5 else: assert v12 == False @@ -3463,7 +3401,7 @@ goto = 6 if goto == 5: - w_13 = fastf_seqiter(space, w_func_3) + w_13 = space.call_function((space.getattr(space.w_builtin, gs__seqiter)), w_self_2) w_6 = w_13 goto = 7 @@ -3476,9 +3414,9 @@ fastf_instance___iter__ = __iter__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'next' -## firstlineno 524 +## firstlineno 526 ##SECTION## # global declaration # global object gs_instance_has_no_next___method @@ -3525,9 +3463,9 @@ fastf_instance_next = next ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__cmp__' -## firstlineno 530 +## firstlineno 532 ##SECTION## # global declarations # global object gs___cmp___must_return_int @@ -3726,9 +3664,9 @@ fastf_instance___cmp__ = __cmp__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'purify' -## firstlineno 568 +## firstlineno 570 ##SECTION## # global declarations # global object g3tuple @@ -3937,7 +3875,7 @@ # global object gfunc_classobj___str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__abs__' ## firstlineno 4 ##SECTION## @@ -3969,7 +3907,7 @@ fastf_instance___abs__ = __abs__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__add__' ## firstlineno 4 ##SECTION## @@ -4046,7 +3984,7 @@ fastf_instance___add__ = __add__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__and__' ## firstlineno 4 ##SECTION## @@ -4123,7 +4061,7 @@ fastf_instance___and__ = __and__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__div__' ## firstlineno 4 ##SECTION## @@ -4200,7 +4138,7 @@ fastf_instance___div__ = __div__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__divmod__' ## firstlineno 4 ##SECTION## @@ -4277,7 +4215,7 @@ fastf_instance___divmod__ = __divmod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__eq__' ## firstlineno 4 ##SECTION## @@ -4352,7 +4290,7 @@ fastf_instance___eq__ = __eq__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__float__' ## firstlineno 4 ##SECTION## @@ -4384,7 +4322,7 @@ fastf_instance___float__ = __float__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__floordiv__' ## firstlineno 4 ##SECTION## @@ -4461,7 +4399,7 @@ fastf_instance___floordiv__ = __floordiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ge__' ## firstlineno 4 ##SECTION## @@ -4536,7 +4474,7 @@ fastf_instance___ge__ = __ge__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__gt__' ## firstlineno 4 ##SECTION## @@ -4611,7 +4549,7 @@ fastf_instance___gt__ = __gt__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__hex__' ## firstlineno 4 ##SECTION## @@ -4643,7 +4581,7 @@ fastf_instance___hex__ = __hex__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__iadd__' ## firstlineno 4 ##SECTION## @@ -4685,7 +4623,7 @@ fastf_instance___iadd__ = __iadd__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__iand__' ## firstlineno 4 ##SECTION## @@ -4727,7 +4665,7 @@ fastf_instance___iand__ = __iand__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__idiv__' ## firstlineno 4 ##SECTION## @@ -4769,7 +4707,7 @@ fastf_instance___idiv__ = __idiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ifloordiv__' ## firstlineno 4 ##SECTION## @@ -4811,7 +4749,7 @@ fastf_instance___ifloordiv__ = __ifloordiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ilshift__' ## firstlineno 4 ##SECTION## @@ -4853,7 +4791,7 @@ fastf_instance___ilshift__ = __ilshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__imod__' ## firstlineno 4 ##SECTION## @@ -4895,7 +4833,7 @@ fastf_instance___imod__ = __imod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__imul__' ## firstlineno 4 ##SECTION## @@ -4937,7 +4875,7 @@ fastf_instance___imul__ = __imul__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__int__' ## firstlineno 4 ##SECTION## @@ -4969,7 +4907,7 @@ fastf_instance___int__ = __int__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__invert__' ## firstlineno 4 ##SECTION## @@ -5001,7 +4939,7 @@ fastf_instance___invert__ = __invert__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ior__' ## firstlineno 4 ##SECTION## @@ -5043,7 +4981,7 @@ fastf_instance___ior__ = __ior__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ipow__' ## firstlineno 4 ##SECTION## @@ -5085,7 +5023,7 @@ fastf_instance___ipow__ = __ipow__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__irshift__' ## firstlineno 4 ##SECTION## @@ -5127,7 +5065,7 @@ fastf_instance___irshift__ = __irshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__isub__' ## firstlineno 4 ##SECTION## @@ -5169,7 +5107,7 @@ fastf_instance___isub__ = __isub__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__itruediv__' ## firstlineno 4 ##SECTION## @@ -5211,7 +5149,7 @@ fastf_instance___itruediv__ = __itruediv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ixor__' ## firstlineno 4 ##SECTION## @@ -5253,7 +5191,7 @@ fastf_instance___ixor__ = __ixor__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__le__' ## firstlineno 4 ##SECTION## @@ -5328,7 +5266,7 @@ fastf_instance___le__ = __le__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__long__' ## firstlineno 4 ##SECTION## @@ -5360,7 +5298,7 @@ fastf_instance___long__ = __long__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__lshift__' ## firstlineno 4 ##SECTION## @@ -5437,7 +5375,7 @@ fastf_instance___lshift__ = __lshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__lt__' ## firstlineno 4 ##SECTION## @@ -5512,7 +5450,7 @@ fastf_instance___lt__ = __lt__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__mod__' ## firstlineno 4 ##SECTION## @@ -5589,7 +5527,7 @@ fastf_instance___mod__ = __mod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__mul__' ## firstlineno 4 ##SECTION## @@ -5666,7 +5604,7 @@ fastf_instance___mul__ = __mul__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ne__' ## firstlineno 4 ##SECTION## @@ -5741,7 +5679,7 @@ fastf_instance___ne__ = __ne__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__neg__' ## firstlineno 4 ##SECTION## @@ -5773,7 +5711,7 @@ fastf_instance___neg__ = __neg__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__oct__' ## firstlineno 4 ##SECTION## @@ -5805,7 +5743,7 @@ fastf_instance___oct__ = __oct__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__or__' ## firstlineno 4 ##SECTION## @@ -5882,7 +5820,7 @@ fastf_instance___or__ = __or__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__pos__' ## firstlineno 4 ##SECTION## @@ -5914,7 +5852,7 @@ fastf_instance___pos__ = __pos__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rshift__' ## firstlineno 4 ##SECTION## @@ -5991,7 +5929,7 @@ fastf_instance___rshift__ = __rshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__sub__' ## firstlineno 4 ##SECTION## @@ -6068,7 +6006,7 @@ fastf_instance___sub__ = __sub__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__truediv__' ## firstlineno 4 ##SECTION## @@ -6145,7 +6083,7 @@ fastf_instance___truediv__ = __truediv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__xor__' ## firstlineno 4 ##SECTION## @@ -6225,7 +6163,7 @@ fastf_instance___xor__ = __xor__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__radd__' ## firstlineno 14 ##SECTION## @@ -6302,7 +6240,7 @@ fastf_instance___radd__ = __radd__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rand__' ## firstlineno 14 ##SECTION## @@ -6379,7 +6317,7 @@ fastf_instance___rand__ = __rand__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rdiv__' ## firstlineno 14 ##SECTION## @@ -6456,7 +6394,7 @@ fastf_instance___rdiv__ = __rdiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rdivmod__' ## firstlineno 14 ##SECTION## @@ -6533,7 +6471,7 @@ fastf_instance___rdivmod__ = __rdivmod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rfloordiv__' ## firstlineno 14 ##SECTION## @@ -6610,7 +6548,7 @@ fastf_instance___rfloordiv__ = __rfloordiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rlshift__' ## firstlineno 14 ##SECTION## @@ -6687,7 +6625,7 @@ fastf_instance___rlshift__ = __rlshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rmod__' ## firstlineno 14 ##SECTION## @@ -6764,7 +6702,7 @@ fastf_instance___rmod__ = __rmod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rmul__' ## firstlineno 14 ##SECTION## @@ -6841,7 +6779,7 @@ fastf_instance___rmul__ = __rmul__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__ror__' ## firstlineno 14 ##SECTION## @@ -6918,7 +6856,7 @@ fastf_instance___ror__ = __ror__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rrshift__' ## firstlineno 14 ##SECTION## @@ -6995,7 +6933,7 @@ fastf_instance___rrshift__ = __rrshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rsub__' ## firstlineno 14 ##SECTION## @@ -7072,7 +7010,7 @@ fastf_instance___rsub__ = __rsub__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rtruediv__' ## firstlineno 14 ##SECTION## @@ -7149,7 +7087,7 @@ fastf_instance___rtruediv__ = __rtruediv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' +## filename '/Users/pedronis/PyPy/dist/pypy/purify' ## function '__rxor__' ## firstlineno 14 ##SECTION## @@ -7606,9 +7544,8 @@ del m.__itruediv__ m.gs___iter___returned_non_iterator_o = space.wrap('__iter__ returned non-iterator of type %s') m.gs_iteration_over_non_sequence = space.wrap('iteration over non-sequence') - m.gfunc_seqiter = space.wrap(interp2app(f_seqiter)) + m.gs__seqiter = space.wrap('_seqiter') del m.__iter__ - del m.seqiter del m.__isub__ del m.__irshift__ del m.__ipow__ Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Thu Feb 10 22:00:35 2005 @@ -432,6 +432,9 @@ return s.translate(C_IDENTIFIER) def nameof_function(self, func, namehint=''): + if hasattr(func, 'geninterplevel_name'): + return func.geninterplevel_name(self) + printable_name = '(%s:%d) %s' % ( self.trans_funcname(func.func_globals.get('__name__', '?')), func.func_code.co_firstlineno, From hpk at codespeak.net Fri Feb 11 00:24:07 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 00:24:07 +0100 (MET) Subject: [pypy-svn] r9095 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050210232407.BEDCB27BCB@code1.codespeak.net> Author: hpk Date: Fri Feb 11 00:24:07 2005 New Revision: 9095 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Log: handle default arguments for applevel functions defined via appdef(). This involves some (very localized) hacking at definition time but basically doesn't change the semantics of the still existing "space.appexec()". I.e. if you provide: app = appdef("app(x, y=1)", """ return x + y """) the 'app' hook will be compiled from generated sourcode (more or less with pure string-juggling with some help of py.code.Source() :-) The resulting interplevel hook for the app-level definition (as seen by the translator) looks like this: def app(space, w_x, w_y=None): if w_y is None: w_y = space.wrap(1) pypyco = PyCode(space)._from_code(newco) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) frame.setfastscope([w_x, w_y]) return frame.run() which looks pretty reasonable compared to gateway.app2interp and friends, doesn't it? Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 00:24:07 2005 @@ -645,18 +645,6 @@ # and now for something completly different ... # -# the following function might just go away -#def preparesource(source): -# from pypy.tool.pytestsupport import py # aehem -# argdecl, source = source.split(':', 1) -# argdecl = argdecl.strip() -# if not argdecl.startswith('(') or not argdecl.endswith(')'): -# raise SyntaxError("incorrect exec_with header\n%s" % source) -# -# newco = peparesource_funcdecl(source, argdecl+'(') -# argnames = argdecl[1:-1].strip().split(',') -# return newco, argnames - def preparesource(source, funcdecl): from pypy.tool.pytestsupport import py @@ -669,24 +657,56 @@ return d[funcdecl[:i]].func_code def appdef(funcdecl, source): - from pypy.tool.pytestsupport import py from pypy.interpreter.pycode import PyCode + from pypy.tool.pytestsupport import py newco = preparesource(source, funcdecl) funcname, decl = funcdecl.split('(', 1) decl = decl.strip()[:-1] - wargnames = ["w_%s" % x.strip() for x in decl[:-1].split(',')] - wdecl = ", ".join(wargnames) - source = py.code.Source(""" + wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) + source = py.code.Source("""\ def %s(space, %s): + # HERE we inject the defhandlingsource below pypyco = PyCode(space)._from_code(newco) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) frame.setfastscope([%s]) return frame.run() - """ % (funcname, wdecl, wdecl)) + """ % (funcname, wfuncdecl, wfastscope)) + source.lines[1:2] = defaulthandlingsource.indent().lines + print str(source) glob = { 'newco' : newco, 'PyCode': PyCode, } exec source.compile() in glob return glob[funcname] + +def specialargparse(decl): + from pypy.tool.pytestsupport import py # for code generation + wfuncargs = [] + wfastnames = [] + defaultargs = [] + for name in decl.split(','): + name = "w_%s" % name.strip() + if '=' in name: + name, value = name.split('=') + wfastnames.append(name) + defaultargs.append((name, value)) + name += "=None" + else: + assert not defaultargs, "posarg follows defaultarg" + wfastnames.append(name) + wfuncargs.append(name) + + # now we generate some nice code for default arg checking + # (which does not imply that the code doing it is nice :-) + defaulthandlingsource = py.code.Source() + while defaultargs: + name, value = defaultargs.pop() + defaulthandlingsource = defaulthandlingsource.putaround("""\ + if %s is None: + %s = space.wrap(%s) + """ % (name, name, value), "") + wfuncdecl = ", ".join(wfuncargs) + wfastdecl = ", ".join(wfastnames) + return wfuncdecl, wfastdecl, defaulthandlingsource Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Fri Feb 11 00:24:07 2005 @@ -31,3 +31,12 @@ assert app.func_name == 'app' w_result = app(space, space.wrap(41), space.wrap(1)) assert space.eq_w(w_result, space.wrap(42)) + +def test_applevel_withdefault(space): + app = appdef("app(x,y=1)", """ + return x + y + """) + assert app.func_name == 'app' + w_result = app(space, space.wrap(41)) + assert space.eq_w(w_result, space.wrap(42)) + From hpk at codespeak.net Fri Feb 11 00:42:32 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 00:42:32 +0100 (MET) Subject: [pypy-svn] r9096 - in pypy/branch/dist-interpapp/pypy: interpreter interpreter/test tool Message-ID: <20050210234232.51F8427BCB@code1.codespeak.net> Author: hpk Date: Fri Feb 11 00:42:32 2005 New Revision: 9096 Added: pypy/branch/dist-interpapp/pypy/tool/getpy.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Log: make appdef an almost wholesale substitute for app2interp: you can pass in cpython-functions which are basically looked up via inspect.getsource() and then fed into the normal appdef code. also make py more easily importable from interpreter/ (there is a conflict with py.py :-) note that the py lib is only used at code-definition / construction time. The translator should not see the py lib accessed. allowed Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 00:42:32 2005 @@ -19,6 +19,8 @@ from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache +# internal non-translatable parts: +from pypy.tool.getpy import py # XXX from interpreter/ we get py.py NoneNotWrapped = object() @@ -647,7 +649,7 @@ # def preparesource(source, funcdecl): - from pypy.tool.pytestsupport import py + """ NOT_RPYTHON """ source = py.code.Source(source) source = source.putaround("def %s:" % funcdecl) d = {} @@ -656,9 +658,14 @@ assert i != -1 return d[funcdecl[:i]].func_code -def appdef(funcdecl, source): +def appdef(source): + """ NOT_RPYTHON """ from pypy.interpreter.pycode import PyCode - from pypy.tool.pytestsupport import py + if not isinstance(source, str): + source = str(py.code.Source(source).strip()) + assert source.startswith("def "), "can only transform functions" + source = source[4:] + funcdecl, source = str(source).split(':', 1) newco = preparesource(source, funcdecl) funcname, decl = funcdecl.split('(', 1) decl = decl.strip()[:-1] @@ -682,11 +689,13 @@ return glob[funcname] def specialargparse(decl): - from pypy.tool.pytestsupport import py # for code generation + """ NOT_RPYTHON """ wfuncargs = [] wfastnames = [] defaultargs = [] for name in decl.split(','): + if not name.strip(): + continue name = "w_%s" % name.strip() if '=' in name: name, value = name.split('=') Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Fri Feb 11 00:42:32 2005 @@ -25,7 +25,7 @@ assert str(excinfo).find('y y') != -1 def test_simple_applevel(space): - app = appdef("app(x,y)", """ + app = appdef("""app(x,y): return x + y """) assert app.func_name == 'app' @@ -33,10 +33,27 @@ assert space.eq_w(w_result, space.wrap(42)) def test_applevel_withdefault(space): - app = appdef("app(x,y=1)", """ + app = appdef("""app(x,y=1): return x + y """) assert app.func_name == 'app' w_result = app(space, space.wrap(41)) assert space.eq_w(w_result, space.wrap(42)) +def test_applevel_noargs(space): + app = appdef("""app(): + return 42 + """) + assert app.func_name == 'app' + w_result = app(space) + assert space.eq_w(w_result, space.wrap(42)) + +def somefunc(arg2=42): + return arg2 + +def test_app2interp_somefunc(space): + app = appdef(somefunc) + w_result = app(space) + assert space.eq_w(w_result, space.wrap(42)) + + Added: pypy/branch/dist-interpapp/pypy/tool/getpy.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/tool/getpy.py Fri Feb 11 00:42:32 2005 @@ -0,0 +1 @@ +import py From hpk at codespeak.net Fri Feb 11 02:16:18 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 02:16:18 +0100 (MET) Subject: [pypy-svn] r9097 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211011618.7B59027BE6@code1.codespeak.net> Author: hpk Date: Fri Feb 11 02:16:18 2005 New Revision: 9097 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: small tweaks Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 02:16:18 2005 @@ -658,16 +658,20 @@ assert i != -1 return d[funcdecl[:i]].func_code -def appdef(source): +def appdef(source, overridename=None): """ NOT_RPYTHON """ from pypy.interpreter.pycode import PyCode if not isinstance(source, str): source = str(py.code.Source(source).strip()) assert source.startswith("def "), "can only transform functions" source = source[4:] - funcdecl, source = str(source).split(':', 1) + funcdecl, source = source.strip().split(':', 1) newco = preparesource(source, funcdecl) funcname, decl = funcdecl.split('(', 1) + if overridename is not None: + funcname = overridename + else: + funcname = funcname.strip() decl = decl.strip()[:-1] wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) source = py.code.Source("""\ @@ -680,7 +684,6 @@ return frame.run() """ % (funcname, wfuncdecl, wfastscope)) source.lines[1:2] = defaulthandlingsource.indent().lines - print str(source) glob = { 'newco' : newco, 'PyCode': PyCode, From ac at codespeak.net Fri Feb 11 10:40:47 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 11 Feb 2005 10:40:47 +0100 (MET) Subject: [pypy-svn] r9100 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050211094047.E405E27BB1@code1.codespeak.net> Author: ac Date: Fri Feb 11 10:40:47 2005 New Revision: 9100 Added: pypy/dist/pypy/objspace/std/test/test_fake.py (contents, props changed) Modified: pypy/dist/pypy/objspace/std/fake.py Log: Make faked types a little more inheritable. Modified: pypy/dist/pypy/objspace/std/fake.py ============================================================================== --- pypy/dist/pypy/objspace/std/fake.py (original) +++ pypy/dist/pypy/objspace/std/fake.py Fri Feb 11 10:40:47 2005 @@ -65,7 +65,9 @@ r = cpy_type.__new__(cpy_type, *args) except: wrap_exception(space) - return W_Fake(space, r) + w_obj = space.allocate_instance(W_Fake, w_type) + w_obj.__init__(space, r) + return w_obj kw['__new__'] = gateway.interp2app(fake__new__, unwrap_spec = [baseobjspace.ObjSpace, @@ -85,6 +87,7 @@ w_self.val = val def unwrap(w_self): return w_self.val + # cannot write to W_Fake.__name__ in Python 2.2! W_Fake = type(W_Object)('W_Fake%s'%(cpy_type.__name__.capitalize()), (W_Object,), Added: pypy/dist/pypy/objspace/std/test/test_fake.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/objspace/std/test/test_fake.py Fri Feb 11 10:40:47 2005 @@ -0,0 +1,14 @@ +# test the integration of unicode and strings (even though we don't +# really implement unicode yet). + +import autopath, sys + + +objspacename = 'std' + +class AppTestFakedTypes: + def test_inheriting(self): + class MyUnicode(unicode): + pass + my_u = MyUnicode('123') + assert type(my_u) is MyUnicode From ac at codespeak.net Fri Feb 11 10:57:55 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Fri, 11 Feb 2005 10:57:55 +0100 (MET) Subject: [pypy-svn] r9102 - pypy/dist/pypy/objspace/std Message-ID: <20050211095755.80E2727BC1@code1.codespeak.net> Author: ac Date: Fri Feb 11 10:57:55 2005 New Revision: 9102 Modified: pypy/dist/pypy/objspace/std/longobject.py Log: Quick fix to make pow(int, int, long) work. Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Fri Feb 11 10:57:55 2005 @@ -183,6 +183,21 @@ space.wrap(e.args[0])) return W_LongObject(space, t) +def pow__Int_Int_Long(space, w_int1, w_int2, w_long3): + x = w_int1.intval + y = w_int2.intval + z = w_long3.longval + + try: + t = long(pow(x, y, z)) + except TypeError, e: + raise OperationError(space.w_TypeError, + space.wrap(e.args[0])) + except ValueError, e: + raise OperationError(space.w_ValueError, + space.wrap(e.args[0])) + return W_LongObject(space, t) + def neg__Long(space, w_long1): return W_LongObject(space, -w_long1.longval) From hpk at codespeak.net Fri Feb 11 13:25:44 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 13:25:44 +0100 (MET) Subject: [pypy-svn] r9104 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211122544.0538827BD1@code1.codespeak.net> Author: hpk Date: Fri Feb 11 13:25:44 2005 New Revision: 9104 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Log: - move printing code mostly to interp-level (with a few appexec()s - now gateway.appdef is used by default instead of gateway.app2interp! which gives much nicer tracebacks among other things, tests in interpreter pass, those in objspace/std not because we can't share globals and slicetype.py is very heavy in using that Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 13:25:44 2005 @@ -676,7 +676,7 @@ wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) source = py.code.Source("""\ def %s(space, %s): - # HERE we inject the defhandlingsource below + # HERE we inject the defaultargs-handling below pypyco = PyCode(space)._from_code(newco) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) @@ -684,6 +684,7 @@ return frame.run() """ % (funcname, wfuncdecl, wfastscope)) source.lines[1:2] = defaulthandlingsource.indent().lines + print str(source) glob = { 'newco' : newco, 'PyCode': PyCode, @@ -722,3 +723,5 @@ wfuncdecl = ", ".join(wfuncargs) wfastdecl = ", ".join(wfastnames) return wfuncdecl, wfastdecl, defaulthandlingsource + +app2interp = appdef Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Fri Feb 11 13:25:44 2005 @@ -345,7 +345,7 @@ w_globals = f.valuestack.pop() w_prog = f.valuestack.pop() w_compile_flags = f.space.wrap(f.get_compile_flags()) - w_resulttuple = f.prepare_exec(w_prog, w_globals, w_locals, + w_resulttuple = prepare_exec(f.space, f.space.wrap(f), w_prog, w_globals, w_locals, w_compile_flags) w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3) @@ -357,44 +357,6 @@ if plain: f.setdictscope(w_locals) - def app_prepare_exec(f, prog, globals, locals, compile_flags): - """Manipulate parameters to exec statement to (codeobject, dict, dict). - """ - # XXX INCOMPLETE - if (globals is None and locals is None and - isinstance(prog, tuple) and - (len(prog) == 2 or len(prog) == 3)): - globals = prog[1] - if len(prog) == 3: - locals = prog[2] - prog = prog[0] - if globals is None: - globals = f.f_globals - if locals is None: - locals = f.f_locals - if locals is None: - locals = globals - if not isinstance(globals, dict): - raise TypeError("exec: arg 2 must be a dictionary or None") - elif not globals.has_key('__builtins__'): - globals['__builtins__'] = f.f_builtins - if not isinstance(locals, dict): - raise TypeError("exec: arg 3 must be a dictionary or None") - # XXX - HACK to check for code object - co = compile('1','','eval') - if isinstance(prog, type(co)): - return (prog, globals, locals) - if not isinstance(prog, str): - ## if not (isinstance(prog, types.StringTypes) or - ## isinstance(prog, types.FileType)): - raise TypeError("exec: arg 1 must be a string, file, or code object") - ## if isinstance(prog, types.FileType): - ## co = compile(prog.read(),prog.name,'exec',comple_flags,1) - ## return (co,globals,locals) - else: # prog is a string - co = compile(prog,'','exec', compile_flags, 1) - return (co, globals, locals) - def POP_BLOCK(f): block = f.blockstack.pop() block.cleanup(f) # the block knows how to clean up the value stack @@ -785,44 +747,58 @@ # There are also a couple of helpers that are methods, defined in the # class above. -def app_print_expr(x): - try: - displayhook = sys.displayhook - except AttributeError: - raise RuntimeError("lost sys.displayhook") - displayhook(x) - -def app_file_softspace(file, newflag): - try: - softspace = file.softspace - except AttributeError: - softspace = 0 - try: - file.softspace = newflag - except AttributeError: - pass - return softspace - -def app_sys_stdout(): - try: - return sys.stdout - except AttributeError: - raise RuntimeError("lost sys.stdout") +def print_expr(space, w_x): + space.appexec([w_x], """ + (x): + try: + displayhook = sys.displayhook + except AttributeError: + raise RuntimeError("lost sys.displayhook") + displayhook(x) + """) + +def file_softspace(space, w_file, w_newflag): + return space.appexec([w_file, w_newflag], """ + (file, newflag): + try: + softspace = file.softspace + except AttributeError: + softspace = 0 + try: + file.softspace = newflag + except AttributeError: + pass + return softspace + """) + +def sys_stdout(space): + try: + return space.getattr(space.w_sys, space.wrap('stdout')) + except OperationError, e: + if not e.match(space, space.w_AttributeError): + raise + raise OperationError(space.w_RuntimeError, "lost sys.stdout") + +def print_item_to(space, w_x, w_stream): + if space.is_true(file_softspace(space, w_stream, space.w_False)): + space.call_method(w_stream, 'write', space.wrap(" ")) + space.call_method(w_stream, 'write', space.str(w_x)) -def app_print_item_to(x, stream): - if file_softspace(stream, False): - stream.write(" ") - stream.write(str(x)) # add a softspace unless we just printed a string which ends in a '\t' # or '\n' -- or more generally any whitespace character but ' ' - if isinstance(x, str) and len(x) and x[-1].isspace() and x[-1]!=' ': - return + w_skip = space.appexec([w_x], """ + (x): + return isinstance(x, str) and len(x) and \ + x[-1].isspace() and x[-1]!=' ' + """) + if space.is_true(w_skip): + return # XXX add unicode handling - file_softspace(stream, True) + file_softspace(space, w_stream, space.w_True) -def app_print_newline_to(stream): - stream.write("\n") - file_softspace(stream, False) +def print_newline_to(space, w_stream): + space.call_method(w_stream, 'write', space.wrap("\n")) + file_softspace(space, w_stream, space.w_False) def app_find_metaclass(bases, namespace, globals, builtins): if '__metaclass__' in namespace: @@ -859,4 +835,42 @@ into_locals[name] = getattr(module, name) +def app_prepare_exec(f, prog, globals, locals, compile_flags): + """Manipulate parameters to exec statement to (codeobject, dict, dict). + """ + # XXX INCOMPLETE + if (globals is None and locals is None and + isinstance(prog, tuple) and + (len(prog) == 2 or len(prog) == 3)): + globals = prog[1] + if len(prog) == 3: + locals = prog[2] + prog = prog[0] + if globals is None: + globals = f.f_globals + if locals is None: + locals = f.f_locals + if locals is None: + locals = globals + if not isinstance(globals, dict): + raise TypeError("exec: arg 2 must be a dictionary or None") + elif not globals.has_key('__builtins__'): + globals['__builtins__'] = f.f_builtins + if not isinstance(locals, dict): + raise TypeError("exec: arg 3 must be a dictionary or None") + # XXX - HACK to check for code object + co = compile('1','','eval') + if isinstance(prog, type(co)): + return (prog, globals, locals) + if not isinstance(prog, str): +## if not (isinstance(prog, types.StringTypes) or +## isinstance(prog, types.FileType)): + raise TypeError("exec: arg 1 must be a string, file, or code object") +## if isinstance(prog, types.FileType): +## co = compile(prog.read(),prog.name,'exec',comple_flags,1) +## return (co,globals,locals) + else: # prog is a string + co = compile(prog,'','exec', compile_flags, 1) + return (co, globals, locals) + gateway.importall(globals()) # app_xxx() -> xxx() From arigo at codespeak.net Fri Feb 11 13:58:36 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 11 Feb 2005 13:58:36 +0100 (MET) Subject: [pypy-svn] r9106 - pypy/dist/pypy/objspace/std Message-ID: <20050211125836.08DF827BC1@code1.codespeak.net> Author: arigo Date: Fri Feb 11 13:58:35 2005 New Revision: 9106 Modified: pypy/dist/pypy/objspace/std/multimethod.py Log: Python 2.2 compatibility. Modified: pypy/dist/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/dist/pypy/objspace/std/multimethod.py Fri Feb 11 13:58:35 2005 @@ -23,12 +23,9 @@ self.argnames_after = argnames_after def register(self, function, *types, **kwds): - try: - order = kwds.pop('order') - except KeyError: - order = 0 - assert not kwds assert len(types) == self.arity + assert kwds.keys() == [] or kwds.keys() == ['order'] + order = kwds.get('order', 0) node = self.dispatch_tree for type in types[:-1]: node = node.setdefault(type, {}) From hpk at codespeak.net Fri Feb 11 14:04:45 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 14:04:45 +0100 (MET) Subject: [pypy-svn] r9108 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050211130445.005EB27BD1@code1.codespeak.net> Author: hpk Date: Fri Feb 11 14:04:45 2005 New Revision: 9108 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Log: fix ordering bug for default-handling code, add a test for that Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 14:04:45 2005 @@ -715,7 +715,7 @@ # (which does not imply that the code doing it is nice :-) defaulthandlingsource = py.code.Source() while defaultargs: - name, value = defaultargs.pop() + name, value = defaultargs.pop(0) defaulthandlingsource = defaulthandlingsource.putaround("""\ if %s is None: %s = space.wrap(%s) Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Fri Feb 11 14:04:45 2005 @@ -32,7 +32,7 @@ w_result = app(space, space.wrap(41), space.wrap(1)) assert space.eq_w(w_result, space.wrap(42)) -def test_applevel_withdefault(space): +def test_applevel_with_one_default(space): app = appdef("""app(x,y=1): return x + y """) @@ -40,6 +40,20 @@ w_result = app(space, space.wrap(41)) assert space.eq_w(w_result, space.wrap(42)) +def test_applevel_with_two_defaults(space): + app = appdef("""app(x=1,y=2): + return x + y + """) + w_result = app(space, space.wrap(41), space.wrap(1)) + assert space.eq_w(w_result, space.wrap(42)) + + w_result = app(space, space.wrap(15)) + assert space.eq_w(w_result, space.wrap(17)) + + w_result = app(space) + assert space.eq_w(w_result, space.wrap(3)) + + def test_applevel_noargs(space): app = appdef("""app(): return 42 From hpk at codespeak.net Fri Feb 11 14:54:06 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 14:54:06 +0100 (MET) Subject: [pypy-svn] r9111 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050211135406.405D327BE7@code1.codespeak.net> Author: hpk Date: Fri Feb 11 14:54:06 2005 New Revision: 9111 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_class.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py Log: get rid of app2interp and app2interp_temp alltogether. very few tests had to be changed containing indentation that makes live for "appdef()" too hard: multiline source code fed to 'exec'. appdef() dumbly indents/deindents source code on a line-by-line basis and doesn't use the tokenizer to detect multiline strings which should stay unmodified if we want to be correct. See the change to test_class.py for how you can fix the involved indentation problem (which also makes the test code more nicely readable). Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 14:54:06 2005 @@ -467,56 +467,6 @@ w_obj, space.type(w_obj)) -class app2interp(Gateway): - """Build a Gateway that calls 'app' at app-level.""" - - NOT_RPYTHON_ATTRIBUTES = ['_staticcode'] + Gateway.NOT_RPYTHON_ATTRIBUTES - - def __init__(self, app, app_name=None): - "NOT_RPYTHON" - Gateway.__init__(self) - # app must be a function whose name starts with 'app_'. - if not isinstance(app, types.FunctionType): - raise TypeError, "function expected, got %r instead" % app - if app_name is None: - if not app.func_name.startswith('app_'): - raise ValueError, ("function name must start with 'app_'; " - "%r does not" % app.func_name) - app_name = app.func_name[4:] - self.__name__ = app.func_name - self.name = app_name - self._staticcode = app.func_code - self._staticglobals = app.func_globals - self._staticdefs = list(app.func_defaults or ()) - - def getcode(self, space): - "NOT_RPYTHON" - from pypy.interpreter import pycode - code = pycode.PyCode(space) - code._from_code(self._staticcode) - return code - - def getdefaults(self, space): - "NOT_RPYTHON" - return [space.wrap(val) for val in self._staticdefs] - - def __call__(self, space, *args_w): - # to call the Gateway as a non-method, 'space' must be explicitly - # supplied. We build the Function object and call it. - fn = self.get_function(space) - return space.call_function(space.wrap(fn), *args_w) - - def __get__(self, obj, cls=None): - "NOT_RPYTHON" - if obj is None: - return self - else: - space = obj.space - w_method = space.wrap(self.get_method(obj)) - def helper_method_caller(*args_w): - return space.call_function(w_method, *args_w) - return helper_method_caller - class interp2app(Gateway): """Build a Gateway that calls 'f' at interp-level.""" @@ -632,12 +582,6 @@ # # the next gateways are to be used only for # temporary/initialization purposes -class app2interp_temp(app2interp): - "NOT_RPYTHON" - def getcache(self, space): - return self.__dict__.setdefault(space, Cache()) - # ^^^^^ - # armin suggested this class interp2app_temp(interp2app): "NOT_RPYTHON" @@ -725,3 +669,29 @@ return wfuncdecl, wfastdecl, defaulthandlingsource app2interp = appdef + +# for app2interp_temp (used for testing mainly) we can use *args +class app2interp_temp(object): + def __init__(self, func, overridename=None): + """ NOT_RPYTHON """ + self.appfunc = appdef(func, overridename) + + def __get__(self, instance, cls=None): + """ NOT_RPYTHON """ + return app2interp_temp_method(self.appfunc, instance) + + def __call__(self, space, *args_w, **kwargs_w): + """ NOT_RPYTHON """ + return self.appfunc(space, *args_w, **kwargs_w) + +class app2interp_temp_method(object): + def __init__(self, func, instance): + """ NOT_RPYTHON """ + self.func = func + self.instance = instance + + def __call__(self, *args_w, **kwargs_w): + """ NOT_RPYTHON """ + space = self.instance.space + return self.appfunc(space, space.wrap(self.instance), + *args_w, **kwargs_w) Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Fri Feb 11 14:54:06 2005 @@ -69,5 +69,14 @@ app = appdef(somefunc) w_result = app(space) assert space.eq_w(w_result, space.wrap(42)) + +def app_test_something_at_app_level(): + x = 2 + assert x/2 == 1 +class AppTestMethods: + def test_somee_app_test_method(self): + assert 2 == 2 + + Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_class.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_class.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_class.py Fri Feb 11 14:54:06 2005 @@ -30,15 +30,14 @@ def test_metaclass_global(self): d = {} - metatest_text = """ -class M(type): - pass - -__metaclass__ = M - -class C: - pass -""" + metatest_text = """if 1: + class M(type): + pass + + __metaclass__ = M + + class C: + pass\n""" exec metatest_text in d C = d['C'] M = d['M'] Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py Fri Feb 11 14:54:06 2005 @@ -1,6 +1,7 @@ import autopath from pypy.interpreter import gateway +import py class TestBuiltinCode: def test_signature(self): @@ -55,6 +56,11 @@ class TestGateway: + + def setup_method(self, method): + name = method.im_func.func_name + if name in ('test_importall', 'test_exportall'): + py.test.skip("sharing globals for app2interp'ed functions not supported") def test_app2interp(self): w = self.space.wrap def app_g3(a, b): From arigo at codespeak.net Fri Feb 11 14:57:14 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 11 Feb 2005 14:57:14 +0100 (MET) Subject: [pypy-svn] r9112 - pypy/dist/pypy/tool Message-ID: <20050211135714.9047327BE8@code1.codespeak.net> Author: arigo Date: Fri Feb 11 14:57:14 2005 New Revision: 9112 Modified: pypy/dist/pypy/tool/utestconvert.py Log: Not sure why failUnlessEqual(x,y) is converted into assert not x!=y. Modified: pypy/dist/pypy/tool/utestconvert.py ============================================================================== --- pypy/dist/pypy/tool/utestconvert.py (original) +++ pypy/dist/pypy/tool/utestconvert.py Fri Feb 11 14:57:14 2005 @@ -18,11 +18,11 @@ d['assertEqual'] = ('assert', ' ==', [2,3]) d['failIfEqual'] = ('assert not', ' ==', [2,3]) d['assertNotEqual'] = ('assert', ' !=', [2,3]) -d['failUnlessEqual'] = ('assert not', ' !=', [2,3]) +d['failUnlessEqual'] = ('assert', ' ==', [2,3]) d['assertAlmostEqual'] = ('assert round', ' ==', [2,3,4]) d['failIfAlmostEqual'] = ('assert not round', ' ==', [2,3,4]) d['assertNotAlmostEqual'] = ('assert round', ' !=', [2,3,4]) -d['failUnlessAlmostEquals'] = ('assert not round', ' !=', [2,3,4]) +d['failUnlessAlmostEquals'] = ('assert round', ' ==', [2,3,4]) # PyPy specific d['assertRaises_w'] = ('self.space.raises_w', '', ['Any']) d['assertEqual_w'] = ('assert self.space.eq_w','',['Any']) From hpk at codespeak.net Fri Feb 11 16:06:06 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 16:06:06 +0100 (MET) Subject: [pypy-svn] r9122 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211150606.F064027BB9@code1.codespeak.net> Author: hpk Date: Fri Feb 11 16:06:06 2005 New Revision: 9122 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: intermediate checkin of the try to use appexec which is mainly a string-formatting problem now :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 16:06:06 2005 @@ -610,7 +610,7 @@ assert source.startswith("def "), "can only transform functions" source = source[4:] funcdecl, source = source.strip().split(':', 1) - newco = preparesource(source, funcdecl) + #newco = preparesource(source, funcdecl) funcname, decl = funcdecl.split('(', 1) if overridename is not None: funcname = overridename @@ -618,21 +618,25 @@ funcname = funcname.strip() decl = decl.strip()[:-1] wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) - source = py.code.Source("""\ - def %s(space, %s): - # HERE we inject the defaultargs-handling below - pypyco = PyCode(space)._from_code(newco) - w_glob = space.newdict([]) - frame = pypyco.create_frame(space, w_glob) - frame.setfastscope([%s]) - return frame.run() - """ % (funcname, wfuncdecl, wfastscope)) - source.lines[1:2] = defaulthandlingsource.indent().lines + + # get rid of w_ + fastscope = ", ".join([x.strip()[2:] for x in wfastscope.split(',')]) + + # construct the special app source passed to appexec + appsource = py.code.Source(source).strip().putaround("(%s):" % fastscope, "") + sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals()] + sourcelines.extend(defaulthandlingsource.indent().lines) + sourcelines.append( + " return space.appexec([%(wfastscope)s], '''" % locals()) + for line in appsource.indent().indent().lines: + line = line.replace("'''", "\'\'\'") + sourcelines.append(line) + sourcelines.append( "''')") + source = py.code.Source() + source.lines = sourcelines + #source = py.code.Source(sourcelines) print str(source) - glob = { - 'newco' : newco, - 'PyCode': PyCode, - } + glob = {} exec source.compile() in glob return glob[funcname] From tismer at codespeak.net Fri Feb 11 16:55:06 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 11 Feb 2005 16:55:06 +0100 (MET) Subject: [pypy-svn] r9126 - pypy/dist/pypy/tool Message-ID: <20050211155506.4579627BBF@code1.codespeak.net> Author: tismer Date: Fri Feb 11 16:55:06 2005 New Revision: 9126 Modified: pypy/dist/pypy/tool/sourcetools.py Log: fixed backslash handling (how could I forget this) Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Fri Feb 11 16:55:06 2005 @@ -16,6 +16,7 @@ doc = func if doc is None: return None + doc = doc.replace('\\', r'\\') compare = [] for q in '"""', "'''": txt = indent_str + q + doc.replace(q[0], "\\"+q[0]) + q + closing_str From hpk at codespeak.net Fri Feb 11 17:08:22 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 17:08:22 +0100 (MET) Subject: [pypy-svn] r9127 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211160822.73B0327BBF@code1.codespeak.net> Author: hpk Date: Fri Feb 11 17:08:22 2005 New Revision: 9127 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: slight fix for correct quoting of multiline strings (thanks to armin, samuele and christian :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 17:08:22 2005 @@ -622,6 +622,7 @@ # get rid of w_ fastscope = ", ".join([x.strip()[2:] for x in wfastscope.split(',')]) + # SOME MESS AHEAD ! # construct the special app source passed to appexec appsource = py.code.Source(source).strip().putaround("(%s):" % fastscope, "") sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals()] @@ -629,13 +630,11 @@ sourcelines.append( " return space.appexec([%(wfastscope)s], '''" % locals()) for line in appsource.indent().indent().lines: - line = line.replace("'''", "\'\'\'") + line = line.replace("\\", r"\\").replace("'", r"\'") sourcelines.append(line) sourcelines.append( "''')") source = py.code.Source() source.lines = sourcelines - #source = py.code.Source(sourcelines) - print str(source) glob = {} exec source.compile() in glob return glob[funcname] From pedronis at codespeak.net Fri Feb 11 17:13:00 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 11 Feb 2005 17:13:00 +0100 (MET) Subject: [pypy-svn] r9128 - in pypy/dist/pypy: lib module Message-ID: <20050211161300.A866027BB0@code1.codespeak.net> Author: pedronis Date: Fri Feb 11 17:13:00 2005 New Revision: 9128 Modified: pypy/dist/pypy/lib/_classobj.py pypy/dist/pypy/module/classobjinterp.py Log: slight change to _classobj to make translate_pypy -no-a happy again Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Fri Feb 11 17:13:00 2005 @@ -13,14 +13,15 @@ obj_setattr = object.__setattr__ obj_getattribute = object.__getattribute__ -MASK = sys.maxint * 2 + 1 +HMASK = long(sys.maxint) def uid(o): v = id(o) if v < 0: - v += MASK - v += 1 - return v & MASK + v += HMASK + v += HMASK + v += 2 + return v # we use slots that we remove from type __dict__ for special attributes # Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Fri Feb 11 17:13:00 2005 @@ -6,7 +6,7 @@ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '_coerce' ## firstlineno 7 ##SECTION## @@ -68,14 +68,14 @@ fastf__coerce = _coerce ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'uid' ## firstlineno 18 ##SECTION## # global declarations # global object gi_0 -# global object glong_0xffffffffL -# global object gi_1 +# global object glong_0x7fffffffL +# global object gi_2 def uid(space, __args__): funcname = "uid" @@ -88,7 +88,7 @@ def uid(space, w_o): - w_v=w_2=v3=w_v_2=w_4=w_5=w_v_1=w_v_3=w_v_4=None + w_v=w_2=v3=w_4=w_v_1=w_v_2=w_v_3=w_v_4=None goto = 1 # startblock while True: @@ -102,29 +102,25 @@ goto = 2 else: assert v3 == False - w_v_2 = w_v + w_4 = w_v goto = 3 if goto == 2: - w_v_3 = space.inplace_add(w_v_1, glong_0xffffffffL) - w_v_4 = space.inplace_add(w_v_3, gi_1) - w_v_2 = w_v_4 + w_v_2 = space.inplace_add(w_v_1, glong_0x7fffffffL) + w_v_3 = space.inplace_add(w_v_2, glong_0x7fffffffL) + w_v_4 = space.inplace_add(w_v_3, gi_2) + w_4 = w_v_4 goto = 3 if goto == 3: - w_4 = space.and_(w_v_2, glong_0xffffffffL) - w_5 = w_4 - goto = 4 - - if goto == 4: - return w_5 + return w_4 fastf_uid = uid ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'type_err' -## firstlineno 34 +## firstlineno 35 ##SECTION## # global declaration # global object gs_argument__s_must_be__s__not__s @@ -160,9 +156,9 @@ fastf_type_err = type_err ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'set_name' -## firstlineno 37 +## firstlineno 38 ##SECTION## # global declarations # global object gs___name___must_be_a_string_object @@ -211,9 +207,9 @@ fastf_set_name = set_name ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'set_bases' -## firstlineno 42 +## firstlineno 43 ##SECTION## # global declarations # global object gs___bases___must_be_a_tuple_object @@ -296,9 +292,9 @@ fastf_set_bases = set_bases ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'set_dict' -## firstlineno 50 +## firstlineno 51 ##SECTION## # global declarations # global object gcls_TypeError @@ -346,9 +342,9 @@ fastf_set_dict = set_dict ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'retrieve' -## firstlineno 55 +## firstlineno 56 ##SECTION## # global declarations # global object gdescriptor_object___getattribute__ @@ -420,9 +416,9 @@ fastf_retrieve = retrieve ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'lookup' -## firstlineno 62 +## firstlineno 63 ##SECTION## # global declaration # global object g2tuple_1 @@ -552,9 +548,9 @@ fastf_lookup = lookup ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'get_class_module' -## firstlineno 74 +## firstlineno 75 ##SECTION## # global declarations # global object gfunc_retrieve @@ -632,9 +628,9 @@ fastf_get_class_module = get_class_module ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'mro_lookup' -## firstlineno 83 +## firstlineno 84 ##SECTION## # global declaration # global object gs___mro__ @@ -709,9 +705,9 @@ fastf_mro_lookup = mro_lookup ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__new__' -## firstlineno 111 +## firstlineno 112 ##SECTION## # global declarations # global object gfunc_type_err @@ -1126,9 +1122,9 @@ fastf___new__ = __new__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__setattr__' -## firstlineno 161 +## firstlineno 162 ##SECTION## # global declarations # global object gfunc_set_name @@ -1214,9 +1210,9 @@ fastf_classobj___setattr__ = __setattr__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__delattr__' -## firstlineno 171 +## firstlineno 172 ##SECTION## # global declarations # global object g3tuple_2 @@ -1265,14 +1261,14 @@ fastf_classobj___delattr__ = __delattr__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__getattribute__' -## firstlineno 178 +## firstlineno 179 ##SECTION## # global declarations # global object gs___get__ +# global object gi_1 # global object gfunc_lookup -# global object gi_2 # global object gcls_ValueError # global object gs_class__s_has_no_attribute__s # global object gfunc_mro_lookup @@ -1406,9 +1402,9 @@ fastf_classobj___getattribute__ = __getattribute__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__repr__' -## firstlineno 195 +## firstlineno 196 ##SECTION## # global declarations # global object gfunc_uid @@ -1445,9 +1441,9 @@ fastf_classobj___repr__ = __repr__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__str__' -## firstlineno 199 +## firstlineno 200 ##SECTION## # global declarations # global object gfunc_get_class_module @@ -1501,9 +1497,9 @@ fastf_classobj___str__ = __str__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__call__' -## firstlineno 206 +## firstlineno 207 ##SECTION## # global declarations # global object gbltinmethod___new__ @@ -1571,9 +1567,9 @@ fastf_classobj___call__ = __call__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'instance_getattr1' -## firstlineno 227 +## firstlineno 228 ##SECTION## # global declarations # global object gs___class__ @@ -1791,9 +1787,9 @@ fastf_instance_getattr1 = instance_getattr1 ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__getattribute__' -## firstlineno 251 +## firstlineno 252 ##SECTION## # global declaration # global object gs___getattr__ @@ -1898,9 +1894,9 @@ fastf_instance___getattribute__ = __getattribute__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__new__' -## firstlineno 260 +## firstlineno 261 ##SECTION## # global declarations # global object gs_instance___first_arg_must_be_cla @@ -1987,9 +1983,9 @@ fastf___new___1 = __new__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__setattr__' -## firstlineno 273 +## firstlineno 274 ##SECTION## # global declarations # global object gs___dict___must_be_set_to_a_dictio @@ -2111,9 +2107,9 @@ fastf_instance___setattr__ = __setattr__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__delattr__' -## firstlineno 289 +## firstlineno 290 ##SECTION## # global declarations # global object g2tuple_2 @@ -2253,9 +2249,9 @@ fastf_instance___delattr__ = __delattr__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__repr__' -## firstlineno 305 +## firstlineno 306 ##SECTION## # global declaration # global object gs___s__s_instance_at_0x_x_ @@ -2347,9 +2343,9 @@ fastf_instance___repr__ = __repr__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__str__' -## firstlineno 314 +## firstlineno 315 ##SECTION## def __str__(space, __args__): funcname = "__str__" @@ -2427,9 +2423,9 @@ fastf_instance___str__ = __str__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__hash__' -## firstlineno 321 +## firstlineno 322 ##SECTION## # global declarations # global object gs_unhashable_instance @@ -2540,9 +2536,9 @@ fastf_instance___hash__ = __hash__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__len__' -## firstlineno 335 +## firstlineno 336 ##SECTION## # global declarations # global object gs___len_____should_return____0 @@ -2605,9 +2601,9 @@ fastf_instance___len__ = __len__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__getitem__' -## firstlineno 344 +## firstlineno 345 ##SECTION## # global declaration # global object gs___getslice__ @@ -2687,9 +2683,9 @@ fastf_instance___getitem__ = __getitem__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__setitem__' -## firstlineno 351 +## firstlineno 352 ##SECTION## # global declarations # global object gs_step @@ -2775,9 +2771,9 @@ fastf_instance___setitem__ = __setitem__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__delitem__' -## firstlineno 358 +## firstlineno 359 ##SECTION## # global declaration # global object gs___delslice__ @@ -2857,9 +2853,9 @@ fastf_instance___delitem__ = __delitem__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__contains__' -## firstlineno 365 +## firstlineno 366 ##SECTION## def __contains__(space, __args__): funcname = "__contains__" @@ -2929,9 +2925,9 @@ fastf_instance___contains__ = __contains__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__coerce__' -## firstlineno 386 +## firstlineno 387 ##SECTION## def __coerce__(space, __args__): funcname = "__coerce__" @@ -2971,9 +2967,9 @@ fastf_instance___coerce__ = __coerce__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__pow__' -## firstlineno 440 +## firstlineno 441 ##SECTION## def __pow__(space, __args__): funcname = "__pow__" @@ -3077,9 +3073,9 @@ fastf_instance___pow__ = __pow__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__rpow__' -## firstlineno 458 +## firstlineno 459 ##SECTION## def __rpow__(space, __args__): funcname = "__rpow__" @@ -3183,9 +3179,9 @@ fastf_instance___rpow__ = __rpow__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__nonzero__' -## firstlineno 476 +## firstlineno 477 ##SECTION## # global declarations # global object gs___nonzero_____should_return____0 @@ -3275,9 +3271,9 @@ fastf_instance___nonzero__ = __nonzero__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__call__' -## firstlineno 491 +## firstlineno 492 ##SECTION## # global declaration # global object gs__s_instance_has_no___call___meth @@ -3332,9 +3328,9 @@ fastf_instance___call__ = __call__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__iter__' -## firstlineno 511 +## firstlineno 512 ##SECTION## # global declarations # global object gs___iter___returned_non_iterator_o @@ -3414,9 +3410,9 @@ fastf_instance___iter__ = __iter__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'next' -## firstlineno 526 +## firstlineno 527 ##SECTION## # global declaration # global object gs_instance_has_no_next___method @@ -3463,9 +3459,9 @@ fastf_instance_next = next ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function '__cmp__' -## firstlineno 532 +## firstlineno 533 ##SECTION## # global declarations # global object gs___cmp___must_return_int @@ -3664,9 +3660,9 @@ fastf_instance___cmp__ = __cmp__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' ## function 'purify' -## firstlineno 570 +## firstlineno 571 ##SECTION## # global declarations # global object g3tuple @@ -3875,7 +3871,7 @@ # global object gfunc_classobj___str__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__abs__' ## firstlineno 4 ##SECTION## @@ -3907,7 +3903,7 @@ fastf_instance___abs__ = __abs__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__add__' ## firstlineno 4 ##SECTION## @@ -3984,7 +3980,7 @@ fastf_instance___add__ = __add__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__and__' ## firstlineno 4 ##SECTION## @@ -4061,7 +4057,7 @@ fastf_instance___and__ = __and__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__div__' ## firstlineno 4 ##SECTION## @@ -4138,7 +4134,7 @@ fastf_instance___div__ = __div__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__divmod__' ## firstlineno 4 ##SECTION## @@ -4215,7 +4211,7 @@ fastf_instance___divmod__ = __divmod__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__eq__' ## firstlineno 4 ##SECTION## @@ -4290,7 +4286,7 @@ fastf_instance___eq__ = __eq__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__float__' ## firstlineno 4 ##SECTION## @@ -4322,7 +4318,7 @@ fastf_instance___float__ = __float__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__floordiv__' ## firstlineno 4 ##SECTION## @@ -4399,7 +4395,7 @@ fastf_instance___floordiv__ = __floordiv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ge__' ## firstlineno 4 ##SECTION## @@ -4474,7 +4470,7 @@ fastf_instance___ge__ = __ge__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__gt__' ## firstlineno 4 ##SECTION## @@ -4549,7 +4545,7 @@ fastf_instance___gt__ = __gt__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__hex__' ## firstlineno 4 ##SECTION## @@ -4581,7 +4577,7 @@ fastf_instance___hex__ = __hex__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__iadd__' ## firstlineno 4 ##SECTION## @@ -4623,7 +4619,7 @@ fastf_instance___iadd__ = __iadd__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__iand__' ## firstlineno 4 ##SECTION## @@ -4665,7 +4661,7 @@ fastf_instance___iand__ = __iand__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__idiv__' ## firstlineno 4 ##SECTION## @@ -4707,7 +4703,7 @@ fastf_instance___idiv__ = __idiv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ifloordiv__' ## firstlineno 4 ##SECTION## @@ -4749,7 +4745,7 @@ fastf_instance___ifloordiv__ = __ifloordiv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ilshift__' ## firstlineno 4 ##SECTION## @@ -4791,7 +4787,7 @@ fastf_instance___ilshift__ = __ilshift__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__imod__' ## firstlineno 4 ##SECTION## @@ -4833,7 +4829,7 @@ fastf_instance___imod__ = __imod__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__imul__' ## firstlineno 4 ##SECTION## @@ -4875,7 +4871,7 @@ fastf_instance___imul__ = __imul__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__int__' ## firstlineno 4 ##SECTION## @@ -4907,7 +4903,7 @@ fastf_instance___int__ = __int__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__invert__' ## firstlineno 4 ##SECTION## @@ -4939,7 +4935,7 @@ fastf_instance___invert__ = __invert__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ior__' ## firstlineno 4 ##SECTION## @@ -4981,7 +4977,7 @@ fastf_instance___ior__ = __ior__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ipow__' ## firstlineno 4 ##SECTION## @@ -5023,7 +5019,7 @@ fastf_instance___ipow__ = __ipow__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__irshift__' ## firstlineno 4 ##SECTION## @@ -5065,7 +5061,7 @@ fastf_instance___irshift__ = __irshift__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__isub__' ## firstlineno 4 ##SECTION## @@ -5107,7 +5103,7 @@ fastf_instance___isub__ = __isub__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__itruediv__' ## firstlineno 4 ##SECTION## @@ -5149,7 +5145,7 @@ fastf_instance___itruediv__ = __itruediv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ixor__' ## firstlineno 4 ##SECTION## @@ -5191,7 +5187,7 @@ fastf_instance___ixor__ = __ixor__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__le__' ## firstlineno 4 ##SECTION## @@ -5266,7 +5262,7 @@ fastf_instance___le__ = __le__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__long__' ## firstlineno 4 ##SECTION## @@ -5298,7 +5294,7 @@ fastf_instance___long__ = __long__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__lshift__' ## firstlineno 4 ##SECTION## @@ -5375,7 +5371,7 @@ fastf_instance___lshift__ = __lshift__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__lt__' ## firstlineno 4 ##SECTION## @@ -5450,7 +5446,7 @@ fastf_instance___lt__ = __lt__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__mod__' ## firstlineno 4 ##SECTION## @@ -5527,7 +5523,7 @@ fastf_instance___mod__ = __mod__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__mul__' ## firstlineno 4 ##SECTION## @@ -5604,7 +5600,7 @@ fastf_instance___mul__ = __mul__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ne__' ## firstlineno 4 ##SECTION## @@ -5679,7 +5675,7 @@ fastf_instance___ne__ = __ne__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__neg__' ## firstlineno 4 ##SECTION## @@ -5711,7 +5707,7 @@ fastf_instance___neg__ = __neg__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__oct__' ## firstlineno 4 ##SECTION## @@ -5743,7 +5739,7 @@ fastf_instance___oct__ = __oct__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__or__' ## firstlineno 4 ##SECTION## @@ -5820,7 +5816,7 @@ fastf_instance___or__ = __or__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__pos__' ## firstlineno 4 ##SECTION## @@ -5852,7 +5848,7 @@ fastf_instance___pos__ = __pos__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rshift__' ## firstlineno 4 ##SECTION## @@ -5929,7 +5925,7 @@ fastf_instance___rshift__ = __rshift__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__sub__' ## firstlineno 4 ##SECTION## @@ -6006,7 +6002,7 @@ fastf_instance___sub__ = __sub__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__truediv__' ## firstlineno 4 ##SECTION## @@ -6083,7 +6079,7 @@ fastf_instance___truediv__ = __truediv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__xor__' ## firstlineno 4 ##SECTION## @@ -6163,7 +6159,7 @@ fastf_instance___xor__ = __xor__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__radd__' ## firstlineno 14 ##SECTION## @@ -6240,7 +6236,7 @@ fastf_instance___radd__ = __radd__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rand__' ## firstlineno 14 ##SECTION## @@ -6317,7 +6313,7 @@ fastf_instance___rand__ = __rand__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rdiv__' ## firstlineno 14 ##SECTION## @@ -6394,7 +6390,7 @@ fastf_instance___rdiv__ = __rdiv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rdivmod__' ## firstlineno 14 ##SECTION## @@ -6471,7 +6467,7 @@ fastf_instance___rdivmod__ = __rdivmod__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rfloordiv__' ## firstlineno 14 ##SECTION## @@ -6548,7 +6544,7 @@ fastf_instance___rfloordiv__ = __rfloordiv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rlshift__' ## firstlineno 14 ##SECTION## @@ -6625,7 +6621,7 @@ fastf_instance___rlshift__ = __rlshift__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rmod__' ## firstlineno 14 ##SECTION## @@ -6702,7 +6698,7 @@ fastf_instance___rmod__ = __rmod__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rmul__' ## firstlineno 14 ##SECTION## @@ -6779,7 +6775,7 @@ fastf_instance___rmul__ = __rmul__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__ror__' ## firstlineno 14 ##SECTION## @@ -6856,7 +6852,7 @@ fastf_instance___ror__ = __ror__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rrshift__' ## firstlineno 14 ##SECTION## @@ -6933,7 +6929,7 @@ fastf_instance___rrshift__ = __rrshift__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rsub__' ## firstlineno 14 ##SECTION## @@ -7010,7 +7006,7 @@ fastf_instance___rsub__ = __rsub__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rtruediv__' ## firstlineno 14 ##SECTION## @@ -7087,7 +7083,7 @@ fastf_instance___rtruediv__ = __rtruediv__ ##SECTION## -## filename '/Users/pedronis/PyPy/dist/pypy/purify' +## filename '/u/pedronis/PyPy/dist/pypy/purify' ## function '__rxor__' ## firstlineno 14 ##SECTION## @@ -7467,12 +7463,12 @@ m.gs__class__s__s_at_0x_x_ = space.wrap('') del m.__repr__ m.gi_0 = space.newint(0) - m.glong_0xffffffffL = space.wrap(0xffffffffL) # XXX implement long! - m.gi_1 = space.newint(1) + m.glong_0x7fffffffL = space.wrap(0x7fffffffL) # XXX implement long! + m.gi_2 = space.newint(2) del m.uid m.gs___get__ = space.wrap('__get__') + m.gi_1 = space.newint(1) m.gfunc_lookup = space.wrap(interp2app(f_lookup)) - m.gi_2 = space.newint(2) m.gs_class__s_has_no_attribute__s = space.wrap('class %s has no attribute %s') m.gfunc_mro_lookup = space.wrap(interp2app(f_mro_lookup)) del m.__getattribute__ From arigo at codespeak.net Fri Feb 11 17:22:56 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 11 Feb 2005 17:22:56 +0100 (MET) Subject: [pypy-svn] r9129 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211162256.B834E27BB0@code1.codespeak.net> Author: arigo Date: Fri Feb 11 17:22:56 2005 New Revision: 9129 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Log: - accept a missing function name in gateway.appdef() - rewrote print_expr() at interp-level to avoid the dependency on the 'sys' module - rewrote file_softspace() using appdef Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 17:22:56 2005 @@ -615,7 +615,7 @@ if overridename is not None: funcname = overridename else: - funcname = funcname.strip() + funcname = funcname.strip() or 'anonymous' decl = decl.strip()[:-1] wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Fri Feb 11 17:22:56 2005 @@ -748,17 +748,15 @@ # class above. def print_expr(space, w_x): - space.appexec([w_x], """ - (x): - try: - displayhook = sys.displayhook - except AttributeError: - raise RuntimeError("lost sys.displayhook") - displayhook(x) - """) + try: + w_displayhook = space.getattr(space.w_sys, space.wrap('displayhook')) + except OperationError, e: + if not e.match(space, space.w_AttributeError): + raise + raise OperationError(space.w_RuntimeError, "lost sys.displayhook") + space.call_function(w_displayhook, w_x) -def file_softspace(space, w_file, w_newflag): - return space.appexec([w_file, w_newflag], """ +file_softspace = gateway.appdef(""" (file, newflag): try: softspace = file.softspace From hpk at codespeak.net Fri Feb 11 17:45:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 17:45:08 +0100 (MET) Subject: [pypy-svn] r9132 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211164508.3AEBC27BC1@code1.codespeak.net> Author: hpk Date: Fri Feb 11 17:45:08 2005 New Revision: 9132 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: - get rid of unused app2interp_temp_method - preserve function name across appexec() - slight renamings of variables Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Fri Feb 11 17:45:08 2005 @@ -276,20 +276,20 @@ raise TypeError, 'space.exec_(): expected a string, code or PyCode object' return statement.exec_code(self, w_globals, w_locals) - def appexec(self, posargs, source): + def appexec(self, posargs_w, source, funcname="anon"): """ return value from executing given source at applevel with given name=wrapped value parameters as its starting scope. Note: EXPERIMENTAL. """ space = self - pypyco = pypycodecache.getorbuild((space,source), buildpypycode, posargs) + pypyco = pypycodecache.getorbuild((space,source, funcname), buildpypycode, posargs_w) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) - frame.setfastscope(posargs) + frame.setfastscope(posargs_w) return frame.run() pypycodecache = Cache() -def buildpypycode((space, source), posargs): +def buildpypycode((space, source, funcname), posargs_w): """ NOT_RPYTHON """ # XXX will change once we have our own compiler from pypy.interpreter.pycode import PyCode @@ -299,10 +299,10 @@ if not argdecl.startswith('(') or not argdecl.endswith(')'): raise SyntaxError("incorrect exec_with header\n%s" % source) source = py.code.Source(source) - source = source.putaround("def anon%s:" % argdecl) + source = source.putaround("def %s%s:" % (funcname, argdecl)) d = {} exec source.compile() in d - newco = d['anon'].func_code + newco = d[funcname].func_code return PyCode(space)._from_code(newco) ## Table describing the regular part of the interface of object spaces, Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 17:45:08 2005 @@ -624,7 +624,7 @@ # SOME MESS AHEAD ! # construct the special app source passed to appexec - appsource = py.code.Source(source).strip().putaround("(%s):" % fastscope, "") + appsource = py.code.Source(source).strip().putaround("(%s):" % fastscope) sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals()] sourcelines.extend(defaulthandlingsource.indent().lines) sourcelines.append( @@ -632,7 +632,7 @@ for line in appsource.indent().indent().lines: line = line.replace("\\", r"\\").replace("'", r"\'") sourcelines.append(line) - sourcelines.append( "''')") + sourcelines.append( "''', funcname=%r)" % funcname) source = py.code.Source() source.lines = sourcelines glob = {} @@ -679,22 +679,6 @@ """ NOT_RPYTHON """ self.appfunc = appdef(func, overridename) - def __get__(self, instance, cls=None): - """ NOT_RPYTHON """ - return app2interp_temp_method(self.appfunc, instance) - def __call__(self, space, *args_w, **kwargs_w): """ NOT_RPYTHON """ return self.appfunc(space, *args_w, **kwargs_w) - -class app2interp_temp_method(object): - def __init__(self, func, instance): - """ NOT_RPYTHON """ - self.func = func - self.instance = instance - - def __call__(self, *args_w, **kwargs_w): - """ NOT_RPYTHON """ - space = self.instance.space - return self.appfunc(space, space.wrap(self.instance), - *args_w, **kwargs_w) From hpk at codespeak.net Fri Feb 11 17:55:48 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 17:55:48 +0100 (MET) Subject: [pypy-svn] r9133 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211165548.77A7B27BD6@code1.codespeak.net> Author: hpk Date: Fri Feb 11 17:55:48 2005 New Revision: 9133 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Log: use loadfromcache Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Fri Feb 11 17:55:48 2005 @@ -34,6 +34,7 @@ def __init__(self): "NOT_RPYTHON: Basic initialization of objects." self._gatewaycache = Cache() + self._codecache = Cache() # set recursion limit self.recursion_limit = 1000 # sets all the internal descriptors @@ -282,14 +283,15 @@ Note: EXPERIMENTAL. """ space = self - pypyco = pypycodecache.getorbuild((space,source, funcname), buildpypycode, posargs_w) + pypyco = space.loadfromcache((source, funcname), buildpypycode, + self._codecache) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) frame.setfastscope(posargs_w) return frame.run() pypycodecache = Cache() -def buildpypycode((space, source, funcname), posargs_w): +def buildpypycode((source, funcname), space): """ NOT_RPYTHON """ # XXX will change once we have our own compiler from pypy.interpreter.pycode import PyCode From hpk at codespeak.net Fri Feb 11 18:08:18 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 18:08:18 +0100 (MET) Subject: [pypy-svn] r9134 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211170818.C84FC27BD9@code1.codespeak.net> Author: hpk Date: Fri Feb 11 18:08:18 2005 New Revision: 9134 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: simplified appexec() signature by allowing a function name to be optionally specified in the sourcecode string aka: func = appdef("""func(x,1): ... """) Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Fri Feb 11 18:08:18 2005 @@ -277,29 +277,33 @@ raise TypeError, 'space.exec_(): expected a string, code or PyCode object' return statement.exec_code(self, w_globals, w_locals) - def appexec(self, posargs_w, source, funcname="anon"): + def appexec(self, posargs_w, source): """ return value from executing given source at applevel with given name=wrapped value parameters as its starting scope. Note: EXPERIMENTAL. """ space = self - pypyco = space.loadfromcache((source, funcname), buildpypycode, - self._codecache) + pypyco = space.loadfromcache((source), buildpypycode, self._codecache) w_glob = space.newdict([]) frame = pypyco.create_frame(space, w_glob) frame.setfastscope(posargs_w) return frame.run() pypycodecache = Cache() -def buildpypycode((source, funcname), space): +def buildpypycode(source, space): """ NOT_RPYTHON """ # XXX will change once we have our own compiler from pypy.interpreter.pycode import PyCode from pypy.tool.pytestsupport import py # aehem argdecl, source = source.split(':', 1) argdecl = argdecl.strip() + i = argdecl.find('(') + if i >0: + funcname, argdecl = argdecl[:i], argdecl[i:] + else: + funcname = 'anon' if not argdecl.startswith('(') or not argdecl.endswith(')'): - raise SyntaxError("incorrect exec_with header\n%s" % source) + raise SyntaxError("incorrect appexec header\n%s" % source) source = py.code.Source(source) source = source.putaround("def %s%s:" % (funcname, argdecl)) d = {} Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 18:08:18 2005 @@ -624,7 +624,7 @@ # SOME MESS AHEAD ! # construct the special app source passed to appexec - appsource = py.code.Source(source).strip().putaround("(%s):" % fastscope) + appsource = py.code.Source(source).strip().putaround("%s(%s):" % (funcname, fastscope)) sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals()] sourcelines.extend(defaulthandlingsource.indent().lines) sourcelines.append( @@ -632,10 +632,11 @@ for line in appsource.indent().indent().lines: line = line.replace("\\", r"\\").replace("'", r"\'") sourcelines.append(line) - sourcelines.append( "''', funcname=%r)" % funcname) + sourcelines.append("''')") source = py.code.Source() source.lines = sourcelines glob = {} + print str(source) exec source.compile() in glob return glob[funcname] From hpk at codespeak.net Fri Feb 11 18:15:41 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 18:15:41 +0100 (MET) Subject: [pypy-svn] r9135 - in pypy/branch/dist-interpapp/pypy: . interpreter Message-ID: <20050211171541.F035027BDE@code1.codespeak.net> Author: hpk Date: Fri Feb 11 18:15:41 2005 New Revision: 9135 Modified: pypy/branch/dist-interpapp/pypy/conftest.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: appdef() doesn't need to offer overriding the function name (anymore) Modified: pypy/branch/dist-interpapp/pypy/conftest.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/conftest.py (original) +++ pypy/branch/dist-interpapp/pypy/conftest.py Fri Feb 11 18:15:41 2005 @@ -125,7 +125,7 @@ assert not args name = target.func_globals.get('objspacename', None) space = gettestobjspace(name) - func = app2interp_temp(target, target.__name__) + func = app2interp_temp(target) self.execute_appex(space, func, space) @@ -133,7 +133,7 @@ def execute(self, target, *args): assert not args space = target.im_self.space - func = app2interp_temp(target.im_func, target.__name__) + func = app2interp_temp(target.im_func) self.execute_appex(space, func, space, space.w_None) class AppClassCollector(py.test.collect.Class): Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 18:15:41 2005 @@ -562,7 +562,7 @@ for name, obj in d.items(): if name.startswith('app_') and name[4:] not in d: if isinstance(obj, types.FunctionType): - d[name[4:]] = a2i(obj, name[4:]) + d[name[4:]] = a2i(obj) def build_dict(d, space): """NOT_RPYTHON: @@ -602,7 +602,7 @@ assert i != -1 return d[funcdecl[:i]].func_code -def appdef(source, overridename=None): +def appdef(source): """ NOT_RPYTHON """ from pypy.interpreter.pycode import PyCode if not isinstance(source, str): @@ -612,10 +612,7 @@ funcdecl, source = source.strip().split(':', 1) #newco = preparesource(source, funcdecl) funcname, decl = funcdecl.split('(', 1) - if overridename is not None: - funcname = overridename - else: - funcname = funcname.strip() or 'anonymous' + funcname = funcname.strip() or 'anonymous' decl = decl.strip()[:-1] wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) @@ -676,9 +673,9 @@ # for app2interp_temp (used for testing mainly) we can use *args class app2interp_temp(object): - def __init__(self, func, overridename=None): + def __init__(self, func): """ NOT_RPYTHON """ - self.appfunc = appdef(func, overridename) + self.appfunc = appdef(func) def __call__(self, space, *args_w, **kwargs_w): """ NOT_RPYTHON """ From hpk at codespeak.net Fri Feb 11 18:17:52 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 18:17:52 +0100 (MET) Subject: [pypy-svn] r9136 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211171752.454B127BE4@code1.codespeak.net> Author: hpk Date: Fri Feb 11 18:17:52 2005 New Revision: 9136 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: un-print Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 18:17:52 2005 @@ -633,7 +633,6 @@ source = py.code.Source() source.lines = sourcelines glob = {} - print str(source) exec source.compile() in glob return glob[funcname] From arigo at codespeak.net Fri Feb 11 18:37:28 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 11 Feb 2005 18:37:28 +0100 (MET) Subject: [pypy-svn] r9138 - pypy/branch/dist-interpapp/pypy/objspace/flow Message-ID: <20050211173728.4FCA427BBF@code1.codespeak.net> Author: arigo Date: Fri Feb 11 18:37:28 2005 New Revision: 9138 Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py Log: - a fix following the appdef() refactoring - put a w_sys attribute on the flow object space, to allow some objects to be found as constants (e.g. sys.stdout in print statements). Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Fri Feb 11 18:37:28 2005 @@ -52,6 +52,7 @@ self.specialcases = {} #self.make_builtins() #self.make_sys() + self.w_sys = self.wrap(sys) def loadfromcache(self, key, builder, cache): # when populating the caches, the flow space switches to Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py Fri Feb 11 18:37:28 2005 @@ -83,7 +83,7 @@ return space.do_operation(opname, *args_w) def setup(space): - fn = pyframe.normalize_exception.get_function(space) + fn = pyframe.normalize_exception space.specialcases[fn] = sc_normalize_exception space.specialcases[__import__] = sc_import for opname in ['lt', 'le', 'eq', 'ne', 'gt', 'ge', 'is_']: From hpk at codespeak.net Fri Feb 11 18:45:35 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 18:45:35 +0100 (MET) Subject: [pypy-svn] r9139 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211174535.06EF127BF0@code1.codespeak.net> Author: hpk Date: Fri Feb 11 18:45:34 2005 New Revision: 9139 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Log: ups Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Fri Feb 11 18:45:34 2005 @@ -289,7 +289,6 @@ frame.setfastscope(posargs_w) return frame.run() -pypycodecache = Cache() def buildpypycode(source, space): """ NOT_RPYTHON """ # XXX will change once we have our own compiler From hpk at codespeak.net Fri Feb 11 19:04:39 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 11 Feb 2005 19:04:39 +0100 (MET) Subject: [pypy-svn] r9140 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211180439.41A1A27BE6@code1.codespeak.net> Author: hpk Date: Fri Feb 11 19:04:39 2005 New Revision: 9140 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: remove unused code Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 11 19:04:39 2005 @@ -592,16 +592,6 @@ # and now for something completly different ... # -def preparesource(source, funcdecl): - """ NOT_RPYTHON """ - source = py.code.Source(source) - source = source.putaround("def %s:" % funcdecl) - d = {} - exec source.compile() in d - i = funcdecl.find('(') - assert i != -1 - return d[funcdecl[:i]].func_code - def appdef(source): """ NOT_RPYTHON """ from pypy.interpreter.pycode import PyCode @@ -610,7 +600,6 @@ assert source.startswith("def "), "can only transform functions" source = source[4:] funcdecl, source = source.strip().split(':', 1) - #newco = preparesource(source, funcdecl) funcname, decl = funcdecl.split('(', 1) funcname = funcname.strip() or 'anonymous' decl = decl.strip()[:-1] From pedronis at codespeak.net Fri Feb 11 22:35:43 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 11 Feb 2005 22:35:43 +0100 (MET) Subject: [pypy-svn] r9145 - in pypy/branch/dist-interpapp/pypy: interpreter objspace/flow translator/tool Message-ID: <20050211213543.8032127B3D@code1.codespeak.net> Author: pedronis Date: Fri Feb 11 22:35:43 2005 New Revision: 9145 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py pypy/branch/dist-interpapp/pypy/translator/tool/tointerplevel.py Log: with appexec app helpers don't go anymore through space.call_args, so we need a appexec hook too for special cases. flow tests pass again this is still open to discussion Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Fri Feb 11 22:35:43 2005 @@ -785,7 +785,7 @@ # add a softspace unless we just printed a string which ends in a '\t' # or '\n' -- or more generally any whitespace character but ' ' w_skip = space.appexec([w_x], """ - (x): + app_skip_space(x): return isinstance(x, str) and len(x) and \ x[-1].isspace() and x[-1]!=' ' """) Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Fri Feb 11 22:35:43 2005 @@ -301,6 +301,17 @@ self.handle_implicit_exceptions(exceptions) return w_res + def appexec(self, posargs_w, source): + name_end = source.find('(') + appname = source[:name_end].strip() + #print appname + try: + sc = self.specialcases[appname] + except KeyError: + return ObjSpace.appexec(self, posargs_w, source) + else: + return sc(self, posargs_w) + def handle_implicit_exceptions(self, exceptions): if exceptions: # catch possible exceptions implicitly. If the OperationError Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py Fri Feb 11 22:35:43 2005 @@ -16,7 +16,7 @@ return None -def sc_normalize_exception(space, fn, args): +def sc_normalize_exception(space, args): """Special-case for 'raise' statements. Case-by-case analysis: * raise Class @@ -34,7 +34,7 @@ - assumes that Arg is the value you want for the exception, and that Class is exactly the exception class. No check or normalization. """ - w_arg1, w_arg2, w_tb = args.fixedunpack(3) + w_arg1, w_arg2, w_tb = args # w_arg3 (the traceback) is ignored and replaced with None # if it is a Variable, because pyopcode.py tries to unwrap it. @@ -82,9 +82,17 @@ opname = fn.__name__.replace('__', '') return space.do_operation(opname, *args_w) +def skip_space(w_x): + pass + +def sc_skip_space(space, args): + return space.do_operation('simple_call', space.wrap("skip_space"), args[0]) + + def setup(space): fn = pyframe.normalize_exception - space.specialcases[fn] = sc_normalize_exception + space.specialcases["app_normalize_exception"] = sc_normalize_exception + space.specialcases["app_skip_space"] = sc_skip_space space.specialcases[__import__] = sc_import for opname in ['lt', 'le', 'eq', 'ne', 'gt', 'ge', 'is_']: space.specialcases[getattr(operator, opname)] = sc_operator Modified: pypy/branch/dist-interpapp/pypy/translator/tool/tointerplevel.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/translator/tool/tointerplevel.py (original) +++ pypy/branch/dist-interpapp/pypy/translator/tool/tointerplevel.py Fri Feb 11 22:35:43 2005 @@ -30,6 +30,7 @@ as = options.as or name mod = new.module(as) + mod.__dict__['__file__'] = modfile execfile(modfile, mod.__dict__) del mod.__dict__['__builtins__'] From hpk at codespeak.net Sat Feb 12 00:38:17 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 00:38:17 +0100 (MET) Subject: [pypy-svn] r9146 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050211233817.209C327BAA@code1.codespeak.net> Author: hpk Date: Sat Feb 12 00:38:16 2005 New Revision: 9146 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: an experimental hack to allow for apphelpers living together in one w_apphelper_globals and thus they are able to call each other. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Sat Feb 12 00:38:16 2005 @@ -48,6 +48,7 @@ # initializing builtins may require creating a frame which in # turn already accesses space.w_builtins, provide a dummy one ... self.w_builtins = self.newdict([]) + self.w_apphelper_globals = self.newdict([]) # insert stuff into the newly-made builtins for key, w_value in for_builtins.items(): @@ -283,9 +284,8 @@ Note: EXPERIMENTAL. """ space = self - pypyco = space.loadfromcache((source), buildpypycode, self._codecache) - w_glob = space.newdict([]) - frame = pypyco.create_frame(space, w_glob) + pypyco = space.loadfromcache(source, buildpypycode, self._codecache) + frame = pypyco.create_frame(space, self.w_apphelper_globals) frame.setfastscope(posargs_w) return frame.run() Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Sat Feb 12 00:38:16 2005 @@ -592,6 +592,7 @@ # and now for something completly different ... # +pendingapphelpers = [] def appdef(source): """ NOT_RPYTHON """ from pypy.interpreter.pycode import PyCode @@ -611,19 +612,26 @@ # SOME MESS AHEAD ! # construct the special app source passed to appexec appsource = py.code.Source(source).strip().putaround("%s(%s):" % (funcname, fastscope)) - sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals()] + sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals(), + " while pendingapphelpers:", + " ihook = pendingapphelpers.pop()", + " space.setitem(space.w_apphelper_globals,", + " space.wrap(ihook.name), space.wrap(ihook))", ] sourcelines.extend(defaulthandlingsource.indent().lines) sourcelines.append( " return space.appexec([%(wfastscope)s], '''" % locals()) for line in appsource.indent().indent().lines: line = line.replace("\\", r"\\").replace("'", r"\'") sourcelines.append(line) - sourcelines.append("''')") + sourcelines.append("''')") source = py.code.Source() source.lines = sourcelines - glob = {} + #print str(source) + glob = { 'pendingapphelpers' : pendingapphelpers } exec source.compile() in glob - return glob[funcname] + func = glob[funcname] + pendingapphelpers.append(interp2app(func, func.func_name)) + return func def specialargparse(decl): """ NOT_RPYTHON """ From hpk at codespeak.net Sat Feb 12 00:43:23 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 00:43:23 +0100 (MET) Subject: [pypy-svn] r9147 - pypy/branch/dist-interpapp/pypy/objspace/std Message-ID: <20050211234323.68A7527BB1@code1.codespeak.net> Author: hpk Date: Sat Feb 12 00:43:23 2005 New Revision: 9147 Modified: pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py Log: forgot to checkin a slight fix to slicetype which makes the tests pass Modified: pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py Sat Feb 12 00:43:23 2005 @@ -7,7 +7,8 @@ # default application-level implementations for some operations -def app_slice_indices3(slice, length): +slice_indices__ANY_ANY = slice_indices3 = gateway.appdef( + """slice_indices3(slice, length): # this is used internally, analogous to CPython's PySlice_GetIndicesEx step = slice.step if step is None: @@ -50,9 +51,9 @@ stop = length return start, stop, step -slice_indices__ANY_ANY = slice_indices3 = gateway.app2interp(app_slice_indices3) + """) -def app_slice_indices4(slice, sequencelength): +slice_indices4 = gateway.appdef("""slice_indices4(slice, sequencelength): start, stop, step = slice_indices3(slice, sequencelength) slicelength = stop - start lengthsign = cmp(slicelength, 0) @@ -63,7 +64,7 @@ slicelength = 0 return start, stop, step, slicelength -slice_indices4 = gateway.app2interp(app_slice_indices4) + """) # utility functions def indices3(space, w_slice, length): From hpk at codespeak.net Sat Feb 12 00:50:52 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 00:50:52 +0100 (MET) Subject: [pypy-svn] r9148 - pypy/branch/dist-interpapp/pypy/objspace/flow Message-ID: <20050211235052.58C8527BB6@code1.codespeak.net> Author: hpk Date: Sat Feb 12 00:50:52 2005 New Revision: 9148 Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Log: fix missing attribute Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Sat Feb 12 00:50:52 2005 @@ -53,6 +53,7 @@ #self.make_builtins() #self.make_sys() self.w_sys = self.wrap(sys) + self.w_apphelper_globals = Constant({}) def loadfromcache(self, key, builder, cache): # when populating the caches, the flow space switches to From hpk at codespeak.net Sat Feb 12 01:02:18 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 01:02:18 +0100 (MET) Subject: [pypy-svn] r9149 - pypy/branch/dist-interpapp/pypy/module/test Message-ID: <20050212000218.A3C8427BB9@code1.codespeak.net> Author: hpk Date: Sat Feb 12 01:02:18 2005 New Revision: 9149 Modified: pypy/branch/dist-interpapp/pypy/module/test/test_import.py Log: fix test to more sanely use appdef/app2interp logic. Modified: pypy/branch/dist-interpapp/pypy/module/test/test_import.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/test/test_import.py (original) +++ pypy/branch/dist-interpapp/pypy/module/test/test_import.py Sat Feb 12 01:02:18 2005 @@ -2,21 +2,23 @@ from pypy.interpreter import gateway import os - -def _setup(dn=os.path.abspath(os.path.join(os.path.dirname(__file__), 'impsubdir'))): - import sys - sys.path.append(dn) - return sys.modules.copy() - -_setup = gateway.app2interp_temp(_setup,'setup') - -def _teardown(saved_modules): - import sys - sys.path.pop() - sys.modules.clear() - sys.modules.update(saved_modules) - -_teardown = gateway.app2interp_temp(_teardown,'teardown') +def _setup(space): + dn=os.path.abspath(os.path.join(os.path.dirname(__file__), 'impsubdir')) + return space.appexec([space.wrap(dn)], """ + (dn): + import sys + sys.path.append(dn) + return sys.modules.copy() + """) + +def _teardown(space, w_saved_modules): + space.appexec([w_saved_modules], """ + (saved_modules): + import sys + sys.path.pop() + sys.modules.clear() + sys.modules.update(saved_modules) + """) class AppTestImport: From sanxiyn at codespeak.net Sat Feb 12 09:03:12 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 12 Feb 2005 09:03:12 +0100 (MET) Subject: [pypy-svn] r9151 - pypy/dist/pypy/interpreter Message-ID: <20050212080312.B472627BBA@code1.codespeak.net> Author: sanxiyn Date: Sat Feb 12 09:03:12 2005 New Revision: 9151 Modified: pypy/dist/pypy/interpreter/main.py Log: Put __main__ at sys.modules Modified: pypy/dist/pypy/interpreter/main.py ============================================================================== --- pypy/dist/pypy/interpreter/main.py (original) +++ pypy/dist/pypy/interpreter/main.py Sat Feb 12 09:03:12 2005 @@ -18,7 +18,10 @@ w = space.wrap w_code = compile(source, filename, cmd, 0, 0) - mainmodule = module.Module(space, space.wrap("__main__")) + w_main = space.wrap('__main__') + mainmodule = module.Module(space, w_main) + space.setitem(space.sys.w_modules, w_main, mainmodule) + w_globals = mainmodule.w_dict pycode = space.interpclass_w(w_code) From sanxiyn at codespeak.net Sat Feb 12 09:27:20 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 12 Feb 2005 09:27:20 +0100 (MET) Subject: [pypy-svn] r9152 - pypy/dist/pypy/lib Message-ID: <20050212082720.36CC227BCB@code1.codespeak.net> Author: sanxiyn Date: Sat Feb 12 09:27:20 2005 New Revision: 9152 Added: pypy/dist/pypy/lib/decimal.py Log: decimal module from 2.4. All doctests pass. Added: pypy/dist/pypy/lib/decimal.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/lib/decimal.py Sat Feb 12 09:27:20 2005 @@ -0,0 +1,3039 @@ +# Copyright (c) 2004 Python Software Foundation. +# All rights reserved. + +# Written by Eric Price +# and Facundo Batista +# and Raymond Hettinger +# and Aahz +# and Tim Peters + +# This module is currently Py2.3 compatible and should be kept that way +# unless a major compelling advantage arises. IOW, 2.3 compatibility is +# strongly preferred, but not guaranteed. + +# Also, this module should be kept in sync with the latest updates of +# the IBM specification as it evolves. Those updates will be treated +# as bug fixes (deviation from the spec is a compatibility, usability +# bug) and will be backported. At this point the spec is stabilizing +# and the updates are becoming fewer, smaller, and less significant. + +""" +This is a Py2.3 implementation of decimal floating point arithmetic based on +the General Decimal Arithmetic Specification: + + www2.hursley.ibm.com/decimal/decarith.html + +and IEEE standard 854-1987: + + www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html + +Decimal floating point has finite precision with arbitrarily large bounds. + +The purpose of the module is to support arithmetic using familiar +"schoolhouse" rules and to avoid the some of tricky representation +issues associated with binary floating point. The package is especially +useful for financial applications or for contexts where users have +expectations that are at odds with binary floating point (for instance, +in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead +of the expected Decimal("0.00") returned by decimal floating point). + +Here are some examples of using the decimal module: + +>>> from decimal import * +>>> setcontext(ExtendedContext) +>>> Decimal(0) +Decimal("0") +>>> Decimal("1") +Decimal("1") +>>> Decimal("-.0123") +Decimal("-0.0123") +>>> Decimal(123456) +Decimal("123456") +>>> Decimal("123.45e12345678901234567890") +Decimal("1.2345E+12345678901234567892") +>>> Decimal("1.33") + Decimal("1.27") +Decimal("2.60") +>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") +Decimal("-2.20") +>>> dig = Decimal(1) +>>> print dig / Decimal(3) +0.333333333 +>>> getcontext().prec = 18 +>>> print dig / Decimal(3) +0.333333333333333333 +>>> print dig.sqrt() +1 +>>> print Decimal(3).sqrt() +1.73205080756887729 +>>> print Decimal(3) ** 123 +4.85192780976896427E+58 +>>> inf = Decimal(1) / Decimal(0) +>>> print inf +Infinity +>>> neginf = Decimal(-1) / Decimal(0) +>>> print neginf +-Infinity +>>> print neginf + inf +NaN +>>> print neginf * inf +-Infinity +>>> print dig / 0 +Infinity +>>> getcontext().traps[DivisionByZero] = 1 +>>> print dig / 0 +Traceback (most recent call last): + ... + ... + ... +DivisionByZero: x / 0 +>>> c = Context() +>>> c.traps[InvalidOperation] = 0 +>>> print c.flags[InvalidOperation] +0 +>>> c.divide(Decimal(0), Decimal(0)) +Decimal("NaN") +>>> c.traps[InvalidOperation] = 1 +>>> print c.flags[InvalidOperation] +1 +>>> c.flags[InvalidOperation] = 0 +>>> print c.flags[InvalidOperation] +0 +>>> print c.divide(Decimal(0), Decimal(0)) +Traceback (most recent call last): + ... + ... + ... +InvalidOperation: 0 / 0 +>>> print c.flags[InvalidOperation] +1 +>>> c.flags[InvalidOperation] = 0 +>>> c.traps[InvalidOperation] = 0 +>>> print c.divide(Decimal(0), Decimal(0)) +NaN +>>> print c.flags[InvalidOperation] +1 +>>> +""" + +__all__ = [ + # Two major classes + 'Decimal', 'Context', + + # Contexts + 'DefaultContext', 'BasicContext', 'ExtendedContext', + + # Exceptions + 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', + 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', + + # Constants for use in setting up contexts + 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', + 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', + + # Functions for manipulating contexts + 'setcontext', 'getcontext' +] + +import copy + +#Rounding +ROUND_DOWN = 'ROUND_DOWN' +ROUND_HALF_UP = 'ROUND_HALF_UP' +ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' +ROUND_CEILING = 'ROUND_CEILING' +ROUND_FLOOR = 'ROUND_FLOOR' +ROUND_UP = 'ROUND_UP' +ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' + +#Rounding decision (not part of the public API) +NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY +ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end. + +#Errors + +class DecimalException(ArithmeticError): + """Base exception class. + + Used exceptions derive from this. + If an exception derives from another exception besides this (such as + Underflow (Inexact, Rounded, Subnormal) that indicates that it is only + called if the others are present. This isn't actually used for + anything, though. + + handle -- Called when context._raise_error is called and the + trap_enabler is set. First argument is self, second is the + context. More arguments can be given, those being after + the explanation in _raise_error (For example, + context._raise_error(NewError, '(-x)!', self._sign) would + call NewError().handle(context, self._sign).) + + To define a new exception, it should be sufficient to have it derive + from DecimalException. + """ + def handle(self, context, *args): + pass + + +class Clamped(DecimalException): + """Exponent of a 0 changed to fit bounds. + + This occurs and signals clamped if the exponent of a result has been + altered in order to fit the constraints of a specific concrete + representation. This may occur when the exponent of a zero result would + be outside the bounds of a representation, or when a large normal + number would have an encoded exponent that cannot be represented. In + this latter case, the exponent is reduced to fit and the corresponding + number of zero digits are appended to the coefficient ("fold-down"). + """ + + +class InvalidOperation(DecimalException): + """An invalid operation was performed. + + Various bad things cause this: + + Something creates a signaling NaN + -INF + INF + 0 * (+-)INF + (+-)INF / (+-)INF + x % 0 + (+-)INF % x + x._rescale( non-integer ) + sqrt(-x) , x > 0 + 0 ** 0 + x ** (non-integer) + x ** (+-)INF + An operand is invalid + """ + def handle(self, context, *args): + if args: + if args[0] == 1: #sNaN, must drop 's' but keep diagnostics + return Decimal( (args[1]._sign, args[1]._int, 'n') ) + return NaN + +class ConversionSyntax(InvalidOperation): + """Trying to convert badly formed string. + + This occurs and signals invalid-operation if an string is being + converted to a number and it does not conform to the numeric string + syntax. The result is [0,qNaN]. + """ + + def handle(self, context, *args): + return (0, (0,), 'n') #Passed to something which uses a tuple. + +class DivisionByZero(DecimalException, ZeroDivisionError): + """Division by 0. + + This occurs and signals division-by-zero if division of a finite number + by zero was attempted (during a divide-integer or divide operation, or a + power operation with negative right-hand operand), and the dividend was + not zero. + + The result of the operation is [sign,inf], where sign is the exclusive + or of the signs of the operands for divide, or is 1 for an odd power of + -0, for power. + """ + + def handle(self, context, sign, double = None, *args): + if double is not None: + return (Infsign[sign],)*2 + return Infsign[sign] + +class DivisionImpossible(InvalidOperation): + """Cannot perform the division adequately. + + This occurs and signals invalid-operation if the integer result of a + divide-integer or remainder operation had too many digits (would be + longer than precision). The result is [0,qNaN]. + """ + + def handle(self, context, *args): + return (NaN, NaN) + +class DivisionUndefined(InvalidOperation, ZeroDivisionError): + """Undefined result of division. + + This occurs and signals invalid-operation if division by zero was + attempted (during a divide-integer, divide, or remainder operation), and + the dividend is also zero. The result is [0,qNaN]. + """ + + def handle(self, context, tup=None, *args): + if tup is not None: + return (NaN, NaN) #for 0 %0, 0 // 0 + return NaN + +class Inexact(DecimalException): + """Had to round, losing information. + + This occurs and signals inexact whenever the result of an operation is + not exact (that is, it needed to be rounded and any discarded digits + were non-zero), or if an overflow or underflow condition occurs. The + result in all cases is unchanged. + + The inexact signal may be tested (or trapped) to determine if a given + operation (or sequence of operations) was inexact. + """ + pass + +class InvalidContext(InvalidOperation): + """Invalid context. Unknown rounding, for example. + + This occurs and signals invalid-operation if an invalid context was + detected during an operation. This can occur if contexts are not checked + on creation and either the precision exceeds the capability of the + underlying concrete representation or an unknown or unsupported rounding + was specified. These aspects of the context need only be checked when + the values are required to be used. The result is [0,qNaN]. + """ + + def handle(self, context, *args): + return NaN + +class Rounded(DecimalException): + """Number got rounded (not necessarily changed during rounding). + + This occurs and signals rounded whenever the result of an operation is + rounded (that is, some zero or non-zero digits were discarded from the + coefficient), or if an overflow or underflow condition occurs. The + result in all cases is unchanged. + + The rounded signal may be tested (or trapped) to determine if a given + operation (or sequence of operations) caused a loss of precision. + """ + pass + +class Subnormal(DecimalException): + """Exponent < Emin before rounding. + + This occurs and signals subnormal whenever the result of a conversion or + operation is subnormal (that is, its adjusted exponent is less than + Emin, before any rounding). The result in all cases is unchanged. + + The subnormal signal may be tested (or trapped) to determine if a given + or operation (or sequence of operations) yielded a subnormal result. + """ + pass + +class Overflow(Inexact, Rounded): + """Numerical overflow. + + This occurs and signals overflow if the adjusted exponent of a result + (from a conversion or from an operation that is not an attempt to divide + by zero), after rounding, would be greater than the largest value that + can be handled by the implementation (the value Emax). + + The result depends on the rounding mode: + + For round-half-up and round-half-even (and for round-half-down and + round-up, if implemented), the result of the operation is [sign,inf], + where sign is the sign of the intermediate result. For round-down, the + result is the largest finite number that can be represented in the + current precision, with the sign of the intermediate result. For + round-ceiling, the result is the same as for round-down if the sign of + the intermediate result is 1, or is [0,inf] otherwise. For round-floor, + the result is the same as for round-down if the sign of the intermediate + result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded + will also be raised. + """ + + def handle(self, context, sign, *args): + if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, + ROUND_HALF_DOWN, ROUND_UP): + return Infsign[sign] + if sign == 0: + if context.rounding == ROUND_CEILING: + return Infsign[sign] + return Decimal((sign, (9,)*context.prec, + context.Emax-context.prec+1)) + if sign == 1: + if context.rounding == ROUND_FLOOR: + return Infsign[sign] + return Decimal( (sign, (9,)*context.prec, + context.Emax-context.prec+1)) + + +class Underflow(Inexact, Rounded, Subnormal): + """Numerical underflow with result rounded to 0. + + This occurs and signals underflow if a result is inexact and the + adjusted exponent of the result would be smaller (more negative) than + the smallest value that can be handled by the implementation (the value + Emin). That is, the result is both inexact and subnormal. + + The result after an underflow will be a subnormal number rounded, if + necessary, so that its exponent is not less than Etiny. This may result + in 0 with the sign of the intermediate result and an exponent of Etiny. + + In all cases, Inexact, Rounded, and Subnormal will also be raised. + """ + +# List of public traps and flags +_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, + Underflow, InvalidOperation, Subnormal] + +# Map conditions (per the spec) to signals +_condition_map = {ConversionSyntax:InvalidOperation, + DivisionImpossible:InvalidOperation, + DivisionUndefined:InvalidOperation, + InvalidContext:InvalidOperation} + +##### Context Functions ####################################### + +# The getcontext() and setcontext() function manage access to a thread-local +# current context. Py2.4 offers direct support for thread locals. If that +# is not available, use threading.currentThread() which is slower but will +# work for older Pythons. If threads are not part of the build, create a +# mock threading object with threading.local() returning the module namespace. + +try: + import threading +except ImportError: + # Python was compiled without threads; create a mock object instead + import sys + class MockThreading: + def local(self, sys=sys): + return sys.modules[__name__] + threading = MockThreading() + del sys, MockThreading + +try: + threading.local + +except AttributeError: + + #To fix reloading, force it to create a new context + #Old contexts have different exceptions in their dicts, making problems. + if hasattr(threading.currentThread(), '__decimal_context__'): + del threading.currentThread().__decimal_context__ + + def setcontext(context): + """Set this thread's context to context.""" + if context in (DefaultContext, BasicContext, ExtendedContext): + context = context.copy() + context.clear_flags() + threading.currentThread().__decimal_context__ = context + + def getcontext(): + """Returns this thread's context. + + If this thread does not yet have a context, returns + a new context and sets this thread's context. + New contexts are copies of DefaultContext. + """ + try: + return threading.currentThread().__decimal_context__ + except AttributeError: + context = Context() + threading.currentThread().__decimal_context__ = context + return context + +else: + + local = threading.local() + if hasattr(local, '__decimal_context__'): + del local.__decimal_context__ + + def getcontext(_local=local): + """Returns this thread's context. + + If this thread does not yet have a context, returns + a new context and sets this thread's context. + New contexts are copies of DefaultContext. + """ + try: + return _local.__decimal_context__ + except AttributeError: + context = Context() + _local.__decimal_context__ = context + return context + + def setcontext(context, _local=local): + """Set this thread's context to context.""" + if context in (DefaultContext, BasicContext, ExtendedContext): + context = context.copy() + context.clear_flags() + _local.__decimal_context__ = context + + del threading, local # Don't contaminate the namespace + + +##### Decimal class ########################################### + +class Decimal(object): + """Floating point class for decimal arithmetic.""" + + __slots__ = ('_exp','_int','_sign', '_is_special') + # Generally, the value of the Decimal instance is given by + # (-1)**_sign * _int * 10**_exp + # Special values are signified by _is_special == True + + # We're immutable, so use __new__ not __init__ + def __new__(cls, value="0", context=None): + """Create a decimal point instance. + + >>> Decimal('3.14') # string input + Decimal("3.14") + >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent) + Decimal("3.14") + >>> Decimal(314) # int or long + Decimal("314") + >>> Decimal(Decimal(314)) # another decimal instance + Decimal("314") + """ + + self = object.__new__(cls) + self._is_special = False + + # From an internal working value + if isinstance(value, _WorkRep): + self._sign = value.sign + self._int = tuple(map(int, str(value.int))) + self._exp = int(value.exp) + return self + + # From another decimal + if isinstance(value, Decimal): + self._exp = value._exp + self._sign = value._sign + self._int = value._int + self._is_special = value._is_special + return self + + # From an integer + if isinstance(value, (int,long)): + if value >= 0: + self._sign = 0 + else: + self._sign = 1 + self._exp = 0 + self._int = tuple(map(int, str(abs(value)))) + return self + + # tuple/list conversion (possibly from as_tuple()) + if isinstance(value, (list,tuple)): + if len(value) != 3: + raise ValueError, 'Invalid arguments' + if value[0] not in [0,1]: + raise ValueError, 'Invalid sign' + for digit in value[1]: + if not isinstance(digit, (int,long)) or digit < 0: + raise ValueError, "The second value in the tuple must be composed of non negative integer elements." + + self._sign = value[0] + self._int = tuple(value[1]) + if value[2] in ('F','n','N'): + self._exp = value[2] + self._is_special = True + else: + self._exp = int(value[2]) + return self + + if isinstance(value, float): + raise TypeError("Cannot convert float to Decimal. " + + "First convert the float to a string") + + # Other argument types may require the context during interpretation + if context is None: + context = getcontext() + + # From a string + # REs insist on real strings, so we can too. + if isinstance(value, basestring): + if _isinfinity(value): + self._exp = 'F' + self._int = (0,) + self._is_special = True + if _isinfinity(value) == 1: + self._sign = 0 + else: + self._sign = 1 + return self + if _isnan(value): + sig, sign, diag = _isnan(value) + self._is_special = True + if len(diag) > context.prec: #Diagnostic info too long + self._sign, self._int, self._exp = \ + context._raise_error(ConversionSyntax) + return self + if sig == 1: + self._exp = 'n' #qNaN + else: #sig == 2 + self._exp = 'N' #sNaN + self._sign = sign + self._int = tuple(map(int, diag)) #Diagnostic info + return self + try: + self._sign, self._int, self._exp = _string2exact(value) + except ValueError: + self._is_special = True + self._sign, self._int, self._exp = context._raise_error(ConversionSyntax) + return self + + raise TypeError("Cannot convert %r to Decimal" % value) + + def _isnan(self): + """Returns whether the number is not actually one. + + 0 if a number + 1 if NaN + 2 if sNaN + """ + if self._is_special: + exp = self._exp + if exp == 'n': + return 1 + elif exp == 'N': + return 2 + return 0 + + def _isinfinity(self): + """Returns whether the number is infinite + + 0 if finite or not a number + 1 if +INF + -1 if -INF + """ + if self._exp == 'F': + if self._sign: + return -1 + return 1 + return 0 + + def _check_nans(self, other = None, context=None): + """Returns whether the number is not actually one. + + if self, other are sNaN, signal + if self, other are NaN return nan + return 0 + + Done before operations. + """ + + self_is_nan = self._isnan() + if other is None: + other_is_nan = False + else: + other_is_nan = other._isnan() + + if self_is_nan or other_is_nan: + if context is None: + context = getcontext() + + if self_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, self) + if other_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, other) + if self_is_nan: + return self + + return other + return 0 + + def __nonzero__(self): + """Is the number non-zero? + + 0 if self == 0 + 1 if self != 0 + """ + if self._is_special: + return 1 + return sum(self._int) != 0 + + def __cmp__(self, other, context=None): + other = _convert_other(other) + + if self._is_special or other._is_special: + ans = self._check_nans(other, context) + if ans: + return 1 # Comparison involving NaN's always reports self > other + + # INF = INF + return cmp(self._isinfinity(), other._isinfinity()) + + if not self and not other: + return 0 #If both 0, sign comparison isn't certain. + + #If different signs, neg one is less + if other._sign < self._sign: + return -1 + if self._sign < other._sign: + return 1 + + self_adjusted = self.adjusted() + other_adjusted = other.adjusted() + if self_adjusted == other_adjusted and \ + self._int + (0,)*(self._exp - other._exp) == \ + other._int + (0,)*(other._exp - self._exp): + return 0 #equal, except in precision. ([0]*(-x) = []) + elif self_adjusted > other_adjusted and self._int[0] != 0: + return (-1)**self._sign + elif self_adjusted < other_adjusted and other._int[0] != 0: + return -((-1)**self._sign) + + # Need to round, so make sure we have a valid context + if context is None: + context = getcontext() + + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_UP) #round away from 0 + + flags = context._ignore_all_flags() + res = self.__sub__(other, context=context) + + context._regard_flags(*flags) + + context.rounding = rounding + + if not res: + return 0 + elif res._sign: + return -1 + return 1 + + def __eq__(self, other): + if not isinstance(other, (Decimal, int, long)): + return False + return self.__cmp__(other) == 0 + + def __ne__(self, other): + if not isinstance(other, (Decimal, int, long)): + return True + return self.__cmp__(other) != 0 + + def compare(self, other, context=None): + """Compares one to another. + + -1 => a < b + 0 => a = b + 1 => a > b + NaN => one is NaN + Like __cmp__, but returns Decimal instances. + """ + other = _convert_other(other) + + #compare(NaN, NaN) = NaN + if (self._is_special or other and other._is_special): + ans = self._check_nans(other, context) + if ans: + return ans + + return Decimal(self.__cmp__(other, context)) + + def __hash__(self): + """x.__hash__() <==> hash(x)""" + # Decimal integers must hash the same as the ints + # Non-integer decimals are normalized and hashed as strings + # Normalization assures that hast(100E-1) == hash(10) + i = int(self) + if self == Decimal(i): + return hash(i) + assert self.__nonzero__() # '-0' handled by integer case + return hash(str(self.normalize())) + + def as_tuple(self): + """Represents the number as a triple tuple. + + To show the internals exactly as they are. + """ + return (self._sign, self._int, self._exp) + + def __repr__(self): + """Represents the number as an instance of Decimal.""" + # Invariant: eval(repr(d)) == d + return 'Decimal("%s")' % str(self) + + def __str__(self, eng = 0, context=None): + """Return string representation of the number in scientific notation. + + Captures all of the information in the underlying representation. + """ + + if self._isnan(): + minus = '-'*self._sign + if self._int == (0,): + info = '' + else: + info = ''.join(map(str, self._int)) + if self._isnan() == 2: + return minus + 'sNaN' + info + return minus + 'NaN' + info + if self._isinfinity(): + minus = '-'*self._sign + return minus + 'Infinity' + + if context is None: + context = getcontext() + + tmp = map(str, self._int) + numdigits = len(self._int) + leftdigits = self._exp + numdigits + if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY + if self._exp < 0 and self._exp >= -6: #short, no need for e/E + s = '-'*self._sign + '0.' + '0'*(abs(self._exp)) + return s + #exp is closest mult. of 3 >= self._exp + exp = ((self._exp - 1)// 3 + 1) * 3 + if exp != self._exp: + s = '0.'+'0'*(exp - self._exp) + else: + s = '0' + if exp != 0: + if context.capitals: + s += 'E' + else: + s += 'e' + if exp > 0: + s += '+' #0.0e+3, not 0.0e3 + s += str(exp) + s = '-'*self._sign + s + return s + if eng: + dotplace = (leftdigits-1)%3+1 + adjexp = leftdigits -1 - (leftdigits-1)%3 + else: + adjexp = leftdigits-1 + dotplace = 1 + if self._exp == 0: + pass + elif self._exp < 0 and adjexp >= 0: + tmp.insert(leftdigits, '.') + elif self._exp < 0 and adjexp >= -6: + tmp[0:0] = ['0'] * int(-leftdigits) + tmp.insert(0, '0.') + else: + if numdigits > dotplace: + tmp.insert(dotplace, '.') + elif numdigits < dotplace: + tmp.extend(['0']*(dotplace-numdigits)) + if adjexp: + if not context.capitals: + tmp.append('e') + else: + tmp.append('E') + if adjexp > 0: + tmp.append('+') + tmp.append(str(adjexp)) + if eng: + while tmp[0:1] == ['0']: + tmp[0:1] = [] + if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e': + tmp[0:0] = ['0'] + if self._sign: + tmp.insert(0, '-') + + return ''.join(tmp) + + def to_eng_string(self, context=None): + """Convert to engineering-type string. + + Engineering notation has an exponent which is a multiple of 3, so there + are up to 3 digits left of the decimal place. + + Same rules for when in exponential and when as a value as in __str__. + """ + return self.__str__(eng=1, context=context) + + def __neg__(self, context=None): + """Returns a copy with the sign switched. + + Rounds, if it has reason. + """ + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + if not self: + # -Decimal('0') is Decimal('0'), not Decimal('-0') + sign = 0 + elif self._sign: + sign = 0 + else: + sign = 1 + + if context is None: + context = getcontext() + if context._rounding_decision == ALWAYS_ROUND: + return Decimal((sign, self._int, self._exp))._fix(context) + return Decimal( (sign, self._int, self._exp)) + + def __pos__(self, context=None): + """Returns a copy, unless it is a sNaN. + + Rounds the number (if more then precision digits) + """ + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + sign = self._sign + if not self: + # + (-0) = 0 + sign = 0 + + if context is None: + context = getcontext() + + if context._rounding_decision == ALWAYS_ROUND: + ans = self._fix(context) + else: + ans = Decimal(self) + ans._sign = sign + return ans + + def __abs__(self, round=1, context=None): + """Returns the absolute value of self. + + If the second argument is 0, do not round. + """ + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + if not round: + if context is None: + context = getcontext() + context = context._shallow_copy() + context._set_rounding_decision(NEVER_ROUND) + + if self._sign: + ans = self.__neg__(context=context) + else: + ans = self.__pos__(context=context) + + return ans + + def __add__(self, other, context=None): + """Returns self + other. + + -INF + INF (or the reverse) cause InvalidOperation errors. + """ + other = _convert_other(other) + + if context is None: + context = getcontext() + + if self._is_special or other._is_special: + ans = self._check_nans(other, context) + if ans: + return ans + + if self._isinfinity(): + #If both INF, same sign => same as both, opposite => error. + if self._sign != other._sign and other._isinfinity(): + return context._raise_error(InvalidOperation, '-INF + INF') + return Decimal(self) + if other._isinfinity(): + return Decimal(other) #Can't both be infinity here + + shouldround = context._rounding_decision == ALWAYS_ROUND + + exp = min(self._exp, other._exp) + negativezero = 0 + if context.rounding == ROUND_FLOOR and self._sign != other._sign: + #If the answer is 0, the sign should be negative, in this case. + negativezero = 1 + + if not self and not other: + sign = min(self._sign, other._sign) + if negativezero: + sign = 1 + return Decimal( (sign, (0,), exp)) + if not self: + exp = max(exp, other._exp - context.prec-1) + ans = other._rescale(exp, watchexp=0, context=context) + if shouldround: + ans = ans._fix(context) + return ans + if not other: + exp = max(exp, self._exp - context.prec-1) + ans = self._rescale(exp, watchexp=0, context=context) + if shouldround: + ans = ans._fix(context) + return ans + + op1 = _WorkRep(self) + op2 = _WorkRep(other) + op1, op2 = _normalize(op1, op2, shouldround, context.prec) + + result = _WorkRep() + if op1.sign != op2.sign: + # Equal and opposite + if op1.int == op2.int: + if exp < context.Etiny(): + exp = context.Etiny() + context._raise_error(Clamped) + return Decimal((negativezero, (0,), exp)) + if op1.int < op2.int: + op1, op2 = op2, op1 + #OK, now abs(op1) > abs(op2) + if op1.sign == 1: + result.sign = 1 + op1.sign, op2.sign = op2.sign, op1.sign + else: + result.sign = 0 + #So we know the sign, and op1 > 0. + elif op1.sign == 1: + result.sign = 1 + op1.sign, op2.sign = (0, 0) + else: + result.sign = 0 + #Now, op1 > abs(op2) > 0 + + if op2.sign == 0: + result.int = op1.int + op2.int + else: + result.int = op1.int - op2.int + + result.exp = op1.exp + ans = Decimal(result) + if shouldround: + ans = ans._fix(context) + return ans + + __radd__ = __add__ + + def __sub__(self, other, context=None): + """Return self + (-other)""" + other = _convert_other(other) + + if self._is_special or other._is_special: + ans = self._check_nans(other, context=context) + if ans: + return ans + + # -Decimal(0) = Decimal(0), which we don't want since + # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.) + # so we change the sign directly to a copy + tmp = Decimal(other) + tmp._sign = 1-tmp._sign + + return self.__add__(tmp, context=context) + + def __rsub__(self, other, context=None): + """Return other + (-self)""" + other = _convert_other(other) + + tmp = Decimal(self) + tmp._sign = 1 - tmp._sign + return other.__add__(tmp, context=context) + + def _increment(self, round=1, context=None): + """Special case of add, adding 1eExponent + + Since it is common, (rounding, for example) this adds + (sign)*one E self._exp to the number more efficiently than add. + + For example: + Decimal('5.624e10')._increment() == Decimal('5.625e10') + """ + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + return Decimal(self) # Must be infinite, and incrementing makes no difference + + L = list(self._int) + L[-1] += 1 + spot = len(L)-1 + while L[spot] == 10: + L[spot] = 0 + if spot == 0: + L[0:0] = [1] + break + L[spot-1] += 1 + spot -= 1 + ans = Decimal((self._sign, L, self._exp)) + + if context is None: + context = getcontext() + if round and context._rounding_decision == ALWAYS_ROUND: + ans = ans._fix(context) + return ans + + def __mul__(self, other, context=None): + """Return self * other. + + (+-) INF * 0 (or its reverse) raise InvalidOperation. + """ + other = _convert_other(other) + + if context is None: + context = getcontext() + + resultsign = self._sign ^ other._sign + + if self._is_special or other._is_special: + ans = self._check_nans(other, context) + if ans: + return ans + + if self._isinfinity(): + if not other: + return context._raise_error(InvalidOperation, '(+-)INF * 0') + return Infsign[resultsign] + + if other._isinfinity(): + if not self: + return context._raise_error(InvalidOperation, '0 * (+-)INF') + return Infsign[resultsign] + + resultexp = self._exp + other._exp + shouldround = context._rounding_decision == ALWAYS_ROUND + + # Special case for multiplying by zero + if not self or not other: + ans = Decimal((resultsign, (0,), resultexp)) + if shouldround: + #Fixing in case the exponent is out of bounds + ans = ans._fix(context) + return ans + + # Special case for multiplying by power of 10 + if self._int == (1,): + ans = Decimal((resultsign, other._int, resultexp)) + if shouldround: + ans = ans._fix(context) + return ans + if other._int == (1,): + ans = Decimal((resultsign, self._int, resultexp)) + if shouldround: + ans = ans._fix(context) + return ans + + op1 = _WorkRep(self) + op2 = _WorkRep(other) + + ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp)) + if shouldround: + ans = ans._fix(context) + + return ans + __rmul__ = __mul__ + + def __div__(self, other, context=None): + """Return self / other.""" + return self._divide(other, context=context) + __truediv__ = __div__ + + def _divide(self, other, divmod = 0, context=None): + """Return a / b, to context.prec precision. + + divmod: + 0 => true division + 1 => (a //b, a%b) + 2 => a //b + 3 => a%b + + Actually, if divmod is 2 or 3 a tuple is returned, but errors for + computing the other value are not raised. + """ + other = _convert_other(other) + + if context is None: + context = getcontext() + + sign = self._sign ^ other._sign + + if self._is_special or other._is_special: + ans = self._check_nans(other, context) + if ans: + if divmod: + return (ans, ans) + return ans + + if self._isinfinity() and other._isinfinity(): + if divmod: + return (context._raise_error(InvalidOperation, + '(+-)INF // (+-)INF'), + context._raise_error(InvalidOperation, + '(+-)INF % (+-)INF')) + return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') + + if self._isinfinity(): + if divmod == 1: + return (Infsign[sign], + context._raise_error(InvalidOperation, 'INF % x')) + elif divmod == 2: + return (Infsign[sign], NaN) + elif divmod == 3: + return (Infsign[sign], + context._raise_error(InvalidOperation, 'INF % x')) + return Infsign[sign] + + if other._isinfinity(): + if divmod: + return (Decimal((sign, (0,), 0)), Decimal(self)) + context._raise_error(Clamped, 'Division by infinity') + return Decimal((sign, (0,), context.Etiny())) + + # Special cases for zeroes + if not self and not other: + if divmod: + return context._raise_error(DivisionUndefined, '0 / 0', 1) + return context._raise_error(DivisionUndefined, '0 / 0') + + if not self: + if divmod: + otherside = Decimal(self) + otherside._exp = min(self._exp, other._exp) + return (Decimal((sign, (0,), 0)), otherside) + exp = self._exp - other._exp + if exp < context.Etiny(): + exp = context.Etiny() + context._raise_error(Clamped, '0e-x / y') + if exp > context.Emax: + exp = context.Emax + context._raise_error(Clamped, '0e+x / y') + return Decimal( (sign, (0,), exp) ) + + if not other: + if divmod: + return context._raise_error(DivisionByZero, 'divmod(x,0)', + sign, 1) + return context._raise_error(DivisionByZero, 'x / 0', sign) + + #OK, so neither = 0, INF or NaN + + shouldround = context._rounding_decision == ALWAYS_ROUND + + #If we're dividing into ints, and self < other, stop. + #self.__abs__(0) does not round. + if divmod and (self.__abs__(0, context) < other.__abs__(0, context)): + + if divmod == 1 or divmod == 3: + exp = min(self._exp, other._exp) + ans2 = self._rescale(exp, context=context, watchexp=0) + if shouldround: + ans2 = ans2._fix(context) + return (Decimal( (sign, (0,), 0) ), + ans2) + + elif divmod == 2: + #Don't round the mod part, if we don't need it. + return (Decimal( (sign, (0,), 0) ), Decimal(self)) + + op1 = _WorkRep(self) + op2 = _WorkRep(other) + op1, op2, adjust = _adjust_coefficients(op1, op2) + res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) ) + if divmod and res.exp > context.prec + 1: + return context._raise_error(DivisionImpossible) + + prec_limit = 10 ** context.prec + while 1: + while op2.int <= op1.int: + res.int += 1 + op1.int -= op2.int + if res.exp == 0 and divmod: + if res.int >= prec_limit and shouldround: + return context._raise_error(DivisionImpossible) + otherside = Decimal(op1) + frozen = context._ignore_all_flags() + + exp = min(self._exp, other._exp) + otherside = otherside._rescale(exp, context=context, watchexp=0) + context._regard_flags(*frozen) + if shouldround: + otherside = otherside._fix(context) + return (Decimal(res), otherside) + + if op1.int == 0 and adjust >= 0 and not divmod: + break + if res.int >= prec_limit and shouldround: + if divmod: + return context._raise_error(DivisionImpossible) + shouldround=1 + # Really, the answer is a bit higher, so adding a one to + # the end will make sure the rounding is right. + if op1.int != 0: + res.int *= 10 + res.int += 1 + res.exp -= 1 + + break + res.int *= 10 + res.exp -= 1 + adjust += 1 + op1.int *= 10 + op1.exp -= 1 + + if res.exp == 0 and divmod and op2.int > op1.int: + #Solves an error in precision. Same as a previous block. + + if res.int >= prec_limit and shouldround: + return context._raise_error(DivisionImpossible) + otherside = Decimal(op1) + frozen = context._ignore_all_flags() + + exp = min(self._exp, other._exp) + otherside = otherside._rescale(exp, context=context) + + context._regard_flags(*frozen) + + return (Decimal(res), otherside) + + ans = Decimal(res) + if shouldround: + ans = ans._fix(context) + return ans + + def __rdiv__(self, other, context=None): + """Swaps self/other and returns __div__.""" + other = _convert_other(other) + return other.__div__(self, context=context) + __rtruediv__ = __rdiv__ + + def __divmod__(self, other, context=None): + """ + (self // other, self % other) + """ + return self._divide(other, 1, context) + + def __rdivmod__(self, other, context=None): + """Swaps self/other and returns __divmod__.""" + other = _convert_other(other) + return other.__divmod__(self, context=context) + + def __mod__(self, other, context=None): + """ + self % other + """ + other = _convert_other(other) + + if self._is_special or other._is_special: + ans = self._check_nans(other, context) + if ans: + return ans + + if self and not other: + return context._raise_error(InvalidOperation, 'x % 0') + + return self._divide(other, 3, context)[1] + + def __rmod__(self, other, context=None): + """Swaps self/other and returns __mod__.""" + other = _convert_other(other) + return other.__mod__(self, context=context) + + def remainder_near(self, other, context=None): + """ + Remainder nearest to 0- abs(remainder-near) <= other/2 + """ + other = _convert_other(other) + + if self._is_special or other._is_special: + ans = self._check_nans(other, context) + if ans: + return ans + if self and not other: + return context._raise_error(InvalidOperation, 'x % 0') + + if context is None: + context = getcontext() + # If DivisionImpossible causes an error, do not leave Rounded/Inexact + # ignored in the calling function. + context = context._shallow_copy() + flags = context._ignore_flags(Rounded, Inexact) + #keep DivisionImpossible flags + (side, r) = self.__divmod__(other, context=context) + + if r._isnan(): + context._regard_flags(*flags) + return r + + context = context._shallow_copy() + rounding = context._set_rounding_decision(NEVER_ROUND) + + if other._sign: + comparison = other.__div__(Decimal(-2), context=context) + else: + comparison = other.__div__(Decimal(2), context=context) + + context._set_rounding_decision(rounding) + context._regard_flags(*flags) + + s1, s2 = r._sign, comparison._sign + r._sign, comparison._sign = 0, 0 + + if r < comparison: + r._sign, comparison._sign = s1, s2 + #Get flags now + self.__divmod__(other, context=context) + return r._fix(context) + r._sign, comparison._sign = s1, s2 + + rounding = context._set_rounding_decision(NEVER_ROUND) + + (side, r) = self.__divmod__(other, context=context) + context._set_rounding_decision(rounding) + if r._isnan(): + return r + + decrease = not side._iseven() + rounding = context._set_rounding_decision(NEVER_ROUND) + side = side.__abs__(context=context) + context._set_rounding_decision(rounding) + + s1, s2 = r._sign, comparison._sign + r._sign, comparison._sign = 0, 0 + if r > comparison or decrease and r == comparison: + r._sign, comparison._sign = s1, s2 + context.prec += 1 + if len(side.__add__(Decimal(1), context=context)._int) >= context.prec: + context.prec -= 1 + return context._raise_error(DivisionImpossible)[1] + context.prec -= 1 + if self._sign == other._sign: + r = r.__sub__(other, context=context) + else: + r = r.__add__(other, context=context) + else: + r._sign, comparison._sign = s1, s2 + + return r._fix(context) + + def __floordiv__(self, other, context=None): + """self // other""" + return self._divide(other, 2, context)[0] + + def __rfloordiv__(self, other, context=None): + """Swaps self/other and returns __floordiv__.""" + other = _convert_other(other) + return other.__floordiv__(self, context=context) + + def __float__(self): + """Float representation.""" + return float(str(self)) + + def __int__(self): + """Converts self to a int, truncating if necessary.""" + if self._is_special: + if self._isnan(): + context = getcontext() + return context._raise_error(InvalidContext) + elif self._isinfinity(): + raise OverflowError, "Cannot convert infinity to long" + if self._exp >= 0: + s = ''.join(map(str, self._int)) + '0'*self._exp + else: + s = ''.join(map(str, self._int))[:self._exp] + if s == '': + s = '0' + sign = '-'*self._sign + return int(sign + s) + + def __long__(self): + """Converts to a long. + + Equivalent to long(int(self)) + """ + return long(self.__int__()) + + def _fix(self, context): + """Round if it is necessary to keep self within prec precision. + + Rounds and fixes the exponent. Does not raise on a sNaN. + + Arguments: + self - Decimal instance + context - context used. + """ + if self._is_special: + return self + if context is None: + context = getcontext() + prec = context.prec + ans = self._fixexponents(context) + if len(ans._int) > prec: + ans = ans._round(prec, context=context) + ans = ans._fixexponents(context) + return ans + + def _fixexponents(self, context): + """Fix the exponents and return a copy with the exponent in bounds. + Only call if known to not be a special value. + """ + folddown = context._clamp + Emin = context.Emin + ans = self + ans_adjusted = ans.adjusted() + if ans_adjusted < Emin: + Etiny = context.Etiny() + if ans._exp < Etiny: + if not ans: + ans = Decimal(self) + ans._exp = Etiny + context._raise_error(Clamped) + return ans + ans = ans._rescale(Etiny, context=context) + #It isn't zero, and exp < Emin => subnormal + context._raise_error(Subnormal) + if context.flags[Inexact]: + context._raise_error(Underflow) + else: + if ans: + #Only raise subnormal if non-zero. + context._raise_error(Subnormal) + else: + Etop = context.Etop() + if folddown and ans._exp > Etop: + context._raise_error(Clamped) + ans = ans._rescale(Etop, context=context) + else: + Emax = context.Emax + if ans_adjusted > Emax: + if not ans: + ans = Decimal(self) + ans._exp = Emax + context._raise_error(Clamped) + return ans + context._raise_error(Inexact) + context._raise_error(Rounded) + return context._raise_error(Overflow, 'above Emax', ans._sign) + return ans + + def _round(self, prec=None, rounding=None, context=None): + """Returns a rounded version of self. + + You can specify the precision or rounding method. Otherwise, the + context determines it. + """ + + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + if self._isinfinity(): + return Decimal(self) + + if context is None: + context = getcontext() + + if rounding is None: + rounding = context.rounding + if prec is None: + prec = context.prec + + if not self: + if prec <= 0: + dig = (0,) + exp = len(self._int) - prec + self._exp + else: + dig = (0,) * prec + exp = len(self._int) + self._exp - prec + ans = Decimal((self._sign, dig, exp)) + context._raise_error(Rounded) + return ans + + if prec == 0: + temp = Decimal(self) + temp._int = (0,)+temp._int + prec = 1 + elif prec < 0: + exp = self._exp + len(self._int) - prec - 1 + temp = Decimal( (self._sign, (0, 1), exp)) + prec = 1 + else: + temp = Decimal(self) + + numdigits = len(temp._int) + if prec == numdigits: + return temp + + # See if we need to extend precision + expdiff = prec - numdigits + if expdiff > 0: + tmp = list(temp._int) + tmp.extend([0] * expdiff) + ans = Decimal( (temp._sign, tmp, temp._exp - expdiff)) + return ans + + #OK, but maybe all the lost digits are 0. + lostdigits = self._int[expdiff:] + if lostdigits == (0,) * len(lostdigits): + ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff)) + #Rounded, but not Inexact + context._raise_error(Rounded) + return ans + + # Okay, let's round and lose data + + this_function = getattr(temp, self._pick_rounding_function[rounding]) + #Now we've got the rounding function + + if prec != context.prec: + context = context._shallow_copy() + context.prec = prec + ans = this_function(prec, expdiff, context) + context._raise_error(Rounded) + context._raise_error(Inexact, 'Changed in rounding') + + return ans + + _pick_rounding_function = {} + + def _round_down(self, prec, expdiff, context): + """Also known as round-towards-0, truncate.""" + return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) + + def _round_half_up(self, prec, expdiff, context, tmp = None): + """Rounds 5 up (away from 0)""" + + if tmp is None: + tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff)) + if self._int[prec] >= 5: + tmp = tmp._increment(round=0, context=context) + if len(tmp._int) > prec: + return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) + return tmp + + def _round_half_even(self, prec, expdiff, context): + """Round 5 to even, rest to nearest.""" + + tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) + half = (self._int[prec] == 5) + if half: + for digit in self._int[prec+1:]: + if digit != 0: + half = 0 + break + if half: + if self._int[prec-1] & 1 == 0: + return tmp + return self._round_half_up(prec, expdiff, context, tmp) + + def _round_half_down(self, prec, expdiff, context): + """Round 5 down""" + + tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) + half = (self._int[prec] == 5) + if half: + for digit in self._int[prec+1:]: + if digit != 0: + half = 0 + break + if half: + return tmp + return self._round_half_up(prec, expdiff, context, tmp) + + def _round_up(self, prec, expdiff, context): + """Rounds away from 0.""" + tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) + for digit in self._int[prec:]: + if digit != 0: + tmp = tmp._increment(round=1, context=context) + if len(tmp._int) > prec: + return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) + else: + return tmp + return tmp + + def _round_ceiling(self, prec, expdiff, context): + """Rounds up (not away from 0 if negative.)""" + if self._sign: + return self._round_down(prec, expdiff, context) + else: + return self._round_up(prec, expdiff, context) + + def _round_floor(self, prec, expdiff, context): + """Rounds down (not towards 0 if negative)""" + if not self._sign: + return self._round_down(prec, expdiff, context) + else: + return self._round_up(prec, expdiff, context) + + def __pow__(self, n, modulo = None, context=None): + """Return self ** n (mod modulo) + + If modulo is None (default), don't take it mod modulo. + """ + n = _convert_other(n) + + if context is None: + context = getcontext() + + if self._is_special or n._is_special or n.adjusted() > 8: + #Because the spot << doesn't work with really big exponents + if n._isinfinity() or n.adjusted() > 8: + return context._raise_error(InvalidOperation, 'x ** INF') + + ans = self._check_nans(n, context) + if ans: + return ans + + if not n._isinteger(): + return context._raise_error(InvalidOperation, 'x ** (non-integer)') + + if not self and not n: + return context._raise_error(InvalidOperation, '0 ** 0') + + if not n: + return Decimal(1) + + if self == Decimal(1): + return Decimal(1) + + sign = self._sign and not n._iseven() + n = int(n) + + if self._isinfinity(): + if modulo: + return context._raise_error(InvalidOperation, 'INF % x') + if n > 0: + return Infsign[sign] + return Decimal( (sign, (0,), 0) ) + + #with ludicrously large exponent, just raise an overflow and return inf. + if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \ + and self: + + tmp = Decimal('inf') + tmp._sign = sign + context._raise_error(Rounded) + context._raise_error(Inexact) + context._raise_error(Overflow, 'Big power', sign) + return tmp + + elength = len(str(abs(n))) + firstprec = context.prec + + if not modulo and firstprec + elength + 1 > DefaultContext.Emax: + return context._raise_error(Overflow, 'Too much precision.', sign) + + mul = Decimal(self) + val = Decimal(1) + context = context._shallow_copy() + context.prec = firstprec + elength + 1 + if n < 0: + #n is a long now, not Decimal instance + n = -n + mul = Decimal(1).__div__(mul, context=context) + + spot = 1 + while spot <= n: + spot <<= 1 + + spot >>= 1 + #Spot is the highest power of 2 less than n + while spot: + val = val.__mul__(val, context=context) + if val._isinfinity(): + val = Infsign[sign] + break + if spot & n: + val = val.__mul__(mul, context=context) + if modulo is not None: + val = val.__mod__(modulo, context=context) + spot >>= 1 + context.prec = firstprec + + if context._rounding_decision == ALWAYS_ROUND: + return val._fix(context) + return val + + def __rpow__(self, other, context=None): + """Swaps self/other and returns __pow__.""" + other = _convert_other(other) + return other.__pow__(self, context=context) + + def normalize(self, context=None): + """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" + + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + dup = self._fix(context) + if dup._isinfinity(): + return dup + + if not dup: + return Decimal( (dup._sign, (0,), 0) ) + end = len(dup._int) + exp = dup._exp + while dup._int[end-1] == 0: + exp += 1 + end -= 1 + return Decimal( (dup._sign, dup._int[:end], exp) ) + + + def quantize(self, exp, rounding=None, context=None, watchexp=1): + """Quantize self so its exponent is the same as that of exp. + + Similar to self._rescale(exp._exp) but with error checking. + """ + if self._is_special or exp._is_special: + ans = self._check_nans(exp, context) + if ans: + return ans + + if exp._isinfinity() or self._isinfinity(): + if exp._isinfinity() and self._isinfinity(): + return self #if both are inf, it is OK + if context is None: + context = getcontext() + return context._raise_error(InvalidOperation, + 'quantize with one INF') + return self._rescale(exp._exp, rounding, context, watchexp) + + def same_quantum(self, other): + """Test whether self and other have the same exponent. + + same as self._exp == other._exp, except NaN == sNaN + """ + if self._is_special or other._is_special: + if self._isnan() or other._isnan(): + return self._isnan() and other._isnan() and True + if self._isinfinity() or other._isinfinity(): + return self._isinfinity() and other._isinfinity() and True + return self._exp == other._exp + + def _rescale(self, exp, rounding=None, context=None, watchexp=1): + """Rescales so that the exponent is exp. + + exp = exp to scale to (an integer) + rounding = rounding version + watchexp: if set (default) an error is returned if exp is greater + than Emax or less than Etiny. + """ + if context is None: + context = getcontext() + + if self._is_special: + if self._isinfinity(): + return context._raise_error(InvalidOperation, 'rescale with an INF') + + ans = self._check_nans(context=context) + if ans: + return ans + + if watchexp and (context.Emax < exp or context.Etiny() > exp): + return context._raise_error(InvalidOperation, 'rescale(a, INF)') + + if not self: + ans = Decimal(self) + ans._int = (0,) + ans._exp = exp + return ans + + diff = self._exp - exp + digits = len(self._int) + diff + + if watchexp and digits > context.prec: + return context._raise_error(InvalidOperation, 'Rescale > prec') + + tmp = Decimal(self) + tmp._int = (0,) + tmp._int + digits += 1 + + if digits < 0: + tmp._exp = -digits + tmp._exp + tmp._int = (0,1) + digits = 1 + tmp = tmp._round(digits, rounding, context=context) + + if tmp._int[0] == 0 and len(tmp._int) > 1: + tmp._int = tmp._int[1:] + tmp._exp = exp + + tmp_adjusted = tmp.adjusted() + if tmp and tmp_adjusted < context.Emin: + context._raise_error(Subnormal) + elif tmp and tmp_adjusted > context.Emax: + return context._raise_error(InvalidOperation, 'rescale(a, INF)') + return tmp + + def to_integral(self, rounding=None, context=None): + """Rounds to the nearest integer, without raising inexact, rounded.""" + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + if self._exp >= 0: + return self + if context is None: + context = getcontext() + flags = context._ignore_flags(Rounded, Inexact) + ans = self._rescale(0, rounding, context=context) + context._regard_flags(flags) + return ans + + def sqrt(self, context=None): + """Return the square root of self. + + Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) + Should quadratically approach the right answer. + """ + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + + if self._isinfinity() and self._sign == 0: + return Decimal(self) + + if not self: + #exponent = self._exp / 2, using round_down. + #if self._exp < 0: + # exp = (self._exp+1) // 2 + #else: + exp = (self._exp) // 2 + if self._sign == 1: + #sqrt(-0) = -0 + return Decimal( (1, (0,), exp)) + else: + return Decimal( (0, (0,), exp)) + + if context is None: + context = getcontext() + + if self._sign == 1: + return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') + + tmp = Decimal(self) + + expadd = tmp._exp // 2 + if tmp._exp & 1: + tmp._int += (0,) + tmp._exp = 0 + else: + tmp._exp = 0 + + context = context._shallow_copy() + flags = context._ignore_all_flags() + firstprec = context.prec + context.prec = 3 + if tmp.adjusted() & 1 == 0: + ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) + ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), + context=context), context=context) + ans._exp -= 1 + tmp.adjusted() // 2 + else: + ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) + ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), + context=context), context=context) + ans._exp -= 1 + tmp.adjusted() // 2 + + #ans is now a linear approximation. + + Emax, Emin = context.Emax, context.Emin + context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin + + half = Decimal('0.5') + + maxp = firstprec + 2 + rounding = context._set_rounding(ROUND_HALF_EVEN) + while 1: + context.prec = min(2*context.prec - 2, maxp) + ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context), + context=context), context=context) + if context.prec == maxp: + break + + #round to the answer's precision-- the only error can be 1 ulp. + context.prec = firstprec + prevexp = ans.adjusted() + ans = ans._round(context=context) + + #Now, check if the other last digits are better. + context.prec = firstprec + 1 + # In case we rounded up another digit and we should actually go lower. + if prevexp != ans.adjusted(): + ans._int += (0,) + ans._exp -= 1 + + + lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) + context._set_rounding(ROUND_UP) + if lower.__mul__(lower, context=context) > (tmp): + ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) + + else: + upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) + context._set_rounding(ROUND_DOWN) + if upper.__mul__(upper, context=context) < tmp: + ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) + + ans._exp += expadd + + context.prec = firstprec + context.rounding = rounding + ans = ans._fix(context) + + rounding = context._set_rounding_decision(NEVER_ROUND) + if not ans.__mul__(ans, context=context) == self: + # Only rounded/inexact if here. + context._regard_flags(flags) + context._raise_error(Rounded) + context._raise_error(Inexact) + else: + #Exact answer, so let's set the exponent right. + #if self._exp < 0: + # exp = (self._exp +1)// 2 + #else: + exp = self._exp // 2 + context.prec += ans._exp - exp + ans = ans._rescale(exp, context=context) + context.prec = firstprec + context._regard_flags(flags) + context.Emax, context.Emin = Emax, Emin + + return ans._fix(context) + + def max(self, other, context=None): + """Returns the larger value. + + like max(self, other) except if one is not a number, returns + NaN (and signals if one is sNaN). Also rounds. + """ + other = _convert_other(other) + + if self._is_special or other._is_special: + # if one operand is a quiet NaN and the other is number, then the + # number is always returned + sn = self._isnan() + on = other._isnan() + if sn or on: + if on == 1 and sn != 2: + return self + if sn == 1 and on != 2: + return other + return self._check_nans(other, context) + + ans = self + c = self.__cmp__(other) + if c == 0: + # if both operands are finite and equal in numerical value + # then an ordering is applied: + # + # if the signs differ then max returns the operand with the + # positive sign and min returns the operand with the negative sign + # + # if the signs are the same then the exponent is used to select + # the result. + if self._sign != other._sign: + if self._sign: + ans = other + elif self._exp < other._exp and not self._sign: + ans = other + elif self._exp > other._exp and self._sign: + ans = other + elif c == -1: + ans = other + + if context is None: + context = getcontext() + if context._rounding_decision == ALWAYS_ROUND: + return ans._fix(context) + return ans + + def min(self, other, context=None): + """Returns the smaller value. + + like min(self, other) except if one is not a number, returns + NaN (and signals if one is sNaN). Also rounds. + """ + other = _convert_other(other) + + if self._is_special or other._is_special: + # if one operand is a quiet NaN and the other is number, then the + # number is always returned + sn = self._isnan() + on = other._isnan() + if sn or on: + if on == 1 and sn != 2: + return self + if sn == 1 and on != 2: + return other + return self._check_nans(other, context) + + ans = self + c = self.__cmp__(other) + if c == 0: + # if both operands are finite and equal in numerical value + # then an ordering is applied: + # + # if the signs differ then max returns the operand with the + # positive sign and min returns the operand with the negative sign + # + # if the signs are the same then the exponent is used to select + # the result. + if self._sign != other._sign: + if other._sign: + ans = other + elif self._exp > other._exp and not self._sign: + ans = other + elif self._exp < other._exp and self._sign: + ans = other + elif c == 1: + ans = other + + if context is None: + context = getcontext() + if context._rounding_decision == ALWAYS_ROUND: + return ans._fix(context) + return ans + + def _isinteger(self): + """Returns whether self is an integer""" + if self._exp >= 0: + return True + rest = self._int[self._exp:] + return rest == (0,)*len(rest) + + def _iseven(self): + """Returns 1 if self is even. Assumes self is an integer.""" + if self._exp > 0: + return 1 + return self._int[-1+self._exp] & 1 == 0 + + def adjusted(self): + """Return the adjusted exponent of self""" + try: + return self._exp + len(self._int) - 1 + #If NaN or Infinity, self._exp is string + except TypeError: + return 0 + + # support for pickling, copy, and deepcopy + def __reduce__(self): + return (self.__class__, (str(self),)) + + def __copy__(self): + if type(self) == Decimal: + return self # I'm immutable; therefore I am my own clone + return self.__class__(str(self)) + + def __deepcopy__(self, memo): + if type(self) == Decimal: + return self # My components are also immutable + return self.__class__(str(self)) + +##### Context class ########################################### + + +# get rounding method function: +rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')] +for name in rounding_functions: + #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value. + globalname = name[1:].upper() + val = globals()[globalname] + Decimal._pick_rounding_function[val] = name + +del name, val, globalname, rounding_functions + +class Context(object): + """Contains the context for a Decimal instance. + + Contains: + prec - precision (for use in rounding, division, square roots..) + rounding - rounding type. (how you round) + _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round? + traps - If traps[exception] = 1, then the exception is + raised when it is caused. Otherwise, a value is + substituted in. + flags - When an exception is caused, flags[exception] is incremented. + (Whether or not the trap_enabler is set) + Should be reset by user of Decimal instance. + Emin - Minimum exponent + Emax - Maximum exponent + capitals - If 1, 1*10^1 is printed as 1E+1. + If 0, printed as 1e1 + _clamp - If 1, change exponents if too high (Default 0) + """ + + def __init__(self, prec=None, rounding=None, + traps=None, flags=None, + _rounding_decision=None, + Emin=None, Emax=None, + capitals=None, _clamp=0, + _ignored_flags=None): + if flags is None: + flags = [] + if _ignored_flags is None: + _ignored_flags = [] + if not isinstance(flags, dict): + flags = dict([(s,s in flags) for s in _signals]) + del s + if traps is not None and not isinstance(traps, dict): + traps = dict([(s,s in traps) for s in _signals]) + del s + for name, val in locals().items(): + if val is None: + setattr(self, name, copy.copy(getattr(DefaultContext, name))) + else: + setattr(self, name, val) + del self.self + + def __repr__(self): + """Show the current context.""" + s = [] + s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self)) + s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']') + s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']') + return ', '.join(s) + ')' + + def clear_flags(self): + """Reset all flags to zero""" + for flag in self.flags: + self.flags[flag] = 0 + + def _shallow_copy(self): + """Returns a shallow copy from self.""" + nc = Context(self.prec, self.rounding, self.traps, self.flags, + self._rounding_decision, self.Emin, self.Emax, + self.capitals, self._clamp, self._ignored_flags) + return nc + + def copy(self): + """Returns a deep copy from self.""" + nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), + self._rounding_decision, self.Emin, self.Emax, + self.capitals, self._clamp, self._ignored_flags) + return nc + __copy__ = copy + + def _raise_error(self, condition, explanation = None, *args): + """Handles an error + + If the flag is in _ignored_flags, returns the default response. + Otherwise, it increments the flag, then, if the corresponding + trap_enabler is set, it reaises the exception. Otherwise, it returns + the default value after incrementing the flag. + """ + error = _condition_map.get(condition, condition) + if error in self._ignored_flags: + #Don't touch the flag + return error().handle(self, *args) + + self.flags[error] += 1 + if not self.traps[error]: + #The errors define how to handle themselves. + return condition().handle(self, *args) + + # Errors should only be risked on copies of the context + #self._ignored_flags = [] + raise error, explanation + + def _ignore_all_flags(self): + """Ignore all flags, if they are raised""" + return self._ignore_flags(*_signals) + + def _ignore_flags(self, *flags): + """Ignore the flags, if they are raised""" + # Do not mutate-- This way, copies of a context leave the original + # alone. + self._ignored_flags = (self._ignored_flags + list(flags)) + return list(flags) + + def _regard_flags(self, *flags): + """Stop ignoring the flags, if they are raised""" + if flags and isinstance(flags[0], (tuple,list)): + flags = flags[0] + for flag in flags: + self._ignored_flags.remove(flag) + + def __hash__(self): + """A Context cannot be hashed.""" + # We inherit object.__hash__, so we must deny this explicitly + raise TypeError, "Cannot hash a Context." + + def Etiny(self): + """Returns Etiny (= Emin - prec + 1)""" + return int(self.Emin - self.prec + 1) + + def Etop(self): + """Returns maximum exponent (= Emax - prec + 1)""" + return int(self.Emax - self.prec + 1) + + def _set_rounding_decision(self, type): + """Sets the rounding decision. + + Sets the rounding decision, and returns the current (previous) + rounding decision. Often used like: + + context = context._shallow_copy() + # That so you don't change the calling context + # if an error occurs in the middle (say DivisionImpossible is raised). + + rounding = context._set_rounding_decision(NEVER_ROUND) + instance = instance / Decimal(2) + context._set_rounding_decision(rounding) + + This will make it not round for that operation. + """ + + rounding = self._rounding_decision + self._rounding_decision = type + return rounding + + def _set_rounding(self, type): + """Sets the rounding type. + + Sets the rounding type, and returns the current (previous) + rounding type. Often used like: + + context = context.copy() + # so you don't change the calling context + # if an error occurs in the middle. + rounding = context._set_rounding(ROUND_UP) + val = self.__sub__(other, context=context) + context._set_rounding(rounding) + + This will make it round up for that operation. + """ + rounding = self.rounding + self.rounding= type + return rounding + + def create_decimal(self, num='0'): + """Creates a new Decimal instance but using self as context.""" + d = Decimal(num, context=self) + return d._fix(self) + + #Methods + def abs(self, a): + """Returns the absolute value of the operand. + + If the operand is negative, the result is the same as using the minus + operation on the operand. Otherwise, the result is the same as using + the plus operation on the operand. + + >>> ExtendedContext.abs(Decimal('2.1')) + Decimal("2.1") + >>> ExtendedContext.abs(Decimal('-100')) + Decimal("100") + >>> ExtendedContext.abs(Decimal('101.5')) + Decimal("101.5") + >>> ExtendedContext.abs(Decimal('-101.5')) + Decimal("101.5") + """ + return a.__abs__(context=self) + + def add(self, a, b): + """Return the sum of the two operands. + + >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) + Decimal("19.00") + >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) + Decimal("1.02E+4") + """ + return a.__add__(b, context=self) + + def _apply(self, a): + return str(a._fix(self)) + + def compare(self, a, b): + """Compares values numerically. + + If the signs of the operands differ, a value representing each operand + ('-1' if the operand is less than zero, '0' if the operand is zero or + negative zero, or '1' if the operand is greater than zero) is used in + place of that operand for the comparison instead of the actual + operand. + + The comparison is then effected by subtracting the second operand from + the first and then returning a value according to the result of the + subtraction: '-1' if the result is less than zero, '0' if the result is + zero or negative zero, or '1' if the result is greater than zero. + + >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) + Decimal("-1") + >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) + Decimal("0") + >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) + Decimal("0") + >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) + Decimal("1") + >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) + Decimal("1") + >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) + Decimal("-1") + """ + return a.compare(b, context=self) + + def divide(self, a, b): + """Decimal division in a specified context. + + >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) + Decimal("0.333333333") + >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) + Decimal("0.666666667") + >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) + Decimal("2.5") + >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) + Decimal("0.1") + >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) + Decimal("1") + >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) + Decimal("4.00") + >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) + Decimal("1.20") + >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) + Decimal("10") + >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) + Decimal("1000") + >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) + Decimal("1.20E+6") + """ + return a.__div__(b, context=self) + + def divide_int(self, a, b): + """Divides two numbers and returns the integer part of the result. + + >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) + Decimal("0") + >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) + Decimal("3") + >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) + Decimal("3") + """ + return a.__floordiv__(b, context=self) + + def divmod(self, a, b): + return a.__divmod__(b, context=self) + + def max(self, a,b): + """max compares two values numerically and returns the maximum. + + If either operand is a NaN then the general rules apply. + Otherwise, the operands are compared as as though by the compare + operation. If they are numerically equal then the left-hand operand + is chosen as the result. Otherwise the maximum (closer to positive + infinity) of the two operands is chosen as the result. + + >>> ExtendedContext.max(Decimal('3'), Decimal('2')) + Decimal("3") + >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) + Decimal("3") + >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) + Decimal("7") + """ + return a.max(b, context=self) + + def min(self, a,b): + """min compares two values numerically and returns the minimum. + + If either operand is a NaN then the general rules apply. + Otherwise, the operands are compared as as though by the compare + operation. If they are numerically equal then the left-hand operand + is chosen as the result. Otherwise the minimum (closer to negative + infinity) of the two operands is chosen as the result. + + >>> ExtendedContext.min(Decimal('3'), Decimal('2')) + Decimal("2") + >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) + Decimal("-10") + >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) + Decimal("1.0") + >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) + Decimal("7") + """ + return a.min(b, context=self) + + def minus(self, a): + """Minus corresponds to unary prefix minus in Python. + + The operation is evaluated using the same rules as subtract; the + operation minus(a) is calculated as subtract('0', a) where the '0' + has the same exponent as the operand. + + >>> ExtendedContext.minus(Decimal('1.3')) + Decimal("-1.3") + >>> ExtendedContext.minus(Decimal('-1.3')) + Decimal("1.3") + """ + return a.__neg__(context=self) + + def multiply(self, a, b): + """multiply multiplies two operands. + + If either operand is a special value then the general rules apply. + Otherwise, the operands are multiplied together ('long multiplication'), + resulting in a number which may be as long as the sum of the lengths + of the two operands. + + >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) + Decimal("3.60") + >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) + Decimal("21") + >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) + Decimal("0.72") + >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) + Decimal("-0.0") + >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) + Decimal("4.28135971E+11") + """ + return a.__mul__(b, context=self) + + def normalize(self, a): + """normalize reduces an operand to its simplest form. + + Essentially a plus operation with all trailing zeros removed from the + result. + + >>> ExtendedContext.normalize(Decimal('2.1')) + Decimal("2.1") + >>> ExtendedContext.normalize(Decimal('-2.0')) + Decimal("-2") + >>> ExtendedContext.normalize(Decimal('1.200')) + Decimal("1.2") + >>> ExtendedContext.normalize(Decimal('-120')) + Decimal("-1.2E+2") + >>> ExtendedContext.normalize(Decimal('120.00')) + Decimal("1.2E+2") + >>> ExtendedContext.normalize(Decimal('0.00')) + Decimal("0") + """ + return a.normalize(context=self) + + def plus(self, a): + """Plus corresponds to unary prefix plus in Python. + + The operation is evaluated using the same rules as add; the + operation plus(a) is calculated as add('0', a) where the '0' + has the same exponent as the operand. + + >>> ExtendedContext.plus(Decimal('1.3')) + Decimal("1.3") + >>> ExtendedContext.plus(Decimal('-1.3')) + Decimal("-1.3") + """ + return a.__pos__(context=self) + + def power(self, a, b, modulo=None): + """Raises a to the power of b, to modulo if given. + + The right-hand operand must be a whole number whose integer part (after + any exponent has been applied) has no more than 9 digits and whose + fractional part (if any) is all zeros before any rounding. The operand + may be positive, negative, or zero; if negative, the absolute value of + the power is used, and the left-hand operand is inverted (divided into + 1) before use. + + If the increased precision needed for the intermediate calculations + exceeds the capabilities of the implementation then an Invalid operation + condition is raised. + + If, when raising to a negative power, an underflow occurs during the + division into 1, the operation is not halted at that point but + continues. + + >>> ExtendedContext.power(Decimal('2'), Decimal('3')) + Decimal("8") + >>> ExtendedContext.power(Decimal('2'), Decimal('-3')) + Decimal("0.125") + >>> ExtendedContext.power(Decimal('1.7'), Decimal('8')) + Decimal("69.7575744") + >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2')) + Decimal("0") + >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1')) + Decimal("0") + >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0')) + Decimal("1") + >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1')) + Decimal("Infinity") + >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2')) + Decimal("Infinity") + >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2')) + Decimal("0") + >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1')) + Decimal("-0") + >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0')) + Decimal("1") + >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1')) + Decimal("-Infinity") + >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2')) + Decimal("Infinity") + >>> ExtendedContext.power(Decimal('0'), Decimal('0')) + Decimal("NaN") + """ + return a.__pow__(b, modulo, context=self) + + def quantize(self, a, b): + """Returns a value equal to 'a' (rounded) and having the exponent of 'b'. + + The coefficient of the result is derived from that of the left-hand + operand. It may be rounded using the current rounding setting (if the + exponent is being increased), multiplied by a positive power of ten (if + the exponent is being decreased), or is unchanged (if the exponent is + already equal to that of the right-hand operand). + + Unlike other operations, if the length of the coefficient after the + quantize operation would be greater than precision then an Invalid + operation condition is raised. This guarantees that, unless there is an + error condition, the exponent of the result of a quantize is always + equal to that of the right-hand operand. + + Also unlike other operations, quantize will never raise Underflow, even + if the result is subnormal and inexact. + + >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) + Decimal("2.170") + >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) + Decimal("2.17") + >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) + Decimal("2.2") + >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) + Decimal("2") + >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) + Decimal("0E+1") + >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) + Decimal("-Infinity") + >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) + Decimal("NaN") + >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) + Decimal("-0") + >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) + Decimal("-0E+5") + >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) + Decimal("NaN") + >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) + Decimal("NaN") + >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) + Decimal("217.0") + >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) + Decimal("217") + >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) + Decimal("2.2E+2") + >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) + Decimal("2E+2") + """ + return a.quantize(b, context=self) + + def remainder(self, a, b): + """Returns the remainder from integer division. + + The result is the residue of the dividend after the operation of + calculating integer division as described for divide-integer, rounded to + precision digits if necessary. The sign of the result, if non-zero, is + the same as that of the original dividend. + + This operation will fail under the same conditions as integer division + (that is, if integer division on the same two operands would fail, the + remainder cannot be calculated). + + >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) + Decimal("2.1") + >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) + Decimal("1") + >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) + Decimal("-1") + >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) + Decimal("0.2") + >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) + Decimal("0.1") + >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) + Decimal("1.0") + """ + return a.__mod__(b, context=self) + + def remainder_near(self, a, b): + """Returns to be "a - b * n", where n is the integer nearest the exact + value of "x / b" (if two integers are equally near then the even one + is chosen). If the result is equal to 0 then its sign will be the + sign of a. + + This operation will fail under the same conditions as integer division + (that is, if integer division on the same two operands would fail, the + remainder cannot be calculated). + + >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) + Decimal("-0.9") + >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) + Decimal("-2") + >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) + Decimal("1") + >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) + Decimal("-1") + >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) + Decimal("0.2") + >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) + Decimal("0.1") + >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) + Decimal("-0.3") + """ + return a.remainder_near(b, context=self) + + def same_quantum(self, a, b): + """Returns True if the two operands have the same exponent. + + The result is never affected by either the sign or the coefficient of + either operand. + + >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) + False + >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) + True + >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) + False + >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) + True + """ + return a.same_quantum(b) + + def sqrt(self, a): + """Returns the square root of a non-negative number to context precision. + + If the result must be inexact, it is rounded using the round-half-even + algorithm. + + >>> ExtendedContext.sqrt(Decimal('0')) + Decimal("0") + >>> ExtendedContext.sqrt(Decimal('-0')) + Decimal("-0") + >>> ExtendedContext.sqrt(Decimal('0.39')) + Decimal("0.624499800") + >>> ExtendedContext.sqrt(Decimal('100')) + Decimal("10") + >>> ExtendedContext.sqrt(Decimal('1')) + Decimal("1") + >>> ExtendedContext.sqrt(Decimal('1.0')) + Decimal("1.0") + >>> ExtendedContext.sqrt(Decimal('1.00')) + Decimal("1.0") + >>> ExtendedContext.sqrt(Decimal('7')) + Decimal("2.64575131") + >>> ExtendedContext.sqrt(Decimal('10')) + Decimal("3.16227766") + >>> ExtendedContext.prec + 9 + """ + return a.sqrt(context=self) + + def subtract(self, a, b): + """Return the sum of the two operands. + + >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) + Decimal("0.23") + >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) + Decimal("0.00") + >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) + Decimal("-0.77") + """ + return a.__sub__(b, context=self) + + def to_eng_string(self, a): + """Converts a number to a string, using scientific notation. + + The operation is not affected by the context. + """ + return a.to_eng_string(context=self) + + def to_sci_string(self, a): + """Converts a number to a string, using scientific notation. + + The operation is not affected by the context. + """ + return a.__str__(context=self) + + def to_integral(self, a): + """Rounds to an integer. + + When the operand has a negative exponent, the result is the same + as using the quantize() operation using the given operand as the + left-hand-operand, 1E+0 as the right-hand-operand, and the precision + of the operand as the precision setting, except that no flags will + be set. The rounding mode is taken from the context. + + >>> ExtendedContext.to_integral(Decimal('2.1')) + Decimal("2") + >>> ExtendedContext.to_integral(Decimal('100')) + Decimal("100") + >>> ExtendedContext.to_integral(Decimal('100.0')) + Decimal("100") + >>> ExtendedContext.to_integral(Decimal('101.5')) + Decimal("102") + >>> ExtendedContext.to_integral(Decimal('-101.5')) + Decimal("-102") + >>> ExtendedContext.to_integral(Decimal('10E+5')) + Decimal("1.0E+6") + >>> ExtendedContext.to_integral(Decimal('7.89E+77')) + Decimal("7.89E+77") + >>> ExtendedContext.to_integral(Decimal('-Inf')) + Decimal("-Infinity") + """ + return a.to_integral(context=self) + +class _WorkRep(object): + __slots__ = ('sign','int','exp') + # sign: 0 or 1 + # int: int or long + # exp: None, int, or string + + def __init__(self, value=None): + if value is None: + self.sign = None + self.int = 0 + self.exp = None + elif isinstance(value, Decimal): + self.sign = value._sign + cum = 0 + for digit in value._int: + cum = cum * 10 + digit + self.int = cum + self.exp = value._exp + else: + # assert isinstance(value, tuple) + self.sign = value[0] + self.int = value[1] + self.exp = value[2] + + def __repr__(self): + return "(%r, %r, %r)" % (self.sign, self.int, self.exp) + + __str__ = __repr__ + + + +def _normalize(op1, op2, shouldround = 0, prec = 0): + """Normalizes op1, op2 to have the same exp and length of coefficient. + + Done during addition. + """ + # Yes, the exponent is a long, but the difference between exponents + # must be an int-- otherwise you'd get a big memory problem. + numdigits = int(op1.exp - op2.exp) + if numdigits < 0: + numdigits = -numdigits + tmp = op2 + other = op1 + else: + tmp = op1 + other = op2 + + + if shouldround and numdigits > prec + 1: + # Big difference in exponents - check the adjusted exponents + tmp_len = len(str(tmp.int)) + other_len = len(str(other.int)) + if numdigits > (other_len + prec + 1 - tmp_len): + # If the difference in adjusted exps is > prec+1, we know + # other is insignificant, so might as well put a 1 after the precision. + # (since this is only for addition.) Also stops use of massive longs. + + extend = prec + 2 - tmp_len + if extend <= 0: + extend = 1 + tmp.int *= 10 ** extend + tmp.exp -= extend + other.int = 1 + other.exp = tmp.exp + return op1, op2 + + tmp.int *= 10 ** numdigits + tmp.exp -= numdigits + return op1, op2 + +def _adjust_coefficients(op1, op2): + """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int. + + Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. + + Used on _WorkRep instances during division. + """ + adjust = 0 + #If op1 is smaller, make it larger + while op2.int > op1.int: + op1.int *= 10 + op1.exp -= 1 + adjust += 1 + + #If op2 is too small, make it larger + while op1.int >= (10 * op2.int): + op2.int *= 10 + op2.exp -= 1 + adjust -= 1 + + return op1, op2, adjust + +##### Helper Functions ######################################## + +def _convert_other(other): + """Convert other to Decimal. + + Verifies that it's ok to use in an implicit construction. + """ + if isinstance(other, Decimal): + return other + if isinstance(other, (int, long)): + return Decimal(other) + + raise TypeError, "You can interact Decimal only with int, long or Decimal data types." + +_infinity_map = { + 'inf' : 1, + 'infinity' : 1, + '+inf' : 1, + '+infinity' : 1, + '-inf' : -1, + '-infinity' : -1 +} + +def _isinfinity(num): + """Determines whether a string or float is infinity. + + +1 for negative infinity; 0 for finite ; +1 for positive infinity + """ + num = str(num).lower() + return _infinity_map.get(num, 0) + +def _isnan(num): + """Determines whether a string or float is NaN + + (1, sign, diagnostic info as string) => NaN + (2, sign, diagnostic info as string) => sNaN + 0 => not a NaN + """ + num = str(num).lower() + if not num: + return 0 + + #get the sign, get rid of trailing [+-] + sign = 0 + if num[0] == '+': + num = num[1:] + elif num[0] == '-': #elif avoids '+-nan' + num = num[1:] + sign = 1 + + if num.startswith('nan'): + if len(num) > 3 and not num[3:].isdigit(): #diagnostic info + return 0 + return (1, sign, num[3:].lstrip('0')) + if num.startswith('snan'): + if len(num) > 4 and not num[4:].isdigit(): + return 0 + return (2, sign, num[4:].lstrip('0')) + return 0 + + +##### Setup Specific Contexts ################################ + +# The default context prototype used by Context() +# Is mutable, so that new contexts can have different default values + +DefaultContext = Context( + prec=28, rounding=ROUND_HALF_EVEN, + traps=[DivisionByZero, Overflow, InvalidOperation], + flags=[], + _rounding_decision=ALWAYS_ROUND, + Emax=999999999, + Emin=-999999999, + capitals=1 +) + +# Pre-made alternate contexts offered by the specification +# Don't change these; the user should be able to select these +# contexts and be able to reproduce results from other implementations +# of the spec. + +BasicContext = Context( + prec=9, rounding=ROUND_HALF_UP, + traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], + flags=[], +) + +ExtendedContext = Context( + prec=9, rounding=ROUND_HALF_EVEN, + traps=[], + flags=[], +) + + +##### Useful Constants (internal use only) #################### + +#Reusable defaults +Inf = Decimal('Inf') +negInf = Decimal('-Inf') + +#Infsign[sign] is infinity w/ that sign +Infsign = (Inf, negInf) + +NaN = Decimal('NaN') + + +##### crud for parsing strings ################################# +import re + +# There's an optional sign at the start, and an optional exponent +# at the end. The exponent has an optional sign and at least one +# digit. In between, must have either at least one digit followed +# by an optional fraction, or a decimal point followed by at least +# one digit. Yuck. + +_parser = re.compile(r""" +# \s* + (?P[-+])? + ( + (?P\d+) (\. (?P\d*))? + | + \. (?P\d+) + ) + ([eE](?P[-+]? \d+))? +# \s* + $ +""", re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces. + +del re + +# return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly + +def _string2exact(s): + m = _parser(s) + if m is None: + raise ValueError("invalid literal for Decimal: %r" % s) + + if m.group('sign') == "-": + sign = 1 + else: + sign = 0 + + exp = m.group('exp') + if exp is None: + exp = 0 + else: + exp = int(exp) + + intpart = m.group('int') + if intpart is None: + intpart = "" + fracpart = m.group('onlyfrac') + else: + fracpart = m.group('frac') + if fracpart is None: + fracpart = "" + + exp -= len(fracpart) + + mantissa = intpart + fracpart + tmp = map(int, mantissa) + backup = tmp + while tmp and tmp[0] == 0: + del tmp[0] + + # It's a zero + if not tmp: + if backup: + return (sign, tuple(backup), exp) + return (sign, (0,), exp) + mantissa = tuple(tmp) + + return (sign, mantissa, exp) + + +if __name__ == '__main__': + import doctest, sys + doctest.testmod(sys.modules[__name__]) From arigo at codespeak.net Sat Feb 12 12:22:09 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 12 Feb 2005 12:22:09 +0100 (MET) Subject: [pypy-svn] r9154 - pypy/branch/dist-interpapp/pypy/objspace/flow Message-ID: <20050212112209.408E427BD1@code1.codespeak.net> Author: arigo Date: Sat Feb 12 12:22:09 2005 New Revision: 9154 Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py Log: Check that no unexpected frame shows up in bytecode_trace(). Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py Sat Feb 12 12:22:09 2005 @@ -85,6 +85,7 @@ self.code = code self.w_globals = w_globals = space.wrap(globals) self.crnt_offset = -1 + self.crnt_frame = None if closure is None: self.closure = None else: @@ -111,6 +112,7 @@ self.closure) def bytecode_trace(self, frame): + assert frame is self.crnt_frame, "seeing an unexpected frame!" if not isinstance(self.crnt_ops, list): return next_instr = frame.next_instr @@ -213,7 +215,11 @@ except ExitFrame: continue # restarting a dead SpamBlock try: - w_result = frame.resume() + self.crnt_frame = frame + try: + w_result = frame.resume() + finally: + self.crnt_frame = None except OperationThatShouldNotBePropagatedError, e: raise Exception( 'found an operation that always raises %s: %s' % ( From hpk at codespeak.net Sat Feb 12 12:37:04 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 12:37:04 +0100 (MET) Subject: [pypy-svn] r9155 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050212113704.D95EF27BDE@code1.codespeak.net> Author: hpk Date: Sat Feb 12 12:37:04 2005 New Revision: 9155 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Log: fix docstring for appexec() and cosmetic changes. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Sat Feb 12 12:37:04 2005 @@ -280,12 +280,14 @@ def appexec(self, posargs_w, source): """ return value from executing given source at applevel with - given name=wrapped value parameters as its starting scope. - Note: EXPERIMENTAL. + the given list of wrapped arguments. The arguments are + directly set as the fastscope of the underlyingly executing + frame. No Argument parsing is performed at this point. + Consider using gateway.appdef() if you need default + arguments. """ - space = self - pypyco = space.loadfromcache(source, buildpypycode, self._codecache) - frame = pypyco.create_frame(space, self.w_apphelper_globals) + pypyco = self.loadfromcache(source, buildpypycode, self._codecache) + frame = pypyco.create_frame(self, self.w_apphelper_globals) frame.setfastscope(posargs_w) return frame.run() From arigo at codespeak.net Sat Feb 12 15:13:43 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 12 Feb 2005 15:13:43 +0100 (MET) Subject: [pypy-svn] r9160 - in pypy/branch/dist-interpapp/pypy: interpreter interpreter/test objspace/flow objspace/std Message-ID: <20050212141343.01D4E27BC1@code1.codespeak.net> Author: arigo Date: Sat Feb 12 15:13:43 2005 New Revision: 9160 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py Log: First try at gateway.applevel("""...."""). Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Sat Feb 12 15:13:43 2005 @@ -279,38 +279,28 @@ return statement.exec_code(self, w_globals, w_locals) def appexec(self, posargs_w, source): - """ return value from executing given source at applevel with - the given list of wrapped arguments. The arguments are - directly set as the fastscope of the underlyingly executing - frame. No Argument parsing is performed at this point. - Consider using gateway.appdef() if you need default - arguments. - """ - pypyco = self.loadfromcache(source, buildpypycode, self._codecache) - frame = pypyco.create_frame(self, self.w_apphelper_globals) - frame.setfastscope(posargs_w) - return frame.run() + """ return value from executing given source at applevel. + The source must look like + '''(x, y): + do_stuff... + return result + ''' + """ + w_func = self.loadfromcache(source, buildappexecfunc, self._codecache) + args = Arguments(self, posargs_w) + return self.call_args(w_func, args) -def buildpypycode(source, space): +def buildappexecfunc(source, space): """ NOT_RPYTHON """ # XXX will change once we have our own compiler from pypy.interpreter.pycode import PyCode from pypy.tool.pytestsupport import py # aehem - argdecl, source = source.split(':', 1) - argdecl = argdecl.strip() - i = argdecl.find('(') - if i >0: - funcname, argdecl = argdecl[:i], argdecl[i:] - else: - funcname = 'anon' - if not argdecl.startswith('(') or not argdecl.endswith(')'): - raise SyntaxError("incorrect appexec header\n%s" % source) - source = py.code.Source(source) - source = source.putaround("def %s%s:" % (funcname, argdecl)) - d = {} - exec source.compile() in d - newco = d[funcname].func_code - return PyCode(space)._from_code(newco) + source = source.lstrip() + assert source.startswith('('), "incorrect header in:\n%s" % (source,) + source = py.code.Source("def anonymous%s\n" % source) + w_glob = space.newdict([]) + space.exec_(source.compile(), w_glob, w_glob) + return space.getitem(w_glob, space.wrap('anonymous')) ## Table describing the regular part of the interface of object spaces, ## namely all methods which only take w_ arguments and return a w_ result Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Sat Feb 12 15:13:43 2005 @@ -592,87 +592,61 @@ # and now for something completly different ... # -pendingapphelpers = [] -def appdef(source): - """ NOT_RPYTHON """ +class applevel: + """A container for app-level source code that should be executed + as a module in the object space; interphook() builds a static + interp-level function that invokes the callable with the given + name at app-level.""" + + def __init__(self, source): + "NOT_RPYTHON" + self.code = py.code.Source(source).compile() + + def getdict(self, space): + return space.loadfromcache(self, applevel.builddict, + space._gatewaycache) + + def builddict(self, space): + "NOT_RPYTHON" + w_glob = space.newdict([]) + space.exec_(self.code, w_glob, w_glob) + return w_glob + + def interphook(self, name): + "NOT_RPYTHON" + def appcaller(space, *args_w): + w_glob = self.getdict(space) + w_func = space.getitem(w_glob, space.wrap(name)) + args = Arguments(space, args_w) + return space.call_args(w_func, args) + return hack.func_with_new_name(appcaller, name) + + +def appdef(source, applevel=applevel): + """ NOT_RPYTHON: build an app-level helper function, like for example: + myfunc = appdef('''myfunc(x, y): + return x+y + ''') + """ from pypy.interpreter.pycode import PyCode if not isinstance(source, str): source = str(py.code.Source(source).strip()) assert source.startswith("def "), "can only transform functions" source = source[4:] - funcdecl, source = source.strip().split(':', 1) - funcname, decl = funcdecl.split('(', 1) - funcname = funcname.strip() or 'anonymous' - decl = decl.strip()[:-1] - wfuncdecl, wfastscope, defaulthandlingsource = specialargparse(decl) - - # get rid of w_ - fastscope = ", ".join([x.strip()[2:] for x in wfastscope.split(',')]) - - # SOME MESS AHEAD ! - # construct the special app source passed to appexec - appsource = py.code.Source(source).strip().putaround("%s(%s):" % (funcname, fastscope)) - sourcelines = ["def %(funcname)s(space, %(wfuncdecl)s):" % locals(), - " while pendingapphelpers:", - " ihook = pendingapphelpers.pop()", - " space.setitem(space.w_apphelper_globals,", - " space.wrap(ihook.name), space.wrap(ihook))", ] - sourcelines.extend(defaulthandlingsource.indent().lines) - sourcelines.append( - " return space.appexec([%(wfastscope)s], '''" % locals()) - for line in appsource.indent().indent().lines: - line = line.replace("\\", r"\\").replace("'", r"\'") - sourcelines.append(line) - sourcelines.append("''')") - source = py.code.Source() - source.lines = sourcelines - #print str(source) - glob = { 'pendingapphelpers' : pendingapphelpers } - exec source.compile() in glob - func = glob[funcname] - pendingapphelpers.append(interp2app(func, func.func_name)) - return func - -def specialargparse(decl): - """ NOT_RPYTHON """ - wfuncargs = [] - wfastnames = [] - defaultargs = [] - for name in decl.split(','): - if not name.strip(): - continue - name = "w_%s" % name.strip() - if '=' in name: - name, value = name.split('=') - wfastnames.append(name) - defaultargs.append((name, value)) - name += "=None" - else: - assert not defaultargs, "posarg follows defaultarg" - wfastnames.append(name) - wfuncargs.append(name) - - # now we generate some nice code for default arg checking - # (which does not imply that the code doing it is nice :-) - defaulthandlingsource = py.code.Source() - while defaultargs: - name, value = defaultargs.pop(0) - defaulthandlingsource = defaulthandlingsource.putaround("""\ - if %s is None: - %s = space.wrap(%s) - """ % (name, name, value), "") - wfuncdecl = ", ".join(wfuncargs) - wfastdecl = ", ".join(wfastnames) - return wfuncdecl, wfastdecl, defaulthandlingsource - -app2interp = appdef - -# for app2interp_temp (used for testing mainly) we can use *args -class app2interp_temp(object): - def __init__(self, func): - """ NOT_RPYTHON """ - self.appfunc = appdef(func) - - def __call__(self, space, *args_w, **kwargs_w): - """ NOT_RPYTHON """ - return self.appfunc(space, *args_w, **kwargs_w) + p = source.find('(') + assert p >= 0 + funcname = source[:p].strip() + source = source[p:] + return applevel("def %s%s\n" % (funcname, source)).interphook(funcname) + +app2interp = appdef # backward compatibility + + +# app2interp_temp is used for testing mainly +class applevel_temp(applevel): + def getdict(self, space): + return self.builddict(space) # no cache + +def app2interp_temp(func): + """ NOT_RPYTHON """ + return appdef(func, applevel_temp) Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Sat Feb 12 15:13:43 2005 @@ -736,9 +736,6 @@ cls.dispatch_table = dispatch_table - gateway.importall(locals()) # app_xxx() -> xxx() - - ### helpers written at the application-level ### # Some of these functions are expected to be generally useful if other # parts of the code needs to do the same thing as a non-trivial opcode, @@ -747,6 +744,98 @@ # There are also a couple of helpers that are methods, defined in the # class above. +app = gateway.applevel(''' + + def file_softspace(file, newflag): + try: + softspace = file.softspace + except AttributeError: + softspace = 0 + try: + file.softspace = newflag + except AttributeError: + pass + return softspace + + def find_metaclass(bases, namespace, globals, builtins): + if '__metaclass__' in namespace: + return namespace['__metaclass__'] + elif len(bases) > 0: + base = bases[0] + if hasattr(base, '__class__'): + return base.__class__ + else: + return type(base) + elif '__metaclass__' in globals: + return globals['__metaclass__'] + elif '__metaclass__' in builtins: + return builtins['__metaclass__'] + else: + return type + + def import_all_from(module, into_locals): + try: + all = module.__all__ + except AttributeError: + try: + dict = module.__dict__ + except AttributeError: + raise ImportError("from-import-* object has no __dict__ " + "and no __all__") + all = dict.keys() + skip_leading_underscores = True + else: + skip_leading_underscores = False + for name in all: + if skip_leading_underscores and name[0]=='_': + continue + into_locals[name] = getattr(module, name) + + def prepare_exec(f, prog, globals, locals, compile_flags): + """Manipulate parameters to exec statement to (codeobject, dict, dict). + """ + # XXX INCOMPLETE + if (globals is None and locals is None and + isinstance(prog, tuple) and + (len(prog) == 2 or len(prog) == 3)): + globals = prog[1] + if len(prog) == 3: + locals = prog[2] + prog = prog[0] + if globals is None: + globals = f.f_globals + if locals is None: + locals = f.f_locals + if locals is None: + locals = globals + if not isinstance(globals, dict): + raise TypeError("exec: arg 2 must be a dictionary or None") + elif not globals.has_key('__builtins__'): + globals['__builtins__'] = f.f_builtins + if not isinstance(locals, dict): + raise TypeError("exec: arg 3 must be a dictionary or None") + # XXX - HACK to check for code object + co = compile('1','','eval') + if isinstance(prog, type(co)): + return (prog, globals, locals) + if not isinstance(prog, str): + ## if not (isinstance(prog, types.StringTypes) or + ## isinstance(prog, types.FileType)): + raise TypeError("exec: arg 1 must be a string, file, " + "or code object") + ## if isinstance(prog, types.FileType): + ## co = compile(prog.read(),prog.name,'exec',comple_flags,1) + ## return (co,globals,locals) + else: # prog is a string + co = compile(prog,'','exec', compile_flags, 1) + return (co, globals, locals) +''') + +file_softspace = app.interphook('file_softspace') +find_metaclass = app.interphook('find_metaclass') +import_all_from = app.interphook('import_all_from') +prepare_exec = app.interphook('prepare_exec') + def print_expr(space, w_x): try: w_displayhook = space.getattr(space.w_sys, space.wrap('displayhook')) @@ -756,19 +845,6 @@ raise OperationError(space.w_RuntimeError, "lost sys.displayhook") space.call_function(w_displayhook, w_x) -file_softspace = gateway.appdef(""" - (file, newflag): - try: - softspace = file.softspace - except AttributeError: - softspace = 0 - try: - file.softspace = newflag - except AttributeError: - pass - return softspace - """) - def sys_stdout(space): try: return space.getattr(space.w_sys, space.wrap('stdout')) @@ -784,8 +860,7 @@ # add a softspace unless we just printed a string which ends in a '\t' # or '\n' -- or more generally any whitespace character but ' ' - w_skip = space.appexec([w_x], """ - app_skip_space(x): + w_skip = space.appexec([w_x], """(x): return isinstance(x, str) and len(x) and \ x[-1].isspace() and x[-1]!=' ' """) @@ -797,78 +872,3 @@ def print_newline_to(space, w_stream): space.call_method(w_stream, 'write', space.wrap("\n")) file_softspace(space, w_stream, space.w_False) - -def app_find_metaclass(bases, namespace, globals, builtins): - if '__metaclass__' in namespace: - return namespace['__metaclass__'] - elif len(bases) > 0: - base = bases[0] - if hasattr(base, '__class__'): - return base.__class__ - else: - return type(base) - elif '__metaclass__' in globals: - return globals['__metaclass__'] - elif '__metaclass__' in builtins: - return builtins['__metaclass__'] - else: - return type - -def app_import_all_from(module, into_locals): - try: - all = module.__all__ - except AttributeError: - try: - dict = module.__dict__ - except AttributeError: - raise ImportError("from-import-* object has no __dict__ " - "and no __all__") - all = dict.keys() - skip_leading_underscores = True - else: - skip_leading_underscores = False - for name in all: - if skip_leading_underscores and name[0]=='_': - continue - into_locals[name] = getattr(module, name) - - -def app_prepare_exec(f, prog, globals, locals, compile_flags): - """Manipulate parameters to exec statement to (codeobject, dict, dict). - """ - # XXX INCOMPLETE - if (globals is None and locals is None and - isinstance(prog, tuple) and - (len(prog) == 2 or len(prog) == 3)): - globals = prog[1] - if len(prog) == 3: - locals = prog[2] - prog = prog[0] - if globals is None: - globals = f.f_globals - if locals is None: - locals = f.f_locals - if locals is None: - locals = globals - if not isinstance(globals, dict): - raise TypeError("exec: arg 2 must be a dictionary or None") - elif not globals.has_key('__builtins__'): - globals['__builtins__'] = f.f_builtins - if not isinstance(locals, dict): - raise TypeError("exec: arg 3 must be a dictionary or None") - # XXX - HACK to check for code object - co = compile('1','','eval') - if isinstance(prog, type(co)): - return (prog, globals, locals) - if not isinstance(prog, str): -## if not (isinstance(prog, types.StringTypes) or -## isinstance(prog, types.FileType)): - raise TypeError("exec: arg 1 must be a string, file, or code object") -## if isinstance(prog, types.FileType): -## co = compile(prog.read(),prog.name,'exec',comple_flags,1) -## return (co,globals,locals) - else: # prog is a string - co = compile(prog,'','exec', compile_flags, 1) - return (co, globals, locals) - -gateway.importall(globals()) # app_xxx() -> xxx() Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Sat Feb 12 15:13:43 2005 @@ -1,6 +1,6 @@ import py -from pypy.interpreter.gateway import appdef +from pypy.interpreter.gateway import appdef, applevel def test_execwith_novars(space): val = space.appexec([], """ @@ -70,13 +70,21 @@ w_result = app(space) assert space.eq_w(w_result, space.wrap(42)) +def test_applevel_object(space): + app = applevel(''' + def f(x, y): + return x-y + def g(x, y): + return f(y, x) + ''') + g = app.interphook('g') + w_res = g(space, space.wrap(10), space.wrap(1)) + assert space.eq_w(w_res, space.wrap(-9)) + def app_test_something_at_app_level(): x = 2 assert x/2 == 1 - + class AppTestMethods: def test_somee_app_test_method(self): assert 2 == 2 - - - Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py Sat Feb 12 15:13:43 2005 @@ -57,10 +57,6 @@ class TestGateway: - def setup_method(self, method): - name = method.im_func.func_name - if name in ('test_importall', 'test_exportall'): - py.test.skip("sharing globals for app2interp'ed functions not supported") def test_app2interp(self): w = self.space.wrap def app_g3(a, b): @@ -195,26 +191,14 @@ def test_importall(self): w = self.space.wrap - g = {} - exec """ -def app_g3(a, b): - return a+b -def app_g1(x): - return g3('foo', x) -""" in g + g = {'app_g3': app_g3} gateway.importall(g, temporary=True) - g1 = g['g1'] - assert self.space.eq_w(g1(self.space, w('bar')), w('foobar')) + g3 = g['g3'] + assert self.space.eq_w(g3(self.space, w('bar')), w('foobar')) - def test_exportall(self): - w = self.space.wrap - g = {} - exec """ -def g3(space, w_a, w_b): - return space.add(w_a, w_b) -def app_g1(x): - return g3('foo', x) -""" in g - gateway.exportall(g, temporary=True) - g1 = gateway.app2interp_temp(g['app_g1']) - assert self.space.eq_w(g1(self.space, w('bar')), w('foobar')) +## def test_exportall(self): +## not used any more + + +def app_g3(b): + return 'foo'+b Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py Sat Feb 12 15:13:43 2005 @@ -112,9 +112,9 @@ self.closure) def bytecode_trace(self, frame): - assert frame is self.crnt_frame, "seeing an unexpected frame!" if not isinstance(self.crnt_ops, list): return + assert frame is self.crnt_frame, "seeing an unexpected frame!" next_instr = frame.next_instr self.crnt_offset = next_instr # save offset for opcode varnames = frame.code.getvarnames() Modified: pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py Sat Feb 12 15:13:43 2005 @@ -20,75 +20,69 @@ #dict_str = StdObjSpace.str # default application-level implementations for some operations +# gateway is imported in the stdtypedef module +app = gateway.applevel(''' -def app_dict_update__ANY_ANY(d, o): - for k in o.keys(): - d[k] = o[k] - -def app_dict_popitem__ANY(d): - k = d.keys() - if not k: - raise KeyError("popitem(): dictionary is empty") - k = k[0] - v = d[k] - del d[k] - return k, v - -def app_dict_get__ANY_ANY_ANY(d, k, v=None): - if d.has_key(k): - return d[k] - return v - -def app_dict_setdefault__ANY_ANY_ANY(d, k, v): - if d.has_key(k): - return d[k] - d[k] = v - return v - -def app_dict_pop__ANY_ANY(d, k, default): - if len(default) > 1: - raise TypeError, "pop expected at most 2 arguments, got %d" % ( - 1 + len(default)) - try: + def update(d, o): + for k in o.keys(): + d[k] = o[k] + + def popitem(d): + k = d.keys() + if not k: + raise KeyError("popitem(): dictionary is empty") + k = k[0] v = d[k] del d[k] - except KeyError, e: - if default: - return default[0] + return k, v + + def get(d, k, v=None): + if k in d: + return d[k] else: - raise e - return v + return v -def app_dict_iteritems__ANY(d): - return iter(d.items()) + def setdefault(d, k, v=None): + if k in d: + return d[k] + else: + d[k] = v + return v -def app_dict_iterkeys__ANY(d): - return iter(d.keys()) + def pop(d, k, defaults): # XXX defaults is actually *defaults + if len(defaults) > 1: + raise TypeError, "pop expected at most 2 arguments, got %d" % ( + 1 + len(defaults)) + try: + v = d[k] + del d[k] + except KeyError, e: + if defaults: + return defaults[0] + else: + raise e + return v + + def iteritems(d): + return iter(d.items()) + + def iterkeys(d): + return iter(d.keys()) + + def itervalues(d): + return iter(d.values()) +''') +#XXX what about dict.fromkeys()? + +dict_update__ANY_ANY = app.interphook("update") +dict_popitem__ANY = app.interphook("popitem") +dict_get__ANY_ANY_ANY = app.interphook("get") +dict_setdefault__ANY_ANY_ANY = app.interphook("setdefault") +dict_pop__ANY_ANY = app.interphook("pop") +dict_iteritems__ANY = app.interphook("iteritems") +dict_iterkeys__ANY = app.interphook("iterkeys") +dict_itervalues__ANY = app.interphook("itervalues") -def app_dict_itervalues__ANY(d): - return iter(d.values()) - -#def app_dict_fromkeys__ANY_List(d, seq, value): -# d = {} -# if value: -# value = value[0] -# else: -# value = None -# for item in seq: -# d[item] = value -# return d -#XXX implement dict.fromkeys() which must be a static method -#XXX accepting any iterable - -# This can return when multimethods have been fixed -""" -def app_dict_str__ANY(d): - items = [] - for k, v in d.iteritems(): - items.append("%r: %r" % (k, v)) - return "{%s}" % ', '.join(items) -""" -gateway.importall(globals()) register_all(vars(), globals()) # ____________________________________________________________ Modified: pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py Sat Feb 12 15:13:43 2005 @@ -14,15 +14,16 @@ list_sort = MultiMethod('sort', 4, defaults=(None, None, False), argnames=['cmp', 'key', 'reverse']) list_reversed = MultiMethod('__reversed__', 1) -def app_list_reversed__ANY(lst): - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(lst) - # gateway is imported in the stdtypedef module -gateway.importall(globals()) +app = gateway.applevel(''' + + def reversed(lst): + for index in range(len(lst)-1, -1, -1): + yield lst[index] + +''') + +list_reversed__ANY = app.interphook('reversed') register_all(vars(), globals()) # ____________________________________________________________ Modified: pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py Sat Feb 12 15:13:43 2005 @@ -6,65 +6,69 @@ slice_indices = MultiMethod('indices', 2) # default application-level implementations for some operations +# gateway is imported in the stdtypedef module +app = gateway.applevel(""" -slice_indices__ANY_ANY = slice_indices3 = gateway.appdef( - """slice_indices3(slice, length): - # this is used internally, analogous to CPython's PySlice_GetIndicesEx - step = slice.step - if step is None: - step = 1 - elif step == 0: - raise ValueError, "slice step cannot be zero" - if step < 0: - defstart = length - 1 - defstop = -1 - else: - defstart = 0 - defstop = length - - start = slice.start - if start is None: - start = defstart - else: - if start < 0: - start += length + def indices(slice, length): + # this is used internally, analogous to CPython's PySlice_GetIndicesEx + step = slice.step + if step is None: + step = 1 + elif step == 0: + raise ValueError, "slice step cannot be zero" + if step < 0: + defstart = length - 1 + defstop = -1 + else: + defstart = 0 + defstop = length + + start = slice.start + if start is None: + start = defstart + else: if start < 0: + start += length + if start < 0: + if step < 0: + start = -1 + else: + start = 0 + elif start >= length: if step < 0: - start = -1 + start = length - 1 else: - start = 0 - elif start >= length: - if step < 0: - start = length - 1 - else: - start = length - - stop = slice.stop - if stop is None: - stop = defstop - else: - if stop < 0: - stop += length - if stop < 0: - stop = -1 - elif stop > length: - stop = length - - return start, stop, step - """) - -slice_indices4 = gateway.appdef("""slice_indices4(slice, sequencelength): - start, stop, step = slice_indices3(slice, sequencelength) - slicelength = stop - start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(step, 0) - if stepsign == lengthsign: - slicelength = (slicelength - lengthsign) // step + 1 - else: - slicelength = 0 + start = length - return start, stop, step, slicelength - """) + stop = slice.stop + if stop is None: + stop = defstop + else: + if stop < 0: + stop += length + if stop < 0: + stop = -1 + elif stop > length: + stop = length + + return start, stop, step + + def slice_indices4(slice, sequencelength): + start, stop, step = indices(slice, sequencelength) + slicelength = stop - start + lengthsign = cmp(slicelength, 0) + stepsign = cmp(step, 0) + if stepsign == lengthsign: + slicelength = (slicelength - lengthsign) // step + 1 + else: + slicelength = 0 + + return start, stop, step, slicelength +""") + +slice_indices__ANY_ANY = app.interphook("indices") +slice_indices3 = slice_indices__ANY_ANY +slice_indices4 = app.interphook("slice_indices4") # utility functions def indices3(space, w_slice, length): From arigo at codespeak.net Sat Feb 12 16:39:37 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 12 Feb 2005 16:39:37 +0100 (MET) Subject: [pypy-svn] r9166 - in pypy/branch/dist-interpapp/pypy: interpreter objspace/flow tool Message-ID: <20050212153937.5FB0627BD6@code1.codespeak.net> Author: arigo Date: Sat Feb 12 16:39:37 2005 New Revision: 9166 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py pypy/branch/dist-interpapp/pypy/tool/pydis.py Log: * slight additions to the interface to class applevel * rewrite normalize_exception as an applevel * these changes allow the flow objspace to special-case it again * rewrite the app-level helpers of pyopcode.py as a single big applevel(), which looks very nice now (see e.g. the global 'import sys') * random fixes in tool/pydis.py to make the test pass in this new world Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Sat Feb 12 16:39:37 2005 @@ -280,7 +280,7 @@ def appexec(self, posargs_w, source): """ return value from executing given source at applevel. - The source must look like + EXPERIMENTAL. The source must look like '''(x, y): do_stuff... return result Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Sat Feb 12 16:39:37 2005 @@ -606,6 +606,10 @@ return space.loadfromcache(self, applevel.builddict, space._gatewaycache) + def buildmodule(self, space, name='applevel'): + from pypy.interpreter.module import Module + return Module(space, space.wrap(name), self.getdict(space)) + def builddict(self, space): "NOT_RPYTHON" w_glob = space.newdict([]) @@ -619,7 +623,13 @@ w_func = space.getitem(w_glob, space.wrap(name)) args = Arguments(space, args_w) return space.call_args(w_func, args) - return hack.func_with_new_name(appcaller, name) + def get_function(space): + w_glob = self.getdict(space) + w_func = space.getitem(w_glob, space.wrap(name)) + return space.unwrap(w_func) + appcaller = hack.func_with_new_name(appcaller, name) + appcaller.get_function = get_function + return appcaller def appdef(source, applevel=applevel): Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Sat Feb 12 16:39:37 2005 @@ -18,6 +18,9 @@ if not space.is_true(space.contains(w_dict, space.wrap('__doc__'))): space.setitem(w_dict, space.wrap('__doc__'), space.w_None) + def get(self, name): + return self.space.getitem(self.w_dict, self.space.wrap(name)) + def getdict(self): return self.w_dict Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Sat Feb 12 16:39:37 2005 @@ -216,44 +216,46 @@ return True # stop unrolling return False -def app_normalize_exception(etype, value, tb): - """Normalize an (exc_type, exc_value) pair: - exc_value will be an exception instance and exc_type its class. - """ - # mistakes here usually show up as infinite recursion, which is fun. - while isinstance(etype, tuple): - etype = etype[0] - if isinstance(etype, (type, _classobj)): - if not isinstance(value, etype): - if value is None: - # raise Type: we assume we have to instantiate Type - value = etype() - elif isinstance(value, tuple): - # raise Type, Tuple: assume Tuple contains the constructor args - value = etype(*value) - else: - # raise Type, X: assume X is the constructor argument - value = etype(value) - # raise Type, Instance: let etype be the exact type of value - etype = value.__class__ - elif type(etype) is str: - # XXX warn -- deprecated - if value is not None and type(value) is not str: - raise TypeError("string exceptions can only have a string value") - else: - # raise X: we assume that X is an already-built instance - if value is not None: - raise TypeError("instance exception may not have a separate value") - value = etype - etype = value.__class__ - # for the sake of language consistency we should not allow - # things like 'raise 1', but it's probably fine (i.e. - # not ambiguous) to allow them in the explicit form 'raise int, 1' - if not hasattr(value, '__dict__') and not hasattr(value, '__slots__'): - raise TypeError("raising built-in objects can be ambiguous, " - "use 'raise type, value' instead") - return etype, value, tb -normalize_exception = gateway.app2interp(app_normalize_exception) +app = gateway.applevel(''' + def normalize_exception(etype, value, tb): + """Normalize an (exc_type, exc_value) pair: + exc_value will be an exception instance and exc_type its class. + """ + # mistakes here usually show up as infinite recursion, which is fun. + while isinstance(etype, tuple): + etype = etype[0] + if isinstance(etype, (type, _classobj)): + if not isinstance(value, etype): + if value is None: + # raise Type: we assume we have to instantiate Type + value = etype() + elif isinstance(value, tuple): + # raise Type, Tuple: assume Tuple contains the constructor args + value = etype(*value) + else: + # raise Type, X: assume X is the constructor argument + value = etype(value) + # raise Type, Instance: let etype be the exact type of value + etype = value.__class__ + elif type(etype) is str: + # XXX warn -- deprecated + if value is not None and type(value) is not str: + raise TypeError("string exceptions can only have a string value") + else: + # raise X: we assume that X is an already-built instance + if value is not None: + raise TypeError("instance exception may not have a separate value") + value = etype + etype = value.__class__ + # for the sake of language consistency we should not allow + # things like 'raise 1', but it is probably fine (i.e. + # not ambiguous) to allow them in the explicit form 'raise int, 1' + if not hasattr(value, '__dict__') and not hasattr(value, '__slots__'): + raise TypeError("raising built-in objects can be ambiguous, " + "use 'raise type, value' instead") + return etype, value, tb +''') +normalize_exception = app.interphook("normalize_exception") class FinallyBlock(FrameBlock): Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Sat Feb 12 16:39:37 2005 @@ -744,7 +744,38 @@ # There are also a couple of helpers that are methods, defined in the # class above. -app = gateway.applevel(''' +app = gateway.applevel(r''' + + import sys + + def sys_stdout(): + try: + return sys.stdout + except AttributeError: + raise RuntimeError("lost sys.stdout") + + def print_expr(obj): + try: + displayhook = sys.displayhook + except AttributeError: + raise RuntimeError("lost sys.displayhook") + displayhook(obj) + + def print_item_to(x, stream): + if file_softspace(stream, False): + stream.write(" ") + stream.write(str(x)) + + # add a softspace unless we just printed a string which ends in a '\t' + # or '\n' -- or more generally any whitespace character but ' ' + if isinstance(x, str) and x and x[-1].isspace() and x[-1]!=' ': + return + # XXX add unicode handling + file_softspace(stream, True) + + def print_newline_to(stream): + stream.write("\n") + file_softspace(stream, False) def file_softspace(file, newflag): try: @@ -831,44 +862,11 @@ return (co, globals, locals) ''') +sys_stdout = app.interphook('sys_stdout') +print_expr = app.interphook('print_expr') +print_item_to = app.interphook('print_item_to') +print_newline_to= app.interphook('print_newline_to') file_softspace = app.interphook('file_softspace') find_metaclass = app.interphook('find_metaclass') import_all_from = app.interphook('import_all_from') prepare_exec = app.interphook('prepare_exec') - -def print_expr(space, w_x): - try: - w_displayhook = space.getattr(space.w_sys, space.wrap('displayhook')) - except OperationError, e: - if not e.match(space, space.w_AttributeError): - raise - raise OperationError(space.w_RuntimeError, "lost sys.displayhook") - space.call_function(w_displayhook, w_x) - -def sys_stdout(space): - try: - return space.getattr(space.w_sys, space.wrap('stdout')) - except OperationError, e: - if not e.match(space, space.w_AttributeError): - raise - raise OperationError(space.w_RuntimeError, "lost sys.stdout") - -def print_item_to(space, w_x, w_stream): - if space.is_true(file_softspace(space, w_stream, space.w_False)): - space.call_method(w_stream, 'write', space.wrap(" ")) - space.call_method(w_stream, 'write', space.str(w_x)) - - # add a softspace unless we just printed a string which ends in a '\t' - # or '\n' -- or more generally any whitespace character but ' ' - w_skip = space.appexec([w_x], """(x): - return isinstance(x, str) and len(x) and \ - x[-1].isspace() and x[-1]!=' ' - """) - if space.is_true(w_skip): - return - # XXX add unicode handling - file_softspace(space, w_stream, space.w_True) - -def print_newline_to(space, w_stream): - space.call_method(w_stream, 'write', space.wrap("\n")) - file_softspace(space, w_stream, space.w_False) Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Sat Feb 12 16:39:37 2005 @@ -302,17 +302,6 @@ self.handle_implicit_exceptions(exceptions) return w_res - def appexec(self, posargs_w, source): - name_end = source.find('(') - appname = source[:name_end].strip() - #print appname - try: - sc = self.specialcases[appname] - except KeyError: - return ObjSpace.appexec(self, posargs_w, source) - else: - return sc(self, posargs_w) - def handle_implicit_exceptions(self, exceptions): if exceptions: # catch possible exceptions implicitly. If the OperationError Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/specialcase.py Sat Feb 12 16:39:37 2005 @@ -16,7 +16,7 @@ return None -def sc_normalize_exception(space, args): +def sc_normalize_exception(space, fn, args): """Special-case for 'raise' statements. Case-by-case analysis: * raise Class @@ -34,7 +34,7 @@ - assumes that Arg is the value you want for the exception, and that Class is exactly the exception class. No check or normalization. """ - w_arg1, w_arg2, w_tb = args + w_arg1, w_arg2, w_tb = args.fixedunpack(3) # w_arg3 (the traceback) is ignored and replaced with None # if it is a Variable, because pyopcode.py tries to unwrap it. @@ -82,17 +82,10 @@ opname = fn.__name__.replace('__', '') return space.do_operation(opname, *args_w) -def skip_space(w_x): - pass - -def sc_skip_space(space, args): - return space.do_operation('simple_call', space.wrap("skip_space"), args[0]) - def setup(space): - fn = pyframe.normalize_exception - space.specialcases["app_normalize_exception"] = sc_normalize_exception - space.specialcases["app_skip_space"] = sc_skip_space + fn = pyframe.normalize_exception.get_function(space) + space.specialcases[fn] = sc_normalize_exception space.specialcases[__import__] = sc_import for opname in ['lt', 'le', 'eq', 'ne', 'gt', 'ge', 'is_']: space.specialcases[getattr(operator, opname)] = sc_operator Modified: pypy/branch/dist-interpapp/pypy/tool/pydis.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/pydis.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/pydis.py Sat Feb 12 16:39:37 2005 @@ -28,8 +28,7 @@ self.index == other.index and self.op == other.op and self.name == other.name and - self.oparg == other.oparg and - self.lineno == other.lineno) + self.oparg == other.oparg) def __ne__(self, other): return not (self == other) @@ -44,7 +43,12 @@ s = repr(oparg).rjust(5) + " " if op in hasconst: - s += '(' + `co.co_consts_w[oparg]` + ')' + # support both real code objects and PyCode objects + try: + consts = co.co_consts + except AttributeError: + consts = co.co_consts_w + s += '(' + `consts[oparg]` + ')' elif op in hasname: s += '(' + co.co_names[oparg] + ')' elif op in hasjrel: From arigo at codespeak.net Sat Feb 12 16:51:04 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Sat, 12 Feb 2005 16:51:04 +0100 (MET) Subject: [pypy-svn] r9167 - pypy/branch/dist-interpapp/pypy/tool Message-ID: <20050212155104.56C9127B80@code1.codespeak.net> Author: arigo Date: Sat Feb 12 16:51:04 2005 New Revision: 9167 Modified: pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py Log: Argh! Hacks bite. Modified: pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py Sat Feb 12 16:51:04 2005 @@ -85,7 +85,7 @@ frame = framestack.top(0) # Argh! we may see app-level helpers in the frame stack! # that's very probably very bad... - if frame.code.co_name == 'app_normalize_exception': + if frame.code.co_name == 'normalize_exception': frame = framestack.top(1) runner = AppFrame(frame) From hpk at codespeak.net Sat Feb 12 17:38:55 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 17:38:55 +0100 (MET) Subject: [pypy-svn] r9168 - in pypy/branch/dist-interpapp/pypy: interpreter objspace/flow Message-ID: <20050212163855.678DF27BBF@code1.codespeak.net> Author: hpk Date: Sat Feb 12 17:38:55 2005 New Revision: 9168 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Log: removed leftover code Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Sat Feb 12 17:38:55 2005 @@ -48,7 +48,6 @@ # initializing builtins may require creating a frame which in # turn already accesses space.w_builtins, provide a dummy one ... self.w_builtins = self.newdict([]) - self.w_apphelper_globals = self.newdict([]) # insert stuff into the newly-made builtins for key, w_value in for_builtins.items(): Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Sat Feb 12 17:38:55 2005 @@ -53,7 +53,6 @@ #self.make_builtins() #self.make_sys() self.w_sys = self.wrap(sys) - self.w_apphelper_globals = Constant({}) def loadfromcache(self, key, builder, cache): # when populating the caches, the flow space switches to From hpk at codespeak.net Sat Feb 12 17:55:30 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 17:55:30 +0100 (MET) Subject: [pypy-svn] r9169 - pypy/branch/dist-interpapp/pypy/interpreter/test Message-ID: <20050212165530.A9B2927BE7@code1.codespeak.net> Author: hpk Date: Sat Feb 12 17:55:30 2005 New Revision: 9169 Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Log: hey, applevel() works for constructing classes and hooking them to interp on the fly too! Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Sat Feb 12 17:55:30 2005 @@ -70,7 +70,7 @@ w_result = app(space) assert space.eq_w(w_result, space.wrap(42)) -def test_applevel_object(space): +def test_applevel_functions(space): app = applevel(''' def f(x, y): return x-y @@ -81,6 +81,20 @@ w_res = g(space, space.wrap(10), space.wrap(1)) assert space.eq_w(w_res, space.wrap(-9)) +def test_applevel_class(space): + app = applevel(''' + class C: + clsattr = 42 + def __init__(self, x=13): + self.attr = x + ''') + C = app.interphook('C') + c = C(space, space.wrap(17)) + w_attr = space.getattr(c, space.wrap('clsattr')) + assert space.eq_w(w_attr, space.wrap(42)) + w_clsattr = space.getattr(c, space.wrap('attr')) + assert space.eq_w(w_clsattr, space.wrap(17)) + def app_test_something_at_app_level(): x = 2 assert x/2 == 1 From hpk at codespeak.net Sat Feb 12 18:31:59 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 12 Feb 2005 18:31:59 +0100 (MET) Subject: [pypy-svn] r9170 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050212173159.482A727BF5@code1.codespeak.net> Author: hpk Date: Sat Feb 12 18:31:59 2005 New Revision: 9170 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: some slight renaming generally methods on applevel() don't take wrapped arguments so i didn't do it for wget() either. Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Sat Feb 12 18:31:59 2005 @@ -602,36 +602,37 @@ "NOT_RPYTHON" self.code = py.code.Source(source).compile() - def getdict(self, space): - return space.loadfromcache(self, applevel.builddict, + def getwdict(self, space): + return space.loadfromcache(self, applevel._builddict, space._gatewaycache) def buildmodule(self, space, name='applevel'): from pypy.interpreter.module import Module - return Module(space, space.wrap(name), self.getdict(space)) + return Module(space, space.wrap(name), self.getwdict(space)) - def builddict(self, space): + def _builddict(self, space): "NOT_RPYTHON" w_glob = space.newdict([]) space.exec_(self.code, w_glob, w_glob) return w_glob + + def wget(self, space, name): + w_globals = self.getwdict(space) + return space.getitem(w_globals, space.wrap(name)) def interphook(self, name): "NOT_RPYTHON" def appcaller(space, *args_w): - w_glob = self.getdict(space) - w_func = space.getitem(w_glob, space.wrap(name)) args = Arguments(space, args_w) + w_func = self.wget(space, name) return space.call_args(w_func, args) def get_function(space): - w_glob = self.getdict(space) - w_func = space.getitem(w_glob, space.wrap(name)) + w_func = self.wget(space, name) return space.unwrap(w_func) appcaller = hack.func_with_new_name(appcaller, name) appcaller.get_function = get_function return appcaller - def appdef(source, applevel=applevel): """ NOT_RPYTHON: build an app-level helper function, like for example: myfunc = appdef('''myfunc(x, y): @@ -654,8 +655,8 @@ # app2interp_temp is used for testing mainly class applevel_temp(applevel): - def getdict(self, space): - return self.builddict(space) # no cache + def getwdict(self, space): + return self._builddict(space) # no cache def app2interp_temp(func): """ NOT_RPYTHON """ From pedronis at codespeak.net Sat Feb 12 19:08:02 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 12 Feb 2005 19:08:02 +0100 (MET) Subject: [pypy-svn] r9173 - in pypy/branch/dist-interpapp/pypy: interpreter translator Message-ID: <20050212180802.C758A27BA7@code1.codespeak.net> Author: pedronis Date: Sat Feb 12 19:08:02 2005 New Revision: 9173 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/translator/genc.py Log: small fixes for translate_pypy -no-a, ignore py.lib string subclasses Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Sat Feb 12 19:08:02 2005 @@ -598,6 +598,8 @@ interp-level function that invokes the callable with the given name at app-level.""" + NOT_RPYTHON_ATTRIBUTES = ['code'] + def __init__(self, source): "NOT_RPYTHON" self.code = py.code.Source(source).compile() Modified: pypy/branch/dist-interpapp/pypy/translator/genc.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/translator/genc.py (original) +++ pypy/branch/dist-interpapp/pypy/translator/genc.py Sat Feb 12 19:08:02 2005 @@ -35,6 +35,11 @@ return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % ( source, ) +def builtin_base(obj): + typ = type(obj) + while typ.__module__ != '__builtin__': + typ = typ.__base__ + return typ class GenC: MODNAMES = {} @@ -71,8 +76,8 @@ else: stackentry = obj self.debugstack = (self.debugstack, stackentry) - if (type(obj).__module__ != '__builtin__' and - not isinstance(obj, type)): # skip user-defined metaclasses + obj_builtin_base = builtin_base(obj) + if obj_builtin_base in (object, int, long) and type(obj) is not obj_builtin_base: # assume it's a user defined thingy name = self.nameof_instance(obj) else: From sanxiyn at codespeak.net Sun Feb 13 18:05:09 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sun, 13 Feb 2005 18:05:09 +0100 (MET) Subject: [pypy-svn] r9193 - pypy/dist/goal Message-ID: <20050213170509.C3E9F27B8E@code1.codespeak.net> Author: sanxiyn Date: Sun Feb 13 18:05:09 2005 New Revision: 9193 Modified: pypy/dist/goal/compiler-hack.py Log: Now this works without any hacks. Modified: pypy/dist/goal/compiler-hack.py ============================================================================== --- pypy/dist/goal/compiler-hack.py (original) +++ pypy/dist/goal/compiler-hack.py Sun Feb 13 18:05:09 2005 @@ -1,13 +1,6 @@ -# Hacks to import compiler package -# As of revision 3865 - -import os -os.error = OSError -import __builtin__ -__builtin__.reload = lambda x: x -import ihooks -ihooks.install() import compiler c = compiler.compile('a=1', '', 'exec') import dis dis.dis(c) +exec c +print a From ac at codespeak.net Mon Feb 14 10:21:01 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 14 Feb 2005 10:21:01 +0100 (MET) Subject: [pypy-svn] r9196 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050214092101.A990627B6D@code1.codespeak.net> Author: ac Date: Mon Feb 14 10:21:01 2005 New Revision: 9196 Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Log: Work around problem with py.test's raises(). Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/pypy_unittest.py (original) +++ pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Mon Feb 14 10:21:01 2005 @@ -40,7 +40,13 @@ assert False, msg def assertRaises(self, exc, call, *args, **kwargs): - raises(exc, call, *args, **kwargs) + # Work around problem with py.test's raises + # raises(exc, call, *args, **kwargs) + try: + call(*args, **kwargs) + except exc: + return + raise AssertionError('DID NOT RAISE') def assertAlmostEqual(self, x, y, places=7, msg=None): if msg is None: From arigo at codespeak.net Mon Feb 14 11:26:38 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 14 Feb 2005 11:26:38 +0100 (MET) Subject: [pypy-svn] r9201 - pypy/dist/pypy/tool/test Message-ID: <20050214102638.5B9AA27B71@code1.codespeak.net> Author: arigo Date: Mon Feb 14 11:26:38 2005 New Revision: 9201 Modified: pypy/dist/pypy/tool/test/test_utestconvert.py pypy/dist/pypy/tool/test/test_utestconvert2.py Log: fixed the test for the conversion of failUnlessEqual() Modified: pypy/dist/pypy/tool/test/test_utestconvert.py ============================================================================== --- pypy/dist/pypy/tool/test/test_utestconvert.py (original) +++ pypy/dist/pypy/tool/test/test_utestconvert.py Mon Feb 14 11:26:38 2005 @@ -158,7 +158,7 @@ "assert not 0 == 0") assert rewrite_utest("self.failUnlessEqual(0, 0)") == ( - "assert not 0 != 0") + "assert 0 == 0") assert rewrite_utest( """ @@ -171,9 +171,9 @@ """ ) == ( """ - assert not (mushroom() + assert (mushroom() + mushroom() - + mushroom()) != '''badger badger badger + + mushroom()) == '''badger badger badger badger badger badger badger badger badger badger badger ''' # multiline, must move the parens @@ -363,7 +363,7 @@ """ ) == ( """ - assert not round(first - second, 5) != 0, 'A Snake!' + assert round(first - second, 5) == 0, 'A Snake!' """ ) Modified: pypy/dist/pypy/tool/test/test_utestconvert2.py ============================================================================== --- pypy/dist/pypy/tool/test/test_utestconvert2.py (original) +++ pypy/dist/pypy/tool/test/test_utestconvert2.py Mon Feb 14 11:26:38 2005 @@ -158,7 +158,7 @@ "assert not 0 == 0") self.assertEquals(rewrite_utest("self.failUnlessEqual(0, 0)"), - "assert not 0 != 0") + "assert 0 == 0") self.assertEquals(rewrite_utest( """ @@ -171,9 +171,9 @@ """ ), """ - assert not (mushroom() + assert (mushroom() + mushroom() - + mushroom()) != '''badger badger badger + + mushroom()) == '''badger badger badger badger badger badger badger badger badger badger badger ''' # multiline, must move the parens @@ -363,7 +363,7 @@ """ ), """ - assert not round(first - second, 5) != 0, 'A Snake!' + assert round(first - second, 5) == 0, 'A Snake!' """ ) From ac at codespeak.net Mon Feb 14 16:46:54 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 14 Feb 2005 16:46:54 +0100 (MET) Subject: [pypy-svn] r9210 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050214154654.486FC27B6D@code1.codespeak.net> Author: ac Date: Mon Feb 14 16:46:54 2005 New Revision: 9210 Modified: pypy/dist/pypy/objspace/std/strutil.py pypy/dist/pypy/objspace/std/test/test_strutil.py Log: Allow space between the sign and the digits when converting a string to interger as python does. Modified: pypy/dist/pypy/objspace/std/strutil.py ============================================================================== --- pypy/dist/pypy/objspace/std/strutil.py (original) +++ pypy/dist/pypy/objspace/std/strutil.py Mon Feb 14 16:46:54 2005 @@ -23,9 +23,9 @@ sign = 1 if s.startswith('-'): sign = -1 - s = s[1:] + s = strip_spaces(s[1:]) elif s.startswith('+'): - s = s[1:] + s = strip_spaces(s[1:]) if base == 0: if s.startswith('0x') or s.startswith('0X'): base = 16 Modified: pypy/dist/pypy/objspace/std/test/test_strutil.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_strutil.py (original) +++ pypy/dist/pypy/objspace/std/test/test_strutil.py Mon Feb 14 16:46:54 2005 @@ -19,6 +19,8 @@ (' \t \n 32313 \f \v \r \n\r ', 32313), ('+12', 12), ('-5', -5), + ('- 5', -5), + ('+ 5', 5), (' -123456789 ', -123456789), ] for s, expected in cases: @@ -66,8 +68,6 @@ '+-12', '-+12', '--12', - '- 5', - '+ 5', '12a6', '12A6', 'f', From pedronis at codespeak.net Mon Feb 14 18:06:05 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 14 Feb 2005 18:06:05 +0100 (MET) Subject: [pypy-svn] r9211 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050214170605.8B42A27B61@code1.codespeak.net> Author: pedronis Date: Mon Feb 14 18:06:05 2005 New Revision: 9211 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: start of refactoring of interp2app: reorganized how unwrap_spec are parsed Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Mon Feb 14 18:06:05 2005 @@ -37,16 +37,9 @@ self.argnames = argnames self.varargname = varargname self.kwargname = kwargname - self.rewind() - def rewind(self): - self._iter = iter(self.argnames) - - def __iter__(self): - return self - - def next(self): - return self._iter.next() + def next_arg(self): + return self._argiter.next() def append(self, argname): self.argnames.append(argname) @@ -54,12 +47,156 @@ def signature(self): return self.argnames, self.varargname, self.kwargname -def apply_unwrap_spec(unwrap_spec, orig_sig, new_sig, recipes): - for el in unwrap_spec: - recipes[el](orig_sig, new_sig) - return new_sig + def apply_unwrap_spec(self, unwrap_spec, recipe, new_sig): + self._argiter = iter(self.argnames) + for el in unwrap_spec: + recipe(el, self, new_sig) + return new_sig + + +class UnwrapSpecRecipe: + + bases_order = [W_Root, ObjSpace, Arguments, object] + + def dispatch(self, meth_family, el, orig_sig, new_sig): + if isinstance(el,str): + getattr(self, "%s_%s" % (meth_family, el))(el, orig_sig, new_sig) + else: + for typ in self.bases_order: + if issubclass(el, typ): + getattr(self, "%s__%s" % (meth_family, typ.__name__))(el, orig_sig, new_sig) + break + else: + assert False, "no match for unwrap_spec element: %s" % el + + def check(self, el, orig_sig, new_sig): + self.dispatch("check", el, orig_sig, new_sig) + + def emit(self, el, orig_sig, new_sig): + self.dispatch("emit", el, orig_sig, new_sig) + # checks for checking interp2app func argument names wrt unwrap_spec + # and synthetizing an app-level signature + + def check__ObjSpace(self, el, orig_sig, new_sig): + orig_sig.next_arg() + + def check_self(self, el, orig_sig, app_sig): # xxx + argname = orig_sig.next_arg() + app_sig.append(argname) + + def check__W_Root(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert argname.startswith('w_'), ( + "argument %s of built-in function %r should " + "start with 'w_'" % (argname, orig_sig.func)) + app_sig.append(argname[2:]) + + def check__Arguments(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = 'args' + app_sig.kwargname = 'keywords' + + def check_starargs(self, el, orig_sig, app_sig): + varargname = orig_sig.varargname + assert varargname.endswith('_w'), ( + "argument *%s of built-in function %r should end in '_w'" % + (varargname, orig_sig.func)) + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = varargname[:-2] + + def check_args_w(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert argname.endswith('_w'), ( + "rest arguments arg %s of built-in function %r should end in '_w'" % + (argname, orig_sig.func)) + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = argname[:-2] + + def check_w_args(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert argname.startswith('w_'), ( + "rest arguments arg %s of built-in function %r should start 'w_'" % + (argname, orig_sig.func)) + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = argname[2:] + + def check__object(self, el, orig_sig, app_sig): + if el not in (int, str, float): + assert False, "unsupported basic type in uwnrap_spec" + name = el.__name__ + argname = orig_sig.next_arg() + assert not argname.startswith('w_'), ( + "unwrapped %s argument %s of built-in function %r should " + "not start with 'w_'" % (name, argname, orig_sig.func)) + app_sig.append(argname) + + # collect code to emit for interp2app builtin frames based on unwrap_spec + + def emit__ObjSpace(self, el, orig_sig, emit_sig): + emit_sig.run_args.append('self.space') + + def emit_self(self, el, orig_sig, emit_sig): # xxx + emit_sig.setfastscope.append( + "self.self_arg = self.space.interpclass_w(scope_w[%d])" % + (emit_sig.through_scope_w)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.self_arg") + + def emit__W_Root(self, el, orig_sig, emit_sig): + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "self.w_arg%d = scope_w[%d]" % (cur,cur)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.w_arg%d" % cur) + + def emit__Arguments(self, el, orig_sig, emit_sig): + cur = emit_sig.through_scope_w + emit_sig.through_scope_w += 2 + emit_sig.setfastscope.append( + "self.arguments_arg = " + "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" + % (cur, cur+1)) + emit_sig.run_args.append("self.arguments_arg") + + def emit_starargs(self, el, orig_sig, emit_sig): + emit_sig.setfastscope.append( + "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" % + (emit_sig.through_scope_w)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("*self.starargs_arg_w") + + def emit_args_w(self, el, orig_sig, emit_sig): + emit_sig.setfastscope.append( + "self.args_w = self.space.unpacktuple(scope_w[%d])" % + (emit_sig.through_scope_w)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.args_w") + + def emit_w_args(self, el, orig_sig, emit_sig): + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "self.w_args = scope_w[%d]" % cur) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.w_args") + + def emit__object(self, el, orig_sig, emit_sig): + if el not in (int, str, float): + assert False, "unsupported basic type in uwnrap_spec" + name = el.__name__ + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "self.%s_arg%d = self.space.%s_w(scope_w[%d])" % + (name,cur,name,cur)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.%s_arg%d" % (name,cur)) + class BuiltinCodeSignature(Signature): def __init__(self,*args,**kwds): @@ -91,164 +228,20 @@ return type("BuiltinFrame_for_%s" % self.name, (BuiltinFrame,),d) - -def unwrap_spec_check_space(orig_sig, new_sig): - orig_sig.next() - -def unwrap_spec_check_self(orig_sig, new_sig): - argname = orig_sig.next() - new_sig.append(argname) - - -def unwrap_spec_check_wrapped(orig_sig, new_sig): - argname = orig_sig.next() - assert argname.startswith('w_'), ( - "argument %s of built-in function %r should " - "start with 'w_'" % (argname, orig_sig.func)) - new_sig.append(argname[2:]) - -def unwrap_spec_check_arguments(orig_sig, new_sig): - argname = orig_sig.next() - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = 'args' - new_sig.kwargname = 'keywords' - -def unwrap_spec_check_starargs(orig_sig, new_sig): - varargname = orig_sig.varargname - assert varargname.endswith('_w'), ( - "argument *%s of built-in function %r should end in '_w'" % - (varargname, orig_sig.func)) - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = varargname[:-2] - -def unwrap_spec_check_args_w(orig_sig, new_sig): - argname = orig_sig.next() - assert argname.endswith('_w'), ( - "rest arguments arg %s of built-in function %r should end in '_w'" % - (argname, orig_sig.func)) - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = argname[:-2] - -def unwrap_spec_check_w_args(orig_sig, new_sig): - argname = orig_sig.next() - assert argname.startswith('w_'), ( - "rest arguments arg %s of built-in function %r should start 'w_'" % - (argname, orig_sig.func)) - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = argname[2:] - -# recipes for checking interp2app func argumes wrt unwrap_spec -unwrap_spec_checks = { - ObjSpace: unwrap_spec_check_space, - 'self': unwrap_spec_check_self, - W_Root: unwrap_spec_check_wrapped, - Arguments: unwrap_spec_check_arguments, - '*': unwrap_spec_check_starargs, - 'args_w': unwrap_spec_check_args_w, - 'w_args': unwrap_spec_check_w_args, -} - -def unwrap_spec_emit_space(orig_sig, new_sig): - new_sig.run_args.append('self.space') - -def unwrap_spec_emit_self(orig_sig, new_sig): - new_sig.setfastscope.append( - "self.self_arg = self.space.interpclass_w(scope_w[%d])" % - (new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.self_arg") - -def unwrap_spec_emit_wrapped(orig_sig, new_sig): - cur = new_sig.through_scope_w - new_sig.setfastscope.append( - "self.w_arg%d = scope_w[%d]" % (cur,cur)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.w_arg%d" % cur) - - -def unwrap_spec_emit_arguments(orig_sig, new_sig): - cur = new_sig.through_scope_w - new_sig.through_scope_w += 2 - new_sig.setfastscope.append( - "self.arguments_arg = " - "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" - % (cur, cur+1)) - new_sig.run_args.append("self.arguments_arg") - -def unwrap_spec_emit_starargs(orig_sig, new_sig): - new_sig.setfastscope.append( - "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" % - (new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("*self.starargs_arg_w") - -def unwrap_spec_emit_args_w(orig_sig, new_sig): - new_sig.setfastscope.append( - "self.args_w = self.space.unpacktuple(scope_w[%d])" % - (new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.args_w") - -def unwrap_spec_emit_w_args(orig_sig, new_sig): - cur = new_sig.through_scope_w - new_sig.setfastscope.append( - "self.w_args = scope_w[%d]" % cur) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.w_args") - -# recipes for emitting unwrapping code for arguments of a interp2app func -# wrt a unwrap_spec -unwrap_spec_emit = { - ObjSpace: unwrap_spec_emit_space, - 'self': unwrap_spec_emit_self, - W_Root: unwrap_spec_emit_wrapped, - Arguments: unwrap_spec_emit_arguments, - '*': unwrap_spec_emit_starargs, - 'args_w': unwrap_spec_emit_args_w, - 'w_args': unwrap_spec_emit_w_args, -} - -# unwrap_spec_check/emit for str,int,float -for basic_type in [str,int,float]: - name = basic_type.__name__ - def unwrap_spec_check_basic(orig_sig, new_sig, name=name): - argname = orig_sig.next() - assert not argname.startswith('w_'), ( - "unwrapped %s argument %s of built-in function %r should " - "not start with 'w_'" % (name, argname, orig_sig.func)) - new_sig.append(argname) - def unwrap_spec_emit_basic(orig_sig, new_sig, name=name): - cur = new_sig.through_scope_w - new_sig.setfastscope.append( - "self.%s_arg%d = self.space.%s_w(scope_w[%d])" % - (name,cur,name,cur)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.%s_arg%d" % (name,cur)) - unwrap_spec_checks[basic_type] = hack.func_with_new_name( - unwrap_spec_check_basic, "unwrap_spec_check_%s" % name) - unwrap_spec_emit[basic_type] = hack.func_with_new_name( - unwrap_spec_emit_basic, "unwrap_spec_emit_%s" % name) - - - -def make_builtin_frame_class_for_unwrap_spec(unwrap_spec, cache={}): +def make_builtin_frame_class_for_unwrap_spec(orig_sig, unwrap_spec, cache={}): "NOT_RPYTHON" key = tuple(unwrap_spec) try: return cache[key] except KeyError: name = '_'.join([getattr(k, "__name__", k) for k in key]) - emit_sig = apply_unwrap_spec(unwrap_spec, None, - BuiltinCodeSignature(name=name), - unwrap_spec_emit) + emit_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().emit, + BuiltinCodeSignature(name=name)) cache[key] = cls = emit_sig.make_frame_class() return cls - + + class BuiltinCode(eval.Code): "The code object implementing a built-in (interpreter-level) hook." @@ -324,7 +317,7 @@ unwrap_spec.extend([W_Root] * n) if self.starargs: - unwrap_spec.append('*') + unwrap_spec.append('starargs') else: assert not ismethod, ("if unwrap_spec is specified, " "ismethod is not expected") @@ -333,11 +326,10 @@ orig_sig = Signature(func, argnames, varargname, kwargname) - new_sig = apply_unwrap_spec(unwrap_spec, orig_sig, - Signature(func), - unwrap_spec_checks) + app_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().check, + Signature(func)) - self.sig = argnames, varargname, kwargname = new_sig.signature() + self.sig = argnames, varargname, kwargname = app_sig.signature() self.minargs = len(argnames) if varargname: @@ -345,7 +337,7 @@ else: self.maxargs = self.minargs - self.framecls = make_builtin_frame_class_for_unwrap_spec(unwrap_spec) + self.framecls = make_builtin_frame_class_for_unwrap_spec(orig_sig, unwrap_spec) def create_frame(self, space, w_globals, closure=None): return self.framecls(space, self, w_globals) From ac at codespeak.net Mon Feb 14 18:16:48 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 14 Feb 2005 18:16:48 +0100 (MET) Subject: [pypy-svn] r9212 - in pypy/dist/pypy/objspace/std: . test Message-ID: <20050214171648.DCC6F27B52@code1.codespeak.net> Author: ac Date: Mon Feb 14 18:16:48 2005 New Revision: 9212 Modified: pypy/dist/pypy/objspace/std/inttype.py pypy/dist/pypy/objspace/std/longtype.py pypy/dist/pypy/objspace/std/test/test_floatobject.py pypy/dist/pypy/objspace/std/test/test_intobject.py pypy/dist/pypy/objspace/std/unicodeobject.py Log: Allow converting unicode -> int/long/float. Modified: pypy/dist/pypy/objspace/std/inttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/inttype.py (original) +++ pypy/dist/pypy/objspace/std/inttype.py Mon Feb 14 18:16:48 2005 @@ -35,12 +35,16 @@ else: base = space.int_w(w_base) - try: - s = space.str_w(w_value) - except OperationError, e: - raise OperationError(space.w_TypeError, - space.wrap("int() can't convert non-string " - "with explicit base")) + if space.is_true(space.isinstance(w_value, space.w_unicode)): + from pypy.objspace.std.unicodeobject import unicode_to_decimal_w + s = unicode_to_decimal_w(space, w_value) + else: + try: + s = space.str_w(w_value) + except OperationError, e: + raise OperationError(space.w_TypeError, + space.wrap("int() can't convert non-string " + "with explicit base")) try: # XXX can produce unwrapped long, need real long impl to know # what to do Modified: pypy/dist/pypy/objspace/std/longtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/longtype.py (original) +++ pypy/dist/pypy/objspace/std/longtype.py Mon Feb 14 18:16:48 2005 @@ -32,12 +32,16 @@ else: base = space.int_w(w_base) - try: - s = space.str_w(w_value) - except OperationError, e: - raise OperationError(space.w_TypeError, - space.wrap("long() can't convert non-string " - "with explicit base")) + if space.is_true(space.isinstance(w_value, space.w_unicode)): + from pypy.objspace.std.unicodeobject import unicode_to_decimal_w + s = unicode_to_decimal_w(space, w_value) + else: + try: + s = space.str_w(w_value) + except OperationError, e: + raise OperationError(space.w_TypeError, + space.wrap("long() can't convert non-string " + "with explicit base")) try: # XXX value can be unwrapped long value = string_to_long(s, base) Modified: pypy/dist/pypy/objspace/std/test/test_floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_floatobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_floatobject.py Mon Feb 14 18:16:48 2005 @@ -55,7 +55,10 @@ assert int(4e10) == 40000000000L def test_float_string(self): - assert 42.0 == float("42") + assert 42 == float("42") + + def test_float_unicode(self): + assert 42.3 == float(unicode("42.3")) def test_float_long(self): assert 42.0 == float(42L) Modified: pypy/dist/pypy/objspace/std/test/test_intobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_intobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_intobject.py Mon Feb 14 18:16:48 2005 @@ -292,6 +292,9 @@ assert 42 == int("42") assert 10000000000 == long("10000000000") + def test_int_unicode(self): + assert 42 == int(unicode('42')) + def test_int_float(self): assert 4 == int(4.2) Modified: pypy/dist/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/unicodeobject.py (original) +++ pypy/dist/pypy/objspace/std/unicodeobject.py Mon Feb 14 18:16:48 2005 @@ -1,9 +1,29 @@ from pypy.objspace.std.objspace import * from pypy.objspace.std.fake import fake_type, wrap_exception from pypy.objspace.std.stringobject import W_StringObject +from pypy.objspace.std.strutil import string_to_int, string_to_long W_UnicodeObject = fake_type(unicode) +# Helper for converting int/long +import unicodedata +def unicode_to_decimal_w(space, w_unistr): + result = [] + for uchr in space.unwrap(w_unistr): + if uchr.isspace(): + result.append(' ') + continue + try: + result.append(chr(ord('0') + unicodedata.decimal(uchr))) + continue + except ValueError: + ch = ord(uchr) + if 0 < ch < 256: + result.append(chr(ch)) + continue + raise OperationError(space.w_UnicodeEncodeError, space.wrap('invalid decimal Unicode string')) + return ''.join(result) + # string-to-unicode delegation def delegate_String2Unicode(w_str): space = w_str.space @@ -49,7 +69,25 @@ def ord__Unicode(space, w_uni): try: - return space.wrap(ord(w_uni.val)) + return space.wrap(ord(space.unwrap(w_uni))) + except: + wrap_exception(space) + +def float__Unicode(space, w_uni): + try: + return space.wrap(float(unicode_to_decimal_w(space, w_uni))) + except: + wrap_exception(space) + +def int__Unicode(space, w_uni): + try: + return space.wrap(string_to_int(unicode_to_decimal_w(space, w_uni))) + except: + wrap_exception(space) + +def long__Unicode(space, w_uni): + try: + return space.wrap(string_to_long(unicode_to_decimal_w(space, w_uni))) except: wrap_exception(space) From pedronis at codespeak.net Mon Feb 14 19:16:07 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 14 Feb 2005 19:16:07 +0100 (MET) Subject: [pypy-svn] r9213 - pypy/branch/dist-interpapp/pypy/translator/test Message-ID: <20050214181607.11C3927B5A@code1.codespeak.net> Author: pedronis Date: Mon Feb 14 19:16:06 2005 New Revision: 9213 Modified: pypy/branch/dist-interpapp/pypy/translator/test/snippet.py pypy/branch/dist-interpapp/pypy/translator/test/test_annrpython.py Log: proof of concept test of what should happen with the bltin frame/code setup, if the unwrapping in setfastscope is precise enough Modified: pypy/branch/dist-interpapp/pypy/translator/test/snippet.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/translator/test/snippet.py (original) +++ pypy/branch/dist-interpapp/pypy/translator/test/snippet.py Mon Feb 14 19:16:06 2005 @@ -764,3 +764,52 @@ return (a,a1,b,b1) +# reorg + +class BltinCodeReorg: + def __init__(self, framecls): + self.framecls = framecls + + def call(self, x): + frame = self.framecls() + frame.set(x) + return frame.run() + +class BltinFrameReorg: + def __init__(self): + pass + + def set(self,x): + pass + + def run(self): + pass + +class FBltinFrameReorg(BltinFrameReorg): + + def set(self, x): + self.arg = int(x) + + def run(self): + return bltin_code_frame_f(self.arg) + +class GBltinFrameReorg(BltinFrameReorg): + + def set(self, x): + self.arg = str(x) + + def run(self): + return bltin_code_frame_g(self.arg) + + +bltin_code_for_f_reorg = BltinCodeReorg(FBltinFrameReorg) +bltin_code_for_g_reorg = BltinCodeReorg(GBltinFrameReorg) + +def bltin_code_frame_reorg(): + a = bltin_code_for_f_reorg.call(0) + a1 = bltin_code_for_f_reorg.call(1) + b = bltin_code_for_g_reorg.call("a") + b1 = bltin_code_for_g_reorg.call("b") + return (a,a1,b,b1) + + Modified: pypy/branch/dist-interpapp/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/translator/test/test_annrpython.py (original) +++ pypy/branch/dist-interpapp/pypy/translator/test/test_annrpython.py Mon Feb 14 19:16:06 2005 @@ -494,10 +494,17 @@ a.build_types(snippet.bltin_code_frame_confusion,[]) f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f) g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g) - is_int = isinstance(a.binding(f_flowgraph.getreturnvar()), + # annotator confused by original bltin code/frame setup, we just get SomeObject here + assert a.binding(f_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject + assert a.binding(g_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject + + def test_bltin_code_frame_reorg(self): + a = RPythonAnnotator() + a.build_types(snippet.bltin_code_frame_reorg,[]) + f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f) + g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g) + assert isinstance(a.binding(f_flowgraph.getreturnvar()), annmodel.SomeInteger) - if not is_int: - py.test.skip("annotator confused with bltin code/frame setup") assert isinstance(a.binding(g_flowgraph.getreturnvar()), annmodel.SomeString) From arigo at codespeak.net Mon Feb 14 20:07:53 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 14 Feb 2005 20:07:53 +0100 (MET) Subject: [pypy-svn] r9215 - pypy/dist/pypy/translator Message-ID: <20050214190753.6D05A27B5B@code1.codespeak.net> Author: arigo Date: Mon Feb 14 20:07:52 2005 New Revision: 9215 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: Don't put full paths in the generated code. It makes the result differ depending on who runs the translation, and creates longer diffs. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 14 20:07:52 2005 @@ -883,7 +883,7 @@ print >> f, ("## filename %r\n" "## function %r\n" "## firstlineno %d") % ( - func.func_code.co_filename, + os.path.basename(func.func_code.co_filename), func.func_code.co_name, func.func_code.co_firstlineno) print >> f, "##SECTION##" From arigo at codespeak.net Mon Feb 14 20:24:05 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 14 Feb 2005 20:24:05 +0100 (MET) Subject: [pypy-svn] r9218 - pypy/dist/pypy/interpreter/test Message-ID: <20050214192405.5C2D427B5B@code1.codespeak.net> Author: arigo Date: Mon Feb 14 20:24:05 2005 New Revision: 9218 Modified: pypy/dist/pypy/interpreter/test/test_eval.py pypy/dist/pypy/interpreter/test/test_exec.py Log: Changed our tests from "assert not a != b" to "assert a == b". Modified: pypy/dist/pypy/interpreter/test/test_eval.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_eval.py (original) +++ pypy/dist/pypy/interpreter/test/test_eval.py Mon Feb 14 20:24:05 2005 @@ -45,7 +45,7 @@ def sameList(self, l1, l2): assert len(l1) == len(l2) for w_1, w_2 in zip(l1, l2): - assert not ((w_1 is UNDEFINED) != (w_2 is UNDEFINED)) + assert (w_1 is UNDEFINED) == (w_2 is UNDEFINED) if w_1 is not UNDEFINED: assert self.space.eq_w(w_1, w_2) Modified: pypy/dist/pypy/interpreter/test/test_exec.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_exec.py (original) +++ pypy/dist/pypy/interpreter/test/test_exec.py Mon Feb 14 20:24:05 2005 @@ -10,12 +10,12 @@ g = {} l = {} exec "a = 3" in g, l - assert not l['a'] != 3 + assert l['a'] == 3 def test_localfill(self): g = {} exec "a = 3" in g - assert not g['a'] != 3 + assert g['a'] == 3 def test_builtinsupply(self): g = {} @@ -37,7 +37,7 @@ g = {} l = {} exec co in g, l - assert not l['a'] != 3 + assert l['a'] == 3 ## # Commented out as PyPy give errors using open() ## # ["Not availible in restricted mode"] @@ -50,18 +50,18 @@ def test_implicit(self): a = 4 exec "a = 3" - assert not a !=3 + assert a == 3 def test_tuplelocals(self): g = {} l = {} exec ("a = 3", g, l) - assert not l['a'] != 3 + assert l['a'] == 3 def test_tupleglobals(self): g = {} exec ("a = 3", g) - assert not g['a'] != 3 + assert g['a'] == 3 def test_exceptionfallthrough(self): def f(): From ac at codespeak.net Mon Feb 14 21:40:11 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 14 Feb 2005 21:40:11 +0100 (MET) Subject: [pypy-svn] r9220 - in pypy/dist/pypy/module: . test Message-ID: <20050214204011.7AA8927B5A@code1.codespeak.net> Author: ac Date: Mon Feb 14 21:40:11 2005 New Revision: 9220 Modified: pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/module/test/test_builtin.py Log: Have getattr() accept unicode argument. Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Mon Feb 14 21:40:11 2005 @@ -261,6 +261,8 @@ return space.w_None def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): + if space.is_true(space.isinstance(w_name, space.w_unicode)): + w_name = space.call_method(w_name, 'encode') try: return space.getattr(w_object, w_name) except OperationError, e: Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Mon Feb 14 21:40:11 2005 @@ -69,6 +69,9 @@ assert getattr(a, 'i') == 5 raises(AttributeError, getattr, a, 'k') assert getattr(a, 'k', 42) == 42 + assert getattr(a, u'i') == 5 + raises(AttributeError, getattr, a, u'k') + assert getattr(a, u'k', 42) == 42 def test_sum(self): assert sum([]) ==0 From ac at codespeak.net Mon Feb 14 22:03:26 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 14 Feb 2005 22:03:26 +0100 (MET) Subject: [pypy-svn] r9221 - pypy/dist/pypy/module Message-ID: <20050214210326.C570F27B5A@code1.codespeak.net> Author: ac Date: Mon Feb 14 22:03:26 2005 New Revision: 9221 Modified: pypy/dist/pypy/module/__builtin__interp.py Log: Have eval() and compile() accept unicode argument. Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Mon Feb 14 22:03:26 2005 @@ -197,8 +197,20 @@ w_exc = space.call_function(space.w_ImportError, w_failing) raise OperationError(space.w_ImportError, w_exc) -def compile(str_, filename, startstr, - supplied_flags=0, dont_inherit=0): +def compile(w_str_, w_filename, w_startstr, + w_supplied_flags=None, w_dont_inherit=None): + if space.is_true(space.isinstance(w_str_, space.w_unicode)): + str_ = space.unwrap(w_str_) + else: + str_ = space.str_w(w_str_) + filename = space.str_w(w_filename) + startstr = space.str_w(w_startstr) + supplied_flags = 0 + if not space.is_w(w_supplied_flags, space.w_None): + supplied_flags = space.int_w(w_supplied_flags) + dont_inherit = 0 + if not space.is_w(w_dont_inherit, space.w_None): + dont_inherit = space.int_w(w_dont_inherit) #print (str_, filename, startstr, supplied_flags, dont_inherit) # XXX we additionally allow GENERATORS because compiling some builtins # requires it. doesn't feel quite right to do that here. @@ -223,14 +235,15 @@ raise OperationError(space.w_TypeError,space.wrap(str(e))) return space.wrap(PyCode(space)._from_code(c)) # -compile.unwrap_spec = [str,str,str,int,int] +#compile.unwrap_spec = [str,str,str,int,int] def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): w = space.wrap - if space.is_true(space.isinstance(w_source, space.w_str)): - w_codeobj = compile(space.str_w(w_source).lstrip(' \t'), "", "eval") + if (space.is_true(space.isinstance(w_source, space.w_str)) or + space.is_true(space.isinstance(w_source, space.w_unicode))): + w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), space.wrap(""), space.wrap("eval"), space.w_None, space.w_None) elif isinstance(space.interpclass_w(w_source), PyCode): w_codeobj = w_source else: From hpk at codespeak.net Tue Feb 15 00:01:39 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 15 Feb 2005 00:01:39 +0100 (MET) Subject: [pypy-svn] r9225 - pypy/dist/pypy/interpreter Message-ID: <20050214230139.6C08927B5A@code1.codespeak.net> Author: hpk Date: Tue Feb 15 00:01:39 2005 New Revision: 9225 Modified: pypy/dist/pypy/interpreter/gateway.py Log: frame.run() is expected to convert MemoryErrors, KeyboardInterrupts and RuntimeErrors into their wrapped space-error equivalents. This is now fixed for frames run()ning at interplevel. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Tue Feb 15 00:01:39 2005 @@ -81,7 +81,15 @@ exec setfastscope in globals(),d exec """ def run(self): - w_result = self.code.func(%s) + try: + w_result = self.code.func(%s) + except KeyboardInterrupt: + raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) + except MemoryError: + raise OperationError(self.space.w_MemoryError, self.space.w_None) + except RuntimeError, e: + raise OperationError(self.space.w_RuntimeError, + self.space.wrap("internal error" + str(e))) if w_result is None: w_result = self.space.w_None return w_result From arigo at codespeak.net Tue Feb 15 00:36:26 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Tue, 15 Feb 2005 00:36:26 +0100 (MET) Subject: [pypy-svn] r9226 - pypy/dist/pypy/translator Message-ID: <20050214233626.9FB7527B5A@code1.codespeak.net> Author: arigo Date: Tue Feb 15 00:36:26 2005 New Revision: 9226 Modified: pypy/dist/pypy/translator/genc.h pypy/dist/pypy/translator/genc.py pypy/dist/pypy/translator/translator.py Log: This is a try (revertable if needed!) at writing the C init code in Python instead, as a big frozen bytecode. Modified: pypy/dist/pypy/translator/genc.h ============================================================================== --- pypy/dist/pypy/translator/genc.h (original) +++ pypy/dist/pypy/translator/genc.h Tue Feb 15 00:36:26 2005 @@ -173,26 +173,6 @@ #define REGISTER_GLOBAL(name) Py_INCREF(name); PyModule_AddObject(m, #name, name); -/*** classes ***/ - -/*#define SETUP_CLASS(t, name, base) \ - t = PyObject_CallFunction((PyObject*) &PyType_Type, \ - "s(O){}", name, base)*/ - -#define SETUP_CLASS_ATTR(t, attr, value) \ - (PyObject_SetAttrString(t, attr, value) >= 0) - -/*** instances ***/ - -#define SETUP_INSTANCE_ATTR(t, attr, value) \ - (PyObject_SetAttrString(t, attr, value) >= 0) - -#define SETUP_INSTANCE(i, cls) \ - (PyType_Check(cls) ? \ - (i = PyType_GenericAlloc((PyTypeObject *)cls, 0)) : \ - (i = PyInstance_NewRaw(cls, NULL))) - - #if defined(USE_CALL_TRACE) #define TRACE_CALL __f, __tstate, @@ -293,7 +273,95 @@ PyModule_AddStringConstant(m, "__sourcefile__", __FILE__); \ this_module_globals = PyModule_GetDict(m); \ PyGenCFunction_Type.tp_base = &PyCFunction_Type; \ - PyType_Ready(&PyGenCFunction_Type); + PyType_Ready(&PyGenCFunction_Type); \ + if (setup_globalfunctions(globalfunctiondefs) < 0) \ + return; \ + if (setup_initcode(frozen_initcode, sizeof(frozen_initcode)) < 0) \ + return; \ + if (setup_globalobjects(globalobjectdefs) < 0) \ + return; + + +/*** table of global objects ***/ + +typedef struct { + PyObject** p; + char* name; +} globalobjectdef_t; + +typedef struct { + PyObject** p; + PyMethodDef ml; +} globalfunctiondef_t; + +static int setup_globalobjects(globalobjectdef_t* def) +{ + PyObject* obj; + + for (; def->p != NULL; def++) { + obj = PyDict_GetItemString(this_module_globals, def->name); + if (obj == NULL) { + PyErr_Format(PyExc_AttributeError, + "initialization code should have " + "created '%s'", def->name); + return -1; + } + Py_INCREF(obj); + *def->p = obj; /* store the object ref in the global var */ + } + return 0; +} + +static int setup_globalfunctions(globalfunctiondef_t* def) +{ + PyObject* fn; + PyObject* name; + int len; + + for (; def->p != NULL; def++) { + fn = PyCFunction_New(&def->ml, NULL); + if (fn == NULL) + return -1; + fn->ob_type = &PyGenCFunction_Type; + *def->p = fn; /* store the object ref in the global var */ + + len = 0; + while (def->ml.ml_name[len] != 0) + len++; + name = PyString_FromStringAndSize(NULL, 6+len); + if (name == NULL) + return -1; + memcpy(PyString_AS_STRING(name), "gfunc_", 6); + memcpy(PyString_AS_STRING(name)+6, def->ml.ml_name, len); + if (PyDict_SetItem(this_module_globals, name, fn) < 0) + return -1; + Py_DECREF(name); + } + return 0; +} + +static int setup_initcode(unsigned char* frozendata, int len) +{ + PyObject* co; + PyObject* globals; + PyObject* res; + co = PyMarshal_ReadObjectFromString((char*) frozendata, len); + if (co == NULL) + return -1; + if (!PyCode_Check(co)) { + PyErr_SetString(PyExc_TypeError, "uh?"); + return -1; + } + globals = this_module_globals; + if (PyDict_GetItemString(globals, "__builtins__") == NULL) + PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()); + res = PyEval_EvalCode((PyCodeObject *) co, globals, globals); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; +} /*** operations with a variable number of arguments ***/ @@ -451,14 +519,6 @@ } #endif -static PyObject* skipped(PyObject* self, PyObject* args) -{ - PyErr_Format(PyExc_AssertionError, - "calling the skipped function '%s'", - (((PyCFunctionObject *)self) -> m_ml -> ml_name)); - return NULL; -} - static PyObject* CallWithShape(PyObject* callable, PyObject* shape, ...) { /* XXX the 'shape' argument is a tuple as specified by Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Tue Feb 15 00:36:26 2005 @@ -3,7 +3,7 @@ """ from __future__ import generators -import autopath, os, sys +import autopath, os, sys, __builtin__, marshal from pypy.objspace.flow.model import Variable, Constant, SpaceOperation from pypy.objspace.flow.model import FunctionGraph, Block, Link from pypy.objspace.flow.model import last_exception, last_exc_value @@ -11,7 +11,7 @@ from pypy.translator.simplify import remove_direct_loops from pypy.interpreter.pycode import CO_VARARGS from pypy.annotation import model as annmodel -from types import FunctionType, CodeType +from types import FunctionType, CodeType, InstanceType from pypy.objspace.std.restricted_int import r_int, r_uint @@ -30,19 +30,18 @@ SEEN[result] = True return result -def go_figure_out_this_name(source): - # ahem - return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % ( - source, ) +#def go_figure_out_this_name(source): +# # ahem +# return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % ( +# source, ) class GenC: MODNAMES = {} - def __init__(self, f, translator, modname=None, f2=None, f2name=None): + def __init__(self, f, translator, modname=None, f2=None): self.f = f self.f2 = f2 - self.f2name = f2name self.translator = translator self.modname = (modname or uniquemodulename(translator.functions[0].__name__)) @@ -51,7 +50,12 @@ Constant(True).key: 'Py_True', } self.seennames = {} - self.initcode = [] # list of lines for the module's initxxx() + self.initcode = [ # list of lines for the module's initxxx() + 'import new, types', + 'Py_None = None', + 'Py_False = False', + 'Py_True = True', + ] self.latercode = [] # list of generators generating extra lines # for later in initxxx() -- for recursive # objects @@ -101,11 +105,15 @@ else: return self.uniquename('%s_%d' % (basename, n)) + def initcode_python(self, name, pyexpr): + # generate init code that will evaluate the given Python expression + self.initcode.append("%s = %s" % (name, pyexpr)) + def nameof_object(self, value): if type(value) is not object: raise Exception, "nameof(%r)" % (value,) name = self.uniquename('g_object') - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*)&PyBaseObject_Type, ""))'%name) + self.initcode_python(name, "object()") return name def nameof_module(self, value): @@ -115,7 +123,7 @@ value.__file__.endswith('.pyo')), \ "%r is not a builtin module (probably :)"%value name = self.uniquename('mod%s'%value.__name__) - self.initcode.append('INITCHK(%s = PyImport_ImportModule("%s"))'%(name, value.__name__)) + self.initcode_python(name, "__import__(%r)" % (value.__name__,)) return name @@ -125,19 +133,16 @@ else: name = 'gint_minus%d' % abs(value) name = self.uniquename(name) - self.initcode.append('INITCHK(%s = ' - 'PyInt_FromLong(%d))' % (name, value)) + self.initcode_python(name, repr(value)) return name def nameof_long(self, value): - assert type(int(value)) is int, "your literal long is too long" if value >= 0: name = 'glong%d' % value else: name = 'glong_minus%d' % abs(value) name = self.uniquename(name) - self.initcode.append('INITCHK(%s = ' - 'PyLong_FromLong(%d))' % (name, value)) + self.initcode_python(name, repr(value)) return name def nameof_float(self, value): @@ -145,33 +150,28 @@ name = (name.replace('-', 'minus') .replace('.', 'dot')) name = self.uniquename(name) - self.initcode.append('INITCHK(%s = ' - 'PyFloat_FromDouble(%r))' % (name, value)) + self.initcode_python(name, repr(value)) return name def nameof_str(self, value): name = self.uniquename('gstr_' + value[:32]) - if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']: - # non-printable string - s = 'chr_%s' % name - self.globaldecl.append('static char %s[] = { %s };' % ( - s, ', '.join(['%d' % ord(c) for c in value]))) - else: - # printable string - s = '"%s"' % value - self.initcode.append('INITCHK(%s = PyString_FromStringAndSize(' - '%s, %d))' % (name, s, len(value))) +## if [c for c in value if c<' ' or c>'~' or c=='"' or c=='\\']: +## # non-printable string +## s = 'chr_%s' % name +## self.globaldecl.append('static char %s[] = { %s };' % ( +## s, ', '.join(['%d' % ord(c) for c in value]))) +## else: +## # printable string +## s = '"%s"' % value + self.initcode_python(name, repr(value)) return name def skipped_function(self, func): # debugging only! Generates a placeholder for missing functions # that raises an exception when called. name = self.uniquename('gskippedfunc_' + func.__name__) - self.globaldecl.append('static PyMethodDef ml_%s = { "%s", &skipped, METH_VARARGS };' % (name, name)) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\tPy_INCREF(%s);' % name) - self.initcode.append('\tPyCFunction_GET_SELF(%s) = %s;' % (name, name)) + self.initcode.append('def %s(*a,**k):' % name) + self.initcode.append(' raise NotImplementedError') return name def nameof_function(self, func, progress=['-\x08', '\\\x08', @@ -193,9 +193,6 @@ sys.stderr.write(p) progress.append(p) name = self.uniquename('gfunc_' + func.__name__) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, name)) - self.initcode.append('\t%s->ob_type = &PyGenCFunction_Type;' % name) self.pendingfunctions.append(func) return name @@ -204,8 +201,7 @@ func = sm.__get__(42.5) name = self.uniquename('gsm_' + func.__name__) functionname = self.nameof(func) - self.initcode.append('INITCHK(%s = PyCFunction_New(' - '&ml_%s, NULL))' % (name, functionname)) + self.initcode_python(name, 'staticmethod(%s)' % functionname) return name def nameof_instancemethod(self, meth): @@ -217,9 +213,8 @@ func = self.nameof(meth.im_func) typ = self.nameof(meth.im_class) name = self.uniquename('gmeth_'+meth.im_func.__name__) - self.initcode.append( - 'INITCHK(%s = gencfunc_descr_get(%s, %s, %s))'%( - name, func, ob, typ)) + self.initcode_python(name, 'new.instancemethod(%s, %s, %s)' % ( + func, ob, typ)) return name def should_translate_attr(self, pbc, attr): @@ -246,10 +241,11 @@ content.sort() for key, value in content: if self.should_translate_attr(instance, key): - yield 'INITCHK(SETUP_INSTANCE_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) - self.initcode.append('INITCHK(SETUP_INSTANCE(%s, %s))' % ( - name, cls)) + yield '%s.%s = %s' % (name, key, self.nameof(value)) + self.initcode.append('if isinstance(%s, type):' % cls) + self.initcode.append(' %s = %s.__new__(%s)' % (name, cls, cls)) + self.initcode.append('else:') + self.initcode.append(' %s = new.instance(%s)' % (name, cls)) self.later(initinstance()) return name @@ -269,29 +265,27 @@ raise Exception, '%r not found in any built-in module' % (func,) name = self.uniquename('gbltin_' + func.__name__) if modname == '__builtin__': - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - 'PyEval_GetBuiltins(), "%s"))' % ( - name, func.__name__)) + self.initcode_python(name, func.__name__) else: - self.initcode.append('INITCHK(%s = PyObject_GetAttrString(' - '%s, "%s"))' % ( - name, self.nameof(module), func.__name__)) + modname = self.nameof(module) + self.initcode_python(name, '%s.%s' % (modname, func.__name__)) else: # builtin (bound) method name = self.uniquename('gbltinmethod_' + func.__name__) - self.initcode.append('INITCHK(%s = PyObject_GetAttrString(' - '%s, "%s"))' % ( - name, self.nameof(func.__self__), func.__name__)) + selfname = self.nameof(func.__self__) + self.initcode_python(name, '%s.%s' % (selfname, func.__name__)) return name def nameof_classobj(self, cls): if cls.__doc__ and cls.__doc__.lstrip().startswith('NOT_RPYTHON'): raise Exception, "%r should never be reached" % (cls,) - metaclass = "&PyType_Type" + metaclass = "type" if issubclass(cls, Exception): if cls.__module__ == 'exceptions': - return 'PyExc_%s'%cls.__name__ + name = self.uniquename('gexc_' + cls.__name__) + self.initcode_python(name, cls.__name__) + return name #else: # # exceptions must be old-style classes (grr!) # metaclass = "&PyClass_Type" @@ -299,7 +293,7 @@ # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): assert type(cls) is type(Exception) - metaclass = "&PyClass_Type" + metaclass = "types.ClassType" name = self.uniquename('gcls_' + cls.__name__) basenames = [self.nameof(base) for base in cls.__bases__] @@ -320,74 +314,57 @@ print value continue - yield 'INITCHK(SETUP_CLASS_ATTR(%s, "%s", %s))' % ( - name, key, self.nameof(value)) + yield '%s.%s = %s' % (name, key, self.nameof(value)) baseargs = ", ".join(basenames) if baseargs: - baseargs = ', '+baseargs - self.initcode.append('INITCHK(%s = PyObject_CallFunction((PyObject*) %s,' - %(name, metaclass)) - self.initcode.append('\t\t"s(%s){}", "%s"%s))' - %("O"*len(basenames), cls.__name__, baseargs)) - + baseargs = '(%s)' % baseargs + self.initcode.append('class %s%s:' % (name, baseargs)) + self.initcode.append(' __metaclass__ = %s' % metaclass) self.later(initclassobj()) return name nameof_class = nameof_classobj # for Python 2.2 typename_mapping = { - object: '&PyBaseObject_Type', - int: '&PyInt_Type', - long: '&PyLong_Type', - bool: '&PyBool_Type', - list: '&PyList_Type', - tuple: '&PyTuple_Type', - dict: '&PyDict_Type', - str: '&PyString_Type', - float: '&PyFloat_Type', - type(Exception()): '&PyInstance_Type', - type: '&PyType_Type', - complex:'&PyComplex_Type', - unicode:'&PyUnicode_Type', - file: '&PyFile_Type', - type(None): 'Py_None->ob_type', - CodeType: '&PyCode_Type', - slice: '&PySlice_Type', + InstanceType: 'types.InstanceType', + type(None): 'type(None)', + CodeType: 'types.CodeType', - r_int: '&PyInt_Type', - r_uint: '&PyInt_Type', + r_int: 'int', # XXX + r_uint: 'int', # XXX - # XXX we leak 5 references here, but that's the least of the - # problems with this section of code + # XXX more hacks # type 'builtin_function_or_method': - type(len): go_figure_out_this_name('type(len)'), + type(len): 'type(len)', # type 'method_descriptor': - type(list.append): go_figure_out_this_name('type(list.append)'), + type(list.append): 'type(list.append)', # type 'wrapper_descriptor': - type(type(None).__repr__): go_figure_out_this_name( - 'type(type(None).__repr__)'), + type(type(None).__repr__): 'type(type(None).__repr__)', # type 'getset_descriptor': - type(type.__dict__['__dict__']): go_figure_out_this_name( - "type(type.__dict__['__dict__'])"), + type(type.__dict__['__dict__']): "type(type.__dict__['__dict__'])", # type 'member_descriptor': - type(type.__dict__['__basicsize__']): go_figure_out_this_name( - "type(type.__dict__['__basicsize__'])"), + type(type.__dict__['__basicsize__']): "type(type.__dict__['__basicsize__'])", } def nameof_type(self, cls): - if cls in self.typename_mapping: - return '(PyObject*) %s' % self.typename_mapping[cls] - assert cls.__module__ != '__builtin__', \ - "built-in class %r not found in typename_mapping" % (cls,) - return self.nameof_classobj(cls) + if cls.__module__ != '__builtin__': + return self.nameof_classobj(cls) # user-defined type + name = self.uniquename('gtype_%s' % cls.__name__) + if getattr(__builtin__, cls.__name__, None) is cls: + expr = cls.__name__ # type available from __builtin__ + else: + expr = self.typename_mapping[cls] + self.initcode_python(name, expr) + return name def nameof_tuple(self, tup): name = self.uniquename('g%dtuple' % len(tup)) args = [self.nameof(x) for x in tup] - args.insert(0, '%d' % len(tup)) args = ', '.join(args) - self.initcode.append('INITCHK(%s = PyTuple_Pack(%s))' % (name, args)) + if args: + args += ',' + self.initcode_python(name, '(%s)' % args) return name def nameof_list(self, lis): @@ -395,9 +372,8 @@ def initlist(): for i in range(len(lis)): item = self.nameof(lis[i]) - yield '\tPy_INCREF(%s);' % item - yield '\tPyList_SET_ITEM(%s, %d, %s);' % (name, i, item) - self.initcode.append('INITCHK(%s = PyList_New(%d))' % (name, len(lis))) + yield '%s.append(%s)' % (name, item) + self.initcode_python(name, '[]') self.later(initlist()) return name @@ -409,14 +385,11 @@ def initdict(): for k in dic: if type(k) is str: - yield ('\tINITCHK(PyDict_SetItemString' - '(%s, "%s", %s) >= 0)'%( - name, k, self.nameof(dic[k]))) + yield '%s[%r] = %s' % (name, k, self.nameof(dic[k])) else: - yield ('\tINITCHK(PyDict_SetItem' - '(%s, %s, %s) >= 0)'%( - name, self.nameof(k), self.nameof(dic[k]))) - self.initcode.append('INITCHK(%s = PyDict_New())' % (name,)) + yield '%s[%s] = %s' % (name, self.nameof(k), + self.nameof(dic[k])) + self.initcode_python(name, '{}') self.later(initdict()) return name @@ -426,11 +399,7 @@ name = self.uniquename('gdescriptor_%s_%s' % ( md.__objclass__.__name__, md.__name__)) cls = self.nameof(md.__objclass__) - self.initcode.append('INITCHK(PyType_Ready((PyTypeObject*) %s) >= 0)' % - cls) - self.initcode.append('INITCHK(%s = PyMapping_GetItemString(' - '((PyTypeObject*) %s)->tp_dict, "%s"))' % - (name, cls, md.__name__)) + self.initcode_python(name, '%s.__dict__[%r]' % (cls, md.__name__)) return name nameof_getset_descriptor = nameof_member_descriptor nameof_method_descriptor = nameof_member_descriptor @@ -468,13 +437,31 @@ self.debugstack = () self.gen_global_declarations() - # footer - print >> f, self.C_INIT_HEADER % info - if self.f2name is not None: - print >> f, '#include "%s"' % self.f2name - for codeline in self.initcode: - print >> f, '\t' + codeline - print >> f, self.C_INIT_FOOTER % info + # after all the functions: global object table + print >> f, self.C_OBJECT_TABLE + for name in self.globalobjects: + if not name.startswith('gfunc_'): + print >> f, '\t{&%s, "%s"},' % (name, name) + print >> f, self.C_TABLE_END + + # global function table + print >> f, self.C_FUNCTION_TABLE + for name in self.globalobjects: + if name.startswith('gfunc_'): + print >> f, ('\t{&%s, {"%s", (PyCFunction)f_%s, ' + 'METH_VARARGS|METH_KEYWORDS}},' % ( + name, name[6:], name[6:])) + print >> f, self.C_TABLE_END + + # frozen init bytecode + print >> f, self.C_FROZEN_BEGIN + bytecode = self.getfrozenbytecode() + for i in range(0, len(bytecode), 20): + print >> f, ''.join(['%d,' % ord(c) for c in bytecode[i:i+20]]) + print >> f, self.C_FROZEN_END + + # the footer proper: the module init function */ + print >> f, self.C_FOOTER % info def gen_global_declarations(self): g = self.globaldecl @@ -485,15 +472,22 @@ print >> f, line print >> f del g[:] - g = self.globalobjects - for name in g: - self.initcode.append('REGISTER_GLOBAL(%s)' % (name,)) - del g[:] if self.f2 is not None: for line in self.initcode: print >> self.f2, line del self.initcode[:] + def getfrozenbytecode(self): + if self.f2 is not None: + self.f2.seek(0) + self.initcode.insert(0, self.f2.read()) + self.initcode.append('') + source = '\n'.join(self.initcode) + del self.initcode[:] + co = compile(source, self.modname, 'exec') + del source + return marshal.dumps(co) + def gen_cfunction(self, func): ## print 'gen_cfunction (%s:%d) %s' % ( ## func.func_globals.get('__name__', '?'), @@ -638,12 +632,6 @@ f.write(fmt % line) print >> f, '}' - # print the PyMethodDef - print >> f, ('static PyMethodDef ml_%s = {\n' - ' "%s", (PyCFunction)%s, METH_VARARGS|METH_KEYWORDS };' % ( - cname, func.__name__, f_name)) - print >> f - if not self.translator.frozen: # this is only to keep the RAM consumption under control del self.translator.flowgraphs[func] @@ -791,14 +779,28 @@ C_SEP = "/************************************************************/" - C_INIT_HEADER = C_SEP + ''' + C_OBJECT_TABLE = C_SEP + ''' + +/* Table of global objects */ +static globalobjectdef_t globalobjectdefs[] = {''' + + C_FUNCTION_TABLE = ''' +/* Table of functions */ +static globalfunctiondef_t globalfunctiondefs[] = {''' + + C_TABLE_END = '\t{ NULL }\t/* Sentinel */\n};' + + C_FROZEN_BEGIN = ''' +/* Frozen Python bytecode: the initialization code */ +static unsigned char frozen_initcode[] = {''' + + C_FROZEN_END = '''};\n''' + + C_FOOTER = C_SEP + ''' MODULE_INITFUNC(%(modname)s) { \tSETUP_MODULE(%(modname)s) -''' - - C_INIT_FOOTER = ''' \tPyModule_AddObject(m, "%(entrypointname)s", %(entrypoint)s); }''' Modified: pypy/dist/pypy/translator/translator.py ============================================================================== --- pypy/dist/pypy/translator/translator.py (original) +++ pypy/dist/pypy/translator/translator.py Tue Feb 15 00:36:26 2005 @@ -228,8 +228,8 @@ name = uniquemodulename(self.entrypoint.func_name) cfile = udir.join('%s.c' % name) f = cfile.open('w') - f2 = udir.join('%s-init.h' % name).open('w') - GenC(f, self, name, f2=f2, f2name='%s-init.h' % name) + f2 = udir.join('%s-init.py' % name).open('w+') + GenC(f, self, name, f2=f2) f2.close() f.close() if not really_compile: From pedronis at codespeak.net Tue Feb 15 01:46:05 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 15 Feb 2005 01:46:05 +0100 (MET) Subject: [pypy-svn] r9227 - in pypy/dist/pypy: interpreter interpreter/test module objspace/std Message-ID: <20050215004605.172B627B5B@code1.codespeak.net> Author: pedronis Date: Tue Feb 15 01:46:04 2005 New Revision: 9227 Modified: pypy/dist/pypy/interpreter/main.py pypy/dist/pypy/interpreter/test/test_interpreter.py pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/objspace/std/unicodeobject.py Log: fixes for tests and comments str_w works with unicode Modified: pypy/dist/pypy/interpreter/main.py ============================================================================== --- pypy/dist/pypy/interpreter/main.py (original) +++ pypy/dist/pypy/interpreter/main.py Tue Feb 15 01:46:04 2005 @@ -16,7 +16,7 @@ compile = space.builtin.compile w = space.wrap - w_code = compile(source, filename, cmd, 0, 0) + w_code = compile(w(source), filename, cmd, 0, 0) w_main = space.wrap('__main__') mainmodule = module.Module(space, w_main) Modified: pypy/dist/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/dist/pypy/interpreter/test/test_interpreter.py Tue Feb 15 01:46:04 2005 @@ -12,7 +12,7 @@ compile = space.builtin.compile w = space.wrap - w_code = compile(source, '', 'exec', 0, 0) + w_code = compile(w(source), '', 'exec', 0, 0) ec = executioncontext.ExecutionContext(space) Modified: pypy/dist/pypy/module/__builtin__interp.py ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/dist/pypy/module/__builtin__interp.py Tue Feb 15 01:46:04 2005 @@ -197,20 +197,12 @@ w_exc = space.call_function(space.w_ImportError, w_failing) raise OperationError(space.w_ImportError, w_exc) -def compile(w_str_, w_filename, w_startstr, - w_supplied_flags=None, w_dont_inherit=None): +def compile(w_str_, filename, startstr, + supplied_flags=0, dont_inherit=0): if space.is_true(space.isinstance(w_str_, space.w_unicode)): - str_ = space.unwrap(w_str_) + str_ = space.unwrap(w_str_) # xxx generic unwrap else: str_ = space.str_w(w_str_) - filename = space.str_w(w_filename) - startstr = space.str_w(w_startstr) - supplied_flags = 0 - if not space.is_w(w_supplied_flags, space.w_None): - supplied_flags = space.int_w(w_supplied_flags) - dont_inherit = 0 - if not space.is_w(w_dont_inherit, space.w_None): - dont_inherit = space.int_w(w_dont_inherit) #print (str_, filename, startstr, supplied_flags, dont_inherit) # XXX we additionally allow GENERATORS because compiling some builtins # requires it. doesn't feel quite right to do that here. @@ -235,7 +227,7 @@ raise OperationError(space.w_TypeError,space.wrap(str(e))) return space.wrap(PyCode(space)._from_code(c)) # -#compile.unwrap_spec = [str,str,str,int,int] +compile.unwrap_spec = [W_Root,str,str,int,int] def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): @@ -243,7 +235,7 @@ if (space.is_true(space.isinstance(w_source, space.w_str)) or space.is_true(space.isinstance(w_source, space.w_unicode))): - w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), space.wrap(""), space.wrap("eval"), space.w_None, space.w_None) + w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), "", "eval") elif isinstance(space.interpclass_w(w_source), PyCode): w_codeobj = w_source else: @@ -274,7 +266,7 @@ return space.w_None def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): - if space.is_true(space.isinstance(w_name, space.w_unicode)): + if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere w_name = space.call_method(w_name, 'encode') try: return space.getattr(w_object, w_name) Modified: pypy/dist/pypy/objspace/std/unicodeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/unicodeobject.py (original) +++ pypy/dist/pypy/objspace/std/unicodeobject.py Tue Feb 15 01:46:04 2005 @@ -29,6 +29,8 @@ space = w_str.space return W_UnicodeObject(space, unicode(space.str_w(w_str))) +def str_w__Unicode(space, w_uni): + return space.str_w(space.call_method(w_uni, 'encode')) def eq__Unicode_ANY(space, w_uni, w_other): try: From pedronis at codespeak.net Tue Feb 15 13:36:00 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 15 Feb 2005 13:36:00 +0100 (MET) Subject: [pypy-svn] r9232 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050215123600.05EF927B4B@code1.codespeak.net> Author: pedronis Date: Tue Feb 15 13:36:00 2005 New Revision: 9232 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: introduce miniglobals in BuiltinFrame subclasses construction Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Tue Feb 15 13:36:00 2005 @@ -159,6 +159,7 @@ def emit__Arguments(self, el, orig_sig, emit_sig): cur = emit_sig.through_scope_w emit_sig.through_scope_w += 2 + emit_sig.miniglobals['Arguments'] = Arguments emit_sig.setfastscope.append( "self.arguments_arg = " "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" @@ -204,6 +205,7 @@ self.setfastscope = [] self.run_args = [] self.through_scope_w = 0 + self.miniglobals = {} def make_frame_class(self): setfastscope = self.setfastscope @@ -217,14 +219,14 @@ # Python 2.2 SyntaxError without newline: Bug #501622 setfastscope += '\n' d = {} - exec setfastscope in globals(),d + exec setfastscope in self.miniglobals, d exec """ def run(self): w_result = self.code.func(%s) if w_result is None: w_result = self.space.w_None return w_result -""" % ','.join(self.run_args) in globals(),d +""" % ','.join(self.run_args) in self.miniglobals, d return type("BuiltinFrame_for_%s" % self.name, (BuiltinFrame,),d) From pedronis at codespeak.net Tue Feb 15 13:57:47 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 15 Feb 2005 13:57:47 +0100 (MET) Subject: [pypy-svn] r9233 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050215125747.A48FC27B55@code1.codespeak.net> Author: pedronis Date: Tue Feb 15 13:57:47 2005 New Revision: 9233 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: attach builtin code function to builtin frame through miniglobals Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Tue Feb 15 13:57:47 2005 @@ -198,6 +198,24 @@ emit_sig.through_scope_w += 1 emit_sig.run_args.append("self.%s_arg%d" % (name,cur)) +class BuiltinFrame(eval.Frame): + "Frame emulation for BuiltinCode." + # Subclasses of this are defined with the function to delegate to attached through miniglobals. + # Initialization of locals is already done by the time run() is called, + # via the interface defined in eval.Frame. + + def setfastscope(self, scope_w): + """Subclasses with behavior specific for an unwrap spec are generated""" + raise TypeError, "abstract" + + def getfastscope(self): + raise OperationError(self.space.w_TypeError, + self.space.wrap("cannot get fastscope of a BuiltinFrame")) + + def run(self): + """Subclasses with behavior specific for an unwrap spec are generated""" + raise TypeError, "abstract" + class BuiltinCodeSignature(Signature): def __init__(self,*args,**kwds): @@ -207,7 +225,7 @@ self.through_scope_w = 0 self.miniglobals = {} - def make_frame_class(self): + def make_frame_class(self, func): setfastscope = self.setfastscope if not setfastscope: setfastscope = ["pass"] @@ -220,28 +238,27 @@ setfastscope += '\n' d = {} exec setfastscope in self.miniglobals, d + + self.miniglobals['func'] = func + exec """ def run(self): - w_result = self.code.func(%s) + w_result = func(%s) if w_result is None: w_result = self.space.w_None return w_result """ % ','.join(self.run_args) in self.miniglobals, d + return type("BuiltinFrame_for_%s" % self.name, (BuiltinFrame,),d) -def make_builtin_frame_class_for_unwrap_spec(orig_sig, unwrap_spec, cache={}): +def make_builtin_frame_class(func, orig_sig, unwrap_spec): "NOT_RPYTHON" - key = tuple(unwrap_spec) - try: - return cache[key] - except KeyError: - name = '_'.join([getattr(k, "__name__", k) for k in key]) - emit_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().emit, + name = (getattr(func, '__module__', None) or '')+'_'+func.__name__ + emit_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().emit, BuiltinCodeSignature(name=name)) - - cache[key] = cls = emit_sig.make_frame_class() - return cls + cls = emit_sig.make_frame_class(func) + return cls @@ -256,7 +273,6 @@ # 'implfunc' is the interpreter-level function. # Note that this uses a lot of (construction-time) introspection. eval.Code.__init__(self, func.__name__) - self.func = func self.docstring = func.__doc__ # signature-based hacks if unwrap_spec is not specified: # renaming arguments from w_xyz to xyz. @@ -339,7 +355,7 @@ else: self.maxargs = self.minargs - self.framecls = make_builtin_frame_class_for_unwrap_spec(orig_sig, unwrap_spec) + self.framecls = make_builtin_frame_class(func, orig_sig, unwrap_spec) def create_frame(self, space, w_globals, closure=None): return self.framecls(space, self, w_globals) @@ -350,26 +366,6 @@ def getdocstring(self): return self.docstring - -class BuiltinFrame(eval.Frame): - "Frame emulation for BuiltinCode." - # This is essentially just a delegation to the 'func' of the BuiltinCode. - # Initialization of locals is already done by the time run() is called, - # via the interface defined in eval.Frame. - - def setfastscope(self, scope_w): - """Subclasses with behavior specific for an unwrap spec are generated""" - raise TypeError, "abstract" - - def getfastscope(self): - raise OperationError(self.space.w_TypeError, - self.space.wrap("cannot get fastscope of a BuiltinFrame")) - - def run(self): - """Subclasses with behavior specific for an unwrap spec are generated""" - raise TypeError, "abstract" - - class Gateway(Wrappable): """General-purpose utility for the interpreter-level to create callables that transparently invoke code objects (and thus possibly interpreted From pedronis at codespeak.net Tue Feb 15 15:37:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 15 Feb 2005 15:37:54 +0100 (MET) Subject: [pypy-svn] r9234 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050215143754.A6F3127B55@code1.codespeak.net> Author: pedronis Date: Tue Feb 15 15:37:54 2005 New Revision: 9234 Modified: pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: coalesce Gateway into interp2app Modified: pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py Tue Feb 15 15:37:54 2005 @@ -20,7 +20,7 @@ gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False) self.w_globals = w_globals - def getglobals(self, space): + def _getglobals(self, space): "NOT_RPYTHON" return self.w_globals Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Tue Feb 15 15:37:54 2005 @@ -2,7 +2,6 @@ Gateway between app-level and interpreter-level: * BuiltinCode (call interp-level code from app-level) -* Gateway (a space-independent gateway to a Code object) * app2interp (embed an app-level function into an interp-level callable) * interp2app (publish an interp-level object to be visible from app-level) * exportall (mass-call interp2app on a whole dict of objects) @@ -366,113 +365,25 @@ def getdocstring(self): return self.docstring -class Gateway(Wrappable): - """General-purpose utility for the interpreter-level to create callables - that transparently invoke code objects (and thus possibly interpreted - app-level code).""" - - # This is similar to a Function object, but not bound to a particular - # object space. During the call, the object space is either given - # explicitly as the first argument (for plain function), or is read - # from 'self.space' for methods. - - # after initialization the following attributes should be set - # name - # _staticglobals - # _staticdefs - # - # getcode is called lazily to get the code object to construct - # the space-bound function - NOT_RPYTHON_ATTRIBUTES = ['_staticglobals', '_staticdefs'] +class interp2app(Wrappable): + """Build a gateway that calls 'f' at interp-level.""" - def getcode(self, space): - # needs to be implemented by subclasses - raise TypeError, "abstract" - - def __spacebind__(self, space): - # to wrap a Gateway, we first make a real Function object out of it - # and the result is a wrapped version of this Function. - return self.get_function(space) - - def get_function(self, space): - return space.loadfromcache(self, - Gateway.build_all_functions, - self.getcache(space)) - - def getglobals(self, space): - "NOT_RPYTHON" - if self._staticglobals is None: - w_globals = None - else: - # is there another Gateway in _staticglobals for which we - # already have a w_globals for this space ? - cache = self.getcache(space) - for value in self._staticglobals.itervalues(): - if isinstance(value, Gateway): - if value in cache.content: - # yes, we share its w_globals - fn = cache.content[value] - w_globals = fn.w_func_globals - break - else: - # no, we build all Gateways in the _staticglobals now. - w_globals = build_dict(self._staticglobals, space) - return w_globals - - def build_all_functions(self, space): - "NOT_RPYTHON" - # the construction is supposed to be done only once in advance, - # but must be done lazily when needed only, because - # 1) it depends on the object space - # 2) the w_globals must not be built before the underlying - # _staticglobals is completely initialized, because - # w_globals must be built only once for all the Gateway - # instances of _staticglobals - return self._build_function(space, self.getglobals(space)) - - def getcache(self, space): - return space._gatewaycache - - def _build_function(self, space, w_globals): - "NOT_RPYTHON" - cache = self.getcache(space) - try: - return cache.content[self] - except KeyError: - defs = self.getdefaults(space) # needs to be implemented by subclass - code = self.getcode(space) - fn = Function(space, code, w_globals, defs, forcename = self.name) - cache.content[self] = fn - return fn - - def get_method(self, obj): - # to get the Gateway as a method out of an instance, we build a - # Function and get it. - # the object space is implicitely fetched out of the instance - space = obj.space - fn = self.get_function(space) - w_obj = space.wrap(obj) - return Method(space, space.wrap(fn), - w_obj, space.type(w_obj)) - - -class interp2app(Gateway): - """Build a Gateway that calls 'f' at interp-level.""" - - # NOTICE even interp2app defaults are stored and passed as + # NOTICE interp2app defaults are stored and passed as # wrapped values, this to avoid having scope_w be of mixed - # wrapped and unwrapped types, - # an exception is made for None which is passed around as default - # as an unwrapped None, unwrapped None and wrapped types are - # compatible + # wrapped and unwrapped types; + # an exception is made for the NoneNotWrapped special value + # which is passed around as default as an unwrapped None, + # unwrapped None and wrapped types are compatible # # Takes optionally an unwrap_spec, see BuiltinCode + + NOT_RPYTHON_ATTRIBUTES = ['_staticdefs'] def __init__(self, f, app_name=None, ismethod=None, spacearg=None, unwrap_spec = None): "NOT_RPYTHON" - Gateway.__init__(self) + Wrappable.__init__(self) # f must be a function whose name does NOT starts with 'app_' if not isinstance(f, types.FunctionType): raise TypeError, "function expected, got %r instead" % f @@ -487,14 +398,8 @@ self.__name__ = f.func_name self.name = app_name self._staticdefs = list(f.func_defaults or ()) - #if self._staticdefs: - # print f.__module__,f.__name__,"HAS NON TRIVIAL DEFLS",self._staticdefs - self._staticglobals = None - - def getcode(self, space): - return self._code - def getdefaults(self, space): + def _getdefaults(self, space): "NOT_RPYTHON" defs_w = [] for val in self._staticdefs: @@ -504,13 +409,52 @@ defs_w.append(space.wrap(val)) return defs_w + def _getglobals(self, space): + return None + + # lazy binding to space + + def __spacebind__(self, space): + # we first make a real Function object out of it + # and the result is a wrapped version of this Function. + return self.get_function(space) + + def get_function(self, space): + return space.loadfromcache(self, + interp2app.build_function, + self.getcache(space)) + + def getcache(self, space): + return space._gatewaycache + def get_method(self, obj): - assert self._code.ismethod, ( - 'global built-in function %r used as method' % - self._code.func) - return Gateway.get_method(self, obj) + # to bind this as a method out of an instance, we build a + # Function and get it. + # the object space is implicitely fetched out of the instance + assert self._code.ismethod, ( + 'global built-in function %r used as method' % + self._code.func) + space = obj.space + fn = self.get_function(space) + w_obj = space.wrap(obj) + return Method(space, space.wrap(fn), + w_obj, space.type(w_obj)) + + def build_function(self, space): + "NOT_RPYTHON" + cache = self.getcache(space) + try: + return cache.content[self] + except KeyError: + defs = self._getdefaults(space) # needs to be implemented by subclass + code = self._code + fn = Function(space, code, self._getglobals(space), defs, forcename = self.name) + cache.content[self] = fn + return fn + + def exportall(d, temporary=False): """NOT_RPYTHON: Publish every function from a dict.""" if temporary: @@ -554,21 +498,6 @@ if isinstance(obj, types.FunctionType): d[name[4:]] = a2i(obj) -def build_dict(d, space): - """NOT_RPYTHON: - Search all Gateways and put them into a wrapped dictionary.""" - w_globals = space.newdict([]) - for value in d.itervalues(): - if isinstance(value, Gateway): - fn = value._build_function(space, w_globals) - w_name = space.wrap(value.name) - w_object = space.wrap(fn) - space.setitem(w_globals, w_name, w_object) - if hasattr(space, 'w_sys'): # give them 'sys' if it exists already - space.setitem(w_globals, space.wrap('sys'), space.w_sys) - return w_globals - - # # the next gateways are to be used only for # temporary/initialization purposes From ac at codespeak.net Tue Feb 15 16:06:34 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 15 Feb 2005 16:06:34 +0100 (MET) Subject: [pypy-svn] r9235 - in pypy/dist/pypy: interpreter module/test objspace Message-ID: <20050215150634.8E89A27B55@code1.codespeak.net> Author: ac Date: Tue Feb 15 16:06:34 2005 New Revision: 9235 Modified: pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/interpreter/executioncontext.py pypy/dist/pypy/module/test/test_builtin.py pypy/dist/pypy/objspace/descroperation.py Log: Implement python 2.3 semantics for comparing cyclic strucures. All of this kludge can go away as soon as we move to tracking python 2.4 behaviour. Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Tue Feb 15 16:06:34 2005 @@ -97,6 +97,11 @@ return cache.getorbuild(key, builder, self) loadfromcache._specialize_ = "location" + + def get_ec_state_dict(self): + "Return the 'state dict' from the active execution context." + return self.getexecutioncontext().get_state_dict() + def getexecutioncontext(self): "Return what we consider to be the active execution context." ec = getthreadlocals().executioncontext Modified: pypy/dist/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/dist/pypy/interpreter/executioncontext.py (original) +++ pypy/dist/pypy/interpreter/executioncontext.py Tue Feb 15 16:06:34 2005 @@ -9,7 +9,8 @@ # Note that self.framestack only contains PyFrames self.space = space self.framestack = Stack() - + self.stateDict = {} + def enter(self, frame): if self.framestack.depth() > self.space.recursion_limit: raise OperationError(self.space.w_RuntimeError, @@ -54,3 +55,9 @@ if frame.last_exception is not None: return frame.last_exception return None + + def get_state_dict(self): + """A mechanism to store arbitrary per ExecutionContext data. + Similar to cpython's PyThreadState_GetDict. + """ + return self.stateDict Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Tue Feb 15 16:06:34 2005 @@ -251,6 +251,18 @@ c2 = C() raises(RuntimeError, cmp, c1, c2) + def test_cmp_cyclic(self): + a = []; a.append(a) + b = []; b.append(b) + from UserList import UserList + c = UserList(); c.append(c) + assert cmp(a, b) == 0 + assert cmp(b, c) == 0 + assert cmp(c, a) == 0 + assert cmp(a, c) == 0 + # okay, now break the cycles + a.pop(); b.pop(); c.pop() + def test_coerce(self): assert coerce(1, 2) == (1, 2) assert coerce(1L, 2L) == (1L, 2L) Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Tue Feb 15 16:06:34 2005 @@ -275,23 +275,64 @@ if w_del is not None: space.get_and_call_function(w_del, w_obj) - def cmp(space, w_x, w_y): - # full compliant implementation of the built-in cmp(). - if space.is_w(w_x, w_y): - return space.wrap(0) # identical objects always compare equal. - if space.is_w(space.type(w_x), space.type(w_y)): - # for object of the same type, prefer __cmp__ over rich comparison. - w_cmp = space.lookup(w_x, '__cmp__') - w_res = _invoke_binop(space, w_cmp, w_x, w_y) - if w_res is not None: - return w_res - # fall back to rich comparison. - if space.eq_w(w_x, w_y): + _NESTING_LIMIT = 20 + + _compare_nesting = 0 + + def cmp(space, w_v, w_w): + # Icky implementation trying to mimic python 2.3 semantics. + + if space.is_w(w_v, w_w): return space.wrap(0) - elif space.is_true(space.lt(w_x, w_y)): - return space.wrap(-1) - else: - return space.wrap(1) + + w_vt = space.type(w_v) + token = None + _inprogress_dict = None + try: + # Try to do some magic to compare cyclic constructs. + space._compare_nesting += 1 + if (space._compare_nesting > space._NESTING_LIMIT and + (space.lookup(w_v, '__getitem__') is not None) and + not (space.is_w(w_vt, space.w_str) or + space.is_w(w_vt, space.w_tuple))): + try: + iv = space.int_w(space.id(w_v)) + iw = space.int_w(space.id(w_w)) + if iv <= iw: + t = (iv, iw, -1) + else: + t = (iw, iv, -1) + _inprogress_dict = space.get_ec_state_dict().setdefault('cmp_state', {}) + if t in _inprogress_dict: + # If we are allready trying to compare the arguments + # presume they are equal + return space.wrap(0) + else: + token = _inprogress_dict[t] = t + except: + return space.wrap(-1) + try: + # The real comparison + if space.is_w(space.type(w_v), space.type(w_w)): + # for object of the same type, prefer __cmp__ over rich comparison. + w_cmp = space.lookup(w_v, '__cmp__') + w_res = _invoke_binop(space, w_cmp, w_v, w_w) + if w_res is not None: + return w_res + # fall back to rich comparison. + if space.eq_w(w_v, w_w): + return space.wrap(0) + elif space.is_true(space.lt(w_v, w_w)): + return space.wrap(-1) + return space.wrap(1) + finally: + if token is not None: + try: + del _inprogress_dict[token] + except: + pass + finally: + space._compare_nesting -= 1 def coerce(space, w_obj1, w_obj2): w_typ1 = space.type(w_obj1) @@ -425,25 +466,60 @@ w_first = w_obj1 w_second = w_obj2 - if space.is_true(space.is_(w_typ1, w_typ2)): - w_right_impl = None - else: - w_right_impl = space.lookup(w_obj2, right) - if space.is_true(space.issubtype(w_typ1, w_typ2)): - w_obj1, w_obj2 = w_obj2, w_obj1 - w_left_impl, w_right_impl = w_right_impl, w_left_impl - - w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2) - if w_res is not None: - return w_res - w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1) - if w_res is not None: - return w_res - # fallback: lt(a, b) <= lt(cmp(a, b), 0) ... - w_res = _cmp(space, w_first, w_second) - res = space.int_w(w_res) - return space.wrap(op(res, 0)) + token = None + _inprogress_dict = None + try: + # Try to do some magic to compare cyclic constructs. + space._compare_nesting += 1 + if (space._compare_nesting > space._NESTING_LIMIT and + (space.lookup(w_obj1, '__getitem__') is not None) and + not (space.is_w(w_typ1, space.w_str) or + space.is_w(w_typ1, space.w_tuple))): + i1 = space.int_w(space.id(w_obj1)) + i2 = space.int_w(space.id(w_obj2)) + if i1 <= i2: + t = (i1, i2, left) + else: + t = (i2, i1, right) + _inprogress_dict = space.get_ec_state_dict().setdefault('cmp_state', {}) + if t in _inprogress_dict: + # If we are allready trying to compare the arguments + # presume they are equal + if symbol == '==': + return space.w_True + elif symbol == '!=': + return space.w_False + else: + raise OperationError(space.w_ValueError, + space.wrap("can't order recursive values")) + else: + token = _inprogress_dict[t] = t + + if space.is_true(space.is_(w_typ1, w_typ2)): + w_right_impl = None + else: + w_right_impl = space.lookup(w_obj2, right) + if space.is_true(space.issubtype(w_typ1, w_typ2)): + w_obj1, w_obj2 = w_obj2, w_obj1 + w_left_impl, w_right_impl = w_right_impl, w_left_impl + w_res = _invoke_binop(space, w_left_impl, w_obj1, w_obj2) + if w_res is not None: + return w_res + w_res = _invoke_binop(space, w_right_impl, w_obj2, w_obj1) + if w_res is not None: + return w_res + # fallback: lt(a, b) <= lt(cmp(a, b), 0) ... + w_res = _cmp(space, w_first, w_second) + res = space.int_w(w_res) + return space.wrap(op(res, 0)) + finally: + if token is not None: + try: + del _inprogress_dict[token] + except: + pass + return func_with_new_name(comparison_impl, 'comparison_%s_impl'%left.strip('_')) From ac at codespeak.net Tue Feb 15 16:16:15 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 15 Feb 2005 16:16:15 +0100 (MET) Subject: [pypy-svn] r9236 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050215151615.2A61B27B55@code1.codespeak.net> Author: ac Date: Tue Feb 15 16:16:14 2005 New Revision: 9236 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: builtin passed regression test. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Tue Feb 15 16:16:14 2005 @@ -28,6 +28,7 @@ 'test_base64.py', 'test_binop.py', 'test_bisect.py', +'test_builtin.py', 'test_call', 'test_codeop.py', 'test_compile.py', From hpk at codespeak.net Tue Feb 15 16:22:11 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Tue, 15 Feb 2005 16:22:11 +0100 (MET) Subject: [pypy-svn] r9237 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050215152211.5493227B55@code1.codespeak.net> Author: hpk Date: Tue Feb 15 16:22:11 2005 New Revision: 9237 Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Log: use py.test's 'raises' again because underlying problems have been fixed (test_builtin.py passes with py.test) Modified: pypy/dist/lib-python-2.3.4/test/pypy_unittest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/pypy_unittest.py (original) +++ pypy/dist/lib-python-2.3.4/test/pypy_unittest.py Tue Feb 15 16:22:11 2005 @@ -40,13 +40,7 @@ assert False, msg def assertRaises(self, exc, call, *args, **kwargs): - # Work around problem with py.test's raises - # raises(exc, call, *args, **kwargs) - try: - call(*args, **kwargs) - except exc: - return - raise AssertionError('DID NOT RAISE') + raises(exc, call, *args, **kwargs) def assertAlmostEqual(self, x, y, places=7, msg=None): if msg is None: From ac at codespeak.net Tue Feb 15 17:14:56 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Tue, 15 Feb 2005 17:14:56 +0100 (MET) Subject: [pypy-svn] r9238 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050215161456.891DE27B52@code1.codespeak.net> Author: ac Date: Tue Feb 15 17:14:56 2005 New Revision: 9238 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: More tests passing. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Tue Feb 15 17:14:56 2005 @@ -31,6 +31,8 @@ 'test_builtin.py', 'test_call', 'test_codeop.py', +'test_commands.py', +'test_compare.py', 'test_compile.py', 'test_heapq.py', 'test_htmllib.py', From mwh at codespeak.net Tue Feb 15 18:44:49 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 15 Feb 2005 18:44:49 +0100 (MET) Subject: [pypy-svn] r9239 - pypy/dist/pypy/annotation Message-ID: <20050215174449.D7BAF27B4F@code1.codespeak.net> Author: mwh Date: Tue Feb 15 18:44:49 2005 New Revision: 9239 Modified: pypy/dist/pypy/annotation/model.py Log: remove some no-longer-used imports Modified: pypy/dist/pypy/annotation/model.py ============================================================================== --- pypy/dist/pypy/annotation/model.py (original) +++ pypy/dist/pypy/annotation/model.py Tue Feb 15 18:44:49 2005 @@ -28,8 +28,7 @@ # -from types import ClassType, BuiltinFunctionType, FunctionType, MethodType -from types import InstanceType +from types import BuiltinFunctionType, MethodType import pypy from pypy.annotation.pairtype import pair, extendabletype from pypy.objspace.flow.model import Constant From mwh at codespeak.net Tue Feb 15 18:45:52 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 15 Feb 2005 18:45:52 +0100 (MET) Subject: [pypy-svn] r9240 - pypy/dist/pypy/translator Message-ID: <20050215174552.266D727B4F@code1.codespeak.net> Author: mwh Date: Tue Feb 15 18:45:51 2005 New Revision: 9240 Modified: pypy/dist/pypy/translator/annrpython.py pypy/dist/pypy/translator/genc.py Log: small fixes to cope with new-style exceptions. Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Tue Feb 15 18:45:51 2005 @@ -313,7 +313,7 @@ self.links_followed[link] = True import types in_except_block = False - if isinstance(link.exitcase, types.ClassType) \ + if isinstance(link.exitcase, (types.ClassType, type)) \ and issubclass(link.exitcase, Exception): last_exception_object = annmodel.SomeObject() last_exc_value_object = annmodel.SomeObject() Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Tue Feb 15 18:45:51 2005 @@ -11,7 +11,7 @@ from pypy.translator.simplify import remove_direct_loops from pypy.interpreter.pycode import CO_VARARGS from pypy.annotation import model as annmodel -from types import FunctionType, CodeType, InstanceType +from types import FunctionType, CodeType, InstanceType, ClassType from pypy.objspace.std.restricted_int import r_int, r_uint @@ -292,7 +292,7 @@ # For the moment, use old-style classes exactly when the # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): - assert type(cls) is type(Exception) + assert type(cls) is ClassType metaclass = "types.ClassType" name = self.uniquename('gcls_' + cls.__name__) From mwh at codespeak.net Tue Feb 15 18:48:48 2005 From: mwh at codespeak.net (mwh at codespeak.net) Date: Tue, 15 Feb 2005 18:48:48 +0100 (MET) Subject: [pypy-svn] r9241 - pypy/dist/pypy/interpreter/test Message-ID: <20050215174848.0CDE327B4F@code1.codespeak.net> Author: mwh Date: Tue Feb 15 18:48:47 2005 New Revision: 9241 Modified: pypy/dist/pypy/interpreter/test/test_py.py Log: run py.py with the interpreter running the tests. Modified: pypy/dist/pypy/interpreter/test/test_py.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_py.py (original) +++ pypy/dist/pypy/interpreter/test/test_py.py Tue Feb 15 18:48:47 2005 @@ -9,28 +9,34 @@ def test_executable(): """Ensures sys.executable points to the py.py script""" # TODO : watch out for spaces/special chars in pypath - output = py.process.cmdexec( '''"%s" -c "import sys;print sys.executable" ''' % pypath ) + output = py.process.cmdexec( '''"%s" "%s" -c "import sys;print sys.executable" ''' % + (sys.executable, pypath) ) assert output.splitlines()[-1] == pypath def test_prefix(): """Make sure py.py sys.prefix and exec_prefix are the same as C Python's""" - output = py.process.cmdexec( '''"%s" -c "import sys;print sys.prefix" ''' % pypath ) + output = py.process.cmdexec( '''"%s" "%s" -c "import sys;print sys.prefix" ''' % + (sys.executable, pypath) ) assert output.splitlines()[-1] == sys.prefix - output = py.process.cmdexec( '''"%s" -c "import sys;print sys.exec_prefix" ''' % pypath ) + output = py.process.cmdexec( '''"%s" "%s" -c "import sys;print sys.exec_prefix" ''' % + (sys.executable, pypath) ) assert output.splitlines()[-1] == sys.exec_prefix def test_argv_command(): """Some tests on argv""" # test 1 : no arguments - output = py.process.cmdexec( '''"%s" -c "import sys;print sys.argv" ''' % pypath ) + output = py.process.cmdexec( '''"%s" "%s" -c "import sys;print sys.argv" ''' % + (sys.executable, pypath) ) assert output.splitlines()[-1] == str(['-c']) # test 2 : some arguments after - output = py.process.cmdexec( '''"%s" -c "import sys;print sys.argv" hello''' % pypath ) + output = py.process.cmdexec( '''"%s" "%s" -c "import sys;print sys.argv" hello''' % + (sys.executable, pypath) ) assert output.splitlines()[-1] == str(['-c','hello']) # test 3 : additionnal pypy parameters - output = py.process.cmdexec( '''"%s" -O -c "import sys;print sys.argv" hello''' % pypath ) + output = py.process.cmdexec( '''"%s" "%s" -O -c "import sys;print sys.argv" hello''' % + (sys.executable, pypath) ) assert output.splitlines()[-1] == str(['-c','hello']) SCRIPT_1 = """ @@ -44,14 +50,17 @@ tmpfile.close() # test 1 : no arguments - output = py.process.cmdexec( '''"%s" "%s" ''' % (pypath,tmpfilepath) ) + output = py.process.cmdexec( '''"%s" "%s" "%s" ''' % + (sys.executable, pypath, tmpfilepath) ) assert output.splitlines()[-1] == str([tmpfilepath]) # test 2 : some arguments after - output = py.process.cmdexec( '''"%s" "%s" hello''' % (pypath,tmpfilepath) ) + output = py.process.cmdexec( '''"%s" "%s" "%s" hello''' % + (sys.executable, pypath, tmpfilepath) ) assert output.splitlines()[-1] == str([tmpfilepath,'hello']) # test 3 : additionnal pypy parameters - output = py.process.cmdexec( '''"%s" -O "%s" hello''' % (pypath,tmpfilepath) ) + output = py.process.cmdexec( '''"%s" "%s" -O "%s" hello''' % + (sys.executable, pypath, tmpfilepath) ) assert output.splitlines()[-1] == str([tmpfilepath,'hello']) From cfbolz at codespeak.net Wed Feb 16 00:11:39 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Wed, 16 Feb 2005 00:11:39 +0100 (MET) Subject: [pypy-svn] r9242 - in pypy/dist/pypy/translator/llvm: . test Message-ID: <20050215231139.2B41F27B55@code1.codespeak.net> Author: cfbolz Date: Wed Feb 16 00:11:38 2005 New Revision: 9242 Added: pypy/dist/pypy/translator/llvm/list.c pypy/dist/pypy/translator/llvm/representation.py Modified: pypy/dist/pypy/translator/llvm/genllvm.py pypy/dist/pypy/translator/llvm/list_template.ll pypy/dist/pypy/translator/llvm/llvmbc.py pypy/dist/pypy/translator/llvm/operations.ll pypy/dist/pypy/translator/llvm/test/llvmsnippet.py pypy/dist/pypy/translator/llvm/test/test_genllvm.py Log: Added rudimentary class support to genllvm (no class attributes, inheritance, ...) and improved lists. Modified: pypy/dist/pypy/translator/llvm/genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/genllvm.py Wed Feb 16 00:11:38 2005 @@ -17,41 +17,44 @@ from pypy.translator.test import snippet as test -INTRINSIC_OPS = ["lt", "le", "eq", "ne", "gt", "ge", "is", "is_true", "len", - "neg", "pos", "invert", "add", "sub", "mul", "truediv", - "floordiv", "div", "mod", "pow", "lshift", "rshift", "and", - "or", "xor", "inplace_add", "inplace_sub", "inplace_mul", - "inplace_truediv", "inplace_floordiv", "inplace_div", - "inplace_mod", "inplace_pow", "inplace_lshift", - "inplace_rshift", "inplace_and", "inplace_or", "inplace_xor", - "getitem", "setitem", "delitem", "contains", "newlist", - "alloc_and_set"] - -C_SIMPLE_TYPES = {annmodel.SomeChar: "char", - annmodel.SomeBool: "unsigned char", - annmodel.SomeInteger: "int"} +from pypy.translator.llvm.representation import * -debug = 0 + +debug = 1 def llvmcompile(transl, optimize=False): gen = LLVMGenerator(transl) return gen.compile(optimize) - -class CompileError(exceptions.Exception): - pass +def get_key(obj): + if isinstance(obj, Constant): + #To avoid getting "bool true" as representation for int 1 + if obj.value is True or obj.value is False: + return obj + return obj.value + if isinstance(obj, annmodel.SomeInstance): + return obj.classdef.cls + return obj class LLVMGenerator(object): def __init__(self, transl): self.translator = transl self.annotator = self.translator.annotator - self.global_count = 0 +## transform.transform_allocate(self.annotator) + self.global_counts = {} + self.local_counts = {} self.repr_classes = [eval(s) for s in dir(sys.modules.get(self.__module__)) if "Repr" in s] self.llvm_reprs = {} - self.l_entrypoint = self.get_repr(self.translator.functions[0]) + self.depth = 0 + try: + self.l_entrypoint = self.get_repr( + Constant(self.translator.functions[0])) + except: +## self.translator.view() + raise def compile(self, optimize=False): from pypy.tool.udir import udir @@ -69,22 +72,42 @@ return getattr(mod, "wrap_%s" % name) def get_global_tmp(self, used_by=None): - self.global_count += 1 - return "%%glb.%s.%i" % ((used_by or "unknown"), self.global_count) + used_by = (used_by or "unknown") + if used_by in self.global_counts: + self.global_counts[used_by] += 1 + return "%%glb.%s.%i" % (used_by, self.global_counts[used_by]) + else: + self.global_counts[used_by] = 0 + return "%%glb.%s" % used_by + + def get_local_tmp(self, l_repr): + self.local_counts[l_repr] += 1 + return "%%tmp_%i" % self.local_counts[l_repr] def get_repr(self, obj): + self.depth += 1 if debug: + print " " * self.depth, print "looking for object", obj, type(obj).__name__, obj.__class__, - if obj in self.llvm_reprs: + print id(obj), get_key(obj), + if isinstance(obj, LLVMRepr): + self.depth -= 1 + return obj + if get_key(obj) in self.llvm_reprs: + self.depth -= 1 if debug: - print "->exists already" - return self.llvm_reprs[obj] + print "->exists already:", self.llvm_reprs[get_key(obj)] + return self.llvm_reprs[get_key(obj)] for cl in self.repr_classes: - if debug: - print "trying", cl g = cl.get(obj, self) if g is not None: - self.llvm_reprs[obj] = g + self.llvm_reprs[get_key(obj)] = g + self.local_counts[g] = 0 + if debug: + print " " * self.depth, + print "calling setup of %s, repr of %s" % (g, obj) + g.setup() + self.depth -= 1 return g raise CompileError, "Can't get repr of %s, %s" % (obj, obj.__class__) @@ -121,404 +144,4 @@ for l_dep1 in traverse_dependencies(l_dep, seen_reprs): yield l_dep1 yield l_repr - -class LLVMRepr(object): - def get(obj, gen): - return None - get = staticmethod(get) - - def get_globals(self): - return "" - - def get_functions(self): - return "" - - def llvmname(self): - return "" - - def llvmtype(self): - return self.type.llvmname() - - def typed_name(self): - return self.llvmtype() + " " + self.llvmname() - - def get_dependencies(self): - try: - return self.dependencies - except exceptions.AttributeError: - return [] - -class SimpleRepr(LLVMRepr): - """Representation of values that are directly mapped to types in LLVM: -int, bool, char (string of length 1)""" - - LLVM_SIMPLE_TYPES = {annmodel.SomeInteger: "int", - annmodel.SomeChar: "sbyte", - annmodel.SomeBool: "bool"} - - def get(obj, gen): - if not isinstance(obj, Constant): - return None - type = gen.annotator.binding(obj) - if type.__class__ in SimpleRepr.LLVM_SIMPLE_TYPES: - llvmtype = SimpleRepr.LLVM_SIMPLE_TYPES[type.__class__] - l_repr = SimpleRepr(llvmtype, repr(obj.value), gen) - return l_repr - return None - get = staticmethod(get) - - def __init__(self, type, llvmname, gen): - if debug: - print "SimpleRepr: %s, %s" % (type, llvmname) - self.type = type - if llvmname in ("False", "True"): - llvmname = llvmname.lower() - self.name = llvmname - self.gen = gen - - def llvmname(self): - return self.name - - def llvmtype(self): - return self.type - - -class VariableRepr(LLVMRepr): - def get(obj, gen): - if isinstance(obj, Variable): - return VariableRepr(obj, gen) - return None - get = staticmethod(get) - - def __init__(self, var, gen): - if debug: - print "VariableRepr: %s" % (var.name) - self.var = var - type = gen.annotator.binding(var) - self.type = gen.get_repr(type) - self.dependencies = [self.type] - - def llvmname(self): - return "%" + self.var.name - - -class StringRepr(LLVMRepr): - def get(obj, gen): - if isinstance(obj, Constant): - type = gen.annotator.binding(obj) - if type.__class__ is annmodel.SomeString: - l_repr = StringRepr(obj, gen) - return l_repr - return None - get = staticmethod(get) - - def __init__(self, obj, gen): - if debug: - print "StringRepr: %s" % obj.value - self.s = obj.value - self.gen = gen - self.glvar1 = gen.get_global_tmp("StringRepr") - self.glvar2 = gen.get_global_tmp("StringRepr") - self.type = gen.get_repr(gen.annotator.binding(obj)) - self.dependencies = [self.type] - - def llvmname(self): - return self.glvar2 - - def get_globals(self): - d = {"len": len(self.s), "gv1": self.glvar1, "gv2": self.glvar2, - "type": self.type.llvmname_wo_pointer(), "string": self.s} - s = """%(gv1)s = internal constant [%(len)i x sbyte] c"%(string)s" -%(gv2)s = internal constant %(type)s {uint %(len)i,\ -sbyte* getelementptr ([%(len)i x sbyte]* %(gv1)s, uint 0, uint 0)}""" - return s % d - -class TypeRepr(LLVMRepr): - l_stringtype = None - def get(obj, gen): -## print "TypeRepr", obj - if obj.__class__ is annmodel.SomeString or obj is str: - if TypeRepr.l_stringtype is None: - l_repr = TypeRepr("%std.string", - "%std.string = type {uint, sbyte*}", - "string.ll", gen) - TypeRepr.l_stringtype = l_repr - return TypeRepr.l_stringtype - get = staticmethod(get) - - def __init__(self, llvmname, definition, includefile, gen): - if debug: - print "TypeRepr: %s, %s" % (llvmname, definition) - self.name = llvmname - self.definition = definition - self.gen = gen - self.includefile = includefile - - def get_globals(self): - try: - return self.definition - except exceptions.AttributeError: - return "" - - def get_functions(self): - if self.includefile != "": - f = file(autopath.this_dir + "/" + self.includefile, "r") - s = f.read() - f.close() - return s - return "" - - def llvmname(self): - return self.name + "*" - - def llvmname_wo_pointer(self): - return self.name - -class ListTypeRepr(TypeRepr): - l_listtypes = {} - def get(obj, gen): - if obj.__class__ is annmodel.SomeList: - if obj.s_item.__class__ in ListTypeRepr.l_listtypes: - return ListTypeRepr.l_listtypes[obj.s_item.__class__] - l_repr = ListTypeRepr(obj, gen) - ListTypeRepr.l_listtypes[obj.s_item.__class__] = l_repr - return l_repr - return None - get = staticmethod(get) - - def __init__(self, obj, gen): - if debug: - print "ListTypeRepr: %s, %s" % (obj, obj.s_item) - self.gen = gen - self.l_itemtype = gen.get_repr(obj.s_item) - self.dependencies = [self.l_itemtype] - itemtype = self.l_itemtype.llvmname() - self.name = "%%std.list.%s" % itemtype.strip("%") - self.definition = self.name + " = type {uint, %s*}" % itemtype - - def get_functions(self): - f = file(autopath.this_dir + "/list_template.ll", "r") - s = f.read() - f.close() - s = s.replace("%(item)s", self.l_itemtype.llvmname().strip("%")) - #XXX assuming every type consists of 4 bytes - s = s.replace("%(sizeof)i", str(4)) - return s - -class SimpleTypeRepr(TypeRepr): - def get(obj, gen): - if obj.__class__ in [annmodel.SomeInteger, int]: - l_repr = SimpleTypeRepr("int", gen) - return l_repr - elif obj.__class__ in [annmodel.SomeBool, bool]: - l_repr = SimpleTypeRepr("bool", gen) - return l_repr - return None - get = staticmethod(get) - - def __init__(self, llvmname, gen): - if debug: - print "SimpleTypeRepr: %s" % llvmname - self.name = llvmname - self.gen = gen - self.definition = "" - self.includefile = "" - - def llvmname(self): - return self.name - -class ImpossibleValueRepr(TypeRepr): - def get(obj, gen): - if obj.__class__ is annmodel.SomeImpossibleValue: - return ImpossibleValueRepr() - return None - get = staticmethod(get) - - def __init__(self): - self.definition = "" - self.dependencies = [] - self.includefile = "" - - def llvmname(self): - return "void" - - def typed_name(self): - return self.llvmtype() + " " + self.llvmname() - -class BuiltinFunctionRepr(LLVMRepr): - def get(obj, gen): - if isinstance(obj, Constant) and \ - type(obj.value).__name__ == 'builtin_function_or_method': - l_repr = BuiltinFunctionRepr(obj.value, gen) - return l_repr - return None - get = staticmethod(get) - - def __init__(self, bi, gen): - self.name = "%std." + bi.__name__ - self.gen = gen - - def llvmname(self): - return self.name - -class FunctionRepr(LLVMRepr): - def get(obj, gen): - if isinstance(obj, Constant) and \ - type(obj.value).__name__ == 'function': - name = obj.value.__name__ - l_repr = FunctionRepr(name, obj.value, gen) - return l_repr - elif type(obj).__name__ == 'function': - name = obj.__name__ - l_repr = FunctionRepr(name, obj, gen) - return l_repr - return None - get = staticmethod(get) - - def __init__(self, name, function, gen): - if debug: - print "FunctionRepr: %s" % name - self.gen = gen - self.func = function - self.translator = gen.translator - self.translator.simplify() - self.name = "%" + name - self.graph = self.translator.getflowgraph(self.func) - self.annotator = gen.translator.annotator - transform.transform_allocate(self.annotator) - self.blocknum = {} - self.allblocks = [] - self.pyrex_source = "" - self.dependencies = sets.Set() - self.get_bbs() - self.build_bbs() - - def get_bbs(self): - def visit(node): - if isinstance(node, Block) and node not in self.blocknum: - self.allblocks.append(node) - self.blocknum[node] = len(self.blocknum) - traverse(visit, self.graph) - self.same_origin_block = [False] * len(self.allblocks) - - def build_bbs(self): - a = self.annotator - for number, pyblock in enumerate(self.allblocks): - lblock = llvmbc.BasicBlock("block%i" % number) - pyblock = self.allblocks[number] - if number == 0: - self.llvm_func = llvmbc.Function(self.llvmfuncdef(), lblock) - else: - self.llvm_func.basic_block(lblock) - #Create Phi nodes (but not for the first node) - incoming_links = [] - def visit(node): - if isinstance(node, Link) and node.target == pyblock: - incoming_links.append(node) - traverse(visit, self.graph) - #special case if the incoming links are from the same block - if len(incoming_links) == 2 and \ - incoming_links[0].prevblock == incoming_links[1].prevblock: - for i, arg in enumerate(pyblock.inputargs): - l_select = self.gen.get_repr( - incoming_links[0].prevblock.exitswitch) - l_arg = self.gen.get_repr(arg) - l_v1 = self.gen.get_repr(incoming_links[1].args[i]) - l_v2 = self.gen.get_repr(incoming_links[0].args[i]) - self.dependencies.update([l_arg, l_switch, l_v1, l_v2]) - lblock.select(l_arg, l_select, l_v1, l_v2) - elif len(incoming_links) != 0: - for i, arg in enumerate(pyblock.inputargs): - l_arg = self.gen.get_repr(arg) - l_values = [self.gen.get_repr(l.args[i]) - for l in incoming_links] - self.dependencies.add(l_arg) - self.dependencies.update(l_values) - lblock.phi(l_arg, l_values, - ["%%block%i" % self.blocknum[l.prevblock] - for l in incoming_links]) - #Create a function call for every operation in the block - for op in pyblock.operations: - if op.opname == "simple_call" and \ - isinstance(op.args[0], Constant) and \ - op.args[0].value == self.func: - l_args = [self] + \ - [self.gen.get_repr(arg) for arg in op.args[1:]] - else: - l_args = [self.gen.get_repr(arg) for arg in op.args] - l_target = self.gen.get_repr(op.result) - self.dependencies.update(l_args) - self.dependencies.add(l_target) - if op.opname in INTRINSIC_OPS: - lblock.spaceop(l_target, op.opname, l_args) - elif op.opname == "simple_call": - lblock.call(l_target, l_args[0], l_args[1:]) - else: - self.translator.view() - raise CompileError, "Unhandeled SpaceOp %s" % op.opname - #Create branches - if pyblock.exitswitch is None: - if pyblock.exits == (): - l_returnvalue = self.gen.get_repr(pyblock.inputargs[0]) - self.dependencies.add(l_returnvalue) - lblock.ret(l_returnvalue) - else: - lblock.uncond_branch( - "%%block%i" % self.blocknum[pyblock.exits[0].target]) - else: - assert isinstance(a.binding(pyblock.exitswitch), - annmodel.SomeBool) - l_switch = self.gen.get_repr(pyblock.exitswitch) - self.dependencies.add(l_switch) - lblock.cond_branch( - l_switch, - "%%block%i" % self.blocknum[pyblock.exits[1].target], - "%%block%i" % self.blocknum[pyblock.exits[0].target]) - - def cfuncdef(self): - a = self.translator.annotator - retv = self.graph.returnblock.inputargs[0] - rettype_c = C_SIMPLE_TYPES[a.binding(retv).__class__] - args = self.graph.startblock.inputargs - argtypes_c = [C_SIMPLE_TYPES[a.binding(v).__class__] for v in args] - fd = "%s %s(%s)" % (rettype_c, self.func.func_name, - ", ".join(argtypes_c)) - return fd - - def llvmfuncdef(self): - a = self.translator.annotator - l_retv = self.gen.get_repr(self.graph.returnblock.inputargs[0]) - l_args = [self.gen.get_repr(ar) - for ar in self.graph.startblock.inputargs] - self.dependencies.update(l_args) - self.dependencies.add(l_retv) - s = "%s %s(" % (l_retv.llvmtype(), self.name) - return s + ", ".join([a.typed_name() for a in l_args]) + ")" - return llvmbc.function(l_retv, self.name, l_args) - - def get_pyrex_source(self): - name = self.func.func_name - args = self.graph.startblock.inputargs - self.pyrex_source = ["cdef extern %s\n" % - (self.cfuncdef())] - self.pyrex_source += ["def wrap_%s(" % name] - t = [] - for i, a in enumerate(args): - t += ["%s" % a] - t = ", ".join(t) - self.pyrex_source += t + "):\n\treturn %s(%s)\n\n" % (name, t) - self.pyrex_source += "\ndef test(a):\n\treturn a + 1\n\n" - self.pyrex_source = "".join(self.pyrex_source) - return self.pyrex_source - - - def get_functions(self): - return str(self.llvm_func) - - def llvmname(self): - return self.name - - def llvmtype(self): - assert self.llvmfuncdef().count(self.name) == 1 - return self.llvmfuncdef().replace(self.name + "(", "(") Added: pypy/dist/pypy/translator/llvm/list.c ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/list.c Wed Feb 16 00:11:38 2005 @@ -0,0 +1,92 @@ +#include + +struct item { + char* dummy; +}; + +struct list { + unsigned int length; + struct item** data; +}; + + +void copy(struct item** from, struct item** to, unsigned int length) { + unsigned int i = 0; + while(i < length) { + to[i] = from[i]; + i += 1; + } +} + +struct list* newlist(struct item* value) { + struct list* nlist = malloc(sizeof(struct list)); + nlist->length = 1; + nlist->data = malloc(sizeof(struct item*)); + nlist->data[0] = value; + return nlist; +} + +struct list* alloc_and_set(unsigned int length, struct item* init) { + unsigned int i = 0; + struct list* nlist = malloc(sizeof(struct list)); + nlist->length = length; + nlist->data = malloc(sizeof(struct item*) * length); + while (i < length) { + nlist->data[i] = init; + i += 1; + } + return nlist; +} + +struct item* getitem(struct list* l, int index) { + if (index < 0) + index = l->length + index; + return l->data[index]; +} + +void setitem(struct list* l, int index, struct item* value) { + if (index < 0) + index = l->length + index; + l->data[index] = value; +} + +struct list* add(struct list* a, struct list* b) { + struct list* nlist = malloc(sizeof(struct list)); + unsigned int newlength = a->length + b->length; + nlist->length = newlength; + nlist->data = malloc(sizeof(struct item*) * newlength); + copy(a->data, nlist->data, a->length); + copy(b->data, nlist->data + a->length, newlength - a->length); + return nlist; +} + +struct list* mul(struct list* a, int times) { + struct list* nlist = malloc(sizeof(struct list)); + unsigned int newlength = a->length * times; + int i = 0; + nlist->length = newlength; + nlist->data = malloc(sizeof(struct item*) * newlength); + while (i < times) { + copy(a->data, nlist->data + i * a->length, a->length); + i += 1; + } + return nlist; +} + +void inplace_add(struct list* a, struct list* b) { + struct item** newdata = malloc(sizeof(struct item*) * (a->length + b->length)); + copy(a->data, newdata, a->length); + copy(b->data, newdata + a->length, b->length); + a->length += b->length; + free(a->data); + a->data = newdata; +} + +struct list* append(struct list* a, struct item* value) { + struct item** newdata = malloc(sizeof(struct item*) * (a->length + 1)); + copy(a->data, newdata, a->length); + a->length += 1; + free(a->data); + a->data = newdata; + return a; +} Modified: pypy/dist/pypy/translator/llvm/list_template.ll ============================================================================== --- pypy/dist/pypy/translator/llvm/list_template.ll (original) +++ pypy/dist/pypy/translator/llvm/list_template.ll Wed Feb 16 00:11:38 2005 @@ -1,57 +1,284 @@ -;Template for lists +internal void %copy(%(item)s* %from, %(item)s* %to, uint %length) { +entry: + %tmp.25 = seteq uint %length, 0 + br bool %tmp.25, label %return, label %no_exit -internal uint %std.len(%std.list.%(item)s* %a) { - %p = getelementptr %std.list.%(item)s* %a, int 0, uint 0 - %length1 = load uint* %p - ret uint %length1 -} - -internal int %std.len(%std.list.%(item)s* %a) { - %length1 = call uint %std.len(%std.list.%(item)s* %a) - %length = cast uint %length1 to int - ret int %length +no_exit: + %i.0.0 = phi uint [ %tmp.14, %no_exit ], [ 0, %entry ] + %tmp.7 = getelementptr %(item)s* %to, uint %i.0.0 + %tmp.11 = getelementptr %(item)s* %from, uint %i.0.0 + %tmp.12 = load %(item)s* %tmp.11 + store %(item)s %tmp.12, %(item)s* %tmp.7 + %tmp.14 = add uint %i.0.0, 1 + %tmp.2 = setlt uint %tmp.14, %length + br bool %tmp.2, label %no_exit, label %return + +return: + ret void +} + +internal %std.list.%(name)s* %std.newlist(%(item)s %value) { +entry: + %tmp.0 = malloc %std.list.%(name)s + %tmp.3 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 0 + store uint 1, uint* %tmp.3 + %tmp.5 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 1 + %tmp.6 = malloc %(item)s + store %(item)s* %tmp.6, %(item)s** %tmp.5 + store %(item)s %value, %(item)s* %tmp.6 + ret %std.list.%(name)s* %tmp.0 +} + +internal %std.list.%(name)s* %std.alloc_and_set(uint %length, %(item)s %init) { +entry: + %tmp.0 = malloc %std.list.%(name)s + %tmp.3 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 0 + store uint %length, uint* %tmp.3 + %tmp.6 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 1 + %tmp.7 = malloc %(item)s, uint %length + store %(item)s* %tmp.7, %(item)s** %tmp.6 + %tmp.134 = seteq uint %length, 0 + br bool %tmp.134, label %loopexit, label %no_exit + +no_exit: + %i.0.0 = phi uint [ %tmp.23, %no_exit ], [ 0, %entry ] + %tmp.17 = load %(item)s** %tmp.6 + %tmp.20 = getelementptr %(item)s* %tmp.17, uint %i.0.0 + store %(item)s %init, %(item)s* %tmp.20 + %tmp.23 = add uint %i.0.0, 1 + %tmp.13 = setlt uint %tmp.23, %length + br bool %tmp.13, label %no_exit, label %loopexit + +loopexit: + ret %std.list.%(name)s* %tmp.0 +} + +internal %std.list.%(name)s* %std.alloc_and_set(int %length, %(item)s %init) { +entry: + %ul = cast int %length to uint + %r = call %std.list.%(name)s* %std.alloc_and_set(uint %ul, %(item)s %init) + ret %std.list.%(name)s* %r } +internal %(item)s %std.getitem(%std.list.%(name)s* %l, int %index.1) { +entry: + %tmp.1 = setlt int %index.1, 0 + %tmp.11 = getelementptr %std.list.%(name)s* %l, int 0, uint 1 + br bool %tmp.1, label %then, label %endif -internal %std.list.%(item)s* %std.make(uint %len, %(item)s* %s) { - %ret = malloc %std.list.%(item)s, uint 1 - %lenp = getelementptr %std.list.%(item)s* %ret, int 0, uint 0 - %lsp = getelementptr %std.list.%(item)s* %ret, int 0, uint 1 - store uint %len, uint* %lenp - store %(item)s* %s, %(item)s** %lsp - ret %std.list.%(item)s* %ret +then: + %tmp.4 = getelementptr %std.list.%(name)s* %l, int 0, uint 0 + %tmp.5 = load uint* %tmp.4 + %tmp.5 = cast uint %tmp.5 to int + %tmp.9 = add int %tmp.5, %index.1 + %tmp.121 = load %(item)s** %tmp.11 + %tmp.142 = getelementptr %(item)s* %tmp.121, int %tmp.9 + %tmp.153 = load %(item)s* %tmp.142 + ret %(item)s %tmp.153 + +endif: + %tmp.12 = load %(item)s** %tmp.11 + %tmp.14 = getelementptr %(item)s* %tmp.12, int %index.1 + %tmp.15 = load %(item)s* %tmp.14 + ret %(item)s %tmp.15 } +internal void %std.setitem(%std.list.%(name)s* %l, int %index.1, %(item)s %value) { +entry: + %tmp.1 = setlt int %index.1, 0 + %tmp.11 = getelementptr %std.list.%(name)s* %l, int 0, uint 1 + br bool %tmp.1, label %then, label %endif + +then: + %tmp.4 = getelementptr %std.list.%(name)s* %l, int 0, uint 0 + %tmp.5 = load uint* %tmp.4 + %tmp.5 = cast uint %tmp.5 to int + %tmp.9 = add int %tmp.5, %index.1 + %tmp.121 = load %(item)s** %tmp.11 + %tmp.142 = getelementptr %(item)s* %tmp.121, int %tmp.9 + store %(item)s %value, %(item)s* %tmp.142 + ret void -internal %std.list.%(item)s* %std.newlist(%(item)s %init) { - %nmem = malloc %(item)s, uint 1 - %ret = call %std.list.%(item)s* %std.make(uint 1, %(item)s* %nmem) - call void %std.setitem(%std.list.%(item)s* %ret, int 0, %(item)s %init) - ret %std.list.%(item)s* %ret -} - -internal %(item)s %std.getitem(%std.list.%(item)s* %s, int %p) { - %sp1 = getelementptr %std.list.%(item)s* %s, int 0, uint 1 - %s1 = load %(item)s** %sp1 - %len = call uint %std.len(%std.list.%(item)s* %s) - %ilen = cast uint %len to int - %negpos = add int %ilen, %p - %is_negative = setlt int %p, 0 - %usedpos = select bool %is_negative, int %negpos, int %p - %p_item = getelementptr %(item)s* %s1, int %usedpos - %value = load %(item)s* %p_item - ret %(item)s %value -} - -internal void %std.setitem(%std.list.%(item)s* %s, int %p, %(item)s %n) { - %sp1 = getelementptr %std.list.%(item)s* %s, int 0, uint 1 - %s1 = load %(item)s** %sp1 - %len = call uint %std.len(%std.list.%(item)s* %s) - %ilen = cast uint %len to int - %negpos = add int %ilen, %p - %is_negative = setlt int %p, 0 - %usedpos = select bool %is_negative, int %negpos, int %p - %itemp = getelementptr %(item)s* %s1, int %usedpos - store %(item)s %n, %(item)s* %itemp +endif: + %tmp.12 = load %(item)s** %tmp.11 + %tmp.14 = getelementptr %(item)s* %tmp.12, int %index.1 + store %(item)s %value, %(item)s* %tmp.14 ret void } + +internal %std.list.%(name)s* %std.add(%std.list.%(name)s* %a, %std.list.%(name)s* %b) { +entry: + %tmp.0 = malloc %std.list.%(name)s + %tmp.3 = getelementptr %std.list.%(name)s* %a, int 0, uint 0 + %tmp.4 = load uint* %tmp.3 + %tmp.6 = getelementptr %std.list.%(name)s* %b, int 0, uint 0 + %tmp.7 = load uint* %tmp.6 + %tmp.8 = add uint %tmp.7, %tmp.4 + %tmp.10 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 0 + store uint %tmp.8, uint* %tmp.10 + %tmp.13 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 1 + %tmp.14 = malloc %(item)s, uint %tmp.8 + store %(item)s* %tmp.14, %(item)s** %tmp.13 + %tmp.19 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 + %tmp.20 = load %(item)s** %tmp.19 + %tmp.2.i14 = seteq uint %tmp.4, 0 + br bool %tmp.2.i14, label %copy.entry, label %no_exit.i + +no_exit.i: + %i.0.i.0 = phi uint [ %tmp.14.i, %no_exit.i ], [ 0, %entry ] + %tmp.7.i = getelementptr %(item)s* %tmp.14, uint %i.0.i.0 + %tmp.11.i = getelementptr %(item)s* %tmp.20, uint %i.0.i.0 + %tmp.12.i = load %(item)s* %tmp.11.i + store %(item)s %tmp.12.i, %(item)s* %tmp.7.i + %tmp.14.i = add uint %i.0.i.0, 1 + %tmp.2.i = setlt uint %tmp.14.i, %tmp.4 + br bool %tmp.2.i, label %no_exit.i, label %copy.entry + +copy.entry: + %tmp.28 = getelementptr %std.list.%(name)s* %b, int 0, uint 1 + %tmp.29 = load %(item)s** %tmp.28 + %tmp.42 = sub uint %tmp.8, %tmp.4 + %tmp.2.i319 = seteq uint %tmp.8, %tmp.4 + br bool %tmp.2.i319, label %copy.entry9, label %no_exit.i4 + +no_exit.i4: + %i.0.i2.0 = phi uint [ %tmp.14.i8, %no_exit.i4 ], [ 0, %copy.entry ] + %tmp.37.sum = add uint %i.0.i2.0, %tmp.4 + %tmp.7.i5 = getelementptr %(item)s* %tmp.14, uint %tmp.37.sum + %tmp.11.i6 = getelementptr %(item)s* %tmp.29, uint %i.0.i2.0 + %tmp.12.i7 = load %(item)s* %tmp.11.i6 + store %(item)s %tmp.12.i7, %(item)s* %tmp.7.i5 + %tmp.14.i8 = add uint %i.0.i2.0, 1 + %tmp.2.i3 = setlt uint %tmp.14.i8, %tmp.42 + br bool %tmp.2.i3, label %no_exit.i4, label %copy.entry9 + +copy.entry9: + ret %std.list.%(name)s* %tmp.0 +} + + + +internal %std.list.%(name)s* %std.mul(%std.list.%(name)s* %a, int %times) { +entry: + %tmp.0 = malloc %std.list.%(name)s + %tmp.3 = getelementptr %std.list.%(name)s* %a, int 0, uint 0 + %tmp.4 = load uint* %tmp.3 + %tmp.6 = cast int %times to uint + %tmp.7 = mul uint %tmp.4, %tmp.6 + %tmp.9 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 0 + store uint %tmp.7, uint* %tmp.9 + %tmp.12 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 1 + %tmp.13 = malloc %(item)s, uint %tmp.7 + store %(item)s* %tmp.13, %(item)s** %tmp.12 + %tmp.194 = setgt int %times, 0 + br bool %tmp.194, label %no_exit.preheader, label %loopexit + +no_exit.preheader: + %tmp.22 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 + br label %no_exit + +no_exit: + %indvar = phi uint [ 0, %no_exit.preheader ], [ %indvar.next10, %copy.entry ] + %i.0.0 = cast uint %indvar to int + %tmp.23 = load %(item)s** %tmp.22 + %tmp.26 = load %(item)s** %tmp.12 + %tmp.29 = load uint* %tmp.3 + %tmp.32 = mul uint %indvar, %tmp.29 + %tmp.2.i9 = seteq uint %tmp.29, 0 + br bool %tmp.2.i9, label %copy.entry, label %no_exit.i + +no_exit.i: + %i.0.i.2 = phi uint [ %tmp.14.i, %no_exit.i ], [ 0, %no_exit ] + %tmp.34.sum = add uint %i.0.i.2, %tmp.32 + %tmp.7.i = getelementptr %(item)s* %tmp.26, uint %tmp.34.sum + %tmp.11.i = getelementptr %(item)s* %tmp.23, uint %i.0.i.2 + %tmp.12.i = load %(item)s* %tmp.11.i + store %(item)s %tmp.12.i, %(item)s* %tmp.7.i + %tmp.14.i = add uint %i.0.i.2, 1 + %tmp.2.i = setlt uint %tmp.14.i, %tmp.29 + br bool %tmp.2.i, label %no_exit.i, label %copy.entry + +copy.entry: + %tmp.39 = add int %i.0.0, 1 + %tmp.19 = setlt int %tmp.39, %times + %indvar.next10 = add uint %indvar, 1 + br bool %tmp.19, label %no_exit, label %loopexit + +loopexit: + ret %std.list.%(name)s* %tmp.0 +} + +internal void %std.inplace_add(%std.list.%(name)s* %a, %std.list.%(name)s* %b) { +entry: + %tmp.2 = getelementptr %std.list.%(name)s* %a, int 0, uint 0 + %tmp.3 = load uint* %tmp.2 + %tmp.5 = getelementptr %std.list.%(name)s* %b, int 0, uint 0 + %tmp.6 = load uint* %tmp.5 + %tmp.7 = add uint %tmp.6, %tmp.3 + %tmp.0 = malloc %(item)s, uint %tmp.7 + %tmp.11 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 + %tmp.12 = load %(item)s** %tmp.11 + %tmp.2.i14 = seteq uint %tmp.3, 0 + br bool %tmp.2.i14, label %copy.entry, label %no_exit.i + +no_exit.i: + %i.0.i.0 = phi uint [ %tmp.14.i, %no_exit.i ], [ 0, %entry ] + %tmp.7.i = getelementptr %(item)s* %tmp.0, uint %i.0.i.0 + %tmp.11.i = getelementptr %(item)s* %tmp.12, uint %i.0.i.0 + %tmp.12.i = load %(item)s* %tmp.11.i + store %(item)s %tmp.12.i, %(item)s* %tmp.7.i + %tmp.14.i = add uint %i.0.i.0, 1 + %tmp.2.i = setlt uint %tmp.14.i, %tmp.3 + br bool %tmp.2.i, label %no_exit.i, label %copy.entry + +copy.entry: + %tmp.18 = getelementptr %std.list.%(name)s* %b, int 0, uint 1 + %tmp.19 = load %(item)s** %tmp.18 + %tmp.2.i319 = seteq uint %tmp.6, 0 + br bool %tmp.2.i319, label %copy.entry9, label %no_exit.i4 + +no_exit.i4: + %i.0.i2.0 = phi uint [ %tmp.14.i8, %no_exit.i4 ], [ 0, %copy.entry ] + %tmp.25.sum = add uint %i.0.i2.0, %tmp.3 + %tmp.7.i5 = getelementptr %(item)s* %tmp.0, uint %tmp.25.sum + %tmp.11.i6 = getelementptr %(item)s* %tmp.19, uint %i.0.i2.0 + %tmp.12.i7 = load %(item)s* %tmp.11.i6 + store %(item)s %tmp.12.i7, %(item)s* %tmp.7.i5 + %tmp.14.i8 = add uint %i.0.i2.0, 1 + %tmp.2.i3 = setlt uint %tmp.14.i8, %tmp.6 + br bool %tmp.2.i3, label %no_exit.i4, label %copy.entry9 + +copy.entry9: + store uint %tmp.7, uint* %tmp.2 + free %(item)s* %tmp.12 + store %(item)s* %tmp.0, %(item)s** %tmp.11 + ret void +} + +internal %std.list.%(name)s* %std.append(%std.list.%(name)s* %a, %(item)s %value) { +entry: + %tmp.2 = getelementptr %std.list.%(name)s* %a, int 0, uint 0 + %tmp.3 = load uint* %tmp.2 + %tmp.3-off = add uint %tmp.3, 1 + %tmp.0 = malloc %(item)s, uint %tmp.3-off + %tmp.8 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 + %tmp.9 = load %(item)s** %tmp.8 + %tmp.2.i5 = seteq uint %tmp.3, 0 + br bool %tmp.2.i5, label %copy.entry, label %no_exit.i + +no_exit.i: + %i.0.i.0 = phi uint [ %tmp.14.i, %no_exit.i ], [ 0, %entry ] + %tmp.7.i = getelementptr %(item)s* %tmp.0, uint %i.0.i.0 + %tmp.11.i = getelementptr %(item)s* %tmp.9, uint %i.0.i.0 + %tmp.12.i = load %(item)s* %tmp.11.i + store %(item)s %tmp.12.i, %(item)s* %tmp.7.i + %tmp.14.i = add uint %i.0.i.0, 1 + %tmp.2.i = setlt uint %tmp.14.i, %tmp.3 + br bool %tmp.2.i, label %no_exit.i, label %copy.entry + +copy.entry: + store uint %tmp.3-off, uint* %tmp.2 + free %(item)s* %tmp.9 + store %(item)s* %tmp.0, %(item)s** %tmp.8 + ret %std.list.%(name)s* %a +} Modified: pypy/dist/pypy/translator/llvm/llvmbc.py ============================================================================== --- pypy/dist/pypy/translator/llvm/llvmbc.py (original) +++ pypy/dist/pypy/translator/llvm/llvmbc.py Wed Feb 16 00:11:38 2005 @@ -41,6 +41,8 @@ def phi(self, l_arg, l_values, blocks): assert len(l_values) == len(blocks) vars_string = [] + print "inserting phi node", l_arg, l_values, blocks + print l_arg.llvmname(), l_arg.llvmtype() fd = "" + "%s = phi %s " % (l_arg.llvmname(), l_arg.llvmtype()) fd += ", ".join(["[%s, %s]" % (v.llvmname(), b) for v, b in zip(l_values, blocks)]) @@ -56,11 +58,20 @@ ", ".join([a.typed_name() for a in l_args]) + ")") def call(self, l_target, l_func, l_args): - s = "%s = call %s %s(" % (l_target.llvmname(), l_target.llvmtype(), + if l_target.llvmtype() == "void": + s = "call void %%std.%s(" % opname + elif l_target.llvmtype() == "%std.void": + s = "call %std.void %%std.%s(" % opname + s = "%s = call %s %s(" % (l_target.llvmname(), l_func.rettype(), l_func.llvmname()) self.instructions.append(s + ", ".join([a.typed_name() for a in l_args]) + ")") + def call_void(self, l_func, l_args): + s = "call %s %s(" % (l_func.rettype(), l_func.llvmname()) + self.instructions.append(s + + ", ".join([a.typed_name() for a in l_args]) + ")") + def ret(self, l_value): self.instructions.append("ret %s" % l_value.typed_name()) @@ -72,6 +83,34 @@ blocktrue, blockfalse) self.instructions.append(s) + def malloc(self, l_target, l_type, num=1): + s = "%s = malloc %s" % (l_target.llvmname(), + l_type.llvmname_wo_pointer()) + if num > 1: + s += ", uint %i" % num + self.instructions.append(s) + + def getelementptr(self, target, l_ptr, adresses): + s = "%s = getelementptr %s %s, " % (target, l_ptr.llvmtype(), + l_ptr.llvmname()) + adr = [] + for a in adresses: + if a >= 0: + adr.append("uint %i" % a) + else: + adr.append("int %i" % a) + self.instructions.append(s + ", ".join(adr)) + + def load(self, l_target, pter): + s = "%s = load %s* %s" % (l_target.llvmname(), l_target.llvmtype(), + pter) + self.instructions.append(s) + + def store(self, l_value, pter): + s = "store %s %s, %s* %s" % (l_value.llvmtype(), l_value.llvmname(), + l_value.llvmtype(), pter) + self.instructions.append(s) + def __str__(self): s = [self.label + ":\n"] Modified: pypy/dist/pypy/translator/llvm/operations.ll ============================================================================== --- pypy/dist/pypy/translator/llvm/operations.ll (original) +++ pypy/dist/pypy/translator/llvm/operations.ll Wed Feb 16 00:11:38 2005 @@ -1,4 +1,6 @@ ;implementation of space operations for simple types + + implementation declare void %llvm.memmove(sbyte*, sbyte*, uint, uint) @@ -6,6 +8,8 @@ declare void %llvm.memset(sbyte*, ubyte, uint, uint) + + ;Basic operations for ints internal int %std.add(int %a, int %b) { %r = add int %a, %b @@ -112,7 +116,7 @@ } ;Logical operations for ints -internal int %std.and(int %a, int %b) { +internal int %std.and_(int %a, int %b) { %r = and int %a, %b ret int %r } Added: pypy/dist/pypy/translator/llvm/representation.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/representation.py Wed Feb 16 00:11:38 2005 @@ -0,0 +1,621 @@ +import autopath +import exceptions, sets, StringIO + +from types import FunctionType + +from pypy.objspace.flow.model import Variable, Constant, SpaceOperation +from pypy.objspace.flow.model import FunctionGraph, Block, Link +from pypy.objspace.flow.model import last_exception, last_exc_value +from pypy.objspace.flow.model import traverse, uniqueitems, checkgraph +from pypy.annotation import model as annmodel +from pypy.annotation.classdef import ClassDef +from pypy.translator import transform +from pypy.translator.llvm import llvmbc + + +INTRINSIC_OPS = ["lt", "le", "eq", "ne", "gt", "ge", "is", "is_true", "len", + "neg", "pos", "invert", "add", "sub", "mul", "truediv", + "floordiv", "div", "mod", "pow", "lshift", "rshift", "and_", + "or", "xor", "inplace_add", "inplace_sub", "inplace_mul", + "inplace_truediv", "inplace_floordiv", "inplace_div", + "inplace_mod", "inplace_pow", "inplace_lshift", + "inplace_rshift", "inplace_and", "inplace_or", "inplace_xor", + "contains", "newlist", "alloc_and_set"] + +C_SIMPLE_TYPES = {annmodel.SomeChar: "char", + annmodel.SomeBool: "unsigned char", + annmodel.SomeInteger: "int"} + + +debug = 1 + + +class CompileError(exceptions.Exception): + pass + + +class LLVMRepr(object): + def get(obj, gen): + return None + get = staticmethod(get) + + def __init__(self, obj, gen): + pass + + def setup(self): + pass + + def get_globals(self): + return "" + + def get_functions(self): + return "" + + def llvmname(self): + return "" + + def llvmtype(self): + return self.type.llvmname() + + def typed_name(self): + return self.llvmtype() + " " + self.llvmname() + + def get_dependencies(self): + try: + return self.dependencies + except exceptions.AttributeError: + return [] + + +class SimpleRepr(LLVMRepr): + """Representation of values that are directly mapped to types in LLVM: +int, bool, char (string of length 1)""" + + LLVM_SIMPLE_TYPES = {annmodel.SomeInteger: "int", + annmodel.SomeChar: "sbyte", + annmodel.SomeBool: "bool"} + def get(obj, gen): + if not isinstance(obj, Constant): + return None + type = gen.annotator.binding(obj) + if type.__class__ in SimpleRepr.LLVM_SIMPLE_TYPES: + llvmtype = SimpleRepr.LLVM_SIMPLE_TYPES[type.__class__] + l_repr = SimpleRepr(llvmtype, repr(obj.value), gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, type, llvmname, gen): + if debug: + print "SimpleRepr: %s, %s" % (type, llvmname) + self.type = type + if llvmname in ("False", "True"): + llvmname = llvmname.lower() + self.name = llvmname + self.gen = gen + self.dependencies = sets.Set() + + def llvmname(self): + return self.name + + def llvmtype(self): + return self.type + + def __getattr__(self, name): + return getattr(self.type, name, None) + + +class VariableRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Variable): + return VariableRepr(obj, gen) + return None + get = staticmethod(get) + + def __init__(self, var, gen): + if debug: + print "VariableRepr: %s" % (var.name) + self.var = var + type = gen.annotator.binding(var) + self.type = gen.get_repr(type) + self.dependencies = sets.Set([self.type]) + + def llvmname(self): + return "%" + self.var.name + + def __getattr__(self, name): + if name.startswith("op_"): + return getattr(self.type, "t_" + name, None) + else: + raise AttributeError, ("VariableRepr instance has no attribute %s" + % repr(name)) + +class StringRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Constant): + type = gen.annotator.binding(obj) + if type.__class__ is annmodel.SomeString: + l_repr = StringRepr(obj, gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, obj, gen): + if debug: + print "StringRepr: %s" % obj.value + self.s = obj.value + self.gen = gen + self.glvar1 = gen.get_global_tmp("StringRepr") + self.glvar2 = gen.get_global_tmp("StringRepr") + self.type = gen.get_repr(gen.annotator.binding(obj)) + self.dependencies = sets.Set([self.type]) + + def llvmname(self): + return self.glvar2 + + def get_globals(self): + d = {"len": len(self.s), "gv1": self.glvar1, "gv2": self.glvar2, + "type": self.type.llvmname_wo_pointer(), "string": self.s} + s = """%(gv1)s = internal constant [%(len)i x sbyte] c"%(string)s" +%(gv2)s = internal constant %(type)s {uint %(len)i,\ +sbyte* getelementptr ([%(len)i x sbyte]* %(gv1)s, uint 0, uint 0)}""" + return s % d + +class TypeRepr(LLVMRepr): + l_stringtype = None + def get(obj, gen): +## print "TypeRepr", obj + if obj.__class__ is annmodel.SomeString or obj is str: + if TypeRepr.l_stringtype is None: + l_repr = TypeRepr("%std.string", + "%std.string = type {uint, sbyte*}", + "string.ll", gen) + TypeRepr.l_stringtype = l_repr + return TypeRepr.l_stringtype + if (isinstance(obj, annmodel.SomePBC) and \ + obj.prebuiltinstances.keys()[0] is None) or obj is type(None): + return TypeRepr("%std.void", "%std.void = type sbyte", "", gen) + get = staticmethod(get) + + def __init__(self, llvmname, definition, includefile, gen): + if debug: + print "TypeRepr: %s, %s" % (llvmname, definition) + self.name = llvmname + self.definition = definition + self.gen = gen + self.includefile = includefile + + def get_globals(self): + try: + return self.definition + except exceptions.AttributeError: + return "" + + def get_functions(self): + try: + if self.includefile != "": + f = file(autopath.this_dir + "/" + self.includefile, "r") + s = f.read() + f.close() + return s + except exceptions.AttributeError: + pass + return "" + + def llvmname(self): + return self.name + "*" + + def llvmname_wo_pointer(self): + return self.name + +class ListTypeRepr(TypeRepr): + l_listtypes = {} + def get(obj, gen): + if obj.__class__ is annmodel.SomeList: + if (obj.s_item.__class__, gen) in ListTypeRepr.l_listtypes: + return ListTypeRepr.l_listtypes[(obj.s_item.__class__, gen)] + l_repr = ListTypeRepr(obj, gen) + ListTypeRepr.l_listtypes[(obj.s_item.__class__, gen)] = l_repr + return l_repr + return None + get = staticmethod(get) + + def __init__(self, obj, gen): + if debug: + print "ListTypeRepr: %s, %s" % (obj, obj.s_item) + self.gen = gen + self.l_itemtype = gen.get_repr(obj.s_item) + self.dependencies = sets.Set([self.l_itemtype]) + itemtype = self.l_itemtype.llvmname() + self.name = "%%std.list.%s" % itemtype.strip("%").replace("*", "") + self.definition = self.name + " = type {uint, %s*}" % itemtype + + def get_functions(self): + f = file(autopath.this_dir + "/list_template.ll", "r") + s = f.read() + f.close() + itemtype = self.l_itemtype.llvmname() + s = s.replace("%(item)s", self.l_itemtype.llvmname()) + s = s.replace("%(name)s", itemtype.strip("%").replace("*", "")) + return s + + def t_op_getitem(self, l_target, args, lblock, l_func): + l_args = [self.gen.get_repr(arg) for arg in args] + l_func.dependencies.update(l_args) + lblock.spaceop(l_target, "getitem", l_args) + + def t_op_setitem(self, l_target, args, lblock, l_func): + l_args = [self.gen.get_repr(arg) for arg in args] + l_func.dependencies.update(l_args) + lblock.spaceop(l_target, "setitem", l_args) + + def t_op_delitem(self, l_target, args, lblock, l_func): + l_args = [self.gen.get_repr(arg) for arg in args] + l_func.dependencies.update(l_args) + lblock.spaceop(l_target, "delitem", l_args) + + +class SimpleTypeRepr(TypeRepr): + def get(obj, gen): + if obj.__class__ in [annmodel.SomeInteger, int]: + l_repr = SimpleTypeRepr("int", gen) + return l_repr + elif obj.__class__ in [annmodel.SomeBool, bool]: + l_repr = SimpleTypeRepr("bool", gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, llvmname, gen): + if debug: + print "SimpleTypeRepr: %s" % llvmname + self.name = llvmname + self.gen = gen + self.definition = "" + self.includefile = "" + + def llvmname(self): + return self.name + +class ImpossibleValueRepr(TypeRepr): + def get(obj, gen): + if obj.__class__ is annmodel.SomeImpossibleValue: + return ImpossibleValueRepr() + return None + get = staticmethod(get) + + def __init__(self): + self.definition = "" + self.dependencies = sets.Set() + self.includefile = "" + + def llvmname(self): + return "void" + +class NoneRepr(TypeRepr): + def get(obj, gen): + if isinstance(obj, Constant) and obj.value is None: + return NoneRepr(gen) + get = staticmethod(get) + + def __init__(self, gen): + self.gen = gen + self.type = gen.get_repr(type(None)) + self.dependencies = sets.Set([self.type]) + if debug: + print "NoneRepr, llvmname: %s, llvmtype: %s" % (self.llvmname(), + self.llvmtype()) + + def llvmname(self): + return "null" + + +class ClassRepr(TypeRepr): + def get(obj, gen): + if obj.__class__ is Constant: + bind = gen.annotator.binding(obj) + if bind.__class__ is annmodel.SomePBC and \ + bind.const.__class__ == type: + classdef = gen.annotator.bookkeeper.userclasses[bind.const] + return ClassRepr(classdef, gen) + if isinstance(obj, annmodel.SomeInstance): + return ClassRepr(obj.classdef, gen) + return None + get = staticmethod(get) + + def __init__(self, obj, gen): + if 1: + print "ClassRepr: %s", obj + self.classdef = obj + self.gen = gen + self.includefile = "" + self.name = gen.get_global_tmp("class.%s" % self.classdef.cls.__name__) + self.dependencies = sets.Set() + self.attr_num = {} + self.se = False + + def setup(self): + self.se = True + print "ClassRepr.setup()", id(self) + gen = self.gen + attribs = [] + meth = [] + print "attributes" + for key, attr in self.classdef.attrs.iteritems(): + print key, attr, attr.sources, attr.s_value, + if len(attr.sources) != 0: + func = self.classdef.cls.__dict__[attr.name] + meth.append((key, func)) + print "--> method" + continue + if isinstance(attr.s_value, annmodel.SomePBC) and \ + attr.s_value.knowntype is FunctionType: + func = self.classdef.cls.__dict__[attr.name] + meth.append((key, func)) + print "--> method" + continue + attribs.append(attr) + print "--> value" + self.l_attrs_types = [gen.get_repr(attr.s_value) for attr in attribs] + self.dependencies = sets.Set(self.l_attrs_types) + attributes = ", ".join([at.llvmname() for at in self.l_attrs_types]) + self.definition = "%s = type {int*, %s}" % (self.name, attributes) + self.attr_num = {} + for i, attr in enumerate(attribs): + self.attr_num[attr.name] = i + 1 + self.methods = dict(meth) + print "setup: ", self, self.attr_num, self.methods + + def op_simple_call(self, l_target, args, lblock, l_func): + l_init = self.gen.get_repr(self.methods["__init__"]) + l_func.dependencies.add(l_init) + l_args = [self.gen.get_repr(arg) for arg in args[1:]] + self.dependencies.update(l_args) + lblock.malloc(l_target, self) + lblock.call_void(l_init, [l_target] + l_args) + + def t_op_getattr(self, l_target, args, lblock, l_func): + print "t_op_getattrs", l_target, args + if not isinstance(args[1], Constant): + raise CompileError,"getattr called with non-constant: %s" % args[1] + if args[1].value in self.attr_num: + l_args0 = self.gen.get_repr(args[0]) + l_func.dependencies.add(l_args0) + pter = self.gen.get_local_tmp(l_func) + lblock.getelementptr(pter, l_args0, + [0, self.attr_num[args[1].value]]) + lblock.load(l_target, pter) + elif args[1].value in self.methods: + print "method", + l_args0 = self.gen.get_repr(args[0]) + print l_args0, l_args0.typed_name() + l_func.dependencies.add(l_args0) + l_method = BoundMethodRepr(self.methods[args[1].value], + l_args0, self, self.gen) + l_target.type = l_method + + def t_op_setattr(self, l_target, args, lblock, l_func): + if not isinstance(args[1], Constant): + raise CompileError,"setattr called with non-constant: %s" % args[1] + if args[1].value in self.attr_num: + l_args0 = self.gen.get_repr(args[0]) + l_value = self.gen.get_repr(args[2]) + self.dependencies.update([l_args0, l_value]) + pter = self.gen.get_local_tmp(l_func) + lblock.getelementptr(pter, l_args0, + [0, self.attr_num[args[1].value]]) + lblock.store(l_value, pter) + + +class BuiltinFunctionRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Constant) and \ + type(obj.value).__name__ == 'builtin_function_or_method': + l_repr = BuiltinFunctionRepr(obj.value, gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, bi, gen): + self.name = "%std." + bi.__name__ + self.gen = gen + + def llvmname(self): + return self.name + +class FunctionRepr(LLVMRepr): + def get(obj, gen): + if isinstance(obj, Constant) and \ + type(obj.value).__name__ == 'function': + name = obj.value.__name__ + l_repr = FunctionRepr(name, obj.value, gen) + return l_repr + elif isinstance(obj, annmodel.SomePBC): + obj = obj.prebuiltinstances.keys()[0] + if type(obj).__name__ == 'function': + name = obj.__name__ + l_repr = FunctionRepr(name, obj, gen) + return l_repr + return None + get = staticmethod(get) + + def __init__(self, name, function, gen): + if debug: + print "FunctionRepr: %s" % name + self.gen = gen + self.func = function + self.translator = gen.translator + self.name = "%" + name + self.graph = self.translator.getflowgraph(self.func) + self.annotator = gen.translator.annotator + self.blocknum = {} + self.allblocks = [] + self.pyrex_source = "" + self.dependencies = sets.Set() + self.get_bbs() + + def setup(self): + self.retvalue = self.gen.get_repr(self.graph.returnblock.inputargs[0]) + self.dependencies.add(self.retvalue) + self.build_bbs() + + def get_returntype(): + return self.rettype.llvmname() + + def get_bbs(self): + def visit(node): + if isinstance(node, Block) and node not in self.blocknum: + self.allblocks.append(node) + self.blocknum[node] = len(self.blocknum) + traverse(visit, self.graph) + self.same_origin_block = [False] * len(self.allblocks) + + def build_bbs(self): + a = self.annotator + for number, pyblock in enumerate(self.allblocks): + lblock = llvmbc.BasicBlock("block%i" % number) + pyblock = self.allblocks[number] + if number == 0: + self.llvm_func = llvmbc.Function(self.llvmfuncdef(), lblock) + else: + self.llvm_func.basic_block(lblock) + #Create Phi nodes (but not for the first node) + incoming_links = [] + def visit(node): + if isinstance(node, Link) and node.target == pyblock: + incoming_links.append(node) + traverse(visit, self.graph) + #special case if the incoming links are from the same block + if len(incoming_links) == 2 and \ + incoming_links[0].prevblock == incoming_links[1].prevblock: + for i, arg in enumerate(pyblock.inputargs): + l_select = self.gen.get_repr( + incoming_links[0].prevblock.exitswitch) + l_arg = self.gen.get_repr(arg) + l_v1 = self.gen.get_repr(incoming_links[1].args[i]) + l_v2 = self.gen.get_repr(incoming_links[0].args[i]) + self.dependencies.update([l_arg, l_switch, l_v1, l_v2]) + lblock.select(l_arg, l_select, l_v1, l_v2) + elif len(incoming_links) != 0: + for i, arg in enumerate(pyblock.inputargs): + l_arg = self.gen.get_repr(arg) + l_values = [self.gen.get_repr(l.args[i]) + for l in incoming_links] + self.dependencies.add(l_arg) + self.dependencies.update(l_values) + lblock.phi(l_arg, l_values, + ["%%block%i" % self.blocknum[l.prevblock] + for l in incoming_links]) + #Create a function call for every operation in the block + for op in pyblock.operations: + l_target = self.gen.get_repr(op.result) + self.dependencies.add(l_target) + if op.opname in INTRINSIC_OPS: + l_args = [self.gen.get_repr(arg) for arg in op.args] + self.dependencies.update(l_args) + lblock.spaceop(l_target, op.opname, l_args) + else: + l_arg0 = self.gen.get_repr(op.args[0]) + self.dependencies.add(l_arg0) + l_op = getattr(l_arg0, "op_" + op.opname, None) + if l_op is None: + s = "SpaceOperation %s not supported. Target: %s " \ + "Args: %s" % (op.opname, l_target, op.args) + raise CompileError, s + l_op(l_target, op.args, lblock, self) + #Create branches + if pyblock.exitswitch is None: + if pyblock.exits == (): + l_returnvalue = self.gen.get_repr(pyblock.inputargs[0]) + self.dependencies.add(l_returnvalue) + lblock.ret(l_returnvalue) + else: + lblock.uncond_branch( + "%%block%i" % self.blocknum[pyblock.exits[0].target]) + else: + assert isinstance(a.binding(pyblock.exitswitch), + annmodel.SomeBool) + l_switch = self.gen.get_repr(pyblock.exitswitch) + self.dependencies.add(l_switch) + lblock.cond_branch( + l_switch, + "%%block%i" % self.blocknum[pyblock.exits[1].target], + "%%block%i" % self.blocknum[pyblock.exits[0].target]) + + def cfuncdef(self): + a = self.translator.annotator + retv = self.graph.returnblock.inputargs[0] + rettype_c = C_SIMPLE_TYPES[a.binding(retv).__class__] + args = self.graph.startblock.inputargs + argtypes_c = [C_SIMPLE_TYPES[a.binding(v).__class__] for v in args] + fd = "%s %s(%s)" % (rettype_c, self.func.func_name, + ", ".join(argtypes_c)) + return fd + + def llvmfuncdef(self): + a = self.translator.annotator + l_args = [self.gen.get_repr(ar) + for ar in self.graph.startblock.inputargs] + self.dependencies.update(l_args) + s = "%s %s(" % (self.retvalue.llvmtype(), self.name) + return s + ", ".join([a.typed_name() for a in l_args]) + ")" + + def get_pyrex_source(self): + name = self.func.func_name + args = self.graph.startblock.inputargs + self.pyrex_source = ["cdef extern %s\n" % + (self.cfuncdef())] + self.pyrex_source += ["def wrap_%s(" % name] + t = [] + for i, a in enumerate(args): + t += ["%s" % a] + t = ", ".join(t) + self.pyrex_source += t + "):\n\treturn %s(%s)\n\n" % (name, t) + self.pyrex_source += "\ndef test(a):\n\treturn a + 1\n\n" + self.pyrex_source = "".join(self.pyrex_source) + return self.pyrex_source + + def rettype(self): + return self.retvalue.llvmtype() + + def get_functions(self): + return str(self.llvm_func) + + def llvmname(self): + return self.name + + def llvmtype(self): + assert self.llvmfuncdef().count(self.name) == 1 + return self.llvmfuncdef().replace(self.name + "(", "(") + "*" + + def op_simple_call(self, l_target, args, lblock, l_func): + l_args = [self.gen.get_repr(arg) for arg in args] + self.dependencies.update(l_args) + lblock.call(l_target, l_args[0], l_args[1:]) + +class BoundMethodRepr(LLVMRepr): + def get(obj, gen): + return None + get = staticmethod(get) + + def __init__(self, func, l_self, l_class, gen): + self.gen = gen + self.func = func + self.l_self = l_self + self.l_class = l_class + self.dependencies = sets.Set([l_self, l_class]) + self.se = False + + def setup(self): + print "setup BoundMethodRepr" + self.se = True + self.l_func = self.gen.get_repr(self.func) + self.dependencies.add(self.l_func) + + + def t_op_simple_call(self, l_target, args, lblock, l_func): + if not self.se: + self.setup() + self.l_func.op_simple_call(l_target, + [self.l_func, self.l_self] + args[1:], + lblock, l_func) Modified: pypy/dist/pypy/translator/llvm/test/llvmsnippet.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/llvmsnippet.py (original) +++ pypy/dist/pypy/translator/llvm/test/llvmsnippet.py Wed Feb 16 00:11:38 2005 @@ -1,5 +1,6 @@ import autopath +#function snippets def simple1(): return 1 @@ -31,17 +32,117 @@ return ackermann(n - 1, 1) return ackermann(n - 1, ackermann(n, m - 1)) +def calling1(m): + if m > 1: + return calling2(m - 1) + return m + +def calling2(m): + if m > 1: + return calling1(m - 1) + return m -def arraytestsimple(): +#array snippets + +def array_simple(): a = [42] return a[0] -def arraytestsimple1(): - a = [43] - return a[-1] - -def arraytestsetitem(i): - a = [43] - a[0] = i * 2 - return a[-1] - +def array_simple1(item): + a = [item] * 10 + i = 0 + v = 0 + while i < 10: + v += a[i] + i += 1 + return v + +def array_setitem(i): + a = [1] * 10 + a[i] = i + a[1] = 12 + a[2] = 13 + return a[i] + +def array_add(a0, a1, b0, b1, i): + a = [0] * 2 + b = [0] * 2 + a[0] = a0 + a[1] = a1 + b[0] = b0 + b[1] = b1 + return (a + b)[i] + +def double_array(): + a = [15] + b = [a] + return b[0][0] + +def double_array_set(): + a = [15] * 3 + b = [a] * 3 + b[0][0] = 1 + return b[1][0] + +def bool_array(): + a = [False] * 100 + a[12] = True + return a[12] + +def callee(array): + return array[0] + +def array_arg(i): + a = [i - 5] * 12 + return callee(a) + +#class snippets + +class A(object): + def __init__(self): + self.a = 14 + self.b = False + +def class_simple(): + a = A() + return a.a + +class B(object): + def __init__(self): + self.a = 14 + self.b = False + + def change(self, newa): + self.a = newa * 5 + +def class_simple1(newa): + b = B() + b.change(newa) + return b.a + +class C(object): + def __init__(self, a): + self.a = a + self.b = 1 + +def class_simple2(newa): + b = B() + b.change(newa) + c = C(b) + return c.a.a + +class D(object): + def __init__(self, a, length): + self.a = [a] * length + self.length = length + + def set_range(self): + i = 0 + while i < self.length: + self.a[i] = i + i += 1 + +def id_int(i): + d = D(1, i + 1) + d.set_range() + return d.a[i] Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/test_genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Wed Feb 16 00:11:38 2005 @@ -16,6 +16,7 @@ def compile_function(function, annotate): t = Translator(function) a = t.annotate(annotate) + t.simplify() gen = LLVMGenerator(t) return gen.compile() @@ -28,6 +29,10 @@ return True class TestLLVMRepr(object): + def setup_method(self,method): + if not llvm_found: + py.test.skip("llvm-as not found on path") + def DONOT_test_simple1(self): t = Translator(llvmsnippet.simple1) a = t.annotate([]) @@ -64,7 +69,7 @@ l_repr = gen.get_repr(str) assert l_repr.llvmname() == "%std.string*" - def test_stringrepr(self): + def DONOT_test_stringrepr(self): t = Translator(llvmsnippet.simple3) a = t.annotate([]) gen = LLVMGenerator(t) @@ -107,22 +112,72 @@ assert f(2, i) == 2 * i + 3 assert f(3, i) == 2 ** (i + 3) - 3 + def test_calling(self): + f = compile_function(llvmsnippet.calling1, [int]) + assert f(10) == 1 + class TestLLVMArray(object): def setup_method(self, method): if not llvm_found: py.test.skip("llvm-as not found on path.") - def test_simplearray(self): - f = compile_function(llvmsnippet.arraytestsimple, []) + def test_array(self): + f = compile_function(llvmsnippet.array_simple, []) assert f() == 42 - def test_simplearray1(self): - f = compile_function(llvmsnippet.arraytestsimple1, []) - assert f() == 43 - - def test_simplearray_setitem(self): - f = compile_function(llvmsnippet.arraytestsetitem, [int]) - assert f(32) == 64 + def test_array1(self): + f = compile_function(llvmsnippet.array_simple1, [int]) + assert f(1) == 10 + assert f(-42) == -420 + + def test_array_setitem(self): + f = compile_function(llvmsnippet.array_setitem, [int]) + print f(1), f(2), f(3) + assert f(1) == 12 + assert f(2) == 13 + assert f(3) == 3 + + def test_array_add(self): + f = compile_function(llvmsnippet.array_add, [int, int, int, int, int]) + assert f(1,2,3,4,0) == 1 + assert f(1,2,3,4,1) == 2 + assert f(1,2,3,4,2) == 3 + assert f(1,2,5,6,3) == 6 + + def test_array_double(self): + f = compile_function(llvmsnippet.double_array, []) + assert f() == 15 + + def test_bool_array(self): + f = compile_function(llvmsnippet.bool_array, []) + assert f() == 1 + + def test_array_arg(self): + f = compile_function(llvmsnippet.array_arg, [int]) + assert f(5) == 0 + + +class TestClass(object): + def setup_method(self, method): + if not llvm_found: + py.test.skip("llvm-as not found on path.") + + def test_classsimple(self): + f = compile_function(llvmsnippet.class_simple, []) + assert f() == 14 + + def test_classsimple1(self): + f = compile_function(llvmsnippet.class_simple1, [int]) + assert f(2) == 10 + + def test_classsimple2(self): + f = compile_function(llvmsnippet.class_simple2, [int]) + assert f(2) == 10 + + def test_id_int(self): + f = compile_function(llvmsnippet.id_int, [int]) + for i in range(1, 20): + assert f(i) == i class TestSnippet(object): def setup_method(self, method): @@ -155,6 +210,13 @@ while_func = compile_function(test.while_func, [int]) assert while_func(10) == 55 + def test_time_waster(self): + f = compile_function(test.time_waster, [int]) + assert f(1) == 1 + assert f(2) == 2 + assert f(3) == 6 + assert f(4) == 12 + def test_factorial2(self): factorial2 = compile_function(test.factorial2, [int]) assert factorial2(5) == 120 @@ -162,3 +224,14 @@ def test_factorial(self): factorial = compile_function(test.factorial, [int]) assert factorial(5) == 120 + + def test_two_plus_two(self): + f = compile_function(test.two_plus_two, []) + assert f() == 4 + + def test_sieve_of_eratosthenes(self): + f = compile_function(test.sieve_of_eratosthenes, []) + assert f() == 1028 + + + From arigo at codespeak.net Wed Feb 16 11:26:26 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 16 Feb 2005 11:26:26 +0100 (MET) Subject: [pypy-svn] r9243 - pypy/dist/pypy/module Message-ID: <20050216102626.C61AE27B52@code1.codespeak.net> Author: arigo Date: Wed Feb 16 11:26:26 2005 New Revision: 9243 Modified: pypy/dist/pypy/module/sysinterp.py Log: Use os.pardir instead of '..'. Modified: pypy/dist/pypy/module/sysinterp.py ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/dist/pypy/module/sysinterp.py Wed Feb 16 11:26:26 2005 @@ -62,7 +62,7 @@ from pypy.interpreter import autopath srcdir = os.path.dirname(autopath.pypydir) python_std_lib = os.path.normpath( - os.path.join(autopath.pypydir, '..','lib-python-2.3.4')) + os.path.join(autopath.pypydir, os.pardir,'lib-python-2.3.4')) pypy_override_lib = os.path.join(autopath.pypydir, 'lib') assert os.path.exists(python_std_lib) del os, autopath # XXX for the translator. Something is very wrong around here. From hpk at codespeak.net Wed Feb 16 13:57:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 13:57:50 +0100 (MET) Subject: [pypy-svn] r9244 - in pypy/branch/dist-interpapp/pypy/interpreter: . test test/mixedmodule Message-ID: <20050216125750.A301627B41@code1.codespeak.net> Author: hpk Date: Wed Feb 16 13:57:50 2005 New Revision: 9244 Added: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file2_app.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Log: a first go at a new way of doing mixed modules. Note: - the old mechanisms is still fully in place and used for builtin and sys - test_app2interp.py tests with an example found in mixedmodule - newmodule contains the new ExtModule Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Wed Feb 16 13:57:50 2005 @@ -40,6 +40,9 @@ space.setitem(self.w_dict, space.wrap('__doc__'), w_doc) def descr_module__getattr__(self, w_attr): + return self.ARGL_getattr(w_attr) + + def ARGL_getattr(self, w_attr): space = self.space attr = space.str_w(w_attr) # ______ for the 'sys' module only _____ XXX generalize Added: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Wed Feb 16 13:57:50 2005 @@ -0,0 +1,90 @@ +from pypy.interpreter.module import Module +from pypy.tool.cache import Cache +from pypy.interpreter import gateway +from pypy.interpreter.error import OperationError + +import inspect + +class ExtModule(Module): + def __init__(self, space, w_name): + """ NOT_RPYTHON """ + Module.__init__(self, space, w_name) + self.lazy = True + # build a constant dictionary out of + # applevel/interplevel definitions + self.__class__.buildloaders() + + def ARGL_getattr(self, w_attr): + space = self.space + if not self.lazy: + raise OperationError(space.w_AttributeError, w_attr) + name = space.str_w(w_attr) + return self.get(name) + + def get(self, name): + try: + return Module.get(self, name) + except OperationError, e: + space = self.space + if not self.lazy or not e.match(space, self.space.w_KeyError): + raise + # not rpython + try: + loader = self.loaders[name] + except KeyError: + raise OperationError(space.w_AttributeError, space.wrap(name)) + else: + w_value = loader(space) + space.setitem(self.w_dict, space.wrap(name), w_value) + return w_value + + def buildloaders(cls): + """ NOT_RPYTHON """ + if not hasattr(cls, 'loaders'): + cls.loaders = loaders = {} + pkgroot = cls.__module__ + print cls.interpleveldefs + for name, spec in cls.interpleveldefs.items(): + if spec.startswith('('): + loader = getinterpevalloader(spec) + else: + loader = getinterpfileloader(pkgroot, spec) + loaders[name] = loader + for name, spec in cls.appleveldefs.items(): + loaders[name] = getappfileloader(pkgroot, spec) + buildloaders = classmethod(buildloaders) + +def getinterpevalloader(spec): + def ievalloader(space): + """ NOT_RPYTHON """ + d = {'space' : space} + return eval(spec, d, d) + return ievalloader + +def getinterpfileloader(pkgroot, spec): + modname, attrname = spec.split('.') + impbase = pkgroot + '.' + modname + def ifileloader(space): + """ NOT_RPYTHON """ + mod = __import__(impbase, None, None, [attrname]) + attr = getattr(mod, attrname) + iattr = gateway.interp2app(attr, attrname) + return space.wrap(iattr) + return ifileloader + +applevelcache = Cache() +def getappfileloader(pkgroot, spec): + # hum, it's a bit more involved, because we usually + # want the import at applevel + modname, attrname = spec.split('.') + impbase = pkgroot + '.' + modname + mod = __import__(impbase, None, None, ['attrname']) + app = applevelcache.getorbuild(mod, buildapplevelfrommodule, None) + def afileloader(space): + """ NOT_RPYTHON """ + return app.wget(space, attrname) + return afileloader + +def buildapplevelfrommodule(mod, _): + source = inspect.getsource(mod) + return gateway.applevel(source) Added: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py Wed Feb 16 13:57:50 2005 @@ -0,0 +1,11 @@ +from pypy.interpreter.newmodule import ExtModule + +class Module(ExtModule): + interpleveldefs = { + 'somefunc' : 'file1.somefunc', + 'value' : '(space.w_None)', + } + + appleveldefs = { + 'someappfunc' : 'file2_app.someappfunc', + } Added: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py Wed Feb 16 13:57:50 2005 @@ -0,0 +1,4 @@ + +def somefunc(space): + return space.w_True + Added: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file2_app.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file2_app.py Wed Feb 16 13:57:50 2005 @@ -0,0 +1,3 @@ + +def someappfunc(x): + return x + 1 Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Wed Feb 16 13:57:50 2005 @@ -100,5 +100,27 @@ assert x/2 == 1 class AppTestMethods: - def test_somee_app_test_method(self): + def test_some_app_test_method(self): assert 2 == 2 + +class TestMixedModule: + def test_accesses(self): + space = self.space + import mixedmodule + w_module = mixedmodule.Module(space, space.wrap('mixedmodule')) + space.appexec([w_module], """ + (module): + assert module.value is None + + assert module.somefunc is module.somefunc + result = module.somefunc() + assert result == True + + assert module.someappfunc is module.someappfunc + appresult = module.someappfunc(41) + assert appresult == 42 + + assert module.__dict__ is module.__dict__ + for name in ('somefunc', 'someappfunc'): + assert name in module.__dict__ + """) From hpk at codespeak.net Wed Feb 16 15:51:04 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 15:51:04 +0100 (MET) Subject: [pypy-svn] r9245 - in pypy/branch/dist-interpapp/pypy/interpreter: . test test/mixedmodule Message-ID: <20050216145104.0373027B4F@code1.codespeak.net> Author: hpk Date: Wed Feb 16 15:51:04 2005 New Revision: 9245 Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Log: a variant that uses a custom __getattribute__ for Modules alltogether. Accessing __dict__ explicitely un-lazifies everything and provides a full globals dict. (see test_appinterp.py). the newmodule's ExtModule.__init__ is slightly hackish because it doesn't want to call Module.__init__ but let's see if we want to follow that route anyway. if we go for performing the lazyness at dict-level then REV 9241 (the one before this commit) is probably a better base. Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Wed Feb 16 15:51:04 2005 @@ -10,16 +10,10 @@ def __init__(self, space, w_name, w_dict=None): self.space = space - if w_dict is None: + if w_dict is None: w_dict = space.newdict([]) - self.w_dict = w_dict - self.w_name = w_name - space.setitem(w_dict, space.wrap('__name__'), w_name) - if not space.is_true(space.contains(w_dict, space.wrap('__doc__'))): - space.setitem(w_dict, space.wrap('__doc__'), space.w_None) - - def get(self, name): - return self.space.getitem(self.w_dict, self.space.wrap(name)) + self.w_dict = w_dict + self.descr_module__init__(w_name) def getdict(self): return self.w_dict @@ -35,17 +29,31 @@ def descr_module__init__(self, w_name, w_doc=None): space = self.space self.w_name = w_name - space.setitem(self.w_dict, space.wrap('__name__'), w_name) - if w_doc is not None: - space.setitem(self.w_dict, space.wrap('__doc__'), w_doc) - - def descr_module__getattr__(self, w_attr): - return self.ARGL_getattr(w_attr) + if w_doc is None: + w_doc = space.w_None + w_dict = self.getdict() + space.setitem(w_dict, space.wrap('__name__'), w_name) + space.setitem(w_dict, space.wrap('__doc__'), w_doc) - def ARGL_getattr(self, w_attr): + def descr_module__getattribute__(self, w_attr): space = self.space + w_self = space.wrap(self) attr = space.str_w(w_attr) - # ______ for the 'sys' module only _____ XXX generalize + w_result = space.lookup(w_self, attr) + if w_result is None: + return self.get(attr) + else: + return space.get(w_result, w_self) + + def get(self, attr): + space = self.space + try: + return space.getitem(self.w_dict, self.space.wrap(attr)) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + # ______ for the 'sys' module only _____ XXX put that + # into a special subclass at some point if self is space.sys: if attr == 'exc_type': operror = space.getexecutioncontext().sys_exc_info() Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Wed Feb 16 15:51:04 2005 @@ -8,42 +8,43 @@ class ExtModule(Module): def __init__(self, space, w_name): """ NOT_RPYTHON """ - Module.__init__(self, space, w_name) - self.lazy = True - # build a constant dictionary out of - # applevel/interplevel definitions + #Module.__init__(self, space, w_name) + self.space = space + self.w_name = w_name + self.w_dict = None + self.itemcache = Cache() self.__class__.buildloaders() - def ARGL_getattr(self, w_attr): - space = self.space - if not self.lazy: - raise OperationError(space.w_AttributeError, w_attr) - name = space.str_w(w_attr) - return self.get(name) - def get(self, name): - try: - return Module.get(self, name) - except OperationError, e: + if self.w_dict is not None: + return Module.get(self, name) + return self.space.loadfromcache(name, self.buildwvalue, self.itemcache) + + def getdict(self): + if self.w_dict is None: space = self.space - if not self.lazy or not e.match(space, self.space.w_KeyError): - raise - # not rpython - try: - loader = self.loaders[name] - except KeyError: - raise OperationError(space.w_AttributeError, space.wrap(name)) - else: - w_value = loader(space) - space.setitem(self.w_dict, space.wrap(name), w_value) - return w_value + w_dict = wdict = space.newdict([]) + for name in self.loaders: + w_value = self.get(name) + space.setitem(w_dict, space.wrap(name), w_value) + self.w_dict = w_dict + return self.w_dict + + def buildwvalue(self, name, space): + try: + loader = self.loaders[name] + except KeyError: + raise OperationError(space.w_AttributeError, space.wrap(name)) + else: + return loader(space) def buildloaders(cls): """ NOT_RPYTHON """ if not hasattr(cls, 'loaders'): + # build a constant dictionary out of + # applevel/interplevel definitions cls.loaders = loaders = {} pkgroot = cls.__module__ - print cls.interpleveldefs for name, spec in cls.interpleveldefs.items(): if spec.startswith('('): loader = getinterpevalloader(spec) Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py Wed Feb 16 15:51:04 2005 @@ -2,6 +2,8 @@ class Module(ExtModule): interpleveldefs = { + '__name__' : '(space.wrap("mixedmodule"))', + '__doc__' : '(space.wrap("mixedmodule doc"))', 'somefunc' : 'file1.somefunc', 'value' : '(space.w_None)', } Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_appinterp.py Wed Feb 16 15:51:04 2005 @@ -111,6 +111,7 @@ space.appexec([w_module], """ (module): assert module.value is None + assert module.__doc__ == 'mixedmodule doc' assert module.somefunc is module.somefunc result = module.somefunc() @@ -121,6 +122,6 @@ assert appresult == 42 assert module.__dict__ is module.__dict__ - for name in ('somefunc', 'someappfunc'): + for name in ('somefunc', 'someappfunc', '__doc__', '__name__'): assert name in module.__dict__ """) Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Wed Feb 16 15:51:04 2005 @@ -273,7 +273,7 @@ __new__ = interp2app(Module.descr_module__new__.im_func), __init__ = interp2app(Module.descr_module__init__.im_func), __dict__ = GetSetProperty(descr_get_dict), # module dictionaries are readonly attributes - __getattr__ = interp2app(Module.descr_module__getattr__.im_func), + __getattribute__ = interp2app(Module.descr_module__getattribute__.im_func), ) getset_func_doc = GetSetProperty(Function.fget_func_doc, From arigo at codespeak.net Wed Feb 16 15:55:13 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 16 Feb 2005 15:55:13 +0100 (MET) Subject: [pypy-svn] r9246 - pypy/branch/dist-interpapp/pypy/module/builtin Message-ID: <20050216145513.4D83927B53@code1.codespeak.net> Author: arigo Date: Wed Feb 16 15:55:12 2005 New Revision: 9246 Added: pypy/branch/dist-interpapp/pypy/module/builtin/ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py pypy/branch/dist-interpapp/pypy/module/builtin/app_complex.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/app_functional.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/app_help.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/app_io.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/app_misc.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__interp.py pypy/branch/dist-interpapp/pypy/module/builtin/importing.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__interp.py pypy/branch/dist-interpapp/pypy/module/builtin/operation.py - copied, changed from r9243, pypy/dist/pypy/module/__builtin__interp.py Log: First try, not tested: splitting the __builtin__ module into manageable files, using the new model currently in development. See module/builtin/__init__.py. Note that I tried as much as possible to keep the original authors' svn credits, which explains that the diffs are full of "-". Added: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Wed Feb 16 15:55:12 2005 @@ -0,0 +1,103 @@ +from pypy.interpreter.extmodule import ExtModule + + +class BuiltinModule(ExtModule): + """Built-in functions, exceptions, and other objects. + +Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. +""" + + _applevel_ = { + 'quit' : 'app_help.exit', + 'exit' : 'app_help.exit', + 'copyright' : 'app_help.copyright', + 'license' : 'app_help.license', + 'help' : 'app_help.help', + + 'execfile' : 'app_io.execfile', + 'raw_input' : 'app_io.raw_input', + 'input' : 'app_io.input', + + 'sum' : 'app_functional.sum', + 'apply' : 'app_functional.apply', + 'map' : 'app_functional.map', + 'filter' : 'app_functional.filter', + 'zip' : 'app_functional.zip', + 'reduce' : 'app_functional.reduce', + 'range' : 'app_functional.range', + 'min' : 'app_functional.min', + 'max' : 'app_functional.max', + 'enumerate' : 'app_functional.enumerate', + 'xrange' : 'app_functional.xrange', + 'sorted' : 'app_functional.sorted', + 'reversed' : 'app_functional.reversed', + + 'issubclass' : 'app_inspect.issubclass', + 'isinstance' : 'app_inspect.isinstance', + 'hasattr' : 'app_inspect.hasattr', + 'callable' : 'app_inspect.callable', + 'globals' : 'app_inspect.globals', + 'locals' : 'app_inspect.locals', + 'vars' : 'app_inspect.vars', + 'dir' : 'app_inspect.dir', + + 'property' : 'app_descriptor.property', + 'staticmethod' : 'app_descriptor.staticmethod', + 'classmethod' : 'app_descriptor.classmethod', + 'super' : 'app_descriptor.super', + + 'complex' : 'app_complex.complex', + + 'intern' : 'app_misc.intern', + 'unichr' : 'app_misc.unichr', + 'buffer' : 'app_misc.buffer', + 'reload' : 'app_misc.reload', + } + + _interplevel_ = { + # constants + 'None' : '(space.w_None)', + 'False' : '(space.w_False)', + 'True' : '(space.w_True)', + '__debug__' : '(space.w_True)', # XXX + 'type' : '(space.w_type)', + 'object' : '(space.w_object)', + 'file' : '(space.wrap(file))', + 'open' : '(space.wrap(file))', + 'unicode' : '(space.wrap(unicode)', # XXX faked + + # old-style classes dummy support + '_classobj' : '(space.w_classobj)', + '_instance' : '(space.w_instance)', + # default __metaclass__ + # XXX can use _classobj when we have a working one integrated + '__metaclass__' : '(space.w_type)', + + # interp-level function definitions + 'abs' : 'operation.abs', + 'chr' : 'operation.chr', + 'len' : 'operation.len', + 'ord' : 'operation.ord', + 'pow' : 'operation.pow', + 'repr' : 'operation.repr', + 'hash' : 'operation.hash', + 'oct' : 'operation.oct', + 'hex' : 'operation.hex', + 'round' : 'operation.round', + 'cmp' : 'operation.cmp', + 'coerce' : 'operation.coerce', + 'divmod' : 'operation.divmod', + '_issubtype' : 'operation._issubtype', + 'getattr' : 'operation.getattr', + 'setattr' : 'operation.setattr', + 'delattr' : 'operation.delattr', + 'iter' : 'operation.iter', + 'hash' : 'operation.hash', + 'id' : 'operation.id', + '_seqiter' : 'operation._seqiter', + + 'compile' : 'compiling.compile', + 'eval' : 'compiling.eval', + + '__import__' : 'importing.importhook', + } Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_complex.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_complex.py Wed Feb 16 15:55:12 2005 @@ -1,685 +1,7 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. """ - -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ +Plain Python definition of the 'complex' type. """ -Copyright (c) <2003-2004> -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - class complex(object): """complex(real[, imag]) -> complex number @@ -980,70 +302,3 @@ def __float__(self): raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py Wed Feb 16 15:55:12 2005 @@ -1,573 +1,7 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. -""" - -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ """ -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Plain Python definition of the builtin descriptors. """ -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - # Descriptor code, shamelessly stolen to Raymond Hettinger: # http://users.rcn.com/python/download/Descriptor.htm class property(object): @@ -679,371 +113,3 @@ x = x.__get__(d['__self__'], type(d['__self__'])) return x return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_functional.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_functional.py Wed Feb 16 15:55:12 2005 @@ -1,71 +1,7 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. """ - -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) +Plain Python definition of the builtin functions oriented towards +functional programming. +""" def sum(sequence, total=0): @@ -75,14 +11,7 @@ total = total + item return total -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - +# ____________________________________________________________ def apply(function, args, kwds={}): """call a function (or other callable object) and return its result""" @@ -209,39 +138,7 @@ return initial -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) +# ____________________________________________________________ def range(x, y=None, step=1): """ returns a list of integers in arithmetic position from start (defaults @@ -287,6 +184,8 @@ return arr +# ____________________________________________________________ + # min and max could be one function if we had operator.__gt__ and # operator.__lt__ Perhaps later when we have operator. @@ -330,178 +229,6 @@ max = i return max -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ -""" -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ def enumerate(collection): 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' it = iter(collection) # raises a TypeError early @@ -512,6 +239,8 @@ index += 1 return do_enumerate(it) +# ____________________________________________________________ + class xrange(object): def __init__(self, start, stop=None, step=1): if not isinstance(start, (int, long, float)): @@ -567,426 +296,7 @@ yield i i+=step - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" +# ____________________________________________________________ def sorted(lst, cmp=None, key=None, reverse=None): "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" @@ -1007,43 +317,3 @@ for index in range(len_iterable-1, -1, -1): yield local_iterable[index] return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_help.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_help.py Wed Feb 16 15:55:12 2005 @@ -1,462 +1,13 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. +""" +Plain Python definition of the builtin interactive help functions. """ -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result +import sys -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) +if sys.platform == "win32": + exit = "Use Ctrl-Z plus Return to exit." +else: + exit = "Use Ctrl-D (i.e. EOF) to exit." def copyright(): print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' @@ -473,577 +24,16 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) +# Define the built-in 'help'. +# This is a wrapper around pydoc.help (with a twist). +class _Helper: def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file + return "Type help() for interactive help, " \ + "or help(object) for help about object." + def __call__(self, *args, **kwds): + import pydoc + return pydoc.help(*args, **kwds) -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type +help = _Helper() Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py Wed Feb 16 15:55:12 2005 @@ -1,213 +1,16 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. +""" +Plain Python definition of the builtin functions related to run-time +program introspection. """ -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" +import sys - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res +def globals(): + return sys._getframe(1).f_globals -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] +def locals(): + return sys._getframe(1).f_locals - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial def _recursive_issubclass(cls, klass_or_tuple): if cls is klass_or_tuple: @@ -231,7 +34,7 @@ if not hasattr(klass_or_tuple, '__bases__'): raise TypeError, "arg 2 must be a class or type or a tuple thereof" return _recursive_issubclass(cls, klass_or_tuple) - + def isinstance(obj, klass_or_tuple): if issubclass(type(obj), klass_or_tuple): @@ -243,95 +46,6 @@ else: return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y def vars(*obj): """return a dictionary of all the attributes currently bound in obj. If @@ -450,600 +164,3 @@ result = Dict.keys() result.sort() return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ -""" -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_io.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_io.py Wed Feb 16 15:55:12 2005 @@ -1,33 +1,15 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. +""" +Plain Python definition of the builtin I/O-related functions. """ -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." +import sys def execfile(filename, glob=None, loc=None): if glob is None: - glob = _caller_globals() + caller = sys._getframe(1) + glob = caller.f_globals if loc is None: - loc = _caller_locals() + loc = caller.f_locals elif loc is None: loc = glob f = file(filename) @@ -40,7 +22,6 @@ exec co in glob, loc def raw_input(prompt=None): - import sys try: sys.stdin except AttributeError: @@ -66,984 +47,3 @@ def input(prompt=None): return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ -""" -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Copied: pypy/branch/dist-interpapp/pypy/module/builtin/app_misc.py (from r9243, pypy/dist/pypy/module/__builtin__module.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__module.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_misc.py Wed Feb 16 15:55:12 2005 @@ -1,455 +1,7 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. +""" +Plain Python definition of some miscellaneous builtin functions. """ -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result _stringtable = {} def intern(s): @@ -458,555 +10,18 @@ raise TypeError("intern() argument 1 must be string.") return _stringtable.setdefault(s,s) -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ -""" -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." def unichr(code): import sys if (code < 0 or code > sys.maxunicode): raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ class buffer(object): def __init__(self, object, offset=None, size=None): raise NotImplementedError, "XXX nobody needs this anyway" -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) def reload(module): import imp, sys, errno @@ -1040,10 +55,3 @@ f.close() return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Copied: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py (from r9243, pypy/dist/pypy/module/__builtin__interp.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py Wed Feb 16 15:55:12 2005 @@ -1,203 +1,8 @@ """ -Implementation of interpreter-level builtins. +Implementation of the interpreter-level compile/eval builtins. """ -from pypy.interpreter.module import Module -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import BaseWrappable, W_Root -from pypy.interpreter.gateway import NoneNotWrapped -import __builtin__ as cpy_builtin - -# import useful app-level functions -from __applevel__ import execfile, callable, _iter_generator - - -def _actframe(position=0): - return space.getexecutioncontext().framestack.top(position) - -def globals(): - return _actframe().w_globals - -def locals(): - return _actframe().getdictscope() - -def _caller_globals(position=1): - return _actframe(position).w_globals -# -_caller_globals.unwrap_spec = [int] - -def _caller_locals(position=1): - return _actframe(position).getdictscope() -# -_caller_locals.unwrap_spec = [int] - - -def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None): - import os - w = space.wrap - if os.path.exists(f): - w_mod = space.wrap(Module(space, w_modulename)) - space.sys.setmodule(w_mod) - space.setattr(w_mod, w('__file__'), w(f)) - if pkgdir is not None: - space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)])) - w_dict = space.getattr(w_mod, w('__dict__')) - execfile(w(f), w_dict, w_dict) - w_mod = check_sys_modules(w_modulename) - if w_mod is not None and w_parent is not None: - space.setattr(w_parent, w_name, w_mod) - return w_mod - else: - return None - -def try_getattr(w_obj,w_name): - try: - return space.getattr(w_obj, w_name) - except OperationError, e: - # ugh, but blame CPython :-/ this is supposed to emulate - # hasattr, which eats all exceptions. - return None - -def try_getitem(w_obj,w_key): - try: - return space.getitem(w_obj, w_key) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - return None - - -def check_sys_modules(w_modulename): - try: - w_mod = space.getitem(space.sys.w_modules, w_modulename) - except OperationError, e: - pass - else: - return w_mod - if not e.match(space, space.w_KeyError): - raise - return None - -il_len = len - -def __import__(modulename, w_globals=None, - w_locals=None, w_fromlist=None): - if not isinstance(modulename, str): - try: - helper = ', not ' + modulename.__class__.__name__ - except AttributeError: - helper = '' - raise OperationError(space.w_TypeError, - space.wrap("__import__() argument 1 must be string" + helper)) - w = space.wrap - - if w_globals is not None and not space.is_true(space.is_(w_globals, space.w_None)): - ctxt_w_name = try_getitem(w_globals,w('__name__')) - ctxt_w_path = try_getitem(w_globals,w('__path__')) - else: - ctxt_w_name = None - ctxt_w_path = None - - rel_modulename = None - if ctxt_w_name is not None: - - ctxt_name_prefix_parts = space.str_w(ctxt_w_name).split('.') - if ctxt_w_path is None: # context is a plain module - ctxt_name_prefix_parts = ctxt_name_prefix_parts[:-1] - if ctxt_name_prefix_parts: - rel_modulename = '.'.join(ctxt_name_prefix_parts+[modulename]) - else: # context is a package module - rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename - if rel_modulename is not None: - w_mod = check_sys_modules(w(rel_modulename)) - if (w_mod is None or - not space.is_true(space.is_(w_mod,space.w_None))): - - w_mod = absolute_import(rel_modulename, - il_len(ctxt_name_prefix_parts), - w_fromlist, tentative=1) - if w_mod is not None: - return w_mod - else: - rel_modulename = None - - w_mod = absolute_import(modulename,0,w_fromlist, tentative=0) - if rel_modulename is not None: - space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) - return w_mod -# -__import__.unwrap_spec = [str,W_Root,W_Root,W_Root] - -def absolute_import(modulename, baselevel, w_fromlist, tentative): - w = space.wrap - - w_mod = None - parts = modulename.split('.') - prefix = [] - # it would be nice if we could do here: w_path = space.sys.w_path - # instead: - w_path = space.getitem(space.sys.w_dict, space.wrap('path')) - - first = None - level = 0 - - for part in parts: - w_mod = load_part(w_path, prefix, part, w_mod, tentative=tentative) - if w_mod is None: - return None - - if baselevel == level: - first = w_mod - tentative = 0 - prefix.append(part) - w_path = try_getattr(w_mod,w('__path__')) - level += 1 - - if w_fromlist is not None and space.is_true(w_fromlist): - if w_path is not None: - for w_name in space.unpackiterable(w_fromlist): - load_part(w_path, prefix, space.str_w(w_name), w_mod, - tentative=1) - return w_mod - else: - return first - -def load_part(w_path, prefix, partname, w_parent, tentative): - w = space.wrap - modulename = '.'.join(prefix+[partname]) - w_modulename = w(modulename) - w_mod = check_sys_modules(w_modulename) - if w_mod is not None: - if not space.is_true(space.is_(w_mod,space.w_None)): - return w_mod - else: - w_mod = space.get_builtin_module(modulename) - if w_mod is not None: - return w_mod - import os - for path in space.unpackiterable(w_path): - dir = os.path.join(space.str_w(path), partname) - if os.path.isdir(dir): - f = os.path.join(dir,'__init__.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname), - pkgdir=dir) - if w_mod is not None: - return w_mod - f = os.path.join(space.str_w(path), partname + '.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname)) - if w_mod is not None: - return w_mod - - if tentative: - return None - else: - # ImportError - w_failing = w_modulename - w_exc = space.call_function(space.w_ImportError, w_failing) - raise OperationError(space.w_ImportError, w_exc) - -def compile(w_str_, filename, startstr, +def compile(space, w_str_, filename, startstr, supplied_flags=0, dont_inherit=0): if space.is_true(space.isinstance(w_str_, space.w_unicode)): str_ = space.unwrap(w_str_) # xxx generic unwrap @@ -230,12 +35,15 @@ compile.unwrap_spec = [W_Root,str,str,int,int] -def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): +def eval(space, w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): w = space.wrap if (space.is_true(space.isinstance(w_source, space.w_str)) or space.is_true(space.isinstance(w_source, space.w_unicode))): - w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), "", "eval") + w_codeobj = compile(space, + space.call_method(w_source, 'lstrip', + space.wrap(' \t')), + "", "eval") elif isinstance(space.interpclass_w(w_source), PyCode): w_codeobj = w_source else: @@ -243,94 +51,14 @@ w('eval() arg 1 must be a string or code object')) if w_globals is None: - w_globals = globals() - w_locals = locals() + try: + caller = space.getexecutioncontext().framestack.top() + except IndexError: + w_globals = w_locals = space.newdict([]) + else: + w_globals = caller.w_globals + w_locals = caller.getdictscope() elif w_locals is None: w_locals = w_globals return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals) - -def abs(w_val): - "abs(number) -> number\n\nReturn the absolute value of the argument." - return space.abs(w_val) - -def chr(w_ascii): - w_character = space.newstring([w_ascii]) - return w_character - -def len(w_obj): - return space.len(w_obj) - -def delattr(w_object, w_name): - space.delattr(w_object, w_name) - return space.w_None - -def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): - if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere - w_name = space.call_method(w_name, 'encode') - try: - return space.getattr(w_object, w_name) - except OperationError, e: - if e.match(space, space.w_AttributeError): - if w_defvalue is not None: - return w_defvalue - raise - -def hash(w_object): - return space.hash(w_object) - -def oct(w_val): - # XXX does this need to be a space operation? - return space.oct(w_val) - -def hex(w_val): - return space.hex(w_val) - -def round(w_val, w_n=0): - return space.round(w_val, w_n) - -def id(w_object): - return space.id(w_object) - -def cmp(w_x, w_y): - """return 0 when x == y, -1 when x < y and 1 when x > y """ - return space.cmp(w_x, w_y) - -def coerce(w_x, w_y): - """coerce(x, y) -> (x1, y1) - - Return a tuple consisting of the two numeric arguments converted to - a common type, using the same rules as used by arithmetic operations. - If coercion is not possible, raise TypeError.""" - return space.coerce(w_x, w_y) - - -#XXX works only for new-style classes. -#So we have to fix it, when we add support for old-style classes -def _issubtype(w_cls1, w_cls2): - return space.issubtype(w_cls1, w_cls2) - -def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): - if w_sentinel is None: - return space.iter(w_collection_or_callable) - else: - if not space.is_true(callable(w_collection_or_callable)): - raise OperationError(space.w_TypeError, - space.wrap('iter(v, w): w must be callable')) - return _iter_generator(w_collection_or_callable, w_sentinel) - -def _seqiter(w_obj): - return space.newseqiter(w_obj) - -def ord(w_val): - return space.ord(w_val) - -def pow(w_base, w_exponent, w_modulus=None): - return space.pow(w_base, w_exponent, w_modulus) - -def repr(w_object): - return space.repr(w_object) - -def setattr(w_object, w_name, w_val): - space.setattr(w_object, w_name, w_val) - return space.w_None Copied: pypy/branch/dist-interpapp/pypy/module/builtin/importing.py (from r9243, pypy/dist/pypy/module/__builtin__interp.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Wed Feb 16 15:55:12 2005 @@ -1,40 +1,17 @@ """ -Implementation of interpreter-level builtins. +Implementation of the interpreter-level default import logic. """ -from pypy.interpreter.module import Module -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import BaseWrappable, W_Root -from pypy.interpreter.gateway import NoneNotWrapped -import __builtin__ as cpy_builtin +import sys, os -# import useful app-level functions -from __applevel__ import execfile, callable, _iter_generator +# XXX this uses the os.path module at interp-level, which means +# XXX that translate_pypy will produce a translated version of +# XXX PyPy that will only run on the same platform, as it contains +# XXX a frozen version of some routines of only one of the +# XXX posixpath/ntpath/macpath modules. -def _actframe(position=0): - return space.getexecutioncontext().framestack.top(position) - -def globals(): - return _actframe().w_globals - -def locals(): - return _actframe().getdictscope() - -def _caller_globals(position=1): - return _actframe(position).w_globals -# -_caller_globals.unwrap_spec = [int] - -def _caller_locals(position=1): - return _actframe(position).getdictscope() -# -_caller_locals.unwrap_spec = [int] - - -def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None): - import os +def try_import_mod(space, w_modulename, f, w_parent, w_name, pkgdir=None): w = space.wrap if os.path.exists(f): w_mod = space.wrap(Module(space, w_modulename)) @@ -44,14 +21,14 @@ space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)])) w_dict = space.getattr(w_mod, w('__dict__')) execfile(w(f), w_dict, w_dict) - w_mod = check_sys_modules(w_modulename) + w_mod = check_sys_modules(space, w_modulename) if w_mod is not None and w_parent is not None: space.setattr(w_parent, w_name, w_mod) return w_mod else: return None -def try_getattr(w_obj,w_name): +def try_getattr(space, w_obj, w_name): try: return space.getattr(w_obj, w_name) except OperationError, e: @@ -59,7 +36,7 @@ # hasattr, which eats all exceptions. return None -def try_getitem(w_obj,w_key): +def try_getitem(space, w_obj, w_key): try: return space.getitem(w_obj, w_key) except OperationError, e: @@ -68,7 +45,7 @@ return None -def check_sys_modules(w_modulename): +def check_sys_modules(space, w_modulename): try: w_mod = space.getitem(space.sys.w_modules, w_modulename) except OperationError, e: @@ -79,9 +56,7 @@ raise return None -il_len = len - -def __import__(modulename, w_globals=None, +def importhook(space, modulename, w_globals=None, w_locals=None, w_fromlist=None): if not isinstance(modulename, str): try: @@ -93,8 +68,8 @@ w = space.wrap if w_globals is not None and not space.is_true(space.is_(w_globals, space.w_None)): - ctxt_w_name = try_getitem(w_globals,w('__name__')) - ctxt_w_path = try_getitem(w_globals,w('__path__')) + ctxt_w_name = try_getitem(space, w_globals, w('__name__')) + ctxt_w_path = try_getitem(space, w_globals, w('__path__')) else: ctxt_w_name = None ctxt_w_path = None @@ -110,26 +85,26 @@ else: # context is a package module rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename if rel_modulename is not None: - w_mod = check_sys_modules(w(rel_modulename)) + w_mod = check_sys_modules(space, w(rel_modulename)) if (w_mod is None or not space.is_true(space.is_(w_mod,space.w_None))): - w_mod = absolute_import(rel_modulename, - il_len(ctxt_name_prefix_parts), + w_mod = absolute_import(space, rel_modulename, + len(ctxt_name_prefix_parts), w_fromlist, tentative=1) if w_mod is not None: return w_mod else: rel_modulename = None - w_mod = absolute_import(modulename,0,w_fromlist, tentative=0) + w_mod = absolute_import(space, modulename, 0, w_fromlist, tentative=0) if rel_modulename is not None: space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) return w_mod # -__import__.unwrap_spec = [str,W_Root,W_Root,W_Root] +importhook.unwrap_spec = [str,W_Root,W_Root,W_Root] -def absolute_import(modulename, baselevel, w_fromlist, tentative): +def absolute_import(space, modulename, baselevel, w_fromlist, tentative): w = space.wrap w_mod = None @@ -143,7 +118,8 @@ level = 0 for part in parts: - w_mod = load_part(w_path, prefix, part, w_mod, tentative=tentative) + w_mod = load_part(space, w_path, prefix, part, w_mod, + tentative=tentative) if w_mod is None: return None @@ -151,23 +127,23 @@ first = w_mod tentative = 0 prefix.append(part) - w_path = try_getattr(w_mod,w('__path__')) + w_path = try_getattr(space, w_mod, w('__path__')) level += 1 if w_fromlist is not None and space.is_true(w_fromlist): if w_path is not None: for w_name in space.unpackiterable(w_fromlist): - load_part(w_path, prefix, space.str_w(w_name), w_mod, + load_part(space, w_path, prefix, space.str_w(w_name), w_mod, tentative=1) return w_mod else: return first -def load_part(w_path, prefix, partname, w_parent, tentative): +def load_part(space, w_path, prefix, partname, w_parent, tentative): w = space.wrap modulename = '.'.join(prefix+[partname]) w_modulename = w(modulename) - w_mod = check_sys_modules(w_modulename) + w_mod = check_sys_modules(space, w_modulename) if w_mod is not None: if not space.is_true(space.is_(w_mod,space.w_None)): return w_mod @@ -175,17 +151,17 @@ w_mod = space.get_builtin_module(modulename) if w_mod is not None: return w_mod - import os for path in space.unpackiterable(w_path): dir = os.path.join(space.str_w(path), partname) if os.path.isdir(dir): f = os.path.join(dir,'__init__.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname), - pkgdir=dir) + w_mod = try_import_mod(space, w_modulename, f, w_parent, + w(partname), pkgdir=dir) if w_mod is not None: return w_mod f = os.path.join(space.str_w(path), partname + '.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname)) + w_mod = try_import_mod(space, w_modulename, f, w_parent, + w(partname)) if w_mod is not None: return w_mod @@ -196,141 +172,3 @@ w_failing = w_modulename w_exc = space.call_function(space.w_ImportError, w_failing) raise OperationError(space.w_ImportError, w_exc) - -def compile(w_str_, filename, startstr, - supplied_flags=0, dont_inherit=0): - if space.is_true(space.isinstance(w_str_, space.w_unicode)): - str_ = space.unwrap(w_str_) # xxx generic unwrap - else: - str_ = space.str_w(w_str_) - #print (str_, filename, startstr, supplied_flags, dont_inherit) - # XXX we additionally allow GENERATORS because compiling some builtins - # requires it. doesn't feel quite right to do that here. - supplied_flags |= 4096 - if not dont_inherit: - try: - frame = _actframe() - except IndexError: - pass - else: - supplied_flags |= frame.get_compile_flags() - try: - c = cpy_builtin.compile(str_, filename, startstr, supplied_flags, 1) - # It would be nice to propagate all exceptions to app level, - # but here we only propagate the 'usual' ones, until we figure - # out how to do it generically. - except SyntaxError,e: - raise OperationError(space.w_SyntaxError,space.wrap(str(e))) - except ValueError,e: - raise OperationError(space.w_ValueError,space.wrap(str(e))) - except TypeError,e: - raise OperationError(space.w_TypeError,space.wrap(str(e))) - return space.wrap(PyCode(space)._from_code(c)) -# -compile.unwrap_spec = [W_Root,str,str,int,int] - - -def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): - w = space.wrap - - if (space.is_true(space.isinstance(w_source, space.w_str)) or - space.is_true(space.isinstance(w_source, space.w_unicode))): - w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), "", "eval") - elif isinstance(space.interpclass_w(w_source), PyCode): - w_codeobj = w_source - else: - raise OperationError(space.w_TypeError, - w('eval() arg 1 must be a string or code object')) - - if w_globals is None: - w_globals = globals() - w_locals = locals() - elif w_locals is None: - w_locals = w_globals - - return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals) - -def abs(w_val): - "abs(number) -> number\n\nReturn the absolute value of the argument." - return space.abs(w_val) - -def chr(w_ascii): - w_character = space.newstring([w_ascii]) - return w_character - -def len(w_obj): - return space.len(w_obj) - -def delattr(w_object, w_name): - space.delattr(w_object, w_name) - return space.w_None - -def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): - if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere - w_name = space.call_method(w_name, 'encode') - try: - return space.getattr(w_object, w_name) - except OperationError, e: - if e.match(space, space.w_AttributeError): - if w_defvalue is not None: - return w_defvalue - raise - -def hash(w_object): - return space.hash(w_object) - -def oct(w_val): - # XXX does this need to be a space operation? - return space.oct(w_val) - -def hex(w_val): - return space.hex(w_val) - -def round(w_val, w_n=0): - return space.round(w_val, w_n) - -def id(w_object): - return space.id(w_object) - -def cmp(w_x, w_y): - """return 0 when x == y, -1 when x < y and 1 when x > y """ - return space.cmp(w_x, w_y) - -def coerce(w_x, w_y): - """coerce(x, y) -> (x1, y1) - - Return a tuple consisting of the two numeric arguments converted to - a common type, using the same rules as used by arithmetic operations. - If coercion is not possible, raise TypeError.""" - return space.coerce(w_x, w_y) - - -#XXX works only for new-style classes. -#So we have to fix it, when we add support for old-style classes -def _issubtype(w_cls1, w_cls2): - return space.issubtype(w_cls1, w_cls2) - -def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): - if w_sentinel is None: - return space.iter(w_collection_or_callable) - else: - if not space.is_true(callable(w_collection_or_callable)): - raise OperationError(space.w_TypeError, - space.wrap('iter(v, w): w must be callable')) - return _iter_generator(w_collection_or_callable, w_sentinel) - -def _seqiter(w_obj): - return space.newseqiter(w_obj) - -def ord(w_val): - return space.ord(w_val) - -def pow(w_base, w_exponent, w_modulus=None): - return space.pow(w_base, w_exponent, w_modulus) - -def repr(w_object): - return space.repr(w_object) - -def setattr(w_object, w_name, w_val): - space.setattr(w_object, w_name, w_val) - return space.w_None Copied: pypy/branch/dist-interpapp/pypy/module/builtin/operation.py (from r9243, pypy/dist/pypy/module/__builtin__interp.py) ============================================================================== --- pypy/dist/pypy/module/__builtin__interp.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/operation.py Wed Feb 16 15:55:12 2005 @@ -1,271 +1,27 @@ """ -Implementation of interpreter-level builtins. +Interp-level implementation of the basic space operations. """ -from pypy.interpreter.module import Module -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import BaseWrappable, W_Root -from pypy.interpreter.gateway import NoneNotWrapped - -import __builtin__ as cpy_builtin - -# import useful app-level functions -from __applevel__ import execfile, callable, _iter_generator - - -def _actframe(position=0): - return space.getexecutioncontext().framestack.top(position) - -def globals(): - return _actframe().w_globals - -def locals(): - return _actframe().getdictscope() - -def _caller_globals(position=1): - return _actframe(position).w_globals -# -_caller_globals.unwrap_spec = [int] - -def _caller_locals(position=1): - return _actframe(position).getdictscope() -# -_caller_locals.unwrap_spec = [int] - - -def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None): - import os - w = space.wrap - if os.path.exists(f): - w_mod = space.wrap(Module(space, w_modulename)) - space.sys.setmodule(w_mod) - space.setattr(w_mod, w('__file__'), w(f)) - if pkgdir is not None: - space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)])) - w_dict = space.getattr(w_mod, w('__dict__')) - execfile(w(f), w_dict, w_dict) - w_mod = check_sys_modules(w_modulename) - if w_mod is not None and w_parent is not None: - space.setattr(w_parent, w_name, w_mod) - return w_mod - else: - return None - -def try_getattr(w_obj,w_name): - try: - return space.getattr(w_obj, w_name) - except OperationError, e: - # ugh, but blame CPython :-/ this is supposed to emulate - # hasattr, which eats all exceptions. - return None - -def try_getitem(w_obj,w_key): - try: - return space.getitem(w_obj, w_key) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - return None - -def check_sys_modules(w_modulename): - try: - w_mod = space.getitem(space.sys.w_modules, w_modulename) - except OperationError, e: - pass - else: - return w_mod - if not e.match(space, space.w_KeyError): - raise - return None +from pypy.interpreter import gateway -il_len = len -def __import__(modulename, w_globals=None, - w_locals=None, w_fromlist=None): - if not isinstance(modulename, str): - try: - helper = ', not ' + modulename.__class__.__name__ - except AttributeError: - helper = '' - raise OperationError(space.w_TypeError, - space.wrap("__import__() argument 1 must be string" + helper)) - w = space.wrap - - if w_globals is not None and not space.is_true(space.is_(w_globals, space.w_None)): - ctxt_w_name = try_getitem(w_globals,w('__name__')) - ctxt_w_path = try_getitem(w_globals,w('__path__')) - else: - ctxt_w_name = None - ctxt_w_path = None - - rel_modulename = None - if ctxt_w_name is not None: - - ctxt_name_prefix_parts = space.str_w(ctxt_w_name).split('.') - if ctxt_w_path is None: # context is a plain module - ctxt_name_prefix_parts = ctxt_name_prefix_parts[:-1] - if ctxt_name_prefix_parts: - rel_modulename = '.'.join(ctxt_name_prefix_parts+[modulename]) - else: # context is a package module - rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename - if rel_modulename is not None: - w_mod = check_sys_modules(w(rel_modulename)) - if (w_mod is None or - not space.is_true(space.is_(w_mod,space.w_None))): - - w_mod = absolute_import(rel_modulename, - il_len(ctxt_name_prefix_parts), - w_fromlist, tentative=1) - if w_mod is not None: - return w_mod - else: - rel_modulename = None - - w_mod = absolute_import(modulename,0,w_fromlist, tentative=0) - if rel_modulename is not None: - space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) - return w_mod -# -__import__.unwrap_spec = [str,W_Root,W_Root,W_Root] - -def absolute_import(modulename, baselevel, w_fromlist, tentative): - w = space.wrap - - w_mod = None - parts = modulename.split('.') - prefix = [] - # it would be nice if we could do here: w_path = space.sys.w_path - # instead: - w_path = space.getitem(space.sys.w_dict, space.wrap('path')) - - first = None - level = 0 - - for part in parts: - w_mod = load_part(w_path, prefix, part, w_mod, tentative=tentative) - if w_mod is None: - return None - - if baselevel == level: - first = w_mod - tentative = 0 - prefix.append(part) - w_path = try_getattr(w_mod,w('__path__')) - level += 1 - - if w_fromlist is not None and space.is_true(w_fromlist): - if w_path is not None: - for w_name in space.unpackiterable(w_fromlist): - load_part(w_path, prefix, space.str_w(w_name), w_mod, - tentative=1) - return w_mod - else: - return first - -def load_part(w_path, prefix, partname, w_parent, tentative): - w = space.wrap - modulename = '.'.join(prefix+[partname]) - w_modulename = w(modulename) - w_mod = check_sys_modules(w_modulename) - if w_mod is not None: - if not space.is_true(space.is_(w_mod,space.w_None)): - return w_mod - else: - w_mod = space.get_builtin_module(modulename) - if w_mod is not None: - return w_mod - import os - for path in space.unpackiterable(w_path): - dir = os.path.join(space.str_w(path), partname) - if os.path.isdir(dir): - f = os.path.join(dir,'__init__.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname), - pkgdir=dir) - if w_mod is not None: - return w_mod - f = os.path.join(space.str_w(path), partname + '.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname)) - if w_mod is not None: - return w_mod - - if tentative: - return None - else: - # ImportError - w_failing = w_modulename - w_exc = space.call_function(space.w_ImportError, w_failing) - raise OperationError(space.w_ImportError, w_exc) - -def compile(w_str_, filename, startstr, - supplied_flags=0, dont_inherit=0): - if space.is_true(space.isinstance(w_str_, space.w_unicode)): - str_ = space.unwrap(w_str_) # xxx generic unwrap - else: - str_ = space.str_w(w_str_) - #print (str_, filename, startstr, supplied_flags, dont_inherit) - # XXX we additionally allow GENERATORS because compiling some builtins - # requires it. doesn't feel quite right to do that here. - supplied_flags |= 4096 - if not dont_inherit: - try: - frame = _actframe() - except IndexError: - pass - else: - supplied_flags |= frame.get_compile_flags() - try: - c = cpy_builtin.compile(str_, filename, startstr, supplied_flags, 1) - # It would be nice to propagate all exceptions to app level, - # but here we only propagate the 'usual' ones, until we figure - # out how to do it generically. - except SyntaxError,e: - raise OperationError(space.w_SyntaxError,space.wrap(str(e))) - except ValueError,e: - raise OperationError(space.w_ValueError,space.wrap(str(e))) - except TypeError,e: - raise OperationError(space.w_TypeError,space.wrap(str(e))) - return space.wrap(PyCode(space)._from_code(c)) -# -compile.unwrap_spec = [W_Root,str,str,int,int] - - -def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): - w = space.wrap - - if (space.is_true(space.isinstance(w_source, space.w_str)) or - space.is_true(space.isinstance(w_source, space.w_unicode))): - w_codeobj = compile(space.call_method(w_source, 'lstrip', space.wrap(' \t')), "", "eval") - elif isinstance(space.interpclass_w(w_source), PyCode): - w_codeobj = w_source - else: - raise OperationError(space.w_TypeError, - w('eval() arg 1 must be a string or code object')) - - if w_globals is None: - w_globals = globals() - w_locals = locals() - elif w_locals is None: - w_locals = w_globals - - return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals) - -def abs(w_val): +def abs(space, w_val): "abs(number) -> number\n\nReturn the absolute value of the argument." return space.abs(w_val) -def chr(w_ascii): +def chr(space, w_ascii): w_character = space.newstring([w_ascii]) return w_character -def len(w_obj): +def len(space, w_obj): + "len(object) -> integer\n\nReturn the number of items of a sequence or mapping." return space.len(w_obj) -def delattr(w_object, w_name): +def delattr(space, w_object, w_name): space.delattr(w_object, w_name) return space.w_None -def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): +def getattr(space, w_object, w_name, w_defvalue=NoneNotWrapped): if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere w_name = space.call_method(w_name, 'encode') try: @@ -276,27 +32,27 @@ return w_defvalue raise -def hash(w_object): +def hash(space, w_object): return space.hash(w_object) -def oct(w_val): +def oct(space, w_val): # XXX does this need to be a space operation? return space.oct(w_val) -def hex(w_val): +def hex(space, w_val): return space.hex(w_val) -def round(w_val, w_n=0): +def round(space, w_val, w_n=0): return space.round(w_val, w_n) -def id(w_object): +def id(space, w_object): return space.id(w_object) -def cmp(w_x, w_y): +def cmp(space, w_x, w_y): """return 0 when x == y, -1 when x < y and 1 when x > y """ return space.cmp(w_x, w_y) -def coerce(w_x, w_y): +def coerce(space, w_x, w_y): """coerce(x, y) -> (x1, y1) Return a tuple consisting of the two numeric arguments converted to @@ -304,22 +60,41 @@ If coercion is not possible, raise TypeError.""" return space.coerce(w_x, w_y) +def divmod(space, w_x, w_y): + return space.divmod(w_x, w_y) -#XXX works only for new-style classes. -#So we have to fix it, when we add support for old-style classes -def _issubtype(w_cls1, w_cls2): +# semi-private: works only for new-style classes. +def _issubtype(space, w_cls1, w_cls2): return space.issubtype(w_cls1, w_cls2) -def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): + +# ____________________________________________________________ + +app = gateway.applevel(''' + # App-level implementation of the iter(callable,sentinel) operation. + + def iter_generator(callable_, sentinel): + while 1: + result = callable_() + if result == sentinel: + return + yield result + + def iter_sentinel(callable_, sentinel): + if not callable(callable_): + raise TypeError, 'iter(v, w): v must be callable' + return iter_generator(callable_, sentinel) + +''') +iter_sentinel = app.interphook("iter_sentinel") + +def iter(space, w_collection_or_callable, w_sentinel=NoneNotWrapped): if w_sentinel is None: return space.iter(w_collection_or_callable) else: - if not space.is_true(callable(w_collection_or_callable)): - raise OperationError(space.w_TypeError, - space.wrap('iter(v, w): w must be callable')) - return _iter_generator(w_collection_or_callable, w_sentinel) + return iter_sentinel(space, w_collection_or_callable, w_sentinel) -def _seqiter(w_obj): +def _seqiter(space, w_obj): return space.newseqiter(w_obj) def ord(w_val): From hpk at codespeak.net Wed Feb 16 16:09:27 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 16:09:27 +0100 (MET) Subject: [pypy-svn] r9247 - in pypy/branch/dist-interpapp/pypy: interpreter module/builtin Message-ID: <20050216150927.6555527B5C@code1.codespeak.net> Author: hpk Date: Wed Feb 16 16:09:27 2005 New Revision: 9247 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Log: slight renaming and a TEMPORARY hack to make 'builtin' directly available in the current __builtin__ :-) type builtin.map to see that it works and builtin.__dict__ to see where the unlazifying fails :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Wed Feb 16 16:09:27 2005 @@ -74,6 +74,11 @@ self.sys.setbuiltinmodule(self.w_builtin, '__builtin__') + # XXX TEMPORARY + from pypy.module.builtin import Module + w_name = self.wrap('builtin') + self.setitem(self.w_builtins, w_name, Module(self, w_name)) + def make_sys(self): "NOT_RPYTHON: only for initializing the space." from pypy.interpreter.extmodule import BuiltinModule Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Wed Feb 16 16:09:27 2005 @@ -1,13 +1,12 @@ -from pypy.interpreter.extmodule import ExtModule +from pypy.interpreter.newmodule import ExtModule - -class BuiltinModule(ExtModule): +class Module(ExtModule): """Built-in functions, exceptions, and other objects. Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. """ - _applevel_ = { + appleveldefs = { 'quit' : 'app_help.exit', 'exit' : 'app_help.exit', 'copyright' : 'app_help.copyright', @@ -54,7 +53,7 @@ 'reload' : 'app_misc.reload', } - _interplevel_ = { + interpleveldefs = { # constants 'None' : '(space.w_None)', 'False' : '(space.w_False)', From hpk at codespeak.net Wed Feb 16 16:25:19 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 16:25:19 +0100 (MET) Subject: [pypy-svn] r9248 - pypy/branch/dist-interpapp/pypy/module/builtin Message-ID: <20050216152519.7D86F27B57@code1.codespeak.net> Author: hpk Date: Wed Feb 16 16:25:19 2005 New Revision: 9248 Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py pypy/branch/dist-interpapp/pypy/module/builtin/importing.py pypy/branch/dist-interpapp/pypy/module/builtin/operation.py Log: a few fixes Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Wed Feb 16 16:25:19 2005 @@ -63,7 +63,7 @@ 'object' : '(space.w_object)', 'file' : '(space.wrap(file))', 'open' : '(space.wrap(file))', - 'unicode' : '(space.wrap(unicode)', # XXX faked + 'unicode' : '(space.wrap(unicode))', # XXX faked # old-style classes dummy support '_classobj' : '(space.w_classobj)', Modified: pypy/branch/dist-interpapp/pypy/module/builtin/importing.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/importing.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Wed Feb 16 16:25:19 2005 @@ -4,6 +4,10 @@ import sys, os +from pypy.interpreter.module import Module +from pypy.interpreter.error import OperationError +from pypy.interpreter.baseobjspace import W_Root + # XXX this uses the os.path module at interp-level, which means # XXX that translate_pypy will produce a translated version of # XXX PyPy that will only run on the same platform, as it contains Modified: pypy/branch/dist-interpapp/pypy/module/builtin/operation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/operation.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/operation.py Wed Feb 16 16:25:19 2005 @@ -3,7 +3,7 @@ """ from pypy.interpreter import gateway - +NoneNotWrapped = gateway.NoneNotWrapped def abs(space, w_val): "abs(number) -> number\n\nReturn the absolute value of the argument." From arigo at codespeak.net Wed Feb 16 16:27:58 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Wed, 16 Feb 2005 16:27:58 +0100 (MET) Subject: [pypy-svn] r9249 - pypy/branch/dist-interpapp/pypy/module/builtin Message-ID: <20050216152758.10FEF27B57@code1.codespeak.net> Author: arigo Date: Wed Feb 16 16:27:57 2005 New Revision: 9249 Modified: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Log: More missing imports; and fixed the unwrap_spec. Modified: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py Wed Feb 16 16:27:57 2005 @@ -2,6 +2,10 @@ Implementation of the interpreter-level compile/eval builtins. """ +from pypy.interpreter.pycode import PyCode +from pypy.interpreter.baseobjspace import W_Root, ObjSpace +from pypy.interpreter.gateway import NoneNotWrapped + def compile(space, w_str_, filename, startstr, supplied_flags=0, dont_inherit=0): if space.is_true(space.isinstance(w_str_, space.w_unicode)): @@ -32,7 +36,7 @@ raise OperationError(space.w_TypeError,space.wrap(str(e))) return space.wrap(PyCode(space)._from_code(c)) # -compile.unwrap_spec = [W_Root,str,str,int,int] +compile.unwrap_spec = [ObjSpace,W_Root,str,str,int,int] def eval(space, w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): Modified: pypy/branch/dist-interpapp/pypy/module/builtin/importing.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/importing.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Wed Feb 16 16:27:57 2005 @@ -6,7 +6,7 @@ from pypy.interpreter.module import Module from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import W_Root +from pypy.interpreter.baseobjspace import W_Root, ObjSpace # XXX this uses the os.path module at interp-level, which means # XXX that translate_pypy will produce a translated version of @@ -106,7 +106,7 @@ space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) return w_mod # -importhook.unwrap_spec = [str,W_Root,W_Root,W_Root] +importhook.unwrap_spec = [ObjSpace,str,W_Root,W_Root,W_Root] def absolute_import(space, modulename, baselevel, w_fromlist, tentative): w = space.wrap From hpk at codespeak.net Wed Feb 16 16:49:56 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 16:49:56 +0100 (MET) Subject: [pypy-svn] r9250 - pypy/branch/dist-interpapp/pypy/module/builtin Message-ID: <20050216154956.B97F227B4F@code1.codespeak.net> Author: hpk Date: Wed Feb 16 16:49:56 2005 New Revision: 9250 Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Log: add __name__ and __doc__ Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Wed Feb 16 16:49:56 2005 @@ -55,6 +55,8 @@ interpleveldefs = { # constants + '__name__' : '(space.wrap("__builtin__"))', + '__doc__' : '(space.wrap("PyPy builtin module"))', 'None' : '(space.w_None)', 'False' : '(space.w_False)', 'True' : '(space.w_True)', From hpk at codespeak.net Wed Feb 16 17:04:31 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 17:04:31 +0100 (MET) Subject: [pypy-svn] r9251 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050216160431.308B727B4F@code1.codespeak.net> Author: hpk Date: Wed Feb 16 17:04:31 2005 New Revision: 9251 Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Log: again use a flag for switching lazyness in a newmodule.ExtModule Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Wed Feb 16 17:04:31 2005 @@ -13,7 +13,8 @@ if w_dict is None: w_dict = space.newdict([]) self.w_dict = w_dict - self.descr_module__init__(w_name) + self.w_name = w_name + space.setitem(w_dict, space.wrap('__name__'), w_name) def getdict(self): return self.w_dict @@ -75,7 +76,7 @@ return space.wrap(operror.application_traceback) # produce a nice error message that shows the name of the module try: - name = space.str_w(self.w_name) + name = space.str_w(self.get('__name__')) except OperationError: name = '?' msg = "'%s' module has no attribute '%s'" % (name, attr) Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Wed Feb 16 17:04:31 2005 @@ -8,36 +8,35 @@ class ExtModule(Module): def __init__(self, space, w_name): """ NOT_RPYTHON """ - #Module.__init__(self, space, w_name) - self.space = space - self.w_name = w_name - self.w_dict = None - self.itemcache = Cache() + Module.__init__(self, space, w_name) + self.lazy = True self.__class__.buildloaders() def get(self, name): - if self.w_dict is not None: - return Module.get(self, name) - return self.space.loadfromcache(name, self.buildwvalue, self.itemcache) + space = self.space + try: + return space.getitem(self.w_dict, space.wrap(name)) + except OperationError, e: + if not self.lazy or not e.match(space, space.w_KeyError): + raise + try: + loader = self.loaders[name] + except KeyError: + raise OperationError(space.w_AttributeError, space.wrap(name)) + else: + w_value = loader(space) + self.space.setitem(self.w_dict, space.wrap(name), w_value) + return w_value def getdict(self): - if self.w_dict is None: + if self.lazy: space = self.space - w_dict = wdict = space.newdict([]) for name in self.loaders: w_value = self.get(name) - space.setitem(w_dict, space.wrap(name), w_value) - self.w_dict = w_dict + space.setitem(self.w_dict, space.wrap(name), w_value) + self.lazy = False return self.w_dict - def buildwvalue(self, name, space): - try: - loader = self.loaders[name] - except KeyError: - raise OperationError(space.w_AttributeError, space.wrap(name)) - else: - return loader(space) - def buildloaders(cls): """ NOT_RPYTHON """ if not hasattr(cls, 'loaders'): From pedronis at codespeak.net Wed Feb 16 18:14:44 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 16 Feb 2005 18:14:44 +0100 (MET) Subject: [pypy-svn] r9252 - in pypy/branch/dist-interpapp/pypy: interpreter objspace objspace/std Message-ID: <20050216171444.9379327B53@code1.codespeak.net> Author: pedronis Date: Wed Feb 16 18:14:44 2005 New Revision: 9252 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/objspace/descroperation.py pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Log: introduced getdictvalue on W_Root (w_obj.getdictvalue(space, attr) and on descroperation derived spaces descrspace.getdictvalue(w_obj, attr). Use in default __getattribute__ and in type lookup. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Wed Feb 16 18:14:44 2005 @@ -13,6 +13,18 @@ in a 'normal' object space like StdObjSpace.""" def getdict(self): return None + + def getdictvalue(self, space, attr): + w_dict = self.getdict() + if w_dict is not None: + try: + return space.getitem(w_dict, space.wrap(attr)) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + return None + + def getclass(self, space): return space.gettypeobject(self.typedef) Modified: pypy/branch/dist-interpapp/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/descroperation.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/descroperation.py Wed Feb 16 18:14:44 2005 @@ -12,15 +12,12 @@ if w_descr is not None: if space.is_data_descr(w_descr): return space.get(w_descr, w_obj) - w_dict = space.getdict(w_obj) - if w_dict is not None: - try: - return space.getitem(w_dict, w_name) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise + w_value = space.getdictvalue(w_obj, name) + if w_value is not None: + return w_value if w_descr is not None: return space.get(w_descr, w_obj) + raise OperationError(space.w_AttributeError, w_name) def descr__setattr__(space, w_obj, w_name, w_value): @@ -57,6 +54,9 @@ def getdict(space, w_obj): return w_obj.getdict() + def getdictvalue(space, w_obj, attr): + return w_obj.getdictvalue(space, attr) + def is_data_descr(space, w_obj): return space.lookup(w_obj, '__set__') is not None Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Wed Feb 16 18:14:44 2005 @@ -106,21 +106,19 @@ if isinstance(w_new, Function): w_self.dict_w['__new__'] = StaticMethod(w_new) + def getdictvalue(w_self, space, attr): + try: + return w_self.dict_w[attr] + except KeyError: + return None + def lookup(w_self, key): # note that this doesn't call __get__ on the result at all space = w_self.space for w_class in w_self.mro_w: - try: - if isinstance(w_class, W_TypeObject): - return w_class.dict_w[key] - else: - try: - return space.getitem(space.getdict(w_class),space.wrap(key)) - except OperationError,e: - if not e.match(space, space.w_KeyError): - raise - except KeyError: - pass + w_value = space.getdictvalue(w_class, key) + if w_value is not None: + return w_value return None def lookup_where(w_self, key): @@ -128,17 +126,9 @@ # attribute was found space = w_self.space for w_class in w_self.mro_w: - try: - if isinstance(w_class, W_TypeObject): - return w_class, w_class.dict_w[key] - else: - try: - return w_class, space.getitem(space.getdict(w_class),space.wrap(key)) - except OperationError,e: - if not e.match(space, space.w_KeyError): - raise - except KeyError: - pass + w_value = space.getdictvalue(w_class, key) + if w_value is not None: + return w_class, w_value return None, None def check_user_subclass(w_self, w_subtype): From hpk at codespeak.net Wed Feb 16 18:56:14 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 18:56:14 +0100 (MET) Subject: [pypy-svn] r9257 - pypy/extradoc/sprintinfo Message-ID: <20050216175614.1240F27B53@code1.codespeak.net> Author: hpk Date: Wed Feb 16 18:56:13 2005 New Revision: 9257 Added: pypy/extradoc/sprintinfo/pycon2005-announcement.txt - copied unchanged from r9219, user/hpk/draft/pypy-washington-announcement.txt Log: copy to correct place From hpk at codespeak.net Wed Feb 16 19:01:25 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 19:01:25 +0100 (MET) Subject: [pypy-svn] r9258 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050216180125.E1AA727B53@code1.codespeak.net> Author: hpk Date: Wed Feb 16 19:01:25 2005 New Revision: 9258 Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Log: get rid of __getattribute__ semnatics in favour of the new getdictvalue Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Wed Feb 16 19:01:25 2005 @@ -36,18 +36,7 @@ space.setitem(w_dict, space.wrap('__name__'), w_name) space.setitem(w_dict, space.wrap('__doc__'), w_doc) - def descr_module__getattribute__(self, w_attr): - space = self.space - w_self = space.wrap(self) - attr = space.str_w(w_attr) - w_result = space.lookup(w_self, attr) - if w_result is None: - return self.get(attr) - else: - return space.get(w_result, w_self) - - def get(self, attr): - space = self.space + def getdictvalue(self, space, attr): try: return space.getitem(self.w_dict, self.space.wrap(attr)) except OperationError, e: @@ -74,10 +63,4 @@ return space.w_None else: return space.wrap(operror.application_traceback) - # produce a nice error message that shows the name of the module - try: - name = space.str_w(self.get('__name__')) - except OperationError: - name = '?' - msg = "'%s' module has no attribute '%s'" % (name, attr) - raise OperationError(space.w_AttributeError, space.wrap(msg)) + return None Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Wed Feb 16 19:01:25 2005 @@ -13,16 +13,23 @@ self.__class__.buildloaders() def get(self, name): - space = self.space + w_value = self.getdictvalue(self.space, name) + if w_value is None: + raise OperationError(space.w_AttributeError, space.wrap(name)) + return w_value + + def getdictvalue(self, space, name): try: return space.getitem(self.w_dict, space.wrap(name)) except OperationError, e: - if not self.lazy or not e.match(space, space.w_KeyError): + if not e.match(space, space.w_KeyError): raise + if not self.lazy: + return None try: loader = self.loaders[name] except KeyError: - raise OperationError(space.w_AttributeError, space.wrap(name)) + return None else: w_value = loader(space) self.space.setitem(self.w_dict, space.wrap(name), w_value) Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Wed Feb 16 19:01:25 2005 @@ -273,7 +273,6 @@ __new__ = interp2app(Module.descr_module__new__.im_func), __init__ = interp2app(Module.descr_module__init__.im_func), __dict__ = GetSetProperty(descr_get_dict), # module dictionaries are readonly attributes - __getattribute__ = interp2app(Module.descr_module__getattribute__.im_func), ) getset_func_doc = GetSetProperty(Function.fget_func_doc, From hpk at codespeak.net Wed Feb 16 22:31:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Wed, 16 Feb 2005 22:31:50 +0100 (MET) Subject: [pypy-svn] r9260 - in pypy/branch/dist-interpapp/pypy/interpreter: . test/mixedmodule Message-ID: <20050216213150.43D3727B4C@code1.codespeak.net> Author: hpk Date: Wed Feb 16 22:31:50 2005 New Revision: 9260 Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py Log: Armin, look away now :-) the interpleveldefs for newmodule's ExtModule are now much more general and flexible. See mixedmodule's __init__.py for what is possible now. The original reason for this change was that the sys module has a lot of actual state ('path', 'modules' ...) which the previous interpleveldefs' couldn't really specify. (and overriding getdictvalue() of the sysmodule in particular seems not nice). Armin, are you still reading? Then don't look at newmodule.getinterpevalloader() :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Wed Feb 16 22:31:50 2005 @@ -52,33 +52,34 @@ cls.loaders = loaders = {} pkgroot = cls.__module__ for name, spec in cls.interpleveldefs.items(): - if spec.startswith('('): - loader = getinterpevalloader(spec) - else: - loader = getinterpfileloader(pkgroot, spec) - loaders[name] = loader + loaders[name] = getinterpevalloader(pkgroot, spec) for name, spec in cls.appleveldefs.items(): loaders[name] = getappfileloader(pkgroot, spec) buildloaders = classmethod(buildloaders) -def getinterpevalloader(spec): - def ievalloader(space): - """ NOT_RPYTHON """ - d = {'space' : space} - return eval(spec, d, d) - return ievalloader - -def getinterpfileloader(pkgroot, spec): - modname, attrname = spec.split('.') - impbase = pkgroot + '.' + modname +def getinterpevalloader(pkgroot, spec): def ifileloader(space): """ NOT_RPYTHON """ - mod = __import__(impbase, None, None, [attrname]) - attr = getattr(mod, attrname) - iattr = gateway.interp2app(attr, attrname) - return space.wrap(iattr) + d = {'space' : space} + # EVIL HACK (but it works, and this is not RPython :-) + while 1: + try: + value = eval(spec, d) + except NameError, ex: + #assert name not in d, "huh, am i looping?" + name = ex.args[0].split("'")[1] # super-Evil + try: + d[name] = __import__(pkgroot+'.'+name, None, None, [name]) + except ImportError: + d[name] = __import__(name, None, None, [name]) + else: + #print spec, "->", value + if hasattr(value, 'func_code'): # semi-evil + return space.wrap(gateway.interp2app(value)) + assert value is not None + return value return ifileloader - + applevelcache = Cache() def getappfileloader(pkgroot, spec): # hum, it's a bit more involved, because we usually Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py Wed Feb 16 22:31:50 2005 @@ -2,10 +2,12 @@ class Module(ExtModule): interpleveldefs = { - '__name__' : '(space.wrap("mixedmodule"))', - '__doc__' : '(space.wrap("mixedmodule doc"))', + '__name__' : '(space.wrap("mixedmodule"))', + '__doc__' : '(space.wrap("mixedmodule doc"))', 'somefunc' : 'file1.somefunc', - 'value' : '(space.w_None)', + 'value' : '(space.w_None)', + 'path' : 'file1.initpath(space)', + 'cpypath' : 'space.wrap(sys.path)' } appleveldefs = { Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py Wed Feb 16 22:31:50 2005 @@ -2,3 +2,6 @@ def somefunc(space): return space.w_True +def initpath(space): + print "got to initpath", space + return space.wrap(3) From hpk at codespeak.net Thu Feb 17 08:27:27 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 08:27:27 +0100 (MET) Subject: [pypy-svn] r9263 - pypy/dist/pypy/tool/test Message-ID: <20050217072727.75D4D27B58@code1.codespeak.net> Author: hpk Date: Thu Feb 17 08:27:27 2005 New Revision: 9263 Modified: pypy/dist/pypy/tool/test/test_utestconvert.py pypy/dist/pypy/tool/test/test_utestconvert2.py Log: renamed test class to not be found by py.test (because now py.test recognizes functions by 'test' instead of 'test_'). Modified: pypy/dist/pypy/tool/test/test_utestconvert.py ============================================================================== --- pypy/dist/pypy/tool/test/test_utestconvert.py (original) +++ pypy/dist/pypy/tool/test/test_utestconvert.py Thu Feb 17 08:27:27 2005 @@ -2,7 +2,7 @@ from pypy.tool.utestconvert import rewrite_utest import unittest -class Testit(unittest.TestCase): +class NonpyTest(unittest.TestCase): def test(self): assert rewrite_utest("badger badger badger") == ( "badger badger badger") Modified: pypy/dist/pypy/tool/test/test_utestconvert2.py ============================================================================== --- pypy/dist/pypy/tool/test/test_utestconvert2.py (original) +++ pypy/dist/pypy/tool/test/test_utestconvert2.py Thu Feb 17 08:27:27 2005 @@ -2,7 +2,7 @@ from pypy.tool.utestconvert import rewrite_utest import unittest -class Testit(unittest.TestCase): +class NonPyTest(unittest.TestCase): def test(self): self.assertEquals(rewrite_utest("badger badger badger"), "badger badger badger") From hpk at codespeak.net Thu Feb 17 10:49:00 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 10:49:00 +0100 (MET) Subject: [pypy-svn] r9264 - in pypy/branch/dist-interpapp/pypy: interpreter module/sys2 Message-ID: <20050217094900.927FB27B75@code1.codespeak.net> Author: hpk Date: Thu Feb 17 10:49:00 2005 New Revision: 9264 Added: pypy/branch/dist-interpapp/pypy/module/sys2/ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py pypy/branch/dist-interpapp/pypy/module/sys2/app.py - copied, changed from r9258, pypy/dist/pypy/module/sysmodule.py pypy/branch/dist-interpapp/pypy/module/sys2/state.py - copied, changed from r9258, pypy/dist/pypy/module/sysinterp.py pypy/branch/dist-interpapp/pypy/module/sys2/vm.py - copied, changed from r9258, pypy/dist/pypy/module/sysinterp.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Log: a careful port (preserving history as feasible) of the module/sys*.py module parts to the new module definition structure. Currently, when you startup "py.py" then you you will have 'builtin' and 'sys2' automatically in your namespace so that you can play a bit with the two converted modules. accessing their dict completely un-lazifies them. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 10:49:00 2005 @@ -90,6 +90,9 @@ from pypy.module.builtin import Module w_name = self.wrap('builtin') self.setitem(self.w_builtins, w_name, Module(self, w_name)) + from pypy.module.sys2 import Module + w_name = self.wrap('sys2') + self.setitem(self.w_builtins, w_name, Module(self, w_name)) def make_sys(self): "NOT_RPYTHON: only for initializing the space." Added: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Thu Feb 17 10:49:00 2005 @@ -0,0 +1,54 @@ +from pypy.interpreter.newmodule import ExtModule + +class Module(ExtModule): + """Sys Builtin Module. """ + interpleveldefs = { + 'pypy_objspaceclass' : '(space.wrap(space.__class__.__name__))', + + '__name__' : '(space.wrap("sys"))', + '__doc__' : '(space.wrap("PyPy sys module"))', + + 'platform' : 'space.wrap(sys.platform)', + 'maxint' : 'space.wrap(sys.maxint)', + 'byteorder' : 'space.wrap(sys.byteorder)', + 'exec_prefix' : 'space.wrap(sys.exec_prefix)', + 'prefix' : 'space.wrap(sys.prefix)', + 'maxunicode' : 'space.wrap(sys.maxunicode)', + 'maxint' : 'space.wrap(sys.maxint)', + 'stdin' : 'space.wrap(sys.stdin)', + 'stdout' : 'space.wrap(sys.stdout)', + 'stderr' : 'space.wrap(sys.stderr)', + 'pypy_objspaceclass' : 'space.wrap(space.__class__.__name__)', + + 'path' : 'state.get(space).w_path', + 'modules' : 'state.get(space).w_modules', + 'argv' : 'state.get(space).w_argv', + 'warnoptions' : 'state.get(space).w_warnoptions', + 'builtin_module_names' : 'state.get(space).w_builtin_module_names', + 'pypy_getudir' : 'state.pypy_getudir', + + 'getdefaultencoding' : 'space.wrap(sys.getdefaultencoding())', + 'getrefcount' : 'vm.getrefcount', + '_getframe' : 'vm._getframe', + 'setrecursionlimit' : 'vm.setrecursionlimit', + 'getrecursionlimit' : 'vm.getrecursionlimit', + 'setcheckinterval' : 'vm.setcheckinterval', + 'getcheckinterval' : 'vm.getcheckinterval', + 'exc_info' : 'vm.exc_info', + 'exc_clear' : 'vm.exc_clear', + + 'executable' : 'space.wrap("py.py")', + 'copyright' : 'space.wrap("MIT-License")', + 'version_info' : 'space.wrap((2,3,4, "pypy1"))', + 'version' : 'space.wrap("2.3.4 (pypy1 build)")', + 'hexversion' : 'space.wrap(0x020304a0)', + 'ps1' : 'space.wrap(">>>>")', + 'ps2' : 'space.wrap("....")', + } + appleveldefs = { + 'displayhook' : 'app.displayhook', + '__displayhook__' : 'app.__displayhook__', + 'excepthook' : 'app.excepthook', + '__excepthook__' : 'app.__excepthook__', + 'exit' : 'app.exit', + } Copied: pypy/branch/dist-interpapp/pypy/module/sys2/app.py (from r9258, pypy/dist/pypy/module/sysmodule.py) ============================================================================== --- pypy/dist/pypy/module/sysmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/app.py Thu Feb 17 10:49:00 2005 @@ -2,36 +2,7 @@ The 'sys' module. """ -__interplevel__execfile('sysinterp.py') - -# Common data structures -from __interplevel__ import initialpath as path -from __interplevel__ import modules, argv -from __interplevel__ import warnoptions, builtin_module_names -from __interplevel__ import maxunicode - -# Objects from interpreter-level -from __interplevel__ import stdin, stdout, stderr, maxint -from __interplevel__ import platform, byteorder -from __interplevel__ import pypy_objspaceclass -from __interplevel__ import exec_prefix, prefix - -# Functions from interpreter-level -from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir -from __interplevel__ import getrecursionlimit, setrecursionlimit -from __interplevel__ import getcheckinterval, setcheckinterval -from __interplevel__ import getdefaultencoding, getrefcount - -# Dummy -executable = 'py.py' -api_version = 0 -copyright = '' -version = '2.3a0 (pypy build)' -version_info = (2, 3, 0, 'alpha', 0) -hexversion = 0x020300a0 -ps1 = '>>>> ' -ps2 = '.... ' - +import sys # XXX not called by the core yet def excepthook(exctype, value, traceback): @@ -46,6 +17,10 @@ # in normalize_exception, which is exactlylike CPython. raise SystemExit, exitcode +def setmodule(module): + """ put a module into the modules dict """ + sys.modules[module.__name__] = module + def displayhook(obj): if obj is not None: __builtins__['_'] = obj @@ -56,14 +31,13 @@ __displayhook__ = displayhook # this is exactly like in CPython def getfilesystemencoding(): - """getfilesystemencoding() -> string - -Return the encoding used to convert Unicode filenames in -operating system filenames.""" - - if platform == "win32": + """ getfilesystemencoding() -> string + Return the encoding used to convert Unicode filenames in + operating system filenames. + """ + if sys.platform == "win32": encoding = "mbcs" - elif platform == "darwin": + elif sys.platform == "darwin": encoding = "utf-8" else: encoding = None Copied: pypy/branch/dist-interpapp/pypy/module/sys2/state.py (from r9258, pypy/dist/pypy/module/sysinterp.py) ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/state.py Thu Feb 17 10:49:00 2005 @@ -3,30 +3,19 @@ """ #from pypy.interpreter.module import Module from pypy.interpreter.error import OperationError +from pypy.tool.cache import Cache -import sys as cpy_sys +import sys, os def hack_cpython_module(modname): "NOT_RPYTHON. Steal a module from CPython." cpy_module = __import__(modname, globals(), locals(), None) return cpy_module -## # to build the dictionary of the module, we get all the objects -## # accessible as 'self.xxx'. Methods are bound. -## contents = [] -## for name in cpy_module.__dict__: -## # ignore names in '_xyz' -## if not name.startswith('_') or name.endswith('_'): -## value = cpy_module.__dict__[name] -## contents.append((space.wrap(name), space.wrap(value))) -## w_contents = space.newdict(contents) -## return Module(space, space.wrap(modname), w_contents) # ____________________________________________________________ # -# List of built-in modules. -# It should contain the name of all the files 'module/*module.py'. -builtin_module_names = ['__builtin__', 'sys', 'exceptions' - ] + +builtin_module_names = ['__builtin__', 'sys', 'exceptions'] # Create the builtin_modules dictionary, mapping names to Module instances builtin_modules = {} @@ -47,156 +36,38 @@ else: builtin_module_names.append(fn) -# ____________________________________________________________ -# -# Common data structures -w_modules = space.newdict([]) -w_warnoptions = space.newlist([]) -w_argv = space.newlist([]) -builtin_module_names.sort() -w_builtin_module_names = space.newtuple([space.wrap(fn) - for fn in builtin_module_names]) - -# Initialize the default path -import os -from pypy.interpreter import autopath -srcdir = os.path.dirname(autopath.pypydir) -python_std_lib = os.path.normpath( - os.path.join(autopath.pypydir, os.pardir,'lib-python-2.3.4')) -pypy_override_lib = os.path.join(autopath.pypydir, 'lib') -assert os.path.exists(python_std_lib) -del os, autopath # XXX for the translator. Something is very wrong around here. - -w_initialpath = space.newlist([space.wrap(''), - space.wrap(pypy_override_lib), - space.wrap(python_std_lib), - ] + - [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) - -# XXX - Replace with appropriate PyPy version numbering -w_platform = space.wrap(cpy_sys.platform) -w_maxint = space.wrap(cpy_sys.maxint) -w_byteorder = space.wrap(cpy_sys.byteorder) -w_exec_prefix = space.wrap(cpy_sys.exec_prefix) -w_prefix = space.wrap(cpy_sys.prefix) -w_maxunicode = space.wrap(cpy_sys.maxunicode) -w_stdin = space.wrap(cpy_sys.stdin) -w_stdout = space.wrap(cpy_sys.stdout) -w_stderr = space.wrap(cpy_sys.stderr) - -w_pypy_objspaceclass = space.wrap(space.__class__.__name__) +builtin_module_names.sort() -# ____________________________________________________________ - -def setmodule(w_module): - """ put a module into the modules dict """ - w_name = space.getattr(w_module, space.wrap('__name__')) - space.setitem(w_modules, w_name, w_module) - -def setbuiltinmodule(w_module, name): - """ put a module into the modules builtin_modules dicts """ - if builtin_modules[name] is None: - builtin_modules[name] = space.unwrap(w_module) - else: - assert builtin_modules[name] is space.unwrap(w_module), ( - "trying to change the builtin-in module %r" % (name,)) - space.setitem(w_modules, space.wrap(name), w_module) - -##def displayhook(w_x): -## w = space.wrap -## if not space.is_true(space.is_(w_x, space.w_None)): -## w_stdout = space.getattr(space.w_sys, space.wrap('stdout')) -## try: -## w_repr = space.repr(w_x) -## except OperationError: -## w_repr = space.wrap("! __repr__ raised an exception") -## w_repr = space.add(w_repr, space.wrap("\n")) -## space.call_method(w_stdout, 'write', -## space.setitem(space.w_builtins, w('_'), w_x) - -def _getframe(w_depth=0): - depth = space.int_w(w_depth) - try: - f = space.getexecutioncontext().framestack.top(depth) - except IndexError: - raise OperationError(space.w_ValueError, - space.wrap("call stack is not deep enough")) - except ValueError: - raise OperationError(space.w_ValueError, - space.wrap("frame index must not be negative")) - return space.wrap(f) - -# directly from the C code in ceval.c, might be moved somewhere else. - -def setrecursionlimit(w_new_limit): - """setrecursionlimit(n) - -Set the maximum depth of the Python interpreter stack to n. This -limit prevents infinite recursion from causing an overflow of the C -stack and crashing Python. The highest possible limit is platform -dependent.""" - new_limit = space.int_w(w_new_limit) - if new_limit <= 0: - raise OperationError(space.w_ValueError, - space.wrap("recursion limit must be positive")) - # global recursion_limit - # we need to do it without writing globals. - space.recursion_limit = new_limit - -def getrecursionlimit(): - """getrecursionlimit() - -Return the current value of the recursion limit, the maximum depth -of the Python interpreter stack. This limit prevents infinite -recursion from causing an overflow of the C stack and crashing Python.""" - - return space.newint(space.recursion_limit) - -checkinterval = 100 - -def setcheckinterval(w_interval): - """setcheckinterval(n) - -Tell the Python interpreter to check for asynchronous events every -n instructions. This also affects how often thread switches occur.""" - - space.sys.checkinterval = space.int_w(w_interval) - -def getcheckinterval(): - """getcheckinterval() -> current check interval; see setcheckinterval().""" - return space.newint(checkinterval) - - -def exc_info(): - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.newtuple([space.w_None,space.w_None,space.w_None]) - else: - return space.newtuple([operror.w_type,operror.w_value, - space.wrap(operror.application_traceback)]) - -def exc_clear(): - operror = space.getexecutioncontext().sys_exc_info() - if operror is not None: - operror.clear(space) +class State: + def __init__(self, space, stuff=None): + self.space = space + self.w_builtin_module_names = space.newlist( + [space.wrap(fn) for fn in builtin_module_names]) + self.w_modules = space.newdict([]) + self.w_warnoptions = space.newlist([]) + self.w_argv = space.newlist([]) + self.setinitialpath(space) + + def setinitialpath(self, space): + # Initialize the default path + from pypy.interpreter import autopath + srcdir = os.path.dirname(autopath.pypydir) + python_std_lib = os.path.normpath( + os.path.join(autopath.pypydir, os.pardir,'lib-python-2.3.4')) + pypy_override_lib = os.path.join(autopath.pypydir, 'lib') + assert os.path.exists(python_std_lib) + self.w_path = space.newlist([space.wrap(''), + space.wrap(pypy_override_lib), + space.wrap(python_std_lib), + ] + + [space.wrap(p) for p in sys.path if p!= srcdir]) + +statecache = Cache() +def get(space): + return space.loadfromcache(space, State, statecache) -def pypy_getudir(): +def pypy_getudir(space): """NOT_RPYTHON""" from pypy.tool.udir import udir return space.wrap(str(udir)) -def getdefaultencoding(): - """getdefaultencoding() -> return the default encoding used for UNICODE""" - return space.wrap(cpy_sys.getdefaultencoding()) - -def getrefcount(w_obj): - """getrefcount(object) -> integer - -Return the reference count of object. The count returned is generally -one higher than you might expect, because it includes the (temporary) -reference as an argument to getrefcount(). -""" - # From the results i get when using this i need to apply a fudge - # value of 6 to get results comparable to cpythons. /Arre - return space.wrap(cpy_sys.getrefcount(w_obj) - 6) - Copied: pypy/branch/dist-interpapp/pypy/module/sys2/vm.py (from r9258, pypy/dist/pypy/module/sysinterp.py) ============================================================================== --- pypy/dist/pypy/module/sysinterp.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/vm.py Thu Feb 17 10:49:00 2005 @@ -1,97 +1,10 @@ """ Implementation of interpreter-level 'sys' routines. """ -#from pypy.interpreter.module import Module from pypy.interpreter.error import OperationError - -import sys as cpy_sys - -def hack_cpython_module(modname): - "NOT_RPYTHON. Steal a module from CPython." - cpy_module = __import__(modname, globals(), locals(), None) - return cpy_module -## # to build the dictionary of the module, we get all the objects -## # accessible as 'self.xxx'. Methods are bound. -## contents = [] -## for name in cpy_module.__dict__: -## # ignore names in '_xyz' -## if not name.startswith('_') or name.endswith('_'): -## value = cpy_module.__dict__[name] -## contents.append((space.wrap(name), space.wrap(value))) -## w_contents = space.newdict(contents) -## return Module(space, space.wrap(modname), w_contents) - -# ____________________________________________________________ -# -# List of built-in modules. -# It should contain the name of all the files 'module/*module.py'. -builtin_module_names = ['__builtin__', 'sys', 'exceptions' - ] - -# Create the builtin_modules dictionary, mapping names to Module instances -builtin_modules = {} -for fn in builtin_module_names: - builtin_modules[fn] = None - -# The following built-in modules are not written in PyPy, so we -# steal them from Python. -for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos', - 'math', '_codecs', 'array', - '_random', '_sre', 'time', '_socket', 'errno', - 'marshal', 'binascii', 'parser']: - if fn not in builtin_modules: - try: - builtin_modules[fn] = hack_cpython_module(fn) - except ImportError: - pass - else: - builtin_module_names.append(fn) +import sys # ____________________________________________________________ -# -# Common data structures -w_modules = space.newdict([]) -w_warnoptions = space.newlist([]) -w_argv = space.newlist([]) -builtin_module_names.sort() -w_builtin_module_names = space.newtuple([space.wrap(fn) - for fn in builtin_module_names]) - -# Initialize the default path -import os -from pypy.interpreter import autopath -srcdir = os.path.dirname(autopath.pypydir) -python_std_lib = os.path.normpath( - os.path.join(autopath.pypydir, os.pardir,'lib-python-2.3.4')) -pypy_override_lib = os.path.join(autopath.pypydir, 'lib') -assert os.path.exists(python_std_lib) -del os, autopath # XXX for the translator. Something is very wrong around here. - -w_initialpath = space.newlist([space.wrap(''), - space.wrap(pypy_override_lib), - space.wrap(python_std_lib), - ] + - [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) - -# XXX - Replace with appropriate PyPy version numbering -w_platform = space.wrap(cpy_sys.platform) -w_maxint = space.wrap(cpy_sys.maxint) -w_byteorder = space.wrap(cpy_sys.byteorder) -w_exec_prefix = space.wrap(cpy_sys.exec_prefix) -w_prefix = space.wrap(cpy_sys.prefix) -w_maxunicode = space.wrap(cpy_sys.maxunicode) -w_stdin = space.wrap(cpy_sys.stdin) -w_stdout = space.wrap(cpy_sys.stdout) -w_stderr = space.wrap(cpy_sys.stderr) - -w_pypy_objspaceclass = space.wrap(space.__class__.__name__) - -# ____________________________________________________________ - -def setmodule(w_module): - """ put a module into the modules dict """ - w_name = space.getattr(w_module, space.wrap('__name__')) - space.setitem(w_modules, w_name, w_module) def setbuiltinmodule(w_module, name): """ put a module into the modules builtin_modules dicts """ @@ -102,19 +15,7 @@ "trying to change the builtin-in module %r" % (name,)) space.setitem(w_modules, space.wrap(name), w_module) -##def displayhook(w_x): -## w = space.wrap -## if not space.is_true(space.is_(w_x, space.w_None)): -## w_stdout = space.getattr(space.w_sys, space.wrap('stdout')) -## try: -## w_repr = space.repr(w_x) -## except OperationError: -## w_repr = space.wrap("! __repr__ raised an exception") -## w_repr = space.add(w_repr, space.wrap("\n")) -## space.call_method(w_stdout, 'write', -## space.setitem(space.w_builtins, w('_'), w_x) - -def _getframe(w_depth=0): +def _getframe(space, w_depth=0): depth = space.int_w(w_depth) try: f = space.getexecutioncontext().framestack.top(depth) @@ -128,7 +29,7 @@ # directly from the C code in ceval.c, might be moved somewhere else. -def setrecursionlimit(w_new_limit): +def setrecursionlimit(space, w_new_limit): """setrecursionlimit(n) Set the maximum depth of the Python interpreter stack to n. This @@ -141,62 +42,54 @@ space.wrap("recursion limit must be positive")) # global recursion_limit # we need to do it without writing globals. - space.recursion_limit = new_limit + space.sys.recursion_limit = new_limit -def getrecursionlimit(): +def getrecursionlimit(space): """getrecursionlimit() + Return the current value of the recursion limit, the maximum depth + of the Python interpreter stack. This limit prevents infinite + recursion from causing an overflow of the C stack and crashing Python. + """ -Return the current value of the recursion limit, the maximum depth -of the Python interpreter stack. This limit prevents infinite -recursion from causing an overflow of the C stack and crashing Python.""" - - return space.newint(space.recursion_limit) + return space.wrap(space.sys.recursion_limit) checkinterval = 100 -def setcheckinterval(w_interval): +def setcheckinterval(space, w_interval): """setcheckinterval(n) + Tell the Python interpreter to check for asynchronous events every + n instructions. This also affects how often thread switches occur.""" + space.sys.checkinterval = space.int_w(w_interval) -Tell the Python interpreter to check for asynchronous events every -n instructions. This also affects how often thread switches occur.""" - - space.sys.checkinterval = space.int_w(w_interval) - -def getcheckinterval(): +def getcheckinterval(space): """getcheckinterval() -> current check interval; see setcheckinterval().""" - return space.newint(checkinterval) + return space.wrap(space.sys.checkinterval) - -def exc_info(): +def exc_info(space): operror = space.getexecutioncontext().sys_exc_info() if operror is None: return space.newtuple([space.w_None,space.w_None,space.w_None]) else: - return space.newtuple([operror.w_type,operror.w_value, + return space.newtuple([operror.w_type, operror.w_value, space.wrap(operror.application_traceback)]) -def exc_clear(): +def exc_clear(space): operror = space.getexecutioncontext().sys_exc_info() if operror is not None: operror.clear(space) -def pypy_getudir(): +def pypy_getudir(space): """NOT_RPYTHON""" from pypy.tool.udir import udir return space.wrap(str(udir)) -def getdefaultencoding(): - """getdefaultencoding() -> return the default encoding used for UNICODE""" - return space.wrap(cpy_sys.getdefaultencoding()) - -def getrefcount(w_obj): +def getrefcount(space, w_obj): """getrefcount(object) -> integer - -Return the reference count of object. The count returned is generally -one higher than you might expect, because it includes the (temporary) -reference as an argument to getrefcount(). -""" + Return the reference count of object. The count returned is generally + one higher than you might expect, because it includes the (temporary) + reference as an argument to getrefcount(). + """ # From the results i get when using this i need to apply a fudge # value of 6 to get results comparable to cpythons. /Arre - return space.wrap(cpy_sys.getrefcount(w_obj) - 6) + return space.wrap(sys.getrefcount(w_obj) - 6) From hpk at codespeak.net Thu Feb 17 11:26:49 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 11:26:49 +0100 (MET) Subject: [pypy-svn] r9265 - pypy/branch/dist-interpapp/pypy/module/sys2 Message-ID: <20050217102649.D12AC27B96@code1.codespeak.net> Author: hpk Date: Thu Feb 17 11:26:49 2005 New Revision: 9265 Modified: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Log: specialize the new sys module to provide the dynamic attributes exc_value/exc_type/exc_traceback. (the module app/interplevel-defs cannot deal with dynamic values, should they?) Modified: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Thu Feb 17 11:26:49 2005 @@ -52,3 +52,28 @@ '__excepthook__' : 'app.__excepthook__', 'exit' : 'app.exit', } + + def getdictvalue(self, space, attr): + """ specialize access to dynamic exc_* attributes. """ + value = ExtModule.getdictvalue(self, space, attr) + if value is not None: + return value + if attr == 'exc_type': + operror = space.getexecutioncontext().sys_exc_info() + if operror is None: + return space.w_None + else: + return operror.w_type + elif attr == 'exc_value': + operror = space.getexecutioncontext().sys_exc_info() + if operror is None: + return space.w_None + else: + return operror.w_value + elif attr == 'exc_traceback': + operror = space.getexecutioncontext().sys_exc_info() + if operror is None: + return space.w_None + else: + return space.wrap(operror.application_traceback) + return None From ac at codespeak.net Thu Feb 17 12:11:12 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Thu, 17 Feb 2005 12:11:12 +0100 (MET) Subject: [pypy-svn] r9266 - pypy/dist/pypy/objspace/std Message-ID: <20050217111112.A469C27B90@code1.codespeak.net> Author: ac Date: Thu Feb 17 12:11:12 2005 New Revision: 9266 Modified: pypy/dist/pypy/objspace/std/dictobject.py pypy/dist/pypy/objspace/std/listobject.py Log: Track recursion in repr() using a per ExecutionContext dictionary. Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Thu Feb 17 12:11:12 2005 @@ -246,23 +246,27 @@ # The fix is to move this to dicttype.py, and do a # multimethod lookup mapping str to StdObjSpace.str # This cannot happen until multimethods are fixed. See dicttype.py -def app_str__Dict(d): - global _currently_in_repr - if len(d) == 0: - return '{}' - if '_currently_in_repr' not in globals(): - _currently_in_repr = {} - if id(d) in _currently_in_repr: - return '{...}' - try: - _currently_in_repr[id(d)] = 1 +def app_dictstr(d): items = [] for k, v in d.iteritems(): items.append(repr(k) + ": " + repr(v)) return "{" + ', '.join(items) + "}" + +dictstr = gateway.app2interp(app_dictstr) + +def str__Dict(space, w_dict): + if w_dict.used == 0: + return space.wrap('{}') + d = space.get_ec_state_dict().setdefault('Py_Repr', {}) + dict_id = space.int_w(space.id(w_dict)) + if dict_id in d: + return space.wrap('{...}') + d[dict_id] = 1 + try: + return dictstr(space, w_dict) finally: - del _currently_in_repr[id(d)] + del d[dict_id] -repr__Dict = str__Dict = gateway.app2interp(app_str__Dict) +repr__Dict = str__Dict from pypy.objspace.std import dicttype register_all(vars(), dicttype) Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Thu Feb 17 12:11:12 2005 @@ -278,19 +278,22 @@ items[start+i*step] = sequence2[i] return space.w_None -def app_repr__List(l): - global _currently_in_repr - if len(l) == 0: - return '[]' - if '_currently_in_repr' not in globals(): - _currently_in_repr = {} - if id(l) in _currently_in_repr: - return '[...]' +def app_listrepr(l): + 'The app-level part of repr().' + return "[" + ", ".join([repr(x) for x in l]) + ']' + +def repr__List(space, w_list): + if w_list.ob_size == 0: + return space.wrap('[]') + d = space.get_ec_state_dict().setdefault('Py_Repr', {}) + list_id = space.int_w(space.id(w_list)) + if list_id in d: + return space.wrap('[...]') + d[list_id] = 1 try: - _currently_in_repr[id(l)] = 1 - return "[" + ", ".join([repr(x) for x in l]) + ']' + return listrepr(space, w_list) finally: - del _currently_in_repr[id(l)] + del d[list_id] def hash__List(space,w_list): raise OperationError(space.w_TypeError,space.wrap("list objects are unhashable")) From sanxiyn at codespeak.net Thu Feb 17 13:25:00 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Thu, 17 Feb 2005 13:25:00 +0100 (MET) Subject: [pypy-svn] r9267 - in pypy/dist/pypy/translator/llvm: . test Message-ID: <20050217122500.0D51027B80@code1.codespeak.net> Author: sanxiyn Date: Thu Feb 17 13:24:59 2005 New Revision: 9267 Modified: pypy/dist/pypy/translator/llvm/build_llvm_module.py pypy/dist/pypy/translator/llvm/test/test_genllvm.py Log: Include /usr/include/python2.3, not /usr/include/python. As llvmc problem is now worked around and all tests pass for me, re-enable LLVM tests. Modified: pypy/dist/pypy/translator/llvm/build_llvm_module.py ============================================================================== --- pypy/dist/pypy/translator/llvm/build_llvm_module.py (original) +++ pypy/dist/pypy/translator/llvm/build_llvm_module.py Thu Feb 17 13:24:59 2005 @@ -40,7 +40,7 @@ llvmfile.purebasename), "as %s.s -o %s.o" % (llvmfile.purebasename, llvmfile.purebasename)] - ops2 = ["gcc -c -fPIC -I/usr/include/python %s.c" % pyxfile.purebasename, + ops2 = ["gcc -c -fPIC -I/usr/include/python2.3 %s.c" % pyxfile.purebasename, "gcc -shared %s.o %s.o -o %s.so" % (llvmfile.purebasename, modname, modname)] try: Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/test_genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Thu Feb 17 13:24:59 2005 @@ -11,7 +11,7 @@ from pypy.translator.llvm.test import llvmsnippet def setup_module(mod): - mod.llvm_found = 0 #is_on_path("llvm-as") + mod.llvm_found = is_on_path("llvm-as") def compile_function(function, annotate): t = Translator(function) From pedronis at codespeak.net Thu Feb 17 15:43:15 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 15:43:15 +0100 (MET) Subject: [pypy-svn] r9269 - in pypy/branch/dist-interpapp/pypy: interpreter translator Message-ID: <20050217144315.567AD27B48@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 15:43:15 2005 New Revision: 9269 Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/translator/genc.py Log: (translate_pypy -no-a) add, adjust some NOT_RPYTHON annotations fix unbound local bug spotted by translate_pypy in genc ignore classmethods marked as NOT_RPYTHON Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Thu Feb 17 15:43:15 2005 @@ -5,15 +5,19 @@ import inspect -class ExtModule(Module): +class ExtModule(Module): + + NOT_RPYTHON_ATTRIBUTES = ['loaders'] + def __init__(self, space, w_name): """ NOT_RPYTHON """ Module.__init__(self, space, w_name) self.lazy = True self.__class__.buildloaders() - def get(self, name): - w_value = self.getdictvalue(self.space, name) + def get(self, name): + space = self.space + w_value = self.getdictvalue(space, name) if w_value is None: raise OperationError(space.w_AttributeError, space.wrap(name)) return w_value @@ -57,9 +61,9 @@ loaders[name] = getappfileloader(pkgroot, spec) buildloaders = classmethod(buildloaders) -def getinterpevalloader(pkgroot, spec): +def getinterpevalloader(pkgroot, spec): + """ NOT_RPYTHON """ def ifileloader(space): - """ NOT_RPYTHON """ d = {'space' : space} # EVIL HACK (but it works, and this is not RPython :-) while 1: @@ -81,7 +85,8 @@ return ifileloader applevelcache = Cache() -def getappfileloader(pkgroot, spec): +def getappfileloader(pkgroot, spec): + """ NOT_RPYTHON """ # hum, it's a bit more involved, because we usually # want the import at applevel modname, attrname = spec.split('.') @@ -89,10 +94,10 @@ mod = __import__(impbase, None, None, ['attrname']) app = applevelcache.getorbuild(mod, buildapplevelfrommodule, None) def afileloader(space): - """ NOT_RPYTHON """ return app.wget(space, attrname) return afileloader -def buildapplevelfrommodule(mod, _): +def buildapplevelfrommodule(mod, _): + """ NOT_RPYTHON """ source = inspect.getsource(mod) return gateway.applevel(source) Modified: pypy/branch/dist-interpapp/pypy/translator/genc.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/translator/genc.py (original) +++ pypy/branch/dist-interpapp/pypy/translator/genc.py Thu Feb 17 15:43:15 2005 @@ -321,6 +321,8 @@ if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen: print value continue + if isinstance(value, classmethod) and value.__get__(cls).__doc__.lstrip().startswith("NOT_RPYTHON"): + continue if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: print value continue From pedronis at codespeak.net Thu Feb 17 16:02:42 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 16:02:42 +0100 (MET) Subject: [pypy-svn] r9270 - in pypy/branch/dist-interpapp/pypy: interpreter/test/mixedmodule module/builtin module/sys2 Message-ID: <20050217150242.45B9027B76@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 16:02:42 2005 New Revision: 9270 Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/ (props changed) pypy/branch/dist-interpapp/pypy/module/builtin/ (props changed) pypy/branch/dist-interpapp/pypy/module/sys2/ (props changed) Log: set ignore prop From hpk at codespeak.net Thu Feb 17 16:34:53 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 16:34:53 +0100 (MET) Subject: [pypy-svn] r9271 - in pypy/branch/dist-interpapp/pypy: interpreter module/builtin module/sys2 objspace/std Message-ID: <20050217153453.ED25227B71@code1.codespeak.net> Author: hpk Date: Thu Feb 17 16:34:53 2005 New Revision: 9271 Added: pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py - copied unchanged from r9270, pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Removed: pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/py.py pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py pypy/branch/dist-interpapp/pypy/module/builtin/importing.py pypy/branch/dist-interpapp/pypy/module/builtin/operation.py pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py pypy/branch/dist-interpapp/pypy/module/sys2/app.py pypy/branch/dist-interpapp/pypy/module/sys2/state.py pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py Log: - switch the new builtin and sys modules with (specified and handled by interpreter/newmodule's mechanism) into full existence, the old modules are not used at all anymore (but still existent in the file system) - interpreter/extmodule is renamed to interpreter/oldextmodule.py and will soon go away! - lots and lots of little fixes everywhere (especially in the new builtin/sys modules) - there are issues left (and i didn't even try to run any tests :-), most notably the __builtins__, f_builtins and space.w_builtins thingies. We need to revisit systematically all lines of code that deal with builtins. - LOAD_GLOBAL/LOAD_NAME now uses a common helper getbuiltin(space, w_name) that looks up builtins on the module rather than the dictionary, because only the module's getdictvalue() invokes the lazy-loading logic. (we use plain wrapped dicts for the module's globals) - i am sure the objspace-initialization can be cleaned up now considerably. - there is a problem with _classobj which you'll discover if you do py.py -c "import __builtin__ ; __builtin__.__dict__" but i haven't figured out this one yet. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 16:34:53 2005 @@ -59,21 +59,28 @@ "NOT_RPYTHON: only for initializing the space." # initializing builtins may require creating a frame which in # turn already accesses space.w_builtins, provide a dummy one ... - self.w_builtins = self.newdict([]) - - # insert stuff into the newly-made builtins - for key, w_value in for_builtins.items(): - self.setitem(self.w_builtins, self.wrap(key), w_value) - - assert not hasattr(self, 'builtin') - if not hasattr(self, 'sys'): - self.make_sys() - - from pypy.interpreter.extmodule import BuiltinModule + # XXX TEMPORARY - # the builtins are iteratively initialized - self.builtin = BuiltinModule(self, '__builtin__', self.w_builtins) - self.w_builtin = self.wrap(self.builtin) + from pypy.module.sys2 import Module + w_name = self.wrap('sys') + self.sys = Module(self, w_name) + self.w_sys = self.wrap(self.sys) + + w_modules = self.sys.get('modules') + self.setitem(w_modules, w_name, self.w_sys) + print "initialized", self.w_sys + from pypy.module.builtin import Module + w_name = self.wrap('__builtin__') + self.builtin = Module(self, w_name) + self.w_builtin = self.wrap(self.builtin) + #self.w_builtins = self.builtin.w_dict + self.setitem(w_modules, w_name, self.w_builtin) + self.setitem(self.builtin.w_dict, self.wrap('__builtins__'), self.w_builtin) + print "initialized", self.w_builtin + + # do we need this? + #for key, w_value in for_builtins.items(): + # self.setitem(self.builtin.w_dict, self.wrap(key), w_value) # initialize with "bootstrap types" from objspace (e.g. w_None) for name, value in self.__dict__.items(): @@ -82,27 +89,10 @@ if name.startswith('builtin') or name.startswith('sys'): continue #print "setitem: space instance %-20s into builtins" % name - self.setitem(self.w_builtins, self.wrap(name), value) + self.setitem(self.builtin.w_dict, self.wrap(name), value) + print "finished make_builtins", self - self.sys.setbuiltinmodule(self.w_builtin, '__builtin__') - - # XXX TEMPORARY - from pypy.module.builtin import Module - w_name = self.wrap('builtin') - self.setitem(self.w_builtins, w_name, Module(self, w_name)) - from pypy.module.sys2 import Module - w_name = self.wrap('sys2') - self.setitem(self.w_builtins, w_name, Module(self, w_name)) - - def make_sys(self): - "NOT_RPYTHON: only for initializing the space." - from pypy.interpreter.extmodule import BuiltinModule - assert not hasattr(self, 'sys') - self.sys = BuiltinModule(self, 'sys') - self.w_sys = self.wrap(self.sys) - self.sys.setbuiltinmodule(self.w_sys, 'sys') - - def get_builtin_module(self, name): + def XXXget_builtin_module(self, name): if name not in self.sys.builtin_modules: return None module = self.sys.builtin_modules[name] Modified: pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py Thu Feb 17 16:34:53 2005 @@ -26,10 +26,11 @@ locals.executioncontext = previous_ec def get_w_builtins(self): - if self.framestack.empty(): - return self.space.w_builtins - else: - return self.framestack.top().w_builtins + # XXX sort out __builtins__ issue + #if self.framestack.empty(): + return self.space.w_builtin + #else: + # return self.framestack.top().w_builtins def make_standard_w_globals(self): "Create a new empty 'globals' dictionary." Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/interpreter/extmodule.py Thu Feb 17 16:34:53 2005 +++ (empty file) @@ -1,180 +0,0 @@ -""" - -Helpers to build extension modules. - -""" - -from __future__ import generators # for generators.compiler_flag -import os, sys -import autopath -from pypy.interpreter import gateway -from pypy.interpreter.error import OperationError -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.function import Function -from pypy.interpreter.module import Module - -class interplevelimport_interp2app(gateway.interp2app): - - def __init__(self, f, w_globals): - "NOT_RPYTHON" - gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False) - self.w_globals = w_globals - - def _getglobals(self, space): - "NOT_RPYTHON" - return self.w_globals - - -class BuiltinModule(Module): - """A Module subclass specifically for built-in modules.""" - - # '__builtins__' is stored in self.__dict__ by - # self.interplevel{exec,eval,execfile}() - NOT_RPYTHON_ATTRIBUTES = ['__builtins__'] - - def __init__(self, space, modulename, w_dict=None, sourcefile=None): - """NOT_RPYTHON - Load the named built-in module, by default from the source file - 'pypy/module/module.py', which is app-level Python code - with a few special features that allow it to include interp-level - bits. (See pypy/module/test/foomodule.py) - - The module has two parts: the interp-level objects, stored as - attributes of 'self', and the app-level objects, stored in the - dictionary 'self.w_dict'. The app-level definition of the module - runs with 'self.w_dict' as globals. The interp-level bits are - executed with 'self.__dict__' as globals, i.e. they can read and - change the attributes of 'self' as global variables. - """ - Module.__init__(self, space, space.wrap(modulename), w_dict) - w_dict = self.w_dict - - # Compile the xxxmodule.py source file - self.__name__ = 'interpreter-level %s' % modulename - self.__file__ = sourcefile or os.path.join(autopath.pypydir, 'module', - modulename+'module.py') - space.setitem(w_dict, space.wrap('__file__'), - space.wrap(self.__file__)) - f = open(self.__file__, 'r') - modulesource = f.read() - f.close() - code = compile(modulesource, self.__file__, 'exec', - generators.compiler_flag) - pycode = PyCode(space)._from_code(code) - - # Set the hooks that call back from app-level to interp-level - w_builtins = space.w_builtins - self.__saved_hooks = {} - newhooks = {} - - for name, impl in [ - ('__interplevel__exec', self.interplevelexec.im_func), - ('__interplevel__eval', self.interpleveleval.im_func), - ('__interplevel__execfile', self.interplevelexecfile.im_func), - ('__import__', self.interplevelimport.im_func)]: - hook = gateway.interp2app_temp(impl).get_method(self) - w_name = space.wrap(name) - try: - self.__saved_hooks[name] = space.getitem(w_builtins, w_name) - except OperationError: - pass - w_hook = space.wrap(hook) - space.setitem(w_builtins, w_name, w_hook) - newhooks[name] = w_hook - space.setitem(self.w_dict, space.wrap('__builtins__'), - space.w_builtins) - - # Temporarily install an '__applevel__' pseudo-module - sys.modules['__applevel__'] = AppModuleHack(self) - - # Run the app-level module definition (xxxmodule.py) - pycode.exec_code(space, w_dict, w_dict) - - # Remove the pseudo-module - del sys.modules['__applevel__'] - try: - del self.__applevel__ - except AttributeError: - pass - - # Remove/restore the hooks unless they have been modified at app-level - for name, w_hook in newhooks.items(): - w_name = space.wrap(name) - try: - w_current = space.getitem(w_builtins, w_name) - except OperationError: - pass - else: - if space.is_true(space.is_(w_current, w_hook)): - if name in self.__saved_hooks: - space.setitem(w_builtins, w_name, - self.__saved_hooks[name]) - else: - space.delitem(w_builtins, w_name) - del self.__saved_hooks - - def interplevelexec(self, w_codestring): - "NOT_RPYTHON: 'exec' a string at interp-level." - codestring = self.space.str_w(w_codestring) - exec codestring in self.__dict__ - return self.space.w_None - - def interpleveleval(self, w_codestring): - """NOT_RPYTHON: 'eval' a string at interp-level. The result must - be None or a wrapped object, which is returned to the caller.""" - space = self.space - codestring = space.str_w(w_codestring) - w_result = eval(codestring, self.__dict__) - if w_result is None: - w_result = space.w_None # else assume that it is already wrapped - return w_result - - def interplevelexecfile(self, w_filename): - """NOT_RPYTON: 'exec' a file at interp-level. The file should be in - the same directory as the xxxmodule.py source file of the module.""" - filename = self.space.str_w(w_filename) - filename = os.path.join(os.path.dirname(self.__file__), filename) - execfile(filename, self.__dict__) - return self.space.w_None - - def interplevelimport(self, w_modulename, w_globals, w_locals, w_fromlist): - """NOT_RPYTHON: Hook for 'from __interplevel__ import something'. - If there is a wrapped interp-level object 'w_something', returns it. - If there is an interp-level function 'def something(w_x, w_y...)', - build an appropriate gateway and returns it. - """ - space = self.space - w = space.wrap - if space.is_true(space.eq(w_modulename, w('__interplevel__'))): - if w_fromlist == space.w_None: - raise ImportError, "must use 'from __interplevel__ import xx'" - for w_name in space.unpacktuple(w_fromlist): - name = space.str_w(w_name) - if not hasattr(self, 'w_' + name): - f = getattr(self, name) - func = interplevelimport_interp2app(f, self.w_dict) - w_result = space.wrap(func) - else: - w_result = getattr(self, 'w_' + name) - space.setitem(self.w_dict, w_name, w_result) - return space.wrap(self) - else: - return space.call_function(self.__saved_hooks['__import__'], - w_modulename, w_globals, - w_locals, w_fromlist) - -class AppModuleHack: - """NOT_RPYTHON - For interp-level convenience: 'from __applevel__ import func' - imports the app-level function 'func' via an appropriate gateway. - """ - def __init__(self, builtinmodule): - self.space = builtinmodule.space - self.w_dict = builtinmodule.w_dict - def __getattr__(self, name): - if name.startswith('__'): - raise AttributeError, name - w_func = self.space.getitem(self.w_dict, self.space.wrap(name)) - def caller(*args): - return self.space.call_function(w_func, *args) - return caller Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Thu Feb 17 16:34:53 2005 @@ -35,8 +35,10 @@ except KeyError: return None else: + print "trying to load", name w_value = loader(space) - self.space.setitem(self.w_dict, space.wrap(name), w_value) + #print "loaded", w_value + space.setitem(self.w_dict, space.wrap(name), w_value) return w_value def getdict(self): Modified: pypy/branch/dist-interpapp/pypy/interpreter/py.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/py.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/py.py Thu Feb 17 16:34:53 2005 @@ -56,14 +56,14 @@ if Options.command: args = ['-c'] + Options.command[1:] for arg in args: - space.call_method(space.sys.w_argv, 'append', space.wrap(arg)) + space.call_method(space.sys.get('argv'), 'append', space.wrap(arg)) try: if Options.command: main.run_string(Options.command[0], '', space) elif args: main.run_file(args[0], space) else: - space.call_method(space.sys.w_argv, 'append', space.wrap('')) + space.call_method(space.sys.get('argv'), 'append', space.wrap('')) go_interactive = 1 banner = None except error.OperationError, operationerr: Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Thu Feb 17 16:34:53 2005 @@ -33,7 +33,7 @@ self.blockstack = Stack() self.last_exception = None self.next_instr = 0 - self.w_builtins = self.space.w_builtins + #self.w_builtins = self.space.w_builtins # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS. # class bodies only have CO_NEWLOCALS. if code.dictscope_needed(): Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Thu Feb 17 16:34:53 2005 @@ -346,7 +346,7 @@ w_prog = f.valuestack.pop() w_compile_flags = f.space.wrap(f.get_compile_flags()) w_resulttuple = prepare_exec(f.space, f.space.wrap(f), w_prog, w_globals, w_locals, - w_compile_flags) + w_compile_flags, f.space.builtin.w_dict) w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3) plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) @@ -379,7 +379,7 @@ w_bases = f.valuestack.pop() w_name = f.valuestack.pop() w_metaclass = find_metaclass(f.space, w_bases, - w_methodsdict, f.w_globals, f.w_builtins) + w_methodsdict, f.w_globals, f.space.builtin) w_newclass = f.space.call_function(w_metaclass, w_name, w_bases, w_methodsdict) f.valuestack.push(w_newclass) @@ -436,27 +436,21 @@ w_varname = f.getname_w(nameindex) if f.w_globals is f.w_locals: - try_list_w = [f.w_globals, f.w_builtins] + try_list_w = [f.w_globals] else: - try_list_w = [f.w_locals, f.w_globals, f.w_builtins] + try_list_w = [f.w_locals, f.w_globals] - w_value = None for wrapped in try_list_w: try: w_value = f.space.getitem(wrapped, w_varname) - f.valuestack.push(w_value) - return - + break except OperationError, e: if not e.match(f.space, f.space.w_KeyError): raise - message = "name '%s' is not defined" % f.space.str_w(w_varname) - w_exc_type = f.space.w_NameError - w_exc_value = f.space.wrap(message) - raise OperationError(w_exc_type, w_exc_value) - - + else: + w_value = getbuiltin(f.space, w_varname) + f.valuestack.push(w_value) # XXX the implementation can be pushed back into app-space as an # when exception handling begins to behave itself. For now, it # was getting on my nerves -- mwh @@ -473,16 +467,7 @@ if not e.match(f.space, f.space.w_KeyError): raise # we got a KeyError, now look in the built-ins - try: - w_value = f.space.getitem(f.w_builtins, w_varname) - except OperationError, e: - # catch KeyErrors again - if not e.match(f.space, f.space.w_KeyError): - raise - message = "global name '%s' is not defined" % f.space.str_w(w_varname) - w_exc_type = f.space.w_NameError - w_exc_value = f.space.wrap(message) - raise OperationError(w_exc_type, w_exc_value) + w_value = getbuiltin(f.space, w_varname) f.valuestack.push(w_value) def DELETE_FAST(f, varindex): @@ -564,9 +549,9 @@ modulename = f.space.str_w(w_modulename) w_fromlist = f.valuestack.pop() try: - w_import = space.getitem(f.w_builtins, space.wrap("__import__")) + w_import = space.builtin.get('__import__') except OperationError, e: - if not e.match(space, space.w_KeyError): + if not e.match(space, space.w_AttributeError): raise raise OperationError(space.w_ImportError, space.wrap("__import__ not found")) @@ -736,6 +721,19 @@ cls.dispatch_table = dispatch_table +def getbuiltin(space, w_varname): + varname = space.str_w(w_varname) + try: + return space.builtin.get(space.str_w(w_varname)) + except OperationError, e: + # catch AttributeErrors + if not e.match(space, space.w_AttributeError): + raise + message = "global name '%s' is not defined" % space.str_w(w_varname) + w_exc_type = space.w_NameError + w_exc_value = space.wrap(message) + raise OperationError(w_exc_type, w_exc_value) + ### helpers written at the application-level ### # Some of these functions are expected to be generally useful if other # parts of the code needs to do the same thing as a non-trivial opcode, @@ -788,7 +786,7 @@ pass return softspace - def find_metaclass(bases, namespace, globals, builtins): + def find_metaclass(bases, namespace, globals, builtin): if '__metaclass__' in namespace: return namespace['__metaclass__'] elif len(bases) > 0: @@ -799,10 +797,11 @@ return type(base) elif '__metaclass__' in globals: return globals['__metaclass__'] - elif '__metaclass__' in builtins: - return builtins['__metaclass__'] - else: - return type + else: + try: + builtin.__metaclass__ + except AttributeError: + return type def import_all_from(module, into_locals): try: @@ -822,7 +821,7 @@ continue into_locals[name] = getattr(module, name) - def prepare_exec(f, prog, globals, locals, compile_flags): + def prepare_exec(f, prog, globals, locals, compile_flags, builtins): """Manipulate parameters to exec statement to (codeobject, dict, dict). """ # XXX INCOMPLETE @@ -842,7 +841,7 @@ if not isinstance(globals, dict): raise TypeError("exec: arg 2 must be a dictionary or None") elif not globals.has_key('__builtins__'): - globals['__builtins__'] = f.f_builtins + globals['__builtins__'] = builtins # f.space.w_builtin # f_builtins if not isinstance(locals, dict): raise TypeError("exec: arg 3 must be a dictionary or None") # XXX - HACK to check for code object Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Thu Feb 17 16:34:53 2005 @@ -265,7 +265,7 @@ ) PyFrame.typedef = TypeDef('frame', - f_builtins = interp_attrproperty_w('w_builtins'), + #f_builtins = interp_attrproperty_w('w_builtins'), f_lineno = GetSetProperty(PyFrame.fget_f_lineno.im_func), **Frame.typedef.rawdict) Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Thu Feb 17 16:34:53 2005 @@ -68,8 +68,8 @@ 'unicode' : '(space.wrap(unicode))', # XXX faked # old-style classes dummy support - '_classobj' : '(space.w_classobj)', - '_instance' : '(space.w_instance)', + '_classobj' : 'space.w_classobj', + '_instance' : 'space.w_instance', # default __metaclass__ # XXX can use _classobj when we have a working one integrated '__metaclass__' : '(space.w_type)', Modified: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py Thu Feb 17 16:34:53 2005 @@ -5,6 +5,7 @@ from pypy.interpreter.pycode import PyCode from pypy.interpreter.baseobjspace import W_Root, ObjSpace from pypy.interpreter.gateway import NoneNotWrapped +import __builtin__ as cpy_builtin def compile(space, w_str_, filename, startstr, supplied_flags=0, dont_inherit=0): @@ -18,7 +19,7 @@ supplied_flags |= 4096 if not dont_inherit: try: - frame = _actframe() + frame = space.call_function(space.sys.get('_getframe')) except IndexError: pass else: Modified: pypy/branch/dist-interpapp/pypy/module/builtin/importing.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/importing.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Thu Feb 17 16:34:53 2005 @@ -24,7 +24,8 @@ if pkgdir is not None: space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)])) w_dict = space.getattr(w_mod, w('__dict__')) - execfile(w(f), w_dict, w_dict) + w_execfile = space.builtin.get("execfile") + space.call_function(w_execfile, w(f), w_dict, w_dict) w_mod = check_sys_modules(space, w_modulename) if w_mod is not None and w_parent is not None: space.setattr(w_parent, w_name, w_mod) @@ -50,8 +51,9 @@ def check_sys_modules(space, w_modulename): + w_modules = space.sys.get('modules') try: - w_mod = space.getitem(space.sys.w_modules, w_modulename) + w_mod = space.getitem(w_modules, w_modulename) except OperationError, e: pass else: @@ -116,7 +118,7 @@ prefix = [] # it would be nice if we could do here: w_path = space.sys.w_path # instead: - w_path = space.getitem(space.sys.w_dict, space.wrap('path')) + w_path = space.sys.get('path') first = None level = 0 @@ -152,7 +154,7 @@ if not space.is_true(space.is_(w_mod,space.w_None)): return w_mod else: - w_mod = space.get_builtin_module(modulename) + w_mod = space.sys.getmodule(modulename) if w_mod is not None: return w_mod for path in space.unpackiterable(w_path): Modified: pypy/branch/dist-interpapp/pypy/module/builtin/operation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/operation.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/operation.py Thu Feb 17 16:34:53 2005 @@ -97,15 +97,15 @@ def _seqiter(space, w_obj): return space.newseqiter(w_obj) -def ord(w_val): +def ord(space, w_val): return space.ord(w_val) -def pow(w_base, w_exponent, w_modulus=None): +def pow(space, w_base, w_exponent, w_modulus=None): return space.pow(w_base, w_exponent, w_modulus) -def repr(w_object): +def repr(space, w_object): return space.repr(w_object) -def setattr(w_object, w_name, w_val): +def setattr(space, w_object, w_name, w_val): space.setattr(w_object, w_name, w_val) return space.w_None Modified: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Thu Feb 17 16:34:53 2005 @@ -1,4 +1,5 @@ from pypy.interpreter.newmodule import ExtModule +from pypy.interpreter.error import OperationError class Module(ExtModule): """Sys Builtin Module. """ @@ -44,15 +45,40 @@ 'hexversion' : 'space.wrap(0x020304a0)', 'ps1' : 'space.wrap(">>>>")', 'ps2' : 'space.wrap("....")', + + 'displayhook' : 'hook.displayhook', + '__displayhook__' : 'hook.__displayhook__', } appleveldefs = { - 'displayhook' : 'app.displayhook', - '__displayhook__' : 'app.__displayhook__', + #'displayhook' : 'app.displayhook', + #'__displayhook__' : 'app.__displayhook__', 'excepthook' : 'app.excepthook', '__excepthook__' : 'app.__excepthook__', 'exit' : 'app.exit', + 'getfilesystemencoding' : 'app.getfilesystemencoding', } + def setbuiltinmodule(self, w_module, name): + w_name = self.space.wrap(name) + w_modules = self.get('modules') + self.space.setitem(w_modules, w_name, w_module) + + def getmodule(self, name): + space = self.space + w_modules = self.get('modules') + try: + return space.getitem(w_modules, space.wrap(name)) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + return None + + def setmodule(self, w_module): + space = self.space + w_name = self.space.getattr(w_module, space.wrap('__name__')) + w_modules = self.get('modules') + self.space.setitem(w_modules, w_name, w_module) + def getdictvalue(self, space, attr): """ specialize access to dynamic exc_* attributes. """ value = ExtModule.getdictvalue(self, space, attr) Modified: pypy/branch/dist-interpapp/pypy/module/sys2/app.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/app.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/app.py Thu Feb 17 16:34:53 2005 @@ -17,18 +17,7 @@ # in normalize_exception, which is exactlylike CPython. raise SystemExit, exitcode -def setmodule(module): - """ put a module into the modules dict """ - sys.modules[module.__name__] = module - -def displayhook(obj): - if obj is not None: - __builtins__['_'] = obj - # NB. this is slightly more complicated in CPython, - # see e.g. the difference with >>> print 5,; 8 - print `obj` - -__displayhook__ = displayhook # this is exactly like in CPython +#import __builtin__ def getfilesystemencoding(): """ getfilesystemencoding() -> string Added: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Thu Feb 17 16:34:53 2005 @@ -0,0 +1,13 @@ + +def displayhook(space, w_obj): + if not space.is_w(w_obj, space.w_None): + space.setitem(space.builtin.w_dict, space.wrap('_'), w_obj) + # NB. this is slightly more complicated in CPython, + # see e.g. the difference with >>> print 5,; 8 + space.appexec([w_obj], """ + (obj): + print `obj` + """) + +__displayhook__ = displayhook # this is exactly like in CPython + Modified: pypy/branch/dist-interpapp/pypy/module/sys2/state.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/state.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/state.py Thu Feb 17 16:34:53 2005 @@ -44,6 +44,8 @@ self.w_builtin_module_names = space.newlist( [space.wrap(fn) for fn in builtin_module_names]) self.w_modules = space.newdict([]) + for fn, module in builtin_modules.items(): + space.setitem(self.w_modules, space.wrap(fn), space.wrap(module)) self.w_warnoptions = space.newlist([]) self.w_argv = space.newlist([]) self.setinitialpath(space) Modified: pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py Thu Feb 17 16:34:53 2005 @@ -178,7 +178,7 @@ if isinstance(x, complex): # XXX is this right? YYY no, this is wrong right now (CT) # ZZZ hum, seems necessary for complex literals in co_consts (AR) - c = self.getitem(self.w_builtins, self.wrap("complex")) + c = self.builtin.get('complex') return self.call_function(c, self.wrap(x.real), self.wrap(x.imag)) From hpk at codespeak.net Thu Feb 17 17:22:54 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 17:22:54 +0100 (MET) Subject: [pypy-svn] r9275 - in pypy/branch/dist-interpapp/pypy: . interpreter module/builtin tool Message-ID: <20050217162254.128EA27B7D@code1.codespeak.net> Author: hpk Date: Thu Feb 17 17:22:53 2005 New Revision: 9275 Modified: pypy/branch/dist-interpapp/pypy/conftest.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py pypy/branch/dist-interpapp/pypy/module/builtin/operation.py pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py Log: a couple of random fixes ... (more to follow) Modified: pypy/branch/dist-interpapp/pypy/conftest.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/conftest.py (original) +++ pypy/branch/dist-interpapp/pypy/conftest.py Thu Feb 17 17:22:53 2005 @@ -33,11 +33,11 @@ space = module.Space() _spacecache[name] = space if name != 'flow': # not sensible for flow objspace case - space.setitem(space.w_builtins, space.wrap('AssertionError'), + space.setitem(space.builtin.w_dict, space.wrap('AssertionError'), pytestsupport.build_pytest_assertion(space)) - space.setitem(space.w_builtins, space.wrap('raises'), + space.setitem(space.builtin.w_dict, space.wrap('raises'), space.wrap(pytestsupport.app_raises)) - space.setitem(space.w_builtins, space.wrap('skip'), + space.setitem(space.builtin.w_dict, space.wrap('skip'), space.wrap(pytestsupport.app_skip)) space.raises_w = pytestsupport.raises_w.__get__(space) space.eq_w = pytestsupport.eq_w.__get__(space) Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Thu Feb 17 17:22:53 2005 @@ -799,7 +799,7 @@ return globals['__metaclass__'] else: try: - builtin.__metaclass__ + return builtin.__metaclass__ except AttributeError: return type Modified: pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py Thu Feb 17 17:22:53 2005 @@ -11,6 +11,8 @@ def locals(): return sys._getframe(1).f_locals +def _caller_locals(): + return sys._getframe(2).f_locals def _recursive_issubclass(cls, klass_or_tuple): if cls is klass_or_tuple: Modified: pypy/branch/dist-interpapp/pypy/module/builtin/operation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/operation.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/operation.py Thu Feb 17 17:22:53 2005 @@ -3,6 +3,7 @@ """ from pypy.interpreter import gateway +from pypy.interpreter.error import OperationError NoneNotWrapped = gateway.NoneNotWrapped def abs(space, w_val): Modified: pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py Thu Feb 17 17:22:53 2005 @@ -104,7 +104,7 @@ space.setattr(w_self, space.wrap('msg'), w_msg) # build a new AssertionError class to replace the original one. - w_BuiltinAssertionError = space.getitem(space.w_builtins, + w_BuiltinAssertionError = space.getitem(space.builtin.w_dict, space.wrap('AssertionError')) w_metaclass = space.type(w_BuiltinAssertionError) w_init = space.wrap(interp2app_temp(my_init)) @@ -137,14 +137,14 @@ w_locals) except OperationError, e: if e.match(space, w_ExpectedException): - return space.sys.exc_info() + return space.call_function(space.sys.get('exc_info')) raise else: try: space.call_args(w_expr, __args__) except OperationError, e: if e.match(space, w_ExpectedException): - return space.sys.exc_info() + return space.call_function(space.sys.get('exc_info')) raise raise OperationError(space.w_AssertionError, space.wrap("DID NOT RAISE")) From hpk at codespeak.net Thu Feb 17 17:27:02 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 17:27:02 +0100 (MET) Subject: [pypy-svn] r9276 - in pypy/branch/dist-interpapp/pypy/module: builtin test Message-ID: <20050217162702.8ACB027B72@code1.codespeak.net> Author: hpk Date: Thu Feb 17 17:27:02 2005 New Revision: 9276 Modified: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py pypy/branch/dist-interpapp/pypy/module/test/test_builtin.py Log: test_builtin.py passes (whatever that means) Modified: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py Thu Feb 17 17:27:02 2005 @@ -4,6 +4,7 @@ from pypy.interpreter.pycode import PyCode from pypy.interpreter.baseobjspace import W_Root, ObjSpace +from pypy.interpreter.error import OperationError from pypy.interpreter.gateway import NoneNotWrapped import __builtin__ as cpy_builtin Modified: pypy/branch/dist-interpapp/pypy/module/test/test_builtin.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/test/test_builtin.py (original) +++ pypy/branch/dist-interpapp/pypy/module/test/test_builtin.py Thu Feb 17 17:27:02 2005 @@ -366,10 +366,7 @@ space = self.space def get_builtin(self, name): - w = self.space.wrap - w_builtins = self.space.w_builtins - w_obj = self.space.getitem(w_builtins, w(name)) - return w_obj + return self.space.builtin.get(name) def test_execfile(self): from pypy.tool.udir import udir From hpk at codespeak.net Thu Feb 17 17:42:04 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 17:42:04 +0100 (MET) Subject: [pypy-svn] r9277 - in pypy/branch/dist-interpapp/pypy: interpreter module/sys2 module/test Message-ID: <20050217164204.A155327B72@code1.codespeak.net> Author: hpk Date: Thu Feb 17 17:42:04 2005 New Revision: 9277 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py pypy/branch/dist-interpapp/pypy/module/sys2/state.py pypy/branch/dist-interpapp/pypy/module/sys2/vm.py pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py Log: random fixes to make test_sysmodule.py pass Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 17:42:04 2005 @@ -48,7 +48,6 @@ self._gatewaycache = Cache() self._codecache = Cache() # set recursion limit - self.recursion_limit = 1000 # sets all the internal descriptors self.initialize() Modified: pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py Thu Feb 17 17:42:04 2005 @@ -11,7 +11,7 @@ self.framestack = Stack() def enter(self, frame): - if self.framestack.depth() > self.space.recursion_limit: + if self.framestack.depth() > self.space.sys.recursionlimit: raise OperationError(self.space.w_RuntimeError, self.space.wrap("maximum recursion depth exceeded")) locals = getthreadlocals() Modified: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Thu Feb 17 17:42:04 2005 @@ -3,6 +3,11 @@ class Module(ExtModule): """Sys Builtin Module. """ + def __init__(self, space, w_name): + super(Module, self).__init__(space, w_name) + self.checkinterval = 100 + self.recursionlimit = 100 + interpleveldefs = { 'pypy_objspaceclass' : '(space.wrap(space.__class__.__name__))', @@ -28,7 +33,7 @@ 'builtin_module_names' : 'state.get(space).w_builtin_module_names', 'pypy_getudir' : 'state.pypy_getudir', - 'getdefaultencoding' : 'space.wrap(sys.getdefaultencoding())', + 'getdefaultencoding' : 'state.getdefaultencoding', 'getrefcount' : 'vm.getrefcount', '_getframe' : 'vm._getframe', 'setrecursionlimit' : 'vm.setrecursionlimit', @@ -40,7 +45,8 @@ 'executable' : 'space.wrap("py.py")', 'copyright' : 'space.wrap("MIT-License")', - 'version_info' : 'space.wrap((2,3,4, "pypy1"))', + 'api_version' : 'space.wrap(1012)', + 'version_info' : 'space.wrap((2,3,4, "alpha", 42))', 'version' : 'space.wrap("2.3.4 (pypy1 build)")', 'hexversion' : 'space.wrap(0x020304a0)', 'ps1' : 'space.wrap(">>>>")', Modified: pypy/branch/dist-interpapp/pypy/module/sys2/state.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/state.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/state.py Thu Feb 17 17:42:04 2005 @@ -41,7 +41,7 @@ class State: def __init__(self, space, stuff=None): self.space = space - self.w_builtin_module_names = space.newlist( + self.w_builtin_module_names = space.newtuple( [space.wrap(fn) for fn in builtin_module_names]) self.w_modules = space.newdict([]) for fn, module in builtin_modules.items(): @@ -73,3 +73,5 @@ from pypy.tool.udir import udir return space.wrap(str(udir)) +def getdefaultencoding(space): + return space.wrap(sys.getdefaultencoding()) Modified: pypy/branch/dist-interpapp/pypy/module/sys2/vm.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/vm.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/vm.py Thu Feb 17 17:42:04 2005 @@ -42,7 +42,7 @@ space.wrap("recursion limit must be positive")) # global recursion_limit # we need to do it without writing globals. - space.sys.recursion_limit = new_limit + space.sys.recursionlimit = new_limit def getrecursionlimit(space): """getrecursionlimit() @@ -51,7 +51,7 @@ recursion from causing an overflow of the C stack and crashing Python. """ - return space.wrap(space.sys.recursion_limit) + return space.wrap(space.sys.recursionlimit) checkinterval = 100 Modified: pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py Thu Feb 17 17:42:04 2005 @@ -10,11 +10,9 @@ b.sys = sys class TestSysTests: - def setup_method(self,method): - self.sys_w = self.space.get_builtin_module("sys") def test_stdout_exists(self): s = self.space - assert s.is_true(s.getattr(self.sys_w, s.wrap("stdout"))) + assert s.is_true(s.getattr(s.w_sys, s.wrap("stdout"))) class AppTestAppSysTests: def test_path_exists(self): From hpk at codespeak.net Thu Feb 17 18:14:55 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 18:14:55 +0100 (MET) Subject: [pypy-svn] r9278 - in pypy/branch/dist-interpapp/pypy: interpreter/test module/builtin Message-ID: <20050217171455.1674B27B8E@code1.codespeak.net> Author: hpk Date: Thu Feb 17 18:14:54 2005 New Revision: 9278 Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py Log: make test_interpreter.py pass Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py Thu Feb 17 18:14:54 2005 @@ -10,15 +10,16 @@ source = str(py.code.Source(source).strip()) + '\n' - compile = space.builtin.compile + #from pypy.module.builtin.compiling import compile + w_compile = space.builtin.get('compile') w = space.wrap - w_code = compile(source, '', 'exec', 0, 0) - + w_code = space.call_function(w_compile, + w(source), w(''), w('exec'), w(0), w(0)) ec = executioncontext.ExecutionContext(space) tempmodule = module.Module(space, w("__temp__")) w_glob = tempmodule.w_dict - space.setitem(w_glob, w("__builtins__"), space.w_builtins) + #space.setitem(w_glob, w("__builtins__"), space.sys.w_builtins) code = space.unwrap(w_code) code.exec_code(space, w_glob, w_glob) Modified: pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py Thu Feb 17 18:14:54 2005 @@ -21,7 +21,9 @@ if not dont_inherit: try: frame = space.call_function(space.sys.get('_getframe')) - except IndexError: + except OperationError, e: + if not e.match(space, space.w_ValueError): + raise pass else: supplied_flags |= frame.get_compile_flags() From hpk at codespeak.net Thu Feb 17 18:21:31 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 18:21:31 +0100 (MET) Subject: [pypy-svn] r9279 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050217172131.6B99827B8E@code1.codespeak.net> Author: hpk Date: Thu Feb 17 18:21:31 2005 New Revision: 9279 Removed: pypy/branch/dist-interpapp/pypy/interpreter/test/foomodule.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_extmodule.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/main.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py Log: make interpreter-tests mostly pass (test_py.py fails due to stdout-output which i don'T want to comment out yet) get rid of test_extmodule and the accompanying foomodule.py because we will hopefully not see the old way again :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/main.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/main.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/main.py Thu Feb 17 18:21:31 2005 @@ -14,10 +14,10 @@ from pypy.objspace.std import StdObjSpace space = StdObjSpace() - compile = space.builtin.compile + w_compile = space.builtin.get('compile') w = space.wrap - w_code = compile(source, filename, cmd, 0, 0) - + w_code = space.call_function(w_compile, + w(source), w(filename), w(cmd), w(0), w(0)) mainmodule = module.Module(space, space.wrap("__main__")) w_globals = mainmodule.w_dict Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/test/foomodule.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/interpreter/test/foomodule.py Thu Feb 17 18:21:31 2005 +++ (empty file) @@ -1,13 +0,0 @@ - -__interplevel__exec("w_foo = space.w_Ellipsis") -foo1 = __interplevel__eval("w_foo") # foo1 is Ellipsis -from __interplevel__ import foo # Ellipsis too - -def bar(a, b): # visible from interp-level code - return a * b - -__interplevel__execfile("foointerp.py") # defines w_foo2 and foobuilder() - -from __interplevel__ import foo2 # from w_foo2, gives "hello" -from __interplevel__ import foobuilder -foo3 = foobuilder("guido") # gives "hi, guido!" Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/test/test_extmodule.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/interpreter/test/test_extmodule.py Thu Feb 17 18:21:31 2005 +++ (empty file) @@ -1,25 +0,0 @@ - -import autopath -import os -from pypy.interpreter.extmodule import BuiltinModule - -class TestBuiltinModule: - def test_foomodule(self): - space = self.space - sourcefile = os.path.join(autopath.this_dir, 'foomodule.py') - m = BuiltinModule(space, 'foo', sourcefile=sourcefile) - w = space.wrap - w_m = space.wrap(m) - assert self.space.eq_w(space.getattr(w_m, w('__name__')), w('foo')) - assert self.space.eq_w(space.getattr(w_m, w('__file__')), w(sourcefile)) - # check app-level definitions - assert self.space.eq_w(m.w_foo, space.w_Ellipsis) - assert self.space.eq_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis) - assert self.space.eq_w(space.getattr(w_m, w('foo')), space.w_Ellipsis) - assert self.space.eq_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12)) - assert self.space.eq_w(space.getattr(w_m, w('foo2')), w('hello')) - assert self.space.eq_w(space.getattr(w_m, w('foo3')), w('hi, guido!')) - # check interp-level definitions - assert self.space.eq_w(m.w_foo2, w('hello')) - assert self.space.eq_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!')) - assert self.space.eq_w(m.fortytwo, w(42)) Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py Thu Feb 17 18:21:31 2005 @@ -17,7 +17,7 @@ testresultoutput = '11\n' def checkoutput(space, expected_output,f,*args): - w_sys = space.get_builtin_module("sys") + w_sys = space.w_sys w_oldout = space.getattr(w_sys, space.wrap("stdout")) capturefn = udir.join('capturefile') capturefile = capturefn.open('w') Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py Thu Feb 17 18:21:31 2005 @@ -89,12 +89,12 @@ class TestModuleMinimal: def test_sys_exists(self): - w_sys = self.space.get_builtin_module('sys') + w_sys = self.space.w_sys assert self.space.is_true(w_sys) def test_import_exists(self): space = self.space - w_builtin = space.get_builtin_module('__builtin__') + w_builtin = space.w_builtin assert space.is_true(w_builtin) w_name = space.wrap('__import__') w_import = self.space.getattr(w_builtin, w_name) From jacob at codespeak.net Thu Feb 17 18:30:26 2005 From: jacob at codespeak.net (jacob at codespeak.net) Date: Thu, 17 Feb 2005 18:30:26 +0100 (MET) Subject: [pypy-svn] r9280 - pypy/funding/negotiations Message-ID: <20050217173026.59D1827B88@code1.codespeak.net> Author: jacob Date: Thu Feb 17 18:30:26 2005 New Revision: 9280 Modified: pypy/funding/negotiations/pypy-association-agreement.sxw Log: Fixed missed places where Consortium needed to be changed to Association. Modified: pypy/funding/negotiations/pypy-association-agreement.sxw ============================================================================== Binary files. No diff available. From tismer at codespeak.net Thu Feb 17 18:39:10 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Thu, 17 Feb 2005 18:39:10 +0100 (MET) Subject: [pypy-svn] r9282 - pypy/dist/pypy/tool Message-ID: <20050217173910.44ADC27B88@code1.codespeak.net> Author: tismer Date: Thu Feb 17 18:39:10 2005 New Revision: 9282 Modified: pypy/dist/pypy/tool/sourcetools.py Log: added a feature that shows true source code for our generated method stuff. I think something alike could go into py.code, but this needs to be discussed. Here the effect of the patch on the source output of _classobj.py: After running of _classobj.py, this can be done: >>> import inspect >>> print inspect.getsource(instance.__div__) def __%(op)s__(self, other): coerced = _coerce(self, other) if coerced is None or coerced[0] is self: func = instance_getattr1(self, '__%(op)s__', False) if func: return func(other) return NotImplemented else: return %(opref)s(self, other) >>> from pypy.tool import sourcetools >>> print sourcetools.getsource(instance.__div__) def __div__(self, other): coerced = _coerce(self, other) if coerced is None or coerced[0] is self: func = instance_getattr1(self, '__div__', False) if func: return func(other) return NotImplemented else: return operator.div(self, other) >>> Modified: pypy/dist/pypy/tool/sourcetools.py ============================================================================== --- pypy/dist/pypy/tool/sourcetools.py (original) +++ pypy/dist/pypy/tool/sourcetools.py Thu Feb 17 18:39:10 2005 @@ -1,7 +1,7 @@ # a couple of support functions which # help with generating Python source. -import sys, os +import sys, os, inspect def render_docstr(func, indent_str='', closing_str=''): """ Render a docstring as a string of lines. @@ -70,4 +70,64 @@ src = 'if 1:\n' + src src = '\n' * prelines + src % args c = compile(src, self.srcname, "exec") + # preserve the arguments of the code in an attribute + # of the code's co_filename + if self.srcname: + srcname = MyStr(self.srcname) + srcname.__sourceargs__ = args + c = newcode_withfilename(c, srcname) return c + +def getsource(object): + """ similar to inspect.getsource, but trying to + find the parameters of formatting generated methods and + functions. + """ + src = inspect.getsource(object) + name = inspect.getfile(object) + if hasattr(name, "__sourceargs__"): + return src % name.__sourceargs__ + return src + +## the following is stolen frompy.code.source.py for now. +## XXX discuss whether and how to put this functionality +## into py.code.source. +# +# various helper functions +# +class MyStr(str): + """ custom string which allows to add attributes. """ + +def newcode(fromcode, **kwargs): + names = [x for x in dir(fromcode) if x[:3] == 'co_'] + for name in names: + if name not in kwargs: + kwargs[name] = getattr(fromcode, name) + import new + return new.code( + kwargs['co_argcount'], + kwargs['co_nlocals'], + kwargs['co_stacksize'], + kwargs['co_flags'], + kwargs['co_code'], + kwargs['co_consts'], + kwargs['co_names'], + kwargs['co_varnames'], + kwargs['co_filename'], + kwargs['co_name'], + kwargs['co_firstlineno'], + kwargs['co_lnotab'], + kwargs['co_freevars'], + kwargs['co_cellvars'], + ) + +def newcode_withfilename(co, co_filename): + newconstlist = [] + cotype = type(co) + for c in co.co_consts: + if isinstance(c, cotype): + c = newcode_withfilename(c, co_filename) + newconstlist.append(c) + return newcode(co, co_consts = tuple(newconstlist), + co_filename = co_filename) + From arigo at codespeak.net Thu Feb 17 18:47:08 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 17 Feb 2005 18:47:08 +0100 (MET) Subject: [pypy-svn] r9283 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217174708.1870D27B88@code1.codespeak.net> Author: arigo Date: Thu Feb 17 18:47:07 2005 New Revision: 9283 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/pycode.py pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Log: (intermediate check-in, things still break.) Added proper support for the __builtins__ name in globals, as in CPython. Now PyFrame.w_builtins has been replaced with PyFrame.builtin, which is the builtin module to use, instead of a dict (to enable lazy-loading). Also changed PyCode.co_names_w back to PyCode.co_names, to avoid unwrapping. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 18:47:07 2005 @@ -284,6 +284,8 @@ statement = PyCode(self)._from_code(statement) if not isinstance(statement, PyCode): raise TypeError, 'space.exec_(): expected a string, code or PyCode object' + self.call_method(w_globals, 'setdefault', + self.wrap('__builtins__'), self.wrap(self.builtin)) return statement.exec_code(self, w_globals, w_locals) def appexec(self, posargs_w, source): Modified: pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/executioncontext.py Thu Feb 17 18:47:07 2005 @@ -25,17 +25,16 @@ locals = getthreadlocals() locals.executioncontext = previous_ec - def get_w_builtins(self): - # XXX sort out __builtins__ issue - #if self.framestack.empty(): - return self.space.w_builtin - #else: - # return self.framestack.top().w_builtins + def get_builtin(self): + try: + return self.framestack.top().builtin + except IndexError: + return self.space.builtin def make_standard_w_globals(self): "Create a new empty 'globals' dictionary." w_key = self.space.wrap("__builtins__") - w_value = self.get_w_builtins() + w_value = self.space.wrap(self.get_builtin()) w_globals = self.space.newdict([(w_key, w_value)]) return w_globals Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Thu Feb 17 18:47:07 2005 @@ -14,7 +14,8 @@ w_dict = space.newdict([]) self.w_dict = w_dict self.w_name = w_name - space.setitem(w_dict, space.wrap('__name__'), w_name) + if w_name is not None: + space.setitem(w_dict, space.wrap('__name__'), w_name) def getdict(self): return self.w_dict Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pycode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Thu Feb 17 18:47:07 2005 @@ -55,7 +55,7 @@ self.co_flags = 0 # CO_..., see above self.co_code = None # string: instruction opcodes self.co_consts_w = [] # list of constants used (wrapped!) - self.co_names_w = [] # list of wrapped strs: names (for attrs..) + self.co_names = [] # list of strings: names (for attrs..) self.co_varnames = () # tuple of strings: local variable names self.co_freevars = () # tuple of strings: free variable names self.co_cellvars = () # tuple of strings: cell variable names @@ -88,13 +88,13 @@ self.co_code = x #self.co_consts = x = code.co_names; assert isinstance(x, tuple) - self.co_names_w = [ self.space.wrap(i) for i in x ] + self.co_names = list(x) x = code.co_varnames; assert isinstance(x, tuple) - self.co_varnames = x + self.co_varnames = list(x) x = code.co_freevars; assert isinstance(x, tuple) - self.co_freevars = x + self.co_freevars = list(x) x = code.co_cellvars; assert isinstance(x, tuple) - self.co_cellvars = x + self.co_cellvars = list(x) x = code.co_filename; assert isinstance(x, str) self.co_filename = x x = code.co_name; assert isinstance(x, str) @@ -157,7 +157,7 @@ def fget_co_names(space, w_self): self = space.interpclass_w(w_self) - return space.newtuple(self.co_names_w) + return space.newtuple([space.wrap(name) for name in self.co_names]) def descr_code__eq__(space, w_self, w_other): self = space.interpclass_w(w_self) @@ -170,7 +170,11 @@ self.co_flags == other.co_flags and self.co_firstlineno == other.co_firstlineno and self.co_code == other.co_code and - len(self.co_consts_w) == len(other.co_consts_w)) + len(self.co_consts_w) == len(other.co_consts_w) and + self.co_names == other.co_names and + self.co_varnames == other.co_varnames and + self.co_freevars == other.co_freevars and + self.co_cellvars == other.co_cellvars) if not areEqual: return space.w_False @@ -178,17 +182,6 @@ if not space.eq_w(self.co_consts_w[i], other.co_consts_w[i]): return space.w_False - if len(self.co_names_w) != len(other.co_names_w): - return space.w_False - - for i in range(len(self.co_names_w)): - if not space.eq_w(self.co_names_w[i], other.co_names_w[i]): - return space.w_False - if (self.co_varnames == other.co_varnames and - self.co_freevars == other.co_freevars and - self.co_cellvars == other.co_cellvars): - return space.w_True - return space.w_True def descr_code__new__(space, w_subtype, @@ -206,7 +199,7 @@ code.co_flags = space.int_w(w_flags) code.co_code = space.str_w(w_codestring) code.co_consts_w = space.unpacktuple(w_constants) - code.co_names_w = space.unpacktuple(w_names) + code.co_names = unpack_str_tuple(space, w_names) code.co_varnames = unpack_str_tuple(space, w_varnames) code.co_filename = space.str_w(w_filename) code.co_name = space.str_w(w_name) Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Thu Feb 17 18:47:07 2005 @@ -5,6 +5,7 @@ from pypy.interpreter.miscutils import Stack from pypy.interpreter.error import OperationError from pypy.interpreter import pytraceback +from pypy.interpreter import module import __future__ compiler_flags = 0 @@ -23,7 +24,7 @@ * 'code' is the PyCode object this frame runs * 'w_locals' is the locals dictionary to use * 'w_globals' is the attached globals dictionary - * 'w_builtins' is the attached built-ins dictionary + * 'builtin' is the attached built-in module * 'valuestack', 'blockstack', 'next_instr' control the interpretation """ @@ -33,7 +34,7 @@ self.blockstack = Stack() self.last_exception = None self.next_instr = 0 - #self.w_builtins = self.space.w_builtins + self.builtin = lookup_builtin(space, w_globals) # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS. # class bodies only have CO_NEWLOCALS. if code.dictscope_needed(): @@ -130,6 +131,31 @@ "Returns the line number of the next instruction to execute." return pytraceback.offset2lineno(self.code, self.next_instr) + def fget_f_builtins(space, w_self): + self = space.interpclass_w(w_self) + return self.builtin.getdict() + + +def lookup_builtin(space, w_globals): + "Look up the builtin module to use from the __builtins__ global" + try: + w_builtin = space.getitem(w_globals, space.wrap('__builtins__')) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + else: + if w_builtin is space.builtin: # common case + return space.builtin + if space.is_true(space.isinstance(w_builtin, space.w_dict)): + return module.Module(space, None, w_builtin) + builtin = space.interpclass_w(w_builtin) + if isinstance(builtin, Module): + return builtin + # no builtin! make a default one. Given them None, at least. + builtin = module.Module(space, None) + space.setitem(builtin.w_dict, space.wrap('None'), space.w_None) + return builtin + ### Frame Blocks ### Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Thu Feb 17 18:47:07 2005 @@ -71,9 +71,11 @@ def getconstant_w(self, index): return self.code.co_consts_w[index] + def getname(self, index): + return self.code.co_names[index] + def getname_w(self, index): - w_varname = self.code.co_names_w[index] - return w_varname + return self.space.wrap(self.code.co_names[index]) ################################################################ @@ -346,7 +348,7 @@ w_prog = f.valuestack.pop() w_compile_flags = f.space.wrap(f.get_compile_flags()) w_resulttuple = prepare_exec(f.space, f.space.wrap(f), w_prog, w_globals, w_locals, - w_compile_flags, f.space.builtin.w_dict) + w_compile_flags, space.wrap(f.builtin)) w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3) plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) @@ -379,7 +381,8 @@ w_bases = f.valuestack.pop() w_name = f.valuestack.pop() w_metaclass = find_metaclass(f.space, w_bases, - w_methodsdict, f.w_globals, f.space.builtin) + w_methodsdict, f.w_globals, + f.space.wrap(f.builtin)) w_newclass = f.space.call_function(w_metaclass, w_name, w_bases, w_methodsdict) f.valuestack.push(w_newclass) @@ -433,32 +436,19 @@ f.space.delitem(f.w_globals, w_varname) def LOAD_NAME(f, nameindex): - w_varname = f.getname_w(nameindex) - - if f.w_globals is f.w_locals: - try_list_w = [f.w_globals] - - else: - try_list_w = [f.w_locals, f.w_globals] - - for wrapped in try_list_w: + if f.w_locals is not f.w_globals: + w_varname = f.getname_w(nameindex) try: - w_value = f.space.getitem(wrapped, w_varname) - break + w_value = f.space.getitem(f.w_locals, w_varname) except OperationError, e: if not e.match(f.space, f.space.w_KeyError): raise - else: - w_value = getbuiltin(f.space, w_varname) - f.valuestack.push(w_value) - # XXX the implementation can be pushed back into app-space as an - # when exception handling begins to behave itself. For now, it - # was getting on my nerves -- mwh - # w_value = f.load_name(w_varname) - # f.valuestack.push(w_value) + else: + f.valuestack.push(w_value) + return + f.LOAD_GLOBAL(nameindex) # fall-back def LOAD_GLOBAL(f, nameindex): - assert f.w_globals is not None w_varname = f.getname_w(nameindex) try: w_value = f.space.getitem(f.w_globals, w_varname) @@ -467,7 +457,12 @@ if not e.match(f.space, f.space.w_KeyError): raise # we got a KeyError, now look in the built-ins - w_value = getbuiltin(f.space, w_varname) + varname = f.getname(nameindex) + w_value = f.builtin.getdictvalue(f.space, varname) + if w_value is None: + message = "global name '%s' is not defined" % varname + raise OperationError(space.w_NameError, + space.wrap(message)) f.valuestack.push(w_value) def DELETE_FAST(f, varindex): @@ -548,11 +543,8 @@ w_modulename = f.getname_w(nameindex) modulename = f.space.str_w(w_modulename) w_fromlist = f.valuestack.pop() - try: - w_import = space.builtin.get('__import__') - except OperationError, e: - if not e.match(space, space.w_AttributeError): - raise + w_import = f.builtin.getdictvalue(f.space, '__import__') + if w_import is None: raise OperationError(space.w_ImportError, space.wrap("__import__ not found")) w_locals = f.w_locals @@ -721,19 +713,6 @@ cls.dispatch_table = dispatch_table -def getbuiltin(space, w_varname): - varname = space.str_w(w_varname) - try: - return space.builtin.get(space.str_w(w_varname)) - except OperationError, e: - # catch AttributeErrors - if not e.match(space, space.w_AttributeError): - raise - message = "global name '%s' is not defined" % space.str_w(w_varname) - w_exc_type = space.w_NameError - w_exc_value = space.wrap(message) - raise OperationError(w_exc_type, w_exc_value) - ### helpers written at the application-level ### # Some of these functions are expected to be generally useful if other # parts of the code needs to do the same thing as a non-trivial opcode, @@ -821,7 +800,7 @@ continue into_locals[name] = getattr(module, name) - def prepare_exec(f, prog, globals, locals, compile_flags, builtins): + def prepare_exec(f, prog, globals, locals, compile_flags, builtin): """Manipulate parameters to exec statement to (codeobject, dict, dict). """ # XXX INCOMPLETE @@ -841,7 +820,7 @@ if not isinstance(globals, dict): raise TypeError("exec: arg 2 must be a dictionary or None") elif not globals.has_key('__builtins__'): - globals['__builtins__'] = builtins # f.space.w_builtin # f_builtins + globals['__builtins__'] = builtin if not isinstance(locals, dict): raise TypeError("exec: arg 3 must be a dictionary or None") # XXX - HACK to check for code object Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Thu Feb 17 18:47:07 2005 @@ -265,7 +265,7 @@ ) PyFrame.typedef = TypeDef('frame', - #f_builtins = interp_attrproperty_w('w_builtins'), + f_builtins = GetSetProperty(PyFrame.fget_f_builtins.im_func), f_lineno = GetSetProperty(PyFrame.fget_f_lineno.im_func), **Frame.typedef.rawdict) From arigo at codespeak.net Thu Feb 17 18:58:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 17 Feb 2005 18:58:47 +0100 (MET) Subject: [pypy-svn] r9284 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217175847.2A33B27B7A@code1.codespeak.net> Author: arigo Date: Thu Feb 17 18:58:46 2005 New Revision: 9284 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Log: Remember the interp-level traceback for RuntimeError/MemoryError/KeyboardInterrupt. Useful when running with PYPY_TB=1. Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Thu Feb 17 18:58:46 2005 @@ -75,14 +75,17 @@ # catch asynchronous exceptions and turn them # into OperationErrors except KeyboardInterrupt: - raise OperationError(self.space.w_KeyboardInterrupt, - self.space.w_None) + import sys; tb = sys.exc_info()[2] + raise OperationError, (self.space.w_KeyboardInterrupt, + self.space.w_None), tb except MemoryError: - raise OperationError(self.space.w_MemoryError, - self.space.w_None) + import sys; tb = sys.exc_info()[2] + raise OperationError, (self.space.w_MemoryError, + self.space.w_None), tb except RuntimeError, e: - raise OperationError(self.space.w_RuntimeError, - self.space.wrap("internal error: " + str(e))) + import sys; tb = sys.exc_info()[2] + raise OperationError, (self.space.w_RuntimeError, + self.space.wrap("internal error: " + str(e))), tb except OperationError, e: pytraceback.record_application_traceback( From arigo at codespeak.net Thu Feb 17 19:00:56 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 17 Feb 2005 19:00:56 +0100 (MET) Subject: [pypy-svn] r9285 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217180056.DA83D27B7A@code1.codespeak.net> Author: arigo Date: Thu Feb 17 19:00:56 2005 New Revision: 9285 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Log: Oups! applevel() uses space.exec_(), which cannot call 'setdefault', because this is implemented at app-level in stdobjspace... Argh. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 19:00:56 2005 @@ -284,8 +284,9 @@ statement = PyCode(self)._from_code(statement) if not isinstance(statement, PyCode): raise TypeError, 'space.exec_(): expected a string, code or PyCode object' - self.call_method(w_globals, 'setdefault', - self.wrap('__builtins__'), self.wrap(self.builtin)) + w_key = self.wrap('__builtins__') + if not self.is_true(self.contains(w_globals, w_key)): + self.setitem(w_globals, w_key, self.wrap(self.builtin)) return statement.exec_code(self, w_globals, w_locals) def appexec(self, posargs_w, source): From pedronis at codespeak.net Thu Feb 17 19:06:35 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 19:06:35 +0100 (MET) Subject: [pypy-svn] r9286 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217180635.46EA527B7A@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 19:06:35 2005 New Revision: 9286 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Log: small fix Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Thu Feb 17 19:06:35 2005 @@ -348,7 +348,7 @@ w_prog = f.valuestack.pop() w_compile_flags = f.space.wrap(f.get_compile_flags()) w_resulttuple = prepare_exec(f.space, f.space.wrap(f), w_prog, w_globals, w_locals, - w_compile_flags, space.wrap(f.builtin)) + w_compile_flags, f.space.wrap(f.builtin)) w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3) plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) From hpk at codespeak.net Thu Feb 17 19:09:39 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 19:09:39 +0100 (MET) Subject: [pypy-svn] r9287 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217180939.9616827B7A@code1.codespeak.net> Author: hpk Date: Thu Feb 17 19:09:39 2005 New Revision: 9287 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Log: fix typo Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyopcode.py Thu Feb 17 19:09:39 2005 @@ -461,8 +461,8 @@ w_value = f.builtin.getdictvalue(f.space, varname) if w_value is None: message = "global name '%s' is not defined" % varname - raise OperationError(space.w_NameError, - space.wrap(message)) + raise OperationError(f.space.w_NameError, + f.space.wrap(message)) f.valuestack.push(w_value) def DELETE_FAST(f, varindex): From arigo at codespeak.net Thu Feb 17 19:12:12 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Thu, 17 Feb 2005 19:12:12 +0100 (MET) Subject: [pypy-svn] r9288 - in pypy/branch/dist-interpapp/pypy: objspace/std tool Message-ID: <20050217181212.2B2FF27B7A@code1.codespeak.net> Author: arigo Date: Thu Feb 17 19:12:11 2005 New Revision: 9288 Modified: pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py pypy/branch/dist-interpapp/pypy/tool/uid.py Log: Shup up this warning everyone complains about: '%x' % id(obj). Yet another fix to the way ids should be made positive... Modified: pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py Thu Feb 17 19:12:11 2005 @@ -3,12 +3,14 @@ from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.register_all import register_all from pypy.objspace.std.objspace import StdObjSpace +from pypy.tool.uid import fixid def descr__repr__(space, w_obj): w = space.wrap classname = space.str_w(space.getattr(space.type(w_obj), w("__name__"))) id = space.int_w(space.id(w_obj))# xxx ids could be long + id = fixid(id) return w("<%s object at 0x%x>" % (classname, id)) def descr__str__(space, w_obj): Modified: pypy/branch/dist-interpapp/pypy/tool/uid.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/uid.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/uid.py Thu Feb 17 19:12:11 2005 @@ -1,12 +1,16 @@ -import sys -HUGEINT = (sys.maxint + 1L) * 2L +import struct + +HUGEVAL = 256 ** struct.calcsize('P') + + +def fixid(result): + if result < 0: + result += HUGEVAL + return result def uid(obj): """ Return the id of an object as an unsigned number so that its hex representation makes sense """ - rval = id(obj) - if rval < 0: - rval += HUGEINT - return rval + return fixid(id(obj)) From hpk at codespeak.net Thu Feb 17 19:16:47 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 19:16:47 +0100 (MET) Subject: [pypy-svn] r9289 - pypy/branch/dist-interpapp/pypy/module/sys2 Message-ID: <20050217181647.BBEA827B7A@code1.codespeak.net> Author: hpk Date: Thu Feb 17 19:16:47 2005 New Revision: 9289 Modified: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Log: move the displayhook to use one layer of applevel code less Modified: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/hook.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Thu Feb 17 19:16:47 2005 @@ -1,13 +1,11 @@ +from pypy.interpreter.pyopcode import print_item_to, sys_stdout def displayhook(space, w_obj): if not space.is_w(w_obj, space.w_None): space.setitem(space.builtin.w_dict, space.wrap('_'), w_obj) # NB. this is slightly more complicated in CPython, # see e.g. the difference with >>> print 5,; 8 - space.appexec([w_obj], """ - (obj): - print `obj` - """) + print_item_to(space, w_obj, sys_stdout(space)) __displayhook__ = displayhook # this is exactly like in CPython From pedronis at codespeak.net Thu Feb 17 19:24:39 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 19:24:39 +0100 (MET) Subject: [pypy-svn] r9290 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217182439.AB8FD27B71@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 19:24:39 2005 New Revision: 9290 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Log: we need proper tuple-making accessors, for now remove the list conversion Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pycode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Thu Feb 17 19:24:39 2005 @@ -90,11 +90,11 @@ x = code.co_names; assert isinstance(x, tuple) self.co_names = list(x) x = code.co_varnames; assert isinstance(x, tuple) - self.co_varnames = list(x) + self.co_varnames = x x = code.co_freevars; assert isinstance(x, tuple) - self.co_freevars = list(x) + self.co_freevars = x x = code.co_cellvars; assert isinstance(x, tuple) - self.co_cellvars = list(x) + self.co_cellvars = x x = code.co_filename; assert isinstance(x, str) self.co_filename = x x = code.co_name; assert isinstance(x, str) From hpk at codespeak.net Thu Feb 17 19:42:27 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 17 Feb 2005 19:42:27 +0100 (MET) Subject: [pypy-svn] r9291 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050217184227.1E86F27B7A@code1.codespeak.net> Author: hpk Date: Thu Feb 17 19:42:26 2005 New Revision: 9291 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_function.py Log: fixed the applevel tests to properly construct Functions with w_globals as dicts. removed some dead code from interp2papp Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Thu Feb 17 19:42:26 2005 @@ -409,9 +409,6 @@ defs_w.append(space.wrap(val)) return defs_w - def _getglobals(self, space): - return None - # lazy binding to space def __spacebind__(self, space): @@ -450,7 +447,7 @@ except KeyError: defs = self._getdefaults(space) # needs to be implemented by subclass code = self._code - fn = Function(space, code, self._getglobals(space), defs, forcename = self.name) + fn = Function(space, code, None, defs, forcename = self.name) cache.content[self] = fn return fn Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_function.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_function.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_function.py Thu Feb 17 19:42:26 2005 @@ -176,7 +176,7 @@ def c(self, bar): return bar code = PyCode(self.space)._from_code(c.func_code) - self.fn = Function(self.space, code) + self.fn = Function(self.space, code, self.space.newdict([])) def test_get(self): space = self.space @@ -202,7 +202,8 @@ space = self.space # Create some function for this test only def m(self): return self - func = Function(space, PyCode(self.space)._from_code(m.func_code)) + func = Function(space, PyCode(self.space)._from_code(m.func_code), + space.newdict([])) # Some shorthands obj1 = space.wrap(23) obj2 = space.wrap(42) From pedronis at codespeak.net Thu Feb 17 20:01:01 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 20:01:01 +0100 (MET) Subject: [pypy-svn] r9292 - pypy/branch/dist-interpapp/pypy/interpreter/test Message-ID: <20050217190101.8CBD227B7A@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 20:01:01 2005 New Revision: 9292 Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py Log: fixed test_interpreter Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_interpreter.py Thu Feb 17 20:01:01 2005 @@ -19,7 +19,7 @@ tempmodule = module.Module(space, w("__temp__")) w_glob = tempmodule.w_dict - #space.setitem(w_glob, w("__builtins__"), space.sys.w_builtins) + space.setitem(w_glob, w("__builtins__"), space.builtin) code = space.unwrap(w_code) code.exec_code(space, w_glob, w_glob) From pedronis at codespeak.net Thu Feb 17 20:03:01 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 20:03:01 +0100 (MET) Subject: [pypy-svn] r9293 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050217190301.62FA227B7A@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 20:03:01 2005 New Revision: 9293 Modified: pypy/branch/dist-interpapp/pypy/interpreter/main.py Log: fixed main.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/main.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/main.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/main.py Thu Feb 17 20:03:01 2005 @@ -20,6 +20,7 @@ w(source), w(filename), w(cmd), w(0), w(0)) mainmodule = module.Module(space, space.wrap("__main__")) w_globals = mainmodule.w_dict + space.setitem(w_globals, w('__builtins__'), space.builtin) pycode = space.interpclass_w(w_code) retval = pycode.exec_code(space, w_globals, w_globals) From pedronis at codespeak.net Thu Feb 17 20:17:06 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 20:17:06 +0100 (MET) Subject: [pypy-svn] r9294 - pypy/branch/dist-interpapp/pypy/module/builtin Message-ID: <20050217191706.7D40D27B7A@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 20:17:06 2005 New Revision: 9294 Modified: pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Log: small fix to importing access to sys.modules Modified: pypy/branch/dist-interpapp/pypy/module/builtin/importing.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/importing.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/importing.py Thu Feb 17 20:17:06 2005 @@ -105,7 +105,7 @@ w_mod = absolute_import(space, modulename, 0, w_fromlist, tentative=0) if rel_modulename is not None: - space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) + space.setitem(space.sys.get('modules'), w(rel_modulename),space.w_None) return w_mod # importhook.unwrap_spec = [ObjSpace,str,W_Root,W_Root,W_Root] From pedronis at codespeak.net Thu Feb 17 20:27:16 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 20:27:16 +0100 (MET) Subject: [pypy-svn] r9295 - pypy/branch/dist-interpapp/pypy/module/sys2 Message-ID: <20050217192716.44C1227B7A@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 20:27:16 2005 New Revision: 9295 Modified: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Log: fix displayhook Modified: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/hook.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Thu Feb 17 20:27:16 2005 @@ -1,4 +1,4 @@ -from pypy.interpreter.pyopcode import print_item_to, sys_stdout +from pypy.interpreter.pyopcode import print_item_to, print_newline_to, sys_stdout def displayhook(space, w_obj): if not space.is_w(w_obj, space.w_None): @@ -6,6 +6,7 @@ # NB. this is slightly more complicated in CPython, # see e.g. the difference with >>> print 5,; 8 print_item_to(space, w_obj, sys_stdout(space)) + print_newline_to(space, sys_stdout(space)) __displayhook__ = displayhook # this is exactly like in CPython From pedronis at codespeak.net Thu Feb 17 21:16:13 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 21:16:13 +0100 (MET) Subject: [pypy-svn] r9296 - in pypy/branch/dist-interpapp/pypy: interpreter objspace/flow Message-ID: <20050217201613.0A64027B76@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 21:16:12 2005 New Revision: 9296 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Log: mainly fixed flow space, moved lookup_builtin on the space so that it is hookable. Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 21:16:12 2005 @@ -37,6 +37,9 @@ class Wrappable(BaseWrappable, object): """Same as BaseWrappable, just new-style instead.""" + +from pypy.interpreter import module + class ObjSpace(object): """Base class for the interpreter-level implementations of object spaces. http://codespeak.net/moin/pypy/moin.cgi/ObjectSpace""" @@ -91,6 +94,27 @@ self.setitem(self.builtin.w_dict, self.wrap(name), value) print "finished make_builtins", self + def lookup_builtin(space, w_globals): + "Look up the builtin module to use from the __builtins__ global" + try: + w_builtin = space.getitem(w_globals, space.wrap('__builtins__')) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + else: + if w_builtin is space.builtin: # common case + return space.builtin + if space.is_true(space.isinstance(w_builtin, space.w_dict)): + return module.Module(space, None, w_builtin) + builtin = space.interpclass_w(w_builtin) + if isinstance(builtin, module.Module): + return builtin + # no builtin! make a default one. Given them None, at least. + builtin = module.Module(space, None) + space.setitem(builtin.w_dict, space.wrap('None'), space.w_None) + return builtin + + def XXXget_builtin_module(self, name): if name not in self.sys.builtin_modules: return None Modified: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Thu Feb 17 21:16:12 2005 @@ -35,7 +35,7 @@ except KeyError: return None else: - print "trying to load", name + #print "trying to load", name w_value = loader(space) #print "loaded", w_value space.setitem(self.w_dict, space.wrap(name), w_value) Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Thu Feb 17 21:16:12 2005 @@ -34,7 +34,7 @@ self.blockstack = Stack() self.last_exception = None self.next_instr = 0 - self.builtin = lookup_builtin(space, w_globals) + self.builtin = space.lookup_builtin(w_globals) # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS. # class bodies only have CO_NEWLOCALS. if code.dictscope_needed(): @@ -139,27 +139,6 @@ return self.builtin.getdict() -def lookup_builtin(space, w_globals): - "Look up the builtin module to use from the __builtins__ global" - try: - w_builtin = space.getitem(w_globals, space.wrap('__builtins__')) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - else: - if w_builtin is space.builtin: # common case - return space.builtin - if space.is_true(space.isinstance(w_builtin, space.w_dict)): - return module.Module(space, None, w_builtin) - builtin = space.interpclass_w(w_builtin) - if isinstance(builtin, Module): - return builtin - # no builtin! make a default one. Given them None, at least. - builtin = module.Module(space, None) - space.setitem(builtin.w_dict, space.wrap('None'), space.w_None) - return builtin - - ### Frame Blocks ### class FrameBlock: Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/flowcontext.py Thu Feb 17 21:16:12 2005 @@ -83,7 +83,9 @@ name=None): ExecutionContext.__init__(self, space) self.code = code + self.w_globals = w_globals = space.wrap(globals) + self.crnt_offset = -1 self.crnt_frame = None if closure is None: Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Thu Feb 17 21:16:12 2005 @@ -2,6 +2,7 @@ import sys, operator, types from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable from pypy.interpreter.pycode import PyCode +from pypy.interpreter.module import Module from pypy.interpreter.error import OperationError from pypy.objspace.flow.model import * from pypy.objspace.flow import flowcontext @@ -35,7 +36,9 @@ def initialize(self): import __builtin__ self.concrete_mode = 0 - self.w_builtins = Constant(__builtin__.__dict__) + self.builtin = Module(self, Constant('__builtin__'), Constant(__builtin__.__dict__)) + self.sys = Module(self, Constant('sys'), Constant(sys.__dict__)) + self.sys.recursionlimit = 100 self.w_None = Constant(None) self.w_False = Constant(False) self.w_True = Constant(True) @@ -52,7 +55,10 @@ self.specialcases = {} #self.make_builtins() #self.make_sys() - self.w_sys = self.wrap(sys) + + + def lookup_builtin(self, w_globals): + return self.builtin def loadfromcache(self, key, builder, cache): # when populating the caches, the flow space switches to From pedronis at codespeak.net Thu Feb 17 23:33:28 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 17 Feb 2005 23:33:28 +0100 (MET) Subject: [pypy-svn] r9297 - in pypy/branch/dist-interpapp/pypy: interpreter module/builtin objspace/flow Message-ID: <20050217223328.583CD27B88@code1.codespeak.net> Author: pedronis Date: Thu Feb 17 23:33:28 2005 New Revision: 9297 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Log: find a home for lookup builtin logic such that we don't have circular import problems. The other placements would require moving the imports after the W_Root etc class defs in baseobjspace Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Thu Feb 17 23:33:28 2005 @@ -38,8 +38,6 @@ """Same as BaseWrappable, just new-style instead.""" -from pypy.interpreter import module - class ObjSpace(object): """Base class for the interpreter-level implementations of object spaces. http://codespeak.net/moin/pypy/moin.cgi/ObjectSpace""" @@ -94,27 +92,6 @@ self.setitem(self.builtin.w_dict, self.wrap(name), value) print "finished make_builtins", self - def lookup_builtin(space, w_globals): - "Look up the builtin module to use from the __builtins__ global" - try: - w_builtin = space.getitem(w_globals, space.wrap('__builtins__')) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - else: - if w_builtin is space.builtin: # common case - return space.builtin - if space.is_true(space.isinstance(w_builtin, space.w_dict)): - return module.Module(space, None, w_builtin) - builtin = space.interpclass_w(w_builtin) - if isinstance(builtin, module.Module): - return builtin - # no builtin! make a default one. Given them None, at least. - builtin = module.Module(space, None) - space.setitem(builtin.w_dict, space.wrap('None'), space.w_None) - return builtin - - def XXXget_builtin_module(self, name): if name not in self.sys.builtin_modules: return None Modified: pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pyframe.py Thu Feb 17 23:33:28 2005 @@ -5,7 +5,6 @@ from pypy.interpreter.miscutils import Stack from pypy.interpreter.error import OperationError from pypy.interpreter import pytraceback -from pypy.interpreter import module import __future__ compiler_flags = 0 @@ -34,7 +33,7 @@ self.blockstack = Stack() self.last_exception = None self.next_instr = 0 - self.builtin = space.lookup_builtin(w_globals) + self.builtin = space.builtin.pick_builtin(w_globals) # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS. # class bodies only have CO_NEWLOCALS. if code.dictscope_needed(): Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Thu Feb 17 23:33:28 2005 @@ -1,3 +1,5 @@ +from pypy.interpreter.error import OperationError +from pypy.interpreter import module from pypy.interpreter.newmodule import ExtModule class Module(ExtModule): @@ -102,3 +104,24 @@ '__import__' : 'importing.importhook', } + + def pick_builtin(self, w_globals): + "Look up the builtin module to use from the __builtins__ global" + space = self.space + try: + w_builtin = space.getitem(w_globals, space.wrap('__builtins__')) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + else: + if w_builtin is space.builtin: # common case + return space.builtin + if space.is_true(space.isinstance(w_builtin, space.w_dict)): + return module.Module(space, None, w_builtin) + builtin = space.interpclass_w(w_builtin) + if isinstance(builtin, module.Module): + return builtin + # no builtin! make a default one. Given them None, at least. + builtin = module.Module(space, None) + space.setitem(builtin.w_dict, space.wrap('None'), space.w_None) + return builtin Modified: pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/flow/objspace.py Thu Feb 17 23:33:28 2005 @@ -37,6 +37,9 @@ import __builtin__ self.concrete_mode = 0 self.builtin = Module(self, Constant('__builtin__'), Constant(__builtin__.__dict__)) + def pick_builtin(w_globals): + return self.builtin + self.builtin.pick_builtin = pick_builtin self.sys = Module(self, Constant('sys'), Constant(sys.__dict__)) self.sys.recursionlimit = 100 self.w_None = Constant(None) @@ -56,10 +59,6 @@ #self.make_builtins() #self.make_sys() - - def lookup_builtin(self, w_globals): - return self.builtin - def loadfromcache(self, key, builder, cache): # when populating the caches, the flow space switches to # "concrete mode". In this mode, only Constants are allowed From pedronis at codespeak.net Fri Feb 18 00:25:00 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 18 Feb 2005 00:25:00 +0100 (MET) Subject: [pypy-svn] r9298 - pypy/branch/dist-interpapp/pypy/objspace/test Message-ID: <20050217232500.986F727B90@code1.codespeak.net> Author: pedronis Date: Fri Feb 18 00:25:00 2005 New Revision: 9298 Modified: pypy/branch/dist-interpapp/pypy/objspace/test/test_traceobjspace.py Log: changed for the new world Modified: pypy/branch/dist-interpapp/pypy/objspace/test/test_traceobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/test/test_traceobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/test/test_traceobjspace.py Fri Feb 18 00:25:00 2005 @@ -22,7 +22,7 @@ def test_traceobjspace_basic(self): tspace = self.space - assert tspace.is_true(tspace.w_builtins) + assert tspace.is_true(tspace.builtin) #for name, value in vars(self.space).items(): # if not name.startswith('_'): # self.assert_(value is getattr(t, name)) From pedronis at codespeak.net Fri Feb 18 00:32:38 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 18 Feb 2005 00:32:38 +0100 (MET) Subject: [pypy-svn] r9299 - pypy/branch/dist-interpapp/pypy/tool/test Message-ID: <20050217233238.9B48E27B90@code1.codespeak.net> Author: pedronis Date: Fri Feb 18 00:32:38 2005 New Revision: 9299 Modified: pypy/branch/dist-interpapp/pypy/tool/test/test_pytestsupport.py Log: adapted Modified: pypy/branch/dist-interpapp/pypy/tool/test/test_pytestsupport.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/test/test_pytestsupport.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/test/test_pytestsupport.py Fri Feb 18 00:32:38 2005 @@ -28,7 +28,7 @@ assert x == 43 t = app2interp_temp(app_test_func) f = t.get_function(space) - space.setitem(space.w_builtins, space.wrap('AssertionError'), + space.setitem(space.builtin.w_dict, space.wrap('AssertionError'), build_pytest_assertion(space)) try: f.call_args(Arguments([])) From hpk at codespeak.net Fri Feb 18 11:32:37 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 11:32:37 +0100 (MET) Subject: [pypy-svn] r9300 - in pypy/branch/dist-interpapp/pypy: interpreter interpreter/test module/test objspace objspace/std translator Message-ID: <20050218103237.03E2A27B71@code1.codespeak.net> Author: hpk Date: Fri Feb 18 11:32:37 2005 New Revision: 9300 Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py pypy/branch/dist-interpapp/pypy/objspace/trivial.py pypy/branch/dist-interpapp/pypy/translator/geninterplevel.py Log: - cleanup the initialization process for objectspaces - get rid of space.w_sys and space.w_builtin because instead of getitem(space.w_sys, ...) you can do space.sys.get(unwrapped_name) - trivial objectspace fails the tests but it did before Modified: pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/baseobjspace.py Fri Feb 18 11:32:37 2005 @@ -55,50 +55,28 @@ def __repr__(self): return self.__class__.__name__ - def make_builtins(self, for_builtins): + def make_builtins(self): "NOT_RPYTHON: only for initializing the space." - # initializing builtins may require creating a frame which in - # turn already accesses space.w_builtins, provide a dummy one ... - # XXX TEMPORARY from pypy.module.sys2 import Module w_name = self.wrap('sys') self.sys = Module(self, w_name) - self.w_sys = self.wrap(self.sys) - w_modules = self.sys.get('modules') - self.setitem(w_modules, w_name, self.w_sys) - print "initialized", self.w_sys + self.setitem(w_modules, w_name, self.wrap(self.sys)) + from pypy.module.builtin import Module w_name = self.wrap('__builtin__') self.builtin = Module(self, w_name) - self.w_builtin = self.wrap(self.builtin) - #self.w_builtins = self.builtin.w_dict - self.setitem(w_modules, w_name, self.w_builtin) - self.setitem(self.builtin.w_dict, self.wrap('__builtins__'), self.w_builtin) - print "initialized", self.w_builtin - - # do we need this? - #for key, w_value in for_builtins.items(): - # self.setitem(self.builtin.w_dict, self.wrap(key), w_value) + w_builtin = self.wrap(self.builtin) + self.setitem(w_modules, w_name, w_builtin) + self.setitem(self.builtin.w_dict, self.wrap('__builtins__'), w_builtin) # initialize with "bootstrap types" from objspace (e.g. w_None) for name, value in self.__dict__.items(): if name.startswith('w_'): name = name[2:] - if name.startswith('builtin') or name.startswith('sys'): - continue #print "setitem: space instance %-20s into builtins" % name self.setitem(self.builtin.w_dict, self.wrap(name), value) - print "finished make_builtins", self - - def XXXget_builtin_module(self, name): - if name not in self.sys.builtin_modules: - return None - module = self.sys.builtin_modules[name] - w_module = self.wrap(module) - self.sys.setbuiltinmodule(w_module, name) - return w_module def initialize(self): """NOT_RPYTHON: Abstract method that should put some minimal Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_main.py Fri Feb 18 11:32:37 2005 @@ -17,10 +17,10 @@ testresultoutput = '11\n' def checkoutput(space, expected_output,f,*args): - w_sys = space.w_sys - w_oldout = space.getattr(w_sys, space.wrap("stdout")) + w_oldout = space.sys.get('stdout') capturefn = udir.join('capturefile') capturefile = capturefn.open('w') + w_sys = space.sys.getmodule('sys') space.setattr(w_sys, space.wrap("stdout"), space.wrap(capturefile)) try: f(*(args + (space,))) @@ -29,7 +29,6 @@ capturefile.close() assert capturefn.read(mode='rU') == expected_output - testfn = 'tmp_hello_world.py' class TestMain: Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_objspace.py Fri Feb 18 11:32:37 2005 @@ -89,15 +89,14 @@ class TestModuleMinimal: def test_sys_exists(self): - w_sys = self.space.w_sys - assert self.space.is_true(w_sys) + assert self.space.sys def test_import_exists(self): space = self.space - w_builtin = space.w_builtin - assert space.is_true(w_builtin) + assert space.builtin w_name = space.wrap('__import__') - w_import = self.space.getattr(w_builtin, w_name) + w_builtin = space.sys.getmodule('__builtin__') + w_import = self.space.getattr(w_builtin, w_name) assert space.is_true(w_import) def test_sys_import(self): Modified: pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py Fri Feb 18 11:32:37 2005 @@ -9,10 +9,8 @@ b.cStringIO = cStringIO b.sys = sys -class TestSysTests: - def test_stdout_exists(self): - s = self.space - assert s.is_true(s.getattr(s.w_sys, s.wrap("stdout"))) +def test_stdout_exists(space): + assert space.sys.get('stdout') class AppTestAppSysTests: def test_path_exists(self): Modified: pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py Fri Feb 18 11:32:37 2005 @@ -55,40 +55,28 @@ self.w_None = W_NoneObject(self) self.w_False = W_BoolObject(self, False) self.w_True = W_BoolObject(self, True) - from pypy.interpreter.special import NotImplemented, Ellipsis + from pypy.interpreter.special import NotImplemented, Ellipsis self.w_NotImplemented = self.wrap(NotImplemented(self)) self.w_Ellipsis = self.wrap(Ellipsis(self)) - for_builtins = {"False": self.w_False, - "True" : self.w_True, - "None" : self.w_None, - "NotImplemented": self.w_NotImplemented, - "Ellipsis": self.w_Ellipsis, - } - # types self.types_w = {} for typedef in self.model.pythontypes: w_type = self.gettypeobject(typedef) setattr(self, 'w_' + typedef.name, w_type) - for_builtins[typedef.name] = w_type + + # exceptions & builtins + mod = self.setup_exceptions() + self.make_builtins() + self.sys.setmodule(self.wrap(mod)) # dummy old-style classes types self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {}) self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {}) - # exceptions - mod = self.setup_exceptions(for_builtins) - # old-style classes #self.setup_old_style_classes() - # install things in the __builtin__ module - self.make_builtins(for_builtins) - - w_exceptions = self.wrap(mod) - self.sys.setbuiltinmodule(w_exceptions, 'exceptions') - def setup_old_style_classes(self): """NOT_RPYTHON""" from pypy.module import classobjinterp @@ -98,7 +86,7 @@ self.w_classobj = w_classobj self.w_instance = w_instance - def setup_exceptions(self, for_builtins): + def setup_exceptions(self): """NOT_RPYTHON""" ## hacking things in from pypy.module import exceptionsinterp as ex @@ -133,8 +121,6 @@ w_exc = self.getitem(w_dic, w_name) setattr(self, "w_"+excname, w_exc) - for_builtins[excname] = w_exc - # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module Modified: pypy/branch/dist-interpapp/pypy/objspace/trivial.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/trivial.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/trivial.py Fri Feb 18 11:32:37 2005 @@ -12,7 +12,8 @@ import __builtin__ as cpy_builtin class CPyWrapper(object): - pass + def getdictvalue(self, space, name): + return self.__dict__.get(name, None) class TrivialObjSpace(ObjSpace, DescrOperation): @@ -122,7 +123,10 @@ setattr(self, 'w_' + c.__name__, c) newstuff[c.__name__] = c newstuff.update(self.clone_exception_hierarchy()) - self.make_builtins(newstuff) + self.make_builtins() + # XXX Do we need the following still? + #for name, value in newstuff.items(): + # self.builtin.w_dict[name] = value # general stuff def wrap(self, x): Modified: pypy/branch/dist-interpapp/pypy/translator/geninterplevel.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/translator/geninterplevel.py (original) +++ pypy/branch/dist-interpapp/pypy/translator/geninterplevel.py Fri Feb 18 11:32:37 2005 @@ -540,10 +540,10 @@ #self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( # name, self.nameof(func.__name__))) # be lazy - return "(space.getattr(space.w_builtin, %s))" % self.nameof(func.__name__) + return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__) elif modname == 'sys': # be lazy - return "(space.getattr(space.w_sys, %s))" % self.nameof(func.__name__) + return "(space.sys.get(space.str_w(%s)))" % self.nameof(func.__name__) else: print ("WARNING: accessing builtin modules different from sys or __builtin__" " is likely producing non-sense") From hpk at codespeak.net Fri Feb 18 11:45:25 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 11:45:25 +0100 (MET) Subject: [pypy-svn] r9301 - in pypy/branch/dist-interpapp/pypy: interpreter interpreter/test/mixedmodule module module/builtin module/sys2 Message-ID: <20050218104525.C093D27B82@code1.codespeak.net> Author: hpk Date: Fri Feb 18 11:45:25 2005 New Revision: 9301 Added: pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py - copied, changed from r9299, pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Removed: pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py pypy/branch/dist-interpapp/pypy/module/__builtin__interp.py pypy/branch/dist-interpapp/pypy/module/__builtin__module.py pypy/branch/dist-interpapp/pypy/module/sysinterp.py pypy/branch/dist-interpapp/pypy/module/sysmodule.py Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Log: - removed support and definitions of old-style builtins/sys modules (yay!) in favour of the new lazy ones. - cleaned up interpreter/module.py because it doesn't have to care anymore for special sys-attributes - moved newmodule.py -> lazymodule.py Copied: pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py (from r9299, pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py) ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py Fri Feb 18 11:45:25 2005 @@ -5,7 +5,7 @@ import inspect -class ExtModule(Module): +class LazyModule(Module): NOT_RPYTHON_ATTRIBUTES = ['loaders'] Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Fri Feb 18 11:45:25 2005 @@ -36,32 +36,3 @@ w_dict = self.getdict() space.setitem(w_dict, space.wrap('__name__'), w_name) space.setitem(w_dict, space.wrap('__doc__'), w_doc) - - def getdictvalue(self, space, attr): - try: - return space.getitem(self.w_dict, self.space.wrap(attr)) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - # ______ for the 'sys' module only _____ XXX put that - # into a special subclass at some point - if self is space.sys: - if attr == 'exc_type': - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.w_None - else: - return operror.w_type - if attr == 'exc_value': - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.w_None - else: - return operror.w_value - if attr == 'exc_traceback': - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.w_None - else: - return space.wrap(operror.application_traceback) - return None Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py Fri Feb 18 11:45:25 2005 +++ (empty file) @@ -1,105 +0,0 @@ -from pypy.interpreter.module import Module -from pypy.tool.cache import Cache -from pypy.interpreter import gateway -from pypy.interpreter.error import OperationError - -import inspect - -class ExtModule(Module): - - NOT_RPYTHON_ATTRIBUTES = ['loaders'] - - def __init__(self, space, w_name): - """ NOT_RPYTHON """ - Module.__init__(self, space, w_name) - self.lazy = True - self.__class__.buildloaders() - - def get(self, name): - space = self.space - w_value = self.getdictvalue(space, name) - if w_value is None: - raise OperationError(space.w_AttributeError, space.wrap(name)) - return w_value - - def getdictvalue(self, space, name): - try: - return space.getitem(self.w_dict, space.wrap(name)) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - if not self.lazy: - return None - try: - loader = self.loaders[name] - except KeyError: - return None - else: - #print "trying to load", name - w_value = loader(space) - #print "loaded", w_value - space.setitem(self.w_dict, space.wrap(name), w_value) - return w_value - - def getdict(self): - if self.lazy: - space = self.space - for name in self.loaders: - w_value = self.get(name) - space.setitem(self.w_dict, space.wrap(name), w_value) - self.lazy = False - return self.w_dict - - def buildloaders(cls): - """ NOT_RPYTHON """ - if not hasattr(cls, 'loaders'): - # build a constant dictionary out of - # applevel/interplevel definitions - cls.loaders = loaders = {} - pkgroot = cls.__module__ - for name, spec in cls.interpleveldefs.items(): - loaders[name] = getinterpevalloader(pkgroot, spec) - for name, spec in cls.appleveldefs.items(): - loaders[name] = getappfileloader(pkgroot, spec) - buildloaders = classmethod(buildloaders) - -def getinterpevalloader(pkgroot, spec): - """ NOT_RPYTHON """ - def ifileloader(space): - d = {'space' : space} - # EVIL HACK (but it works, and this is not RPython :-) - while 1: - try: - value = eval(spec, d) - except NameError, ex: - #assert name not in d, "huh, am i looping?" - name = ex.args[0].split("'")[1] # super-Evil - try: - d[name] = __import__(pkgroot+'.'+name, None, None, [name]) - except ImportError: - d[name] = __import__(name, None, None, [name]) - else: - #print spec, "->", value - if hasattr(value, 'func_code'): # semi-evil - return space.wrap(gateway.interp2app(value)) - assert value is not None - return value - return ifileloader - -applevelcache = Cache() -def getappfileloader(pkgroot, spec): - """ NOT_RPYTHON """ - # hum, it's a bit more involved, because we usually - # want the import at applevel - modname, attrname = spec.split('.') - impbase = pkgroot + '.' + modname - mod = __import__(impbase, None, None, ['attrname']) - app = applevelcache.getorbuild(mod, buildapplevelfrommodule, None) - def afileloader(space): - return app.wget(space, attrname) - return afileloader - -def buildapplevelfrommodule(mod, _): - """ NOT_RPYTHON """ - source = inspect.getsource(mod) - return gateway.applevel(source) Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py Fri Feb 18 11:45:25 2005 +++ (empty file) @@ -1,180 +0,0 @@ -""" - -Helpers to build extension modules. - -""" - -from __future__ import generators # for generators.compiler_flag -import os, sys -import autopath -from pypy.interpreter import gateway -from pypy.interpreter.error import OperationError -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.function import Function -from pypy.interpreter.module import Module - -class interplevelimport_interp2app(gateway.interp2app): - - def __init__(self, f, w_globals): - "NOT_RPYTHON" - gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False) - self.w_globals = w_globals - - def _getglobals(self, space): - "NOT_RPYTHON" - return self.w_globals - - -class BuiltinModule(Module): - """A Module subclass specifically for built-in modules.""" - - # '__builtins__' is stored in self.__dict__ by - # self.interplevel{exec,eval,execfile}() - NOT_RPYTHON_ATTRIBUTES = ['__builtins__'] - - def __init__(self, space, modulename, w_dict=None, sourcefile=None): - """NOT_RPYTHON - Load the named built-in module, by default from the source file - 'pypy/module/module.py', which is app-level Python code - with a few special features that allow it to include interp-level - bits. (See pypy/module/test/foomodule.py) - - The module has two parts: the interp-level objects, stored as - attributes of 'self', and the app-level objects, stored in the - dictionary 'self.w_dict'. The app-level definition of the module - runs with 'self.w_dict' as globals. The interp-level bits are - executed with 'self.__dict__' as globals, i.e. they can read and - change the attributes of 'self' as global variables. - """ - Module.__init__(self, space, space.wrap(modulename), w_dict) - w_dict = self.w_dict - - # Compile the xxxmodule.py source file - self.__name__ = 'interpreter-level %s' % modulename - self.__file__ = sourcefile or os.path.join(autopath.pypydir, 'module', - modulename+'module.py') - space.setitem(w_dict, space.wrap('__file__'), - space.wrap(self.__file__)) - f = open(self.__file__, 'r') - modulesource = f.read() - f.close() - code = compile(modulesource, self.__file__, 'exec', - generators.compiler_flag) - pycode = PyCode(space)._from_code(code) - - # Set the hooks that call back from app-level to interp-level - w_builtins = space.w_builtins - self.__saved_hooks = {} - newhooks = {} - - for name, impl in [ - ('__interplevel__exec', self.interplevelexec.im_func), - ('__interplevel__eval', self.interpleveleval.im_func), - ('__interplevel__execfile', self.interplevelexecfile.im_func), - ('__import__', self.interplevelimport.im_func)]: - hook = gateway.interp2app_temp(impl).get_method(self) - w_name = space.wrap(name) - try: - self.__saved_hooks[name] = space.getitem(w_builtins, w_name) - except OperationError: - pass - w_hook = space.wrap(hook) - space.setitem(w_builtins, w_name, w_hook) - newhooks[name] = w_hook - space.setitem(self.w_dict, space.wrap('__builtins__'), - space.w_builtins) - - # Temporarily install an '__applevel__' pseudo-module - sys.modules['__applevel__'] = AppModuleHack(self) - - # Run the app-level module definition (xxxmodule.py) - pycode.exec_code(space, w_dict, w_dict) - - # Remove the pseudo-module - del sys.modules['__applevel__'] - try: - del self.__applevel__ - except AttributeError: - pass - - # Remove/restore the hooks unless they have been modified at app-level - for name, w_hook in newhooks.items(): - w_name = space.wrap(name) - try: - w_current = space.getitem(w_builtins, w_name) - except OperationError: - pass - else: - if space.is_true(space.is_(w_current, w_hook)): - if name in self.__saved_hooks: - space.setitem(w_builtins, w_name, - self.__saved_hooks[name]) - else: - space.delitem(w_builtins, w_name) - del self.__saved_hooks - - def interplevelexec(self, w_codestring): - "NOT_RPYTHON: 'exec' a string at interp-level." - codestring = self.space.str_w(w_codestring) - exec codestring in self.__dict__ - return self.space.w_None - - def interpleveleval(self, w_codestring): - """NOT_RPYTHON: 'eval' a string at interp-level. The result must - be None or a wrapped object, which is returned to the caller.""" - space = self.space - codestring = space.str_w(w_codestring) - w_result = eval(codestring, self.__dict__) - if w_result is None: - w_result = space.w_None # else assume that it is already wrapped - return w_result - - def interplevelexecfile(self, w_filename): - """NOT_RPYTON: 'exec' a file at interp-level. The file should be in - the same directory as the xxxmodule.py source file of the module.""" - filename = self.space.str_w(w_filename) - filename = os.path.join(os.path.dirname(self.__file__), filename) - execfile(filename, self.__dict__) - return self.space.w_None - - def interplevelimport(self, w_modulename, w_globals, w_locals, w_fromlist): - """NOT_RPYTHON: Hook for 'from __interplevel__ import something'. - If there is a wrapped interp-level object 'w_something', returns it. - If there is an interp-level function 'def something(w_x, w_y...)', - build an appropriate gateway and returns it. - """ - space = self.space - w = space.wrap - if space.is_true(space.eq(w_modulename, w('__interplevel__'))): - if w_fromlist == space.w_None: - raise ImportError, "must use 'from __interplevel__ import xx'" - for w_name in space.unpacktuple(w_fromlist): - name = space.str_w(w_name) - if not hasattr(self, 'w_' + name): - f = getattr(self, name) - func = interplevelimport_interp2app(f, self.w_dict) - w_result = space.wrap(func) - else: - w_result = getattr(self, 'w_' + name) - space.setitem(self.w_dict, w_name, w_result) - return space.wrap(self) - else: - return space.call_function(self.__saved_hooks['__import__'], - w_modulename, w_globals, - w_locals, w_fromlist) - -class AppModuleHack: - """NOT_RPYTHON - For interp-level convenience: 'from __applevel__ import func' - imports the app-level function 'func' via an appropriate gateway. - """ - def __init__(self, builtinmodule): - self.space = builtinmodule.space - self.w_dict = builtinmodule.w_dict - def __getattr__(self, name): - if name.startswith('__'): - raise AttributeError, name - w_func = self.space.getitem(self.w_dict, self.space.wrap(name)) - def caller(*args): - return self.space.call_function(w_func, *args) - return caller Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py Fri Feb 18 11:45:25 2005 @@ -1,6 +1,6 @@ -from pypy.interpreter.newmodule import ExtModule +from pypy.interpreter.lazymodule import LazyModule -class Module(ExtModule): +class Module(LazyModule): interpleveldefs = { '__name__' : '(space.wrap("mixedmodule"))', '__doc__' : '(space.wrap("mixedmodule doc"))', Deleted: /pypy/branch/dist-interpapp/pypy/module/__builtin__interp.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/module/__builtin__interp.py Fri Feb 18 11:45:25 2005 +++ (empty file) @@ -1,326 +0,0 @@ -""" -Implementation of interpreter-level builtins. -""" -from pypy.interpreter.module import Module -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.error import OperationError -from pypy.interpreter.baseobjspace import BaseWrappable, W_Root -from pypy.interpreter.gateway import NoneNotWrapped - -import __builtin__ as cpy_builtin - -# import useful app-level functions -from __applevel__ import execfile, callable, _iter_generator - - -def _actframe(position=0): - return space.getexecutioncontext().framestack.top(position) - -def globals(): - return _actframe().w_globals - -def locals(): - return _actframe().getdictscope() - -def _caller_globals(position=1): - return _actframe(position).w_globals -# -_caller_globals.unwrap_spec = [int] - -def _caller_locals(position=1): - return _actframe(position).getdictscope() -# -_caller_locals.unwrap_spec = [int] - - -def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None): - import os - w = space.wrap - if os.path.exists(f): - w_mod = space.wrap(Module(space, w_modulename)) - space.sys.setmodule(w_mod) - space.setattr(w_mod, w('__file__'), w(f)) - if pkgdir is not None: - space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)])) - w_dict = space.getattr(w_mod, w('__dict__')) - execfile(w(f), w_dict, w_dict) - w_mod = check_sys_modules(w_modulename) - if w_mod is not None and w_parent is not None: - space.setattr(w_parent, w_name, w_mod) - return w_mod - else: - return None - -def try_getattr(w_obj,w_name): - try: - return space.getattr(w_obj, w_name) - except OperationError, e: - # ugh, but blame CPython :-/ this is supposed to emulate - # hasattr, which eats all exceptions. - return None - -def try_getitem(w_obj,w_key): - try: - return space.getitem(w_obj, w_key) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise - return None - - -def check_sys_modules(w_modulename): - try: - w_mod = space.getitem(space.sys.w_modules, w_modulename) - except OperationError, e: - pass - else: - return w_mod - if not e.match(space, space.w_KeyError): - raise - return None - -il_len = len - -def __import__(modulename, w_globals=None, - w_locals=None, w_fromlist=None): - if not isinstance(modulename, str): - try: - helper = ', not ' + modulename.__class__.__name__ - except AttributeError: - helper = '' - raise OperationError(space.w_TypeError, - space.wrap("__import__() argument 1 must be string" + helper)) - w = space.wrap - - if w_globals is not None and not space.is_true(space.is_(w_globals, space.w_None)): - ctxt_w_name = try_getitem(w_globals,w('__name__')) - ctxt_w_path = try_getitem(w_globals,w('__path__')) - else: - ctxt_w_name = None - ctxt_w_path = None - - rel_modulename = None - if ctxt_w_name is not None: - - ctxt_name_prefix_parts = space.str_w(ctxt_w_name).split('.') - if ctxt_w_path is None: # context is a plain module - ctxt_name_prefix_parts = ctxt_name_prefix_parts[:-1] - if ctxt_name_prefix_parts: - rel_modulename = '.'.join(ctxt_name_prefix_parts+[modulename]) - else: # context is a package module - rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename - if rel_modulename is not None: - w_mod = check_sys_modules(w(rel_modulename)) - if (w_mod is None or - not space.is_true(space.is_(w_mod,space.w_None))): - - w_mod = absolute_import(rel_modulename, - il_len(ctxt_name_prefix_parts), - w_fromlist, tentative=1) - if w_mod is not None: - return w_mod - else: - rel_modulename = None - - w_mod = absolute_import(modulename,0,w_fromlist, tentative=0) - if rel_modulename is not None: - space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None) - return w_mod -# -__import__.unwrap_spec = [str,W_Root,W_Root,W_Root] - -def absolute_import(modulename, baselevel, w_fromlist, tentative): - w = space.wrap - - w_mod = None - parts = modulename.split('.') - prefix = [] - # it would be nice if we could do here: w_path = space.sys.w_path - # instead: - w_path = space.getitem(space.sys.w_dict, space.wrap('path')) - - first = None - level = 0 - - for part in parts: - w_mod = load_part(w_path, prefix, part, w_mod, tentative=tentative) - if w_mod is None: - return None - - if baselevel == level: - first = w_mod - tentative = 0 - prefix.append(part) - w_path = try_getattr(w_mod,w('__path__')) - level += 1 - - if w_fromlist is not None and space.is_true(w_fromlist): - if w_path is not None: - for w_name in space.unpackiterable(w_fromlist): - load_part(w_path, prefix, space.str_w(w_name), w_mod, - tentative=1) - return w_mod - else: - return first - -def load_part(w_path, prefix, partname, w_parent, tentative): - w = space.wrap - modulename = '.'.join(prefix+[partname]) - w_modulename = w(modulename) - w_mod = check_sys_modules(w_modulename) - if w_mod is not None: - if not space.is_true(space.is_(w_mod,space.w_None)): - return w_mod - else: - w_mod = space.get_builtin_module(modulename) - if w_mod is not None: - return w_mod - import os - for path in space.unpackiterable(w_path): - dir = os.path.join(space.str_w(path), partname) - if os.path.isdir(dir): - f = os.path.join(dir,'__init__.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname), - pkgdir=dir) - if w_mod is not None: - return w_mod - f = os.path.join(space.str_w(path), partname + '.py') - w_mod = try_import_mod(w_modulename, f, w_parent, w(partname)) - if w_mod is not None: - return w_mod - - if tentative: - return None - else: - # ImportError - w_failing = w_modulename - w_exc = space.call_function(space.w_ImportError, w_failing) - raise OperationError(space.w_ImportError, w_exc) - -def compile(str_, filename, startstr, - supplied_flags=0, dont_inherit=0): - #print (str_, filename, startstr, supplied_flags, dont_inherit) - # XXX we additionally allow GENERATORS because compiling some builtins - # requires it. doesn't feel quite right to do that here. - supplied_flags |= 4096 - if not dont_inherit: - try: - frame = _actframe() - except IndexError: - pass - else: - supplied_flags |= frame.get_compile_flags() - try: - c = cpy_builtin.compile(str_, filename, startstr, supplied_flags, 1) - # It would be nice to propagate all exceptions to app level, - # but here we only propagate the 'usual' ones, until we figure - # out how to do it generically. - except SyntaxError,e: - raise OperationError(space.w_SyntaxError,space.wrap(str(e))) - except ValueError,e: - raise OperationError(space.w_ValueError,space.wrap(str(e))) - except TypeError,e: - raise OperationError(space.w_TypeError,space.wrap(str(e))) - return space.wrap(PyCode(space)._from_code(c)) -# -compile.unwrap_spec = [str,str,str,int,int] - - -def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped): - w = space.wrap - - if space.is_true(space.isinstance(w_source, space.w_str)): - w_codeobj = compile(space.str_w(w_source).lstrip(' \t'), "", "eval") - elif isinstance(space.interpclass_w(w_source), PyCode): - w_codeobj = w_source - else: - raise OperationError(space.w_TypeError, - w('eval() arg 1 must be a string or code object')) - - if w_globals is None: - w_globals = globals() - w_locals = locals() - elif w_locals is None: - w_locals = w_globals - - return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals) - -def abs(w_val): - "abs(number) -> number\n\nReturn the absolute value of the argument." - return space.abs(w_val) - -def chr(w_ascii): - w_character = space.newstring([w_ascii]) - return w_character - -def len(w_obj): - return space.len(w_obj) - -def delattr(w_object, w_name): - space.delattr(w_object, w_name) - return space.w_None - -def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): - try: - return space.getattr(w_object, w_name) - except OperationError, e: - if e.match(space, space.w_AttributeError): - if w_defvalue is not None: - return w_defvalue - raise - -def hash(w_object): - return space.hash(w_object) - -def oct(w_val): - # XXX does this need to be a space operation? - return space.oct(w_val) - -def hex(w_val): - return space.hex(w_val) - -def round(w_val, w_n=0): - return space.round(w_val, w_n) - -def id(w_object): - return space.id(w_object) - -def cmp(w_x, w_y): - """return 0 when x == y, -1 when x < y and 1 when x > y """ - return space.cmp(w_x, w_y) - -def coerce(w_x, w_y): - """coerce(x, y) -> (x1, y1) - - Return a tuple consisting of the two numeric arguments converted to - a common type, using the same rules as used by arithmetic operations. - If coercion is not possible, raise TypeError.""" - return space.coerce(w_x, w_y) - - -#XXX works only for new-style classes. -#So we have to fix it, when we add support for old-style classes -def _issubtype(w_cls1, w_cls2): - return space.issubtype(w_cls1, w_cls2) - -def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): - if w_sentinel is None: - return space.iter(w_collection_or_callable) - else: - if not space.is_true(callable(w_collection_or_callable)): - raise OperationError(space.w_TypeError, - space.wrap('iter(v, w): w must be callable')) - return _iter_generator(w_collection_or_callable, w_sentinel) - -def ord(w_val): - return space.ord(w_val) - -def pow(w_base, w_exponent, w_modulus=None): - return space.pow(w_base, w_exponent, w_modulus) - -def repr(w_object): - return space.repr(w_object) - -def setattr(w_object, w_name, w_val): - space.setattr(w_object, w_name, w_val) - return space.w_None Deleted: /pypy/branch/dist-interpapp/pypy/module/__builtin__module.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/module/__builtin__module.py Fri Feb 18 11:45:25 2005 +++ (empty file) @@ -1,1049 +0,0 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. -""" - -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ -""" -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py Fri Feb 18 11:45:25 2005 @@ -1,8 +1,8 @@ from pypy.interpreter.error import OperationError from pypy.interpreter import module -from pypy.interpreter.newmodule import ExtModule +from pypy.interpreter.lazymodule import LazyModule -class Module(ExtModule): +class Module(LazyModule): """Built-in functions, exceptions, and other objects. Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. Modified: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py Fri Feb 18 11:45:25 2005 @@ -1,7 +1,7 @@ -from pypy.interpreter.newmodule import ExtModule +from pypy.interpreter.lazymodule import LazyModule from pypy.interpreter.error import OperationError -class Module(ExtModule): +class Module(LazyModule): """Sys Builtin Module. """ def __init__(self, space, w_name): super(Module, self).__init__(space, w_name) @@ -87,7 +87,7 @@ def getdictvalue(self, space, attr): """ specialize access to dynamic exc_* attributes. """ - value = ExtModule.getdictvalue(self, space, attr) + value = LazyModule.getdictvalue(self, space, attr) if value is not None: return value if attr == 'exc_type': Deleted: /pypy/branch/dist-interpapp/pypy/module/sysinterp.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/module/sysinterp.py Fri Feb 18 11:45:25 2005 +++ (empty file) @@ -1,202 +0,0 @@ -""" -Implementation of interpreter-level 'sys' routines. -""" -#from pypy.interpreter.module import Module -from pypy.interpreter.error import OperationError - -import sys as cpy_sys - -def hack_cpython_module(modname): - "NOT_RPYTHON. Steal a module from CPython." - cpy_module = __import__(modname, globals(), locals(), None) - return cpy_module -## # to build the dictionary of the module, we get all the objects -## # accessible as 'self.xxx'. Methods are bound. -## contents = [] -## for name in cpy_module.__dict__: -## # ignore names in '_xyz' -## if not name.startswith('_') or name.endswith('_'): -## value = cpy_module.__dict__[name] -## contents.append((space.wrap(name), space.wrap(value))) -## w_contents = space.newdict(contents) -## return Module(space, space.wrap(modname), w_contents) - -# ____________________________________________________________ -# -# List of built-in modules. -# It should contain the name of all the files 'module/*module.py'. -builtin_module_names = ['__builtin__', 'sys', 'exceptions' - ] - -# Create the builtin_modules dictionary, mapping names to Module instances -builtin_modules = {} -for fn in builtin_module_names: - builtin_modules[fn] = None - -# The following built-in modules are not written in PyPy, so we -# steal them from Python. -for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos', - 'math', '_codecs', 'array', - '_random', '_sre', 'time', '_socket', 'errno', - 'marshal', 'binascii', 'parser']: - if fn not in builtin_modules: - try: - builtin_modules[fn] = hack_cpython_module(fn) - except ImportError: - pass - else: - builtin_module_names.append(fn) - -# ____________________________________________________________ -# -# Common data structures -w_modules = space.newdict([]) -w_warnoptions = space.newlist([]) -w_argv = space.newlist([]) -builtin_module_names.sort() -w_builtin_module_names = space.newtuple([space.wrap(fn) - for fn in builtin_module_names]) - -# Initialize the default path -import os -from pypy.interpreter import autopath -srcdir = os.path.dirname(autopath.pypydir) -python_std_lib = os.path.normpath( - os.path.join(autopath.pypydir, '..','lib-python-2.3.4')) -pypy_override_lib = os.path.join(autopath.pypydir, 'lib') -assert os.path.exists(python_std_lib) -del os, autopath # XXX for the translator. Something is very wrong around here. - -w_initialpath = space.newlist([space.wrap(''), - space.wrap(pypy_override_lib), - space.wrap(python_std_lib), - ] + - [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) - -# XXX - Replace with appropriate PyPy version numbering -w_platform = space.wrap(cpy_sys.platform) -w_maxint = space.wrap(cpy_sys.maxint) -w_byteorder = space.wrap(cpy_sys.byteorder) -w_exec_prefix = space.wrap(cpy_sys.exec_prefix) -w_prefix = space.wrap(cpy_sys.prefix) -w_maxunicode = space.wrap(cpy_sys.maxunicode) -w_stdin = space.wrap(cpy_sys.stdin) -w_stdout = space.wrap(cpy_sys.stdout) -w_stderr = space.wrap(cpy_sys.stderr) - -w_pypy_objspaceclass = space.wrap(space.__class__.__name__) - -# ____________________________________________________________ - -def setmodule(w_module): - """ put a module into the modules dict """ - w_name = space.getattr(w_module, space.wrap('__name__')) - space.setitem(w_modules, w_name, w_module) - -def setbuiltinmodule(w_module, name): - """ put a module into the modules builtin_modules dicts """ - if builtin_modules[name] is None: - builtin_modules[name] = space.unwrap(w_module) - else: - assert builtin_modules[name] is space.unwrap(w_module), ( - "trying to change the builtin-in module %r" % (name,)) - space.setitem(w_modules, space.wrap(name), w_module) - -##def displayhook(w_x): -## w = space.wrap -## if not space.is_true(space.is_(w_x, space.w_None)): -## w_stdout = space.getattr(space.w_sys, space.wrap('stdout')) -## try: -## w_repr = space.repr(w_x) -## except OperationError: -## w_repr = space.wrap("! __repr__ raised an exception") -## w_repr = space.add(w_repr, space.wrap("\n")) -## space.call_method(w_stdout, 'write', -## space.setitem(space.w_builtins, w('_'), w_x) - -def _getframe(w_depth=0): - depth = space.int_w(w_depth) - try: - f = space.getexecutioncontext().framestack.top(depth) - except IndexError: - raise OperationError(space.w_ValueError, - space.wrap("call stack is not deep enough")) - except ValueError: - raise OperationError(space.w_ValueError, - space.wrap("frame index must not be negative")) - return space.wrap(f) - -# directly from the C code in ceval.c, might be moved somewhere else. - -def setrecursionlimit(w_new_limit): - """setrecursionlimit(n) - -Set the maximum depth of the Python interpreter stack to n. This -limit prevents infinite recursion from causing an overflow of the C -stack and crashing Python. The highest possible limit is platform -dependent.""" - new_limit = space.int_w(w_new_limit) - if new_limit <= 0: - raise OperationError(space.w_ValueError, - space.wrap("recursion limit must be positive")) - # global recursion_limit - # we need to do it without writing globals. - space.recursion_limit = new_limit - -def getrecursionlimit(): - """getrecursionlimit() - -Return the current value of the recursion limit, the maximum depth -of the Python interpreter stack. This limit prevents infinite -recursion from causing an overflow of the C stack and crashing Python.""" - - return space.newint(space.recursion_limit) - -checkinterval = 100 - -def setcheckinterval(w_interval): - """setcheckinterval(n) - -Tell the Python interpreter to check for asynchronous events every -n instructions. This also affects how often thread switches occur.""" - - space.sys.checkinterval = space.int_w(w_interval) - -def getcheckinterval(): - """getcheckinterval() -> current check interval; see setcheckinterval().""" - return space.newint(checkinterval) - - -def exc_info(): - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.newtuple([space.w_None,space.w_None,space.w_None]) - else: - return space.newtuple([operror.w_type,operror.w_value, - space.wrap(operror.application_traceback)]) - -def exc_clear(): - operror = space.getexecutioncontext().sys_exc_info() - if operror is not None: - operror.clear(space) - -def pypy_getudir(): - """NOT_RPYTHON""" - from pypy.tool.udir import udir - return space.wrap(str(udir)) - -def getdefaultencoding(): - """getdefaultencoding() -> return the default encoding used for UNICODE""" - return space.wrap(cpy_sys.getdefaultencoding()) - -def getrefcount(w_obj): - """getrefcount(object) -> integer - -Return the reference count of object. The count returned is generally -one higher than you might expect, because it includes the (temporary) -reference as an argument to getrefcount(). -""" - # From the results i get when using this i need to apply a fudge - # value of 6 to get results comparable to cpythons. /Arre - return space.wrap(cpy_sys.getrefcount(w_obj) - 6) - Deleted: /pypy/branch/dist-interpapp/pypy/module/sysmodule.py ============================================================================== --- /pypy/branch/dist-interpapp/pypy/module/sysmodule.py Fri Feb 18 11:45:25 2005 +++ (empty file) @@ -1,70 +0,0 @@ -""" -The 'sys' module. -""" - -__interplevel__execfile('sysinterp.py') - -# Common data structures -from __interplevel__ import initialpath as path -from __interplevel__ import modules, argv -from __interplevel__ import warnoptions, builtin_module_names -from __interplevel__ import maxunicode - -# Objects from interpreter-level -from __interplevel__ import stdin, stdout, stderr, maxint -from __interplevel__ import platform, byteorder -from __interplevel__ import pypy_objspaceclass -from __interplevel__ import exec_prefix, prefix - -# Functions from interpreter-level -from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir -from __interplevel__ import getrecursionlimit, setrecursionlimit -from __interplevel__ import getcheckinterval, setcheckinterval -from __interplevel__ import getdefaultencoding, getrefcount - -# Dummy -executable = 'py.py' -api_version = 0 -copyright = '' -version = '2.3a0 (pypy build)' -version_info = (2, 3, 0, 'alpha', 0) -hexversion = 0x020300a0 -ps1 = '>>>> ' -ps2 = '.... ' - - -# XXX not called by the core yet -def excepthook(exctype, value, traceback): - from traceback import print_exception - print_exception(exctype, value, traceback) - -__excepthook__ = excepthook # this is exactly like in CPython - -def exit(exitcode=0): - # note that we cannot use SystemExit(exitcode) here. - # The comma version leads to an extra de-tupelizing - # in normalize_exception, which is exactlylike CPython. - raise SystemExit, exitcode - -def displayhook(obj): - if obj is not None: - __builtins__['_'] = obj - # NB. this is slightly more complicated in CPython, - # see e.g. the difference with >>> print 5,; 8 - print `obj` - -__displayhook__ = displayhook # this is exactly like in CPython - -def getfilesystemencoding(): - """getfilesystemencoding() -> string - -Return the encoding used to convert Unicode filenames in -operating system filenames.""" - - if platform == "win32": - encoding = "mbcs" - elif platform == "darwin": - encoding = "utf-8" - else: - encoding = None - return encoding From hpk at codespeak.net Fri Feb 18 11:56:37 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 11:56:37 +0100 (MET) Subject: [pypy-svn] r9302 - in pypy/branch/dist-interpapp/pypy: module/builtin objspace/std Message-ID: <20050218105637.5813B27B82@code1.codespeak.net> Author: hpk Date: Fri Feb 18 11:56:37 2005 New Revision: 9302 Modified: pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py Log: move the "dict.fromkeys" special case out of builtins to the standard objectspace Modified: pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py (original) +++ pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py Fri Feb 18 11:56:37 2005 @@ -53,21 +53,6 @@ return self.f(klass, *args, **kwargs) return newfunc -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - # super is a modified version from Guido's tutorial # http://www.python.org/2.2.3/descrintro.html # it exposes the same special attributes as CPython's. Modified: pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/objspace.py Fri Feb 18 11:56:37 2005 @@ -74,6 +74,17 @@ self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {}) self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {}) + # fix up a problem where multimethods apparently don't + # like to define this at interp-level + self.appexec([self.w_dict], """ + (dict): + def fromkeys(cls, seq, value=None): + r = cls() + for s in seq: + r[s] = value + return r + dict.fromkeys = classmethod(fromkeys) + """) # old-style classes #self.setup_old_style_classes() From hpk at codespeak.net Fri Feb 18 12:06:32 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 12:06:32 +0100 (MET) Subject: [pypy-svn] r9303 - pypy/branch/dist-interpapp/pypy Message-ID: <20050218110632.32B0B27B76@code1.codespeak.net> Author: hpk Date: Fri Feb 18 12:06:31 2005 New Revision: 9303 Modified: pypy/branch/dist-interpapp/pypy/TODO Log: modified the todo list Modified: pypy/branch/dist-interpapp/pypy/TODO ============================================================================== --- pypy/branch/dist-interpapp/pypy/TODO (original) +++ pypy/branch/dist-interpapp/pypy/TODO Fri Feb 18 12:06:31 2005 @@ -20,21 +20,13 @@ * (documentation) remove/retire all web-pages referencing e.g. AnnSpace or other deprecated stuff -* Review, enhance the new mixed-level module mechanism - (e.g. the module/builtin*.py files comprise the builtin module) - and try to apply the same technique for the application level - type definitions (types.py). Think about a way to split up - especially app-level definitions of __builtin__ into multiple - files. (like allowing __builtin__ to be a directory with files - comprising the complete definition of the builtin module etc.pp) - * review whatever you like StdObjSpace =========== -* find a way via hacking or elegance to run CPython's unit tests - against the StdObjSpace. +* allow CPython's "output-checking" tests to run in a convenient + way over StdObjSpace * String formatting is agonizingly slow. From tismer at codespeak.net Fri Feb 18 13:28:48 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Fri, 18 Feb 2005 13:28:48 +0100 (MET) Subject: [pypy-svn] r9304 - pypy/dist/pypy/lib/test2 Message-ID: <20050218122848.B2AA227B76@code1.codespeak.net> Author: tismer Date: Fri Feb 18 13:28:48 2005 New Revision: 9304 Modified: pypy/dist/pypy/lib/test2/test_md5.py Log: fixed the md5 test. This failed since appspace is no longer importable. XXX how do we handle this in general? Modified: pypy/dist/pypy/lib/test2/test_md5.py ============================================================================== --- pypy/dist/pypy/lib/test2/test_md5.py (original) +++ pypy/dist/pypy/lib/test2/test_md5.py Fri Feb 18 13:28:48 2005 @@ -7,8 +7,16 @@ import autopath import string, unittest import md5 # CPython's implementation in C. -from pypy.appspace import md5 as pymd5 # The pure Python implementation. - +# since appspace is gone, we cannot test this way any longer: +#from pypy.appspace import md5 as pymd5 # The pure Python implementation. +# instead, we fake a module. +# XXX think of a better wayto do this +import os, new +# fake import of the python module which we cannot see +import pypy +fname = os.path.join(pypy.__path__[0], 'lib', 'md5.py') +pymd5 = new.module('pymd5') +exec file(fname).read() in pymd5.__dict__ # Helpers... From hpk at codespeak.net Fri Feb 18 14:20:07 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 14:20:07 +0100 (MET) Subject: [pypy-svn] r9305 - in pypy/branch/dist-interpapp/pypy/objspace: . std Message-ID: <20050218132007.199FC27B76@code1.codespeak.net> Author: hpk Date: Fri Feb 18 14:20:06 2005 New Revision: 9305 Modified: pypy/branch/dist-interpapp/pypy/objspace/descroperation.py pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Log: better AttributeError messages Modified: pypy/branch/dist-interpapp/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/descroperation.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/descroperation.py Fri Feb 18 14:20:06 2005 @@ -5,6 +5,11 @@ from pypy.interpreter.gateway import BuiltinCode from pypy.interpreter.argument import Arguments +def raiseattrerror(space, w_obj, name): + w_type = space.type(w_obj) + msg = "'%s' object has not attribute '%s'" %(w_type.name, name) + raise OperationError(space.w_AttributeError, space.wrap(msg)) + class Object: def descr__getattribute__(space, w_obj, w_name): name = space.str_w(w_name) @@ -17,8 +22,7 @@ return w_value if w_descr is not None: return space.get(w_descr, w_obj) - - raise OperationError(space.w_AttributeError, w_name) + raiseattrerror(space, w_obj, name) def descr__setattr__(space, w_obj, w_name, w_value): name = space.str_w(w_name) @@ -29,7 +33,7 @@ w_dict = space.getdict(w_obj) if w_dict is not None: return space.setitem(w_dict, w_name, w_value) - raise OperationError(space.w_AttributeError, w_name) + raiseattrerror(space, w_obj, name) def descr__delattr__(space, w_obj, w_name): name = space.str_w(w_name) @@ -44,7 +48,7 @@ except OperationError, ex: if not ex.match(space, space.w_KeyError): raise - raise OperationError(space.w_AttributeError, w_name) + raiseattrerror(space, w_obj, name) def descr__init__(space, w_obj, __args__): pass # XXX some strange checking maybe Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Fri Feb 18 14:20:06 2005 @@ -203,7 +203,8 @@ return space.get(w_value, space.w_None, w_type) if w_descr is not None: return space.get(w_descr,w_type) - raise OperationError(space.w_AttributeError,w_name) + msg = "type object '%s' has no attribute '%s'" %(w_type.name, name) + raise OperationError(space.w_AttributeError, space.wrap(msg)) def setattr__Type_ANY_ANY(space, w_type, w_name, w_value): name = space.str_w(w_name) From pedronis at codespeak.net Fri Feb 18 14:27:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 18 Feb 2005 14:27:54 +0100 (MET) Subject: [pypy-svn] r9306 - pypy/branch/dist-interpapp/pypy/objspace Message-ID: <20050218132754.ECC2A27B76@code1.codespeak.net> Author: pedronis Date: Fri Feb 18 14:27:54 2005 New Revision: 9306 Modified: pypy/branch/dist-interpapp/pypy/objspace/descroperation.py Log: match CPython Modified: pypy/branch/dist-interpapp/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/descroperation.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/descroperation.py Fri Feb 18 14:27:54 2005 @@ -7,7 +7,7 @@ def raiseattrerror(space, w_obj, name): w_type = space.type(w_obj) - msg = "'%s' object has not attribute '%s'" %(w_type.name, name) + msg = "'%s' object has no attribute '%s'" %(w_type.name, name) raise OperationError(space.w_AttributeError, space.wrap(msg)) class Object: From hpk at codespeak.net Fri Feb 18 14:44:58 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 14:44:58 +0100 (MET) Subject: [pypy-svn] r9307 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050218134458.C0B0D27B76@code1.codespeak.net> Author: hpk Date: Fri Feb 18 14:44:58 2005 New Revision: 9307 Modified: pypy/branch/dist-interpapp/pypy/interpreter/interactive.py pypy/branch/dist-interpapp/pypy/interpreter/py.py Log: add startup-time for interactive console :-) Modified: pypy/branch/dist-interpapp/pypy/interpreter/interactive.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/interactive.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/interactive.py Fri Feb 18 14:44:58 2005 @@ -4,6 +4,7 @@ from pypy.interpreter import executioncontext, baseobjspace import sys import code +import time class PyPyConsole(code.InteractiveConsole): @@ -22,8 +23,9 @@ #banner = "Python %s in pypy\n%s / %s" % ( # sys.version, self.__class__.__name__, # self.space.__class__.__name__) - banner = "PyPy in %s on top of Python %s" % ( - self.space.__class__.__name__, sys.version.split()[0]) + elapsed = time.time() - self.space._starttime + banner = "PyPy in %s on top of Python %s (startupttime: %.2f secs)" % ( + self.space.__class__.__name__, sys.version.split()[0], elapsed) code.InteractiveConsole.interact(self, banner) def raw_input(self, prompt=""): Modified: pypy/branch/dist-interpapp/pypy/interpreter/py.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/py.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/py.py Fri Feb 18 14:44:58 2005 @@ -9,6 +9,7 @@ from pypy.tool.optik import make_option from pypy.interpreter import main, interactive, error import os, sys +import time class Options(option.Options): verbose = os.getenv('PYPY_TB') @@ -42,11 +43,13 @@ return options def main_(argv=None): + starttime = time.time() from pypy.tool import tb_server args = option.process_options(get_main_options(), Options, argv[1:]) space = None try: space = option.objspace() + space._starttime = starttime assert 'pypy.tool.udir' not in sys.modules, ( "running py.py should not import pypy.tool.udir, which is\n" "only for testing or translating purposes.") From arigo at codespeak.net Fri Feb 18 14:56:54 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 14:56:54 +0100 (MET) Subject: [pypy-svn] r9308 - pypy/branch/dist-interpapp/pypy/objspace/std Message-ID: <20050218135654.1C05427B76@code1.codespeak.net> Author: arigo Date: Fri Feb 18 14:56:53 2005 New Revision: 9308 Modified: pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py Log: Make W_TypeObject.dict_w lazy-loading, following the model of LazyModule. This allows the multimethods to be installed only when needed. Modified: pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py Fri Feb 18 14:56:53 2005 @@ -73,15 +73,19 @@ from pypy.objspace.std.objecttype import object_typedef w = space.wrap - rawdict = typedef.rawdict.copy() + rawdict = typedef.rawdict + lazyloaders = {} if isinstance(typedef, StdTypeDef): # get all the sliced multimethods multimethods = slicemultimethods(space, typedef) - for name, gateway in multimethods.items(): - assert name not in rawdict, 'name clash: %s in %s_typedef' % ( - name, typedef.name) - rawdict[name] = gateway + for name, loader in multimethods.items(): + if name in rawdict: + # the name specified in the rawdict has priority + continue + assert name not in lazyloaders, ( + 'name clash: %s in %s.lazyloaders' % (name, typedef.name)) + lazyloaders[name] = loader # compute the bases if typedef is object_typedef: @@ -95,8 +99,10 @@ for descrname, descrvalue in rawdict.items(): dict_w[descrname] = w(descrvalue) - return W_TypeObject(space, typedef.name, bases_w, dict_w, - overridetypedef=typedef) + w_type = W_TypeObject(space, typedef.name, bases_w, dict_w, + overridetypedef=typedef) + w_type.lazyloaders = lazyloaders + return w_type def hack_out_multimethods(ns): "NOT_RPYTHON: initialization-time only." @@ -261,29 +267,30 @@ return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) def slicemultimethod(space, multimethod, typedef, result, local=False): - from pypy.objspace.std.objecttype import object_typedef for i in range(len(multimethod.specialnames)): - # each MultimethodCode embeds a multimethod methname = multimethod.specialnames[i] if methname in result: # conflict between e.g. __lt__ and # __lt__-as-reversed-version-of-__gt__ - gw = result[methname] - if gw.bound_position < i: + loader = result[methname] + if loader.bound_position < i: continue - prefix, list_of_typeorders = sliced_typeorders( - space.model.typeorder, multimethod, typedef, i, local=local) - exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, - baked_perform_call=False) - if fallback: - continue # skip empty multimethods - trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals, - multimethod, i, - allow_NotImplemented_results=True) - gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) - gw.bound_position = i # for the check above - result[methname] = gw + def multimethod_loader(i=i, methname=methname): + prefix, list_of_typeorders = sliced_typeorders( + space.model.typeorder, multimethod, typedef, i, local=local) + exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, + baked_perform_call=False) + if fallback: + return None # skip empty multimethods + trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals, + multimethod, i, + allow_NotImplemented_results=True) + gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) + return space.wrap(gw) + + multimethod_loader.bound_position = i # for the check above + result[methname] = multimethod_loader def slicemultimethods(space, typedef): result = {} Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Fri Feb 18 14:56:53 2005 @@ -8,6 +8,8 @@ class W_TypeObject(W_Object): from pypy.objspace.std.typetype import type_typedef as typedef + lazyloaders = None # can be overridden by specific instances + def __init__(w_self, space, name, bases_w, dict_w, overridetypedef=None): W_Object.__init__(w_self, space) @@ -110,6 +112,13 @@ try: return w_self.dict_w[attr] except KeyError: + if w_self.lazyloaders and attr in w_self.lazyloaders: + loader = w_self.lazyloaders[attr] + del w_self.lazyloaders[attr] + w_value = loader() + if w_value is not None: # None means no such attribute + w_self.dict_w[attr] = w_value + return w_value return None def lookup(w_self, key): @@ -148,6 +157,10 @@ def getdict(w_self): # XXX should return a + if w_self.lazyloaders: + for attr in w_self.lazyloaders.keys(): + w_self.getdictvalue(w_self.space, attr) + del w_self.lazyloaders space = w_self.space dictspec = [] for key, w_value in w_self.dict_w.items(): @@ -215,6 +228,8 @@ w_type.dict_w[name] = w_value def delattr__Type_ANY(space, w_type, w_name): + if w_type.lazyloaders: + w_type.getdict() # force un-lazification name = space.str_w(w_name) w_descr = space.lookup(w_type, name) if w_descr is not None: Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py Fri Feb 18 14:56:53 2005 @@ -62,7 +62,11 @@ return space.w_object def descr__doc(space, w_type): - return w_type.dict_w.get('__doc__') + w_result = w_type.getdictvalue(space, '__doc__') + if w_result is None: + return space.w_None + else: + return w_result # ____________________________________________________________ From hpk at codespeak.net Fri Feb 18 15:26:50 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 15:26:50 +0100 (MET) Subject: [pypy-svn] r9309 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050218142650.1EB2627B76@code1.codespeak.net> Author: hpk Date: Fri Feb 18 15:26:49 2005 New Revision: 9309 Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_module.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Log: let accesses to __dict__ and other internal type-descrs raise a TypeError (like CPython). removed superflous code. Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/module.py Fri Feb 18 15:26:49 2005 @@ -20,9 +20,6 @@ def getdict(self): return self.w_dict - def setdict(self, w_dict): - self.w_dict = w_dict - def descr_module__new__(space, w_subtype, __args__): module = space.allocate_instance(Module, w_subtype) module.__init__(space, space.wrap('?')) Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_module.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_module.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_module.py Fri Feb 18 15:26:49 2005 @@ -37,6 +37,8 @@ delattr(m, 'x') raises(AttributeError, getattr, m, 'x') raises(AttributeError, delattr, m, 'x') + raises(TypeError, setattr, m, '__dict__', {}) + def test_docstring(self): import sys foo = type(sys)('foo') Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Fri Feb 18 15:26:49 2005 @@ -114,7 +114,7 @@ def descr_property_set(space, w_property, w_obj, w_value): fset = space.interpclass_w(w_property).fset if fset is None: - raise OperationError(space.w_AttributeError, + raise OperationError(space.w_TypeError, space.wrap("read-only attribute")) fset(space, w_obj, w_value) From arigo at codespeak.net Fri Feb 18 17:40:27 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 17:40:27 +0100 (MET) Subject: [pypy-svn] r9310 - pypy/branch/dist-interpapp/pypy/objspace/std Message-ID: <20050218164027.2ABF227B76@code1.codespeak.net> Author: arigo Date: Fri Feb 18 17:40:26 2005 New Revision: 9310 Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Log: Work around a bug in inspect.getsource() introduced by Python 2.4 :-( Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/typeobject.py Fri Feb 18 17:40:26 2005 @@ -243,7 +243,8 @@ # ____________________________________________________________ -def app_abstract_mro(klass): # abstract/classic mro +def app_abstract_mro(klass): + # abstract/classic mro mro = [] def fill_mro(klass): if klass not in mro: From hpk at codespeak.net Fri Feb 18 17:47:39 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 17:47:39 +0100 (MET) Subject: [pypy-svn] r9311 - pypy/branch/dist-interpapp/lib-python-2.3.4/test Message-ID: <20050218164739.A362427B76@code1.codespeak.net> Author: hpk Date: Fri Feb 18 17:47:39 2005 New Revision: 9311 Modified: pypy/branch/dist-interpapp/lib-python-2.3.4/test/conftest.py Log: some adaption to the new space.builtin interface. Modified: pypy/branch/dist-interpapp/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/branch/dist-interpapp/lib-python-2.3.4/test/conftest.py (original) +++ pypy/branch/dist-interpapp/lib-python-2.3.4/test/conftest.py Fri Feb 18 17:47:39 2005 @@ -59,9 +59,10 @@ mod = PyPyModule(space, w_dottedname) w_globals = mod.w_dict w_filename = space.wrap(str(filepath)) - space.builtin.execfile(w_filename, w_globals, w_globals) + w_execfile = space.builtin.get('execfile') + space.call_function(w_execfile, w_filename, w_globals, w_globals) w_mod = space.wrap(mod) - w_modules = space.getitem(space.sys.w_dict, space.wrap('modules')) + w_modules = space.sys.get('modules') space.setitem(w_modules, w_dottedname, w_mod) return w_mod From arigo at codespeak.net Fri Feb 18 18:45:30 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 18:45:30 +0100 (MET) Subject: [pypy-svn] r9313 - pypy/branch/dist-interpapp/pypy/module/sys2 Message-ID: <20050218174530.1C87027B76@code1.codespeak.net> Author: arigo Date: Fri Feb 18 18:45:29 2005 New Revision: 9313 Modified: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Log: sys.displayhook() needs to print the repr() of its argument. (How do we write a test for that?) Modified: pypy/branch/dist-interpapp/pypy/module/sys2/hook.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/sys2/hook.py (original) +++ pypy/branch/dist-interpapp/pypy/module/sys2/hook.py Fri Feb 18 18:45:29 2005 @@ -5,7 +5,7 @@ space.setitem(space.builtin.w_dict, space.wrap('_'), w_obj) # NB. this is slightly more complicated in CPython, # see e.g. the difference with >>> print 5,; 8 - print_item_to(space, w_obj, sys_stdout(space)) + print_item_to(space, space.repr(w_obj), sys_stdout(space)) print_newline_to(space, sys_stdout(space)) __displayhook__ = displayhook # this is exactly like in CPython From arigo at codespeak.net Fri Feb 18 18:50:38 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 18:50:38 +0100 (MET) Subject: [pypy-svn] r9314 - pypy/branch/dist-interpapp/pypy/module/test Message-ID: <20050218175038.0F62B27B76@code1.codespeak.net> Author: arigo Date: Fri Feb 18 18:50:37 2005 New Revision: 9314 Modified: pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py Log: Enhanced the test for sys.displayhook(). (thanks pedronis) Modified: pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py (original) +++ pypy/branch/dist-interpapp/pypy/module/test/test_sysmodule.py Fri Feb 18 18:50:37 2005 @@ -115,9 +115,9 @@ dh(None) assert out.getvalue() == "" assert not hasattr(__builtin__, "_") - dh(42) - assert out.getvalue() == "42\n" - assert __builtin__._ == 42 + dh("hello") + assert out.getvalue() == "'hello'\n" + assert __builtin__._ == "hello" del sys.stdout raises(RuntimeError, dh, 42) From pedronis at codespeak.net Fri Feb 18 18:52:52 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 18 Feb 2005 18:52:52 +0100 (MET) Subject: [pypy-svn] r9315 - in pypy/branch/dist-interpapp/pypy: interpreter interpreter/test objspace/std tool Message-ID: <20050218175252.A118027B76@code1.codespeak.net> Author: pedronis Date: Fri Feb 18 18:52:52 2005 New Revision: 9315 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/pycode.py pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py Log: now except for the simplest cases inter2app unwrap_spec is mandatory if an unbound method is used the its class is used for the unwrap_spec of the self argument when explicitly specifying the unwrap_spec for an unbound method the placeholder 'self' should be used Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 18 18:52:52 2005 @@ -15,7 +15,7 @@ from pypy.interpreter.error import OperationError from pypy.interpreter import eval from pypy.interpreter.function import Function, Method -from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable +from pypy.interpreter.baseobjspace import W_Root,ObjSpace, BaseWrappable, Wrappable from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache # internal non-translatable parts: @@ -55,7 +55,7 @@ class UnwrapSpecRecipe: - bases_order = [W_Root, ObjSpace, Arguments, object] + bases_order = [BaseWrappable, W_Root, ObjSpace, Arguments, object] def dispatch(self, meth_family, el, orig_sig, new_sig): if isinstance(el,str): @@ -78,14 +78,19 @@ # checks for checking interp2app func argument names wrt unwrap_spec # and synthetizing an app-level signature - def check__ObjSpace(self, el, orig_sig, new_sig): - orig_sig.next_arg() - - def check_self(self, el, orig_sig, app_sig): # xxx + def check__BaseWrappable(self, el, orig_sig, app_sig): + name = el.__name__ argname = orig_sig.next_arg() + assert not argname.startswith('w_'), ( + "unwrapped %s argument %s of built-in function %r should " + "not start with 'w_'" % (name, argname, orig_sig.func)) app_sig.append(argname) + + def check__ObjSpace(self, el, orig_sig, app_sig): + orig_sig.next_arg() def check__W_Root(self, el, orig_sig, app_sig): + assert el is W_Root, "oops" argname = orig_sig.next_arg() assert argname.startswith('w_'), ( "argument %s of built-in function %r should " @@ -138,15 +143,24 @@ # collect code to emit for interp2app builtin frames based on unwrap_spec - def emit__ObjSpace(self, el, orig_sig, emit_sig): - emit_sig.run_args.append('self.space') - - def emit_self(self, el, orig_sig, emit_sig): # xxx + def emit__BaseWrappable(self, el, orig_sig, emit_sig): + name = el.__name__ + cur = emit_sig.through_scope_w emit_sig.setfastscope.append( - "self.self_arg = self.space.interpclass_w(scope_w[%d])" % - (emit_sig.through_scope_w)) + "x = self.space.interpclass_w(scope_w[%d])" % cur) + emit_sig.setfastscope.append( + "if x is None or not isinstance(x, %s):" % name) + emit_sig.setfastscope.append( + " raise OperationError(self.space.w_TypeError,space.wrap('unexpected arg type'))") # xxx + emit_sig.miniglobals[name] = el + emit_sig.miniglobals['OperationError'] = OperationError + emit_sig.setfastscope.append( + "self.%s_arg%d = x" % (name,cur)) emit_sig.through_scope_w += 1 - emit_sig.run_args.append("self.self_arg") + emit_sig.run_args.append("self.%s_arg%d" % (name,cur)) + + def emit__ObjSpace(self, el, orig_sig, emit_sig): + emit_sig.run_args.append('self.space') def emit__W_Root(self, el, orig_sig, emit_sig): cur = emit_sig.through_scope_w @@ -267,27 +281,19 @@ # When a BuiltinCode is stored in a Function object, # you get the functionality of CPython's built-in function type. - def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None): + def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None, self_type = None): "NOT_RPYTHON" # 'implfunc' is the interpreter-level function. # Note that this uses a lot of (construction-time) introspection. eval.Code.__init__(self, func.__name__) self.docstring = func.__doc__ - # signature-based hacks if unwrap_spec is not specified: - # renaming arguments from w_xyz to xyz. - # Currently we enforce the following signature tricks: - # * the first arg must be either 'self' or 'space' - # * 'w_' prefixes for the rest - # * '_w' suffix for the optional '*' argument - # * alternatively a final '__args__' means an Arguments() - # Not exactly a clean approach XXX. - # -- + # unwrap_spec can be passed to interp2app or # attached as an attribute to the function. # It is a list of types or singleton objects: # baseobjspace.ObjSpace is used to specify the space argument - # 'self' is used to specify a self method argument # baseobjspace.W_Root is for wrapped arguments to keep wrapped + # baseobjspace.BaseWrappable subclasses imply interpclass_w and a typecheck # argument.Arguments is for a final rest arguments Arguments object # 'args_w' for unpacktuple applied to rest arguments # 'w_args' for rest arguments passed as wrapped tuple @@ -297,49 +303,25 @@ from pypy.interpreter import pycode argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) + assert not ismethod, ("ismethod is not expected anymore") + assert not spacearg, ("spacearg is not expected anymore") + if unwrap_spec is None: unwrap_spec = getattr(func,'unwrap_spec',None) - - if unwrap_spec is None: - unwrap_spec = [] + if unwrap_spec is None and argnames == ['space', '__args__']: #xxx for geninterp + unwrap_spec = [ObjSpace, Arguments] - argnames = list(argnames) - lookslikemethod = argnames[:1] == ['self'] - if ismethod is None: - ismethod = lookslikemethod - if spacearg is None: - spacearg = not lookslikemethod - self.ismethod = ismethod - self.spacearg = spacearg - assert kwargname is None, ( - "built-in function %r should not take a ** argument" % func) - - n = len(argnames) - - if self.ismethod: - unwrap_spec.append('self') - n -= 1 - if self.spacearg: - unwrap_spec.append(ObjSpace) - n -= 1 - - self.generalargs = argnames[-1:] == ['__args__'] - self.starargs = varargname is not None - - if self.generalargs: - unwrap_spec.extend([W_Root] * (n-1)) - unwrap_spec.append(Arguments) - else: - unwrap_spec.extend([W_Root] * n) + if unwrap_spec is None: + unwrap_spec = [ObjSpace]+ [W_Root] * (len(argnames)-1) - if self.starargs: - unwrap_spec.append('starargs') - else: - assert not ismethod, ("if unwrap_spec is specified, " - "ismethod is not expected") - assert not spacearg, ("if unwrap_spec is specified, " - "spacearg is not expected") + if self_type: + unwrap_spec = ['self'] + unwrap_spec[1:] + + if self_type: + assert unwrap_spec[0] == 'self',"self_type without 'self' spec element" + unwrap_spec = list(unwrap_spec) + unwrap_spec[0] = self_type orig_sig = Signature(func, argnames, varargname, kwargname) @@ -385,6 +367,10 @@ "NOT_RPYTHON" Wrappable.__init__(self) # f must be a function whose name does NOT starts with 'app_' + self_type = None + if hasattr(f, 'im_func'): + self_type = f.im_class + f = f.im_func if not isinstance(f, types.FunctionType): raise TypeError, "function expected, got %r instead" % f if app_name is None: @@ -394,7 +380,8 @@ app_name = f.func_name self._code = BuiltinCode(f, ismethod=ismethod, spacearg=spacearg, - unwrap_spec=unwrap_spec) + unwrap_spec=unwrap_spec, + self_type = self_type) self.__name__ = f.func_name self.name = app_name self._staticdefs = list(f.func_defaults or ()) @@ -450,7 +437,6 @@ fn = Function(space, code, None, defs, forcename = self.name) cache.content[self] = fn return fn - def exportall(d, temporary=False): """NOT_RPYTHON: Publish every function from a dict.""" Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pycode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Fri Feb 18 18:52:52 2005 @@ -159,8 +159,7 @@ self = space.interpclass_w(w_self) return space.newtuple([space.wrap(name) for name in self.co_names]) - def descr_code__eq__(space, w_self, w_other): - self = space.interpclass_w(w_self) + def descr_code__eq__(self, w_other): other = space.interpclass_w(w_other) if not isinstance(other, PyCode): return space.w_False Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_gateway.py Fri Feb 18 18:52:52 2005 @@ -7,15 +7,22 @@ def test_signature(self): def c(space, w_x, w_y, *hello_w): pass - code = gateway.BuiltinCode(c) + code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + 'starargs']) assert code.signature() == (['x', 'y'], 'hello', None) def d(self, w_boo): pass - code = gateway.BuiltinCode(d) + code = gateway.BuiltinCode(d, unwrap_spec= ['self', + gateway.W_Root], self_type=gateway.BaseWrappable) assert code.signature() == (['self', 'boo'], None, None) def e(space, w_x, w_y, __args__): pass - code = gateway.BuiltinCode(e) + code = gateway.BuiltinCode(e, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + gateway.Arguments]) assert code.signature() == (['x', 'y'], 'args', 'keywords') def test_call(self): @@ -26,7 +33,10 @@ assert u(hello_w[0]) == 0 assert u(hello_w[1]) == True return w((u(w_x) - u(w_y) + len(hello_w))) - code = gateway.BuiltinCode(c) + code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + 'starargs']) w = self.space.wrap w_dict = self.space.newdict([ (w('x'), w(123)), @@ -43,7 +53,10 @@ w = space.wrap return w((u(w_x) - u(w_y) + len(args_w)) * u(kwds_w['boo'])) - code = gateway.BuiltinCode(c) + code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + gateway.Arguments]) w = self.space.wrap w_dict = self.space.newdict([ (w('x'), w(123)), Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Fri Feb 18 18:52:52 2005 @@ -2,7 +2,7 @@ """ -from pypy.interpreter.gateway import interp2app +from pypy.interpreter.gateway import interp2app, ObjSpace, Arguments, W_Root from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.error import OperationError from pypy.tool.cache import Cache @@ -247,7 +247,7 @@ PyCode.typedef = TypeDef('code', __new__ = interp2app(PyCode.descr_code__new__.im_func), - __eq__ = interp2app(PyCode.descr_code__eq__.im_func), + __eq__ = interp2app(PyCode.descr_code__eq__), co_argcount = interp_attrproperty('co_argcount'), co_nlocals = interp_attrproperty('co_nlocals'), co_stacksize = interp_attrproperty('co_stacksize'), @@ -270,8 +270,9 @@ **Frame.typedef.rawdict) Module.typedef = TypeDef("module", - __new__ = interp2app(Module.descr_module__new__.im_func), - __init__ = interp2app(Module.descr_module__init__.im_func), + __new__ = interp2app(Module.descr_module__new__.im_func, + unwrap_spec=[ObjSpace, W_Root, Arguments]), + __init__ = interp2app(Module.descr_module__init__), __dict__ = GetSetProperty(descr_get_dict), # module dictionaries are readonly attributes ) @@ -297,8 +298,9 @@ getset_func_dict = GetSetProperty(descr_get_dict, descr_set_dict) Function.typedef = TypeDef("function", - __call__ = interp2app(Function.descr_function_call.im_func), - __get__ = interp2app(Function.descr_function_get.im_func), + __call__ = interp2app(Function.descr_function_call, + unwrap_spec=['self', Arguments]), + __get__ = interp2app(Function.descr_function_get), func_code = getset_func_code, func_doc = getset_func_doc, func_name = interp_attrproperty('name'), @@ -315,17 +317,18 @@ Method.typedef = TypeDef("method", __new__ = interp2app(Method.descr_method__new__.im_func), - __call__ = interp2app(Method.descr_method_call.im_func), - __get__ = interp2app(Method.descr_method_get.im_func), + __call__ = interp2app(Method.descr_method_call, + unwrap_spec=['self', Arguments]), + __get__ = interp2app(Method.descr_method_get), im_func = interp_attrproperty_w('w_function'), im_self = interp_attrproperty_w('w_instance'), im_class = interp_attrproperty_w('w_class'), - __getattribute__ = interp2app(Method.descr_method_getattribute.im_func), + __getattribute__ = interp2app(Method.descr_method_getattribute), # XXX getattribute/setattribute etc.pp ) StaticMethod.typedef = TypeDef("staticmethod", - __get__ = interp2app(StaticMethod.descr_staticmethod_get.im_func), + __get__ = interp2app(StaticMethod.descr_staticmethod_get), # XXX getattribute etc.pp ) @@ -337,8 +340,8 @@ ) GeneratorIterator.typedef = TypeDef("generator", - next = interp2app(GeneratorIterator.descr_next.im_func), - __iter__ = interp2app(GeneratorIterator.descr__iter__.im_func), + next = interp2app(GeneratorIterator.descr_next), + __iter__ = interp2app(GeneratorIterator.descr__iter__), gi_running = interp_attrproperty('running'), gi_frame = interp_attrproperty('frame'), ) @@ -346,11 +349,11 @@ Cell.typedef = TypeDef("cell") Ellipsis.typedef = TypeDef("Ellipsis", - __repr__ = interp2app(Ellipsis.descr__repr__.im_func), + __repr__ = interp2app(Ellipsis.descr__repr__), ) NotImplemented.typedef = TypeDef("NotImplemented", - __repr__ = interp2app(NotImplemented.descr__repr__.im_func), + __repr__ = interp2app(NotImplemented.descr__repr__), ) ControlFlowException.typedef = TypeDef("ControlFlowException") Modified: pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/dicttype.py Fri Feb 18 18:52:52 2005 @@ -96,6 +96,7 @@ # ____________________________________________________________ dict_typedef = StdTypeDef("dict", - __new__ = newmethod(descr__new__), + __new__ = newmethod(descr__new__, + unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]), ) dict_typedef.registermethods(globals()) Modified: pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/listtype.py Fri Feb 18 18:52:52 2005 @@ -37,6 +37,8 @@ # ____________________________________________________________ list_typedef = StdTypeDef("list", - __new__ = newmethod(descr__new__), + __new__ = newmethod(descr__new__, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.Arguments]), ) list_typedef.registermethods(globals()) Modified: pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/objecttype.py Fri Feb 18 18:52:52 2005 @@ -47,6 +47,8 @@ __str__ = gateway.interp2app(descr__str__), __repr__ = gateway.interp2app(descr__repr__), __class__ = GetSetProperty(descr__class__), - __new__ = newmethod(descr__new__), - __init__ = gateway.interp2app(descr__init__), + __new__ = newmethod(descr__new__, + unwrap_spec = [gateway.ObjSpace,gateway.W_Root,gateway.Arguments]), + __init__ = gateway.interp2app(descr__init__, + unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]), ) Modified: pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py Fri Feb 18 18:52:52 2005 @@ -55,10 +55,10 @@ std_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict) -def newmethod(descr_new): +def newmethod(descr_new, unwrap_spec=None): "NOT_RPYTHON: initialization-time only." # this is turned into a static method by the constructor of W_TypeObject. - return gateway.interp2app(descr_new) + return gateway.interp2app(descr_new, unwrap_spec=unwrap_spec) # ____________________________________________________________ # Modified: pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py Fri Feb 18 18:52:52 2005 @@ -78,5 +78,5 @@ __mro__ = GetSetProperty(descr_get__mro__), __dict__ = dictproxy_descr, __doc__ = GetSetProperty(descr__doc), - mro = newmethod(descr_mro), + mro = gateway.interp2app(descr_mro), ) Modified: pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/pytestsupport.py Fri Feb 18 18:52:52 2005 @@ -2,7 +2,7 @@ import autopath import py from py.__impl__.magic import exprinfo -from pypy.interpreter.gateway import interp2app_temp +from pypy.interpreter import gateway from pypy.interpreter.error import OperationError # ____________________________________________________________ @@ -107,7 +107,10 @@ w_BuiltinAssertionError = space.getitem(space.builtin.w_dict, space.wrap('AssertionError')) w_metaclass = space.type(w_BuiltinAssertionError) - w_init = space.wrap(interp2app_temp(my_init)) + w_init = space.wrap(gateway.interp2app_temp(my_init, + unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.Arguments])) w_dict = space.newdict([]) space.setitem(w_dict, space.wrap('__init__'), w_init) return space.call_function(w_metaclass, @@ -149,14 +152,18 @@ raise OperationError(space.w_AssertionError, space.wrap("DID NOT RAISE")) -app_raises = interp2app_temp(pypyraises) +app_raises = gateway.interp2app_temp(pypyraises, + unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + gateway.Arguments]) def pypyskip(space, w_message): """skip a test at app-level. """ msg = space.unwrap(w_message) py.test.skip(msg) -app_skip = interp2app_temp(pypyskip) +app_skip = gateway.interp2app_temp(pypyskip) def raises_w(space, w_ExpectedException, *args, **kwds): try: From arigo at codespeak.net Fri Feb 18 19:48:15 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 19:48:15 +0100 (MET) Subject: [pypy-svn] r9317 - pypy/dist/pypy/interpreter Message-ID: <20050218184815.DF11F27B90@code1.codespeak.net> Author: arigo Date: Fri Feb 18 19:48:15 2005 New Revision: 9317 Modified: pypy/dist/pypy/interpreter/error.py Log: dead code. Modified: pypy/dist/pypy/interpreter/error.py ============================================================================== --- pypy/dist/pypy/interpreter/error.py (original) +++ pypy/dist/pypy/interpreter/error.py Fri Feb 18 19:48:15 2005 @@ -124,16 +124,6 @@ # Utilities -def inlinecompile(source, space, symbol='exec'): - """Compile the given 'source' string. - This function differs from the built-in compile() because it abuses - co_filename to store a copy of the complete source code. - This lets OperationError.print_application_traceback() print the - actual source line in the traceback.""" - compile = space.builtin.compile - return compile(source, '\n%s'%source, symbol, 0, 0) - - def debug_print(text, file=None): if file is None: file = sys.stderr text = text.rstrip() From arigo at codespeak.net Fri Feb 18 19:49:23 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 19:49:23 +0100 (MET) Subject: [pypy-svn] r9318 - pypy/dist/pypy/objspace/std Message-ID: <20050218184923.39C5327B90@code1.codespeak.net> Author: arigo Date: Fri Feb 18 19:49:23 2005 New Revision: 9318 Modified: pypy/dist/pypy/objspace/std/longobject.py Log: Now that we have pow__Int_Int_Long(), we don't need pow_ovr__Int_Int_Int() any more. Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Fri Feb 18 19:49:23 2005 @@ -183,21 +183,6 @@ space.wrap(e.args[0])) return W_LongObject(space, t) -def pow__Int_Int_Long(space, w_int1, w_int2, w_long3): - x = w_int1.intval - y = w_int2.intval - z = w_long3.longval - - try: - t = long(pow(x, y, z)) - except TypeError, e: - raise OperationError(space.w_TypeError, - space.wrap(e.args[0])) - except ValueError, e: - raise OperationError(space.w_ValueError, - space.wrap(e.args[0])) - return W_LongObject(space, t) - def neg__Long(space, w_long1): return W_LongObject(space, -w_long1.longval) @@ -293,11 +278,10 @@ w_long2 = delegate_Int2Long(w_int2) return pow__Long_Long_None(space, w_long1, w_long2, w_none3) -def pow_ovr__Int_Int_Int(space, w_int1, w_int2, w_int3): +def pow_ovr__Int_Int_Long(space, w_int1, w_int2, w_long3): w_long1 = delegate_Int2Long(w_int1) w_long2 = delegate_Int2Long(w_int2) - w_long3 = delegate_Int2Long(w_int3) return pow__Long_Long_Long(space, w_long1, w_long2, w_long3) StdObjSpace.MM.pow.register(pow_ovr__Int_Int_None, W_IntObject, W_IntObject, W_NoneObject, order=1) -StdObjSpace.MM.pow.register(pow_ovr__Int_Int_Int , W_IntObject, W_IntObject, W_IntObject, order=1) +StdObjSpace.MM.pow.register(pow_ovr__Int_Int_Long, W_IntObject, W_IntObject, W_LongObject, order=1) From arigo at codespeak.net Fri Feb 18 20:15:32 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Fri, 18 Feb 2005 20:15:32 +0100 (MET) Subject: [pypy-svn] r9319 - pypy/dist/pypy/objspace/std/test Message-ID: <20050218191532.DF75F27B90@code1.codespeak.net> Author: arigo Date: Fri Feb 18 20:15:32 2005 New Revision: 9319 Added: pypy/dist/pypy/objspace/std/test/test_operation.py Log: A new test file to check mixed-type integer operations in the stdobjspace. Added: pypy/dist/pypy/objspace/std/test/test_operation.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/objspace/std/test/test_operation.py Fri Feb 18 20:15:32 2005 @@ -0,0 +1,134 @@ + + +def app_test_int_vs_long(): + def teq(a, b): + assert a == b + assert type(a) is type(b) + + # binary operators + teq( 5 - 2 , 3 ) + teq( 5 - 2L , 3L ) + teq( 5L - 2 , 3L ) + teq( 5L - 2L , 3L ) + + teq( 5 .__sub__(2 ), 3 ) + teq( 5 .__sub__(2L), NotImplemented ) + teq( 5L .__sub__(2 ), 3L ) + teq( 5L .__sub__(2L), 3L ) + + teq( 5 .__rsub__(2 ), -3 ) + teq( 5 .__rsub__(2L), NotImplemented ) + teq( 5L .__rsub__(2 ), -3L ) + teq( 5L .__rsub__(2L), -3L ) + + teq( 5 ** 2 , 25 ) + teq( 5 ** 2L , 25L ) + teq( 5L ** 2 , 25L ) + teq( 5L ** 2L , 25L ) + + # ternary operator + teq( pow( 5 , 3 , 100 ), 25 ) + teq( pow( 5 , 3 , 100L), 25L) + teq( pow( 5 , 3L, 100 ), 25L) + teq( pow( 5 , 3L, 100L), 25L) + teq( pow( 5L, 3 , 100 ), 25L) + teq( pow( 5L, 3 , 100L), 25L) + teq( pow( 5L, 3L, 100 ), 25L) + teq( pow( 5L, 3L, 100L), 25L) + + # two tests give a different result on PyPy and CPython. + # however, there is no sane way that PyPy can match CPython here, + # short of reintroducing three-way coercion... + teq( 5 .__pow__(3 , 100 ), 25 ) + #teq( 5 .__pow__(3 , 100L), 25L or NotImplemented? ) + teq( 5 .__pow__(3L, 100 ), NotImplemented ) + teq( 5 .__pow__(3L, 100L), NotImplemented ) + teq( 5L .__pow__(3 , 100 ), 25L) + teq( 5L .__pow__(3 , 100L), 25L) + teq( 5L .__pow__(3L, 100 ), 25L) + teq( 5L .__pow__(3L, 100L), 25L) + + teq( 5 .__rpow__(3 , 100 ), 43 ) + #teq( 5 .__rpow__(3 , 100L), 43L or NotImplemented? ) + teq( 5 .__rpow__(3L, 100 ), NotImplemented ) + teq( 5 .__rpow__(3L, 100L), NotImplemented ) + teq( 5L .__rpow__(3 , 100 ), 43L) + teq( 5L .__rpow__(3 , 100L), 43L) + teq( 5L .__rpow__(3L, 100 ), 43L) + teq( 5L .__rpow__(3L, 100L), 43L) + + +def app_test_int_vs_float(): + def teq(a, b): + assert a == b + assert type(a) is type(b) + + # binary operators + teq( 5 - 2 , 3 ) + teq( 5 - 2.0 , 3.0 ) + teq( 5.0 - 2 , 3.0 ) + teq( 5.0 - 2.0 , 3.0 ) + + teq( 5 .__sub__(2 ), 3 ) + teq( 5 .__sub__(2.0), NotImplemented ) + teq( 5.0 .__sub__(2 ), 3.0 ) + teq( 5.0 .__sub__(2.0), 3.0 ) + + teq( 5 .__rsub__(2 ), -3 ) + teq( 5 .__rsub__(2.0), NotImplemented ) + teq( 5.0 .__rsub__(2 ), -3.0 ) + teq( 5.0 .__rsub__(2.0), -3.0 ) + + teq( 5 ** 2 , 25 ) + teq( 5 ** 2.0 , 25.0 ) + teq( 5.0 ** 2 , 25.0 ) + teq( 5.0 ** 2.0 , 25.0 ) + + # pow() fails with a float argument anywhere + raises(TypeError, pow, 5 , 3 , 100.0) + raises(TypeError, pow, 5 , 3.0, 100 ) + raises(TypeError, pow, 5 , 3.0, 100.0) + raises(TypeError, pow, 5.0, 3 , 100 ) + raises(TypeError, pow, 5.0, 3 , 100.0) + raises(TypeError, pow, 5.0, 3.0, 100 ) + raises(TypeError, pow, 5.0, 3.0, 100.0) + + teq( 5 .__pow__(3.0, 100 ), NotImplemented ) + teq( 5 .__pow__(3.0, 100.0), NotImplemented ) + + teq( 5 .__rpow__(3.0, 100 ), NotImplemented ) + teq( 5 .__rpow__(3.0, 100.0), NotImplemented ) + + +def app_test_long_vs_float(): + def teq(a, b): + assert a == b + assert type(a) is type(b) + + # binary operators + teq( 5L - 2.0 , 3.0 ) + teq( 5.0 - 2L , 3.0 ) + + teq( 5L .__sub__(2.0), NotImplemented ) + teq( 5.0 .__sub__(2L ), 3.0 ) + + teq( 5L .__rsub__(2.0), NotImplemented ) + teq( 5.0 .__rsub__(2L ), -3.0 ) + + teq( 5L ** 2.0 , 25.0 ) + teq( 5.0 ** 2L , 25.0 ) + + # pow() fails with a float argument anywhere + raises(TypeError, pow, 5L , 3L , 100.0) + raises(TypeError, pow, 5L , 3.0, 100 ) + raises(TypeError, pow, 5L , 3.0, 100.0) + raises(TypeError, pow, 5.0, 3L , 100 ) + raises(TypeError, pow, 5.0, 3L , 100.0) + raises(TypeError, pow, 5.0, 3.0, 100 ) + raises(TypeError, pow, 5.0, 3.0, 100.0) + + teq( 5L .__pow__(3.0, 100L ), NotImplemented ) + teq( 5L .__pow__(3.0, 100.0), NotImplemented ) + + teq( 5L .__rpow__(3.0, 100L ), NotImplemented ) + teq( 5L .__rpow__(3.0, 100.0), NotImplemented ) From pedronis at codespeak.net Fri Feb 18 20:30:58 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 18 Feb 2005 20:30:58 +0100 (MET) Subject: [pypy-svn] r9320 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050218193058.9CA1427B90@code1.codespeak.net> Author: pedronis Date: Fri Feb 18 20:30:58 2005 New Revision: 9320 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Log: first pass at adding typecheck support to GetSetProperties Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 18 20:30:58 2005 @@ -310,6 +310,7 @@ unwrap_spec = getattr(func,'unwrap_spec',None) if unwrap_spec is None and argnames == ['space', '__args__']: #xxx for geninterp + #print sys._getframe(2).f_globals['__name__'] unwrap_spec = [ObjSpace, Arguments] if unwrap_spec is None: Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Fri Feb 18 20:30:58 2005 @@ -92,44 +92,73 @@ else: return new.instance(cls) +def make_descr_typecheck_wrapper(func, extraargs=()): + if not hasattr(func, 'im_func'): + return func + cls = func.im_class + func = func.im_func + #print cls.__name__, func.__name__ + miniglobals = { + cls.__name__: cls, + func.__name__: func, + 'OperationError': OperationError + } + exec ("""def descr_typecheck_%(name)s(space, w_obj, %(extra)s): + obj = space.interpclass_w(w_obj) + if obj is None or not isinstance(obj, %(cls)s): + raise OperationError(space.w_TypeError, + space.wrap("descriptor is for '%%s'" %% %(cls)s.typedef.name)) # xxx improve + return %(name)s(space, obj, %(extra)s) +""" % {'name': func.__name__, 'cls': cls.__name__, + 'extra': ', '.join(extraargs)}) in miniglobals + return miniglobals['descr_typecheck_%s' % func.__name__] + + class GetSetProperty(Wrappable): def __init__(self, fget, fset=None, fdel=None, doc=None): "NOT_RPYTHON: initialization-time only" - fget = getattr(fget, 'im_func', fget) - fset = getattr(fset, 'im_func', fset) - fdel = getattr(fdel, 'im_func', fdel) + fget = make_descr_typecheck_wrapper(fget) + fset = make_descr_typecheck_wrapper(fset, ('w_value',)) + fdel = make_descr_typecheck_wrapper(fdel) self.fget = fget self.fset = fset self.fdel = fdel self.doc = doc - def descr_property_get(space, w_property, w_obj, w_cls=None): + def descr_property_get(space, property, w_obj, w_cls=None): # XXX HAAAAAAAAAAAACK (but possibly a good one) if w_obj == space.w_None and not space.is_true(space.is_(w_cls, space.type(space.w_None))): - #print w_property, w_obj, w_cls - return w_property + #print property, w_obj, w_cls + return space.wrap(property) else: - return space.interpclass_w(w_property).fget(space, w_obj) + return property.fget(space, w_obj) - def descr_property_set(space, w_property, w_obj, w_value): - fset = space.interpclass_w(w_property).fset + def descr_property_set(space, property, w_obj, w_value): + fset = property.fset if fset is None: raise OperationError(space.w_TypeError, space.wrap("read-only attribute")) fset(space, w_obj, w_value) - def descr_property_del(space, w_property, w_obj): - fdel = space.interpclass_w(w_property).fdel + def descr_property_del(space, property, w_obj): + fdel = property.fdel if fdel is None: raise OperationError(space.w_AttributeError, space.wrap("cannot delete attribute")) fdel(space, w_obj) - typedef = TypeDef("GetSetProperty", - __get__ = interp2app(descr_property_get), - __set__ = interp2app(descr_property_set), - __delete__ = interp2app(descr_property_del), - ) +GetSetProperty.typedef = TypeDef( + "GetSetProperty", + __get__ = interp2app(GetSetProperty.descr_property_get.im_func, + unwrap_spec = [ObjSpace, + GetSetProperty, W_Root, W_Root]), + __set__ = interp2app(GetSetProperty.descr_property_set.im_func, + unwrap_spec = [ObjSpace, + GetSetProperty, W_Root, W_Root]), + __delete__ = interp2app(GetSetProperty.descr_property_del.im_func, + unwrap_spec = [ObjSpace, + GetSetProperty, W_Root]), + ) def interp_attrproperty(name): "NOT_RPYTHON: initialization-time only" @@ -241,7 +270,7 @@ Frame.typedef = TypeDef('internal-frame', f_code = interp_attrproperty('code'), - f_locals = GetSetProperty(Frame.fget_getdictscope.im_func), + f_locals = GetSetProperty(Frame.fget_getdictscope), f_globals = interp_attrproperty_w('w_globals'), ) @@ -265,8 +294,8 @@ ) PyFrame.typedef = TypeDef('frame', - f_builtins = GetSetProperty(PyFrame.fget_f_builtins.im_func), - f_lineno = GetSetProperty(PyFrame.fget_f_lineno.im_func), + f_builtins = GetSetProperty(PyFrame.fget_f_builtins), + f_lineno = GetSetProperty(PyFrame.fget_f_lineno), **Frame.typedef.rawdict) Module.typedef = TypeDef("module", From pedronis at codespeak.net Fri Feb 18 22:57:59 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 18 Feb 2005 22:57:59 +0100 (MET) Subject: [pypy-svn] r9322 - in pypy/branch/dist-interpapp/pypy/interpreter: . test Message-ID: <20050218215759.E82C527B90@code1.codespeak.net> Author: pedronis Date: Fri Feb 18 22:57:59 2005 New Revision: 9322 Added: pypy/branch/dist-interpapp/pypy/interpreter/test/test_descrtypecheck.py (contents, props changed) Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Log: small fix and tests Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Fri Feb 18 22:57:59 2005 @@ -147,15 +147,15 @@ name = el.__name__ cur = emit_sig.through_scope_w emit_sig.setfastscope.append( - "x = self.space.interpclass_w(scope_w[%d])" % cur) + "obj = self.space.interpclass_w(scope_w[%d])" % cur) emit_sig.setfastscope.append( - "if x is None or not isinstance(x, %s):" % name) + "if obj is None or not isinstance(obj, %s):" % name) emit_sig.setfastscope.append( - " raise OperationError(self.space.w_TypeError,space.wrap('unexpected arg type'))") # xxx + " raise OperationError(self.space.w_TypeError,self.space.wrap('expected %%s' %% %s.typedef.name ))" % name) # xxx emit_sig.miniglobals[name] = el emit_sig.miniglobals['OperationError'] = OperationError emit_sig.setfastscope.append( - "self.%s_arg%d = x" % (name,cur)) + "self.%s_arg%d = obj" % (name,cur)) emit_sig.through_scope_w += 1 emit_sig.run_args.append("self.%s_arg%d" % (name,cur)) Added: pypy/branch/dist-interpapp/pypy/interpreter/test/test_descrtypecheck.py ============================================================================== --- (empty file) +++ pypy/branch/dist-interpapp/pypy/interpreter/test/test_descrtypecheck.py Fri Feb 18 22:57:59 2005 @@ -0,0 +1,13 @@ + + +class AppTestDescrTypecheck: + + def test_getsetprop_get(self): + def f(): + pass + raises(TypeError, type(f).__dict__['func_code'].__get__.im_func,1,None) + + def test_func_code_get(self): + def f(): + pass + raises(TypeError, type(f).func_code.__get__,1) From hpk at codespeak.net Fri Feb 18 23:11:27 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Fri, 18 Feb 2005 23:11:27 +0100 (MET) Subject: [pypy-svn] r9323 - pypy/branch/dist-interpapp/pypy/tool/test Message-ID: <20050218221127.9DE1F27B90@code1.codespeak.net> Author: hpk Date: Fri Feb 18 23:11:27 2005 New Revision: 9323 Modified: pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert.py pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert2.py Log: according to my newest theory this should not cause a conflict upon merging: i copied the slightly modified test_utest*.py files verbatim from dist to the branch. Modified: pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert.py Fri Feb 18 23:11:27 2005 @@ -2,7 +2,7 @@ from pypy.tool.utestconvert import rewrite_utest import unittest -class Testit(unittest.TestCase): +class NonpyTest(unittest.TestCase): def test(self): assert rewrite_utest("badger badger badger") == ( "badger badger badger") @@ -158,7 +158,7 @@ "assert not 0 == 0") assert rewrite_utest("self.failUnlessEqual(0, 0)") == ( - "assert not 0 != 0") + "assert 0 == 0") assert rewrite_utest( """ @@ -171,9 +171,9 @@ """ ) == ( """ - assert not (mushroom() + assert (mushroom() + mushroom() - + mushroom()) != '''badger badger badger + + mushroom()) == '''badger badger badger badger badger badger badger badger badger badger badger ''' # multiline, must move the parens @@ -363,7 +363,7 @@ """ ) == ( """ - assert not round(first - second, 5) != 0, 'A Snake!' + assert round(first - second, 5) == 0, 'A Snake!' """ ) Modified: pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert2.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert2.py (original) +++ pypy/branch/dist-interpapp/pypy/tool/test/test_utestconvert2.py Fri Feb 18 23:11:27 2005 @@ -2,7 +2,7 @@ from pypy.tool.utestconvert import rewrite_utest import unittest -class Testit(unittest.TestCase): +class NonPyTest(unittest.TestCase): def test(self): self.assertEquals(rewrite_utest("badger badger badger"), "badger badger badger") @@ -158,7 +158,7 @@ "assert not 0 == 0") self.assertEquals(rewrite_utest("self.failUnlessEqual(0, 0)"), - "assert not 0 != 0") + "assert 0 == 0") self.assertEquals(rewrite_utest( """ @@ -171,9 +171,9 @@ """ ), """ - assert not (mushroom() + assert (mushroom() + mushroom() - + mushroom()) != '''badger badger badger + + mushroom()) == '''badger badger badger badger badger badger badger badger badger badger badger ''' # multiline, must move the parens @@ -363,7 +363,7 @@ """ ), """ - assert not round(first - second, 5) != 0, 'A Snake!' + assert round(first - second, 5) == 0, 'A Snake!' """ ) From pedronis at codespeak.net Sat Feb 19 01:37:35 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 19 Feb 2005 01:37:35 +0100 (MET) Subject: [pypy-svn] r9324 - in pypy/branch/dist-interpapp/pypy: interpreter objspace/std objspace/std/test Message-ID: <20050219003735.83D7927B97@code1.codespeak.net> Author: pedronis Date: Sat Feb 19 01:37:35 2005 New Revision: 9324 Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py pypy/branch/dist-interpapp/pypy/objspace/std/dictproxyobject.py pypy/branch/dist-interpapp/pypy/objspace/std/dictproxytype.py pypy/branch/dist-interpapp/pypy/objspace/std/model.py pypy/branch/dist-interpapp/pypy/objspace/std/slicetype.py pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py pypy/branch/dist-interpapp/pypy/objspace/std/test/test_typeobject.py pypy/branch/dist-interpapp/pypy/objspace/std/typetype.py Log: typechecks through GetSetProperty notice that in std objspace the feature is not that useful because when we construct the typedefs we don't have the W_*Object classes, in fact they depend on the typedef being there first for their def, for now I used a direct approach do we want to reverse space, self where possible, given the situation we would have to support space, ... / self, ... / self, space, ... not totally related to the branch there are surely some more typechecks missing that could use unwrap_specs more, what to do about typechecking .slots_w access in members (there's no clear superclass we can check for), same for setdict in generic __dict__ descr impl Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Sat Feb 19 01:37:35 2005 @@ -3,7 +3,7 @@ """ from pypy.interpreter.gateway import interp2app, ObjSpace, Arguments, W_Root -from pypy.interpreter.baseobjspace import Wrappable +from pypy.interpreter.baseobjspace import BaseWrappable, Wrappable from pypy.interpreter.error import OperationError from pypy.tool.cache import Cache import new @@ -92,34 +92,58 @@ else: return new.instance(cls) -def make_descr_typecheck_wrapper(func, extraargs=()): - if not hasattr(func, 'im_func'): +def make_descr_typecheck_wrapper(func, extraargs=(), cls=None): + if func is None: + return None + if hasattr(func, 'im_func'): + assert not cls or cls is func.im_class + cls = func.im_class + func = func.im_func + if not cls: + #print "UNCHECKED", func.__module__ or '?', func.__name__ return func - cls = func.im_class - func = func.im_func - #print cls.__name__, func.__name__ + miniglobals = { - cls.__name__: cls, - func.__name__: func, + func.__name__: func, 'OperationError': OperationError } + if isinstance(cls, str): + #print " Author: hpk Date: Sat Feb 19 11:52:05 2005 New Revision: 9325 Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Log: improved formatting for generating the typecheck code Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Sat Feb 19 11:52:05 2005 @@ -123,18 +123,21 @@ miniglobals[cls_name] = cls check = "isinstance(obj, %s)" % cls_name expected = "%s.typedef.name" % cls_name - - exec ("""def descr_typecheck_%(name)s(space, w_obj, %(extra)s): - obj = %(unwrap)s - if obj is None or not %(check)s: - raise OperationError(space.w_TypeError, - space.wrap("descriptor is for '%%s'" %% %(expected)s)) # xxx improve - return %(name)s(space, obj, %(extra)s) -""" % {'name': func.__name__, - 'check': check, - 'expected': expected, - 'unwrap': unwrap, - 'extra': ', '.join(extraargs)}) in miniglobals + + source = """if 1: + def descr_typecheck_%(name)s(space, w_obj, %(extra)s): + obj = %(unwrap)s + if obj is None or not %(check)s: + # xxx improve msg + msg = "descriptor is for '%%s'" %% %(expected)s + raise OperationError(space.w_TypeError, space.wrap(msg)) + return %(name)s(space, obj, %(extra)s) + \n""" % {'name': func.__name__, + 'check': check, + 'expected': expected, + 'unwrap': unwrap, + 'extra': ', '.join(extraargs)} + exec source in miniglobals return miniglobals['descr_typecheck_%s' % func.__name__] From hpk at codespeak.net Sat Feb 19 12:05:30 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 12:05:30 +0100 (MET) Subject: [pypy-svn] r9326 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050219110530.BA79727B84@code1.codespeak.net> Author: hpk Date: Sat Feb 19 12:05:30 2005 New Revision: 9326 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Log: small fix (uncovered by running the lib-python-2.3.4 tests) Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pycode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Sat Feb 19 12:05:30 2005 @@ -160,6 +160,7 @@ return space.newtuple([space.wrap(name) for name in self.co_names]) def descr_code__eq__(self, w_other): + space = self.space other = space.interpclass_w(w_other) if not isinstance(other, PyCode): return space.w_False From hpk at codespeak.net Sat Feb 19 12:18:53 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 12:18:53 +0100 (MET) Subject: [pypy-svn] r9327 - pypy/branch/dist-interpapp/pypy/interpreter Message-ID: <20050219111853.8B82327B84@code1.codespeak.net> Author: hpk Date: Sat Feb 19 12:18:53 2005 New Revision: 9327 Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Log: added typechecks/unwrap_spec's for Pycode's __new__ descriptor Modified: pypy/branch/dist-interpapp/pypy/interpreter/pycode.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/pycode.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/pycode.py Sat Feb 19 12:18:53 2005 @@ -6,7 +6,8 @@ import dis from pypy.interpreter import eval -from pypy.interpreter.gateway import NoneNotWrapped +from pypy.interpreter.gateway import NoneNotWrapped +from pypy.interpreter.baseobjspace import ObjSpace, W_Root from pypy.tool.cache import Cache # helper @@ -183,33 +184,39 @@ return space.w_False return space.w_True - + + unwrap_spec = [ObjSpace, W_Root, + int, int, int, int, + str, W_Root, W_Root, + W_Root, str, str, int, + str, W_Root, + W_Root] def descr_code__new__(space, w_subtype, - w_argcount, w_nlocals, w_stacksize, w_flags, - w_codestring, w_constants, w_names, - w_varnames, w_filename, w_name, w_firstlineno, - w_lnotab, w_freevars=NoneNotWrapped, + argcount, nlocals, stacksize, flags, + codestring, w_constants, w_names, + w_varnames, filename, name, firstlineno, + lnotab, w_freevars=NoneNotWrapped, w_cellvars=NoneNotWrapped): code = space.allocate_instance(PyCode, w_subtype) code.__init__(space) - # XXX typechecking everywhere! - code.co_argcount = space.int_w(w_argcount) - code.co_nlocals = space.int_w(w_nlocals) - code.co_stacksize = space.int_w(w_stacksize) - code.co_flags = space.int_w(w_flags) - code.co_code = space.str_w(w_codestring) + code.co_argcount = argcount + code.co_nlocals = nlocals + code.co_stacksize = stacksize + code.co_flags = flags + code.co_code = codestring code.co_consts_w = space.unpacktuple(w_constants) code.co_names = unpack_str_tuple(space, w_names) code.co_varnames = unpack_str_tuple(space, w_varnames) - code.co_filename = space.str_w(w_filename) - code.co_name = space.str_w(w_name) - code.co_firstlineno= space.int_w(w_firstlineno) - code.co_lnotab = space.str_w(w_lnotab) + code.co_filename = filename + code.co_name = name + code.co_firstlineno= firstlineno + code.co_lnotab = lnotab if w_freevars is not None: code.co_freevars = unpack_str_tuple(space, w_freevars) if w_cellvars is not None: code.co_cellvars = unpack_str_tuple(space, w_cellvars) return space.wrap(code) + descr_code__new__.unwrap_spec = unwrap_spec def _really_enhanceclass(key, stuff): From hpk at codespeak.net Sat Feb 19 13:59:57 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 13:59:57 +0100 (MET) Subject: [pypy-svn] r9330 - in pypy/branch/dist-interpapp/pypy: interpreter objspace objspace/std Message-ID: <20050219125957.9825327B84@code1.codespeak.net> Author: hpk Date: Sat Feb 19 13:59:57 2005 New Revision: 9330 Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py pypy/branch/dist-interpapp/pypy/interpreter/py.py pypy/branch/dist-interpapp/pypy/interpreter/typedef.py pypy/branch/dist-interpapp/pypy/objspace/descroperation.py pypy/branch/dist-interpapp/pypy/objspace/std/longobject.py pypy/branch/dist-interpapp/pypy/objspace/std/multimethod.py pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py Log: quickly went through some important places where we generate code dynamically. Changed all exec "..." to "exec compile(...)". This way we can easily override the builtin compile to preserve source code information. Actually, if you uncomment the "py.magic.invoke(compile=1)" line in pypy/interpreter/py.py then you will get nice tracebacks with py.test and can look at a function's source code with e.g. print py.code.Source(space.str) Modified: pypy/branch/dist-interpapp/pypy/interpreter/gateway.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/gateway.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/gateway.py Sat Feb 19 13:59:57 2005 @@ -250,18 +250,18 @@ # Python 2.2 SyntaxError without newline: Bug #501622 setfastscope += '\n' d = {} - exec setfastscope in self.miniglobals, d + exec compile(setfastscope, '', 'exec') in self.miniglobals, d self.miniglobals['func'] = func - exec """ -def run(self): - w_result = func(%s) - if w_result is None: - w_result = self.space.w_None - return w_result -""" % ','.join(self.run_args) in self.miniglobals, d - + source = """if 1: + def run(self): + w_result = func(%s) + if w_result is None: + w_result = self.space.w_None + return w_result + \n""" % ','.join(self.run_args) + exec compile(source, '', 'exec') in self.miniglobals, d return type("BuiltinFrame_for_%s" % self.name, (BuiltinFrame,),d) Modified: pypy/branch/dist-interpapp/pypy/interpreter/py.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/py.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/py.py Sat Feb 19 13:59:57 2005 @@ -5,6 +5,9 @@ except ImportError: pass +from pypy.tool.getpy import py +#py.magic.invoke(compile=1) + from pypy.tool import option from pypy.tool.optik import make_option from pypy.interpreter import main, interactive, error Modified: pypy/branch/dist-interpapp/pypy/interpreter/typedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/interpreter/typedef.py (original) +++ pypy/branch/dist-interpapp/pypy/interpreter/typedef.py Sat Feb 19 13:59:57 2005 @@ -137,7 +137,7 @@ 'expected': expected, 'unwrap': unwrap, 'extra': ', '.join(extraargs)} - exec source in miniglobals + exec compile(source, '', 'exec') in miniglobals return miniglobals['descr_typecheck_%s' % func.__name__] Modified: pypy/branch/dist-interpapp/pypy/objspace/descroperation.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/descroperation.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/descroperation.py Sat Feb 19 13:59:57 2005 @@ -494,24 +494,25 @@ l = ["space.is_true(space.isinstance(w_result, %s))" % x for x in checkerspec] checker = " or ".join(l) - exec """ -def %(targetname)s(space, w_obj): - w_impl = space.lookup(w_obj, %(specialname)r) - if w_impl is None: - raise OperationError(space.w_TypeError, - space.wrap("operand does not support unary %(targetname)s")) - w_result = space.get_and_call_function(w_impl, w_obj) + source = """if 1: + def %(targetname)s(space, w_obj): + w_impl = space.lookup(w_obj, %(specialname)r) + if w_impl is None: + raise OperationError(space.w_TypeError, + space.wrap("operand does not support unary %(targetname)s")) + w_result = space.get_and_call_function(w_impl, w_obj) - if %(checker)s: - return w_result - typename = space.str_w(space.getattr(space.type(w_result), - space.wrap('__name__'))) - msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) - raise OperationError(space.w_TypeError, space.wrap(msg)) -assert not hasattr(DescrOperation, %(targetname)r) -DescrOperation.%(targetname)s = %(targetname)s -del %(targetname)s -""" % locals() + if %(checker)s: + return w_result + typename = space.str_w(space.getattr(space.type(w_result), + space.wrap('__name__'))) + msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) + raise OperationError(space.w_TypeError, space.wrap(msg)) + assert not hasattr(DescrOperation, %(targetname)r) + DescrOperation.%(targetname)s = %(targetname)s + del %(targetname)s + \n""" % locals() + exec compile(source, '', 'exec') # add default operation implementations for all still missing ops Modified: pypy/branch/dist-interpapp/pypy/objspace/std/longobject.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/longobject.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/longobject.py Sat Feb 19 13:59:57 2005 @@ -253,12 +253,12 @@ # binary ops for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod', 'lshift']: - exec """ + exec compile(""" def %(opname)s_ovr__Int_Int(space, w_int1, w_int2): w_long1 = delegate_Int2Long(w_int1) w_long2 = delegate_Int2Long(w_int2) return %(opname)s__Long_Long(space, w_long1, w_long2) -""" % {'opname': opname} +""" % {'opname': opname}, '', 'exec') getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int_Int' %opname], W_IntObject, W_IntObject, order=1) Modified: pypy/branch/dist-interpapp/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/multimethod.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/multimethod.py Sat Feb 19 13:59:57 2005 @@ -255,7 +255,7 @@ source = '\n'.join(bodylines) #print source #print "*"*60 - exec source in miniglobals + exec compile(source, '', 'exec') in miniglobals func = miniglobals[funcname] self.to_install.append((target, funcname, func, source, fallback)) return func Modified: pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py (original) +++ pypy/branch/dist-interpapp/pypy/objspace/std/stdtypedef.py Sat Feb 19 13:59:57 2005 @@ -237,7 +237,7 @@ return w_res """ % (prefix, wrapper_sig, renaming, expr, multimethod.operatorsymbol, ', '.join(solid_arglist)) - exec code in miniglobals + exec compile(code, '', 'exec') in miniglobals return miniglobals["%s_perform_call" % prefix] def wrap_trampoline_in_gateway(func, methname, multimethod): From hpk at codespeak.net Sat Feb 19 15:30:46 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 15:30:46 +0100 (MET) Subject: [pypy-svn] r9332 - in pypy/dist: lib-python-2.3.4/test pypy pypy/interpreter pypy/interpreter/test pypy/interpreter/test/mixedmodule pypy/module pypy/module/builtin pypy/module/sys2 pypy/module/test pypy/objspace pypy/objspace/flow pypy/objspace/std pypy/objspace/std/test pypy/objspace/test pypy/tool pypy/tool/test pypy/translator pypy/translator/test pypy/translator/tool Message-ID: <20050219143046.2C11C27B84@code1.codespeak.net> Author: hpk Date: Sat Feb 19 15:30:45 2005 New Revision: 9332 Added: pypy/dist/pypy/interpreter/lazymodule.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py pypy/dist/pypy/interpreter/test/mixedmodule/ (props changed) - copied from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/ pypy/dist/pypy/interpreter/test/mixedmodule/__init__.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py pypy/dist/pypy/interpreter/test/mixedmodule/file1.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file1.py pypy/dist/pypy/interpreter/test/mixedmodule/file2_app.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/file2_app.py pypy/dist/pypy/interpreter/test/test_descrtypecheck.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/interpreter/test/test_descrtypecheck.py pypy/dist/pypy/module/builtin/ (props changed) - copied from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/ pypy/dist/pypy/module/builtin/__init__.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py pypy/dist/pypy/module/builtin/app_complex.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_complex.py pypy/dist/pypy/module/builtin/app_descriptor.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_descriptor.py pypy/dist/pypy/module/builtin/app_functional.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_functional.py pypy/dist/pypy/module/builtin/app_help.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_help.py pypy/dist/pypy/module/builtin/app_inspect.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_inspect.py pypy/dist/pypy/module/builtin/app_io.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_io.py pypy/dist/pypy/module/builtin/app_misc.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/app_misc.py pypy/dist/pypy/module/builtin/compiling.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/compiling.py pypy/dist/pypy/module/builtin/importing.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/importing.py pypy/dist/pypy/module/builtin/operation.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/builtin/operation.py pypy/dist/pypy/module/sys2/ (props changed) - copied from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/ pypy/dist/pypy/module/sys2/__init__.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py pypy/dist/pypy/module/sys2/app.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/app.py pypy/dist/pypy/module/sys2/hook.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/hook.py pypy/dist/pypy/module/sys2/state.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/state.py pypy/dist/pypy/module/sys2/vm.py (props changed) - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/module/sys2/vm.py pypy/dist/pypy/tool/getpy.py - copied unchanged from r9330, pypy/branch/dist-interpapp/pypy/tool/getpy.py Removed: pypy/dist/pypy/interpreter/extmodule.py pypy/dist/pypy/interpreter/test/foomodule.py pypy/dist/pypy/interpreter/test/test_extmodule.py pypy/dist/pypy/module/__builtin__interp.py pypy/dist/pypy/module/__builtin__module.py pypy/dist/pypy/module/sysinterp.py pypy/dist/pypy/module/sysmodule.py Modified: pypy/dist/lib-python-2.3.4/test/conftest.py pypy/dist/pypy/TODO pypy/dist/pypy/conftest.py pypy/dist/pypy/interpreter/baseobjspace.py pypy/dist/pypy/interpreter/executioncontext.py pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/interpreter/interactive.py pypy/dist/pypy/interpreter/main.py pypy/dist/pypy/interpreter/module.py pypy/dist/pypy/interpreter/py.py pypy/dist/pypy/interpreter/pycode.py pypy/dist/pypy/interpreter/pyframe.py pypy/dist/pypy/interpreter/pyopcode.py pypy/dist/pypy/interpreter/test/test_appinterp.py pypy/dist/pypy/interpreter/test/test_class.py pypy/dist/pypy/interpreter/test/test_function.py pypy/dist/pypy/interpreter/test/test_gateway.py pypy/dist/pypy/interpreter/test/test_interpreter.py pypy/dist/pypy/interpreter/test/test_main.py pypy/dist/pypy/interpreter/test/test_module.py pypy/dist/pypy/interpreter/test/test_objspace.py pypy/dist/pypy/interpreter/typedef.py pypy/dist/pypy/module/test/test_builtin.py pypy/dist/pypy/module/test/test_import.py pypy/dist/pypy/module/test/test_sysmodule.py pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/flow/flowcontext.py pypy/dist/pypy/objspace/flow/objspace.py pypy/dist/pypy/objspace/flow/specialcase.py pypy/dist/pypy/objspace/std/dictproxyobject.py pypy/dist/pypy/objspace/std/dictproxytype.py pypy/dist/pypy/objspace/std/dicttype.py pypy/dist/pypy/objspace/std/listtype.py pypy/dist/pypy/objspace/std/longobject.py pypy/dist/pypy/objspace/std/model.py pypy/dist/pypy/objspace/std/multimethod.py pypy/dist/pypy/objspace/std/objecttype.py pypy/dist/pypy/objspace/std/objspace.py pypy/dist/pypy/objspace/std/slicetype.py pypy/dist/pypy/objspace/std/stdtypedef.py pypy/dist/pypy/objspace/std/test/test_typeobject.py pypy/dist/pypy/objspace/std/typeobject.py pypy/dist/pypy/objspace/std/typetype.py pypy/dist/pypy/objspace/test/test_traceobjspace.py pypy/dist/pypy/objspace/trivial.py pypy/dist/pypy/tool/pydis.py pypy/dist/pypy/tool/pytestsupport.py pypy/dist/pypy/tool/test/test_pytestsupport.py pypy/dist/pypy/tool/uid.py pypy/dist/pypy/translator/genc.py pypy/dist/pypy/translator/geninterplevel.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py pypy/dist/pypy/translator/tool/tointerplevel.py Log: merge of the dist-interpapp branch where Samuele Armin and me worked for 9 days (summing up to a hundred commits, as you may have noticed in your inbox). Major results (apart from little stuff here and there) are: - a new app2interp mechanism that is now indepedent from the interp2app implementation - a new way to do "mixed modules" which contain applevel and interplevel definitions. We also ported the builtin and sys module and they now live as packages/directory structures. in pypy/module/sys2/__init__.py and pypy/module/builtin/__init__.py you'll find dictionaries which specify where attributes are loaded from (on demand). The old very hacky code for interplevel/applevel modules is gone. - in the course, interp2app was cleaned up a bit and we added more type information/checks for GetSetProperties and other interp-level functions. One consequence of the finalized branch is that the startup time for interactive usage of PyPy is reduced by some 50-70 %. This is mainly due to the now-lazy sys and builtin module. Btw, if you access "__builtin__.__dict__" or "sys.__dict__" then the lazyness ends: all attributes will be loaded and you get a normal dictionary. So from application level the module-lazyness is basically invisible. There are still bits and pieces to be further cleaned or fixed up but that can happen in the trunk now. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Feb 19 15:30:45 2005 @@ -62,9 +62,10 @@ mod = PyPyModule(space, w_dottedname) w_globals = mod.w_dict w_filename = space.wrap(str(filepath)) - space.builtin.execfile(w_filename, w_globals, w_globals) + w_execfile = space.builtin.get('execfile') + space.call_function(w_execfile, w_filename, w_globals, w_globals) w_mod = space.wrap(mod) - w_modules = space.getitem(space.sys.w_dict, space.wrap('modules')) + w_modules = space.sys.get('modules') space.setitem(w_modules, w_dottedname, w_mod) return w_mod Modified: pypy/dist/pypy/TODO ============================================================================== --- pypy/dist/pypy/TODO (original) +++ pypy/dist/pypy/TODO Sat Feb 19 15:30:45 2005 @@ -20,21 +20,13 @@ * (documentation) remove/retire all web-pages referencing e.g. AnnSpace or other deprecated stuff -* Review, enhance the new mixed-level module mechanism - (e.g. the module/builtin*.py files comprise the builtin module) - and try to apply the same technique for the application level - type definitions (types.py). Think about a way to split up - especially app-level definitions of __builtin__ into multiple - files. (like allowing __builtin__ to be a directory with files - comprising the complete definition of the builtin module etc.pp) - * review whatever you like StdObjSpace =========== -* find a way via hacking or elegance to run CPython's unit tests - against the StdObjSpace. +* allow CPython's "output-checking" tests to run in a convenient + way over StdObjSpace * String formatting is agonizingly slow. Modified: pypy/dist/pypy/conftest.py ============================================================================== --- pypy/dist/pypy/conftest.py (original) +++ pypy/dist/pypy/conftest.py Sat Feb 19 15:30:45 2005 @@ -37,11 +37,11 @@ if name == 'std' and py.test.config.option.oldstyle: space.enable_old_style_classes_as_default_metaclass() if name != 'flow': # not sensible for flow objspace case - space.setitem(space.w_builtins, space.wrap('AssertionError'), + space.setitem(space.builtin.w_dict, space.wrap('AssertionError'), pytestsupport.build_pytest_assertion(space)) - space.setitem(space.w_builtins, space.wrap('raises'), + space.setitem(space.builtin.w_dict, space.wrap('raises'), space.wrap(pytestsupport.app_raises)) - space.setitem(space.w_builtins, space.wrap('skip'), + space.setitem(space.builtin.w_dict, space.wrap('skip'), space.wrap(pytestsupport.app_skip)) space.raises_w = pytestsupport.raises_w.__get__(space) space.eq_w = pytestsupport.eq_w.__get__(space) @@ -129,7 +129,7 @@ assert not args name = target.func_globals.get('objspacename', None) space = gettestobjspace(name) - func = app2interp_temp(target, target.__name__) + func = app2interp_temp(target) self.execute_appex(space, func, space) @@ -137,7 +137,7 @@ def execute(self, target, *args): assert not args space = target.im_self.space - func = app2interp_temp(target.im_func, target.__name__) + func = app2interp_temp(target.im_func) self.execute_appex(space, func, space, space.w_None) class AppClassCollector(py.test.collect.Class): Modified: pypy/dist/pypy/interpreter/baseobjspace.py ============================================================================== --- pypy/dist/pypy/interpreter/baseobjspace.py (original) +++ pypy/dist/pypy/interpreter/baseobjspace.py Sat Feb 19 15:30:45 2005 @@ -13,6 +13,18 @@ in a 'normal' object space like StdObjSpace.""" def getdict(self): return None + + def getdictvalue(self, space, attr): + w_dict = self.getdict() + if w_dict is not None: + try: + return space.getitem(w_dict, space.wrap(attr)) + except OperationError, e: + if not e.match(space, space.w_KeyError): + raise + return None + + def getclass(self, space): return space.gettypeobject(self.typedef) @@ -25,6 +37,7 @@ class Wrappable(BaseWrappable, object): """Same as BaseWrappable, just new-style instead.""" + class ObjSpace(object): """Base class for the interpreter-level implementations of object spaces. http://codespeak.net/moin/pypy/moin.cgi/ObjectSpace""" @@ -34,60 +47,36 @@ def __init__(self): "NOT_RPYTHON: Basic initialization of objects." self._gatewaycache = Cache() + self._codecache = Cache() # set recursion limit - self.recursion_limit = 1000 # sets all the internal descriptors self.initialize() def __repr__(self): return self.__class__.__name__ - def make_builtins(self, for_builtins): + def make_builtins(self): "NOT_RPYTHON: only for initializing the space." - # initializing builtins may require creating a frame which in - # turn already accesses space.w_builtins, provide a dummy one ... - self.w_builtins = self.newdict([]) - - # insert stuff into the newly-made builtins - for key, w_value in for_builtins.items(): - self.setitem(self.w_builtins, self.wrap(key), w_value) - - assert not hasattr(self, 'builtin') - if not hasattr(self, 'sys'): - self.make_sys() - - from pypy.interpreter.extmodule import BuiltinModule - - # the builtins are iteratively initialized - self.builtin = BuiltinModule(self, '__builtin__', self.w_builtins) - self.w_builtin = self.wrap(self.builtin) + + from pypy.module.sys2 import Module + w_name = self.wrap('sys') + self.sys = Module(self, w_name) + w_modules = self.sys.get('modules') + self.setitem(w_modules, w_name, self.wrap(self.sys)) + + from pypy.module.builtin import Module + w_name = self.wrap('__builtin__') + self.builtin = Module(self, w_name) + w_builtin = self.wrap(self.builtin) + self.setitem(w_modules, w_name, w_builtin) + self.setitem(self.builtin.w_dict, self.wrap('__builtins__'), w_builtin) # initialize with "bootstrap types" from objspace (e.g. w_None) for name, value in self.__dict__.items(): if name.startswith('w_'): name = name[2:] - if name.startswith('builtin') or name.startswith('sys'): - continue #print "setitem: space instance %-20s into builtins" % name - self.setitem(self.w_builtins, self.wrap(name), value) - - self.sys.setbuiltinmodule(self.w_builtin, '__builtin__') - - def make_sys(self): - "NOT_RPYTHON: only for initializing the space." - from pypy.interpreter.extmodule import BuiltinModule - assert not hasattr(self, 'sys') - self.sys = BuiltinModule(self, 'sys') - self.w_sys = self.wrap(self.sys) - self.sys.setbuiltinmodule(self.w_sys, 'sys') - - def get_builtin_module(self, name): - if name not in self.sys.builtin_modules: - return None - module = self.sys.builtin_modules[name] - w_module = self.wrap(module) - self.sys.setbuiltinmodule(w_module, name) - return w_module + self.setitem(self.builtin.w_dict, self.wrap(name), value) def initialize(self): """NOT_RPYTHON: Abstract method that should put some minimal @@ -279,36 +268,34 @@ statement = PyCode(self)._from_code(statement) if not isinstance(statement, PyCode): raise TypeError, 'space.exec_(): expected a string, code or PyCode object' + w_key = self.wrap('__builtins__') + if not self.is_true(self.contains(w_globals, w_key)): + self.setitem(w_globals, w_key, self.wrap(self.builtin)) return statement.exec_code(self, w_globals, w_locals) - def appexec(self, posargs, source): - """ return value from executing given source at applevel with - given name=wrapped value parameters as its starting scope. - Note: EXPERIMENTAL. - """ - space = self - pypyco = pypycodecache.getorbuild((space,source), buildpypycode, posargs) - w_glob = space.newdict([]) - frame = pypyco.create_frame(space, w_glob) - frame.setfastscope(posargs) - return frame.run() + def appexec(self, posargs_w, source): + """ return value from executing given source at applevel. + EXPERIMENTAL. The source must look like + '''(x, y): + do_stuff... + return result + ''' + """ + w_func = self.loadfromcache(source, buildappexecfunc, self._codecache) + args = Arguments(self, posargs_w) + return self.call_args(w_func, args) -pypycodecache = Cache() -def buildpypycode((space, source), posargs): +def buildappexecfunc(source, space): """ NOT_RPYTHON """ # XXX will change once we have our own compiler from pypy.interpreter.pycode import PyCode from pypy.tool.pytestsupport import py # aehem - argdecl, source = source.split(':', 1) - argdecl = argdecl.strip() - if not argdecl.startswith('(') or not argdecl.endswith(')'): - raise SyntaxError("incorrect exec_with header\n%s" % source) - source = py.code.Source(source) - source = source.putaround("def anon%s:" % argdecl) - d = {} - exec source.compile() in d - newco = d['anon'].func_code - return PyCode(space)._from_code(newco) + source = source.lstrip() + assert source.startswith('('), "incorrect header in:\n%s" % (source,) + source = py.code.Source("def anonymous%s\n" % source) + w_glob = space.newdict([]) + space.exec_(source.compile(), w_glob, w_glob) + return space.getitem(w_glob, space.wrap('anonymous')) ## Table describing the regular part of the interface of object spaces, ## namely all methods which only take w_ arguments and return a w_ result Modified: pypy/dist/pypy/interpreter/executioncontext.py ============================================================================== --- pypy/dist/pypy/interpreter/executioncontext.py (original) +++ pypy/dist/pypy/interpreter/executioncontext.py Sat Feb 19 15:30:45 2005 @@ -12,7 +12,7 @@ self.stateDict = {} def enter(self, frame): - if self.framestack.depth() > self.space.recursion_limit: + if self.framestack.depth() > self.space.sys.recursionlimit: raise OperationError(self.space.w_RuntimeError, self.space.wrap("maximum recursion depth exceeded")) locals = getthreadlocals() @@ -26,16 +26,16 @@ locals = getthreadlocals() locals.executioncontext = previous_ec - def get_w_builtins(self): - if self.framestack.empty(): - return self.space.w_builtins - else: - return self.framestack.top().w_builtins + def get_builtin(self): + try: + return self.framestack.top().builtin + except IndexError: + return self.space.builtin def make_standard_w_globals(self): "Create a new empty 'globals' dictionary." w_key = self.space.wrap("__builtins__") - w_value = self.get_w_builtins() + w_value = self.space.wrap(self.get_builtin()) w_globals = self.space.newdict([(w_key, w_value)]) return w_globals Deleted: /pypy/dist/pypy/interpreter/extmodule.py ============================================================================== --- /pypy/dist/pypy/interpreter/extmodule.py Sat Feb 19 15:30:45 2005 +++ (empty file) @@ -1,180 +0,0 @@ -""" - -Helpers to build extension modules. - -""" - -from __future__ import generators # for generators.compiler_flag -import os, sys -import autopath -from pypy.interpreter import gateway -from pypy.interpreter.error import OperationError -from pypy.interpreter.pycode import PyCode -from pypy.interpreter.function import Function -from pypy.interpreter.module import Module - -class interplevelimport_interp2app(gateway.interp2app): - - def __init__(self, f, w_globals): - "NOT_RPYTHON" - gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False) - self.w_globals = w_globals - - def getglobals(self, space): - "NOT_RPYTHON" - return self.w_globals - - -class BuiltinModule(Module): - """A Module subclass specifically for built-in modules.""" - - # '__builtins__' is stored in self.__dict__ by - # self.interplevel{exec,eval,execfile}() - NOT_RPYTHON_ATTRIBUTES = ['__builtins__'] - - def __init__(self, space, modulename, w_dict=None, sourcefile=None): - """NOT_RPYTHON - Load the named built-in module, by default from the source file - 'pypy/module/module.py', which is app-level Python code - with a few special features that allow it to include interp-level - bits. (See pypy/module/test/foomodule.py) - - The module has two parts: the interp-level objects, stored as - attributes of 'self', and the app-level objects, stored in the - dictionary 'self.w_dict'. The app-level definition of the module - runs with 'self.w_dict' as globals. The interp-level bits are - executed with 'self.__dict__' as globals, i.e. they can read and - change the attributes of 'self' as global variables. - """ - Module.__init__(self, space, space.wrap(modulename), w_dict) - w_dict = self.w_dict - - # Compile the xxxmodule.py source file - self.__name__ = 'interpreter-level %s' % modulename - self.__file__ = sourcefile or os.path.join(autopath.pypydir, 'module', - modulename+'module.py') - space.setitem(w_dict, space.wrap('__file__'), - space.wrap(self.__file__)) - f = open(self.__file__, 'r') - modulesource = f.read() - f.close() - code = compile(modulesource, self.__file__, 'exec', - generators.compiler_flag) - pycode = PyCode(space)._from_code(code) - - # Set the hooks that call back from app-level to interp-level - w_builtins = space.w_builtins - self.__saved_hooks = {} - newhooks = {} - - for name, impl in [ - ('__interplevel__exec', self.interplevelexec.im_func), - ('__interplevel__eval', self.interpleveleval.im_func), - ('__interplevel__execfile', self.interplevelexecfile.im_func), - ('__import__', self.interplevelimport.im_func)]: - hook = gateway.interp2app_temp(impl).get_method(self) - w_name = space.wrap(name) - try: - self.__saved_hooks[name] = space.getitem(w_builtins, w_name) - except OperationError: - pass - w_hook = space.wrap(hook) - space.setitem(w_builtins, w_name, w_hook) - newhooks[name] = w_hook - space.setitem(self.w_dict, space.wrap('__builtins__'), - space.w_builtins) - - # Temporarily install an '__applevel__' pseudo-module - sys.modules['__applevel__'] = AppModuleHack(self) - - # Run the app-level module definition (xxxmodule.py) - pycode.exec_code(space, w_dict, w_dict) - - # Remove the pseudo-module - del sys.modules['__applevel__'] - try: - del self.__applevel__ - except AttributeError: - pass - - # Remove/restore the hooks unless they have been modified at app-level - for name, w_hook in newhooks.items(): - w_name = space.wrap(name) - try: - w_current = space.getitem(w_builtins, w_name) - except OperationError: - pass - else: - if space.is_true(space.is_(w_current, w_hook)): - if name in self.__saved_hooks: - space.setitem(w_builtins, w_name, - self.__saved_hooks[name]) - else: - space.delitem(w_builtins, w_name) - del self.__saved_hooks - - def interplevelexec(self, w_codestring): - "NOT_RPYTHON: 'exec' a string at interp-level." - codestring = self.space.str_w(w_codestring) - exec codestring in self.__dict__ - return self.space.w_None - - def interpleveleval(self, w_codestring): - """NOT_RPYTHON: 'eval' a string at interp-level. The result must - be None or a wrapped object, which is returned to the caller.""" - space = self.space - codestring = space.str_w(w_codestring) - w_result = eval(codestring, self.__dict__) - if w_result is None: - w_result = space.w_None # else assume that it is already wrapped - return w_result - - def interplevelexecfile(self, w_filename): - """NOT_RPYTON: 'exec' a file at interp-level. The file should be in - the same directory as the xxxmodule.py source file of the module.""" - filename = self.space.str_w(w_filename) - filename = os.path.join(os.path.dirname(self.__file__), filename) - execfile(filename, self.__dict__) - return self.space.w_None - - def interplevelimport(self, w_modulename, w_globals, w_locals, w_fromlist): - """NOT_RPYTHON: Hook for 'from __interplevel__ import something'. - If there is a wrapped interp-level object 'w_something', returns it. - If there is an interp-level function 'def something(w_x, w_y...)', - build an appropriate gateway and returns it. - """ - space = self.space - w = space.wrap - if space.is_true(space.eq(w_modulename, w('__interplevel__'))): - if w_fromlist == space.w_None: - raise ImportError, "must use 'from __interplevel__ import xx'" - for w_name in space.unpacktuple(w_fromlist): - name = space.str_w(w_name) - if not hasattr(self, 'w_' + name): - f = getattr(self, name) - func = interplevelimport_interp2app(f, self.w_dict) - w_result = space.wrap(func) - else: - w_result = getattr(self, 'w_' + name) - space.setitem(self.w_dict, w_name, w_result) - return space.wrap(self) - else: - return space.call_function(self.__saved_hooks['__import__'], - w_modulename, w_globals, - w_locals, w_fromlist) - -class AppModuleHack: - """NOT_RPYTHON - For interp-level convenience: 'from __applevel__ import func' - imports the app-level function 'func' via an appropriate gateway. - """ - def __init__(self, builtinmodule): - self.space = builtinmodule.space - self.w_dict = builtinmodule.w_dict - def __getattr__(self, name): - if name.startswith('__'): - raise AttributeError, name - w_func = self.space.getitem(self.w_dict, self.space.wrap(name)) - def caller(*args): - return self.space.call_function(w_func, *args) - return caller Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Sat Feb 19 15:30:45 2005 @@ -2,7 +2,6 @@ Gateway between app-level and interpreter-level: * BuiltinCode (call interp-level code from app-level) -* Gateway (a space-independent gateway to a Code object) * app2interp (embed an app-level function into an interp-level callable) * interp2app (publish an interp-level object to be visible from app-level) * exportall (mass-call interp2app on a whole dict of objects) @@ -16,9 +15,11 @@ from pypy.interpreter.error import OperationError from pypy.interpreter import eval from pypy.interpreter.function import Function, Method -from pypy.interpreter.baseobjspace import W_Root,ObjSpace,Wrappable +from pypy.interpreter.baseobjspace import W_Root,ObjSpace, BaseWrappable, Wrappable from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache +# internal non-translatable parts: +from pypy.tool.getpy import py # XXX from interpreter/ we get py.py NoneNotWrapped = object() @@ -35,16 +36,9 @@ self.argnames = argnames self.varargname = varargname self.kwargname = kwargname - self.rewind() - def rewind(self): - self._iter = iter(self.argnames) - - def __iter__(self): - return self - - def next(self): - return self._iter.next() + def next_arg(self): + return self._argiter.next() def append(self, argname): self.argnames.append(argname) @@ -52,11 +46,188 @@ def signature(self): return self.argnames, self.varargname, self.kwargname -def apply_unwrap_spec(unwrap_spec, orig_sig, new_sig, recipes): - for el in unwrap_spec: - recipes[el](orig_sig, new_sig) - return new_sig + def apply_unwrap_spec(self, unwrap_spec, recipe, new_sig): + self._argiter = iter(self.argnames) + for el in unwrap_spec: + recipe(el, self, new_sig) + return new_sig + + +class UnwrapSpecRecipe: + + bases_order = [BaseWrappable, W_Root, ObjSpace, Arguments, object] + + def dispatch(self, meth_family, el, orig_sig, new_sig): + if isinstance(el,str): + getattr(self, "%s_%s" % (meth_family, el))(el, orig_sig, new_sig) + else: + for typ in self.bases_order: + if issubclass(el, typ): + getattr(self, "%s__%s" % (meth_family, typ.__name__))(el, orig_sig, new_sig) + break + else: + assert False, "no match for unwrap_spec element: %s" % el + + def check(self, el, orig_sig, new_sig): + self.dispatch("check", el, orig_sig, new_sig) + + def emit(self, el, orig_sig, new_sig): + self.dispatch("emit", el, orig_sig, new_sig) + + + # checks for checking interp2app func argument names wrt unwrap_spec + # and synthetizing an app-level signature + + def check__BaseWrappable(self, el, orig_sig, app_sig): + name = el.__name__ + argname = orig_sig.next_arg() + assert not argname.startswith('w_'), ( + "unwrapped %s argument %s of built-in function %r should " + "not start with 'w_'" % (name, argname, orig_sig.func)) + app_sig.append(argname) + + def check__ObjSpace(self, el, orig_sig, app_sig): + orig_sig.next_arg() + + def check__W_Root(self, el, orig_sig, app_sig): + assert el is W_Root, "oops" + argname = orig_sig.next_arg() + assert argname.startswith('w_'), ( + "argument %s of built-in function %r should " + "start with 'w_'" % (argname, orig_sig.func)) + app_sig.append(argname[2:]) + + def check__Arguments(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = 'args' + app_sig.kwargname = 'keywords' + + def check_starargs(self, el, orig_sig, app_sig): + varargname = orig_sig.varargname + assert varargname.endswith('_w'), ( + "argument *%s of built-in function %r should end in '_w'" % + (varargname, orig_sig.func)) + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = varargname[:-2] + + def check_args_w(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert argname.endswith('_w'), ( + "rest arguments arg %s of built-in function %r should end in '_w'" % + (argname, orig_sig.func)) + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = argname[:-2] + + def check_w_args(self, el, orig_sig, app_sig): + argname = orig_sig.next_arg() + assert argname.startswith('w_'), ( + "rest arguments arg %s of built-in function %r should start 'w_'" % + (argname, orig_sig.func)) + assert app_sig.varargname is None,( + "built-in function %r has conflicting rest args specs" % orig_sig.func) + app_sig.varargname = argname[2:] + + def check__object(self, el, orig_sig, app_sig): + if el not in (int, str, float): + assert False, "unsupported basic type in uwnrap_spec" + name = el.__name__ + argname = orig_sig.next_arg() + assert not argname.startswith('w_'), ( + "unwrapped %s argument %s of built-in function %r should " + "not start with 'w_'" % (name, argname, orig_sig.func)) + app_sig.append(argname) + + # collect code to emit for interp2app builtin frames based on unwrap_spec + + def emit__BaseWrappable(self, el, orig_sig, emit_sig): + name = el.__name__ + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "obj = self.space.interpclass_w(scope_w[%d])" % cur) + emit_sig.setfastscope.append( + "if obj is None or not isinstance(obj, %s):" % name) + emit_sig.setfastscope.append( + " raise OperationError(self.space.w_TypeError,self.space.wrap('expected %%s' %% %s.typedef.name ))" % name) # xxx + emit_sig.miniglobals[name] = el + emit_sig.miniglobals['OperationError'] = OperationError + emit_sig.setfastscope.append( + "self.%s_arg%d = obj" % (name,cur)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.%s_arg%d" % (name,cur)) + + def emit__ObjSpace(self, el, orig_sig, emit_sig): + emit_sig.run_args.append('self.space') + + def emit__W_Root(self, el, orig_sig, emit_sig): + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "self.w_arg%d = scope_w[%d]" % (cur,cur)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.w_arg%d" % cur) + + def emit__Arguments(self, el, orig_sig, emit_sig): + cur = emit_sig.through_scope_w + emit_sig.through_scope_w += 2 + emit_sig.miniglobals['Arguments'] = Arguments + emit_sig.setfastscope.append( + "self.arguments_arg = " + "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" + % (cur, cur+1)) + emit_sig.run_args.append("self.arguments_arg") + + def emit_starargs(self, el, orig_sig, emit_sig): + emit_sig.setfastscope.append( + "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" % + (emit_sig.through_scope_w)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("*self.starargs_arg_w") + + def emit_args_w(self, el, orig_sig, emit_sig): + emit_sig.setfastscope.append( + "self.args_w = self.space.unpacktuple(scope_w[%d])" % + (emit_sig.through_scope_w)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.args_w") + + def emit_w_args(self, el, orig_sig, emit_sig): + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "self.w_args = scope_w[%d]" % cur) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.w_args") + + def emit__object(self, el, orig_sig, emit_sig): + if el not in (int, str, float): + assert False, "unsupported basic type in uwnrap_spec" + name = el.__name__ + cur = emit_sig.through_scope_w + emit_sig.setfastscope.append( + "self.%s_arg%d = self.space.%s_w(scope_w[%d])" % + (name,cur,name,cur)) + emit_sig.through_scope_w += 1 + emit_sig.run_args.append("self.%s_arg%d" % (name,cur)) + +class BuiltinFrame(eval.Frame): + "Frame emulation for BuiltinCode." + # Subclasses of this are defined with the function to delegate to attached through miniglobals. + # Initialization of locals is already done by the time run() is called, + # via the interface defined in eval.Frame. + + def setfastscope(self, scope_w): + """Subclasses with behavior specific for an unwrap spec are generated""" + raise TypeError, "abstract" + + def getfastscope(self): + raise OperationError(self.space.w_TypeError, + self.space.wrap("cannot get fastscope of a BuiltinFrame")) + def run(self): + """Subclasses with behavior specific for an unwrap spec are generated""" + raise TypeError, "abstract" class BuiltinCodeSignature(Signature): @@ -65,8 +236,9 @@ self.setfastscope = [] self.run_args = [] self.through_scope_w = 0 + self.miniglobals = {} - def make_frame_class(self): + def make_frame_class(self, func): setfastscope = self.setfastscope if not setfastscope: setfastscope = ["pass"] @@ -78,183 +250,37 @@ # Python 2.2 SyntaxError without newline: Bug #501622 setfastscope += '\n' d = {} - exec setfastscope in globals(),d - exec """ -def run(self): - try: - w_result = self.code.func(%s) - except KeyboardInterrupt: - raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) - except MemoryError: - raise OperationError(self.space.w_MemoryError, self.space.w_None) - except RuntimeError, e: - raise OperationError(self.space.w_RuntimeError, - self.space.wrap("internal error" + str(e))) - if w_result is None: - w_result = self.space.w_None - return w_result -""" % ','.join(self.run_args) in globals(),d + exec compile(setfastscope, '', 'exec') in self.miniglobals, d + + self.miniglobals['func'] = func + source = """if 1: + def run(self): + try: + w_result = func(%s) + except KeyboardInterrupt: + raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) + except MemoryError: + raise OperationError(self.space.w_MemoryError, self.space.w_None) + except RuntimeError, e: + raise OperationError(self.space.w_RuntimeError, + self.space.wrap("internal error" + str(e))) + if w_result is None: + w_result = self.space.w_None + return w_result + \n""" % ','.join(self.run_args) + exec compile(source, '', 'exec') in self.miniglobals, d return type("BuiltinFrame_for_%s" % self.name, (BuiltinFrame,),d) - -def unwrap_spec_check_space(orig_sig, new_sig): - orig_sig.next() - -def unwrap_spec_check_self(orig_sig, new_sig): - argname = orig_sig.next() - new_sig.append(argname) - - -def unwrap_spec_check_wrapped(orig_sig, new_sig): - argname = orig_sig.next() - assert argname.startswith('w_'), ( - "argument %s of built-in function %r should " - "start with 'w_'" % (argname, orig_sig.func)) - new_sig.append(argname[2:]) - -def unwrap_spec_check_arguments(orig_sig, new_sig): - argname = orig_sig.next() - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = 'args' - new_sig.kwargname = 'keywords' - -def unwrap_spec_check_starargs(orig_sig, new_sig): - varargname = orig_sig.varargname - assert varargname.endswith('_w'), ( - "argument *%s of built-in function %r should end in '_w'" % - (varargname, orig_sig.func)) - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = varargname[:-2] - -def unwrap_spec_check_args_w(orig_sig, new_sig): - argname = orig_sig.next() - assert argname.endswith('_w'), ( - "rest arguments arg %s of built-in function %r should end in '_w'" % - (argname, orig_sig.func)) - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = argname[:-2] - -def unwrap_spec_check_w_args(orig_sig, new_sig): - argname = orig_sig.next() - assert argname.startswith('w_'), ( - "rest arguments arg %s of built-in function %r should start 'w_'" % - (argname, orig_sig.func)) - assert new_sig.varargname is None,( - "built-in function %r has conflicting rest args specs" % orig_sig.func) - new_sig.varargname = argname[2:] - -# recipes for checking interp2app func argumes wrt unwrap_spec -unwrap_spec_checks = { - ObjSpace: unwrap_spec_check_space, - 'self': unwrap_spec_check_self, - W_Root: unwrap_spec_check_wrapped, - Arguments: unwrap_spec_check_arguments, - '*': unwrap_spec_check_starargs, - 'args_w': unwrap_spec_check_args_w, - 'w_args': unwrap_spec_check_w_args, -} - -def unwrap_spec_emit_space(orig_sig, new_sig): - new_sig.run_args.append('self.space') - -def unwrap_spec_emit_self(orig_sig, new_sig): - new_sig.setfastscope.append( - "self.self_arg = self.space.interpclass_w(scope_w[%d])" % - (new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.self_arg") - -def unwrap_spec_emit_wrapped(orig_sig, new_sig): - cur = new_sig.through_scope_w - new_sig.setfastscope.append( - "self.w_arg%d = scope_w[%d]" % (cur,cur)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.w_arg%d" % cur) - - -def unwrap_spec_emit_arguments(orig_sig, new_sig): - cur = new_sig.through_scope_w - new_sig.through_scope_w += 2 - new_sig.setfastscope.append( - "self.arguments_arg = " - "Arguments.frompacked(self.space,scope_w[%d],scope_w[%d])" - % (cur, cur+1)) - new_sig.run_args.append("self.arguments_arg") - -def unwrap_spec_emit_starargs(orig_sig, new_sig): - new_sig.setfastscope.append( - "self.starargs_arg_w = self.space.unpacktuple(scope_w[%d])" % - (new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("*self.starargs_arg_w") - -def unwrap_spec_emit_args_w(orig_sig, new_sig): - new_sig.setfastscope.append( - "self.args_w = self.space.unpacktuple(scope_w[%d])" % - (new_sig.through_scope_w)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.args_w") - -def unwrap_spec_emit_w_args(orig_sig, new_sig): - cur = new_sig.through_scope_w - new_sig.setfastscope.append( - "self.w_args = scope_w[%d]" % cur) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.w_args") - -# recipes for emitting unwrapping code for arguments of a interp2app func -# wrt a unwrap_spec -unwrap_spec_emit = { - ObjSpace: unwrap_spec_emit_space, - 'self': unwrap_spec_emit_self, - W_Root: unwrap_spec_emit_wrapped, - Arguments: unwrap_spec_emit_arguments, - '*': unwrap_spec_emit_starargs, - 'args_w': unwrap_spec_emit_args_w, - 'w_args': unwrap_spec_emit_w_args, -} - -# unwrap_spec_check/emit for str,int,float -for basic_type in [str,int,float]: - name = basic_type.__name__ - def unwrap_spec_check_basic(orig_sig, new_sig, name=name): - argname = orig_sig.next() - assert not argname.startswith('w_'), ( - "unwrapped %s argument %s of built-in function %r should " - "not start with 'w_'" % (name, argname, orig_sig.func)) - new_sig.append(argname) - def unwrap_spec_emit_basic(orig_sig, new_sig, name=name): - cur = new_sig.through_scope_w - new_sig.setfastscope.append( - "self.%s_arg%d = self.space.%s_w(scope_w[%d])" % - (name,cur,name,cur)) - new_sig.through_scope_w += 1 - new_sig.run_args.append("self.%s_arg%d" % (name,cur)) - unwrap_spec_checks[basic_type] = hack.func_with_new_name( - unwrap_spec_check_basic, "unwrap_spec_check_%s" % name) - unwrap_spec_emit[basic_type] = hack.func_with_new_name( - unwrap_spec_emit_basic, "unwrap_spec_emit_%s" % name) - - - -def make_builtin_frame_class_for_unwrap_spec(unwrap_spec, cache={}): +def make_builtin_frame_class(func, orig_sig, unwrap_spec): "NOT_RPYTHON" - key = tuple(unwrap_spec) - try: - return cache[key] - except KeyError: - name = '_'.join([getattr(k, "__name__", k) for k in key]) - emit_sig = apply_unwrap_spec(unwrap_spec, None, - BuiltinCodeSignature(name=name), - unwrap_spec_emit) + name = (getattr(func, '__module__', None) or '')+'_'+func.__name__ + emit_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().emit, + BuiltinCodeSignature(name=name)) + cls = emit_sig.make_frame_class(func) + return cls + - cache[key] = cls = emit_sig.make_frame_class() - return cls - class BuiltinCode(eval.Code): "The code object implementing a built-in (interpreter-level) hook." @@ -262,28 +288,19 @@ # When a BuiltinCode is stored in a Function object, # you get the functionality of CPython's built-in function type. - def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None): + def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None, self_type = None): "NOT_RPYTHON" # 'implfunc' is the interpreter-level function. # Note that this uses a lot of (construction-time) introspection. eval.Code.__init__(self, func.__name__) - self.func = func self.docstring = func.__doc__ - # signature-based hacks if unwrap_spec is not specified: - # renaming arguments from w_xyz to xyz. - # Currently we enforce the following signature tricks: - # * the first arg must be either 'self' or 'space' - # * 'w_' prefixes for the rest - # * '_w' suffix for the optional '*' argument - # * alternatively a final '__args__' means an Arguments() - # Not exactly a clean approach XXX. - # -- + # unwrap_spec can be passed to interp2app or # attached as an attribute to the function. # It is a list of types or singleton objects: # baseobjspace.ObjSpace is used to specify the space argument - # 'self' is used to specify a self method argument # baseobjspace.W_Root is for wrapped arguments to keep wrapped + # baseobjspace.BaseWrappable subclasses imply interpclass_w and a typecheck # argument.Arguments is for a final rest arguments Arguments object # 'args_w' for unpacktuple applied to rest arguments # 'w_args' for rest arguments passed as wrapped tuple @@ -293,57 +310,33 @@ from pypy.interpreter import pycode argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) + assert not ismethod, ("ismethod is not expected anymore") + assert not spacearg, ("spacearg is not expected anymore") + if unwrap_spec is None: unwrap_spec = getattr(func,'unwrap_spec',None) - - if unwrap_spec is None: - unwrap_spec = [] + if unwrap_spec is None and argnames == ['space', '__args__']: #xxx for geninterp + #print sys._getframe(2).f_globals['__name__'] + unwrap_spec = [ObjSpace, Arguments] - argnames = list(argnames) - lookslikemethod = argnames[:1] == ['self'] - if ismethod is None: - ismethod = lookslikemethod - if spacearg is None: - spacearg = not lookslikemethod - self.ismethod = ismethod - self.spacearg = spacearg - assert kwargname is None, ( - "built-in function %r should not take a ** argument" % func) - - n = len(argnames) - - if self.ismethod: - unwrap_spec.append('self') - n -= 1 - if self.spacearg: - unwrap_spec.append(ObjSpace) - n -= 1 - - self.generalargs = argnames[-1:] == ['__args__'] - self.starargs = varargname is not None - - if self.generalargs: - unwrap_spec.extend([W_Root] * (n-1)) - unwrap_spec.append(Arguments) - else: - unwrap_spec.extend([W_Root] * n) + if unwrap_spec is None: + unwrap_spec = [ObjSpace]+ [W_Root] * (len(argnames)-1) - if self.starargs: - unwrap_spec.append('*') - else: - assert not ismethod, ("if unwrap_spec is specified, " - "ismethod is not expected") - assert not spacearg, ("if unwrap_spec is specified, " - "spacearg is not expected") + if self_type: + unwrap_spec = ['self'] + unwrap_spec[1:] + + if self_type: + assert unwrap_spec[0] == 'self',"self_type without 'self' spec element" + unwrap_spec = list(unwrap_spec) + unwrap_spec[0] = self_type orig_sig = Signature(func, argnames, varargname, kwargname) - new_sig = apply_unwrap_spec(unwrap_spec, orig_sig, - Signature(func), - unwrap_spec_checks) + app_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().check, + Signature(func)) - self.sig = argnames, varargname, kwargname = new_sig.signature() + self.sig = argnames, varargname, kwargname = app_sig.signature() self.minargs = len(argnames) if varargname: @@ -351,7 +344,7 @@ else: self.maxargs = self.minargs - self.framecls = make_builtin_frame_class_for_unwrap_spec(unwrap_spec) + self.framecls = make_builtin_frame_class(func, orig_sig, unwrap_spec) def create_frame(self, space, w_globals, closure=None): return self.framecls(space, self, w_globals) @@ -363,183 +356,29 @@ return self.docstring -class BuiltinFrame(eval.Frame): - "Frame emulation for BuiltinCode." - # This is essentially just a delegation to the 'func' of the BuiltinCode. - # Initialization of locals is already done by the time run() is called, - # via the interface defined in eval.Frame. - - def setfastscope(self, scope_w): - """Subclasses with behavior specific for an unwrap spec are generated""" - raise TypeError, "abstract" +class interp2app(Wrappable): + """Build a gateway that calls 'f' at interp-level.""" - def getfastscope(self): - raise OperationError(self.space.w_TypeError, - self.space.wrap("cannot get fastscope of a BuiltinFrame")) - - def run(self): - """Subclasses with behavior specific for an unwrap spec are generated""" - raise TypeError, "abstract" - - -class Gateway(Wrappable): - """General-purpose utility for the interpreter-level to create callables - that transparently invoke code objects (and thus possibly interpreted - app-level code).""" - - # This is similar to a Function object, but not bound to a particular - # object space. During the call, the object space is either given - # explicitly as the first argument (for plain function), or is read - # from 'self.space' for methods. - - # after initialization the following attributes should be set - # name - # _staticglobals - # _staticdefs - # - # getcode is called lazily to get the code object to construct - # the space-bound function - - NOT_RPYTHON_ATTRIBUTES = ['_staticglobals', '_staticdefs'] - - def getcode(self, space): - # needs to be implemented by subclasses - raise TypeError, "abstract" - - def __spacebind__(self, space): - # to wrap a Gateway, we first make a real Function object out of it - # and the result is a wrapped version of this Function. - return self.get_function(space) - - def get_function(self, space): - return space.loadfromcache(self, - Gateway.build_all_functions, - self.getcache(space)) - - def getglobals(self, space): - "NOT_RPYTHON" - if self._staticglobals is None: - w_globals = None - else: - # is there another Gateway in _staticglobals for which we - # already have a w_globals for this space ? - cache = self.getcache(space) - for value in self._staticglobals.itervalues(): - if isinstance(value, Gateway): - if value in cache.content: - # yes, we share its w_globals - fn = cache.content[value] - w_globals = fn.w_func_globals - break - else: - # no, we build all Gateways in the _staticglobals now. - w_globals = build_dict(self._staticglobals, space) - return w_globals - - def build_all_functions(self, space): - "NOT_RPYTHON" - # the construction is supposed to be done only once in advance, - # but must be done lazily when needed only, because - # 1) it depends on the object space - # 2) the w_globals must not be built before the underlying - # _staticglobals is completely initialized, because - # w_globals must be built only once for all the Gateway - # instances of _staticglobals - return self._build_function(space, self.getglobals(space)) - - def getcache(self, space): - return space._gatewaycache - - def _build_function(self, space, w_globals): - "NOT_RPYTHON" - cache = self.getcache(space) - try: - return cache.content[self] - except KeyError: - defs = self.getdefaults(space) # needs to be implemented by subclass - code = self.getcode(space) - fn = Function(space, code, w_globals, defs, forcename = self.name) - cache.content[self] = fn - return fn - - def get_method(self, obj): - # to get the Gateway as a method out of an instance, we build a - # Function and get it. - # the object space is implicitely fetched out of the instance - space = obj.space - fn = self.get_function(space) - w_obj = space.wrap(obj) - return Method(space, space.wrap(fn), - w_obj, space.type(w_obj)) - - -class app2interp(Gateway): - """Build a Gateway that calls 'app' at app-level.""" - - NOT_RPYTHON_ATTRIBUTES = ['_staticcode'] + Gateway.NOT_RPYTHON_ATTRIBUTES - - def __init__(self, app, app_name=None): - "NOT_RPYTHON" - Gateway.__init__(self) - # app must be a function whose name starts with 'app_'. - if not isinstance(app, types.FunctionType): - raise TypeError, "function expected, got %r instead" % app - if app_name is None: - if not app.func_name.startswith('app_'): - raise ValueError, ("function name must start with 'app_'; " - "%r does not" % app.func_name) - app_name = app.func_name[4:] - self.__name__ = app.func_name - self.name = app_name - self._staticcode = app.func_code - self._staticglobals = app.func_globals - self._staticdefs = list(app.func_defaults or ()) - - def getcode(self, space): - "NOT_RPYTHON" - from pypy.interpreter import pycode - code = pycode.PyCode(space) - code._from_code(self._staticcode) - return code - - def getdefaults(self, space): - "NOT_RPYTHON" - return [space.wrap(val) for val in self._staticdefs] - - def __call__(self, space, *args_w): - # to call the Gateway as a non-method, 'space' must be explicitly - # supplied. We build the Function object and call it. - fn = self.get_function(space) - return space.call_function(space.wrap(fn), *args_w) - - def __get__(self, obj, cls=None): - "NOT_RPYTHON" - if obj is None: - return self - else: - space = obj.space - w_method = space.wrap(self.get_method(obj)) - def helper_method_caller(*args_w): - return space.call_function(w_method, *args_w) - return helper_method_caller - -class interp2app(Gateway): - """Build a Gateway that calls 'f' at interp-level.""" - - # NOTICE even interp2app defaults are stored and passed as + # NOTICE interp2app defaults are stored and passed as # wrapped values, this to avoid having scope_w be of mixed - # wrapped and unwrapped types, - # an exception is made for None which is passed around as default - # as an unwrapped None, unwrapped None and wrapped types are - # compatible + # wrapped and unwrapped types; + # an exception is made for the NoneNotWrapped special value + # which is passed around as default as an unwrapped None, + # unwrapped None and wrapped types are compatible # # Takes optionally an unwrap_spec, see BuiltinCode + + NOT_RPYTHON_ATTRIBUTES = ['_staticdefs'] def __init__(self, f, app_name=None, ismethod=None, spacearg=None, unwrap_spec = None): "NOT_RPYTHON" - Gateway.__init__(self) + Wrappable.__init__(self) # f must be a function whose name does NOT starts with 'app_' + self_type = None + if hasattr(f, 'im_func'): + self_type = f.im_class + f = f.im_func if not isinstance(f, types.FunctionType): raise TypeError, "function expected, got %r instead" % f if app_name is None: @@ -549,18 +388,13 @@ app_name = f.func_name self._code = BuiltinCode(f, ismethod=ismethod, spacearg=spacearg, - unwrap_spec=unwrap_spec) + unwrap_spec=unwrap_spec, + self_type = self_type) self.__name__ = f.func_name self.name = app_name self._staticdefs = list(f.func_defaults or ()) - #if self._staticdefs: - # print f.__module__,f.__name__,"HAS NON TRIVIAL DEFLS",self._staticdefs - self._staticglobals = None - def getcode(self, space): - return self._code - - def getdefaults(self, space): + def _getdefaults(self, space): "NOT_RPYTHON" defs_w = [] for val in self._staticdefs: @@ -570,13 +404,48 @@ defs_w.append(space.wrap(val)) return defs_w + # lazy binding to space + + def __spacebind__(self, space): + # we first make a real Function object out of it + # and the result is a wrapped version of this Function. + return self.get_function(space) + + def get_function(self, space): + return space.loadfromcache(self, + interp2app.build_function, + self.getcache(space)) + + def getcache(self, space): + return space._gatewaycache + def get_method(self, obj): - assert self._code.ismethod, ( - 'global built-in function %r used as method' % - self._code.func) - return Gateway.get_method(self, obj) + # to bind this as a method out of an instance, we build a + # Function and get it. + # the object space is implicitely fetched out of the instance + assert self._code.ismethod, ( + 'global built-in function %r used as method' % + self._code.func) + + space = obj.space + fn = self.get_function(space) + w_obj = space.wrap(obj) + return Method(space, space.wrap(fn), + w_obj, space.type(w_obj)) + def build_function(self, space): + "NOT_RPYTHON" + cache = self.getcache(space) + try: + return cache.content[self] + except KeyError: + defs = self._getdefaults(space) # needs to be implemented by subclass + code = self._code + fn = Function(space, code, None, defs, forcename = self.name) + cache.content[self] = fn + return fn + def exportall(d, temporary=False): """NOT_RPYTHON: Publish every function from a dict.""" if temporary: @@ -618,34 +487,89 @@ for name, obj in d.items(): if name.startswith('app_') and name[4:] not in d: if isinstance(obj, types.FunctionType): - d[name[4:]] = a2i(obj, name[4:]) - -def build_dict(d, space): - """NOT_RPYTHON: - Search all Gateways and put them into a wrapped dictionary.""" - w_globals = space.newdict([]) - for value in d.itervalues(): - if isinstance(value, Gateway): - fn = value._build_function(space, w_globals) - w_name = space.wrap(value.name) - w_object = space.wrap(fn) - space.setitem(w_globals, w_name, w_object) - if hasattr(space, 'w_sys'): # give them 'sys' if it exists already - space.setitem(w_globals, space.wrap('sys'), space.w_sys) - return w_globals - + d[name[4:]] = a2i(obj) # # the next gateways are to be used only for # temporary/initialization purposes -class app2interp_temp(app2interp): - "NOT_RPYTHON" - def getcache(self, space): - return self.__dict__.setdefault(space, Cache()) - # ^^^^^ - # armin suggested this class interp2app_temp(interp2app): "NOT_RPYTHON" def getcache(self, space): return self.__dict__.setdefault(space, Cache()) + + +# and now for something completly different ... +# + +class applevel: + """A container for app-level source code that should be executed + as a module in the object space; interphook() builds a static + interp-level function that invokes the callable with the given + name at app-level.""" + + NOT_RPYTHON_ATTRIBUTES = ['code'] + + def __init__(self, source): + "NOT_RPYTHON" + self.code = py.code.Source(source).compile() + + def getwdict(self, space): + return space.loadfromcache(self, applevel._builddict, + space._gatewaycache) + + def buildmodule(self, space, name='applevel'): + from pypy.interpreter.module import Module + return Module(space, space.wrap(name), self.getwdict(space)) + + def _builddict(self, space): + "NOT_RPYTHON" + w_glob = space.newdict([]) + space.exec_(self.code, w_glob, w_glob) + return w_glob + + def wget(self, space, name): + w_globals = self.getwdict(space) + return space.getitem(w_globals, space.wrap(name)) + + def interphook(self, name): + "NOT_RPYTHON" + def appcaller(space, *args_w): + args = Arguments(space, args_w) + w_func = self.wget(space, name) + return space.call_args(w_func, args) + def get_function(space): + w_func = self.wget(space, name) + return space.unwrap(w_func) + appcaller = hack.func_with_new_name(appcaller, name) + appcaller.get_function = get_function + return appcaller + +def appdef(source, applevel=applevel): + """ NOT_RPYTHON: build an app-level helper function, like for example: + myfunc = appdef('''myfunc(x, y): + return x+y + ''') + """ + from pypy.interpreter.pycode import PyCode + if not isinstance(source, str): + source = str(py.code.Source(source).strip()) + assert source.startswith("def "), "can only transform functions" + source = source[4:] + p = source.find('(') + assert p >= 0 + funcname = source[:p].strip() + source = source[p:] + return applevel("def %s%s\n" % (funcname, source)).interphook(funcname) + +app2interp = appdef # backward compatibility + + +# app2interp_temp is used for testing mainly +class applevel_temp(applevel): + def getwdict(self, space): + return self._builddict(space) # no cache + +def app2interp_temp(func): + """ NOT_RPYTHON """ + return appdef(func, applevel_temp) Modified: pypy/dist/pypy/interpreter/interactive.py ============================================================================== --- pypy/dist/pypy/interpreter/interactive.py (original) +++ pypy/dist/pypy/interpreter/interactive.py Sat Feb 19 15:30:45 2005 @@ -4,6 +4,7 @@ from pypy.interpreter import executioncontext, baseobjspace import sys import code +import time class PyPyConsole(code.InteractiveConsole): @@ -22,8 +23,9 @@ #banner = "Python %s in pypy\n%s / %s" % ( # sys.version, self.__class__.__name__, # self.space.__class__.__name__) - banner = "PyPy in %s on top of Python %s" % ( - self.space.__class__.__name__, sys.version.split()[0]) + elapsed = time.time() - self.space._starttime + banner = "PyPy in %s on top of Python %s (startupttime: %.2f secs)" % ( + self.space.__class__.__name__, sys.version.split()[0], elapsed) code.InteractiveConsole.interact(self, banner) def raw_input(self, prompt=""): Modified: pypy/dist/pypy/interpreter/main.py ============================================================================== --- pypy/dist/pypy/interpreter/main.py (original) +++ pypy/dist/pypy/interpreter/main.py Sat Feb 19 15:30:45 2005 @@ -14,15 +14,17 @@ from pypy.objspace.std import StdObjSpace space = StdObjSpace() - compile = space.builtin.compile + w_compile = space.builtin.get('compile') w = space.wrap - w_code = compile(w(source), filename, cmd, 0, 0) - + w_code = space.call_function(w_compile, + w(source), w(filename), w(cmd), w(0), w(0)) w_main = space.wrap('__main__') mainmodule = module.Module(space, w_main) - space.setitem(space.sys.w_modules, w_main, mainmodule) + w_modules = space.sys.get('modules') + space.setitem(w_modules, w_main, mainmodule) w_globals = mainmodule.w_dict + space.setitem(w_globals, w('__builtins__'), space.builtin) pycode = space.interpclass_w(w_code) retval = pycode.exec_code(space, w_globals, w_globals) Modified: pypy/dist/pypy/interpreter/module.py ============================================================================== --- pypy/dist/pypy/interpreter/module.py (original) +++ pypy/dist/pypy/interpreter/module.py Sat Feb 19 15:30:45 2005 @@ -10,20 +10,16 @@ def __init__(self, space, w_name, w_dict=None): self.space = space - if w_dict is None: + if w_dict is None: w_dict = space.newdict([]) - self.w_dict = w_dict - self.w_name = w_name - space.setitem(w_dict, space.wrap('__name__'), w_name) - if not space.is_true(space.contains(w_dict, space.wrap('__doc__'))): - space.setitem(w_dict, space.wrap('__doc__'), space.w_None) + self.w_dict = w_dict + self.w_name = w_name + if w_name is not None: + space.setitem(w_dict, space.wrap('__name__'), w_name) def getdict(self): return self.w_dict - def setdict(self, w_dict): - self.w_dict = w_dict - def descr_module__new__(space, w_subtype, __args__): module = space.allocate_instance(Module, w_subtype) module.__init__(space, space.wrap('?')) @@ -32,37 +28,8 @@ def descr_module__init__(self, w_name, w_doc=None): space = self.space self.w_name = w_name - space.setitem(self.w_dict, space.wrap('__name__'), w_name) - if w_doc is not None: - space.setitem(self.w_dict, space.wrap('__doc__'), w_doc) - - def descr_module__getattr__(self, w_attr): - space = self.space - attr = space.str_w(w_attr) - # ______ for the 'sys' module only _____ XXX generalize - if self is space.sys: - if attr == 'exc_type': - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.w_None - else: - return operror.w_type - if attr == 'exc_value': - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.w_None - else: - return operror.w_value - if attr == 'exc_traceback': - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.w_None - else: - return space.wrap(operror.application_traceback) - # produce a nice error message that shows the name of the module - try: - name = space.str_w(self.w_name) - except OperationError: - name = '?' - msg = "'%s' module has no attribute '%s'" % (name, attr) - raise OperationError(space.w_AttributeError, space.wrap(msg)) + if w_doc is None: + w_doc = space.w_None + w_dict = self.getdict() + space.setitem(w_dict, space.wrap('__name__'), w_name) + space.setitem(w_dict, space.wrap('__doc__'), w_doc) Modified: pypy/dist/pypy/interpreter/py.py ============================================================================== --- pypy/dist/pypy/interpreter/py.py (original) +++ pypy/dist/pypy/interpreter/py.py Sat Feb 19 15:30:45 2005 @@ -5,10 +5,14 @@ except ImportError: pass +from pypy.tool.getpy import py +#py.magic.invoke(compile=1) + from pypy.tool import option from pypy.tool.optik import make_option from pypy.interpreter import main, interactive, error import os, sys +import time class Options(option.Options): verbose = os.getenv('PYPY_TB') @@ -42,11 +46,13 @@ return options def main_(argv=None): + starttime = time.time() from pypy.tool import tb_server args = option.process_options(get_main_options(), Options, argv[1:]) space = None try: space = option.objspace() + space._starttime = starttime assert 'pypy.tool.udir' not in sys.modules, ( "running py.py should not import pypy.tool.udir, which is\n" "only for testing or translating purposes.") @@ -56,14 +62,14 @@ if Options.command: args = ['-c'] + Options.command[1:] for arg in args: - space.call_method(space.sys.w_argv, 'append', space.wrap(arg)) + space.call_method(space.sys.get('argv'), 'append', space.wrap(arg)) try: if Options.command: main.run_string(Options.command[0], '', space) elif args: main.run_file(args[0], space) else: - space.call_method(space.sys.w_argv, 'append', space.wrap('')) + space.call_method(space.sys.get('argv'), 'append', space.wrap('')) go_interactive = 1 banner = None except error.OperationError, operationerr: Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Sat Feb 19 15:30:45 2005 @@ -6,7 +6,8 @@ import dis from pypy.interpreter import eval -from pypy.interpreter.gateway import NoneNotWrapped +from pypy.interpreter.gateway import NoneNotWrapped +from pypy.interpreter.baseobjspace import ObjSpace, W_Root from pypy.tool.cache import Cache # helper @@ -55,7 +56,7 @@ self.co_flags = 0 # CO_..., see above self.co_code = None # string: instruction opcodes self.co_consts_w = [] # list of constants used (wrapped!) - self.co_names_w = [] # list of wrapped strs: names (for attrs..) + self.co_names = [] # list of strings: names (for attrs..) self.co_varnames = () # tuple of strings: local variable names self.co_freevars = () # tuple of strings: free variable names self.co_cellvars = () # tuple of strings: cell variable names @@ -88,7 +89,7 @@ self.co_code = x #self.co_consts = x = code.co_names; assert isinstance(x, tuple) - self.co_names_w = [ self.space.wrap(i) for i in x ] + self.co_names = list(x) x = code.co_varnames; assert isinstance(x, tuple) self.co_varnames = x x = code.co_freevars; assert isinstance(x, tuple) @@ -157,10 +158,10 @@ def fget_co_names(space, w_self): self = space.interpclass_w(w_self) - return space.newtuple(self.co_names_w) + return space.newtuple([space.wrap(name) for name in self.co_names]) - def descr_code__eq__(space, w_self, w_other): - self = space.interpclass_w(w_self) + def descr_code__eq__(self, w_other): + space = self.space other = space.interpclass_w(w_other) if not isinstance(other, PyCode): return space.w_False @@ -170,7 +171,11 @@ self.co_flags == other.co_flags and self.co_firstlineno == other.co_firstlineno and self.co_code == other.co_code and - len(self.co_consts_w) == len(other.co_consts_w)) + len(self.co_consts_w) == len(other.co_consts_w) and + self.co_names == other.co_names and + self.co_varnames == other.co_varnames and + self.co_freevars == other.co_freevars and + self.co_cellvars == other.co_cellvars) if not areEqual: return space.w_False @@ -178,45 +183,40 @@ if not space.eq_w(self.co_consts_w[i], other.co_consts_w[i]): return space.w_False - if len(self.co_names_w) != len(other.co_names_w): - return space.w_False - - for i in range(len(self.co_names_w)): - if not space.eq_w(self.co_names_w[i], other.co_names_w[i]): - return space.w_False - if (self.co_varnames == other.co_varnames and - self.co_freevars == other.co_freevars and - self.co_cellvars == other.co_cellvars): - return space.w_True - return space.w_True - + + unwrap_spec = [ObjSpace, W_Root, + int, int, int, int, + str, W_Root, W_Root, + W_Root, str, str, int, + str, W_Root, + W_Root] def descr_code__new__(space, w_subtype, - w_argcount, w_nlocals, w_stacksize, w_flags, - w_codestring, w_constants, w_names, - w_varnames, w_filename, w_name, w_firstlineno, - w_lnotab, w_freevars=NoneNotWrapped, + argcount, nlocals, stacksize, flags, + codestring, w_constants, w_names, + w_varnames, filename, name, firstlineno, + lnotab, w_freevars=NoneNotWrapped, w_cellvars=NoneNotWrapped): code = space.allocate_instance(PyCode, w_subtype) code.__init__(space) - # XXX typechecking everywhere! - code.co_argcount = space.int_w(w_argcount) - code.co_nlocals = space.int_w(w_nlocals) - code.co_stacksize = space.int_w(w_stacksize) - code.co_flags = space.int_w(w_flags) - code.co_code = space.str_w(w_codestring) + code.co_argcount = argcount + code.co_nlocals = nlocals + code.co_stacksize = stacksize + code.co_flags = flags + code.co_code = codestring code.co_consts_w = space.unpacktuple(w_constants) - code.co_names_w = space.unpacktuple(w_names) + code.co_names = unpack_str_tuple(space, w_names) code.co_varnames = unpack_str_tuple(space, w_varnames) - code.co_filename = space.str_w(w_filename) - code.co_name = space.str_w(w_name) - code.co_firstlineno= space.int_w(w_firstlineno) - code.co_lnotab = space.str_w(w_lnotab) + code.co_filename = filename + code.co_name = name + code.co_firstlineno= firstlineno + code.co_lnotab = lnotab if w_freevars is not None: code.co_freevars = unpack_str_tuple(space, w_freevars) if w_cellvars is not None: code.co_cellvars = unpack_str_tuple(space, w_cellvars) return space.wrap(code) + descr_code__new__.unwrap_spec = unwrap_spec def _really_enhanceclass(key, stuff): Modified: pypy/dist/pypy/interpreter/pyframe.py ============================================================================== --- pypy/dist/pypy/interpreter/pyframe.py (original) +++ pypy/dist/pypy/interpreter/pyframe.py Sat Feb 19 15:30:45 2005 @@ -23,7 +23,7 @@ * 'code' is the PyCode object this frame runs * 'w_locals' is the locals dictionary to use * 'w_globals' is the attached globals dictionary - * 'w_builtins' is the attached built-ins dictionary + * 'builtin' is the attached built-in module * 'valuestack', 'blockstack', 'next_instr' control the interpretation """ @@ -33,7 +33,7 @@ self.blockstack = Stack() self.last_exception = None self.next_instr = 0 - self.w_builtins = self.space.w_builtins + self.builtin = space.builtin.pick_builtin(w_globals) # regular functions always have CO_OPTIMIZED and CO_NEWLOCALS. # class bodies only have CO_NEWLOCALS. if code.dictscope_needed(): @@ -74,14 +74,17 @@ # catch asynchronous exceptions and turn them # into OperationErrors except KeyboardInterrupt: - raise OperationError(self.space.w_KeyboardInterrupt, - self.space.w_None) + import sys; tb = sys.exc_info()[2] + raise OperationError, (self.space.w_KeyboardInterrupt, + self.space.w_None), tb except MemoryError: - raise OperationError(self.space.w_MemoryError, - self.space.w_None) + import sys; tb = sys.exc_info()[2] + raise OperationError, (self.space.w_MemoryError, + self.space.w_None), tb except RuntimeError, e: - raise OperationError(self.space.w_RuntimeError, - self.space.wrap("internal error: " + str(e))) + import sys; tb = sys.exc_info()[2] + raise OperationError, (self.space.w_RuntimeError, + self.space.wrap("internal error: " + str(e))), tb except OperationError, e: pytraceback.record_application_traceback( @@ -130,6 +133,10 @@ "Returns the line number of the next instruction to execute." return pytraceback.offset2lineno(self.code, self.next_instr) + def fget_f_builtins(space, w_self): + self = space.interpclass_w(w_self) + return self.builtin.getdict() + ### Frame Blocks ### @@ -216,44 +223,46 @@ return True # stop unrolling return False -def app_normalize_exception(etype, value, tb): - """Normalize an (exc_type, exc_value) pair: - exc_value will be an exception instance and exc_type its class. - """ - # mistakes here usually show up as infinite recursion, which is fun. - while isinstance(etype, tuple): - etype = etype[0] - if isinstance(etype, (type, _classobj)): - if not isinstance(value, etype): - if value is None: - # raise Type: we assume we have to instantiate Type - value = etype() - elif isinstance(value, tuple): - # raise Type, Tuple: assume Tuple contains the constructor args - value = etype(*value) - else: - # raise Type, X: assume X is the constructor argument - value = etype(value) - # raise Type, Instance: let etype be the exact type of value - etype = value.__class__ - elif type(etype) is str: - # XXX warn -- deprecated - if value is not None and type(value) is not str: - raise TypeError("string exceptions can only have a string value") - else: - # raise X: we assume that X is an already-built instance - if value is not None: - raise TypeError("instance exception may not have a separate value") - value = etype - etype = value.__class__ - # for the sake of language consistency we should not allow - # things like 'raise 1', but it's probably fine (i.e. - # not ambiguous) to allow them in the explicit form 'raise int, 1' - if not hasattr(value, '__dict__') and not hasattr(value, '__slots__'): - raise TypeError("raising built-in objects can be ambiguous, " - "use 'raise type, value' instead") - return etype, value, tb -normalize_exception = gateway.app2interp(app_normalize_exception) +app = gateway.applevel(''' + def normalize_exception(etype, value, tb): + """Normalize an (exc_type, exc_value) pair: + exc_value will be an exception instance and exc_type its class. + """ + # mistakes here usually show up as infinite recursion, which is fun. + while isinstance(etype, tuple): + etype = etype[0] + if isinstance(etype, (type, _classobj)): + if not isinstance(value, etype): + if value is None: + # raise Type: we assume we have to instantiate Type + value = etype() + elif isinstance(value, tuple): + # raise Type, Tuple: assume Tuple contains the constructor args + value = etype(*value) + else: + # raise Type, X: assume X is the constructor argument + value = etype(value) + # raise Type, Instance: let etype be the exact type of value + etype = value.__class__ + elif type(etype) is str: + # XXX warn -- deprecated + if value is not None and type(value) is not str: + raise TypeError("string exceptions can only have a string value") + else: + # raise X: we assume that X is an already-built instance + if value is not None: + raise TypeError("instance exception may not have a separate value") + value = etype + etype = value.__class__ + # for the sake of language consistency we should not allow + # things like 'raise 1', but it is probably fine (i.e. + # not ambiguous) to allow them in the explicit form 'raise int, 1' + if not hasattr(value, '__dict__') and not hasattr(value, '__slots__'): + raise TypeError("raising built-in objects can be ambiguous, " + "use 'raise type, value' instead") + return etype, value, tb +''') +normalize_exception = app.interphook("normalize_exception") class FinallyBlock(FrameBlock): Modified: pypy/dist/pypy/interpreter/pyopcode.py ============================================================================== --- pypy/dist/pypy/interpreter/pyopcode.py (original) +++ pypy/dist/pypy/interpreter/pyopcode.py Sat Feb 19 15:30:45 2005 @@ -71,9 +71,11 @@ def getconstant_w(self, index): return self.code.co_consts_w[index] + def getname(self, index): + return self.code.co_names[index] + def getname_w(self, index): - w_varname = self.code.co_names_w[index] - return w_varname + return self.space.wrap(self.code.co_names[index]) ################################################################ @@ -345,8 +347,8 @@ w_globals = f.valuestack.pop() w_prog = f.valuestack.pop() w_compile_flags = f.space.wrap(f.get_compile_flags()) - w_resulttuple = f.prepare_exec(w_prog, w_globals, w_locals, - w_compile_flags) + w_resulttuple = prepare_exec(f.space, f.space.wrap(f), w_prog, w_globals, w_locals, + w_compile_flags, f.space.wrap(f.builtin)) w_prog, w_globals, w_locals = f.space.unpacktuple(w_resulttuple, 3) plain = f.space.is_true(f.space.is_(w_locals, f.w_locals)) @@ -357,44 +359,6 @@ if plain: f.setdictscope(w_locals) - def app_prepare_exec(f, prog, globals, locals, compile_flags): - """Manipulate parameters to exec statement to (codeobject, dict, dict). - """ - # XXX INCOMPLETE - if (globals is None and locals is None and - isinstance(prog, tuple) and - (len(prog) == 2 or len(prog) == 3)): - globals = prog[1] - if len(prog) == 3: - locals = prog[2] - prog = prog[0] - if globals is None: - globals = f.f_globals - if locals is None: - locals = f.f_locals - if locals is None: - locals = globals - if not isinstance(globals, dict): - raise TypeError("exec: arg 2 must be a dictionary or None") - elif not globals.has_key('__builtins__'): - globals['__builtins__'] = f.f_builtins - if not isinstance(locals, dict): - raise TypeError("exec: arg 3 must be a dictionary or None") - # XXX - HACK to check for code object - co = compile('1','','eval') - if isinstance(prog, type(co)): - return (prog, globals, locals) - if not isinstance(prog, str): - ## if not (isinstance(prog, types.StringTypes) or - ## isinstance(prog, types.FileType)): - raise TypeError("exec: arg 1 must be a string, file, or code object") - ## if isinstance(prog, types.FileType): - ## co = compile(prog.read(),prog.name,'exec',comple_flags,1) - ## return (co,globals,locals) - else: # prog is a string - co = compile(prog,'','exec', compile_flags, 1) - return (co, globals, locals) - def POP_BLOCK(f): block = f.blockstack.pop() block.cleanup(f) # the block knows how to clean up the value stack @@ -417,7 +381,8 @@ w_bases = f.valuestack.pop() w_name = f.valuestack.pop() w_metaclass = find_metaclass(f.space, w_bases, - w_methodsdict, f.w_globals, f.w_builtins) + w_methodsdict, f.w_globals, + f.space.wrap(f.builtin)) w_newclass = f.space.call_function(w_metaclass, w_name, w_bases, w_methodsdict) f.valuestack.push(w_newclass) @@ -471,38 +436,19 @@ f.space.delitem(f.w_globals, w_varname) def LOAD_NAME(f, nameindex): - w_varname = f.getname_w(nameindex) - - if f.w_globals is f.w_locals: - try_list_w = [f.w_globals, f.w_builtins] - - else: - try_list_w = [f.w_locals, f.w_globals, f.w_builtins] - - w_value = None - for wrapped in try_list_w: + if f.w_locals is not f.w_globals: + w_varname = f.getname_w(nameindex) try: - w_value = f.space.getitem(wrapped, w_varname) - f.valuestack.push(w_value) - return - + w_value = f.space.getitem(f.w_locals, w_varname) except OperationError, e: if not e.match(f.space, f.space.w_KeyError): raise - message = "name '%s' is not defined" % f.space.str_w(w_varname) - w_exc_type = f.space.w_NameError - w_exc_value = f.space.wrap(message) - raise OperationError(w_exc_type, w_exc_value) - - - # XXX the implementation can be pushed back into app-space as an - # when exception handling begins to behave itself. For now, it - # was getting on my nerves -- mwh - # w_value = f.load_name(w_varname) - # f.valuestack.push(w_value) + else: + f.valuestack.push(w_value) + return + f.LOAD_GLOBAL(nameindex) # fall-back def LOAD_GLOBAL(f, nameindex): - assert f.w_globals is not None w_varname = f.getname_w(nameindex) try: w_value = f.space.getitem(f.w_globals, w_varname) @@ -511,16 +457,12 @@ if not e.match(f.space, f.space.w_KeyError): raise # we got a KeyError, now look in the built-ins - try: - w_value = f.space.getitem(f.w_builtins, w_varname) - except OperationError, e: - # catch KeyErrors again - if not e.match(f.space, f.space.w_KeyError): - raise - message = "global name '%s' is not defined" % f.space.str_w(w_varname) - w_exc_type = f.space.w_NameError - w_exc_value = f.space.wrap(message) - raise OperationError(w_exc_type, w_exc_value) + varname = f.getname(nameindex) + w_value = f.builtin.getdictvalue(f.space, varname) + if w_value is None: + message = "global name '%s' is not defined" % varname + raise OperationError(f.space.w_NameError, + f.space.wrap(message)) f.valuestack.push(w_value) def DELETE_FAST(f, varindex): @@ -601,11 +543,8 @@ w_modulename = f.getname_w(nameindex) modulename = f.space.str_w(w_modulename) w_fromlist = f.valuestack.pop() - try: - w_import = space.getitem(f.w_builtins, space.wrap("__import__")) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise + w_import = f.builtin.getdictvalue(f.space, '__import__') + if w_import is None: raise OperationError(space.w_ImportError, space.wrap("__import__ not found")) w_locals = f.w_locals @@ -774,9 +713,6 @@ cls.dispatch_table = dispatch_table - gateway.importall(locals()) # app_xxx() -> xxx() - - ### helpers written at the application-level ### # Some of these functions are expected to be generally useful if other # parts of the code needs to do the same thing as a non-trivial opcode, @@ -785,78 +721,130 @@ # There are also a couple of helpers that are methods, defined in the # class above. -def app_print_expr(x): - try: - displayhook = sys.displayhook - except AttributeError: - raise RuntimeError("lost sys.displayhook") - displayhook(x) - -def app_file_softspace(file, newflag): - try: - softspace = file.softspace - except AttributeError: - softspace = 0 - try: - file.softspace = newflag - except AttributeError: - pass - return softspace +app = gateway.applevel(r''' -def app_sys_stdout(): - try: - return sys.stdout - except AttributeError: - raise RuntimeError("lost sys.stdout") - -def app_print_item_to(x, stream): - if file_softspace(stream, False): - stream.write(" ") - stream.write(str(x)) - # add a softspace unless we just printed a string which ends in a '\t' - # or '\n' -- or more generally any whitespace character but ' ' - if isinstance(x, str) and len(x) and x[-1].isspace() and x[-1]!=' ': - return - # XXX add unicode handling - file_softspace(stream, True) - -def app_print_newline_to(stream): - stream.write("\n") - file_softspace(stream, False) - -def app_find_metaclass(bases, namespace, globals, builtins): - if '__metaclass__' in namespace: - return namespace['__metaclass__'] - elif len(bases) > 0: - base = bases[0] - if hasattr(base, '__class__'): - return base.__class__ - else: - return type(base) - elif '__metaclass__' in globals: - return globals['__metaclass__'] - elif '__metaclass__' in builtins: - return builtins['__metaclass__'] - else: - return type - -def app_import_all_from(module, into_locals): - try: - all = module.__all__ - except AttributeError: + import sys + + def sys_stdout(): + try: + return sys.stdout + except AttributeError: + raise RuntimeError("lost sys.stdout") + + def print_expr(obj): + try: + displayhook = sys.displayhook + except AttributeError: + raise RuntimeError("lost sys.displayhook") + displayhook(obj) + + def print_item_to(x, stream): + if file_softspace(stream, False): + stream.write(" ") + stream.write(str(x)) + + # add a softspace unless we just printed a string which ends in a '\t' + # or '\n' -- or more generally any whitespace character but ' ' + if isinstance(x, str) and x and x[-1].isspace() and x[-1]!=' ': + return + # XXX add unicode handling + file_softspace(stream, True) + + def print_newline_to(stream): + stream.write("\n") + file_softspace(stream, False) + + def file_softspace(file, newflag): + try: + softspace = file.softspace + except AttributeError: + softspace = 0 try: - dict = module.__dict__ + file.softspace = newflag except AttributeError: - raise ImportError("from-import-* object has no __dict__ " - "and no __all__") - all = dict.keys() - skip_leading_underscores = True - else: - skip_leading_underscores = False - for name in all: - if skip_leading_underscores and name[0]=='_': - continue - into_locals[name] = getattr(module, name) + pass + return softspace + def find_metaclass(bases, namespace, globals, builtin): + if '__metaclass__' in namespace: + return namespace['__metaclass__'] + elif len(bases) > 0: + base = bases[0] + if hasattr(base, '__class__'): + return base.__class__ + else: + return type(base) + elif '__metaclass__' in globals: + return globals['__metaclass__'] + else: + try: + return builtin.__metaclass__ + except AttributeError: + return type + + def import_all_from(module, into_locals): + try: + all = module.__all__ + except AttributeError: + try: + dict = module.__dict__ + except AttributeError: + raise ImportError("from-import-* object has no __dict__ " + "and no __all__") + all = dict.keys() + skip_leading_underscores = True + else: + skip_leading_underscores = False + for name in all: + if skip_leading_underscores and name[0]=='_': + continue + into_locals[name] = getattr(module, name) + + def prepare_exec(f, prog, globals, locals, compile_flags, builtin): + """Manipulate parameters to exec statement to (codeobject, dict, dict). + """ + # XXX INCOMPLETE + if (globals is None and locals is None and + isinstance(prog, tuple) and + (len(prog) == 2 or len(prog) == 3)): + globals = prog[1] + if len(prog) == 3: + locals = prog[2] + prog = prog[0] + if globals is None: + globals = f.f_globals + if locals is None: + locals = f.f_locals + if locals is None: + locals = globals + if not isinstance(globals, dict): + raise TypeError("exec: arg 2 must be a dictionary or None") + elif not globals.has_key('__builtins__'): + globals['__builtins__'] = builtin + if not isinstance(locals, dict): + raise TypeError("exec: arg 3 must be a dictionary or None") + # XXX - HACK to check for code object + co = compile('1','','eval') + if isinstance(prog, type(co)): + return (prog, globals, locals) + if not isinstance(prog, str): + ## if not (isinstance(prog, types.StringTypes) or + ## isinstance(prog, types.FileType)): + raise TypeError("exec: arg 1 must be a string, file, " + "or code object") + ## if isinstance(prog, types.FileType): + ## co = compile(prog.read(),prog.name,'exec',comple_flags,1) + ## return (co,globals,locals) + else: # prog is a string + co = compile(prog,'','exec', compile_flags, 1) + return (co, globals, locals) +''') -gateway.importall(globals()) # app_xxx() -> xxx() +sys_stdout = app.interphook('sys_stdout') +print_expr = app.interphook('print_expr') +print_item_to = app.interphook('print_item_to') +print_newline_to= app.interphook('print_newline_to') +file_softspace = app.interphook('file_softspace') +find_metaclass = app.interphook('find_metaclass') +import_all_from = app.interphook('import_all_from') +prepare_exec = app.interphook('prepare_exec') Deleted: /pypy/dist/pypy/interpreter/test/foomodule.py ============================================================================== --- /pypy/dist/pypy/interpreter/test/foomodule.py Sat Feb 19 15:30:45 2005 +++ (empty file) @@ -1,13 +0,0 @@ - -__interplevel__exec("w_foo = space.w_Ellipsis") -foo1 = __interplevel__eval("w_foo") # foo1 is Ellipsis -from __interplevel__ import foo # Ellipsis too - -def bar(a, b): # visible from interp-level code - return a * b - -__interplevel__execfile("foointerp.py") # defines w_foo2 and foobuilder() - -from __interplevel__ import foo2 # from w_foo2, gives "hello" -from __interplevel__ import foobuilder -foo3 = foobuilder("guido") # gives "hi, guido!" Modified: pypy/dist/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/dist/pypy/interpreter/test/test_appinterp.py Sat Feb 19 15:30:45 2005 @@ -1,5 +1,6 @@ import py +from pypy.interpreter.gateway import appdef, applevel def test_execwith_novars(space): val = space.appexec([], """ @@ -23,4 +24,104 @@ """) assert str(excinfo).find('y y') != -1 - +def test_simple_applevel(space): + app = appdef("""app(x,y): + return x + y + """) + assert app.func_name == 'app' + w_result = app(space, space.wrap(41), space.wrap(1)) + assert space.eq_w(w_result, space.wrap(42)) + +def test_applevel_with_one_default(space): + app = appdef("""app(x,y=1): + return x + y + """) + assert app.func_name == 'app' + w_result = app(space, space.wrap(41)) + assert space.eq_w(w_result, space.wrap(42)) + +def test_applevel_with_two_defaults(space): + app = appdef("""app(x=1,y=2): + return x + y + """) + w_result = app(space, space.wrap(41), space.wrap(1)) + assert space.eq_w(w_result, space.wrap(42)) + + w_result = app(space, space.wrap(15)) + assert space.eq_w(w_result, space.wrap(17)) + + w_result = app(space) + assert space.eq_w(w_result, space.wrap(3)) + + +def test_applevel_noargs(space): + app = appdef("""app(): + return 42 + """) + assert app.func_name == 'app' + w_result = app(space) + assert space.eq_w(w_result, space.wrap(42)) + +def somefunc(arg2=42): + return arg2 + +def test_app2interp_somefunc(space): + app = appdef(somefunc) + w_result = app(space) + assert space.eq_w(w_result, space.wrap(42)) + +def test_applevel_functions(space): + app = applevel(''' + def f(x, y): + return x-y + def g(x, y): + return f(y, x) + ''') + g = app.interphook('g') + w_res = g(space, space.wrap(10), space.wrap(1)) + assert space.eq_w(w_res, space.wrap(-9)) + +def test_applevel_class(space): + app = applevel(''' + class C: + clsattr = 42 + def __init__(self, x=13): + self.attr = x + ''') + C = app.interphook('C') + c = C(space, space.wrap(17)) + w_attr = space.getattr(c, space.wrap('clsattr')) + assert space.eq_w(w_attr, space.wrap(42)) + w_clsattr = space.getattr(c, space.wrap('attr')) + assert space.eq_w(w_clsattr, space.wrap(17)) + +def app_test_something_at_app_level(): + x = 2 + assert x/2 == 1 + +class AppTestMethods: + def test_some_app_test_method(self): + assert 2 == 2 + +class TestMixedModule: + def test_accesses(self): + space = self.space + import mixedmodule + w_module = mixedmodule.Module(space, space.wrap('mixedmodule')) + space.appexec([w_module], """ + (module): + assert module.value is None + assert module.__doc__ == 'mixedmodule doc' + + assert module.somefunc is module.somefunc + result = module.somefunc() + assert result == True + + assert module.someappfunc is module.someappfunc + appresult = module.someappfunc(41) + assert appresult == 42 + + assert module.__dict__ is module.__dict__ + for name in ('somefunc', 'someappfunc', '__doc__', '__name__'): + assert name in module.__dict__ + """) Modified: pypy/dist/pypy/interpreter/test/test_class.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_class.py (original) +++ pypy/dist/pypy/interpreter/test/test_class.py Sat Feb 19 15:30:45 2005 @@ -30,15 +30,14 @@ def test_metaclass_global(self): d = {} - metatest_text = """ -class M(type): - pass - -__metaclass__ = M - -class C: - pass -""" + metatest_text = """if 1: + class M(type): + pass + + __metaclass__ = M + + class C: + pass\n""" exec metatest_text in d C = d['C'] M = d['M'] Deleted: /pypy/dist/pypy/interpreter/test/test_extmodule.py ============================================================================== --- /pypy/dist/pypy/interpreter/test/test_extmodule.py Sat Feb 19 15:30:45 2005 +++ (empty file) @@ -1,25 +0,0 @@ - -import autopath -import os -from pypy.interpreter.extmodule import BuiltinModule - -class TestBuiltinModule: - def test_foomodule(self): - space = self.space - sourcefile = os.path.join(autopath.this_dir, 'foomodule.py') - m = BuiltinModule(space, 'foo', sourcefile=sourcefile) - w = space.wrap - w_m = space.wrap(m) - assert self.space.eq_w(space.getattr(w_m, w('__name__')), w('foo')) - assert self.space.eq_w(space.getattr(w_m, w('__file__')), w(sourcefile)) - # check app-level definitions - assert self.space.eq_w(m.w_foo, space.w_Ellipsis) - assert self.space.eq_w(space.getattr(w_m, w('foo1')), space.w_Ellipsis) - assert self.space.eq_w(space.getattr(w_m, w('foo')), space.w_Ellipsis) - assert self.space.eq_w(space.call_method(w_m, 'bar', w(4), w(3)), w(12)) - assert self.space.eq_w(space.getattr(w_m, w('foo2')), w('hello')) - assert self.space.eq_w(space.getattr(w_m, w('foo3')), w('hi, guido!')) - # check interp-level definitions - assert self.space.eq_w(m.w_foo2, w('hello')) - assert self.space.eq_w(m.foobuilder(w('xyzzy')), w('hi, xyzzy!')) - assert self.space.eq_w(m.fortytwo, w(42)) Modified: pypy/dist/pypy/interpreter/test/test_function.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_function.py (original) +++ pypy/dist/pypy/interpreter/test/test_function.py Sat Feb 19 15:30:45 2005 @@ -176,7 +176,7 @@ def c(self, bar): return bar code = PyCode(self.space)._from_code(c.func_code) - self.fn = Function(self.space, code) + self.fn = Function(self.space, code, self.space.newdict([])) def test_get(self): space = self.space @@ -202,7 +202,8 @@ space = self.space # Create some function for this test only def m(self): return self - func = Function(space, PyCode(self.space)._from_code(m.func_code)) + func = Function(space, PyCode(self.space)._from_code(m.func_code), + space.newdict([])) # Some shorthands obj1 = space.wrap(23) obj2 = space.wrap(42) Modified: pypy/dist/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_gateway.py (original) +++ pypy/dist/pypy/interpreter/test/test_gateway.py Sat Feb 19 15:30:45 2005 @@ -1,20 +1,28 @@ import autopath from pypy.interpreter import gateway +import py class TestBuiltinCode: def test_signature(self): def c(space, w_x, w_y, *hello_w): pass - code = gateway.BuiltinCode(c) + code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + 'starargs']) assert code.signature() == (['x', 'y'], 'hello', None) def d(self, w_boo): pass - code = gateway.BuiltinCode(d) + code = gateway.BuiltinCode(d, unwrap_spec= ['self', + gateway.W_Root], self_type=gateway.BaseWrappable) assert code.signature() == (['self', 'boo'], None, None) def e(space, w_x, w_y, __args__): pass - code = gateway.BuiltinCode(e) + code = gateway.BuiltinCode(e, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + gateway.Arguments]) assert code.signature() == (['x', 'y'], 'args', 'keywords') def test_call(self): @@ -25,7 +33,10 @@ assert u(hello_w[0]) == 0 assert u(hello_w[1]) == True return w((u(w_x) - u(w_y) + len(hello_w))) - code = gateway.BuiltinCode(c) + code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + 'starargs']) w = self.space.wrap w_dict = self.space.newdict([ (w('x'), w(123)), @@ -42,7 +53,10 @@ w = space.wrap return w((u(w_x) - u(w_y) + len(args_w)) * u(kwds_w['boo'])) - code = gateway.BuiltinCode(c) + code = gateway.BuiltinCode(c, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + gateway.Arguments]) w = self.space.wrap w_dict = self.space.newdict([ (w('x'), w(123)), @@ -55,6 +69,7 @@ class TestGateway: + def test_app2interp(self): w = self.space.wrap def app_g3(a, b): @@ -189,26 +204,14 @@ def test_importall(self): w = self.space.wrap - g = {} - exec """ -def app_g3(a, b): - return a+b -def app_g1(x): - return g3('foo', x) -""" in g + g = {'app_g3': app_g3} gateway.importall(g, temporary=True) - g1 = g['g1'] - assert self.space.eq_w(g1(self.space, w('bar')), w('foobar')) + g3 = g['g3'] + assert self.space.eq_w(g3(self.space, w('bar')), w('foobar')) - def test_exportall(self): - w = self.space.wrap - g = {} - exec """ -def g3(space, w_a, w_b): - return space.add(w_a, w_b) -def app_g1(x): - return g3('foo', x) -""" in g - gateway.exportall(g, temporary=True) - g1 = gateway.app2interp_temp(g['app_g1']) - assert self.space.eq_w(g1(self.space, w('bar')), w('foobar')) +## def test_exportall(self): +## not used any more + + +def app_g3(b): + return 'foo'+b Modified: pypy/dist/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/dist/pypy/interpreter/test/test_interpreter.py Sat Feb 19 15:30:45 2005 @@ -10,15 +10,16 @@ source = str(py.code.Source(source).strip()) + '\n' - compile = space.builtin.compile + #from pypy.module.builtin.compiling import compile + w_compile = space.builtin.get('compile') w = space.wrap - w_code = compile(w(source), '', 'exec', 0, 0) - + w_code = space.call_function(w_compile, + w(source), w(''), w('exec'), w(0), w(0)) ec = executioncontext.ExecutionContext(space) tempmodule = module.Module(space, w("__temp__")) w_glob = tempmodule.w_dict - space.setitem(w_glob, w("__builtins__"), space.w_builtins) + space.setitem(w_glob, w("__builtins__"), space.builtin) code = space.unwrap(w_code) code.exec_code(space, w_glob, w_glob) Modified: pypy/dist/pypy/interpreter/test/test_main.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_main.py (original) +++ pypy/dist/pypy/interpreter/test/test_main.py Sat Feb 19 15:30:45 2005 @@ -17,10 +17,10 @@ testresultoutput = '11\n' def checkoutput(space, expected_output,f,*args): - w_sys = space.get_builtin_module("sys") - w_oldout = space.getattr(w_sys, space.wrap("stdout")) + w_oldout = space.sys.get('stdout') capturefn = udir.join('capturefile') capturefile = capturefn.open('w') + w_sys = space.sys.getmodule('sys') space.setattr(w_sys, space.wrap("stdout"), space.wrap(capturefile)) try: f(*(args + (space,))) @@ -29,7 +29,6 @@ capturefile.close() assert capturefn.read(mode='rU') == expected_output - testfn = 'tmp_hello_world.py' class TestMain: Modified: pypy/dist/pypy/interpreter/test/test_module.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_module.py (original) +++ pypy/dist/pypy/interpreter/test/test_module.py Sat Feb 19 15:30:45 2005 @@ -37,6 +37,8 @@ delattr(m, 'x') raises(AttributeError, getattr, m, 'x') raises(AttributeError, delattr, m, 'x') + raises(TypeError, setattr, m, '__dict__', {}) + def test_docstring(self): import sys foo = type(sys)('foo') Modified: pypy/dist/pypy/interpreter/test/test_objspace.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_objspace.py (original) +++ pypy/dist/pypy/interpreter/test/test_objspace.py Sat Feb 19 15:30:45 2005 @@ -89,15 +89,14 @@ class TestModuleMinimal: def test_sys_exists(self): - w_sys = self.space.get_builtin_module('sys') - assert self.space.is_true(w_sys) + assert self.space.sys def test_import_exists(self): space = self.space - w_builtin = space.get_builtin_module('__builtin__') - assert space.is_true(w_builtin) + assert space.builtin w_name = space.wrap('__import__') - w_import = self.space.getattr(w_builtin, w_name) + w_builtin = space.sys.getmodule('__builtin__') + w_import = self.space.getattr(w_builtin, w_name) assert space.is_true(w_import) def test_sys_import(self): Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Sat Feb 19 15:30:45 2005 @@ -2,8 +2,8 @@ """ -from pypy.interpreter.gateway import interp2app -from pypy.interpreter.baseobjspace import Wrappable +from pypy.interpreter.gateway import interp2app, ObjSpace, Arguments, W_Root +from pypy.interpreter.baseobjspace import BaseWrappable, Wrappable from pypy.interpreter.error import OperationError from pypy.tool.cache import Cache import new @@ -92,63 +92,117 @@ else: return new.instance(cls) +def make_descr_typecheck_wrapper(func, extraargs=(), cls=None): + if func is None: + return None + if hasattr(func, 'im_func'): + assert not cls or cls is func.im_class + cls = func.im_class + func = func.im_func + if not cls: + #print "UNCHECKED", func.__module__ or '?', func.__name__ + return func + + miniglobals = { + func.__name__: func, + 'OperationError': OperationError + } + if isinstance(cls, str): + #print "", "eval") - elif isinstance(space.interpclass_w(w_source), PyCode): - w_codeobj = w_source - else: - raise OperationError(space.w_TypeError, - w('eval() arg 1 must be a string or code object')) - - if w_globals is None: - w_globals = globals() - w_locals = locals() - elif w_locals is None: - w_locals = w_globals - - return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals) - -def abs(w_val): - "abs(number) -> number\n\nReturn the absolute value of the argument." - return space.abs(w_val) - -def chr(w_ascii): - w_character = space.newstring([w_ascii]) - return w_character - -def len(w_obj): - return space.len(w_obj) - -def delattr(w_object, w_name): - space.delattr(w_object, w_name) - return space.w_None - -def getattr(w_object, w_name, w_defvalue=NoneNotWrapped): - if space.is_true(space.isinstance(w_name, space.w_unicode)): # xxx collect this logic somewhere - w_name = space.call_method(w_name, 'encode') - try: - return space.getattr(w_object, w_name) - except OperationError, e: - if e.match(space, space.w_AttributeError): - if w_defvalue is not None: - return w_defvalue - raise - -def hash(w_object): - return space.hash(w_object) - -def oct(w_val): - # XXX does this need to be a space operation? - return space.oct(w_val) - -def hex(w_val): - return space.hex(w_val) - -def round(w_val, w_n=0): - return space.round(w_val, w_n) - -def id(w_object): - return space.id(w_object) - -def cmp(w_x, w_y): - """return 0 when x == y, -1 when x < y and 1 when x > y """ - return space.cmp(w_x, w_y) - -def coerce(w_x, w_y): - """coerce(x, y) -> (x1, y1) - - Return a tuple consisting of the two numeric arguments converted to - a common type, using the same rules as used by arithmetic operations. - If coercion is not possible, raise TypeError.""" - return space.coerce(w_x, w_y) - - -#XXX works only for new-style classes. -#So we have to fix it, when we add support for old-style classes -def _issubtype(w_cls1, w_cls2): - return space.issubtype(w_cls1, w_cls2) - -def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped): - if w_sentinel is None: - return space.iter(w_collection_or_callable) - else: - if not space.is_true(callable(w_collection_or_callable)): - raise OperationError(space.w_TypeError, - space.wrap('iter(v, w): w must be callable')) - return _iter_generator(w_collection_or_callable, w_sentinel) - -def _seqiter(w_obj): - return space.newseqiter(w_obj) - -def ord(w_val): - return space.ord(w_val) - -def pow(w_base, w_exponent, w_modulus=None): - return space.pow(w_base, w_exponent, w_modulus) - -def repr(w_object): - return space.repr(w_object) - -def setattr(w_object, w_name, w_val): - space.setattr(w_object, w_name, w_val) - return space.w_None Deleted: /pypy/dist/pypy/module/__builtin__module.py ============================================================================== --- /pypy/dist/pypy/module/__builtin__module.py Sat Feb 19 15:30:45 2005 +++ (empty file) @@ -1,1049 +0,0 @@ -"""Built-in functions, exceptions, and other objects. - -Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. -""" - -__builtins__['None'] = __interplevel__eval('space.w_None') -__builtins__['False'] = __interplevel__eval('space.w_False') -__builtins__['True'] = __interplevel__eval('space.w_True') -__builtins__['type'] = __interplevel__eval('space.w_type') -__builtins__['__debug__'] = True - -object = __interplevel__eval('space.w_object') -# XXX these are faked: -unicode = __interplevel__eval('space.wrap(unicode)') -file = __interplevel__eval('space.wrap(file)') -open = file - -# old-style classes dummy support -__builtins__['_classobj'] = __interplevel__eval('space.w_classobj') -__builtins__['_instance'] = __interplevel__eval('space.w_instance') - - -# TODO Fix this later to show Ctrl-D on Unix -quit = exit = "Use Ctrl-Z (i.e. EOF) to exit." - -def execfile(filename, glob=None, loc=None): - if glob is None: - glob = _caller_globals() - if loc is None: - loc = _caller_locals() - elif loc is None: - loc = glob - f = file(filename) - try: - source = f.read() - finally: - f.close() - #Don't exec the source directly, as this loses the filename info - co = compile(source, filename, 'exec') - exec co in glob, loc - -def raw_input(prompt=None): - import sys - try: - sys.stdin - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdin"); - try: - sys.stdout - except AttributeError: - raise RuntimeError("[raw_]input: lost sys.stdout"); - if prompt is not None: - sys.stdout.write(prompt) - try: - flush = sys.stdout.flush - except AttributeError: - pass - else: - flush() - line = sys.stdin.readline() - if not line: # inputting an empty line gives line == '\n' - raise EOFError - if line[-1] == '\n': - return line[:-1] - return line - -def input(prompt=None): - return eval(raw_input(prompt)) - - -def sum(sequence, total=0): - # must forbid "summing" strings, per specs of built-in 'sum' - if isinstance(total, str): raise TypeError - for item in sequence: - total = total + item - return total - -def _iter_generator(callable_, sentinel): - """ This generator implements the __iter__(callable,sentinel) protocol """ - while 1: - result = callable_() - if result == sentinel: - return - yield result - - -def apply(function, args, kwds={}): - """call a function (or other callable object) and return its result""" - return function(*args, **kwds) - -def map(function, *collections): - """does 3 separate things, hence this enormous docstring. - 1. if function is None, return a list of tuples, each with one - item from each collection. If the collections have different - lengths, shorter ones are padded with None. - - 2. if function is not None, and there is only one collection, - apply function to every item in the collection and return a - list of the results. - - 3. if function is not None, and there are several collections, - repeatedly call the function with one argument from each - collection. If the collections have different lengths, - shorter ones are padded with None - """ - - if len(collections) == 0: - raise TypeError, "map() requires at least one sequence" - - if len(collections) == 1: - #it's the most common case, so make it faster - if function is None: - return list(collections[0]) - return [function(x) for x in collections[0]] - - iterators = [ iter(collection) for collection in collections ] - res = [] - while 1: - cont = False #is any collection not empty? - args = [] - for iterator in iterators: - try: - elem = iterator.next() - cont = True - except StopIteration: - elem = None - args.append(elem) - if cont: - if function is None: - res.append(tuple(args)) - else: - res.append(function(*args)) - else: - return res - -def filter(function, collection): - """construct a list of those elements of collection for which function - is True. If function is None, then return the items in the sequence - which are True.""" - str_type = None - if isinstance(collection, str): - str_type = str - elif isinstance(collection, unicode): - str_type = unicode - - if str_type is not None: - if function is None and type(collection) is str_type: - return collection - res = [] - for i in xrange(len(collection)): - c = collection[i] - if function is None or function(c): - if not isinstance(c, str_type): - raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__) - res.append(c) - return str_type().join(res) - - if function is None: - res = [item for item in collection if item] - else: - res = [item for item in collection if function(item)] - - if isinstance(collection, tuple): - return tuple(res) - else: - return res - -def zip(*collections): - """return a list of tuples, where the nth tuple contains every - nth item of each collection. If the collections have different - lengths, zip returns a list as long as the shortest collection, - ignoring the trailing items in the other collections.""" - - if len(collections) == 0: - import sys - if sys.version_info < (2,4): - raise TypeError("zip() requires at least one sequence") - return [] - res = [] - iterators = [ iter(collection) for collection in collections ] - while 1: - try: - elems = [] - for iterator in iterators: - elems.append(iterator.next()) - res.append(tuple(elems)) - except StopIteration: - return res - -def reduce(function, seq, *initialt): - """ Apply function of two arguments cumulatively to the items of - sequence, from left to right, so as to reduce the sequence to a - single value. Optionally begin with an initial value.""" - - seqiter = iter(seq) - if initialt: - initial, = initialt - else: - try: - initial = seqiter.next() - except StopIteration: - raise TypeError, "reduce() of empty sequence with no initial value" - while 1: - try: - arg = seqiter.next() - except StopIteration: - break - initial = function(initial, arg) - - return initial - -def _recursive_issubclass(cls, klass_or_tuple): - if cls is klass_or_tuple: - return True - for base in cls.__bases__: - if _recursive_issubclass(base, klass_or_tuple): - return True - return False - -def issubclass(cls, klass_or_tuple): - if _issubtype(type(klass_or_tuple), tuple): - for klass in klass_or_tuple: - if issubclass(cls, klass): - return True - return False - try: - return _issubtype(cls, klass_or_tuple) - except TypeError: - if not hasattr(cls, '__bases__'): - raise TypeError, "arg 1 must be a class or type" - if not hasattr(klass_or_tuple, '__bases__'): - raise TypeError, "arg 2 must be a class or type or a tuple thereof" - return _recursive_issubclass(cls, klass_or_tuple) - - -def isinstance(obj, klass_or_tuple): - if issubclass(type(obj), klass_or_tuple): - return True - try: - objcls = obj.__class__ - except AttributeError: - return False - else: - return objcls is not type(obj) and issubclass(objcls, klass_or_tuple) - -def range(x, y=None, step=1): - """ returns a list of integers in arithmetic position from start (defaults - to zero) to stop - 1 by step (defaults to 1). Use a negative step to - get a list in decending order.""" - - - if y is None: - start = 0 - stop = x - else: - start = x - stop = y - - if not isinstance(start, (int, long)): - raise TypeError('range() interger start argument expected, got %s' % type(start)) - if not isinstance(stop, (int, long)): - raise TypeError('range() interger stop argument expected, got %s' % type(stop)) - if not isinstance(step, (int, long)): - raise TypeError('range() interger step argument expected, got %s' % type(step)) - - if step == 0: - raise ValueError, 'range() arg 3 must not be zero' - - elif step > 0: - if stop <= start: # no work for us - return [] - howmany = (stop - start + step - 1)/step - - else: # step must be < 0, or we would have raised ValueError - if stop >= start: # no work for us - return [] - howmany = (start - stop - step - 1)/-step - - arr = [None] * howmany # this is to avoid using append. - - i = start - n = 0 - while n < howmany: - arr[n] = i - i += step - n += 1 - - return arr - -# min and max could be one function if we had operator.__gt__ and -# operator.__lt__ Perhaps later when we have operator. - -def min(*arr): - """return the smallest number in a list""" - - if not arr: - raise TypeError, 'min() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - min = iterator.next() - except StopIteration: - raise ValueError, 'min() arg is an empty sequence' - - for i in iterator: - if min > i: - min = i - return min - -def max(*arr): - """return the largest number in a list""" - - if not arr: - raise TypeError, 'max() takes at least one argument' - - if len(arr) == 1: - arr = arr[0] - - iterator = iter(arr) - try: - max = iterator.next() - except StopIteration: - raise ValueError, 'max() arg is an empty sequence' - - for i in iterator: - if max < i: - max = i - return max - -def divmod(x, y): - return x//y, x%y - -def vars(*obj): - """return a dictionary of all the attributes currently bound in obj. If - called with no argument, return the variables bound in local scope.""" - - if len(obj) == 0: - return _caller_locals() - elif len(obj) != 1: - raise TypeError, "vars() takes at most 1 argument." - else: - try: - return obj[0].__dict__ - except AttributeError: - raise TypeError, "vars() argument must have __dict__ attribute" - -def hasattr(ob, attr): - try: - getattr(ob, attr) - return True - except AttributeError: - return False - -def callable(ob): - for c in type(ob).__mro__: - if '__call__' in c.__dict__: - return True - else: - return False - -def dir(*args): - """dir([object]) -> list of strings - - Return an alphabetized list of names comprising (some of) the attributes - of the given object, and of attributes reachable from it: - - No argument: the names in the current scope. - Module object: the module attributes. - Type or class object: its attributes, and recursively the attributes of - its bases. - Otherwise: its attributes, its class's attributes, and recursively the - attributes of its class's base classes. - """ - if len(args) > 1: - raise TypeError("dir expected at most 1 arguments, got %d" - % len(args)) - if len(args) == 0: - local_names = _caller_locals().keys() # 2 stackframes away - local_names.sort() - return local_names - - import types - def _classdir(klass): - """Return a dict of the accessible attributes of class/type klass. - - This includes all attributes of klass and all of the - base classes recursively. - - The values of this dict have no meaning - only the keys have - meaning. - """ - Dict = {} - try: - Dict.update(klass.__dict__) - except AttributeError: pass - try: - # XXX - Use of .__mro__ would be suggested, if the existance - # of that attribute could be guarranted. - bases = klass.__bases__ - except AttributeError: pass - else: - try: - #Note that since we are only interested in the keys, - # the order we merge classes is unimportant - for base in bases: - Dict.update(_classdir(base)) - except TypeError: pass - return Dict - #End _classdir - - obj = args[0] - - if isinstance(obj, types.ModuleType): - try: - result = obj.__dict__.keys() - result.sort() - return result - except AttributeError: - return [] - - elif isinstance(obj, (types.TypeType, types.ClassType)): - #Don't look at __class__, as metaclass methods would be confusing. - result = _classdir(obj).keys() - result.sort() - return result - - else: #(regular item) - Dict = {} - try: - Dict.update(obj.__dict__) - except AttributeError: pass - try: - Dict.update(_classdir(obj.__class__)) - except AttributeError: pass - - ## Comment from object.c: - ## /* Merge in __members__ and __methods__ (if any). - ## XXX Would like this to go away someday; for now, it's - ## XXX needed to get at im_self etc of method objects. */ - for attr in ['__members__','__methods__']: - try: - for item in getattr(obj, attr): - if isinstance(item, types.StringTypes): - Dict[item] = None - except (AttributeError, TypeError): pass - - result = Dict.keys() - result.sort() - return result - -_stringtable = {} -def intern(s): - # XXX CPython has also non-immortal interned strings - if not isinstance(s, str): - raise TypeError("intern() argument 1 must be string.") - return _stringtable.setdefault(s,s) - -def copyright(): - print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.' - -def license(): - print \ -""" -Copyright (c) <2003-2004> - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -""" - -def help(): - print "You must be joking." - -def unichr(code): - import sys - if (code < 0 or code > sys.maxunicode): - raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1)) - return unicode('\\U%08x' %(code), 'unicode-escape') -# ______________________________________________________________________ -# -# Interpreter-level function definitions -# - -__interplevel__execfile('__builtin__interp.py') - -from __interplevel__ import abs, chr, len, ord, pow, repr -from __interplevel__ import hash, oct, hex, round, cmp, coerce -from __interplevel__ import getattr, setattr, delattr, iter, hash, id -from __interplevel__ import _issubtype, _seqiter -from __interplevel__ import compile, eval -from __interplevel__ import globals, locals, _caller_globals, _caller_locals - -# The following must be the last import from __interplevel__ because it -# overwrites the special __import__ hook with the normal one. - -from __interplevel__ import __import__ - - -# ________________________________________________________________________ -def enumerate(collection): - 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' - it = iter(collection) # raises a TypeError early - def do_enumerate(it): - index = 0 - for value in it: - yield index, value - index += 1 - return do_enumerate(it) - -class xrange(object): - def __init__(self, start, stop=None, step=1): - if not isinstance(start, (int, long, float)): - raise TypeError('an integer is required') - start = int(start) - if stop is None: - self.start = 0 - self.stop = start - else: - if not isinstance(stop, (int, long, float)): - raise TypeError('an integer is required') - stop = int(stop) - self.start = start - self.stop = stop - if not isinstance(step, (int, long, float)): - raise TypeError('an integer is required') - step = int(step) - if step == 0: - raise ValueError, 'xrange() step-argument (arg 3) must not be zero' - self.step = step - - def __len__(self): - if not hasattr(self, '_len'): - slicelength = self.stop - self.start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(self.step, 0) - if stepsign == lengthsign: - self._len = (slicelength - lengthsign) // self.step + 1 - else: - self._len = 0 - return self._len - - def __getitem__(self, index): - # xrange does NOT support slicing - if not isinstance(index, int): - raise TypeError, "sequence index must be integer" - len = self.__len__() - if index<0: - index += len - if 0 <= index < len: - return self.start + index * self.step - raise IndexError, "xrange object index out of range" - - def __iter__(self): - start, stop, step = self.start, self.stop, self.step - i = start - if step > 0: - while i < stop: - yield i - i+=step - else: - while i > stop: - yield i - i+=step - - -# Descriptor code, shamelessly stolen to Raymond Hettinger: -# http://users.rcn.com/python/download/Descriptor.htm -class property(object): - - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - self.fget = fget - self.fset = fset - self.fdel = fdel - self.__doc__ = doc or "" # XXX why: or "" ? - - def __get__(self, obj, objtype=None): - if obj is None: - return self - if self.fget is None: - raise AttributeError, "unreadable attribute" - return self.fget(obj) - - def __set__(self, obj, value): - if self.fset is None: - raise AttributeError, "can't set attribute" - self.fset(obj, value) - - def __delete__(self, obj): - if self.fdel is None: - raise AttributeError, "can't delete attribute" - self.fdel(obj) - - -# XXX there is an interp-level pypy.interpreter.function.StaticMethod -# XXX because __new__ needs to be a StaticMethod early. -class staticmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, objtype=None): - return self.f - - -class classmethod(object): - - def __init__(self, f): - self.f = f - - def __get__(self, obj, klass=None): - if klass is None: - klass = type(obj) - def newfunc(*args, **kwargs): - return self.f(klass, *args, **kwargs) - return newfunc - -if not hasattr(dict, 'fromkeys'): - def _fromkeys(cls, seq, value=None): - r = cls() - for s in seq: - r[s] = value - return r - - try: - dict.fromkeys = classmethod(_fromkeys) - except TypeError: - pass # Python2.2 with trivial object space - - del _fromkeys - - -# super is a modified version from Guido's tutorial -# http://www.python.org/2.2.3/descrintro.html -# it exposes the same special attributes as CPython's. -class super(object): - def __init__(self, typ, obj=None): - if obj is None: - objcls = None # unbound super object - elif _issubtype(type(obj), type) and _issubtype(obj, type): - objcls = obj # special case for class methods - elif _issubtype(type(obj), typ): - objcls = type(obj) # normal case - else: - objcls = getattr(obj, '__class__', type(obj)) - if not _issubtype(objcls, typ): - raise TypeError, ("super(type, obj): " - "obj must be an instance or subtype of type") - self.__thisclass__ = typ - self.__self__ = obj - self.__self_class__ = objcls - def __get__(self, obj, type=None): - ga = object.__getattribute__ - if ga(self, '__self__') is None and obj is not None: - return super(ga(self, '__thisclass__'), obj) - else: - return self - def __getattribute__(self, attr): - d = object.__getattribute__(self, '__dict__') - if attr != '__class__' and d['__self_class__'] is not None: - # we want super().__class__ to be the real class - # and we don't do anything for unbound type objects - mro = iter(d['__self_class__'].__mro__) - for cls in mro: - if cls is d['__thisclass__']: - break - # Note: mro is an iterator, so the second loop - # picks up where the first one left off! - for cls in mro: - try: - x = cls.__dict__[attr] - except KeyError: - continue - if hasattr(x, '__get__'): - x = x.__get__(d['__self__'], type(d['__self__'])) - return x - return object.__getattribute__(self, attr) # fall-back - -class complex(object): - """complex(real[, imag]) -> complex number - - Create a complex number from a real part and an optional imaginary part. - This is equivalent to (real + imag*1j) where imag defaults to 0.""" - PREC_REPR = 17 - PREC_STR = 12 - - # XXX this class is not well tested - - def __init__(self, real=0.0, imag=None): - if isinstance(real, str) and imag is not None: - msg = "complex() can't take second arg if first is a string" - raise TypeError, msg - - if isinstance(imag, str): - msg = "complex() second arg can't be a string" - raise TypeError, msg - - if isinstance(real, str): - real, imag = self._makeComplexFromString(real) - self.__dict__['real'] = real - self.__dict__['imag'] = imag - else: - if imag is None: - imag = 0. - self.__dict__['real'] = float(real) - self.__dict__['imag'] = float(imag) - - - def __setattr__(self, name, value): - if name in ('real', 'imag'): - raise AttributeError, "readonly attribute" - else: - raise AttributeError, "'complex' object has no attribute %s" % name - - def _makeComplexFromString(self, string): - import re - pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *") - m = pat.match(string) - x, y = m.groups() - if len(y) == 1 and y in '+-': - y = y + '1.0' - x, y = map(float, [x, y]) - return x, y - - - def __description(self, precision): - if self.real != 0.: - return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag) - else: - return "%.*gj"%(precision, self.imag) - - - def __repr__(self): - return self.__description(self.PREC_REPR) - - - def __str__(self): - return self.__description(self.PREC_STR) - - - def __hash__(self): - hashreal = hash(self.real) - hashimag = hash(self.imag) - - # Note: if the imaginary part is 0, hashimag is 0 now, - # so the following returns hashreal unchanged. This is - # important because numbers of different types that - # compare equal must have the same hash value, so that - # hash(x + 0*j) must equal hash(x). - - return hashreal + 1000003 * hashimag - - - def __add__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real + other.real - imag = self.imag + other.imag - return complex(real, imag) - - __radd__ = __add__ - - def __sub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real - other.real - imag = self.imag - other.imag - return complex(real, imag) - - def __rsub__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__sub__(self) - - def __mul__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - real = self.real*other.real - self.imag*other.imag - imag = self.real*other.imag + self.imag*other.real - return complex(real, imag) - - __rmul__ = __mul__ - - def __div__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - if abs(other.real) >= abs(other.imag): - # divide tops and bottom by other.real - try: - ratio = other.imag / other.real - except ZeroDivisionError: - raise ZeroDivisionError, "complex division" - denom = other.real + other.imag * ratio - real = (self.real + self.imag * ratio) / denom - imag = (self.imag - self.real * ratio) / denom - else: - # divide tops and bottom by other.imag - assert other.imag != 0.0 - ratio = other.real / other.imag - denom = other.real * ratio + other.imag - real = (self.real * ratio + self.imag) / denom - imag = (self.imag * ratio - self.real) / denom - - return complex(real, imag) - - def __rdiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__div__(self) - - def __floordiv__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return div - - def __rfloordiv__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__floordiv__(self) - - __truediv__ = __div__ - __rtruediv__ = __rdiv__ - - def __mod__(self, other): - result = self.__divmod__(other) - if result is NotImplemented: - return result - div, mod = result - return mod - - def __rmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__mod__(self) - - def __divmod__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - - import warnings, math - warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning) - - try: - div = self/other # The raw divisor value. - except ZeroDivisionError: - raise ZeroDivisionError, "complex remainder" - div = complex(math.floor(div.real), 0.0) - mod = self - div*other - return div, mod - - - def __pow__(self, other, mod=None): - if mod is not None: - raise ValueError("complex modulo") - result = self.__coerce__(other) - if result is NotImplemented: - return result - a, b = result - import math - - if b.real == 0. and b.imag == 0.: - real = 1. - imag = 0. - elif a.real == 0. and a.imag == 0.: - real = 0. - imag = 0. - else: - vabs = math.hypot(a.real,a.imag) - len = math.pow(vabs,b.real) - at = math.atan2(a.imag, a.real) - phase = at*b.real - if b.imag != 0.0: - len /= math.exp(at*b.imag) - phase += b.imag*math.log(vabs) - real = len*math.cos(phase) - imag = len*math.sin(phase) - - result = complex(real, imag) - return result - - def __rpow__(self, other, mod=None): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return other.__pow__(self, mod) - - def __neg__(self): - return complex(-self.real, -self.imag) - - - def __pos__(self): - return complex(self.real, self.imag) - - - def __abs__(self): - import math - result = math.hypot(self.real, self.imag) - return float(result) - - - def __nonzero__(self): - return self.real != 0.0 or self.imag != 0.0 - - - def __coerce__(self, other): - if isinstance(other, complex): - return self, other - if isinstance(other, (int, long, float)): - return self, complex(other) - return NotImplemented - - def conjugate(self): - return complex(self.real, -self.imag) - - def __eq__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real == other.real and self.imag == other.imag - - def __ne__(self, other): - result = self.__coerce__(other) - if result is NotImplemented: - return result - self, other = result - return self.real != other.real or self.imag != other.imag - - - # unsupported operations - - def __lt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __le__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __gt__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __ge__(self, other): - raise TypeError, "cannot compare complex numbers using <, <=, >, >=" - - - def __int__(self): - raise TypeError, "can't convert complex to int; use e.g. int(abs(z))" - - - def __long__(self): - raise TypeError, "can't convert complex to long; use e.g. long(abs(z))" - - - def __float__(self): - raise TypeError, "can't convert complex to float; use e.g. float(abs(z))" - - -# ________________________________________________________________________ - -class buffer(object): - def __init__(self, object, offset=None, size=None): - raise NotImplementedError, "XXX nobody needs this anyway" - -def sorted(lst, cmp=None, key=None, reverse=None): - "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list" - sorted_lst = list(lst) - sorted_lst.sort(cmp, key, reverse) - return sorted_lst - -def reversed(iterable): - """reversed(sequence) -> reverse iterator over values of the sequence - - Return a reverse iterator - """ - if hasattr(iterable, '__reversed__'): - return iterable.__reversed__() - seq = list(iterable) - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(seq) - -def reload(module): - import imp, sys, errno - - if type(module) not in (type(imp), type(errno)): - raise TypeError("reload() argument must be module") - - name = module.__name__ - if module is not sys.modules[name]: - raise ImportError("reload(): module %.200s not in sys.modules" % name) - - namepath = name.split('.') - subname = namepath[-1] - parent_name = '.'.join(namepath[:-1]) - parent = None - path = None - if parent_name: - try: - parent = sys.modules[parent_name] - except KeyError: - raise ImportError("reload(): parent %.200s not in sys.modules" % - parent_name) - path = parent.__path__ - - f, filename, description = imp.find_module(subname, path) - try: - new_module = imp.load_module(name, f, filename, description) - finally: - sys.modules[name] = module - if f is not None: - f.close() - - return new_module - -#from _file import file -#open = file - -#default __metaclass__ -# XXX can use _classobj when we have a working one integrated -__metaclass__ = type Deleted: /pypy/dist/pypy/module/sysinterp.py ============================================================================== --- /pypy/dist/pypy/module/sysinterp.py Sat Feb 19 15:30:45 2005 +++ (empty file) @@ -1,202 +0,0 @@ -""" -Implementation of interpreter-level 'sys' routines. -""" -#from pypy.interpreter.module import Module -from pypy.interpreter.error import OperationError - -import sys as cpy_sys - -def hack_cpython_module(modname): - "NOT_RPYTHON. Steal a module from CPython." - cpy_module = __import__(modname, globals(), locals(), None) - return cpy_module -## # to build the dictionary of the module, we get all the objects -## # accessible as 'self.xxx'. Methods are bound. -## contents = [] -## for name in cpy_module.__dict__: -## # ignore names in '_xyz' -## if not name.startswith('_') or name.endswith('_'): -## value = cpy_module.__dict__[name] -## contents.append((space.wrap(name), space.wrap(value))) -## w_contents = space.newdict(contents) -## return Module(space, space.wrap(modname), w_contents) - -# ____________________________________________________________ -# -# List of built-in modules. -# It should contain the name of all the files 'module/*module.py'. -builtin_module_names = ['__builtin__', 'sys', 'exceptions' - ] - -# Create the builtin_modules dictionary, mapping names to Module instances -builtin_modules = {} -for fn in builtin_module_names: - builtin_modules[fn] = None - -# The following built-in modules are not written in PyPy, so we -# steal them from Python. -for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos', - 'math', '_codecs', 'array', - '_random', '_sre', 'time', '_socket', 'errno', - 'marshal', 'binascii', 'parser']: - if fn not in builtin_modules: - try: - builtin_modules[fn] = hack_cpython_module(fn) - except ImportError: - pass - else: - builtin_module_names.append(fn) - -# ____________________________________________________________ -# -# Common data structures -w_modules = space.newdict([]) -w_warnoptions = space.newlist([]) -w_argv = space.newlist([]) -builtin_module_names.sort() -w_builtin_module_names = space.newtuple([space.wrap(fn) - for fn in builtin_module_names]) - -# Initialize the default path -import os -from pypy.interpreter import autopath -srcdir = os.path.dirname(autopath.pypydir) -python_std_lib = os.path.normpath( - os.path.join(autopath.pypydir, os.pardir,'lib-python-2.3.4')) -pypy_override_lib = os.path.join(autopath.pypydir, 'lib') -assert os.path.exists(python_std_lib) -del os, autopath # XXX for the translator. Something is very wrong around here. - -w_initialpath = space.newlist([space.wrap(''), - space.wrap(pypy_override_lib), - space.wrap(python_std_lib), - ] + - [space.wrap(p) for p in cpy_sys.path if p!= srcdir]) - -# XXX - Replace with appropriate PyPy version numbering -w_platform = space.wrap(cpy_sys.platform) -w_maxint = space.wrap(cpy_sys.maxint) -w_byteorder = space.wrap(cpy_sys.byteorder) -w_exec_prefix = space.wrap(cpy_sys.exec_prefix) -w_prefix = space.wrap(cpy_sys.prefix) -w_maxunicode = space.wrap(cpy_sys.maxunicode) -w_stdin = space.wrap(cpy_sys.stdin) -w_stdout = space.wrap(cpy_sys.stdout) -w_stderr = space.wrap(cpy_sys.stderr) - -w_pypy_objspaceclass = space.wrap(space.__class__.__name__) - -# ____________________________________________________________ - -def setmodule(w_module): - """ put a module into the modules dict """ - w_name = space.getattr(w_module, space.wrap('__name__')) - space.setitem(w_modules, w_name, w_module) - -def setbuiltinmodule(w_module, name): - """ put a module into the modules builtin_modules dicts """ - if builtin_modules[name] is None: - builtin_modules[name] = space.unwrap(w_module) - else: - assert builtin_modules[name] is space.unwrap(w_module), ( - "trying to change the builtin-in module %r" % (name,)) - space.setitem(w_modules, space.wrap(name), w_module) - -##def displayhook(w_x): -## w = space.wrap -## if not space.is_true(space.is_(w_x, space.w_None)): -## w_stdout = space.getattr(space.w_sys, space.wrap('stdout')) -## try: -## w_repr = space.repr(w_x) -## except OperationError: -## w_repr = space.wrap("! __repr__ raised an exception") -## w_repr = space.add(w_repr, space.wrap("\n")) -## space.call_method(w_stdout, 'write', -## space.setitem(space.w_builtins, w('_'), w_x) - -def _getframe(w_depth=0): - depth = space.int_w(w_depth) - try: - f = space.getexecutioncontext().framestack.top(depth) - except IndexError: - raise OperationError(space.w_ValueError, - space.wrap("call stack is not deep enough")) - except ValueError: - raise OperationError(space.w_ValueError, - space.wrap("frame index must not be negative")) - return space.wrap(f) - -# directly from the C code in ceval.c, might be moved somewhere else. - -def setrecursionlimit(w_new_limit): - """setrecursionlimit(n) - -Set the maximum depth of the Python interpreter stack to n. This -limit prevents infinite recursion from causing an overflow of the C -stack and crashing Python. The highest possible limit is platform -dependent.""" - new_limit = space.int_w(w_new_limit) - if new_limit <= 0: - raise OperationError(space.w_ValueError, - space.wrap("recursion limit must be positive")) - # global recursion_limit - # we need to do it without writing globals. - space.recursion_limit = new_limit - -def getrecursionlimit(): - """getrecursionlimit() - -Return the current value of the recursion limit, the maximum depth -of the Python interpreter stack. This limit prevents infinite -recursion from causing an overflow of the C stack and crashing Python.""" - - return space.newint(space.recursion_limit) - -checkinterval = 100 - -def setcheckinterval(w_interval): - """setcheckinterval(n) - -Tell the Python interpreter to check for asynchronous events every -n instructions. This also affects how often thread switches occur.""" - - space.sys.checkinterval = space.int_w(w_interval) - -def getcheckinterval(): - """getcheckinterval() -> current check interval; see setcheckinterval().""" - return space.newint(checkinterval) - - -def exc_info(): - operror = space.getexecutioncontext().sys_exc_info() - if operror is None: - return space.newtuple([space.w_None,space.w_None,space.w_None]) - else: - return space.newtuple([operror.w_type,operror.w_value, - space.wrap(operror.application_traceback)]) - -def exc_clear(): - operror = space.getexecutioncontext().sys_exc_info() - if operror is not None: - operror.clear(space) - -def pypy_getudir(): - """NOT_RPYTHON""" - from pypy.tool.udir import udir - return space.wrap(str(udir)) - -def getdefaultencoding(): - """getdefaultencoding() -> return the default encoding used for UNICODE""" - return space.wrap(cpy_sys.getdefaultencoding()) - -def getrefcount(w_obj): - """getrefcount(object) -> integer - -Return the reference count of object. The count returned is generally -one higher than you might expect, because it includes the (temporary) -reference as an argument to getrefcount(). -""" - # From the results i get when using this i need to apply a fudge - # value of 6 to get results comparable to cpythons. /Arre - return space.wrap(cpy_sys.getrefcount(w_obj) - 6) - Deleted: /pypy/dist/pypy/module/sysmodule.py ============================================================================== --- /pypy/dist/pypy/module/sysmodule.py Sat Feb 19 15:30:45 2005 +++ (empty file) @@ -1,70 +0,0 @@ -""" -The 'sys' module. -""" - -__interplevel__execfile('sysinterp.py') - -# Common data structures -from __interplevel__ import initialpath as path -from __interplevel__ import modules, argv -from __interplevel__ import warnoptions, builtin_module_names -from __interplevel__ import maxunicode - -# Objects from interpreter-level -from __interplevel__ import stdin, stdout, stderr, maxint -from __interplevel__ import platform, byteorder -from __interplevel__ import pypy_objspaceclass -from __interplevel__ import exec_prefix, prefix - -# Functions from interpreter-level -from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir -from __interplevel__ import getrecursionlimit, setrecursionlimit -from __interplevel__ import getcheckinterval, setcheckinterval -from __interplevel__ import getdefaultencoding, getrefcount - -# Dummy -executable = 'py.py' -api_version = 0 -copyright = '' -version = '2.3a0 (pypy build)' -version_info = (2, 3, 0, 'alpha', 0) -hexversion = 0x020300a0 -ps1 = '>>>> ' -ps2 = '.... ' - - -# XXX not called by the core yet -def excepthook(exctype, value, traceback): - from traceback import print_exception - print_exception(exctype, value, traceback) - -__excepthook__ = excepthook # this is exactly like in CPython - -def exit(exitcode=0): - # note that we cannot use SystemExit(exitcode) here. - # The comma version leads to an extra de-tupelizing - # in normalize_exception, which is exactlylike CPython. - raise SystemExit, exitcode - -def displayhook(obj): - if obj is not None: - __builtins__['_'] = obj - # NB. this is slightly more complicated in CPython, - # see e.g. the difference with >>> print 5,; 8 - print `obj` - -__displayhook__ = displayhook # this is exactly like in CPython - -def getfilesystemencoding(): - """getfilesystemencoding() -> string - -Return the encoding used to convert Unicode filenames in -operating system filenames.""" - - if platform == "win32": - encoding = "mbcs" - elif platform == "darwin": - encoding = "utf-8" - else: - encoding = None - return encoding Modified: pypy/dist/pypy/module/test/test_builtin.py ============================================================================== --- pypy/dist/pypy/module/test/test_builtin.py (original) +++ pypy/dist/pypy/module/test/test_builtin.py Sat Feb 19 15:30:45 2005 @@ -381,10 +381,7 @@ space = self.space def get_builtin(self, name): - w = self.space.wrap - w_builtins = self.space.w_builtins - w_obj = self.space.getitem(w_builtins, w(name)) - return w_obj + return self.space.builtin.get(name) def test_execfile(self): from pypy.tool.udir import udir Modified: pypy/dist/pypy/module/test/test_import.py ============================================================================== --- pypy/dist/pypy/module/test/test_import.py (original) +++ pypy/dist/pypy/module/test/test_import.py Sat Feb 19 15:30:45 2005 @@ -2,21 +2,23 @@ from pypy.interpreter import gateway import os - -def _setup(dn=os.path.abspath(os.path.join(os.path.dirname(__file__), 'impsubdir'))): - import sys - sys.path.append(dn) - return sys.modules.copy() - -_setup = gateway.app2interp_temp(_setup,'setup') - -def _teardown(saved_modules): - import sys - sys.path.pop() - sys.modules.clear() - sys.modules.update(saved_modules) - -_teardown = gateway.app2interp_temp(_teardown,'teardown') +def _setup(space): + dn=os.path.abspath(os.path.join(os.path.dirname(__file__), 'impsubdir')) + return space.appexec([space.wrap(dn)], """ + (dn): + import sys + sys.path.append(dn) + return sys.modules.copy() + """) + +def _teardown(space, w_saved_modules): + space.appexec([w_saved_modules], """ + (saved_modules): + import sys + sys.path.pop() + sys.modules.clear() + sys.modules.update(saved_modules) + """) class AppTestImport: Modified: pypy/dist/pypy/module/test/test_sysmodule.py ============================================================================== --- pypy/dist/pypy/module/test/test_sysmodule.py (original) +++ pypy/dist/pypy/module/test/test_sysmodule.py Sat Feb 19 15:30:45 2005 @@ -9,12 +9,8 @@ b.cStringIO = cStringIO b.sys = sys -class TestSysTests: - def setup_method(self,method): - self.sys_w = self.space.get_builtin_module("sys") - def test_stdout_exists(self): - s = self.space - assert s.is_true(s.getattr(self.sys_w, s.wrap("stdout"))) +def test_stdout_exists(space): + assert space.sys.get('stdout') class AppTestAppSysTests: def test_path_exists(self): @@ -119,9 +115,9 @@ dh(None) assert out.getvalue() == "" assert not hasattr(__builtin__, "_") - dh(42) - assert out.getvalue() == "42\n" - assert __builtin__._ == 42 + dh("hello") + assert out.getvalue() == "'hello'\n" + assert __builtin__._ == "hello" del sys.stdout raises(RuntimeError, dh, 42) Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Sat Feb 19 15:30:45 2005 @@ -5,6 +5,11 @@ from pypy.interpreter.gateway import BuiltinCode from pypy.interpreter.argument import Arguments +def raiseattrerror(space, w_obj, name): + w_type = space.type(w_obj) + msg = "'%s' object has no attribute '%s'" %(w_type.name, name) + raise OperationError(space.w_AttributeError, space.wrap(msg)) + class Object: def descr__getattribute__(space, w_obj, w_name): name = space.str_w(w_name) @@ -12,16 +17,12 @@ if w_descr is not None: if space.is_data_descr(w_descr): return space.get(w_descr, w_obj) - w_dict = space.getdict(w_obj) - if w_dict is not None: - try: - return space.getitem(w_dict, w_name) - except OperationError, e: - if not e.match(space, space.w_KeyError): - raise + w_value = space.getdictvalue(w_obj, name) + if w_value is not None: + return w_value if w_descr is not None: return space.get(w_descr, w_obj) - raise OperationError(space.w_AttributeError, w_name) + raiseattrerror(space, w_obj, name) def descr__setattr__(space, w_obj, w_name, w_value): name = space.str_w(w_name) @@ -32,7 +33,7 @@ w_dict = space.getdict(w_obj) if w_dict is not None: return space.setitem(w_dict, w_name, w_value) - raise OperationError(space.w_AttributeError, w_name) + raiseattrerror(space, w_obj, name) def descr__delattr__(space, w_obj, w_name): name = space.str_w(w_name) @@ -47,7 +48,7 @@ except OperationError, ex: if not ex.match(space, space.w_KeyError): raise - raise OperationError(space.w_AttributeError, w_name) + raiseattrerror(space, w_obj, name) def descr__init__(space, w_obj, __args__): pass # XXX some strange checking maybe @@ -57,6 +58,9 @@ def getdict(space, w_obj): return w_obj.getdict() + def getdictvalue(space, w_obj, attr): + return w_obj.getdictvalue(space, attr) + def is_data_descr(space, w_obj): return space.lookup(w_obj, '__set__') is not None @@ -566,24 +570,25 @@ l = ["space.is_true(space.isinstance(w_result, %s))" % x for x in checkerspec] checker = " or ".join(l) - exec """ -def %(targetname)s(space, w_obj): - w_impl = space.lookup(w_obj, %(specialname)r) - if w_impl is None: - raise OperationError(space.w_TypeError, - space.wrap("operand does not support unary %(targetname)s")) - w_result = space.get_and_call_function(w_impl, w_obj) + source = """if 1: + def %(targetname)s(space, w_obj): + w_impl = space.lookup(w_obj, %(specialname)r) + if w_impl is None: + raise OperationError(space.w_TypeError, + space.wrap("operand does not support unary %(targetname)s")) + w_result = space.get_and_call_function(w_impl, w_obj) - if %(checker)s: - return w_result - typename = space.str_w(space.getattr(space.type(w_result), - space.wrap('__name__'))) - msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) - raise OperationError(space.w_TypeError, space.wrap(msg)) -assert not hasattr(DescrOperation, %(targetname)r) -DescrOperation.%(targetname)s = %(targetname)s -del %(targetname)s -""" % locals() + if %(checker)s: + return w_result + typename = space.str_w(space.getattr(space.type(w_result), + space.wrap('__name__'))) + msg = '%(specialname)s returned non-%(targetname)s (type %%s)' %% (typename,) + raise OperationError(space.w_TypeError, space.wrap(msg)) + assert not hasattr(DescrOperation, %(targetname)r) + DescrOperation.%(targetname)s = %(targetname)s + del %(targetname)s + \n""" % locals() + exec compile(source, '', 'exec') # add default operation implementations for all still missing ops Modified: pypy/dist/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/dist/pypy/objspace/flow/flowcontext.py (original) +++ pypy/dist/pypy/objspace/flow/flowcontext.py Sat Feb 19 15:30:45 2005 @@ -83,8 +83,11 @@ name=None): ExecutionContext.__init__(self, space) self.code = code + self.w_globals = w_globals = space.wrap(globals) + self.crnt_offset = -1 + self.crnt_frame = None if closure is None: self.closure = None else: @@ -113,6 +116,7 @@ def bytecode_trace(self, frame): if not isinstance(self.crnt_ops, list): return + assert frame is self.crnt_frame, "seeing an unexpected frame!" next_instr = frame.next_instr self.crnt_offset = next_instr # save offset for opcode varnames = frame.code.getvarnames() @@ -213,7 +217,11 @@ except ExitFrame: continue # restarting a dead SpamBlock try: - w_result = frame.resume() + self.crnt_frame = frame + try: + w_result = frame.resume() + finally: + self.crnt_frame = None except OperationThatShouldNotBePropagatedError, e: raise Exception( 'found an operation that always raises %s: %s' % ( Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Sat Feb 19 15:30:45 2005 @@ -2,6 +2,7 @@ import sys, operator, types from pypy.interpreter.baseobjspace import ObjSpace, BaseWrappable from pypy.interpreter.pycode import PyCode +from pypy.interpreter.module import Module from pypy.interpreter.error import OperationError from pypy.objspace.flow.model import * from pypy.objspace.flow import flowcontext @@ -35,7 +36,12 @@ def initialize(self): import __builtin__ self.concrete_mode = 0 - self.w_builtins = Constant(__builtin__.__dict__) + self.builtin = Module(self, Constant('__builtin__'), Constant(__builtin__.__dict__)) + def pick_builtin(w_globals): + return self.builtin + self.builtin.pick_builtin = pick_builtin + self.sys = Module(self, Constant('sys'), Constant(sys.__dict__)) + self.sys.recursionlimit = 100 self.w_None = Constant(None) self.w_False = Constant(False) self.w_True = Constant(True) Modified: pypy/dist/pypy/objspace/flow/specialcase.py ============================================================================== --- pypy/dist/pypy/objspace/flow/specialcase.py (original) +++ pypy/dist/pypy/objspace/flow/specialcase.py Sat Feb 19 15:30:45 2005 @@ -82,6 +82,7 @@ opname = fn.__name__.replace('__', '') return space.do_operation(opname, *args_w) + def setup(space): fn = pyframe.normalize_exception.get_function(space) space.specialcases[fn] = sc_normalize_exception Modified: pypy/dist/pypy/objspace/std/dictproxyobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictproxyobject.py (original) +++ pypy/dist/pypy/objspace/std/dictproxyobject.py Sat Feb 19 15:30:45 2005 @@ -4,8 +4,6 @@ def descr_get_dictproxy(space, w_obj): return W_DictProxyObject(space, w_obj.getdict()) -dictproxy_descr = GetSetProperty(descr_get_dictproxy) - class W_DictProxyObject(W_Object): from pypy.objspace.std.dictproxytype import dictproxy_typedef as typedef Modified: pypy/dist/pypy/objspace/std/dictproxytype.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictproxytype.py (original) +++ pypy/dist/pypy/objspace/std/dictproxytype.py Sat Feb 19 15:30:45 2005 @@ -4,34 +4,38 @@ # ____________________________________________________________ -def proxymethod(name): +def _proxymethod(name): def fget(space, w_obj): + from pypy.objspace.std.dictproxyobject import W_DictProxyObject + if not isinstance(w_obj, W_DictProxyObject): + raise OperationError(space.w_TypeError, + space.wrap("expected dictproxy")) return space.getattr(w_obj.w_dict, space.wrap(name)) return GetSetProperty(fget) # ____________________________________________________________ dictproxy_typedef = StdTypeDef("dictproxy", - has_key = proxymethod('has_key'), - get = proxymethod('get'), - keys = proxymethod('keys'), - values = proxymethod('values'), - items = proxymethod('items'), - iterkeys = proxymethod('iterkeys'), - itervalues = proxymethod('itervalues'), - iteritems = proxymethod('iteritems'), - copy = proxymethod('copy'), - __len__ = proxymethod('__len__'), - __getitem__ = proxymethod('__getitem__'), - __contains__ = proxymethod('__contains__'), - __str__ = proxymethod('__str__'), - __iter__ = proxymethod('__iter__'), - __cmp__ = proxymethod('__cmp__'), - __lt__ = proxymethod('__lt__'), - __le__ = proxymethod('__le__'), - __eq__ = proxymethod('__eq__'), - __ne__ = proxymethod('__ne__'), - __gt__ = proxymethod('__gt__'), - __ge__ = proxymethod('__ge__'), + has_key = _proxymethod('has_key'), + get = _proxymethod('get'), + keys = _proxymethod('keys'), + values = _proxymethod('values'), + items = _proxymethod('items'), + iterkeys = _proxymethod('iterkeys'), + itervalues = _proxymethod('itervalues'), + iteritems = _proxymethod('iteritems'), + copy = _proxymethod('copy'), + __len__ = _proxymethod('__len__'), + __getitem__ = _proxymethod('__getitem__'), + __contains__ = _proxymethod('__contains__'), + __str__ = _proxymethod('__str__'), + __iter__ = _proxymethod('__iter__'), + __cmp__ = _proxymethod('__cmp__'), + __lt__ = _proxymethod('__lt__'), + __le__ = _proxymethod('__le__'), + __eq__ = _proxymethod('__eq__'), + __ne__ = _proxymethod('__ne__'), + __gt__ = _proxymethod('__gt__'), + __ge__ = _proxymethod('__ge__'), ) dictproxy_typedef.registermethods(globals()) Modified: pypy/dist/pypy/objspace/std/dicttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/dicttype.py (original) +++ pypy/dist/pypy/objspace/std/dicttype.py Sat Feb 19 15:30:45 2005 @@ -20,75 +20,69 @@ #dict_str = StdObjSpace.str # default application-level implementations for some operations +# gateway is imported in the stdtypedef module +app = gateway.applevel(''' -def app_dict_update__ANY_ANY(d, o): - for k in o.keys(): - d[k] = o[k] - -def app_dict_popitem__ANY(d): - k = d.keys() - if not k: - raise KeyError("popitem(): dictionary is empty") - k = k[0] - v = d[k] - del d[k] - return k, v - -def app_dict_get__ANY_ANY_ANY(d, k, v=None): - if d.has_key(k): - return d[k] - return v - -def app_dict_setdefault__ANY_ANY_ANY(d, k, v): - if d.has_key(k): - return d[k] - d[k] = v - return v - -def app_dict_pop__ANY_ANY(d, k, default): - if len(default) > 1: - raise TypeError, "pop expected at most 2 arguments, got %d" % ( - 1 + len(default)) - try: + def update(d, o): + for k in o.keys(): + d[k] = o[k] + + def popitem(d): + k = d.keys() + if not k: + raise KeyError("popitem(): dictionary is empty") + k = k[0] v = d[k] del d[k] - except KeyError, e: - if default: - return default[0] + return k, v + + def get(d, k, v=None): + if k in d: + return d[k] else: - raise e - return v + return v -def app_dict_iteritems__ANY(d): - return iter(d.items()) + def setdefault(d, k, v=None): + if k in d: + return d[k] + else: + d[k] = v + return v -def app_dict_iterkeys__ANY(d): - return iter(d.keys()) + def pop(d, k, defaults): # XXX defaults is actually *defaults + if len(defaults) > 1: + raise TypeError, "pop expected at most 2 arguments, got %d" % ( + 1 + len(defaults)) + try: + v = d[k] + del d[k] + except KeyError, e: + if defaults: + return defaults[0] + else: + raise e + return v + + def iteritems(d): + return iter(d.items()) + + def iterkeys(d): + return iter(d.keys()) + + def itervalues(d): + return iter(d.values()) +''') +#XXX what about dict.fromkeys()? + +dict_update__ANY_ANY = app.interphook("update") +dict_popitem__ANY = app.interphook("popitem") +dict_get__ANY_ANY_ANY = app.interphook("get") +dict_setdefault__ANY_ANY_ANY = app.interphook("setdefault") +dict_pop__ANY_ANY = app.interphook("pop") +dict_iteritems__ANY = app.interphook("iteritems") +dict_iterkeys__ANY = app.interphook("iterkeys") +dict_itervalues__ANY = app.interphook("itervalues") -def app_dict_itervalues__ANY(d): - return iter(d.values()) - -#def app_dict_fromkeys__ANY_List(d, seq, value): -# d = {} -# if value: -# value = value[0] -# else: -# value = None -# for item in seq: -# d[item] = value -# return d -#XXX implement dict.fromkeys() which must be a static method -#XXX accepting any iterable - -# This can return when multimethods have been fixed -""" -def app_dict_str__ANY(d): - items = [] - for k, v in d.iteritems(): - items.append("%r: %r" % (k, v)) - return "{%s}" % ', '.join(items) -""" -gateway.importall(globals()) register_all(vars(), globals()) # ____________________________________________________________ @@ -102,6 +96,7 @@ # ____________________________________________________________ dict_typedef = StdTypeDef("dict", - __new__ = newmethod(descr__new__), + __new__ = newmethod(descr__new__, + unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]), ) dict_typedef.registermethods(globals()) Modified: pypy/dist/pypy/objspace/std/listtype.py ============================================================================== --- pypy/dist/pypy/objspace/std/listtype.py (original) +++ pypy/dist/pypy/objspace/std/listtype.py Sat Feb 19 15:30:45 2005 @@ -14,15 +14,16 @@ list_sort = MultiMethod('sort', 4, defaults=(None, None, False), argnames=['cmp', 'key', 'reverse']) list_reversed = MultiMethod('__reversed__', 1) -def app_list_reversed__ANY(lst): - def reversed_gen(local_iterable): - len_iterable = len(local_iterable) - for index in range(len_iterable-1, -1, -1): - yield local_iterable[index] - return reversed_gen(lst) - # gateway is imported in the stdtypedef module -gateway.importall(globals()) +app = gateway.applevel(''' + + def reversed(lst): + for index in range(len(lst)-1, -1, -1): + yield lst[index] + +''') + +list_reversed__ANY = app.interphook('reversed') register_all(vars(), globals()) # ____________________________________________________________ @@ -36,6 +37,8 @@ # ____________________________________________________________ list_typedef = StdTypeDef("list", - __new__ = newmethod(descr__new__), + __new__ = newmethod(descr__new__, unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.Arguments]), ) list_typedef.registermethods(globals()) Modified: pypy/dist/pypy/objspace/std/longobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/longobject.py (original) +++ pypy/dist/pypy/objspace/std/longobject.py Sat Feb 19 15:30:45 2005 @@ -253,12 +253,12 @@ # binary ops for opname in ['add', 'sub', 'mul', 'div', 'floordiv', 'truediv', 'mod', 'divmod', 'lshift']: - exec """ + exec compile(""" def %(opname)s_ovr__Int_Int(space, w_int1, w_int2): w_long1 = delegate_Int2Long(w_int1) w_long2 = delegate_Int2Long(w_int2) return %(opname)s__Long_Long(space, w_long1, w_long2) -""" % {'opname': opname} +""" % {'opname': opname}, '', 'exec') getattr(StdObjSpace.MM, opname).register(globals()['%s_ovr__Int_Int' %opname], W_IntObject, W_IntObject, order=1) Modified: pypy/dist/pypy/objspace/std/model.py ============================================================================== --- pypy/dist/pypy/objspace/std/model.py (original) +++ pypy/dist/pypy/objspace/std/model.py Sat Feb 19 15:30:45 2005 @@ -26,6 +26,7 @@ from pypy.objspace.std.slicetype import slice_typedef from pypy.objspace.std.longtype import long_typedef from pypy.objspace.std.unicodetype import unicode_typedef + from pypy.objspace.std.dictproxytype import dictproxy_typedef self.pythontypes = [value for key, value in result.__dict__.items() if not key.startswith('_')] # don't look Modified: pypy/dist/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/dist/pypy/objspace/std/multimethod.py Sat Feb 19 15:30:45 2005 @@ -252,7 +252,7 @@ source = '\n'.join(bodylines) #print source #print "*"*60 - exec source in miniglobals + exec compile(source, '', 'exec') in miniglobals func = miniglobals[funcname] self.to_install.append((target, funcname, func, source, fallback)) return func Modified: pypy/dist/pypy/objspace/std/objecttype.py ============================================================================== --- pypy/dist/pypy/objspace/std/objecttype.py (original) +++ pypy/dist/pypy/objspace/std/objecttype.py Sat Feb 19 15:30:45 2005 @@ -3,12 +3,14 @@ from pypy.objspace.std.stdtypedef import * from pypy.objspace.std.register_all import register_all from pypy.objspace.std.objspace import StdObjSpace +from pypy.tool.uid import fixid def descr__repr__(space, w_obj): w = space.wrap classname = space.str_w(space.getattr(space.type(w_obj), w("__name__"))) id = space.int_w(space.id(w_obj))# xxx ids could be long + id = fixid(id) return w("<%s object at 0x%x>" % (classname, id)) def descr__str__(space, w_obj): @@ -45,6 +47,8 @@ __str__ = gateway.interp2app(descr__str__), __repr__ = gateway.interp2app(descr__repr__), __class__ = GetSetProperty(descr__class__), - __new__ = newmethod(descr__new__), - __init__ = gateway.interp2app(descr__init__), + __new__ = newmethod(descr__new__, + unwrap_spec = [gateway.ObjSpace,gateway.W_Root,gateway.Arguments]), + __init__ = gateway.interp2app(descr__init__, + unwrap_spec=[gateway.ObjSpace,gateway.W_Root,gateway.Arguments]), ) Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Sat Feb 19 15:30:45 2005 @@ -55,40 +55,39 @@ self.w_None = W_NoneObject(self) self.w_False = W_BoolObject(self, False) self.w_True = W_BoolObject(self, True) - from pypy.interpreter.special import NotImplemented, Ellipsis + from pypy.interpreter.special import NotImplemented, Ellipsis self.w_NotImplemented = self.wrap(NotImplemented(self)) self.w_Ellipsis = self.wrap(Ellipsis(self)) - for_builtins = {"False": self.w_False, - "True" : self.w_True, - "None" : self.w_None, - "NotImplemented": self.w_NotImplemented, - "Ellipsis": self.w_Ellipsis, - } - # types self.types_w = {} for typedef in self.model.pythontypes: w_type = self.gettypeobject(typedef) setattr(self, 'w_' + typedef.name, w_type) - for_builtins[typedef.name] = w_type + + # exceptions & builtins + mod = self.setup_exceptions() + self.make_builtins() + self.sys.setmodule(self.wrap(mod)) # dummy old-style classes types self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {}) self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {}) - # exceptions - mod = self.setup_exceptions(for_builtins) - + # fix up a problem where multimethods apparently don't + # like to define this at interp-level + self.appexec([self.w_dict], """ + (dict): + def fromkeys(cls, seq, value=None): + r = cls() + for s in seq: + r[s] = value + return r + dict.fromkeys = classmethod(fromkeys) + """) # old-style classes self.setup_old_style_classes() - # install things in the __builtin__ module - self.make_builtins(for_builtins) - - w_exceptions = self.wrap(mod) - self.sys.setbuiltinmodule(w_exceptions, 'exceptions') - def enable_old_style_classes_as_default_metaclass(self): self.setitem(self.builtin.w_dict, self.wrap('__metaclass__'), self.w_classobj) @@ -101,7 +100,7 @@ self.w_classobj = w_classobj self.w_instance = w_instance - def setup_exceptions(self, for_builtins): + def setup_exceptions(self): """NOT_RPYTHON""" ## hacking things in from pypy.module import exceptionsinterp as ex @@ -136,8 +135,6 @@ w_exc = self.getitem(w_dic, w_name) setattr(self, "w_"+excname, w_exc) - for_builtins[excname] = w_exc - # XXX refine things, clean up, create a builtin module... # but for now, we do a regular one. from pypy.interpreter.module import Module @@ -181,7 +178,7 @@ if isinstance(x, complex): # XXX is this right? YYY no, this is wrong right now (CT) # ZZZ hum, seems necessary for complex literals in co_consts (AR) - c = self.getitem(self.w_builtins, self.wrap("complex")) + c = self.builtin.get('complex') return self.call_function(c, self.wrap(x.real), self.wrap(x.imag)) Modified: pypy/dist/pypy/objspace/std/slicetype.py ============================================================================== --- pypy/dist/pypy/objspace/std/slicetype.py (original) +++ pypy/dist/pypy/objspace/std/slicetype.py Sat Feb 19 15:30:45 2005 @@ -6,64 +6,69 @@ slice_indices = MultiMethod('indices', 2) # default application-level implementations for some operations +# gateway is imported in the stdtypedef module +app = gateway.applevel(""" -def app_slice_indices3(slice, length): - # this is used internally, analogous to CPython's PySlice_GetIndicesEx - step = slice.step - if step is None: - step = 1 - elif step == 0: - raise ValueError, "slice step cannot be zero" - if step < 0: - defstart = length - 1 - defstop = -1 - else: - defstart = 0 - defstop = length - - start = slice.start - if start is None: - start = defstart - else: - if start < 0: - start += length + def indices(slice, length): + # this is used internally, analogous to CPython's PySlice_GetIndicesEx + step = slice.step + if step is None: + step = 1 + elif step == 0: + raise ValueError, "slice step cannot be zero" + if step < 0: + defstart = length - 1 + defstop = -1 + else: + defstart = 0 + defstop = length + + start = slice.start + if start is None: + start = defstart + else: if start < 0: + start += length + if start < 0: + if step < 0: + start = -1 + else: + start = 0 + elif start >= length: if step < 0: - start = -1 + start = length - 1 else: - start = 0 - elif start >= length: - if step < 0: - start = length - 1 - else: - start = length - - stop = slice.stop - if stop is None: - stop = defstop - else: - if stop < 0: - stop += length - if stop < 0: - stop = -1 - elif stop > length: - stop = length - - return start, stop, step -slice_indices__ANY_ANY = slice_indices3 = gateway.app2interp(app_slice_indices3) - -def app_slice_indices4(slice, sequencelength): - start, stop, step = slice_indices3(slice, sequencelength) - slicelength = stop - start - lengthsign = cmp(slicelength, 0) - stepsign = cmp(step, 0) - if stepsign == lengthsign: - slicelength = (slicelength - lengthsign) // step + 1 - else: - slicelength = 0 + start = length - return start, stop, step, slicelength -slice_indices4 = gateway.app2interp(app_slice_indices4) + stop = slice.stop + if stop is None: + stop = defstop + else: + if stop < 0: + stop += length + if stop < 0: + stop = -1 + elif stop > length: + stop = length + + return start, stop, step + + def slice_indices4(slice, sequencelength): + start, stop, step = indices(slice, sequencelength) + slicelength = stop - start + lengthsign = cmp(slicelength, 0) + stepsign = cmp(step, 0) + if stepsign == lengthsign: + slicelength = (slicelength - lengthsign) // step + 1 + else: + slicelength = 0 + + return start, stop, step, slicelength +""") + +slice_indices__ANY_ANY = app.interphook("indices") +slice_indices3 = slice_indices__ANY_ANY +slice_indices4 = app.interphook("slice_indices4") # utility functions def indices3(space, w_slice, length): @@ -120,10 +125,20 @@ # ____________________________________________________________ +def slicewprop(name): + def fget(space, w_obj): + from pypy.objspace.std.sliceobject import W_SliceObject + if not isinstance(w_obj, W_SliceObject): + raise OperationError(space.w_TypeError, + space.wrap("descriptor is for 'slice'")) + return getattr(w_obj, name) + return GetSetProperty(fget) + + slice_typedef = StdTypeDef("slice", __new__ = newmethod(descr__new__), - start = attrproperty_w('w_start'), - stop = attrproperty_w('w_stop'), - step = attrproperty_w('w_step'), + start = slicewprop('w_start'), + stop = slicewprop('w_stop'), + step = slicewprop('w_step'), ) slice_typedef.registermethods(globals()) Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Sat Feb 19 15:30:45 2005 @@ -4,7 +4,7 @@ from pypy.objspace.std.model import MultiMethod, FailedToImplement __all__ = ['StdTypeDef', 'newmethod', 'gateway', - 'GetSetProperty', 'Member', 'attrproperty', 'attrproperty_w', + 'GetSetProperty', 'Member', 'MultiMethod'] @@ -29,36 +29,20 @@ a = a.base return True -def attrproperty(name): - "NOT_RPYTHON: initialization-time only" - def fget(space, w_obj): - return space.wrap(getattr(w_obj, name)) - return GetSetProperty(fget) - -def attrproperty_w(name): - "NOT_RPYTHON: initialization-time only" - def fget(space, w_obj): - w_value = getattr(w_obj, name) - if w_value is None: - return space.w_None - else: - return w_value - return GetSetProperty(fget) - -def descr_get_dict(space, w_obj): +def descr_get_dict(space, w_obj): # xxx typecheck w_dict = w_obj.getdict() assert w_dict is not None, repr(w_obj) return w_dict -def descr_set_dict(space, w_obj, w_dict): +def descr_set_dict(space, w_obj, w_dict): # xxx typecheck w_obj.setdict(w_dict) std_dict_descr = GetSetProperty(descr_get_dict, descr_set_dict) -def newmethod(descr_new): +def newmethod(descr_new, unwrap_spec=None): "NOT_RPYTHON: initialization-time only." # this is turned into a static method by the constructor of W_TypeObject. - return gateway.interp2app(descr_new) + return gateway.interp2app(descr_new, unwrap_spec=unwrap_spec) # ____________________________________________________________ # @@ -73,15 +57,19 @@ from pypy.objspace.std.objecttype import object_typedef w = space.wrap - rawdict = typedef.rawdict.copy() + rawdict = typedef.rawdict + lazyloaders = {} if isinstance(typedef, StdTypeDef): # get all the sliced multimethods multimethods = slicemultimethods(space, typedef) - for name, gateway in multimethods.items(): - assert name not in rawdict, 'name clash: %s in %s_typedef' % ( - name, typedef.name) - rawdict[name] = gateway + for name, loader in multimethods.items(): + if name in rawdict: + # the name specified in the rawdict has priority + continue + assert name not in lazyloaders, ( + 'name clash: %s in %s.lazyloaders' % (name, typedef.name)) + lazyloaders[name] = loader # compute the bases if typedef is object_typedef: @@ -95,8 +83,10 @@ for descrname, descrvalue in rawdict.items(): dict_w[descrname] = w(descrvalue) - return W_TypeObject(space, typedef.name, bases_w, dict_w, - overridetypedef=typedef) + w_type = W_TypeObject(space, typedef.name, bases_w, dict_w, + overridetypedef=typedef) + w_type.lazyloaders = lazyloaders + return w_type def hack_out_multimethods(ns): "NOT_RPYTHON: initialization-time only." @@ -247,7 +237,7 @@ return w_res """ % (prefix, wrapper_sig, renaming, expr, multimethod.operatorsymbol, ', '.join(solid_arglist)) - exec code in miniglobals + exec compile(code, '', 'exec') in miniglobals return miniglobals["%s_perform_call" % prefix] def wrap_trampoline_in_gateway(func, methname, multimethod): @@ -261,29 +251,30 @@ return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) def slicemultimethod(space, multimethod, typedef, result, local=False): - from pypy.objspace.std.objecttype import object_typedef for i in range(len(multimethod.specialnames)): - # each MultimethodCode embeds a multimethod methname = multimethod.specialnames[i] if methname in result: # conflict between e.g. __lt__ and # __lt__-as-reversed-version-of-__gt__ - gw = result[methname] - if gw.bound_position < i: + loader = result[methname] + if loader.bound_position < i: continue - prefix, list_of_typeorders = sliced_typeorders( - space.model.typeorder, multimethod, typedef, i, local=local) - exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, - baked_perform_call=False) - if fallback: - continue # skip empty multimethods - trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals, - multimethod, i, - allow_NotImplemented_results=True) - gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) - gw.bound_position = i # for the check above - result[methname] = gw + def multimethod_loader(i=i, methname=methname): + prefix, list_of_typeorders = sliced_typeorders( + space.model.typeorder, multimethod, typedef, i, local=local) + exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, + baked_perform_call=False) + if fallback: + return None # skip empty multimethods + trampoline = make_perform_trampoline(prefix, exprargs, expr, miniglobals, + multimethod, i, + allow_NotImplemented_results=True) + gw = wrap_trampoline_in_gateway(trampoline, methname, multimethod) + return space.wrap(gw) + + multimethod_loader.bound_position = i # for the check above + result[methname] = multimethod_loader def slicemultimethods(space, typedef): result = {} Modified: pypy/dist/pypy/objspace/std/test/test_typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/test/test_typeobject.py (original) +++ pypy/dist/pypy/objspace/std/test/test_typeobject.py Sat Feb 19 15:30:45 2005 @@ -232,7 +232,11 @@ assert type(D1) is T1 assert type(C) is T1 assert type(G) is T1 - + + def test_descr_typecheck(self): + raises(TypeError,type.__dict__['__name__'].__get__,1) + raises(TypeError,type.__dict__['__mro__'].__get__,1) + Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Sat Feb 19 15:30:45 2005 @@ -8,6 +8,8 @@ class W_TypeObject(W_Object): from pypy.objspace.std.typetype import type_typedef as typedef + lazyloaders = None # can be overridden by specific instances + def __init__(w_self, space, name, bases_w, dict_w, overridetypedef=None): W_Object.__init__(w_self, space) @@ -106,21 +108,26 @@ if isinstance(w_new, Function): w_self.dict_w['__new__'] = StaticMethod(w_new) + def getdictvalue(w_self, space, attr): + try: + return w_self.dict_w[attr] + except KeyError: + if w_self.lazyloaders and attr in w_self.lazyloaders: + loader = w_self.lazyloaders[attr] + del w_self.lazyloaders[attr] + w_value = loader() + if w_value is not None: # None means no such attribute + w_self.dict_w[attr] = w_value + return w_value + return None + def lookup(w_self, key): # note that this doesn't call __get__ on the result at all space = w_self.space for w_class in w_self.mro_w: - try: - if isinstance(w_class, W_TypeObject): - return w_class.dict_w[key] - else: - try: - return space.getitem(space.getdict(w_class),space.wrap(key)) - except OperationError,e: - if not e.match(space, space.w_KeyError): - raise - except KeyError: - pass + w_value = space.getdictvalue(w_class, key) + if w_value is not None: + return w_value return None def lookup_where(w_self, key): @@ -128,17 +135,9 @@ # attribute was found space = w_self.space for w_class in w_self.mro_w: - try: - if isinstance(w_class, W_TypeObject): - return w_class, w_class.dict_w[key] - else: - try: - return w_class, space.getitem(space.getdict(w_class),space.wrap(key)) - except OperationError,e: - if not e.match(space, space.w_KeyError): - raise - except KeyError: - pass + w_value = space.getdictvalue(w_class, key) + if w_value is not None: + return w_class, w_value return None, None def check_user_subclass(w_self, w_subtype): @@ -158,6 +157,10 @@ def getdict(w_self): # XXX should return a + if w_self.lazyloaders: + for attr in w_self.lazyloaders.keys(): + w_self.getdictvalue(w_self.space, attr) + del w_self.lazyloaders space = w_self.space dictspec = [] for key, w_value in w_self.dict_w.items(): @@ -213,7 +216,8 @@ return space.get(w_value, space.w_None, w_type) if w_descr is not None: return space.get(w_descr,w_type) - raise OperationError(space.w_AttributeError,w_name) + msg = "type object '%s' has no attribute '%s'" %(w_type.name, name) + raise OperationError(space.w_AttributeError, space.wrap(msg)) def setattr__Type_ANY_ANY(space, w_type, w_name, w_value): name = space.str_w(w_name) @@ -224,6 +228,8 @@ w_type.dict_w[name] = w_value def delattr__Type_ANY(space, w_type, w_name): + if w_type.lazyloaders: + w_type.getdict() # force un-lazification name = space.str_w(w_name) w_descr = space.lookup(w_type, name) if w_descr is not None: @@ -237,7 +243,8 @@ # ____________________________________________________________ -def app_abstract_mro(klass): # abstract/classic mro +def app_abstract_mro(klass): + # abstract/classic mro mro = [] def fill_mro(klass): if klass not in mro: Modified: pypy/dist/pypy/objspace/std/typetype.py ============================================================================== --- pypy/dist/pypy/objspace/std/typetype.py (original) +++ pypy/dist/pypy/objspace/std/typetype.py Sat Feb 19 15:30:45 2005 @@ -1,6 +1,6 @@ from pypy.interpreter.error import OperationError from pypy.objspace.std.stdtypedef import * -from pypy.objspace.std.dictproxyobject import dictproxy_descr +from pypy.objspace.std.dictproxyobject import descr_get_dictproxy def descr__new__(space, w_typetype, w_name, w_bases, w_dict): @@ -42,17 +42,37 @@ w_type.__init__(space, name, bases_w or [space.w_object], dict_w) return w_type +def _check(space, w_type, msg=None): + from pypy.objspace.std.typeobject import W_TypeObject + if not isinstance(w_type, W_TypeObject): + raise OperationError(space.w_TypeError, + space.wrap(msg or "descriptor is for 'type'")) + return w_type + + +def descr_get__name__(space, w_type): + w_type = _check(space, w_type) + return space.wrap(w_type.name) + def descr_get__mro__(space, w_type): + w_type = _check(space, w_type) # XXX this should be inside typeobject.py return space.newtuple(w_type.mro_w) def descr_mro(space, w_type): + w_type = _check(space, w_type,"expected type") return space.newlist(w_type.compute_mro()) def descr__bases(space, w_type): + w_type = _check(space, w_type) + from pypy.objspace.std.typeobject import W_TypeObject + if not isinstance(w_type, W_TypeObject): + raise OperationError(space.w_TypeError, + space.wrap("descriptor is for 'type'")) return space.newtuple(w_type.bases_w) def descr__base(space, w_type): + w_type = _check(space, w_type) if w_type is space.w_object: return space.w_None b = w_type.instancetypedef.base @@ -62,17 +82,22 @@ return space.w_object def descr__doc(space, w_type): - return w_type.dict_w.get('__doc__') + w_type = _check(space, w_type) + w_result = w_type.getdictvalue(space, '__doc__') + if w_result is None: + return space.w_None + else: + return w_result # ____________________________________________________________ type_typedef = StdTypeDef("type", __new__ = newmethod(descr__new__), - __name__ = attrproperty('name'), + __name__ = GetSetProperty(descr_get__name__), __bases__ = GetSetProperty(descr__bases), __base__ = GetSetProperty(descr__base), __mro__ = GetSetProperty(descr_get__mro__), - __dict__ = dictproxy_descr, + __dict__ = GetSetProperty(descr_get_dictproxy), __doc__ = GetSetProperty(descr__doc), - mro = newmethod(descr_mro), + mro = gateway.interp2app(descr_mro), ) Modified: pypy/dist/pypy/objspace/test/test_traceobjspace.py ============================================================================== --- pypy/dist/pypy/objspace/test/test_traceobjspace.py (original) +++ pypy/dist/pypy/objspace/test/test_traceobjspace.py Sat Feb 19 15:30:45 2005 @@ -22,7 +22,7 @@ def test_traceobjspace_basic(self): tspace = self.space - assert tspace.is_true(tspace.w_builtins) + assert tspace.is_true(tspace.builtin) #for name, value in vars(self.space).items(): # if not name.startswith('_'): # self.assert_(value is getattr(t, name)) Modified: pypy/dist/pypy/objspace/trivial.py ============================================================================== --- pypy/dist/pypy/objspace/trivial.py (original) +++ pypy/dist/pypy/objspace/trivial.py Sat Feb 19 15:30:45 2005 @@ -12,7 +12,8 @@ import __builtin__ as cpy_builtin class CPyWrapper(object): - pass + def getdictvalue(self, space, name): + return self.__dict__.get(name, None) class TrivialObjSpace(ObjSpace, DescrOperation): @@ -122,7 +123,10 @@ setattr(self, 'w_' + c.__name__, c) newstuff[c.__name__] = c newstuff.update(self.clone_exception_hierarchy()) - self.make_builtins(newstuff) + self.make_builtins() + # XXX Do we need the following still? + #for name, value in newstuff.items(): + # self.builtin.w_dict[name] = value # general stuff def wrap(self, x): Modified: pypy/dist/pypy/tool/pydis.py ============================================================================== --- pypy/dist/pypy/tool/pydis.py (original) +++ pypy/dist/pypy/tool/pydis.py Sat Feb 19 15:30:45 2005 @@ -28,8 +28,7 @@ self.index == other.index and self.op == other.op and self.name == other.name and - self.oparg == other.oparg and - self.lineno == other.lineno) + self.oparg == other.oparg) def __ne__(self, other): return not (self == other) @@ -44,7 +43,12 @@ s = repr(oparg).rjust(5) + " " if op in hasconst: - s += '(' + `co.co_consts_w[oparg]` + ')' + # support both real code objects and PyCode objects + try: + consts = co.co_consts + except AttributeError: + consts = co.co_consts_w + s += '(' + `consts[oparg]` + ')' elif op in hasname: s += '(' + co.co_names[oparg] + ')' elif op in hasjrel: Modified: pypy/dist/pypy/tool/pytestsupport.py ============================================================================== --- pypy/dist/pypy/tool/pytestsupport.py (original) +++ pypy/dist/pypy/tool/pytestsupport.py Sat Feb 19 15:30:45 2005 @@ -2,7 +2,7 @@ import autopath import py from py.__impl__.magic import exprinfo -from pypy.interpreter.gateway import interp2app_temp +from pypy.interpreter import gateway from pypy.interpreter.error import OperationError # ____________________________________________________________ @@ -85,7 +85,7 @@ frame = framestack.top(0) # Argh! we may see app-level helpers in the frame stack! # that's very probably very bad... - if frame.code.co_name == 'app_normalize_exception': + if frame.code.co_name == 'normalize_exception': frame = framestack.top(1) runner = AppFrame(frame) @@ -104,10 +104,13 @@ space.setattr(w_self, space.wrap('msg'), w_msg) # build a new AssertionError class to replace the original one. - w_BuiltinAssertionError = space.getitem(space.w_builtins, + w_BuiltinAssertionError = space.getitem(space.builtin.w_dict, space.wrap('AssertionError')) w_metaclass = space.type(w_BuiltinAssertionError) - w_init = space.wrap(interp2app_temp(my_init)) + w_init = space.wrap(gateway.interp2app_temp(my_init, + unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.Arguments])) w_dict = space.newdict([]) space.setitem(w_dict, space.wrap('__init__'), w_init) return space.call_function(w_metaclass, @@ -137,26 +140,30 @@ w_locals) except OperationError, e: if e.match(space, w_ExpectedException): - return space.sys.exc_info() + return space.call_function(space.sys.get('exc_info')) raise else: try: space.call_args(w_expr, __args__) except OperationError, e: if e.match(space, w_ExpectedException): - return space.sys.exc_info() + return space.call_function(space.sys.get('exc_info')) raise raise OperationError(space.w_AssertionError, space.wrap("DID NOT RAISE")) -app_raises = interp2app_temp(pypyraises) +app_raises = gateway.interp2app_temp(pypyraises, + unwrap_spec=[gateway.ObjSpace, + gateway.W_Root, + gateway.W_Root, + gateway.Arguments]) def pypyskip(space, w_message): """skip a test at app-level. """ msg = space.unwrap(w_message) py.test.skip(msg) -app_skip = interp2app_temp(pypyskip) +app_skip = gateway.interp2app_temp(pypyskip) def raises_w(space, w_ExpectedException, *args, **kwds): try: Modified: pypy/dist/pypy/tool/test/test_pytestsupport.py ============================================================================== --- pypy/dist/pypy/tool/test/test_pytestsupport.py (original) +++ pypy/dist/pypy/tool/test/test_pytestsupport.py Sat Feb 19 15:30:45 2005 @@ -28,7 +28,7 @@ assert x == 43 t = app2interp_temp(app_test_func) f = t.get_function(space) - space.setitem(space.w_builtins, space.wrap('AssertionError'), + space.setitem(space.builtin.w_dict, space.wrap('AssertionError'), build_pytest_assertion(space)) try: f.call_args(Arguments([])) Modified: pypy/dist/pypy/tool/uid.py ============================================================================== --- pypy/dist/pypy/tool/uid.py (original) +++ pypy/dist/pypy/tool/uid.py Sat Feb 19 15:30:45 2005 @@ -1,12 +1,16 @@ -import sys -HUGEINT = (sys.maxint + 1L) * 2L +import struct + +HUGEVAL = 256 ** struct.calcsize('P') + + +def fixid(result): + if result < 0: + result += HUGEVAL + return result def uid(obj): """ Return the id of an object as an unsigned number so that its hex representation makes sense """ - rval = id(obj) - if rval < 0: - rval += HUGEINT - return rval + return fixid(id(obj)) Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Sat Feb 19 15:30:45 2005 @@ -35,6 +35,11 @@ # return 'PyRun_String("%s", Py_eval_input, PyEval_GetGlobals(), NULL)' % ( # source, ) +def builtin_base(obj): + typ = type(obj) + while typ.__module__ != '__builtin__': + typ = typ.__base__ + return typ class GenC: MODNAMES = {} @@ -75,8 +80,8 @@ else: stackentry = obj self.debugstack = (self.debugstack, stackentry) - if (type(obj).__module__ != '__builtin__' and - not isinstance(obj, type)): # skip user-defined metaclasses + obj_builtin_base = builtin_base(obj) + if obj_builtin_base in (object, int, long) and type(obj) is not obj_builtin_base: # assume it's a user defined thingy name = self.nameof_instance(obj) else: @@ -310,6 +315,8 @@ if isinstance(value, staticmethod) and value.__get__(1) not in self.translator.flowgraphs and self.translator.frozen: print value continue + if isinstance(value, classmethod) and value.__get__(cls).__doc__.lstrip().startswith("NOT_RPYTHON"): + continue if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: print value continue Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Sat Feb 19 15:30:45 2005 @@ -543,10 +543,10 @@ #self.initcode.append('m.%s = space.getattr(space.w_builtin, %s)'% ( # name, self.nameof(func.__name__))) # be lazy - return "(space.getattr(space.w_builtin, %s))" % self.nameof(func.__name__) + return "(space.builtin.get(space.str_w(%s)))" % self.nameof(func.__name__) elif modname == 'sys': # be lazy - return "(space.getattr(space.w_sys, %s))" % self.nameof(func.__name__) + return "(space.sys.get(space.str_w(%s)))" % self.nameof(func.__name__) else: print ("WARNING: accessing builtin modules different from sys or __builtin__" " is likely producing non-sense") Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Sat Feb 19 15:30:45 2005 @@ -764,3 +764,52 @@ return (a,a1,b,b1) +# reorg + +class BltinCodeReorg: + def __init__(self, framecls): + self.framecls = framecls + + def call(self, x): + frame = self.framecls() + frame.set(x) + return frame.run() + +class BltinFrameReorg: + def __init__(self): + pass + + def set(self,x): + pass + + def run(self): + pass + +class FBltinFrameReorg(BltinFrameReorg): + + def set(self, x): + self.arg = int(x) + + def run(self): + return bltin_code_frame_f(self.arg) + +class GBltinFrameReorg(BltinFrameReorg): + + def set(self, x): + self.arg = str(x) + + def run(self): + return bltin_code_frame_g(self.arg) + + +bltin_code_for_f_reorg = BltinCodeReorg(FBltinFrameReorg) +bltin_code_for_g_reorg = BltinCodeReorg(GBltinFrameReorg) + +def bltin_code_frame_reorg(): + a = bltin_code_for_f_reorg.call(0) + a1 = bltin_code_for_f_reorg.call(1) + b = bltin_code_for_g_reorg.call("a") + b1 = bltin_code_for_g_reorg.call("b") + return (a,a1,b,b1) + + Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Sat Feb 19 15:30:45 2005 @@ -494,10 +494,17 @@ a.build_types(snippet.bltin_code_frame_confusion,[]) f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f) g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g) - is_int = isinstance(a.binding(f_flowgraph.getreturnvar()), + # annotator confused by original bltin code/frame setup, we just get SomeObject here + assert a.binding(f_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject + assert a.binding(g_flowgraph.getreturnvar()).__class__ is annmodel.SomeObject + + def test_bltin_code_frame_reorg(self): + a = RPythonAnnotator() + a.build_types(snippet.bltin_code_frame_reorg,[]) + f_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_f) + g_flowgraph = a.translator.getflowgraph(snippet.bltin_code_frame_g) + assert isinstance(a.binding(f_flowgraph.getreturnvar()), annmodel.SomeInteger) - if not is_int: - py.test.skip("annotator confused with bltin code/frame setup") assert isinstance(a.binding(g_flowgraph.getreturnvar()), annmodel.SomeString) Modified: pypy/dist/pypy/translator/tool/tointerplevel.py ============================================================================== --- pypy/dist/pypy/translator/tool/tointerplevel.py (original) +++ pypy/dist/pypy/translator/tool/tointerplevel.py Sat Feb 19 15:30:45 2005 @@ -30,6 +30,7 @@ as = options.as or name mod = new.module(as) + mod.__dict__['__file__'] = modfile execfile(modfile, mod.__dict__) del mod.__dict__['__builtins__'] From hpk at codespeak.net Sat Feb 19 15:33:08 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 15:33:08 +0100 (MET) Subject: [pypy-svn] r9333 - pypy/branch/dist-interpapp Message-ID: <20050219143308.B5B2027B84@code1.codespeak.net> Author: hpk Date: Sat Feb 19 15:33:08 2005 New Revision: 9333 Removed: pypy/branch/dist-interpapp/ Log: remove completed branch From hpk at codespeak.net Sat Feb 19 16:39:45 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 16:39:45 +0100 (MET) Subject: [pypy-svn] r9342 - pypy/dist/pypy/interpreter Message-ID: <20050219153945.D607C27B5D@code1.codespeak.net> Author: hpk Date: Sat Feb 19 16:39:45 2005 New Revision: 9342 Modified: pypy/dist/pypy/interpreter/gateway.py Log: fix a missing name from the merge Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Sat Feb 19 16:39:45 2005 @@ -253,6 +253,7 @@ exec compile(setfastscope, '', 'exec') in self.miniglobals, d self.miniglobals['func'] = func + self.miniglobals['OperationError'] = OperationError source = """if 1: def run(self): try: From hpk at codespeak.net Sat Feb 19 16:46:20 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 16:46:20 +0100 (MET) Subject: [pypy-svn] r9344 - pypy/dist/pypy Message-ID: <20050219154620.5C06827B5D@code1.codespeak.net> Author: hpk Date: Sat Feb 19 16:46:20 2005 New Revision: 9344 Modified: pypy/dist/pypy/conftest.py Log: i couldn't resist :-) now py.test will show tracebacks including all the generated code. As we probably don'T plan to translate the running of the tests this should not cause a problem for the translator :-) Modified: pypy/dist/pypy/conftest.py ============================================================================== --- pypy/dist/pypy/conftest.py (original) +++ pypy/dist/pypy/conftest.py Sat Feb 19 16:46:20 2005 @@ -31,6 +31,7 @@ try: return _spacecache[name] except KeyError: + py.magic.invoke(compile=True) module = __import__("pypy.objspace.%s" % name, None, None, ["Space"]) space = module.Space() _spacecache[name] = space From hpk at codespeak.net Sat Feb 19 17:04:16 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 17:04:16 +0100 (MET) Subject: [pypy-svn] r9346 - in pypy/dist/pypy: interpreter interpreter/test interpreter/test/mixedmodule lib module/builtin module/sys2 objspace/std/test tool translator/llvm Message-ID: <20050219160416.27C3727B60@code1.codespeak.net> Author: hpk Date: Sat Feb 19 17:04:15 2005 New Revision: 9346 Modified: pypy/dist/pypy/interpreter/lazymodule.py (props changed) pypy/dist/pypy/interpreter/test/mixedmodule/__init__.py (props changed) pypy/dist/pypy/interpreter/test/mixedmodule/file1.py (props changed) pypy/dist/pypy/interpreter/test/mixedmodule/file2_app.py (props changed) pypy/dist/pypy/interpreter/test/test_appinterp.py (props changed) pypy/dist/pypy/lib/decimal.py (props changed) pypy/dist/pypy/lib/itertools.py (props changed) pypy/dist/pypy/module/builtin/__init__.py (props changed) pypy/dist/pypy/module/sys2/__init__.py (props changed) pypy/dist/pypy/module/sys2/hook.py (props changed) pypy/dist/pypy/objspace/std/test/test_operation.py (props changed) pypy/dist/pypy/tool/getpy.py (props changed) pypy/dist/pypy/translator/llvm/representation.py (props changed) Log: fixeol From hpk at codespeak.net Sat Feb 19 17:35:42 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 17:35:42 +0100 (MET) Subject: [pypy-svn] r9349 - pypy/dist/pypy/objspace/std Message-ID: <20050219163542.3F45A27B60@code1.codespeak.net> Author: hpk Date: Sat Feb 19 17:35:42 2005 New Revision: 9349 Modified: pypy/dist/pypy/objspace/std/floatobject.py Log: add nicer repr for floatobject Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Sat Feb 19 17:35:42 2005 @@ -24,6 +24,8 @@ def unwrap(w_self): return w_self.floatval + def __repr__(self): + return "" % self.floatval registerimplementation(W_FloatObject) From pedronis at codespeak.net Sat Feb 19 18:24:18 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 19 Feb 2005 18:24:18 +0100 (MET) Subject: [pypy-svn] r9350 - pypy/dist/pypy/objspace/std Message-ID: <20050219172418.518CF27B60@code1.codespeak.net> Author: pedronis Date: Sat Feb 19 18:24:18 2005 New Revision: 9350 Modified: pypy/dist/pypy/objspace/std/floatobject.py Log: -1.0 should have been 1.0 reuse divmod impl for float // as CPython Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Sat Feb 19 18:24:18 2005 @@ -187,16 +187,8 @@ truediv__Float_Float = div__Float_Float def floordiv__Float_Float(space, w_float1, w_float2): - x = w_float1.floatval - y = w_float2.floatval - try: - z = x // y - except ZeroDivisionError: - raise OperationError(space.w_ZeroDivisionError, space.wrap("float division")) - except FloatingPointError: - raise FailedToImplement(space.w_FloatingPointError, space.wrap("float division")) - # no overflow - return W_FloatObject(space, z) + t = divmod__Float_Float(space, w_float1, w_float2) + return space.getitem(t, space.wrap(0)) def mod__Float_Float(space, w_float1, w_float2): x = w_float1.floatval @@ -225,7 +217,7 @@ if (mod): if ((y < 0.0) != (mod < 0.0)): mod += y - div -= -1.0 + div -= 1.0 else: mod *= mod if y < 0.0: From pedronis at codespeak.net Sat Feb 19 18:27:34 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Sat, 19 Feb 2005 18:27:34 +0100 (MET) Subject: [pypy-svn] r9351 - pypy/dist/pypy/objspace/std Message-ID: <20050219172734.2CEC427B60@code1.codespeak.net> Author: pedronis Date: Sat Feb 19 18:27:33 2005 New Revision: 9351 Modified: pypy/dist/pypy/objspace/std/floatobject.py Log: oops, respect w_ conventions Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Sat Feb 19 18:27:33 2005 @@ -187,8 +187,8 @@ truediv__Float_Float = div__Float_Float def floordiv__Float_Float(space, w_float1, w_float2): - t = divmod__Float_Float(space, w_float1, w_float2) - return space.getitem(t, space.wrap(0)) + w_t = divmod__Float_Float(space, w_float1, w_float2) + return space.getitem(w_t, space.wrap(0)) def mod__Float_Float(space, w_float1, w_float2): x = w_float1.floatval From hpk at codespeak.net Sat Feb 19 19:44:16 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 19:44:16 +0100 (MET) Subject: [pypy-svn] r9352 - in pypy/dist/pypy: interpreter interpreter/test module/builtin tool Message-ID: <20050219184416.715EC27B60@code1.codespeak.net> Author: hpk Date: Sat Feb 19 19:44:16 2005 New Revision: 9352 Modified: pypy/dist/pypy/interpreter/lazymodule.py pypy/dist/pypy/interpreter/main.py pypy/dist/pypy/interpreter/test/test_appinterp.py pypy/dist/pypy/interpreter/test/test_interpreter.py pypy/dist/pypy/module/builtin/compiling.py pypy/dist/pypy/module/builtin/importing.py pypy/dist/pypy/tool/pytestsupport.py Log: added a new module-method "call" which eases calling functions of the builtin and sys module. simplified some locations accordingly. Modified: pypy/dist/pypy/interpreter/lazymodule.py ============================================================================== --- pypy/dist/pypy/interpreter/lazymodule.py (original) +++ pypy/dist/pypy/interpreter/lazymodule.py Sat Feb 19 19:44:16 2005 @@ -22,6 +22,10 @@ raise OperationError(space.w_AttributeError, space.wrap(name)) return w_value + def call(self, name, *args_w): + w_builtin = self.get(name) + return self.space.call_function(w_builtin, *args_w) + def getdictvalue(self, space, name): try: return space.getitem(self.w_dict, space.wrap(name)) Modified: pypy/dist/pypy/interpreter/main.py ============================================================================== --- pypy/dist/pypy/interpreter/main.py (original) +++ pypy/dist/pypy/interpreter/main.py Sat Feb 19 19:44:16 2005 @@ -14,9 +14,8 @@ from pypy.objspace.std import StdObjSpace space = StdObjSpace() - w_compile = space.builtin.get('compile') w = space.wrap - w_code = space.call_function(w_compile, + w_code = space.builtin.call('compile', w(source), w(filename), w(cmd), w(0), w(0)) w_main = space.wrap('__main__') mainmodule = module.Module(space, w_main) Modified: pypy/dist/pypy/interpreter/test/test_appinterp.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_appinterp.py (original) +++ pypy/dist/pypy/interpreter/test/test_appinterp.py Sat Feb 19 19:44:16 2005 @@ -125,3 +125,4 @@ for name in ('somefunc', 'someappfunc', '__doc__', '__name__'): assert name in module.__dict__ """) + assert space.is_true(w_module.call('somefunc')) Modified: pypy/dist/pypy/interpreter/test/test_interpreter.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_interpreter.py (original) +++ pypy/dist/pypy/interpreter/test/test_interpreter.py Sat Feb 19 19:44:16 2005 @@ -10,10 +10,8 @@ source = str(py.code.Source(source).strip()) + '\n' - #from pypy.module.builtin.compiling import compile - w_compile = space.builtin.get('compile') w = space.wrap - w_code = space.call_function(w_compile, + w_code = space.builtin.call('compile', w(source), w(''), w('exec'), w(0), w(0)) ec = executioncontext.ExecutionContext(space) Modified: pypy/dist/pypy/module/builtin/compiling.py ============================================================================== --- pypy/dist/pypy/module/builtin/compiling.py (original) +++ pypy/dist/pypy/module/builtin/compiling.py Sat Feb 19 19:44:16 2005 @@ -20,7 +20,7 @@ supplied_flags |= 4096 if not dont_inherit: try: - frame = space.call_function(space.sys.get('_getframe')) + frame = space.sys.call('_getframe') except OperationError, e: if not e.match(space, space.w_ValueError): raise Modified: pypy/dist/pypy/module/builtin/importing.py ============================================================================== --- pypy/dist/pypy/module/builtin/importing.py (original) +++ pypy/dist/pypy/module/builtin/importing.py Sat Feb 19 19:44:16 2005 @@ -24,8 +24,7 @@ if pkgdir is not None: space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)])) w_dict = space.getattr(w_mod, w('__dict__')) - w_execfile = space.builtin.get("execfile") - space.call_function(w_execfile, w(f), w_dict, w_dict) + space.builtin.call('execfile', w(f), w_dict, w_dict) w_mod = check_sys_modules(space, w_modulename) if w_mod is not None and w_parent is not None: space.setattr(w_parent, w_name, w_mod) Modified: pypy/dist/pypy/tool/pytestsupport.py ============================================================================== --- pypy/dist/pypy/tool/pytestsupport.py (original) +++ pypy/dist/pypy/tool/pytestsupport.py Sat Feb 19 19:44:16 2005 @@ -140,14 +140,14 @@ w_locals) except OperationError, e: if e.match(space, w_ExpectedException): - return space.call_function(space.sys.get('exc_info')) + return space.sys.call('exc_info') raise else: try: space.call_args(w_expr, __args__) except OperationError, e: if e.match(space, w_ExpectedException): - return space.call_function(space.sys.get('exc_info')) + return space.sys.call('exc_info') raise raise OperationError(space.w_AssertionError, space.wrap("DID NOT RAISE")) From hpk at codespeak.net Sat Feb 19 19:54:44 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Sat, 19 Feb 2005 19:54:44 +0100 (MET) Subject: [pypy-svn] r9353 - pypy/dist/lib-python-2.3.4/test Message-ID: <20050219185444.3773627B60@code1.codespeak.net> Author: hpk Date: Sat Feb 19 19:54:44 2005 New Revision: 9353 Modified: pypy/dist/lib-python-2.3.4/test/conftest.py Log: convert w_KeyboardInterrupt back to KeyboardInterrupt to be able to interrupt the lib-python-2.3.4 testing process. Modified: pypy/dist/lib-python-2.3.4/test/conftest.py ============================================================================== --- pypy/dist/lib-python-2.3.4/test/conftest.py (original) +++ pypy/dist/lib-python-2.3.4/test/conftest.py Sat Feb 19 19:54:44 2005 @@ -171,10 +171,16 @@ self.w_teardown = w_teardown def run(self, driver): + space = self.space try: - self.space.call_function(self.w_setup) + space.call_function(self.w_setup) try: - self.execute() + try: + self.execute() + except OperationError, e: + if e.match(space, space.w_KeyboardInterrupt): + raise KeyboardInterrupt + raise finally: self.space.call_function(self.w_teardown) except OperationError, e: From sanxiyn at codespeak.net Mon Feb 21 01:46:37 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Mon, 21 Feb 2005 01:46:37 +0100 (MET) Subject: [pypy-svn] r9372 - pypy/dist/pypy/lib Message-ID: <20050221004637.AEBCB27BBA@code1.codespeak.net> Author: sanxiyn Date: Mon Feb 21 01:46:37 2005 New Revision: 9372 Modified: pypy/dist/pypy/lib/_classobj.py Log: _classobj's geninterplevel_name: Don't reference w_builtin Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Mon Feb 21 01:46:37 2005 @@ -101,7 +101,7 @@ return i += 1 # let geninterplevel retrieve the PyPy builtin instead -_seqiter.geninterplevel_name = lambda gen: "(space.getattr(space.w_builtin, %s))" % gen.nameof('_seqiter') +_seqiter.geninterplevel_name = lambda gen: "space.builtin.get('_seqiter')" OLD_STYLE_CLASSES_IMPL = object() From sanxiyn at codespeak.net Mon Feb 21 01:49:21 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Mon, 21 Feb 2005 01:49:21 +0100 (MET) Subject: [pypy-svn] r9373 - pypy/dist/pypy/module Message-ID: <20050221004921.EB00127BBA@code1.codespeak.net> Author: sanxiyn Date: Mon Feb 21 01:49:21 2005 New Revision: 9373 Modified: pypy/dist/pypy/module/classobjinterp.py Log: Regenerated with: python translator/tool/tointerplevel.py --modname classobj --out module/classobjinterp.py lib/_classobj.py classobj instance purify Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Mon Feb 21 01:49:21 2005 @@ -6,7 +6,7 @@ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '_coerce' ## firstlineno 7 ##SECTION## @@ -68,7 +68,7 @@ fastf__coerce = _coerce ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'uid' ## firstlineno 18 ##SECTION## @@ -118,7 +118,7 @@ fastf_uid = uid ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'type_err' ## firstlineno 35 ##SECTION## @@ -156,7 +156,7 @@ fastf_type_err = type_err ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'set_name' ## firstlineno 38 ##SECTION## @@ -207,7 +207,7 @@ fastf_set_name = set_name ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'set_bases' ## firstlineno 43 ##SECTION## @@ -292,7 +292,7 @@ fastf_set_bases = set_bases ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'set_dict' ## firstlineno 51 ##SECTION## @@ -342,7 +342,7 @@ fastf_set_dict = set_dict ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'retrieve' ## firstlineno 56 ##SECTION## @@ -416,7 +416,7 @@ fastf_retrieve = retrieve ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'lookup' ## firstlineno 63 ##SECTION## @@ -548,7 +548,7 @@ fastf_lookup = lookup ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'get_class_module' ## firstlineno 75 ##SECTION## @@ -628,7 +628,7 @@ fastf_get_class_module = get_class_module ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'mro_lookup' ## firstlineno 84 ##SECTION## @@ -705,7 +705,7 @@ fastf_mro_lookup = mro_lookup ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__new__' ## firstlineno 112 ##SECTION## @@ -911,7 +911,7 @@ if goto == 15: try: - w_42 = space.call_function((space.getattr(space.w_sys, gs__getframe)), w_i) + w_42 = space.call_function((space.sys.get(space.str_w(gs__getframe))), w_i) (w_name_15, w_bases_15, w_dic_15, w_i_1, w_43) = (w_name_13, w_bases_13, w_dic_13, w_i, w_42) goto = 16 @@ -1086,7 +1086,7 @@ if goto == 29: w_74 = space.call_function(space.w_type, w_b_2) - w_75 = space.call_function((space.getattr(space.w_builtin, gs_callable)), w_74) + w_75 = space.call_function((space.builtin.get(space.str_w(gs_callable))), w_74) v76 = space.is_true(w_75) if v76 == True: (w_name_28, w_bases_28, w_dic_28, w_b_3) = (w_name_27, w_bases_27, @@ -1122,7 +1122,7 @@ fastf___new__ = __new__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__setattr__' ## firstlineno 162 ##SECTION## @@ -1210,7 +1210,7 @@ fastf_classobj___setattr__ = __setattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__delattr__' ## firstlineno 172 ##SECTION## @@ -1261,7 +1261,7 @@ fastf_classobj___delattr__ = __delattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__getattribute__' ## firstlineno 179 ##SECTION## @@ -1402,7 +1402,7 @@ fastf_classobj___getattribute__ = __getattribute__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__repr__' ## firstlineno 196 ##SECTION## @@ -1441,7 +1441,7 @@ fastf_classobj___repr__ = __repr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__str__' ## firstlineno 200 ##SECTION## @@ -1497,7 +1497,7 @@ fastf_classobj___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__call__' ## firstlineno 207 ##SECTION## @@ -1567,7 +1567,7 @@ fastf_classobj___call__ = __call__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function 'instance_getattr1' ## firstlineno 228 ##SECTION## @@ -1787,7 +1787,7 @@ fastf_instance_getattr1 = instance_getattr1 ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__getattribute__' ## firstlineno 252 ##SECTION## @@ -1894,7 +1894,7 @@ fastf_instance___getattribute__ = __getattribute__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__new__' ## firstlineno 261 ##SECTION## @@ -1983,7 +1983,7 @@ fastf___new___1 = __new__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__setattr__' ## firstlineno 274 ##SECTION## @@ -2107,7 +2107,7 @@ fastf_instance___setattr__ = __setattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__delattr__' ## firstlineno 290 ##SECTION## @@ -2249,7 +2249,7 @@ fastf_instance___delattr__ = __delattr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__repr__' ## firstlineno 306 ##SECTION## @@ -2343,7 +2343,7 @@ fastf_instance___repr__ = __repr__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__str__' ## firstlineno 315 ##SECTION## @@ -2423,7 +2423,7 @@ fastf_instance___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__hash__' ## firstlineno 322 ##SECTION## @@ -2536,7 +2536,7 @@ fastf_instance___hash__ = __hash__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__len__' ## firstlineno 336 ##SECTION## @@ -2601,7 +2601,7 @@ fastf_instance___len__ = __len__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__getitem__' ## firstlineno 345 ##SECTION## @@ -2683,7 +2683,7 @@ fastf_instance___getitem__ = __getitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__setitem__' ## firstlineno 352 ##SECTION## @@ -2771,7 +2771,7 @@ fastf_instance___setitem__ = __setitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__delitem__' ## firstlineno 359 ##SECTION## @@ -2853,7 +2853,7 @@ fastf_instance___delitem__ = __delitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' +## filename '_classobj.py' ## function '__contains__' ## firstlineno 366 ##SECTION## @@ -2925,565 +2925,508 @@ fastf_instance___contains__ = __contains__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__coerce__' -## firstlineno 387 +## filename '_classobj.py' +## function '__abs__' +## firstlineno 381 ##SECTION## -def __coerce__(space, __args__): - funcname = "__coerce__" - signature = ['self', 'other'], None, None +def __abs__(space, __args__): + funcname = "__abs__" + signature = ['self'], None, None defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___coerce__(space, w_self, w_other) + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___abs__(space, w_self) -f_instance___coerce__ = __coerce__ +f_instance___abs__ = __abs__ -def __coerce__(space, w_self, w_other): +def __abs__(space, w_self): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_0=w_2=w_3=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___coerce__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented - goto = 3 + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___abs__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 - goto = 3 - - if goto == 3: - return w_4 + return w_3 -fastf_instance___coerce__ = __coerce__ +fastf_instance___abs__ = __abs__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__pow__' -## firstlineno 441 +## filename '_classobj.py' +## function '__float__' +## firstlineno 381 ##SECTION## -def __pow__(space, __args__): - funcname = "__pow__" - signature = ['self', 'other', 'modulo'], None, None - defaults_w = [space.w_None] - w_self, w_other, w_modulo = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___pow__(space, w_self, w_other, w_modulo) +def __float__(space, __args__): + funcname = "__float__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___float__(space, w_self) -f_instance___pow__ = __pow__ +f_instance___float__ = __float__ -def __pow__(space, w_self, w_other, w_modulo): +def __float__(space, w_self): - w_0=v2=w_self_2=w_other_2=w_modulo_1=w_func_2=v17=w_14=w_other_8=None - w_modulo_2=w_func_3=w_18=w_self_1=w_other_1=w_coerced=w_6=v7=None - w_self_4=w_other_4=w_coerced_1=w_9=w_10=w_self_3=w_other_3=w_8=None - v11=w_self_6=w_other_6=w_16=w_self_5=w_other_5=w_func=v13=w_other_7=None - w_func_1=w_15=None + w_0=w_2=w_3=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.is_(w_modulo, space.w_None) - v2 = space.is_true(w_0) - if v2 == True: - w_self_1, w_other_1 = w_self, w_other - goto = 2 - else: - assert v2 == False - w_self_2, w_other_2, w_modulo_1 = w_self, w_other, w_modulo - goto = 8 + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___float__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 if goto == 2: - w_coerced = fastf__coerce(space, w_self_1, w_other_1) - w_6 = space.is_(w_coerced, space.w_None) - v7 = space.is_true(w_6) - if v7 == True: - w_self_3, w_other_3, w_8 = w_self_1, w_other_1, w_6 - goto = 4 - else: - assert v7 == False - w_self_4, w_other_4, w_coerced_1 = w_self_1, w_other_1, w_coerced - goto = 3 + return w_3 - if goto == 3: - w_9 = space.getitem(w_coerced_1, gi_0) - w_10 = space.is_(w_9, w_self_4) - w_self_3, w_other_3, w_8 = w_self_4, w_other_4, w_10 - goto = 4 +fastf_instance___float__ = __float__ - if goto == 4: - v11 = space.is_true(w_8) - if v11 == True: - w_self_5, w_other_5 = w_self_3, w_other_3 - goto = 5 - else: - assert v11 == False - w_self_6, w_other_6 = w_self_3, w_other_3 - goto = 7 +##SECTION## +## filename '_classobj.py' +## function '__hex__' +## firstlineno 381 +##SECTION## +def __hex__(space, __args__): + funcname = "__hex__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___hex__(space, w_self) - if goto == 5: - w_func = space.call_function(gfunc_instance_getattr1, w_self_5, gs___pow__, space.w_False) - v13 = space.is_true(w_func) - if v13 == True: - w_other_7, w_func_1 = w_other_5, w_func - goto = 6 - else: - assert v13 == False - w_14 = space.w_NotImplemented - goto = 10 +f_instance___hex__ = __hex__ - if goto == 6: - w_15 = space.call_function(w_func_1, w_other_7) - w_14 = w_15 - goto = 10 +def __hex__(space, w_self): - if goto == 7: - w_16 = space.pow(w_self_6, w_other_6) - w_14 = w_16 - goto = 10 + w_0=w_2=w_3=None - if goto == 8: - w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_2, gs___pow__, space.w_False) - v17 = space.is_true(w_func_2) - if v17 == True: - w_other_8, w_modulo_2, w_func_3 = w_other_2, w_modulo_1, w_func_2 - goto = 9 - else: - assert v17 == False - w_14 = space.w_NotImplemented - goto = 10 + goto = 1 # startblock + while True: - if goto == 9: - w_18 = space.call_function(w_func_3, w_other_8, w_modulo_2) - w_14 = w_18 - goto = 10 + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___hex__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 - if goto == 10: - return w_14 + if goto == 2: + return w_3 -fastf_instance___pow__ = __pow__ +fastf_instance___hex__ = __hex__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__rpow__' -## firstlineno 459 +## filename '_classobj.py' +## function '__int__' +## firstlineno 381 ##SECTION## -def __rpow__(space, __args__): - funcname = "__rpow__" - signature = ['self', 'other', 'modulo'], None, None - defaults_w = [space.w_None] - w_self, w_other, w_modulo = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rpow__(space, w_self, w_other, w_modulo) +def __int__(space, __args__): + funcname = "__int__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___int__(space, w_self) -f_instance___rpow__ = __rpow__ +f_instance___int__ = __int__ -def __rpow__(space, w_self, w_other, w_modulo): +def __int__(space, w_self): - w_0=v2=w_self_2=w_other_2=w_modulo_1=w_func_2=v17=w_14=w_other_8=None - w_modulo_2=w_func_3=w_18=w_self_1=w_other_1=w_coerced=w_6=v7=None - w_self_4=w_other_4=w_coerced_1=w_9=w_10=w_self_3=w_other_3=w_8=None - v11=w_self_6=w_other_6=w_16=w_self_5=w_other_5=w_func=v13=w_other_7=None - w_func_1=w_15=None + w_0=w_2=w_3=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.is_(w_modulo, space.w_None) - v2 = space.is_true(w_0) - if v2 == True: - w_self_1, w_other_1 = w_self, w_other - goto = 2 - else: - assert v2 == False - w_self_2, w_other_2, w_modulo_1 = w_self, w_other, w_modulo - goto = 8 + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___int__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 if goto == 2: - w_coerced = fastf__coerce(space, w_self_1, w_other_1) - w_6 = space.is_(w_coerced, space.w_None) - v7 = space.is_true(w_6) - if v7 == True: - w_self_3, w_other_3, w_8 = w_self_1, w_other_1, w_6 - goto = 4 - else: - assert v7 == False - w_self_4, w_other_4, w_coerced_1 = w_self_1, w_other_1, w_coerced - goto = 3 + return w_3 - if goto == 3: - w_9 = space.getitem(w_coerced_1, gi_0) - w_10 = space.is_(w_9, w_self_4) - w_self_3, w_other_3, w_8 = w_self_4, w_other_4, w_10 - goto = 4 +fastf_instance___int__ = __int__ - if goto == 4: - v11 = space.is_true(w_8) - if v11 == True: - w_self_5, w_other_5 = w_self_3, w_other_3 - goto = 5 - else: - assert v11 == False - w_self_6, w_other_6 = w_self_3, w_other_3 - goto = 7 +##SECTION## +## filename '_classobj.py' +## function '__invert__' +## firstlineno 381 +##SECTION## +def __invert__(space, __args__): + funcname = "__invert__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___invert__(space, w_self) - if goto == 5: - w_func = space.call_function(gfunc_instance_getattr1, w_self_5, gs___rpow__, space.w_False) - v13 = space.is_true(w_func) - if v13 == True: - w_other_7, w_func_1 = w_other_5, w_func - goto = 6 - else: - assert v13 == False - w_14 = space.w_NotImplemented - goto = 10 +f_instance___invert__ = __invert__ - if goto == 6: - w_15 = space.call_function(w_func_1, w_other_7) - w_14 = w_15 - goto = 10 +def __invert__(space, w_self): - if goto == 7: - w_16 = space.pow(w_other_6, w_self_6) - w_14 = w_16 - goto = 10 + w_0=w_2=w_3=None - if goto == 8: - w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_2, gs___rpow__, space.w_False) - v17 = space.is_true(w_func_2) - if v17 == True: - w_other_8, w_modulo_2, w_func_3 = w_other_2, w_modulo_1, w_func_2 - goto = 9 - else: - assert v17 == False - w_14 = space.w_NotImplemented - goto = 10 + goto = 1 # startblock + while True: - if goto == 9: - w_18 = space.call_function(w_func_3, w_other_8, w_modulo_2) - w_14 = w_18 - goto = 10 + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___invert__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 - if goto == 10: - return w_14 + if goto == 2: + return w_3 -fastf_instance___rpow__ = __rpow__ +fastf_instance___invert__ = __invert__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__nonzero__' -## firstlineno 477 +## filename '_classobj.py' +## function '__long__' +## firstlineno 381 ##SECTION## -# global declarations -# global object gs___nonzero_____should_return____0 -# global object gs___nonzero_____should_return_an_i - -def __nonzero__(space, __args__): - funcname = "__nonzero__" +def __long__(space, __args__): + funcname = "__long__" signature = ['self'], None, None defaults_w = [] w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___nonzero__(space, w_self) + return fastf_instance___long__(space, w_self) -f_instance___nonzero__ = __nonzero__ +f_instance___long__ = __long__ -def __nonzero__(space, w_self): +def __long__(space, w_self): - w_func=v2=w_self_1=w_func_2=v3=w_4=w_func_1=w_ret=w_6=v7=w_14=None - w_etype=w_evalue=w_ret_1=w_8=v9=w_ret_2=w_13=w_10=None + w_0=w_2=w_3=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___nonzero__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_func_1 = w_func - goto = 3 - else: - assert v2 == False - w_self_1 = w_self - goto = 2 + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___long__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 if goto == 2: - w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___nonzero__, space.w_False) - v3 = space.is_true(w_func_2) - if v3 == True: - w_func_1 = w_func_2 - goto = 3 - else: - assert v3 == False - w_4 = space.w_True - goto = 9 + return w_3 - if goto == 3: - w_ret = space.call_function(w_func_1, ) - w_6 = space.isinstance(w_ret, space.w_int) - v7 = space.is_true(w_6) - if v7 == True: - w_ret_1 = w_ret - goto = 4 - else: - assert v7 == False - goto = 7 +fastf_instance___long__ = __long__ - if goto == 4: - w_8 = space.lt(w_ret_1, gi_0) - v9 = space.is_true(w_8) - if v9 == True: - goto = 5 - else: - assert v9 == False - w_ret_2 = w_ret_1 - goto = 6 +##SECTION## +## filename '_classobj.py' +## function '__neg__' +## firstlineno 381 +##SECTION## +def __neg__(space, __args__): + funcname = "__neg__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___neg__(space, w_self) - if goto == 5: - w_10 = space.call_function(space.w_ValueError, gs___nonzero_____should_return____0) - w_etype, w_evalue = space.w_ValueError, w_10 - goto = 8 +f_instance___neg__ = __neg__ - if goto == 6: - w_13 = space.gt(w_ret_2, gi_0) - w_4 = w_13 - goto = 9 +def __neg__(space, w_self): - if goto == 7: - w_14 = space.call_function(space.w_TypeError, gs___nonzero_____should_return_an_i) - w_etype, w_evalue = space.w_TypeError, w_14 - goto = 8 + w_0=w_2=w_3=None - if goto == 8: - raise OperationError(w_etype, w_evalue) + goto = 1 # startblock + while True: - if goto == 9: - return w_4 + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___neg__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 -fastf_instance___nonzero__ = __nonzero__ + if goto == 2: + return w_3 + +fastf_instance___neg__ = __neg__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__call__' -## firstlineno 492 +## filename '_classobj.py' +## function '__oct__' +## firstlineno 381 ##SECTION## -# global declaration -# global object gs__s_instance_has_no___call___meth - -def __call__(space, __args__): - funcname = "__call__" - signature = ['self'], 'args', 'kwds' +def __oct__(space, __args__): + funcname = "__oct__" + signature = ['self'], None, None defaults_w = [] - w_self, w_args, w_kwds = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___call__(space, w_self, w_args, w_kwds) + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___oct__(space, w_self) -f_instance___call__ = __call__ +f_instance___oct__ = __oct__ -def __call__(space, w_self, w_args, w_kwds): +def __oct__(space, w_self): - w_func=v2=w_self_1=w_5=w_6=w_7=w_etype=w_evalue=w_args_1=w_kwds_1=None - w_func_1=w_10=w_11=None + w_0=w_2=w_3=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___call__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_args_1, w_kwds_1, w_func_1 = w_args, w_kwds, w_func - goto = 3 - else: - assert v2 == False - w_self_1 = w_self - goto = 2 + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___oct__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 if goto == 2: - w_5 = space.getattr(w_self_1, gs___class__) - w_6 = space.getattr(w_5, gs___name__) - w_7 = space.mod(gs__s_instance_has_no___call___meth, w_6) - w_etype, w_evalue = space.w_AttributeError, w_7 - goto = 4 + return w_3 - if goto == 3: - _args = Arguments.fromshape(space, (0, (), True, True), [w_args_1, w_kwds_1]) - w_10 = space.call_args(w_func_1, _args) - w_11 = w_10 - goto = 5 +fastf_instance___oct__ = __oct__ - if goto == 4: - raise OperationError(w_etype, w_evalue) +##SECTION## +## filename '_classobj.py' +## function '__pos__' +## firstlineno 381 +##SECTION## +def __pos__(space, __args__): + funcname = "__pos__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___pos__(space, w_self) - if goto == 5: - return w_11 +f_instance___pos__ = __pos__ -fastf_instance___call__ = __call__ +def __pos__(space, w_self): + + w_0=w_2=w_3=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___pos__) + w_2 = space.call_function(w_0, ) + w_3 = w_2 + goto = 2 + + if goto == 2: + return w_3 + +fastf_instance___pos__ = __pos__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__iter__' -## firstlineno 512 +## filename '_classobj.py' +## function '__coerce__' +## firstlineno 387 ##SECTION## -# global declarations -# global object gs___iter___returned_non_iterator_o -# global object gs_iteration_over_non_sequence -# global object gs__seqiter - -def __iter__(space, __args__): - funcname = "__iter__" - signature = ['self'], None, None +def __coerce__(space, __args__): + funcname = "__coerce__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___iter__(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___coerce__(space, w_self, w_other) -f_instance___iter__ = __iter__ +f_instance___coerce__ = __coerce__ -def __iter__(space, w_self): +def __coerce__(space, w_self, w_other): - w_func=v2=w_self_1=w_func_2=v12=w_etype=w_evalue=w_self_2=w_13=None - w_6=w_func_1=w_ret=w_4=v5=w_ret_1=w_7=w_8=w_9=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iter__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___coerce__, space.w_False) v2 = space.is_true(w_func) if v2 == True: - w_func_1 = w_func + w_other_1, w_func_1 = w_other, w_func goto = 2 else: assert v2 == False - w_self_1 = w_self - goto = 4 + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_ret = space.call_function(w_func_1, ) - w_4 = fastf_mro_lookup(space, w_ret, gs_next) - v5 = space.is_true(w_4) - if v5 == True: - w_6 = w_ret - goto = 7 - else: - assert v5 == False - w_ret_1 = w_ret - goto = 3 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 if goto == 3: - w_7 = space.call_function(space.w_type, w_ret_1) - w_8 = space.getattr(w_7, gs___name__) - w_9 = space.mod(gs___iter___returned_non_iterator_o, w_8) - w_etype, w_evalue = space.w_TypeError, w_9 - goto = 6 + return w_4 + +fastf_instance___coerce__ = __coerce__ + +##SECTION## +## filename '_classobj.py' +## function '__add__' +## firstlineno 404 +##SECTION## +def __add__(space, __args__): + funcname = "__add__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___add__(space, w_self, w_other) + +f_instance___add__ = __add__ + +def __add__(space, w_self, w_other): + + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 + + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 if goto == 4: - w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___getitem__, space.w_False) - v12 = space.is_true(w_func_2) - if v12 == True: - w_self_2 = w_self_1 + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___add__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func goto = 5 else: - assert v12 == False - (w_etype, w_evalue) = (space.w_TypeError, - gs_iteration_over_non_sequence) - goto = 6 + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 if goto == 5: - w_13 = space.call_function((space.getattr(space.w_builtin, gs__seqiter)), w_self_2) - w_6 = w_13 + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 goto = 7 if goto == 6: - raise OperationError(w_etype, w_evalue) + w_13 = space.add(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 if goto == 7: - return w_6 + return w_11 -fastf_instance___iter__ = __iter__ +fastf_instance___add__ = __add__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function 'next' -## firstlineno 527 +## filename '_classobj.py' +## function '__and__' +## firstlineno 404 ##SECTION## -# global declaration -# global object gs_instance_has_no_next___method - -def next(space, __args__): - funcname = "next" - signature = ['self'], None, None +def __and__(space, __args__): + funcname = "__and__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance_next(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___and__(space, w_self, w_other) -f_instance_next = next +f_instance___and__ = __and__ -def next(space, w_self): +def __and__(space, w_self, w_other): - w_func=v2=w_etype=w_evalue=w_func_1=w_5=w_6=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs_next, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_func_1 = w_func - goto = 2 - else: - assert v2 == False - (w_etype, w_evalue) = (space.w_TypeError, - gs_instance_has_no_next___method) + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, ) - w_6 = w_5 - goto = 4 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 if goto == 3: - raise OperationError(w_etype, w_evalue) + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 if goto == 4: - return w_6 + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___and__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 -fastf_instance_next = next + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.and_(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___and__ = __and__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function '__cmp__' -## firstlineno 533 +## filename '_classobj.py' +## function '__div__' +## firstlineno 404 ##SECTION## -# global declarations -# global object gs___cmp___must_return_int -# global object gi_minus_1 - -def __cmp__(space, __args__): - funcname = "__cmp__" +def __div__(space, __args__): + funcname = "__div__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___cmp__(space, w_self, w_other) + return fastf_instance___div__(space, w_self, w_other) -f_instance___cmp__ = __cmp__ +f_instance___div__ = __div__ -def __cmp__(space, w_self, w_other): +def __div__(space, w_self, w_other): - w_coerced=w_3=v4=w_coerced_1=w_v_1=w_w_1=w_7=v8=w_v_3=w_w_3=w_10=None - v11=w_w_2=w_v_2=w_9=v12=w_w=w_v=w_15=v16=w_w_6=w_v_6=w_28=v29=None - w_14=w_v_7=w_func_2=v30=w_v_8=w_func_3=w_res_3=w_31=v32=w_etype=None - w_evalue=w_res_4=w_33=v34=w_res_5=w_35=v36=w_w_5=w_v_5=w_func=None - v18=w_w_7=w_func_1=w_res=w_20=v21=w_res_1=w_24=v25=w_res_2=w_26=None - v27=w_w_4=w_v_4=w_13=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: @@ -3493,430 +3436,224 @@ w_3 = space.is_(w_coerced, space.w_None) v4 = space.is_true(w_3) if v4 == True: - w_w, w_v = w_other, w_self - goto = 6 + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 else: assert v4 == False - w_coerced_1 = w_coerced + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced goto = 2 if goto == 2: - w_v_1 = space.getitem(w_coerced_1, gi_0) - w_w_1 = space.getitem(w_coerced_1, gi_1) - w_7 = space.isinstance(w_v_1, gcls_instance) - v8 = space.is_true(w_7) - if v8 == True: - w_w_2, w_v_2, w_9 = w_w_1, w_v_1, space.w_False - goto = 4 - else: - assert v8 == False - w_v_3, w_w_3 = w_v_1, w_w_1 - goto = 3 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 if goto == 3: - w_10 = space.isinstance(w_w_3, gcls_instance) - v11 = space.is_true(w_10) - if v11 == True: - w_w_2, w_v_2, w_9 = w_w_3, w_v_3, space.w_False + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 goto = 4 else: - assert v11 == False - w_w_2, w_v_2, w_9 = w_w_3, w_v_3, space.w_True - goto = 4 + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 if goto == 4: - v12 = space.is_true(w_9) - if v12 == True: - w_w_4, w_v_4 = w_w_2, w_v_2 + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___div__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func goto = 5 else: - assert v12 == False - w_w, w_v = w_w_2, w_v_2 - goto = 6 + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 if goto == 5: - w_13 = space.cmp(w_v_4, w_w_4) - w_14 = w_13 - goto = 17 + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 if goto == 6: - w_15 = space.isinstance(w_v, gcls_instance) - v16 = space.is_true(w_15) - if v16 == True: - w_w_5, w_v_5 = w_w, w_v - goto = 7 - else: - assert v16 == False - w_w_6, w_v_6 = w_w, w_v - goto = 11 - - if goto == 7: - w_func = space.call_function(gfunc_instance_getattr1, w_v_5, gs___cmp__, space.w_False) - v18 = space.is_true(w_func) - if v18 == True: - w_w_7, w_func_1 = w_w_5, w_func - goto = 8 - else: - assert v18 == False - w_w_6, w_v_6 = w_w_5, w_v_5 - goto = 11 + w_13 = space.div(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 - if goto == 8: - w_res = space.call_function(w_func_1, w_w_7) - w_20 = space.isinstance(w_res, space.w_int) - v21 = space.is_true(w_20) - if v21 == True: - w_res_1 = w_res - goto = 9 - else: - assert v21 == False - w_etype, w_evalue = space.w_TypeError, gs___cmp___must_return_int - goto = 16 + if goto == 7: + return w_11 - if goto == 9: - w_24 = space.gt(w_res_1, gi_0) - v25 = space.is_true(w_24) - if v25 == True: - w_14 = gi_1 - goto = 17 - else: - assert v25 == False - w_res_2 = w_res_1 - goto = 10 +fastf_instance___div__ = __div__ - if goto == 10: - w_26 = space.lt(w_res_2, gi_0) - v27 = space.is_true(w_26) - if v27 == True: - w_14 = gi_minus_1 - goto = 17 - else: - assert v27 == False - w_14 = gi_0 - goto = 17 +##SECTION## +## filename '_classobj.py' +## function '__divmod__' +## firstlineno 404 +##SECTION## +def __divmod__(space, __args__): + funcname = "__divmod__" + signature = ['self', 'other'], None, None + defaults_w = [] + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___divmod__(space, w_self, w_other) - if goto == 11: - w_28 = space.isinstance(w_w_6, gcls_instance) - v29 = space.is_true(w_28) - if v29 == True: - w_v_7 = w_v_6 - goto = 12 - else: - assert v29 == False - w_14 = space.w_NotImplemented - goto = 17 +f_instance___divmod__ = __divmod__ - if goto == 12: - w_func_2 = space.call_function(gfunc_instance_getattr1, w_v_7, gs___cmp__, space.w_False) - v30 = space.is_true(w_func_2) - if v30 == True: - w_v_8, w_func_3 = w_v_7, w_func_2 - goto = 13 - else: - assert v30 == False - w_14 = space.w_NotImplemented - goto = 17 +def __divmod__(space, w_self, w_other): - if goto == 13: - w_res_3 = space.call_function(w_func_3, w_v_8) - w_31 = space.isinstance(w_res_3, space.w_int) - v32 = space.is_true(w_31) - if v32 == True: - w_res_4 = w_res_3 - goto = 14 + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 else: - assert v32 == False - w_etype, w_evalue = space.w_TypeError, gs___cmp___must_return_int - goto = 16 + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 - if goto == 14: - w_33 = space.gt(w_res_4, gi_0) - v34 = space.is_true(w_33) - if v34 == True: - w_14 = gi_1 - goto = 17 + if goto == 2: + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 + + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 else: - assert v34 == False - w_res_5 = w_res_4 - goto = 15 + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 - if goto == 15: - w_35 = space.lt(w_res_5, gi_0) - v36 = space.is_true(w_35) - if v36 == True: - w_14 = gi_minus_1 - goto = 17 + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___divmod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 else: - assert v36 == False - w_14 = gi_0 - goto = 17 + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 - if goto == 16: - raise OperationError(w_etype, w_evalue) + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 - if goto == 17: - return w_14 + if goto == 6: + w_13 = space.divmod(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 -fastf_instance___cmp__ = __cmp__ + if goto == 7: + return w_11 + +fastf_instance___divmod__ = __divmod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_classobj.py' -## function 'purify' -## firstlineno 571 +## filename '_classobj.py' +## function '__floordiv__' +## firstlineno 404 ##SECTION## -# global declarations -# global object g3tuple -# global object gcls_classobj -# global object gs___module__ -# global object gs__classobj -# global object gs___new__ -# global object gsm___new__ -# global object gfunc___new__ -# global object gs___slots__ -# global object g3tuple_1 -# global object gs__name -# global object gs__bases -# global object gs___dict__ -# global object gs_classobj -# global object gcls_instance -# global object gsm___new___1 -# global object gfunc___new___1 -# global object g2tuple -# global object gs__class -# global object gs_instance -# global object gfunc_purify - -def purify(space, __args__): - funcname = "purify" - signature = [], None, None +def __floordiv__(space, __args__): + funcname = "__floordiv__" + signature = ['self', 'other'], None, None defaults_w = [] - __args__.parse(funcname, signature, defaults_w) - return fastf_purify(space) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___floordiv__(space, w_self, w_other) -f_purify = purify +f_instance___floordiv__ = __floordiv__ -def purify(space): +def __floordiv__(space, w_self, w_other): - w_0=w_1=w_2=w_3=w_4=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.delattr(gcls_classobj, gs__name) - w_1 = space.delattr(gcls_classobj, gs__bases) - w_2 = space.delattr(gcls_classobj, gs___slots__) - w_3 = space.delattr(gcls_instance, gs__class) - w_4 = space.delattr(gcls_instance, gs___slots__) - w_5 = space.w_None - goto = 2 + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - return w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 -fastf_purify = purify + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -# global declarations -# global object gs___abs__ -# global object gfunc_instance___abs__ -# global object gs___add__ -# global object gfunc_instance___add__ -# global object gs___and__ -# global object gfunc_instance___and__ -# global object gs___call__ -# global object gfunc_instance___call__ -# global object gs___cmp__ -# global object gfunc_instance___cmp__ -# global object gs___coerce__ -# global object gfunc_instance___coerce__ -# global object gs___contains__ -# global object gfunc_instance___contains__ -# global object gs___delattr__ -# global object gfunc_instance___delattr__ -# global object gs___delitem__ -# global object gfunc_instance___delitem__ -# global object gs___div__ -# global object gfunc_instance___div__ -# global object gs___divmod__ -# global object gfunc_instance___divmod__ -# global object gs___eq__ -# global object gfunc_instance___eq__ -# global object gs___float__ -# global object gfunc_instance___float__ -# global object gs___floordiv__ -# global object gfunc_instance___floordiv__ -# global object gs___ge__ -# global object gfunc_instance___ge__ -# global object gs___getattribute__ -# global object gfunc_instance___getattribute__ -# global object gs___getitem__ -# global object gfunc_instance___getitem__ -# global object gs___gt__ -# global object gfunc_instance___gt__ -# global object gs___hash__ -# global object gfunc_instance___hash__ -# global object gs___hex__ -# global object gfunc_instance___hex__ -# global object gs___iadd__ -# global object gfunc_instance___iadd__ -# global object gs___iand__ -# global object gfunc_instance___iand__ -# global object gs___idiv__ -# global object gfunc_instance___idiv__ -# global object gs___ifloordiv__ -# global object gfunc_instance___ifloordiv__ -# global object gs___ilshift__ -# global object gfunc_instance___ilshift__ -# global object gs___imod__ -# global object gfunc_instance___imod__ -# global object gs___imul__ -# global object gfunc_instance___imul__ -# global object gs___int__ -# global object gfunc_instance___int__ -# global object gs___invert__ -# global object gfunc_instance___invert__ -# global object gs___ior__ -# global object gfunc_instance___ior__ -# global object gs___ipow__ -# global object gfunc_instance___ipow__ -# global object gs___irshift__ -# global object gfunc_instance___irshift__ -# global object gs___isub__ -# global object gfunc_instance___isub__ -# global object gs___iter__ -# global object gfunc_instance___iter__ -# global object gs___itruediv__ -# global object gfunc_instance___itruediv__ -# global object gs___ixor__ -# global object gfunc_instance___ixor__ -# global object gs___le__ -# global object gfunc_instance___le__ -# global object gs___len__ -# global object gfunc_instance___len__ -# global object gs___long__ -# global object gfunc_instance___long__ -# global object gs___lshift__ -# global object gfunc_instance___lshift__ -# global object gs___lt__ -# global object gfunc_instance___lt__ -# global object gs___mod__ -# global object gfunc_instance___mod__ -# global object gs___mul__ -# global object gfunc_instance___mul__ -# global object gs___ne__ -# global object gfunc_instance___ne__ -# global object gs___neg__ -# global object gfunc_instance___neg__ -# global object gs___nonzero__ -# global object gfunc_instance___nonzero__ -# global object gs___oct__ -# global object gfunc_instance___oct__ -# global object gs___or__ -# global object gfunc_instance___or__ -# global object gs___pos__ -# global object gfunc_instance___pos__ -# global object gs___pow__ -# global object gfunc_instance___pow__ -# global object gs___radd__ -# global object gfunc_instance___radd__ -# global object gs___rand__ -# global object gfunc_instance___rand__ -# global object gs___rdiv__ -# global object gfunc_instance___rdiv__ -# global object gs___rdivmod__ -# global object gfunc_instance___rdivmod__ -# global object gs___repr__ -# global object gfunc_instance___repr__ -# global object gs___rfloordiv__ -# global object gfunc_instance___rfloordiv__ -# global object gs___rlshift__ -# global object gfunc_instance___rlshift__ -# global object gs___rmod__ -# global object gfunc_instance___rmod__ -# global object gs___rmul__ -# global object gfunc_instance___rmul__ -# global object gs___ror__ -# global object gfunc_instance___ror__ -# global object gs___rpow__ -# global object gfunc_instance___rpow__ -# global object gs___rrshift__ -# global object gfunc_instance___rrshift__ -# global object gs___rshift__ -# global object gfunc_instance___rshift__ -# global object gs___rsub__ -# global object gfunc_instance___rsub__ -# global object gs___rtruediv__ -# global object gfunc_instance___rtruediv__ -# global object gs___rxor__ -# global object gfunc_instance___rxor__ -# global object gs___setattr__ -# global object gfunc_instance___setattr__ -# global object gs___setitem__ -# global object gfunc_instance___setitem__ -# global object gs___str__ -# global object gfunc_instance___str__ -# global object gs___sub__ -# global object gfunc_instance___sub__ -# global object gs___truediv__ -# global object gfunc_instance___truediv__ -# global object gs___xor__ -# global object gfunc_instance___xor__ -# global object gs_next -# global object gfunc_instance_next -# global object gfunc_classobj___call__ -# global object gfunc_classobj___delattr__ -# global object gfunc_classobj___getattribute__ -# global object gfunc_classobj___repr__ -# global object gfunc_classobj___setattr__ -# global object gfunc_classobj___str__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__abs__' -## firstlineno 4 -##SECTION## -def __abs__(space, __args__): - funcname = "__abs__" - signature = ['self'], None, None - defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___abs__(space, w_self) - -f_instance___abs__ = __abs__ - -def __abs__(space, w_self): - - w_0=w_2=w_3=None + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___floordiv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 - goto = 1 # startblock - while True: + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 - if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___abs__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + if goto == 6: + w_13 = space.floordiv(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 - if goto == 2: - return w_3 + if goto == 7: + return w_11 -fastf_instance___abs__ = __abs__ +fastf_instance___floordiv__ = __floordiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__add__' -## firstlineno 4 +## filename '_classobj.py' +## function '__lshift__' +## firstlineno 404 ##SECTION## -def __add__(space, __args__): - funcname = "__add__" +def __lshift__(space, __args__): + funcname = "__lshift__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___add__(space, w_self, w_other) + return fastf_instance___lshift__(space, w_self, w_other) -f_instance___add__ = __add__ +f_instance___lshift__ = __lshift__ -def __add__(space, w_self, w_other): +def __lshift__(space, w_self, w_other): w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None @@ -3954,7 +3691,7 @@ goto = 6 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___add__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___lshift__, space.w_False) v10 = space.is_true(w_func) if v10 == True: w_other_5, w_func_1 = w_other_3, w_func @@ -3970,30 +3707,30 @@ goto = 7 if goto == 6: - w_13 = space.add(w_self_4, w_other_4) + w_13 = space.lshift(w_self_4, w_other_4) w_11 = w_13 goto = 7 if goto == 7: return w_11 -fastf_instance___add__ = __add__ +fastf_instance___lshift__ = __lshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__and__' -## firstlineno 4 +## filename '_classobj.py' +## function '__mod__' +## firstlineno 404 ##SECTION## -def __and__(space, __args__): - funcname = "__and__" +def __mod__(space, __args__): + funcname = "__mod__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___and__(space, w_self, w_other) + return fastf_instance___mod__(space, w_self, w_other) -f_instance___and__ = __and__ +f_instance___mod__ = __mod__ -def __and__(space, w_self, w_other): +def __mod__(space, w_self, w_other): w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None @@ -4031,7 +3768,7 @@ goto = 6 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___and__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___mod__, space.w_False) v10 = space.is_true(w_func) if v10 == True: w_other_5, w_func_1 = w_other_3, w_func @@ -4047,30 +3784,30 @@ goto = 7 if goto == 6: - w_13 = space.and_(w_self_4, w_other_4) + w_13 = space.mod(w_self_4, w_other_4) w_11 = w_13 goto = 7 if goto == 7: return w_11 -fastf_instance___and__ = __and__ +fastf_instance___mod__ = __mod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__div__' -## firstlineno 4 +## filename '_classobj.py' +## function '__mul__' +## firstlineno 404 ##SECTION## -def __div__(space, __args__): - funcname = "__div__" +def __mul__(space, __args__): + funcname = "__mul__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___div__(space, w_self, w_other) + return fastf_instance___mul__(space, w_self, w_other) -f_instance___div__ = __div__ +f_instance___mul__ = __mul__ -def __div__(space, w_self, w_other): +def __mul__(space, w_self, w_other): w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None @@ -4108,7 +3845,7 @@ goto = 6 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___div__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___mul__, space.w_False) v10 = space.is_true(w_func) if v10 == True: w_other_5, w_func_1 = w_other_3, w_func @@ -4124,30 +3861,30 @@ goto = 7 if goto == 6: - w_13 = space.div(w_self_4, w_other_4) + w_13 = space.mul(w_self_4, w_other_4) w_11 = w_13 goto = 7 if goto == 7: return w_11 -fastf_instance___div__ = __div__ +fastf_instance___mul__ = __mul__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__divmod__' -## firstlineno 4 +## filename '_classobj.py' +## function '__or__' +## firstlineno 404 ##SECTION## -def __divmod__(space, __args__): - funcname = "__divmod__" +def __or__(space, __args__): + funcname = "__or__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___divmod__(space, w_self, w_other) + return fastf_instance___or__(space, w_self, w_other) -f_instance___divmod__ = __divmod__ +f_instance___or__ = __or__ -def __divmod__(space, w_self, w_other): +def __or__(space, w_self, w_other): w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None @@ -4185,7 +3922,7 @@ goto = 6 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___divmod__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___or__, space.w_False) v10 = space.is_true(w_func) if v10 == True: w_other_5, w_func_1 = w_other_3, w_func @@ -4201,137 +3938,107 @@ goto = 7 if goto == 6: - w_13 = space.divmod(w_self_4, w_other_4) + w_13 = space.or_(w_self_4, w_other_4) w_11 = w_13 goto = 7 if goto == 7: return w_11 -fastf_instance___divmod__ = __divmod__ +fastf_instance___or__ = __or__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__eq__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rshift__' +## firstlineno 404 ##SECTION## -def __eq__(space, __args__): - funcname = "__eq__" +def __rshift__(space, __args__): + funcname = "__rshift__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___eq__(space, w_self, w_other) + return fastf_instance___rshift__(space, w_self, w_other) -f_instance___eq__ = __eq__ +f_instance___rshift__ = __rshift__ -def __eq__(space, w_self, w_other): +def __rshift__(space, w_self, w_other): - w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None - w_9=v11=w_etype=w_evalue=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - try: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___eq__) - w_other_1, w_3 = w_other, w_0 + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced goto = 2 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen if goto == 2: - try: - w_7 = space.call_function(w_3, w_other_1) - w_8 = w_7 - goto = 6 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 if goto == 3: - w_9 = space.issubtype(w_10, space.w_AttributeError) - v11 = space.is_true(w_9) - if v11 == True: - w_8 = space.w_NotImplemented - goto = 6 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 else: - assert v11 == False - w_etype, w_evalue = w_12, w_14 - goto = 5 + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 if goto == 4: - w_16 = space.is_(w_6, space.w_AttributeError) - v17 = space.is_true(w_16) - if v17 == True: - w_8 = space.w_NotImplemented - goto = 6 + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 else: - assert v17 == False - w_12, w_14, w_10 = w_4, w_5, w_6 - goto = 3 - continue + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 if goto == 5: - raise OperationError(w_etype, w_evalue) + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 if goto == 6: - return w_8 - -fastf_instance___eq__ = __eq__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__float__' -## firstlineno 4 -##SECTION## -def __float__(space, __args__): - funcname = "__float__" - signature = ['self'], None, None - defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___float__(space, w_self) - -f_instance___float__ = __float__ - -def __float__(space, w_self): - - w_0=w_2=w_3=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___float__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_13 = space.rshift(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 - if goto == 2: - return w_3 + if goto == 7: + return w_11 -fastf_instance___float__ = __float__ +fastf_instance___rshift__ = __rshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__floordiv__' -## firstlineno 4 +## filename '_classobj.py' +## function '__sub__' +## firstlineno 404 ##SECTION## -def __floordiv__(space, __args__): - funcname = "__floordiv__" +def __sub__(space, __args__): + funcname = "__sub__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___floordiv__(space, w_self, w_other) + return fastf_instance___sub__(space, w_self, w_other) -f_instance___floordiv__ = __floordiv__ +f_instance___sub__ = __sub__ -def __floordiv__(space, w_self, w_other): +def __sub__(space, w_self, w_other): w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None @@ -4369,7 +4076,7 @@ goto = 6 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___floordiv__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___sub__, space.w_False) v10 = space.is_true(w_func) if v10 == True: w_other_5, w_func_1 = w_other_3, w_func @@ -4385,929 +4092,1111 @@ goto = 7 if goto == 6: - w_13 = space.floordiv(w_self_4, w_other_4) + w_13 = space.sub(w_self_4, w_other_4) w_11 = w_13 goto = 7 if goto == 7: return w_11 -fastf_instance___floordiv__ = __floordiv__ +fastf_instance___sub__ = __sub__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ge__' -## firstlineno 4 +## filename '_classobj.py' +## function '__truediv__' +## firstlineno 404 ##SECTION## -def __ge__(space, __args__): - funcname = "__ge__" +def __truediv__(space, __args__): + funcname = "__truediv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ge__(space, w_self, w_other) + return fastf_instance___truediv__(space, w_self, w_other) -f_instance___ge__ = __ge__ +f_instance___truediv__ = __truediv__ -def __ge__(space, w_self, w_other): +def __truediv__(space, w_self, w_other): - w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None - w_9=v11=w_etype=w_evalue=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - try: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___ge__) - w_other_1, w_3 = w_other, w_0 + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced goto = 2 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen if goto == 2: - try: - w_7 = space.call_function(w_3, w_other_1) - w_8 = w_7 - goto = 6 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 if goto == 3: - w_9 = space.issubtype(w_10, space.w_AttributeError) - v11 = space.is_true(w_9) - if v11 == True: - w_8 = space.w_NotImplemented - goto = 6 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 else: - assert v11 == False - w_etype, w_evalue = w_12, w_14 - goto = 5 + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 if goto == 4: - w_16 = space.is_(w_6, space.w_AttributeError) - v17 = space.is_true(w_16) - if v17 == True: - w_8 = space.w_NotImplemented - goto = 6 + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___truediv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 else: - assert v17 == False - w_12, w_14, w_10 = w_4, w_5, w_6 - goto = 3 - continue + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 if goto == 5: - raise OperationError(w_etype, w_evalue) + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 if goto == 6: - return w_8 + w_13 = space.truediv(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 -fastf_instance___ge__ = __ge__ + if goto == 7: + return w_11 + +fastf_instance___truediv__ = __truediv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__gt__' -## firstlineno 4 +## filename '_classobj.py' +## function '__xor__' +## firstlineno 404 ##SECTION## -def __gt__(space, __args__): - funcname = "__gt__" +# global declaration +# global object gfunc__coerce + +def __xor__(space, __args__): + funcname = "__xor__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___gt__(space, w_self, w_other) + return fastf_instance___xor__(space, w_self, w_other) -f_instance___gt__ = __gt__ +f_instance___xor__ = __xor__ -def __gt__(space, w_self, w_other): +def __xor__(space, w_self, w_other): - w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None - w_9=v11=w_etype=w_evalue=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - try: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___gt__) - w_other_1, w_3 = w_other, w_0 - goto = 2 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - try: - w_7 = space.call_function(w_3, w_other_1) - w_8 = w_7 - goto = 6 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 if goto == 3: - w_9 = space.issubtype(w_10, space.w_AttributeError) - v11 = space.is_true(w_9) - if v11 == True: - w_8 = space.w_NotImplemented - goto = 6 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 else: - assert v11 == False - w_etype, w_evalue = w_12, w_14 - goto = 5 + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 if goto == 4: - w_16 = space.is_(w_6, space.w_AttributeError) - v17 = space.is_true(w_16) - if v17 == True: - w_8 = space.w_NotImplemented - goto = 6 + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___xor__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 else: - assert v17 == False - w_12, w_14, w_10 = w_4, w_5, w_6 - goto = 3 - continue + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 if goto == 5: - raise OperationError(w_etype, w_evalue) + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 if goto == 6: - return w_8 + w_13 = space.xor(w_self_4, w_other_4) + w_11 = w_13 + goto = 7 -fastf_instance___gt__ = __gt__ + if goto == 7: + return w_11 + +fastf_instance___xor__ = __xor__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__hex__' -## firstlineno 4 +## filename '_classobj.py' +## function '__radd__' +## firstlineno 414 ##SECTION## -def __hex__(space, __args__): - funcname = "__hex__" - signature = ['self'], None, None +def __radd__(space, __args__): + funcname = "__radd__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___hex__(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___radd__(space, w_self, w_other) -f_instance___hex__ = __hex__ +f_instance___radd__ = __radd__ -def __hex__(space, w_self): +def __radd__(space, w_self, w_other): - w_0=w_2=w_3=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___hex__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - return w_3 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 -fastf_instance___hex__ = __hex__ + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 + + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___radd__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.add(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___radd__ = __radd__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__iadd__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rand__' +## firstlineno 414 ##SECTION## -def __iadd__(space, __args__): - funcname = "__iadd__" +def __rand__(space, __args__): + funcname = "__rand__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___iadd__(space, w_self, w_other) + return fastf_instance___rand__(space, w_self, w_other) -f_instance___iadd__ = __iadd__ +f_instance___rand__ = __rand__ -def __iadd__(space, w_self, w_other): +def __rand__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iadd__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___iadd__ = __iadd__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rand__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.and_(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rand__ = __rand__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__iand__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rdiv__' +## firstlineno 414 ##SECTION## -def __iand__(space, __args__): - funcname = "__iand__" +def __rdiv__(space, __args__): + funcname = "__rdiv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___iand__(space, w_self, w_other) + return fastf_instance___rdiv__(space, w_self, w_other) -f_instance___iand__ = __iand__ +f_instance___rdiv__ = __rdiv__ -def __iand__(space, w_self, w_other): +def __rdiv__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iand__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 - -fastf_instance___iand__ = __iand__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__idiv__' -## firstlineno 4 -##SECTION## -def __idiv__(space, __args__): - funcname = "__idiv__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___idiv__(space, w_self, w_other) - -f_instance___idiv__ = __idiv__ - -def __idiv__(space, w_self, w_other): - - w_func=v2=w_4=w_other_1=w_func_1=w_5=None - - goto = 1 # startblock - while True: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 - if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___idiv__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rdiv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 else: - assert v2 == False - w_4 = space.w_NotImplemented - goto = 3 + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 - if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 - goto = 3 + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 - if goto == 3: - return w_4 + if goto == 6: + w_13 = space.div(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 -fastf_instance___idiv__ = __idiv__ + if goto == 7: + return w_11 + +fastf_instance___rdiv__ = __rdiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ifloordiv__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rdivmod__' +## firstlineno 414 ##SECTION## -def __ifloordiv__(space, __args__): - funcname = "__ifloordiv__" +def __rdivmod__(space, __args__): + funcname = "__rdivmod__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ifloordiv__(space, w_self, w_other) + return fastf_instance___rdivmod__(space, w_self, w_other) -f_instance___ifloordiv__ = __ifloordiv__ +f_instance___rdivmod__ = __rdivmod__ -def __ifloordiv__(space, w_self, w_other): +def __rdivmod__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ifloordiv__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___ifloordiv__ = __ifloordiv__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rdivmod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.divmod(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rdivmod__ = __rdivmod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ilshift__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rfloordiv__' +## firstlineno 414 ##SECTION## -def __ilshift__(space, __args__): - funcname = "__ilshift__" +def __rfloordiv__(space, __args__): + funcname = "__rfloordiv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ilshift__(space, w_self, w_other) + return fastf_instance___rfloordiv__(space, w_self, w_other) -f_instance___ilshift__ = __ilshift__ +f_instance___rfloordiv__ = __rfloordiv__ -def __ilshift__(space, w_self, w_other): +def __rfloordiv__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ilshift__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___ilshift__ = __ilshift__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rfloordiv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.floordiv(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rfloordiv__ = __rfloordiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__imod__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rlshift__' +## firstlineno 414 ##SECTION## -def __imod__(space, __args__): - funcname = "__imod__" +def __rlshift__(space, __args__): + funcname = "__rlshift__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___imod__(space, w_self, w_other) + return fastf_instance___rlshift__(space, w_self, w_other) -f_instance___imod__ = __imod__ +f_instance___rlshift__ = __rlshift__ -def __imod__(space, w_self, w_other): +def __rlshift__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___imod__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 - -fastf_instance___imod__ = __imod__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__imul__' -## firstlineno 4 -##SECTION## -def __imul__(space, __args__): - funcname = "__imul__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___imul__(space, w_self, w_other) - -f_instance___imul__ = __imul__ - -def __imul__(space, w_self, w_other): - - w_func=v2=w_4=w_other_1=w_func_1=w_5=None - - goto = 1 # startblock - while True: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 - if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___imul__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rlshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 else: - assert v2 == False - w_4 = space.w_NotImplemented - goto = 3 + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 - if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 - goto = 3 + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 - if goto == 3: - return w_4 + if goto == 6: + w_13 = space.lshift(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 -fastf_instance___imul__ = __imul__ + if goto == 7: + return w_11 + +fastf_instance___rlshift__ = __rlshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__int__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rmod__' +## firstlineno 414 ##SECTION## -def __int__(space, __args__): - funcname = "__int__" - signature = ['self'], None, None +def __rmod__(space, __args__): + funcname = "__rmod__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___int__(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rmod__(space, w_self, w_other) -f_instance___int__ = __int__ +f_instance___rmod__ = __rmod__ -def __int__(space, w_self): +def __rmod__(space, w_self, w_other): - w_0=w_2=w_3=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___int__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - return w_3 - -fastf_instance___int__ = __int__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__invert__' -## firstlineno 4 -##SECTION## -def __invert__(space, __args__): - funcname = "__invert__" - signature = ['self'], None, None - defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___invert__(space, w_self) - -f_instance___invert__ = __invert__ + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + goto = 3 -def __invert__(space, w_self): + if goto == 3: + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 - w_0=w_2=w_3=None + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rmod__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 - goto = 1 # startblock - while True: + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 - if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___invert__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + if goto == 6: + w_13 = space.mod(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 - if goto == 2: - return w_3 + if goto == 7: + return w_11 -fastf_instance___invert__ = __invert__ +fastf_instance___rmod__ = __rmod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ior__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rmul__' +## firstlineno 414 ##SECTION## -def __ior__(space, __args__): - funcname = "__ior__" +def __rmul__(space, __args__): + funcname = "__rmul__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ior__(space, w_self, w_other) + return fastf_instance___rmul__(space, w_self, w_other) -f_instance___ior__ = __ior__ +f_instance___rmul__ = __rmul__ -def __ior__(space, w_self, w_other): +def __rmul__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ior__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___ior__ = __ior__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rmul__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.mul(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rmul__ = __rmul__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ipow__' -## firstlineno 4 +## filename '_classobj.py' +## function '__ror__' +## firstlineno 414 ##SECTION## -def __ipow__(space, __args__): - funcname = "__ipow__" +def __ror__(space, __args__): + funcname = "__ror__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ipow__(space, w_self, w_other) + return fastf_instance___ror__(space, w_self, w_other) -f_instance___ipow__ = __ipow__ +f_instance___ror__ = __ror__ -def __ipow__(space, w_self, w_other): +def __ror__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ipow__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + goto = 3 else: - assert v2 == False - w_4 = space.w_NotImplemented - goto = 3 + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___ipow__ = __ipow__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___ror__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.or_(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___ror__ = __ror__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__irshift__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rrshift__' +## firstlineno 414 ##SECTION## -def __irshift__(space, __args__): - funcname = "__irshift__" +def __rrshift__(space, __args__): + funcname = "__rrshift__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___irshift__(space, w_self, w_other) + return fastf_instance___rrshift__(space, w_self, w_other) -f_instance___irshift__ = __irshift__ +f_instance___rrshift__ = __rrshift__ -def __irshift__(space, w_self, w_other): +def __rrshift__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___irshift__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___irshift__ = __irshift__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rrshift__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.rshift(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rrshift__ = __rrshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__isub__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rsub__' +## firstlineno 414 ##SECTION## -def __isub__(space, __args__): - funcname = "__isub__" +def __rsub__(space, __args__): + funcname = "__rsub__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___isub__(space, w_self, w_other) + return fastf_instance___rsub__(space, w_self, w_other) -f_instance___isub__ = __isub__ +f_instance___rsub__ = __rsub__ -def __isub__(space, w_self, w_other): +def __rsub__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___isub__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___isub__ = __isub__ + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rsub__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 + + if goto == 5: + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 + + if goto == 6: + w_13 = space.sub(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 + + if goto == 7: + return w_11 + +fastf_instance___rsub__ = __rsub__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__itruediv__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rtruediv__' +## firstlineno 414 ##SECTION## -def __itruediv__(space, __args__): - funcname = "__itruediv__" +def __rtruediv__(space, __args__): + funcname = "__rtruediv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___itruediv__(space, w_self, w_other) + return fastf_instance___rtruediv__(space, w_self, w_other) -f_instance___itruediv__ = __itruediv__ +f_instance___rtruediv__ = __rtruediv__ -def __itruediv__(space, w_self, w_other): +def __rtruediv__(space, w_self, w_other): - w_func=v2=w_4=w_other_1=w_func_1=w_5=None + w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None + w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None + w_func=v10=w_other_5=w_func_1=w_12=None goto = 1 # startblock while True: if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___itruediv__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented + w_coerced = fastf__coerce(space, w_self, w_other) + w_3 = space.is_(w_coerced, space.w_None) + v4 = space.is_true(w_3) + if v4 == True: + w_self_1, w_other_1, w_5 = w_self, w_other, w_3 goto = 3 + else: + assert v4 == False + w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + goto = 2 if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 + w_6 = space.getitem(w_coerced_1, gi_0) + w_7 = space.is_(w_6, w_self_2) + w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 goto = 3 if goto == 3: - return w_4 + v8 = space.is_true(w_5) + if v8 == True: + w_self_3, w_other_3 = w_self_1, w_other_1 + goto = 4 + else: + assert v8 == False + w_self_4, w_other_4 = w_self_1, w_other_1 + goto = 6 -fastf_instance___itruediv__ = __itruediv__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ixor__' -## firstlineno 4 -##SECTION## -def __ixor__(space, __args__): - funcname = "__ixor__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ixor__(space, w_self, w_other) - -f_instance___ixor__ = __ixor__ - -def __ixor__(space, w_self, w_other): - - w_func=v2=w_4=w_other_1=w_func_1=w_5=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ixor__, space.w_False) - v2 = space.is_true(w_func) - if v2 == True: - w_other_1, w_func_1 = w_other, w_func - goto = 2 - else: - assert v2 == False - w_4 = space.w_NotImplemented - goto = 3 - - if goto == 2: - w_5 = space.call_function(w_func_1, w_other_1) - w_4 = w_5 - goto = 3 - - if goto == 3: - return w_4 - -fastf_instance___ixor__ = __ixor__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__le__' -## firstlineno 4 -##SECTION## -def __le__(space, __args__): - funcname = "__le__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___le__(space, w_self, w_other) - -f_instance___le__ = __le__ - -def __le__(space, w_self, w_other): - - w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None - w_9=v11=w_etype=w_evalue=None - - goto = 1 # startblock - while True: - - if goto == 1: - try: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___le__) - w_other_1, w_3 = w_other, w_0 - goto = 2 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen - - if goto == 2: - try: - w_7 = space.call_function(w_3, w_other_1) - w_8 = w_7 - goto = 6 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen - - if goto == 3: - w_9 = space.issubtype(w_10, space.w_AttributeError) - v11 = space.is_true(w_9) - if v11 == True: - w_8 = space.w_NotImplemented - goto = 6 - else: - assert v11 == False - w_etype, w_evalue = w_12, w_14 - goto = 5 - - if goto == 4: - w_16 = space.is_(w_6, space.w_AttributeError) - v17 = space.is_true(w_16) - if v17 == True: - w_8 = space.w_NotImplemented - goto = 6 - else: - assert v17 == False - w_12, w_14, w_10 = w_4, w_5, w_6 - goto = 3 - continue + if goto == 4: + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rtruediv__, space.w_False) + v10 = space.is_true(w_func) + if v10 == True: + w_other_5, w_func_1 = w_other_3, w_func + goto = 5 + else: + assert v10 == False + w_11 = space.w_NotImplemented + goto = 7 if goto == 5: - raise OperationError(w_etype, w_evalue) + w_12 = space.call_function(w_func_1, w_other_5) + w_11 = w_12 + goto = 7 if goto == 6: - return w_8 - -fastf_instance___le__ = __le__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__long__' -## firstlineno 4 -##SECTION## -def __long__(space, __args__): - funcname = "__long__" - signature = ['self'], None, None - defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___long__(space, w_self) - -f_instance___long__ = __long__ - -def __long__(space, w_self): - - w_0=w_2=w_3=None - - goto = 1 # startblock - while True: - - if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___long__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_13 = space.truediv(w_other_4, w_self_4) + w_11 = w_13 + goto = 7 - if goto == 2: - return w_3 + if goto == 7: + return w_11 -fastf_instance___long__ = __long__ +fastf_instance___rtruediv__ = __rtruediv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__lshift__' -## firstlineno 4 +## filename '_classobj.py' +## function '__rxor__' +## firstlineno 414 ##SECTION## -def __lshift__(space, __args__): - funcname = "__lshift__" +def __rxor__(space, __args__): + funcname = "__rxor__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___lshift__(space, w_self, w_other) + return fastf_instance___rxor__(space, w_self, w_other) -f_instance___lshift__ = __lshift__ +f_instance___rxor__ = __rxor__ -def __lshift__(space, w_self, w_other): +def __rxor__(space, w_self, w_other): w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None @@ -5345,7 +5234,7 @@ goto = 6 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___lshift__, space.w_False) + w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rxor__, space.w_False) v10 = space.is_true(w_func) if v10 == True: w_other_5, w_func_1 = w_other_3, w_func @@ -5361,1746 +5250,1528 @@ goto = 7 if goto == 6: - w_13 = space.lshift(w_self_4, w_other_4) + w_13 = space.xor(w_other_4, w_self_4) w_11 = w_13 goto = 7 if goto == 7: return w_11 -fastf_instance___lshift__ = __lshift__ +fastf_instance___rxor__ = __rxor__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__lt__' -## firstlineno 4 +## filename '_classobj.py' +## function '__iadd__' +## firstlineno 432 ##SECTION## -def __lt__(space, __args__): - funcname = "__lt__" +def __iadd__(space, __args__): + funcname = "__iadd__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___lt__(space, w_self, w_other) + return fastf_instance___iadd__(space, w_self, w_other) -f_instance___lt__ = __lt__ +f_instance___iadd__ = __iadd__ -def __lt__(space, w_self, w_other): +def __iadd__(space, w_self, w_other): - w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None - w_9=v11=w_etype=w_evalue=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - try: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___lt__) - w_other_1, w_3 = w_other, w_0 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iadd__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen - - if goto == 2: - try: - w_7 = space.call_function(w_3, w_other_1) - w_8 = w_7 - goto = 6 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen - - if goto == 3: - w_9 = space.issubtype(w_10, space.w_AttributeError) - v11 = space.is_true(w_9) - if v11 == True: - w_8 = space.w_NotImplemented - goto = 6 - else: - assert v11 == False - w_etype, w_evalue = w_12, w_14 - goto = 5 - - if goto == 4: - w_16 = space.is_(w_6, space.w_AttributeError) - v17 = space.is_true(w_16) - if v17 == True: - w_8 = space.w_NotImplemented - goto = 6 else: - assert v17 == False - w_12, w_14, w_10 = w_4, w_5, w_6 + assert v2 == False + w_4 = space.w_NotImplemented goto = 3 - continue - if goto == 5: - raise OperationError(w_etype, w_evalue) + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 - if goto == 6: - return w_8 + if goto == 3: + return w_4 -fastf_instance___lt__ = __lt__ +fastf_instance___iadd__ = __iadd__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__mod__' -## firstlineno 4 +## filename '_classobj.py' +## function '__iand__' +## firstlineno 432 ##SECTION## -def __mod__(space, __args__): - funcname = "__mod__" +def __iand__(space, __args__): + funcname = "__iand__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___mod__(space, w_self, w_other) + return fastf_instance___iand__(space, w_self, w_other) -f_instance___mod__ = __mod__ +f_instance___iand__ = __iand__ -def __mod__(space, w_self, w_other): +def __iand__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced - goto = 2 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iand__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___mod__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.mod(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_4 -fastf_instance___mod__ = __mod__ +fastf_instance___iand__ = __iand__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__mul__' -## firstlineno 4 +## filename '_classobj.py' +## function '__idiv__' +## firstlineno 432 ##SECTION## -def __mul__(space, __args__): - funcname = "__mul__" +def __idiv__(space, __args__): + funcname = "__idiv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___mul__(space, w_self, w_other) + return fastf_instance___idiv__(space, w_self, w_other) -f_instance___mul__ = __mul__ +f_instance___idiv__ = __idiv__ -def __mul__(space, w_self, w_other): +def __idiv__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___idiv__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___mul__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.mul(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_4 -fastf_instance___mul__ = __mul__ +fastf_instance___idiv__ = __idiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ne__' -## firstlineno 4 +## filename '_classobj.py' +## function '__ifloordiv__' +## firstlineno 432 ##SECTION## -def __ne__(space, __args__): - funcname = "__ne__" +def __ifloordiv__(space, __args__): + funcname = "__ifloordiv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ne__(space, w_self, w_other) + return fastf_instance___ifloordiv__(space, w_self, w_other) -f_instance___ne__ = __ne__ +f_instance___ifloordiv__ = __ifloordiv__ -def __ne__(space, w_self, w_other): +def __ifloordiv__(space, w_self, w_other): - w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None - w_9=v11=w_etype=w_evalue=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - try: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___ne__) - w_other_1, w_3 = w_other, w_0 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ifloordiv__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen - - if goto == 2: - try: - w_7 = space.call_function(w_3, w_other_1) - w_8 = w_7 - goto = 6 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 4 - else:raise # unhandled case, should not happen - - if goto == 3: - w_9 = space.issubtype(w_10, space.w_AttributeError) - v11 = space.is_true(w_9) - if v11 == True: - w_8 = space.w_NotImplemented - goto = 6 - else: - assert v11 == False - w_etype, w_evalue = w_12, w_14 - goto = 5 - - if goto == 4: - w_16 = space.is_(w_6, space.w_AttributeError) - v17 = space.is_true(w_16) - if v17 == True: - w_8 = space.w_NotImplemented - goto = 6 else: - assert v17 == False - w_12, w_14, w_10 = w_4, w_5, w_6 + assert v2 == False + w_4 = space.w_NotImplemented goto = 3 - continue - if goto == 5: - raise OperationError(w_etype, w_evalue) + if goto == 2: + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 - if goto == 6: - return w_8 + if goto == 3: + return w_4 -fastf_instance___ne__ = __ne__ +fastf_instance___ifloordiv__ = __ifloordiv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__neg__' -## firstlineno 4 +## filename '_classobj.py' +## function '__ilshift__' +## firstlineno 432 ##SECTION## -def __neg__(space, __args__): - funcname = "__neg__" - signature = ['self'], None, None +def __ilshift__(space, __args__): + funcname = "__ilshift__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___neg__(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ilshift__(space, w_self, w_other) -f_instance___neg__ = __neg__ +f_instance___ilshift__ = __ilshift__ -def __neg__(space, w_self): +def __ilshift__(space, w_self, w_other): - w_0=w_2=w_3=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___neg__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ilshift__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - return w_3 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 -fastf_instance___neg__ = __neg__ + if goto == 3: + return w_4 + +fastf_instance___ilshift__ = __ilshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__oct__' -## firstlineno 4 +## filename '_classobj.py' +## function '__imod__' +## firstlineno 432 ##SECTION## -def __oct__(space, __args__): - funcname = "__oct__" - signature = ['self'], None, None +def __imod__(space, __args__): + funcname = "__imod__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___oct__(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___imod__(space, w_self, w_other) -f_instance___oct__ = __oct__ +f_instance___imod__ = __imod__ -def __oct__(space, w_self): +def __imod__(space, w_self, w_other): - w_0=w_2=w_3=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___oct__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___imod__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - return w_3 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 -fastf_instance___oct__ = __oct__ + if goto == 3: + return w_4 + +fastf_instance___imod__ = __imod__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__or__' -## firstlineno 4 +## filename '_classobj.py' +## function '__imul__' +## firstlineno 432 ##SECTION## -def __or__(space, __args__): - funcname = "__or__" +def __imul__(space, __args__): + funcname = "__imul__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___or__(space, w_self, w_other) + return fastf_instance___imul__(space, w_self, w_other) -f_instance___or__ = __or__ +f_instance___imul__ = __imul__ -def __or__(space, w_self, w_other): +def __imul__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___imul__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___or__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.or_(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_4 -fastf_instance___or__ = __or__ +fastf_instance___imul__ = __imul__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__pos__' -## firstlineno 4 +## filename '_classobj.py' +## function '__ior__' +## firstlineno 432 ##SECTION## -def __pos__(space, __args__): - funcname = "__pos__" - signature = ['self'], None, None +def __ior__(space, __args__): + funcname = "__ior__" + signature = ['self', 'other'], None, None defaults_w = [] - w_self, = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___pos__(space, w_self) + w_self, w_other = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___ior__(space, w_self, w_other) -f_instance___pos__ = __pos__ +f_instance___ior__ = __ior__ -def __pos__(space, w_self): +def __ior__(space, w_self, w_other): - w_0=w_2=w_3=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___pos__) - w_2 = space.call_function(w_0, ) - w_3 = w_2 - goto = 2 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ior__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func + goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - return w_3 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 + goto = 3 -fastf_instance___pos__ = __pos__ + if goto == 3: + return w_4 + +fastf_instance___ior__ = __ior__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rshift__' -## firstlineno 4 +## filename '_classobj.py' +## function '__ipow__' +## firstlineno 432 ##SECTION## -def __rshift__(space, __args__): - funcname = "__rshift__" +def __ipow__(space, __args__): + funcname = "__ipow__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rshift__(space, w_self, w_other) + return fastf_instance___ipow__(space, w_self, w_other) -f_instance___rshift__ = __rshift__ +f_instance___ipow__ = __ipow__ -def __rshift__(space, w_self, w_other): +def __ipow__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ipow__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rshift__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.rshift(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_4 -fastf_instance___rshift__ = __rshift__ +fastf_instance___ipow__ = __ipow__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__sub__' -## firstlineno 4 +## filename '_classobj.py' +## function '__irshift__' +## firstlineno 432 ##SECTION## -def __sub__(space, __args__): - funcname = "__sub__" +def __irshift__(space, __args__): + funcname = "__irshift__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___sub__(space, w_self, w_other) + return fastf_instance___irshift__(space, w_self, w_other) -f_instance___sub__ = __sub__ +f_instance___irshift__ = __irshift__ -def __sub__(space, w_self, w_other): +def __irshift__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___irshift__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 + return w_4 - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___sub__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.sub(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 - -fastf_instance___sub__ = __sub__ +fastf_instance___irshift__ = __irshift__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__truediv__' -## firstlineno 4 +## filename '_classobj.py' +## function '__isub__' +## firstlineno 432 ##SECTION## -def __truediv__(space, __args__): - funcname = "__truediv__" +def __isub__(space, __args__): + funcname = "__isub__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___truediv__(space, w_self, w_other) + return fastf_instance___isub__(space, w_self, w_other) -f_instance___truediv__ = __truediv__ +f_instance___isub__ = __isub__ -def __truediv__(space, w_self, w_other): +def __isub__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___isub__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___truediv__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.truediv(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_4 -fastf_instance___truediv__ = __truediv__ +fastf_instance___isub__ = __isub__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__xor__' -## firstlineno 4 +## filename '_classobj.py' +## function '__itruediv__' +## firstlineno 432 ##SECTION## -# global declaration -# global object gfunc__coerce - -def __xor__(space, __args__): - funcname = "__xor__" +def __itruediv__(space, __args__): + funcname = "__itruediv__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___xor__(space, w_self, w_other) + return fastf_instance___itruediv__(space, w_self, w_other) -f_instance___xor__ = __xor__ +f_instance___itruediv__ = __itruediv__ -def __xor__(space, w_self, w_other): +def __itruediv__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___itruediv__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___xor__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.xor(w_self_4, w_other_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_4 -fastf_instance___xor__ = __xor__ +fastf_instance___itruediv__ = __itruediv__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__radd__' -## firstlineno 14 +## filename '_classobj.py' +## function '__ixor__' +## firstlineno 432 ##SECTION## -def __radd__(space, __args__): - funcname = "__radd__" +def __ixor__(space, __args__): + funcname = "__ixor__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___radd__(space, w_self, w_other) + return fastf_instance___ixor__(space, w_self, w_other) -f_instance___radd__ = __radd__ +f_instance___ixor__ = __ixor__ -def __radd__(space, w_self, w_other): +def __ixor__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_4=w_other_1=w_func_1=w_5=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___ixor__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_other_1, w_func_1 = w_other, w_func goto = 2 + else: + assert v2 == False + w_4 = space.w_NotImplemented + goto = 3 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 + w_5 = space.call_function(w_func_1, w_other_1) + w_4 = w_5 goto = 3 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___radd__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + return w_4 - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 +fastf_instance___ixor__ = __ixor__ - if goto == 6: - w_13 = space.add(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 +##SECTION## +## filename '_classobj.py' +## function '__pow__' +## firstlineno 441 +##SECTION## +def __pow__(space, __args__): + funcname = "__pow__" + signature = ['self', 'other', 'modulo'], None, None + defaults_w = [space.w_None] + w_self, w_other, w_modulo = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___pow__(space, w_self, w_other, w_modulo) - if goto == 7: - return w_11 +f_instance___pow__ = __pow__ -fastf_instance___radd__ = __radd__ +def __pow__(space, w_self, w_other, w_modulo): -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rand__' -## firstlineno 14 -##SECTION## -def __rand__(space, __args__): - funcname = "__rand__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rand__(space, w_self, w_other) - -f_instance___rand__ = __rand__ - -def __rand__(space, w_self, w_other): - - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=v2=w_self_2=w_other_2=w_modulo_1=w_func_2=v17=w_14=w_other_8=None + w_modulo_2=w_func_3=w_18=w_self_1=w_other_1=w_coerced=w_6=v7=None + w_self_4=w_other_4=w_coerced_1=w_9=w_10=w_self_3=w_other_3=w_8=None + v11=w_self_6=w_other_6=w_16=w_self_5=w_other_5=w_func=v13=w_other_7=None + w_func_1=w_15=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_0 = space.is_(w_modulo, space.w_None) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_other_1 = w_self, w_other goto = 2 + else: + assert v2 == False + w_self_2, w_other_2, w_modulo_1 = w_self, w_other, w_modulo + goto = 8 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 - - if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 + w_coerced = fastf__coerce(space, w_self_1, w_other_1) + w_6 = space.is_(w_coerced, space.w_None) + v7 = space.is_true(w_6) + if v7 == True: + w_self_3, w_other_3, w_8 = w_self_1, w_other_1, w_6 goto = 4 else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 + assert v7 == False + w_self_4, w_other_4, w_coerced_1 = w_self_1, w_other_1, w_coerced + goto = 3 + + if goto == 3: + w_9 = space.getitem(w_coerced_1, gi_0) + w_10 = space.is_(w_9, w_self_4) + w_self_3, w_other_3, w_8 = w_self_4, w_other_4, w_10 + goto = 4 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rand__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func + v11 = space.is_true(w_8) + if v11 == True: + w_self_5, w_other_5 = w_self_3, w_other_3 goto = 5 else: - assert v10 == False - w_11 = space.w_NotImplemented + assert v11 == False + w_self_6, w_other_6 = w_self_3, w_other_3 goto = 7 if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + w_func = space.call_function(gfunc_instance_getattr1, w_self_5, gs___pow__, space.w_False) + v13 = space.is_true(w_func) + if v13 == True: + w_other_7, w_func_1 = w_other_5, w_func + goto = 6 + else: + assert v13 == False + w_14 = space.w_NotImplemented + goto = 10 if goto == 6: - w_13 = space.and_(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 + w_15 = space.call_function(w_func_1, w_other_7) + w_14 = w_15 + goto = 10 if goto == 7: - return w_11 + w_16 = space.pow(w_self_6, w_other_6) + w_14 = w_16 + goto = 10 -fastf_instance___rand__ = __rand__ + if goto == 8: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_2, gs___pow__, space.w_False) + v17 = space.is_true(w_func_2) + if v17 == True: + w_other_8, w_modulo_2, w_func_3 = w_other_2, w_modulo_1, w_func_2 + goto = 9 + else: + assert v17 == False + w_14 = space.w_NotImplemented + goto = 10 + + if goto == 9: + w_18 = space.call_function(w_func_3, w_other_8, w_modulo_2) + w_14 = w_18 + goto = 10 + + if goto == 10: + return w_14 + +fastf_instance___pow__ = __pow__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rdiv__' -## firstlineno 14 +## filename '_classobj.py' +## function '__rpow__' +## firstlineno 459 ##SECTION## -def __rdiv__(space, __args__): - funcname = "__rdiv__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rdiv__(space, w_self, w_other) +def __rpow__(space, __args__): + funcname = "__rpow__" + signature = ['self', 'other', 'modulo'], None, None + defaults_w = [space.w_None] + w_self, w_other, w_modulo = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___rpow__(space, w_self, w_other, w_modulo) -f_instance___rdiv__ = __rdiv__ +f_instance___rpow__ = __rpow__ -def __rdiv__(space, w_self, w_other): +def __rpow__(space, w_self, w_other, w_modulo): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=v2=w_self_2=w_other_2=w_modulo_1=w_func_2=v17=w_14=w_other_8=None + w_modulo_2=w_func_3=w_18=w_self_1=w_other_1=w_coerced=w_6=v7=None + w_self_4=w_other_4=w_coerced_1=w_9=w_10=w_self_3=w_other_3=w_8=None + v11=w_self_6=w_other_6=w_16=w_self_5=w_other_5=w_func=v13=w_other_7=None + w_func_1=w_15=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_0 = space.is_(w_modulo, space.w_None) + v2 = space.is_true(w_0) + if v2 == True: + w_self_1, w_other_1 = w_self, w_other goto = 2 + else: + assert v2 == False + w_self_2, w_other_2, w_modulo_1 = w_self, w_other, w_modulo + goto = 8 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 - - if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 + w_coerced = fastf__coerce(space, w_self_1, w_other_1) + w_6 = space.is_(w_coerced, space.w_None) + v7 = space.is_true(w_6) + if v7 == True: + w_self_3, w_other_3, w_8 = w_self_1, w_other_1, w_6 goto = 4 else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 + assert v7 == False + w_self_4, w_other_4, w_coerced_1 = w_self_1, w_other_1, w_coerced + goto = 3 + + if goto == 3: + w_9 = space.getitem(w_coerced_1, gi_0) + w_10 = space.is_(w_9, w_self_4) + w_self_3, w_other_3, w_8 = w_self_4, w_other_4, w_10 + goto = 4 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rdiv__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func + v11 = space.is_true(w_8) + if v11 == True: + w_self_5, w_other_5 = w_self_3, w_other_3 goto = 5 else: - assert v10 == False - w_11 = space.w_NotImplemented + assert v11 == False + w_self_6, w_other_6 = w_self_3, w_other_3 goto = 7 if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + w_func = space.call_function(gfunc_instance_getattr1, w_self_5, gs___rpow__, space.w_False) + v13 = space.is_true(w_func) + if v13 == True: + w_other_7, w_func_1 = w_other_5, w_func + goto = 6 + else: + assert v13 == False + w_14 = space.w_NotImplemented + goto = 10 if goto == 6: - w_13 = space.div(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 + w_15 = space.call_function(w_func_1, w_other_7) + w_14 = w_15 + goto = 10 if goto == 7: - return w_11 - -fastf_instance___rdiv__ = __rdiv__ - -##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rdivmod__' -## firstlineno 14 -##SECTION## -def __rdivmod__(space, __args__): - funcname = "__rdivmod__" - signature = ['self', 'other'], None, None - defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rdivmod__(space, w_self, w_other) + w_16 = space.pow(w_other_6, w_self_6) + w_14 = w_16 + goto = 10 -f_instance___rdivmod__ = __rdivmod__ + if goto == 8: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_2, gs___rpow__, space.w_False) + v17 = space.is_true(w_func_2) + if v17 == True: + w_other_8, w_modulo_2, w_func_3 = w_other_2, w_modulo_1, w_func_2 + goto = 9 + else: + assert v17 == False + w_14 = space.w_NotImplemented + goto = 10 -def __rdivmod__(space, w_self, w_other): + if goto == 9: + w_18 = space.call_function(w_func_3, w_other_8, w_modulo_2) + w_14 = w_18 + goto = 10 - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + if goto == 10: + return w_14 - goto = 1 # startblock - while True: - - if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced - goto = 2 - - if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 - - if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 - - if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rdivmod__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 - - if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.divmod(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 - -fastf_instance___rdivmod__ = __rdivmod__ +fastf_instance___rpow__ = __rpow__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rfloordiv__' -## firstlineno 14 +## filename '_classobj.py' +## function '__nonzero__' +## firstlineno 477 ##SECTION## -def __rfloordiv__(space, __args__): - funcname = "__rfloordiv__" - signature = ['self', 'other'], None, None +# global declarations +# global object gs___nonzero_____should_return____0 +# global object gs___nonzero_____should_return_an_i + +def __nonzero__(space, __args__): + funcname = "__nonzero__" + signature = ['self'], None, None defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rfloordiv__(space, w_self, w_other) + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___nonzero__(space, w_self) -f_instance___rfloordiv__ = __rfloordiv__ +f_instance___nonzero__ = __nonzero__ -def __rfloordiv__(space, w_self, w_other): +def __nonzero__(space, w_self): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_self_1=w_func_2=v3=w_4=w_func_1=w_ret=w_6=v7=w_14=None + w_etype=w_evalue=w_ret_1=w_8=v9=w_ret_2=w_13=w_10=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___nonzero__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_func_1 = w_func goto = 3 else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + assert v2 == False + w_self_1 = w_self goto = 2 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___nonzero__, space.w_False) + v3 = space.is_true(w_func_2) + if v3 == True: + w_func_1 = w_func_2 + goto = 3 + else: + assert v3 == False + w_4 = space.w_True + goto = 9 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 + w_ret = space.call_function(w_func_1, ) + w_6 = space.isinstance(w_ret, space.w_int) + v7 = space.is_true(w_6) + if v7 == True: + w_ret_1 = w_ret goto = 4 else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 + assert v7 == False + goto = 7 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rfloordiv__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func + w_8 = space.lt(w_ret_1, gi_0) + v9 = space.is_true(w_8) + if v9 == True: goto = 5 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v9 == False + w_ret_2 = w_ret_1 + goto = 6 if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + w_10 = space.call_function(space.w_ValueError, gs___nonzero_____should_return____0) + w_etype, w_evalue = space.w_ValueError, w_10 + goto = 8 if goto == 6: - w_13 = space.floordiv(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 + w_13 = space.gt(w_ret_2, gi_0) + w_4 = w_13 + goto = 9 if goto == 7: - return w_11 + w_14 = space.call_function(space.w_TypeError, gs___nonzero_____should_return_an_i) + w_etype, w_evalue = space.w_TypeError, w_14 + goto = 8 -fastf_instance___rfloordiv__ = __rfloordiv__ + if goto == 8: + raise OperationError(w_etype, w_evalue) + + if goto == 9: + return w_4 + +fastf_instance___nonzero__ = __nonzero__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rlshift__' -## firstlineno 14 +## filename '_classobj.py' +## function '__call__' +## firstlineno 492 ##SECTION## -def __rlshift__(space, __args__): - funcname = "__rlshift__" - signature = ['self', 'other'], None, None +# global declaration +# global object gs__s_instance_has_no___call___meth + +def __call__(space, __args__): + funcname = "__call__" + signature = ['self'], 'args', 'kwds' defaults_w = [] - w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rlshift__(space, w_self, w_other) + w_self, w_args, w_kwds = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___call__(space, w_self, w_args, w_kwds) -f_instance___rlshift__ = __rlshift__ +f_instance___call__ = __call__ -def __rlshift__(space, w_self, w_other): +def __call__(space, w_self, w_args, w_kwds): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_func=v2=w_self_1=w_5=w_6=w_7=w_etype=w_evalue=w_args_1=w_kwds_1=None + w_func_1=w_10=w_11=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___call__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_args_1, w_kwds_1, w_func_1 = w_args, w_kwds, w_func goto = 3 else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + assert v2 == False + w_self_1 = w_self goto = 2 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + w_5 = space.getattr(w_self_1, gs___class__) + w_6 = space.getattr(w_5, gs___name__) + w_7 = space.mod(gs__s_instance_has_no___call___meth, w_6) + w_etype, w_evalue = space.w_AttributeError, w_7 + goto = 4 if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 + _args = Arguments.fromshape(space, (0, (), True, True), [w_args_1, w_kwds_1]) + w_10 = space.call_args(w_func_1, _args) + w_11 = w_10 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rlshift__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 - else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 - - if goto == 6: - w_13 = space.lshift(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: return w_11 -fastf_instance___rlshift__ = __rlshift__ +fastf_instance___call__ = __call__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rmod__' -## firstlineno 14 +## filename '_classobj.py' +## function '__eq__' +## firstlineno 503 ##SECTION## -def __rmod__(space, __args__): - funcname = "__rmod__" +def __eq__(space, __args__): + funcname = "__eq__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rmod__(space, w_self, w_other) + return fastf_instance___eq__(space, w_self, w_other) -f_instance___rmod__ = __rmod__ +f_instance___eq__ = __eq__ -def __rmod__(space, w_self, w_other): +def __eq__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___eq__) + w_other_1, w_3 = w_other, w_0 goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 + w_9 = space.issubtype(w_10, space.w_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rmod__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 + w_16 = space.is_(w_6, space.w_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 6: - w_13 = space.mod(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_8 -fastf_instance___rmod__ = __rmod__ +fastf_instance___eq__ = __eq__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rmul__' -## firstlineno 14 +## filename '_classobj.py' +## function '__ge__' +## firstlineno 503 ##SECTION## -def __rmul__(space, __args__): - funcname = "__rmul__" +def __ge__(space, __args__): + funcname = "__ge__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rmul__(space, w_self, w_other) + return fastf_instance___ge__(space, w_self, w_other) -f_instance___rmul__ = __rmul__ +f_instance___ge__ = __ge__ -def __rmul__(space, w_self, w_other): +def __ge__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___ge__) + w_other_1, w_3 = w_other, w_0 goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 + w_9 = space.issubtype(w_10, space.w_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rmul__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 + w_16 = space.is_(w_6, space.w_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 6: - w_13 = space.mul(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_8 -fastf_instance___rmul__ = __rmul__ +fastf_instance___ge__ = __ge__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__ror__' -## firstlineno 14 +## filename '_classobj.py' +## function '__gt__' +## firstlineno 503 ##SECTION## -def __ror__(space, __args__): - funcname = "__ror__" +def __gt__(space, __args__): + funcname = "__gt__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___ror__(space, w_self, w_other) + return fastf_instance___gt__(space, w_self, w_other) -f_instance___ror__ = __ror__ +f_instance___gt__ = __gt__ -def __ror__(space, w_self, w_other): +def __gt__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___gt__) + w_other_1, w_3 = w_other, w_0 goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 + w_9 = space.issubtype(w_10, space.w_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___ror__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 + w_16 = space.is_(w_6, space.w_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 6: - w_13 = space.or_(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_8 -fastf_instance___ror__ = __ror__ +fastf_instance___gt__ = __gt__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rrshift__' -## firstlineno 14 +## filename '_classobj.py' +## function '__le__' +## firstlineno 503 ##SECTION## -def __rrshift__(space, __args__): - funcname = "__rrshift__" +def __le__(space, __args__): + funcname = "__le__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rrshift__(space, w_self, w_other) + return fastf_instance___le__(space, w_self, w_other) -f_instance___rrshift__ = __rrshift__ +f_instance___le__ = __le__ -def __rrshift__(space, w_self, w_other): +def __le__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___le__) + w_other_1, w_3 = w_other, w_0 goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 + w_9 = space.issubtype(w_10, space.w_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rrshift__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 + w_16 = space.is_(w_6, space.w_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 6: - w_13 = space.rshift(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_8 -fastf_instance___rrshift__ = __rrshift__ +fastf_instance___le__ = __le__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rsub__' -## firstlineno 14 +## filename '_classobj.py' +## function '__lt__' +## firstlineno 503 ##SECTION## -def __rsub__(space, __args__): - funcname = "__rsub__" +def __lt__(space, __args__): + funcname = "__lt__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rsub__(space, w_self, w_other) + return fastf_instance___lt__(space, w_self, w_other) -f_instance___rsub__ = __rsub__ +f_instance___lt__ = __lt__ -def __rsub__(space, w_self, w_other): +def __lt__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___lt__) + w_other_1, w_3 = w_other, w_0 goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 + w_9 = space.issubtype(w_10, space.w_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rsub__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 + w_16 = space.is_(w_6, space.w_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 6: - w_13 = space.sub(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 - - if goto == 7: - return w_11 + return w_8 -fastf_instance___rsub__ = __rsub__ +fastf_instance___lt__ = __lt__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rtruediv__' -## firstlineno 14 +## filename '_classobj.py' +## function '__ne__' +## firstlineno 503 ##SECTION## -def __rtruediv__(space, __args__): - funcname = "__rtruediv__" +def __ne__(space, __args__): + funcname = "__ne__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rtruediv__(space, w_self, w_other) + return fastf_instance___ne__(space, w_self, w_other) -f_instance___rtruediv__ = __rtruediv__ +f_instance___ne__ = __ne__ -def __rtruediv__(space, w_self, w_other): +def __ne__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_0=w_other_1=w_3=w_7=w_8=w_4=w_5=w_6=w_16=v17=w_12=w_14=w_10=None + w_9=v11=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_coerced = fastf__coerce(space, w_self, w_other) - w_3 = space.is_(w_coerced, space.w_None) - v4 = space.is_true(w_3) - if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 - else: - assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + try: + w_0 = space.call_function(gfunc_instance_getattr1, w_self, gs___ne__) + w_other_1, w_3 = w_other, w_0 goto = 2 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 + try: + w_7 = space.call_function(w_3, w_other_1) + w_8 = w_7 + goto = 6 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 4 + else:raise # unhandled case, should not happen if goto == 3: - v8 = space.is_true(w_5) - if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 - goto = 4 - else: - assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 + w_9 = space.issubtype(w_10, space.w_AttributeError) + v11 = space.is_true(w_9) + if v11 == True: + w_8 = space.w_NotImplemented goto = 6 + else: + assert v11 == False + w_etype, w_evalue = w_12, w_14 + goto = 5 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rtruediv__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func - goto = 5 + w_16 = space.is_(w_6, space.w_AttributeError) + v17 = space.is_true(w_16) + if v17 == True: + w_8 = space.w_NotImplemented + goto = 6 else: - assert v10 == False - w_11 = space.w_NotImplemented + assert v17 == False + w_12, w_14, w_10 = w_4, w_5, w_6 + goto = 3 + continue + + if goto == 5: + raise OperationError(w_etype, w_evalue) + + if goto == 6: + return w_8 + +fastf_instance___ne__ = __ne__ + +##SECTION## +## filename '_classobj.py' +## function '__iter__' +## firstlineno 512 +##SECTION## +# global declarations +# global object gs___iter___returned_non_iterator_o +# global object gs_iteration_over_non_sequence + +def __iter__(space, __args__): + funcname = "__iter__" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance___iter__(space, w_self) + +f_instance___iter__ = __iter__ + +def __iter__(space, w_self): + + w_func=v2=w_self_1=w_func_2=v12=w_etype=w_evalue=w_self_2=w_13=None + w_6=w_func_1=w_ret=w_4=v5=w_ret_1=w_7=w_8=w_9=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs___iter__, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_func_1 = w_func + goto = 2 + else: + assert v2 == False + w_self_1 = w_self + goto = 4 + + if goto == 2: + w_ret = space.call_function(w_func_1, ) + w_4 = fastf_mro_lookup(space, w_ret, gs_next) + v5 = space.is_true(w_4) + if v5 == True: + w_6 = w_ret goto = 7 + else: + assert v5 == False + w_ret_1 = w_ret + goto = 3 + + if goto == 3: + w_7 = space.call_function(space.w_type, w_ret_1) + w_8 = space.getattr(w_7, gs___name__) + w_9 = space.mod(gs___iter___returned_non_iterator_o, w_8) + w_etype, w_evalue = space.w_TypeError, w_9 + goto = 6 + + if goto == 4: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_self_1, gs___getitem__, space.w_False) + v12 = space.is_true(w_func_2) + if v12 == True: + w_self_2 = w_self_1 + goto = 5 + else: + assert v12 == False + (w_etype, w_evalue) = (space.w_TypeError, + gs_iteration_over_non_sequence) + goto = 6 if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 + w_13 = space.builtin.get('_seqiter')(w_self_2) + w_6 = w_13 goto = 7 if goto == 6: - w_13 = space.truediv(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 + raise OperationError(w_etype, w_evalue) if goto == 7: - return w_11 + return w_6 -fastf_instance___rtruediv__ = __rtruediv__ +fastf_instance___iter__ = __iter__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/purify' -## function '__rxor__' -## firstlineno 14 +## filename '_classobj.py' +## function 'next' +## firstlineno 527 ##SECTION## -def __rxor__(space, __args__): - funcname = "__rxor__" +# global declaration +# global object gs_instance_has_no_next___method + +def next(space, __args__): + funcname = "next" + signature = ['self'], None, None + defaults_w = [] + w_self, = __args__.parse(funcname, signature, defaults_w) + return fastf_instance_next(space, w_self) + +f_instance_next = next + +def next(space, w_self): + + w_func=v2=w_etype=w_evalue=w_func_1=w_5=w_6=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_func = space.call_function(gfunc_instance_getattr1, w_self, gs_next, space.w_False) + v2 = space.is_true(w_func) + if v2 == True: + w_func_1 = w_func + goto = 2 + else: + assert v2 == False + (w_etype, w_evalue) = (space.w_TypeError, + gs_instance_has_no_next___method) + goto = 3 + + if goto == 2: + w_5 = space.call_function(w_func_1, ) + w_6 = w_5 + goto = 4 + + if goto == 3: + raise OperationError(w_etype, w_evalue) + + if goto == 4: + return w_6 + +fastf_instance_next = next + +##SECTION## +## filename '_classobj.py' +## function '__cmp__' +## firstlineno 533 +##SECTION## +# global declarations +# global object gs___cmp___must_return_int +# global object gi_minus_1 + +def __cmp__(space, __args__): + funcname = "__cmp__" signature = ['self', 'other'], None, None defaults_w = [] w_self, w_other = __args__.parse(funcname, signature, defaults_w) - return fastf_instance___rxor__(space, w_self, w_other) + return fastf_instance___cmp__(space, w_self, w_other) -f_instance___rxor__ = __rxor__ +f_instance___cmp__ = __cmp__ -def __rxor__(space, w_self, w_other): +def __cmp__(space, w_self, w_other): - w_coerced=w_3=v4=w_self_2=w_other_2=w_coerced_1=w_6=w_7=w_self_1=None - w_other_1=w_5=v8=w_self_4=w_other_4=w_13=w_11=w_self_3=w_other_3=None - w_func=v10=w_other_5=w_func_1=w_12=None + w_coerced=w_3=v4=w_coerced_1=w_v_1=w_w_1=w_7=v8=w_v_3=w_w_3=w_10=None + v11=w_w_2=w_v_2=w_9=v12=w_w=w_v=w_15=v16=w_w_6=w_v_6=w_28=v29=None + w_14=w_v_7=w_func_2=v30=w_v_8=w_func_3=w_res_3=w_31=v32=w_etype=None + w_evalue=w_res_4=w_33=v34=w_res_5=w_35=v36=w_w_5=w_v_5=w_func=None + v18=w_w_7=w_func_1=w_res=w_20=v21=w_res_1=w_24=v25=w_res_2=w_26=None + v27=w_w_4=w_v_4=w_13=None goto = 1 # startblock while True: @@ -7110,54 +6781,382 @@ w_3 = space.is_(w_coerced, space.w_None) v4 = space.is_true(w_3) if v4 == True: - w_self_1, w_other_1, w_5 = w_self, w_other, w_3 - goto = 3 + w_w, w_v = w_other, w_self + goto = 6 else: assert v4 == False - w_self_2, w_other_2, w_coerced_1 = w_self, w_other, w_coerced + w_coerced_1 = w_coerced goto = 2 if goto == 2: - w_6 = space.getitem(w_coerced_1, gi_0) - w_7 = space.is_(w_6, w_self_2) - w_self_1, w_other_1, w_5 = w_self_2, w_other_2, w_7 - goto = 3 - - if goto == 3: - v8 = space.is_true(w_5) + w_v_1 = space.getitem(w_coerced_1, gi_0) + w_w_1 = space.getitem(w_coerced_1, gi_1) + w_7 = space.isinstance(w_v_1, gcls_instance) + v8 = space.is_true(w_7) if v8 == True: - w_self_3, w_other_3 = w_self_1, w_other_1 + w_w_2, w_v_2, w_9 = w_w_1, w_v_1, space.w_False goto = 4 else: assert v8 == False - w_self_4, w_other_4 = w_self_1, w_other_1 - goto = 6 + w_v_3, w_w_3 = w_v_1, w_w_1 + goto = 3 + + if goto == 3: + w_10 = space.isinstance(w_w_3, gcls_instance) + v11 = space.is_true(w_10) + if v11 == True: + w_w_2, w_v_2, w_9 = w_w_3, w_v_3, space.w_False + goto = 4 + else: + assert v11 == False + w_w_2, w_v_2, w_9 = w_w_3, w_v_3, space.w_True + goto = 4 if goto == 4: - w_func = space.call_function(gfunc_instance_getattr1, w_self_3, gs___rxor__, space.w_False) - v10 = space.is_true(w_func) - if v10 == True: - w_other_5, w_func_1 = w_other_3, w_func + v12 = space.is_true(w_9) + if v12 == True: + w_w_4, w_v_4 = w_w_2, w_v_2 goto = 5 else: - assert v10 == False - w_11 = space.w_NotImplemented - goto = 7 + assert v12 == False + w_w, w_v = w_w_2, w_v_2 + goto = 6 if goto == 5: - w_12 = space.call_function(w_func_1, w_other_5) - w_11 = w_12 - goto = 7 + w_13 = space.cmp(w_v_4, w_w_4) + w_14 = w_13 + goto = 17 if goto == 6: - w_13 = space.xor(w_other_4, w_self_4) - w_11 = w_13 - goto = 7 + w_15 = space.isinstance(w_v, gcls_instance) + v16 = space.is_true(w_15) + if v16 == True: + w_w_5, w_v_5 = w_w, w_v + goto = 7 + else: + assert v16 == False + w_w_6, w_v_6 = w_w, w_v + goto = 11 if goto == 7: - return w_11 + w_func = space.call_function(gfunc_instance_getattr1, w_v_5, gs___cmp__, space.w_False) + v18 = space.is_true(w_func) + if v18 == True: + w_w_7, w_func_1 = w_w_5, w_func + goto = 8 + else: + assert v18 == False + w_w_6, w_v_6 = w_w_5, w_v_5 + goto = 11 -fastf_instance___rxor__ = __rxor__ + if goto == 8: + w_res = space.call_function(w_func_1, w_w_7) + w_20 = space.isinstance(w_res, space.w_int) + v21 = space.is_true(w_20) + if v21 == True: + w_res_1 = w_res + goto = 9 + else: + assert v21 == False + w_etype, w_evalue = space.w_TypeError, gs___cmp___must_return_int + goto = 16 + + if goto == 9: + w_24 = space.gt(w_res_1, gi_0) + v25 = space.is_true(w_24) + if v25 == True: + w_14 = gi_1 + goto = 17 + else: + assert v25 == False + w_res_2 = w_res_1 + goto = 10 + + if goto == 10: + w_26 = space.lt(w_res_2, gi_0) + v27 = space.is_true(w_26) + if v27 == True: + w_14 = gi_minus_1 + goto = 17 + else: + assert v27 == False + w_14 = gi_0 + goto = 17 + + if goto == 11: + w_28 = space.isinstance(w_w_6, gcls_instance) + v29 = space.is_true(w_28) + if v29 == True: + w_v_7 = w_v_6 + goto = 12 + else: + assert v29 == False + w_14 = space.w_NotImplemented + goto = 17 + + if goto == 12: + w_func_2 = space.call_function(gfunc_instance_getattr1, w_v_7, gs___cmp__, space.w_False) + v30 = space.is_true(w_func_2) + if v30 == True: + w_v_8, w_func_3 = w_v_7, w_func_2 + goto = 13 + else: + assert v30 == False + w_14 = space.w_NotImplemented + goto = 17 + + if goto == 13: + w_res_3 = space.call_function(w_func_3, w_v_8) + w_31 = space.isinstance(w_res_3, space.w_int) + v32 = space.is_true(w_31) + if v32 == True: + w_res_4 = w_res_3 + goto = 14 + else: + assert v32 == False + w_etype, w_evalue = space.w_TypeError, gs___cmp___must_return_int + goto = 16 + + if goto == 14: + w_33 = space.gt(w_res_4, gi_0) + v34 = space.is_true(w_33) + if v34 == True: + w_14 = gi_1 + goto = 17 + else: + assert v34 == False + w_res_5 = w_res_4 + goto = 15 + + if goto == 15: + w_35 = space.lt(w_res_5, gi_0) + v36 = space.is_true(w_35) + if v36 == True: + w_14 = gi_minus_1 + goto = 17 + else: + assert v36 == False + w_14 = gi_0 + goto = 17 + + if goto == 16: + raise OperationError(w_etype, w_evalue) + + if goto == 17: + return w_14 + +fastf_instance___cmp__ = __cmp__ + +##SECTION## +## filename '_classobj.py' +## function 'purify' +## firstlineno 571 +##SECTION## +# global declarations +# global object g3tuple +# global object gcls_classobj +# global object gs___module__ +# global object gs__classobj +# global object gs___new__ +# global object gsm___new__ +# global object gfunc___new__ +# global object gs___slots__ +# global object g3tuple_1 +# global object gs__name +# global object gs__bases +# global object gs___dict__ +# global object gs_classobj +# global object gcls_instance +# global object gsm___new___1 +# global object gfunc___new___1 +# global object g2tuple +# global object gs__class +# global object gs_instance +# global object gfunc_purify + +def purify(space, __args__): + funcname = "purify" + signature = [], None, None + defaults_w = [] + __args__.parse(funcname, signature, defaults_w) + return fastf_purify(space) + +f_purify = purify + +def purify(space): + + w_0=w_1=w_2=w_3=w_4=w_5=None + + goto = 1 # startblock + while True: + + if goto == 1: + w_0 = space.delattr(gcls_classobj, gs__name) + w_1 = space.delattr(gcls_classobj, gs__bases) + w_2 = space.delattr(gcls_classobj, gs___slots__) + w_3 = space.delattr(gcls_instance, gs__class) + w_4 = space.delattr(gcls_instance, gs___slots__) + w_5 = space.w_None + goto = 2 + + if goto == 2: + return w_5 + +fastf_purify = purify + +# global declarations +# global object gs___abs__ +# global object gfunc_instance___abs__ +# global object gs___add__ +# global object gfunc_instance___add__ +# global object gs___and__ +# global object gfunc_instance___and__ +# global object gs___call__ +# global object gfunc_instance___call__ +# global object gs___cmp__ +# global object gfunc_instance___cmp__ +# global object gs___coerce__ +# global object gfunc_instance___coerce__ +# global object gs___contains__ +# global object gfunc_instance___contains__ +# global object gs___delattr__ +# global object gfunc_instance___delattr__ +# global object gs___delitem__ +# global object gfunc_instance___delitem__ +# global object gs___div__ +# global object gfunc_instance___div__ +# global object gs___divmod__ +# global object gfunc_instance___divmod__ +# global object gs___eq__ +# global object gfunc_instance___eq__ +# global object gs___float__ +# global object gfunc_instance___float__ +# global object gs___floordiv__ +# global object gfunc_instance___floordiv__ +# global object gs___ge__ +# global object gfunc_instance___ge__ +# global object gs___getattribute__ +# global object gfunc_instance___getattribute__ +# global object gs___getitem__ +# global object gfunc_instance___getitem__ +# global object gs___gt__ +# global object gfunc_instance___gt__ +# global object gs___hash__ +# global object gfunc_instance___hash__ +# global object gs___hex__ +# global object gfunc_instance___hex__ +# global object gs___iadd__ +# global object gfunc_instance___iadd__ +# global object gs___iand__ +# global object gfunc_instance___iand__ +# global object gs___idiv__ +# global object gfunc_instance___idiv__ +# global object gs___ifloordiv__ +# global object gfunc_instance___ifloordiv__ +# global object gs___ilshift__ +# global object gfunc_instance___ilshift__ +# global object gs___imod__ +# global object gfunc_instance___imod__ +# global object gs___imul__ +# global object gfunc_instance___imul__ +# global object gs___int__ +# global object gfunc_instance___int__ +# global object gs___invert__ +# global object gfunc_instance___invert__ +# global object gs___ior__ +# global object gfunc_instance___ior__ +# global object gs___ipow__ +# global object gfunc_instance___ipow__ +# global object gs___irshift__ +# global object gfunc_instance___irshift__ +# global object gs___isub__ +# global object gfunc_instance___isub__ +# global object gs___iter__ +# global object gfunc_instance___iter__ +# global object gs___itruediv__ +# global object gfunc_instance___itruediv__ +# global object gs___ixor__ +# global object gfunc_instance___ixor__ +# global object gs___le__ +# global object gfunc_instance___le__ +# global object gs___len__ +# global object gfunc_instance___len__ +# global object gs___long__ +# global object gfunc_instance___long__ +# global object gs___lshift__ +# global object gfunc_instance___lshift__ +# global object gs___lt__ +# global object gfunc_instance___lt__ +# global object gs___mod__ +# global object gfunc_instance___mod__ +# global object gs___mul__ +# global object gfunc_instance___mul__ +# global object gs___ne__ +# global object gfunc_instance___ne__ +# global object gs___neg__ +# global object gfunc_instance___neg__ +# global object gs___nonzero__ +# global object gfunc_instance___nonzero__ +# global object gs___oct__ +# global object gfunc_instance___oct__ +# global object gs___or__ +# global object gfunc_instance___or__ +# global object gs___pos__ +# global object gfunc_instance___pos__ +# global object gs___pow__ +# global object gfunc_instance___pow__ +# global object gs___radd__ +# global object gfunc_instance___radd__ +# global object gs___rand__ +# global object gfunc_instance___rand__ +# global object gs___rdiv__ +# global object gfunc_instance___rdiv__ +# global object gs___rdivmod__ +# global object gfunc_instance___rdivmod__ +# global object gs___repr__ +# global object gfunc_instance___repr__ +# global object gs___rfloordiv__ +# global object gfunc_instance___rfloordiv__ +# global object gs___rlshift__ +# global object gfunc_instance___rlshift__ +# global object gs___rmod__ +# global object gfunc_instance___rmod__ +# global object gs___rmul__ +# global object gfunc_instance___rmul__ +# global object gs___ror__ +# global object gfunc_instance___ror__ +# global object gs___rpow__ +# global object gfunc_instance___rpow__ +# global object gs___rrshift__ +# global object gfunc_instance___rrshift__ +# global object gs___rshift__ +# global object gfunc_instance___rshift__ +# global object gs___rsub__ +# global object gfunc_instance___rsub__ +# global object gs___rtruediv__ +# global object gfunc_instance___rtruediv__ +# global object gs___rxor__ +# global object gfunc_instance___rxor__ +# global object gs___setattr__ +# global object gfunc_instance___setattr__ +# global object gs___setitem__ +# global object gfunc_instance___setitem__ +# global object gs___str__ +# global object gfunc_instance___str__ +# global object gs___sub__ +# global object gfunc_instance___sub__ +# global object gs___truediv__ +# global object gfunc_instance___truediv__ +# global object gs___xor__ +# global object gfunc_instance___xor__ +# global object gs_next +# global object gfunc_instance_next +# global object gfunc_classobj___call__ +# global object gfunc_classobj___delattr__ +# global object gfunc_classobj___getattribute__ +# global object gfunc_classobj___repr__ +# global object gfunc_classobj___setattr__ +# global object gfunc_classobj___str__ ##SECTION## #************************************************************* @@ -7540,7 +7539,6 @@ del m.__itruediv__ m.gs___iter___returned_non_iterator_o = space.wrap('__iter__ returned non-iterator of type %s') m.gs_iteration_over_non_sequence = space.wrap('iteration over non-sequence') - m.gs__seqiter = space.wrap('_seqiter') del m.__iter__ del m.__isub__ del m.__irshift__ From rxe at codespeak.net Mon Feb 21 06:47:23 2005 From: rxe at codespeak.net (rxe at codespeak.net) Date: Mon, 21 Feb 2005 06:47:23 +0100 (MET) Subject: [pypy-svn] r9374 - pypy/dist/pypy/tool Message-ID: <20050221054723.9CFA027BBF@code1.codespeak.net> Author: rxe Date: Mon Feb 21 06:47:23 2005 New Revision: 9374 Modified: pypy/dist/pypy/tool/traceinteractive.py pypy/dist/pypy/tool/traceop.py Log: * Fix up trace tools to work after lazy builtin module change. * Remove unused option from ResultPrinter. Modified: pypy/dist/pypy/tool/traceinteractive.py ============================================================================== --- pypy/dist/pypy/tool/traceinteractive.py (original) +++ pypy/dist/pypy/tool/traceinteractive.py Mon Feb 21 06:47:23 2005 @@ -43,13 +43,12 @@ return None def global_matches(self, text): - w_res = self.space.call_method(self.space.w_globals, "keys") namespace_keys = self.space.unwrap(w_res) - w_res = self.space.call_method(self.space.w_builtins, "keys") + w_res = self.space.call_method(self.space.builtin.getdict(), "keys") builtin_keys = self.space.unwrap(w_res) - + matches = [] n = len(text) @@ -83,7 +82,7 @@ def get_words(self, w_clz): s = self.space - w_dir_func = s.getitem(s.w_builtins, s.wrap("dir")) + w_dir_func = s.builtin.get("dir") w_res = s.call_function(w_dir_func, w_clz) return s.unwrap(w_res) @@ -162,7 +161,7 @@ self.tracelevel = tracelevel # XXX Do something better than this - I'm not really sure what is useful - # and what is (rxe) + # and what isn't (rxe) self.resprinter.operations_level = tracelevel def runcode(self, code): @@ -181,18 +180,18 @@ res = None if self.tracelevel: res = s.getresult() - + s.settrace() + # Did we modify __pytrace__ tracelevel = s.unwrap(s.getitem(s.w_globals, s.wrap("__pytrace__"))) - + if tracelevel != self.tracelevel: self.set_tracelevel(tracelevel) - if res is not None and self.tracelevel: - s.settrace() + if res is not None and self.tracelevel: self.resprinter.print_result(s, res) - + except baseobjspace.OperationError, operationerr: if self.tracelevel: res = s.getresult() Modified: pypy/dist/pypy/tool/traceop.py ============================================================================== --- pypy/dist/pypy/tool/traceop.py (original) +++ pypy/dist/pypy/tool/traceop.py Mon Feb 21 06:47:23 2005 @@ -31,17 +31,14 @@ class ResultPrinter: def __init__(self, - skip_all_below_op = True, operations_level = 2, indentor = ' ', - skip_bytecodes = ["PRINT_EXPR", "PRINT_ITEM", "PRINT_NEWLINE"], - ): + skip_bytecodes = ["PRINT_EXPR", "PRINT_ITEM", "PRINT_NEWLINE"]): # Configurable stuff self.indentor = indentor self.skip_bytecodes = skip_bytecodes self.operations_level = operations_level - self.skip_all_below_op = skip_all_below_op self.reset() @@ -85,6 +82,7 @@ self.print_line(s) def print_bytecode(self, index, bytecode): + # Don't allow bytecodes to be exposed if operations level is up if len(self.ops) >= self.operations_level: return @@ -97,7 +95,7 @@ s = " " * 17 s += ">> %s%s" % (name, str_args) self.print_line_operations(s) - + def print_op_leave(self, name, str_res): s = " " * 20 @@ -190,7 +188,6 @@ try: # XXX Sure this won't go down well - didn't really want # to clutter up the interpeter code - from pypy.interpreter.argument import Arguments from pypy.interpreter.function import Function, Method if isinstance(value, Function): @@ -208,9 +205,9 @@ l = [] for arg in args: if frame and space.is_true(space.is_(arg, frame.w_globals)): - l.append('w_globals') - elif frame and space.is_true(space.is_(arg, space.w_builtins)): - l.append('w_builtins') + l.append('globals()') + elif frame and space.is_true(space.is_(arg, space.builtin)): + l.append('__builtin__') else: l.append(repr_value(space, arg)) @@ -252,6 +249,7 @@ count += ii return count + # Note includes lazy loading of builtins res, traceres = perform_trace(tspace, app_test, tspace.wrap(5)) print_result(tspace, traceres) From rxe at codespeak.net Mon Feb 21 06:48:26 2005 From: rxe at codespeak.net (rxe at codespeak.net) Date: Mon, 21 Feb 2005 06:48:26 +0100 (MET) Subject: [pypy-svn] r9375 - pypy/dist/pypy/objspace Message-ID: <20050221054826.CC2D027BBF@code1.codespeak.net> Author: rxe Date: Mon Feb 21 06:48:26 2005 New Revision: 9375 Modified: pypy/dist/pypy/objspace/trace.py Log: Fix some cosmetic issues. Modified: pypy/dist/pypy/objspace/trace.py ============================================================================== --- pypy/dist/pypy/objspace/trace.py (original) +++ pypy/dist/pypy/objspace/trace.py Mon Feb 21 06:48:26 2005 @@ -1,7 +1,6 @@ -""" +""" Trace object space traces operations and bytecode execution - in frames. - + in frames. """ from __future__ import generators @@ -17,8 +16,8 @@ class ExecBytecode(object): """ bytecode trace. """ def __init__(self, frame): - self.frame = frame - self.code = frame.code + self.frame = frame + self.code = frame.code self.index = frame.next_instr class EnterFrame(object): @@ -54,7 +53,7 @@ class TraceResult(object): """ this is the state of tracing-in-progress. """ def __init__(self, tracespace): - self.events = [] + self.events = [] self.tracespace = tracespace def append(self, arg): @@ -74,7 +73,7 @@ if isinstance(event, ExecBytecode): disres = self.getdisresult(event.frame) yield disres.getbytecode(event.index) - + def getoperations(self): for event in self.events: if isinstance(event, (CallBegin, CallFinished, CallException)): @@ -92,54 +91,56 @@ class ExecutionContextTracer(object): def __init__(self, result, ec): - self.__ec = ec - self.__result = result + self.ec = ec + self.result = result def __getattr__(self, name): """ generically pass through everything else ... """ - return getattr(self.__ec, name) + return getattr(self.ec, name) def enter(self, frame): """ called just before (continuing to) evaluating a frame. """ - self.__result.append(EnterFrame(frame)) - return self.__ec.enter(frame) + self.result.append(EnterFrame(frame)) + return self.ec.enter(frame) def leave(self, previous_ec): """ called just after evaluating of a frame is suspended/finished. """ - frame = self.__ec.framestack.top() - self.__result.append(LeaveFrame(frame)) - return self.__ec.leave(previous_ec) + frame = self.ec.framestack.top() + self.result.append(LeaveFrame(frame)) + return self.ec.leave(previous_ec) def bytecode_trace(self, frame): """ called just before execution of a bytecode. """ - self.__result.append(ExecBytecode(frame)) + self.result.append(ExecBytecode(frame)) class CallableTracer(object): def __init__(self, result, name, func): - self.__result = result - self.__name = name - self.__func = func + self.result = result + self.name = name + self.func = func def __call__(self, *args, **kwargs): - callinfo = CallInfo(self.__name, self.__func, args, kwargs) - self.__result.append(CallBegin(callinfo)) + callinfo = CallInfo(self.name, self.func, args, kwargs) + self.result.append(CallBegin(callinfo)) try: - res = self.__func(*args, **kwargs) + res = self.func(*args, **kwargs) except Exception, e: - self.__result.append(CallException(callinfo, e)) + self.result.append(CallException(callinfo, e)) raise else: - self.__result.append(CallFinished(callinfo, res)) + self.result.append(CallFinished(callinfo, res)) return res def __getattr__(self, name): """ generically pass through everything we don't intercept. """ - return getattr(self.__func, name) + return getattr(self.func, name) def __str__(self): - return "%s - CallableTracer(%s)" % (self.__name, self.__func) - __repr = __str__ + return "%s - CallableTracer(%s)" % (self.name, self.func) + + __repr__ = __str__ + # __________________________________________________________________________ # # Tracer factory @@ -161,7 +162,7 @@ will turn the supplied into a tracable space by extending its class.""" # Don't trace an already tracable space - if hasattr(space, "__pypytrace___"): + if hasattr(space, "__pypytrace__"): return space if space is None: @@ -182,7 +183,7 @@ obj = CallableTracer(self._result, name, obj) return obj - def __pypytrace___(self): + def __pypytrace__(self): pass def settrace(self): @@ -198,17 +199,18 @@ def reset_trace(self): """ Returns the class to it's original form. """ - space.__class__ = space.__oldclass___ - del space.__oldclass___ + space.__class__ = space.__oldclass__ + del space.__oldclass__ if hasattr(self, "_result"): del self._result trace_clz = type("Trace" + space.__class__.__name__, (Trace,), {}) - space.__oldclass___, space.__class__ = space.__class__, trace_clz + space.__oldclass__, space.__class__ = space.__class__, trace_clz + + # XXX Ensure space's sys & builtin are fully loaded? space.settrace() return space # ______________________________________________________________________ # End of trace.py - From ac at codespeak.net Mon Feb 21 11:25:13 2005 From: ac at codespeak.net (ac at codespeak.net) Date: Mon, 21 Feb 2005 11:25:13 +0100 (MET) Subject: [pypy-svn] r9376 - pypy/dist/pypy/objspace/std Message-ID: <20050221102513.B4BF027BBE@code1.codespeak.net> Author: ac Date: Mon Feb 21 11:25:13 2005 New Revision: 9376 Modified: pypy/dist/pypy/objspace/std/dictobject.py pypy/dist/pypy/objspace/std/listobject.py Log: Use applevel dict to keep track of objects. Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Mon Feb 21 11:25:13 2005 @@ -246,26 +246,34 @@ # The fix is to move this to dicttype.py, and do a # multimethod lookup mapping str to StdObjSpace.str # This cannot happen until multimethods are fixed. See dicttype.py -def app_dictstr(d): +def app_dictstr(currently_in_repr, d): + dict_id = id(d) + if dict_id in currently_in_repr: + return '{...}' + currently_in_repr[dict_id] = 1 + try: items = [] for k, v in d.iteritems(): items.append(repr(k) + ": " + repr(v)) return "{" + ', '.join(items) + "}" + finally: + try: + del currently_in_repr[dict_id] + except: + pass dictstr = gateway.app2interp(app_dictstr) def str__Dict(space, w_dict): if w_dict.used == 0: return space.wrap('{}') - d = space.get_ec_state_dict().setdefault('Py_Repr', {}) - dict_id = space.int_w(space.id(w_dict)) - if dict_id in d: - return space.wrap('{...}') - d[dict_id] = 1 + statedict = space.get_ec_state_dict() try: - return dictstr(space, w_dict) - finally: - del d[dict_id] + w_currently_in_repr = statedict['Py_Repr'] + except KeyError: + w_currently_in_repr = statedict['Py_Repr'] = space.newdict(()) + + return dictstr(space, w_currently_in_repr, w_dict) repr__Dict = str__Dict from pypy.objspace.std import dicttype Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Mon Feb 21 11:25:13 2005 @@ -278,22 +278,30 @@ items[start+i*step] = sequence2[i] return space.w_None -def app_listrepr(l): +def app_listrepr(currently_in_repr, l): 'The app-level part of repr().' - return "[" + ", ".join([repr(x) for x in l]) + ']' - + list_id = id(l) + if list_id in currently_in_repr: + return '[...]' + currently_in_repr[list_id] = 1 + try: + return "[" + ", ".join([repr(x) for x in l]) + ']' + finally: + try: + del currently_in_repr[list_id] + except: + pass + def repr__List(space, w_list): if w_list.ob_size == 0: return space.wrap('[]') - d = space.get_ec_state_dict().setdefault('Py_Repr', {}) - list_id = space.int_w(space.id(w_list)) - if list_id in d: - return space.wrap('[...]') - d[list_id] = 1 + statedict = space.get_ec_state_dict() try: - return listrepr(space, w_list) - finally: - del d[list_id] + w_currently_in_repr = statedict['Py_Repr'] + except KeyError: + w_currently_in_repr = statedict['Py_Repr'] = space.newdict(()) + + return listrepr(space, w_currently_in_repr, w_list) def hash__List(space,w_list): raise OperationError(space.w_TypeError,space.wrap("list objects are unhashable")) From pedronis at codespeak.net Mon Feb 21 14:07:42 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 14:07:42 +0100 (MET) Subject: [pypy-svn] r9379 - in pypy/dist/pypy: module translator Message-ID: <20050221130742.68F0427B56@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 14:07:42 2005 New Revision: 9379 Modified: pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: when shortcutting builtins to space. check nargs == arity Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Mon Feb 21 14:07:42 2005 @@ -2,6 +2,7 @@ # -*- coding: LATIN-1 -*- from pypy.interpreter.error import OperationError +from pypy.interpreter.argument import Arguments """Python's standard exception class hierarchy. @@ -94,7 +95,7 @@ +-- FutureWarning""" # global declarations -# global object g47dict +# global object g48dict # global object gs_MemoryError # global object gcls_MemoryError # global object gcls_StandardError @@ -156,6 +157,8 @@ # global object gcls_ZeroDivisionError # global object gs_EOFError # global object gcls_EOFError +# global object gs___file__ +# global object gs__u_pedronis_PyPy_dist_pypy_lib__ # global object gs_TabError # global object gcls_TabError # global object gs_UnicodeEncodeError @@ -216,7 +219,7 @@ # global object gfunc_Exception___str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__getitem__' ## firstlineno 94 ##SECTION## @@ -248,7 +251,7 @@ fastf_Exception___getitem__ = __getitem__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 98 ##SECTION## @@ -279,7 +282,7 @@ fastf_Exception___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 102 ##SECTION## @@ -346,7 +349,7 @@ fastf_Exception___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 131 ##SECTION## @@ -403,11 +406,12 @@ fastf_UnicodeTranslateError___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 141 ##SECTION## # global declarations +# global object gs_getattr # global object gs_start # global object gs_start_ # global object gs_reason @@ -439,19 +443,19 @@ while True: if goto == 1: - w_0 = space.getattr(w_self, gs_start, space.w_None) + w_0 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_start, space.w_None) w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_start_, w_2) - w_4 = space.getattr(w_self, gs_reason, space.w_None) + w_4 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_reason, space.w_None) w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_reason_, w_5) - w_7 = space.getattr(w_self, gs_args, space.w_None) + w_7 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_args, space.w_None) w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_args_, w_8) - w_10 = space.getattr(w_self, gs_end, space.w_None) + w_10 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_end, space.w_None) w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_end_, w_11) - w_13 = space.getattr(w_self, gs_object, space.w_None) + w_13 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_object, space.w_None) w_14 = space.call_function(space.w_str, w_13) w_15 = space.add(gs_object_, w_14) w_16 = space.newlist([w_3, w_6, w_9, w_12, w_15]) @@ -465,7 +469,7 @@ fastf_UnicodeTranslateError___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 159 ##SECTION## @@ -527,7 +531,7 @@ fastf_KeyError___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 185 ##SECTION## @@ -617,7 +621,7 @@ fastf_EnvironmentError___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 199 ##SECTION## @@ -646,16 +650,16 @@ while True: if goto == 1: - w_0 = space.getattr(w_self, gs_errno, space.w_None) + w_0 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_errno, space.w_None) w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_errno_, w_2) - w_4 = space.getattr(w_self, gs_args, space.w_None) + w_4 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_args, space.w_None) w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_args_, w_5) - w_7 = space.getattr(w_self, gs_strerror, space.w_None) + w_7 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_strerror, space.w_None) w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_strerror_, w_8) - w_10 = space.getattr(w_self, gs_filename, space.w_None) + w_10 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_filename, space.w_None) w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_filename_, w_11) w_13 = space.newlist([w_3, w_6, w_9, w_12]) @@ -669,7 +673,7 @@ fastf_EnvironmentError___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 219 ##SECTION## @@ -726,7 +730,7 @@ fastf_UnicodeEncodeError___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 230 ##SECTION## @@ -752,22 +756,22 @@ while True: if goto == 1: - w_0 = space.getattr(w_self, gs_object, space.w_None) + w_0 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_object, space.w_None) w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self, gs_end, space.w_None) + w_4 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_end, space.w_None) w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self, gs_encoding, space.w_None) + w_7 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_encoding, space.w_None) w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self, gs_args, space.w_None) + w_10 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_args, space.w_None) w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self, gs_start, space.w_None) + w_13 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_start, space.w_None) w_14 = space.call_function(space.w_str, w_13) w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self, gs_reason, space.w_None) + w_16 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_reason, space.w_None) w_17 = space.call_function(space.w_str, w_16) w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) @@ -781,7 +785,7 @@ fastf_UnicodeEncodeError___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 270 ##SECTION## @@ -855,7 +859,7 @@ fastf_SyntaxError___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 282 ##SECTION## @@ -876,7 +880,7 @@ while True: if goto == 1: - w_0 = space.getattr(w_self, gs_args, space.w_None) + w_0 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_args, space.w_None) w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_args_, w_2) w_4 = space.newlist([w_3]) @@ -890,7 +894,7 @@ fastf_SyntaxError___str__ = __str__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 296 ##SECTION## @@ -972,7 +976,7 @@ fastf_SystemExit___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__init__' ## firstlineno 331 ##SECTION## @@ -1026,7 +1030,7 @@ fastf_UnicodeDecodeError___init__ = __init__ ##SECTION## -## filename '/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py' +## filename '_exceptions.py' ## function '__str__' ## firstlineno 342 ##SECTION## @@ -1048,22 +1052,22 @@ while True: if goto == 1: - w_0 = space.getattr(w_self, gs_object, space.w_None) + w_0 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_object, space.w_None) w_2 = space.call_function(space.w_str, w_0) w_3 = space.add(gs_object_, w_2) - w_4 = space.getattr(w_self, gs_end, space.w_None) + w_4 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_end, space.w_None) w_5 = space.call_function(space.w_str, w_4) w_6 = space.add(gs_end_, w_5) - w_7 = space.getattr(w_self, gs_encoding, space.w_None) + w_7 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_encoding, space.w_None) w_8 = space.call_function(space.w_str, w_7) w_9 = space.add(gs_encoding_, w_8) - w_10 = space.getattr(w_self, gs_args, space.w_None) + w_10 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_args, space.w_None) w_11 = space.call_function(space.w_str, w_10) w_12 = space.add(gs_args_, w_11) - w_13 = space.getattr(w_self, gs_start, space.w_None) + w_13 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_start, space.w_None) w_14 = space.call_function(space.w_str, w_13) w_15 = space.add(gs_start_, w_14) - w_16 = space.getattr(w_self, gs_reason, space.w_None) + w_16 = space.call_function((space.builtin.get(space.str_w(gs_getattr))), w_self, gs_reason, space.w_None) w_17 = space.call_function(space.w_str, w_16) w_18 = space.add(gs_reason_, w_17) w_19 = space.newlist([w_3, w_6, w_9, w_12, w_15, w_18]) @@ -1086,7 +1090,7 @@ # make sure that this function is run only once: m.initexceptions = lambda *ign:True - m.g47dict = space.newdict([]) + m.g48dict = space.newdict([]) m.__doc__ = space.wrap(m.__doc__) m.gs_MemoryError = space.wrap('MemoryError') _dic = space.newdict([]) @@ -1115,7 +1119,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_MemoryError, _bases, _dic]) m.gcls_MemoryError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_MemoryError, gcls_MemoryError) + space.setitem(g48dict, gs_MemoryError, gcls_MemoryError) m.gs_ImportError = space.wrap('ImportError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1124,7 +1128,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_ImportError, _bases, _dic]) m.gcls_ImportError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_ImportError, gcls_ImportError) + space.setitem(g48dict, gs_ImportError, gcls_ImportError) m.gs_RuntimeError = space.wrap('RuntimeError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1133,7 +1137,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_RuntimeError, _bases, _dic]) m.gcls_RuntimeError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_RuntimeError, gcls_RuntimeError) + space.setitem(g48dict, gs_RuntimeError, gcls_RuntimeError) m.gs_UnicodeTranslateError = space.wrap('UnicodeTranslateError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1158,7 +1162,7 @@ _bases = space.newtuple([gcls_UnicodeError]) _args = space.newtuple([gs_UnicodeTranslateError, _bases, _dic]) m.gcls_UnicodeTranslateError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) + space.setitem(g48dict, gs_UnicodeTranslateError, gcls_UnicodeTranslateError) m.gs_KeyError = space.wrap('KeyError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1175,7 +1179,7 @@ _bases = space.newtuple([gcls_LookupError]) _args = space.newtuple([gs_KeyError, _bases, _dic]) m.gcls_KeyError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_KeyError, gcls_KeyError) + space.setitem(g48dict, gs_KeyError, gcls_KeyError) m.gs_TaskletExit = space.wrap('TaskletExit') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1192,7 +1196,7 @@ _bases = space.newtuple([gcls_SystemExit]) _args = space.newtuple([gs_TaskletExit, _bases, _dic]) m.gcls_TaskletExit = space.call(space.w_type, _args) - space.setitem(g47dict, gs_TaskletExit, gcls_TaskletExit) + space.setitem(g48dict, gs_TaskletExit, gcls_TaskletExit) m.gs_StopIteration = space.wrap('StopIteration') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1201,7 +1205,7 @@ _bases = space.newtuple([gcls_Exception]) _args = space.newtuple([gs_StopIteration, _bases, _dic]) m.gcls_StopIteration = space.call(space.w_type, _args) - space.setitem(g47dict, gs_StopIteration, gcls_StopIteration) + space.setitem(g48dict, gs_StopIteration, gcls_StopIteration) m.gs_PendingDeprecationWarning = space.wrap('PendingDeprecationWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1218,7 +1222,7 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_PendingDeprecationWarning, _bases, _dic]) m.gcls_PendingDeprecationWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) + space.setitem(g48dict, gs_PendingDeprecationWarning, gcls_PendingDeprecationWarning) m.gs_EnvironmentError = space.wrap('EnvironmentError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1227,8 +1231,8 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_EnvironmentError, _bases, _dic]) m.gcls_EnvironmentError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_EnvironmentError, gcls_EnvironmentError) - space.setitem(g47dict, gs_LookupError, gcls_LookupError) + space.setitem(g48dict, gs_EnvironmentError, gcls_EnvironmentError) + space.setitem(g48dict, gs_LookupError, gcls_LookupError) m.gs_OSError = space.wrap('OSError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1237,7 +1241,7 @@ _bases = space.newtuple([gcls_EnvironmentError]) _args = space.newtuple([gs_OSError, _bases, _dic]) m.gcls_OSError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_OSError, gcls_OSError) + space.setitem(g48dict, gs_OSError, gcls_OSError) m.gs_DeprecationWarning = space.wrap('DeprecationWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1246,8 +1250,8 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_DeprecationWarning, _bases, _dic]) m.gcls_DeprecationWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_DeprecationWarning, gcls_DeprecationWarning) - space.setitem(g47dict, gs_UnicodeError, gcls_UnicodeError) + space.setitem(g48dict, gs_DeprecationWarning, gcls_DeprecationWarning) + space.setitem(g48dict, gs_UnicodeError, gcls_UnicodeError) m.gs_FloatingPointError = space.wrap('FloatingPointError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1264,7 +1268,7 @@ _bases = space.newtuple([gcls_ArithmeticError]) _args = space.newtuple([gs_FloatingPointError, _bases, _dic]) m.gcls_FloatingPointError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_FloatingPointError, gcls_FloatingPointError) + space.setitem(g48dict, gs_FloatingPointError, gcls_FloatingPointError) m.gs_AttributeError = space.wrap('AttributeError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1273,7 +1277,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_AttributeError, _bases, _dic]) m.gcls_AttributeError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_AttributeError, gcls_AttributeError) + space.setitem(g48dict, gs_AttributeError, gcls_AttributeError) m.gs_IndentationError = space.wrap('IndentationError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1290,7 +1294,7 @@ _bases = space.newtuple([gcls_SyntaxError]) _args = space.newtuple([gs_IndentationError, _bases, _dic]) m.gcls_IndentationError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_IndentationError, gcls_IndentationError) + space.setitem(g48dict, gs_IndentationError, gcls_IndentationError) m.gs_NameError = space.wrap('NameError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1299,7 +1303,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_NameError, _bases, _dic]) m.gcls_NameError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_NameError, gcls_NameError) + space.setitem(g48dict, gs_NameError, gcls_NameError) m.gs_OverflowWarning = space.wrap('OverflowWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1308,7 +1312,7 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_OverflowWarning, _bases, _dic]) m.gcls_OverflowWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_OverflowWarning, gcls_OverflowWarning) + space.setitem(g48dict, gs_OverflowWarning, gcls_OverflowWarning) m.gs_IOError = space.wrap('IOError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1317,8 +1321,8 @@ _bases = space.newtuple([gcls_EnvironmentError]) _args = space.newtuple([gs_IOError, _bases, _dic]) m.gcls_IOError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_IOError, gcls_IOError) - space.setitem(g47dict, gs_ValueError, gcls_ValueError) + space.setitem(g48dict, gs_IOError, gcls_IOError) + space.setitem(g48dict, gs_ValueError, gcls_ValueError) m.gs_FutureWarning = space.wrap('FutureWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1327,7 +1331,7 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_FutureWarning, _bases, _dic]) m.gcls_FutureWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_FutureWarning, gcls_FutureWarning) + space.setitem(g48dict, gs_FutureWarning, gcls_FutureWarning) m.gs_ZeroDivisionError = space.wrap('ZeroDivisionError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1336,9 +1340,9 @@ _bases = space.newtuple([gcls_ArithmeticError]) _args = space.newtuple([gs_ZeroDivisionError, _bases, _dic]) m.gcls_ZeroDivisionError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) - space.setitem(g47dict, gs_SystemExit, gcls_SystemExit) - space.setitem(g47dict, gs_Exception, gcls_Exception) + space.setitem(g48dict, gs_ZeroDivisionError, gcls_ZeroDivisionError) + space.setitem(g48dict, gs_SystemExit, gcls_SystemExit) + space.setitem(g48dict, gs_Exception, gcls_Exception) m.gs_EOFError = space.wrap('EOFError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1347,8 +1351,11 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_EOFError, _bases, _dic]) m.gcls_EOFError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_EOFError, gcls_EOFError) - space.setitem(g47dict, gs_StandardError, gcls_StandardError) + space.setitem(g48dict, gs_EOFError, gcls_EOFError) + space.setitem(g48dict, gs_StandardError, gcls_StandardError) + m.gs___file__ = space.wrap('__file__') + m.gs__u_pedronis_PyPy_dist_pypy_lib__ = space.wrap('/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py') + space.setitem(g48dict, gs___file__, gs__u_pedronis_PyPy_dist_pypy_lib__) m.gs_TabError = space.wrap('TabError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1357,8 +1364,8 @@ _bases = space.newtuple([gcls_IndentationError]) _args = space.newtuple([gs_TabError, _bases, _dic]) m.gcls_TabError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_TabError, gcls_TabError) - space.setitem(g47dict, gs_SyntaxError, gcls_SyntaxError) + space.setitem(g48dict, gs_TabError, gcls_TabError) + space.setitem(g48dict, gs_SyntaxError, gcls_SyntaxError) m.gs_UnicodeEncodeError = space.wrap('UnicodeEncodeError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1367,7 +1374,7 @@ _bases = space.newtuple([gcls_UnicodeError]) _args = space.newtuple([gs_UnicodeEncodeError, _bases, _dic]) m.gcls_UnicodeEncodeError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) + space.setitem(g48dict, gs_UnicodeEncodeError, gcls_UnicodeEncodeError) m.gs_UnboundLocalError = space.wrap('UnboundLocalError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1376,9 +1383,9 @@ _bases = space.newtuple([gcls_NameError]) _args = space.newtuple([gs_UnboundLocalError, _bases, _dic]) m.gcls_UnboundLocalError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_UnboundLocalError, gcls_UnboundLocalError) + space.setitem(g48dict, gs_UnboundLocalError, gcls_UnboundLocalError) m.gs___name__ = space.wrap('__name__') - space.setitem(g47dict, gs___name__, gs__exceptions) + space.setitem(g48dict, gs___name__, gs__exceptions) m.gs_ReferenceError = space.wrap('ReferenceError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1387,7 +1394,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_ReferenceError, _bases, _dic]) m.gcls_ReferenceError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_ReferenceError, gcls_ReferenceError) + space.setitem(g48dict, gs_ReferenceError, gcls_ReferenceError) m.gs_AssertionError = space.wrap('AssertionError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1396,7 +1403,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_AssertionError, _bases, _dic]) m.gcls_AssertionError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_AssertionError, gcls_AssertionError) + space.setitem(g48dict, gs_AssertionError, gcls_AssertionError) m.gs_UnicodeDecodeError = space.wrap('UnicodeDecodeError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1405,7 +1412,7 @@ _bases = space.newtuple([gcls_UnicodeError]) _args = space.newtuple([gs_UnicodeDecodeError, _bases, _dic]) m.gcls_UnicodeDecodeError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) + space.setitem(g48dict, gs_UnicodeDecodeError, gcls_UnicodeDecodeError) m.gs_TypeError = space.wrap('TypeError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1414,7 +1421,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_TypeError, _bases, _dic]) m.gcls_TypeError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_TypeError, gcls_TypeError) + space.setitem(g48dict, gs_TypeError, gcls_TypeError) m.gs_IndexError = space.wrap('IndexError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1423,7 +1430,7 @@ _bases = space.newtuple([gcls_LookupError]) _args = space.newtuple([gs_IndexError, _bases, _dic]) m.gcls_IndexError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_IndexError, gcls_IndexError) + space.setitem(g48dict, gs_IndexError, gcls_IndexError) m.gs_RuntimeWarning = space.wrap('RuntimeWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1432,7 +1439,7 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_RuntimeWarning, _bases, _dic]) m.gcls_RuntimeWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_RuntimeWarning, gcls_RuntimeWarning) + space.setitem(g48dict, gs_RuntimeWarning, gcls_RuntimeWarning) m.gs_KeyboardInterrupt = space.wrap('KeyboardInterrupt') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1441,7 +1448,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_KeyboardInterrupt, _bases, _dic]) m.gcls_KeyboardInterrupt = space.call(space.w_type, _args) - space.setitem(g47dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) + space.setitem(g48dict, gs_KeyboardInterrupt, gcls_KeyboardInterrupt) m.gs_UserWarning = space.wrap('UserWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1450,7 +1457,7 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_UserWarning, _bases, _dic]) m.gcls_UserWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_UserWarning, gcls_UserWarning) + space.setitem(g48dict, gs_UserWarning, gcls_UserWarning) m.gs_SyntaxWarning = space.wrap('SyntaxWarning') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1459,10 +1466,10 @@ _bases = space.newtuple([gcls_Warning]) _args = space.newtuple([gs_SyntaxWarning, _bases, _dic]) m.gcls_SyntaxWarning = space.call(space.w_type, _args) - space.setitem(g47dict, gs_SyntaxWarning, gcls_SyntaxWarning) - space.setitem(g47dict, gs___doc__, __doc__) - space.setitem(g47dict, gs_ArithmeticError, gcls_ArithmeticError) - space.setitem(g47dict, gs_Warning, gcls_Warning) + space.setitem(g48dict, gs_SyntaxWarning, gcls_SyntaxWarning) + space.setitem(g48dict, gs___doc__, __doc__) + space.setitem(g48dict, gs_ArithmeticError, gcls_ArithmeticError) + space.setitem(g48dict, gs_Warning, gcls_Warning) m.gs_NotImplementedError = space.wrap('NotImplementedError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1471,7 +1478,7 @@ _bases = space.newtuple([gcls_RuntimeError]) _args = space.newtuple([gs_NotImplementedError, _bases, _dic]) m.gcls_NotImplementedError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_NotImplementedError, gcls_NotImplementedError) + space.setitem(g48dict, gs_NotImplementedError, gcls_NotImplementedError) m.gs_SystemError = space.wrap('SystemError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1483,7 +1490,7 @@ _bases = space.newtuple([gcls_StandardError]) _args = space.newtuple([gs_SystemError, _bases, _dic]) m.gcls_SystemError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_SystemError, gcls_SystemError) + space.setitem(g48dict, gs_SystemError, gcls_SystemError) m.gs_OverflowError = space.wrap('OverflowError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1492,7 +1499,7 @@ _bases = space.newtuple([gcls_ArithmeticError]) _args = space.newtuple([gs_OverflowError, _bases, _dic]) m.gcls_OverflowError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_OverflowError, gcls_OverflowError) + space.setitem(g48dict, gs_OverflowError, gcls_OverflowError) m.gs_WindowsError = space.wrap('WindowsError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1501,7 +1508,7 @@ _bases = space.newtuple([gcls_OSError]) _args = space.newtuple([gs_WindowsError, _bases, _dic]) m.gcls_WindowsError = space.call(space.w_type, _args) - space.setitem(g47dict, gs_WindowsError, gcls_WindowsError) + space.setitem(g48dict, gs_WindowsError, gcls_WindowsError) m.gs___init__ = space.wrap('__init__') from pypy.interpreter.gateway import interp2app m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) @@ -1555,6 +1562,7 @@ del m.__str__ del m.__init__ del m.__getitem__ + m.gs_getattr = space.wrap('getattr') m.gs_start = space.wrap('start') m.gs_start_ = space.wrap('start=') m.gs_reason = space.wrap('reason') @@ -1579,5 +1587,5 @@ m.gs_encoding = space.wrap('encoding') m.gs_encoding_ = space.wrap('encoding=') m.gi_5 = space.newint(5) - return g47dict + return g48dict Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 14:07:42 2005 @@ -145,7 +145,9 @@ self.space = FlowObjSpace() # for introspection - self.use_fast_call = False + self.use_fast_call = False + + self._space_arities = None def expr(self, v, localnames, wrapped = True): if isinstance(v, Variable): @@ -189,11 +191,13 @@ def oper(self, op, localnames): if op.opname == "simple_call": v = op.args[0] - exv = self.expr(v, localnames) - if exv.startswith("space.") and not exv.startswith("space.w_"): - # it is a space method + space_shortcut = self.try_space_shortcut_for_builtin(v, len(op.args)-1) + if space_shortcut is not None: + # space method call + exv = space_shortcut fmt = "%(res)s = %(func)s(%(args)s)" else: + exv = self.expr(v, localnames) # default for a spacecall: fmt = "%(res)s = space.call_function(%(func)s, %(args)s)" # see if we can optimize for a fast call. @@ -523,11 +527,26 @@ self.later(initinstance()) return name + def space_arities(self): + if self._space_arities is None: + arities = self._space_arities = {} + for name, sym, arity, specnames in self.space.MethodTable: + arities[name] = arity + return self._space_arities + + def try_space_shortcut_for_builtin(self, v, nargs): + if isinstance(v, Constant) and type(v.value) is type(len): + func = v.value + name = func.__name__ + if func.__self__ is None and hasattr(self.space, name): + if self.space_arities().get(name, -1) == nargs: + return "space.%s" % name + return None + def nameof_builtin_function_or_method(self, func): if func.__self__ is None: # builtin function - if hasattr(self.space, func.__name__): - return "space.%s" % func.__name__ + # where does it come from? Python2.2 doesn't have func.__module__ for modname, module in sys.modules.items(): if hasattr(module, '__file__'): From pedronis at codespeak.net Mon Feb 21 14:16:05 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 14:16:05 +0100 (MET) Subject: [pypy-svn] r9380 - pypy/dist/pypy/translator Message-ID: <20050221131605.AEE6D27B56@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 14:16:05 2005 New Revision: 9380 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: show func module and name in the warning Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 14:16:05 2005 @@ -568,7 +568,7 @@ return "(space.sys.get(space.str_w(%s)))" % self.nameof(func.__name__) else: print ("WARNING: accessing builtin modules different from sys or __builtin__" - " is likely producing non-sense") + " is likely producing non-sense: %s %s" % (module.__name__, func.__name__)) name = self.uniquename('gbltin_' + func.__name__) self.initcode.append('m.%s = space.getattr(%s, %s)' % ( name, self.nameof(module), self.nameof(func.__name__))) From pedronis at codespeak.net Mon Feb 21 14:24:04 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 14:24:04 +0100 (MET) Subject: [pypy-svn] r9381 - in pypy/dist/pypy: lib module translator Message-ID: <20050221132404.9579727B56@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 14:24:04 2005 New Revision: 9381 Modified: pypy/dist/pypy/lib/_classobj.py pypy/dist/pypy/module/classobjinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: regenerate classobjinterp Modified: pypy/dist/pypy/lib/_classobj.py ============================================================================== --- pypy/dist/pypy/lib/_classobj.py (original) +++ pypy/dist/pypy/lib/_classobj.py Mon Feb 21 14:24:04 2005 @@ -447,7 +447,7 @@ return func(other) return NotImplemented else: - return operator.pow(self, other) + return operator.pow(self, other, None) else: # CPython also doesn't try coercion in this case func = instance_getattr1(self, '__pow__', False) @@ -465,7 +465,7 @@ return func(other) return NotImplemented else: - return operator.pow(other, self) + return operator.pow(other, self, None) else: # CPython also doesn't try coercion in this case func = instance_getattr1(self, '__rpow__', False) Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Mon Feb 21 14:24:04 2005 @@ -5886,7 +5886,7 @@ goto = 10 if goto == 7: - w_16 = space.pow(w_self_6, w_other_6) + w_16 = space.pow(w_self_6, w_other_6, space.w_None) w_14 = w_16 goto = 10 @@ -5992,7 +5992,7 @@ goto = 10 if goto == 7: - w_16 = space.pow(w_other_6, w_self_6) + w_16 = space.pow(w_other_6, w_self_6, space.w_None) w_14 = w_16 goto = 10 @@ -6685,7 +6685,7 @@ goto = 6 if goto == 5: - w_13 = space.builtin.get('_seqiter')(w_self_2) + w_13 = space.call_function(space.builtin.get('_seqiter'), w_self_2) w_6 = w_13 goto = 7 Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 14:24:04 2005 @@ -532,6 +532,7 @@ arities = self._space_arities = {} for name, sym, arity, specnames in self.space.MethodTable: arities[name] = arity + arities['isinstance'] = 2 return self._space_arities def try_space_shortcut_for_builtin(self, v, nargs): From tismer at codespeak.net Mon Feb 21 15:53:58 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 21 Feb 2005 15:53:58 +0100 (MET) Subject: [pypy-svn] r9383 - in pypy/dist/pypy/translator: . tool Message-ID: <20050221145358.94B0327B5E@code1.codespeak.net> Author: tismer Date: Mon Feb 21 15:53:58 2005 New Revision: 9383 Modified: pypy/dist/pypy/translator/geninterplevel.py pypy/dist/pypy/translator/tool/tointerplevel.py Log: a few refinements to gen/to interplevel. tointerplevel generates a module's dict if not told otherwise by entry points. geninterplevel has a new function translate_as_module which takes source text, translates it to interplevel, and returns the init function. Calling that with a space returns the module's dict. Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 15:53:58 2005 @@ -45,6 +45,9 @@ from pypy.tool.sourcetools import render_docstr +# change default +FlowObjSpace.builtins_can_raise_exceptions = True + # ____________________________________________________________ def c_string(s): @@ -113,14 +116,14 @@ return name class GenRpy: - def __init__(self, translator, entrypoint=None, modname=None): + def __init__(self, translator, entrypoint=None, modname=None, moddict=None): self.translator = translator if entrypoint is None: entrypoint = translator.entrypoint self.entrypoint = entrypoint self.modname = self.trans_funcname(modname or uniquemodulename(entrypoint)) - self.moddict = None # the dict if we translate a module + self.moddict = moddict # the dict if we translate a module self.rpynames = {Constant(None).key: 'space.w_None', Constant(False).key: 'space.w_False', Constant(True).key: 'space.w_True', @@ -145,7 +148,7 @@ self.space = FlowObjSpace() # for introspection - self.use_fast_call = False + self.use_fast_call = True self._space_arities = None @@ -547,7 +550,6 @@ def nameof_builtin_function_or_method(self, func): if func.__self__ is None: # builtin function - # where does it come from? Python2.2 doesn't have func.__module__ for modname, module in sys.modules.items(): if hasattr(module, '__file__'): @@ -875,12 +877,17 @@ print >> f, indent + codeline self.gen_trailer(info, " ") - - f.close() + # do not close the file here! def gen_trailer(self, info, indent): - info['entrypointname'] = self.trans_funcname(self.entrypoint.__name__) - print >> self.f, self.RPY_INIT_FOOTER % info + if self.moddict: + # we are generating a module, no __main__ etc. + print >> self.f, indent + "return %s" % self.nameof(self.entrypoint) + print >> self.f + else: + # we should have an entrypoint function + info['entrypointname'] = self.trans_funcname(self.entrypoint.__name__) + print >> self.f, self.RPY_INIT_FOOTER % info def gen_global_declarations(self): g = self.globaldecl @@ -1393,14 +1400,13 @@ all_entries) entrypoint = entrypoints[-2] -if __name__ == "__main__": +if False and __name__ == "__main__": # XXX TODO: # extract certain stuff like a general module maker # and put this into tools/compile_exceptions, maybe??? dic, entrypoint = exceptions_helper() t = Translator(None, verbose=False, simplifying=True) gen = GenRpy(t, entrypoint) - gen.use_fast_call = True gen.moddict = dic gen.gen_source('/tmp/look.py') @@ -1439,3 +1445,60 @@ t = Translator(test, verbose=False, simplifying=True) gen2 = GenRpy(t) gen2.gen_source("/tmp/look2.py") + + +import py.code +import cStringIO as StringIO + +def translate_as_module(sourcetext, modname="app2interpexec", tmpname=None): + """ compile sourcetext as a module, translatingto interp level. + The result is the init function that creates the wrapped module dict. + This init function needs a space as argument. + Example: + + initfunc = translate_as_module(text) + from pypy.objspace.stdimport Space + space = Space() + dic = ini(space) + # and now use the members of the dict + """ + # create something like a module + code = py.code.Source(sourcetext).compile() + dic = {'__name__': modname} + exec code in dic + del dic['__builtins__'] + entrypoint = dic + t = Translator(None, verbose=False, simplifying=True) + gen = GenRpy(t, entrypoint, modname, dic) + if tmpname: + out = file(tmpname, 'w') + def readback(): + out.close() + return file(tmpname, 'r').read() + else: + import cStringIO as StringIO + out = StringIO.StringIO() + def readback(): + out.seek(0) + return out.read() + gen.f = out + gen.gen_source_temp() + newsrc = readback() + code = py.code.Source(newsrc).compile() + dic = {'__name__': modname} + exec code in dic + # now we just need to return the init function, + # which then needs to be called with the space to return the dict. + return dic['init%s' % modname] + +testcode = """ +def f(a, b): + return a + b + +def g(): + return f(f(1, 2), f(4, 8)) +""" + +if __name__ == '__main__': + res = translate_as_module(testcode)#, tmpname='/tmp/look.py') + \ No newline at end of file Modified: pypy/dist/pypy/translator/tool/tointerplevel.py ============================================================================== --- pypy/dist/pypy/translator/tool/tointerplevel.py (original) +++ pypy/dist/pypy/translator/tool/tointerplevel.py Mon Feb 21 15:53:58 2005 @@ -20,9 +20,11 @@ options, args = opt_parser.parse_args() + if len(args) < 1: + opt_parser.error("missing module-file") if len(args) < 2: - opt_parser.error("missing module-file and at least one obj-name") - + print "no obj-name given. Using the module dict!" + modfile = os.path.abspath(args[0]) name = os.path.splitext(os.path.basename(modfile))[0] @@ -43,22 +45,17 @@ try: objs.append(getattr(mod, objname)) except AttributeError, e: - raise Exception,"module has no object '%s'" % name + raise Exception,"module has no object '%s'" % objname - if len(objs) == 1: + if len(objs) == 0: + entrypoint = mod.__dict__ + elif len(objs) == 1: entrypoint = objs[0] else: entrypoint = tuple(objs) t = Translator(None, verbose=False, simplifying=True) - gen = GenRpy(t, entrypoint, modname) - def gen_trailer(info, indent): - print >>gen.f, indent + "return %s" % gen.nameof(entrypoint) - print >>gen.f - - gen.use_fast_call = True - gen.moddict = mod.__dict__ # xxx control this - gen.gen_trailer = gen_trailer + gen = GenRpy(t, entrypoint, modname, mod.__dict__) output = options.output or modname + "interp.py" From tismer at codespeak.net Mon Feb 21 17:33:54 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 21 Feb 2005 17:33:54 +0100 (MET) Subject: [pypy-svn] r9385 - pypy/dist/pypy/translator Message-ID: <20050221163354.637D727B99@code1.codespeak.net> Author: tismer Date: Mon Feb 21 17:33:54 2005 New Revision: 9385 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: better doc string Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 17:33:54 2005 @@ -1451,9 +1451,13 @@ import cStringIO as StringIO def translate_as_module(sourcetext, modname="app2interpexec", tmpname=None): - """ compile sourcetext as a module, translatingto interp level. + """ compile sourcetext as a module, translating to interp level. The result is the init function that creates the wrapped module dict. This init function needs a space as argument. + tmpname can be passed for debugging purposes. Note that the generated + output is not sorted, because it is not meant to be persistent. + For persistent output, please use pypy/translator/tool/tointerplevel.py + Example: initfunc = translate_as_module(text) @@ -1491,6 +1495,10 @@ # which then needs to be called with the space to return the dict. return dic['init%s' % modname] +#___________________________________________________________________ + +# some testing code + testcode = """ def f(a, b): return a + b @@ -1501,4 +1509,3 @@ if __name__ == '__main__': res = translate_as_module(testcode)#, tmpname='/tmp/look.py') - \ No newline at end of file From tismer at codespeak.net Mon Feb 21 17:35:16 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 21 Feb 2005 17:35:16 +0100 (MET) Subject: [pypy-svn] r9386 - pypy/dist/pypy/interpreter Message-ID: <20050221163516.1AA7227B99@code1.codespeak.net> Author: tismer Date: Mon Feb 21 17:35:15 2005 New Revision: 9386 Modified: pypy/dist/pypy/interpreter/gateway.py Log: added an experimental applevelinterp with the same interface as applevel. The only difference is that it translates to interp level using geninterplevel.py Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 21 17:35:15 2005 @@ -500,7 +500,7 @@ return self.__dict__.setdefault(space, Cache()) -# and now for something completly different ... +# and now for something completely different ... # class applevel: @@ -546,6 +546,29 @@ appcaller.get_function = get_function return appcaller +## XXX experimental code using geninterplevel + +class applevelinterp(applevel): + """ same as applevel, but using translation to interp-level. + Hopefully this will replace applevelatsome point. + """ + NOT_RPYTHON_ATTRIBUTES = ['initfunc'] + + def __init__(self, source, modname = 'applevelinterp'): + "NOT_RPYTHON" + from pypy.translator.geninterplevel import translate_as_module + self.initfunc = translate_as_module(source, modname) + + def getwdict(self, space): + return space.loadfromcache(self, applevelinterp._builddict, + space._gatewaycache) + + def _builddict(self, space): + "NOT_RPYTHON" + w_glob = self.initfunc(space) + return w_glob + + def appdef(source, applevel=applevel): """ NOT_RPYTHON: build an app-level helper function, like for example: myfunc = appdef('''myfunc(x, y): From tismer at codespeak.net Mon Feb 21 18:20:17 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 21 Feb 2005 18:20:17 +0100 (MET) Subject: [pypy-svn] r9388 - in pypy/dist/pypy/interpreter: . test Message-ID: <20050221172017.53DB027B99@code1.codespeak.net> Author: tismer Date: Mon Feb 21 18:20:17 2005 New Revision: 9388 Modified: pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/interpreter/test/test_gateway.py Log: added alternative versions of applevel and related things. My first trial to extend a given test case gaveproblems for the naming conventions of app_xxx functions. We need to talk about this! Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 21 18:20:17 2005 @@ -589,11 +589,16 @@ app2interp = appdef # backward compatibility -# app2interp_temp is used for testing mainly +# the following two will probably get merged into one class applevel_temp(applevel): def getwdict(self, space): return self._builddict(space) # no cache -def app2interp_temp(func): +class applevelinterp_temp(applevelinterp): + def getwdict(self, space): + return self._builddict(space) # no cache + +# app2interp_temp is used for testing mainly +def app2interp_temp(func, applevel_temp=applevel_temp): """ NOT_RPYTHON """ return appdef(func, applevel_temp) Modified: pypy/dist/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_gateway.py (original) +++ pypy/dist/pypy/interpreter/test/test_gateway.py Mon Feb 21 18:20:17 2005 @@ -77,6 +77,14 @@ g3 = gateway.app2interp_temp(app_g3) assert self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar')) + def test_app2interp2(self): + """same but using transformed code""" + w = self.space.wrap + def noapp_g3(a, b): + return a+b + g3 = gateway.app2interp_temp(noapp_g3, gateway.applevelinterp_temp) + assert self.space.eq_w(g3(self.space, w('foo'), w('bar')), w('foobar')) + def test_interp2app(self): space = self.space w = space.wrap From tismer at codespeak.net Mon Feb 21 18:23:25 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Mon, 21 Feb 2005 18:23:25 +0100 (MET) Subject: [pypy-svn] r9389 - pypy/dist/pypy/interpreter Message-ID: <20050221172325.24C1527B99@code1.codespeak.net> Author: tismer Date: Mon Feb 21 18:23:24 2005 New Revision: 9389 Modified: pypy/dist/pypy/interpreter/gateway.py Log: additional comments about app_xxx naming problem Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 21 18:23:24 2005 @@ -375,7 +375,7 @@ ismethod=None, spacearg=None, unwrap_spec = None): "NOT_RPYTHON" Wrappable.__init__(self) - # f must be a function whose name does NOT starts with 'app_' + # f must be a function whose name does NOT start with 'app_' self_type = None if hasattr(f, 'im_func'): self_type = f.im_class @@ -550,7 +550,7 @@ class applevelinterp(applevel): """ same as applevel, but using translation to interp-level. - Hopefully this will replace applevelatsome point. + Hopefully this will replace applevel at some point. """ NOT_RPYTHON_ATTRIBUTES = ['initfunc'] @@ -568,6 +568,8 @@ w_glob = self.initfunc(space) return w_glob +## XXX there is a problem with the naming convention of app_xxx not allowed +## for interp2app! What shall we do? def appdef(source, applevel=applevel): """ NOT_RPYTHON: build an app-level helper function, like for example: From pedronis at codespeak.net Mon Feb 21 22:44:49 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 22:44:49 +0100 (MET) Subject: [pypy-svn] r9390 - pypy/dist/pypy/objspace/std Message-ID: <20050221214449.4D74E27B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 22:44:48 2005 New Revision: 9390 Modified: pypy/dist/pypy/objspace/std/objspace.py Log: sanity check that no app-level code has seen dummy old-style classes impls Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Mon Feb 21 22:44:48 2005 @@ -94,6 +94,8 @@ def setup_old_style_classes(self): """NOT_RPYTHON""" from pypy.module import classobjinterp + # sanity check that this approach is working and is not too late + assert not self.is_true(self.contains(self.builtin.w_dict,self.wrap('_classobj'))) w_setup = classobjinterp.initclassobj(self) w_classobj, w_instance, w_purify = self.unpackiterable(w_setup) self.call_function(w_purify) From pedronis at codespeak.net Mon Feb 21 22:47:41 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 22:47:41 +0100 (MET) Subject: [pypy-svn] r9391 - pypy/dist/pypy/objspace/std Message-ID: <20050221214741.45A3B27B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 22:47:41 2005 New Revision: 9391 Modified: pypy/dist/pypy/objspace/std/objspace.py Log: assert msg Modified: pypy/dist/pypy/objspace/std/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/std/objspace.py (original) +++ pypy/dist/pypy/objspace/std/objspace.py Mon Feb 21 22:47:41 2005 @@ -95,7 +95,7 @@ """NOT_RPYTHON""" from pypy.module import classobjinterp # sanity check that this approach is working and is not too late - assert not self.is_true(self.contains(self.builtin.w_dict,self.wrap('_classobj'))) + assert not self.is_true(self.contains(self.builtin.w_dict,self.wrap('_classobj'))),"app-level code has seen dummy old style classes" w_setup = classobjinterp.initclassobj(self) w_classobj, w_instance, w_purify = self.unpackiterable(w_setup) self.call_function(w_purify) From pedronis at codespeak.net Mon Feb 21 23:03:14 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 23:03:14 +0100 (MET) Subject: [pypy-svn] r9392 - pypy/dist/pypy/objspace/std Message-ID: <20050221220314.A907D27B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 23:03:14 2005 New Revision: 9392 Modified: pypy/dist/pypy/objspace/std/floatobject.py pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/tupleobject.py Log: removed the last overkill usages of importall Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Mon Feb 21 23:03:14 2005 @@ -63,6 +63,7 @@ return r else: return r + '.0' +repr__Float = gateway.app2interp(app_repr__Float) def app_str__Float(f): r = "%.12g"%f @@ -71,6 +72,7 @@ return r else: return r + '.0' +str__Float = gateway.app2interp(app_str__Float) def lt__Float_Float(space, w_float1, w_float2): i = w_float1.floatval @@ -274,5 +276,4 @@ StdObjSpace.coerce.register(float_coerce, W_FloatObject) """ -gateway.importall(globals()) register_all(vars()) Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Mon Feb 21 23:03:14 2005 @@ -291,6 +291,7 @@ del currently_in_repr[list_id] except: pass +listrepr = gateway.app2interp(app_listrepr) def repr__List(space, w_list): if w_list.ob_size == 0: @@ -613,7 +614,5 @@ }; """ -from pypy.interpreter import gateway -gateway.importall(globals()) from pypy.objspace.std import listtype register_all(vars(), listtype) Modified: pypy/dist/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupleobject.py (original) +++ pypy/dist/pypy/objspace/std/tupleobject.py Mon Feb 21 23:03:14 2005 @@ -2,7 +2,7 @@ from pypy.objspace.std.intobject import W_IntObject from pypy.objspace.std.sliceobject import W_SliceObject from pypy.objspace.std import slicetype - +from pypy.interpreter import gateway class W_TupleObject(W_Object): from pypy.objspace.std.tupletype import tuple_typedef as typedef @@ -117,10 +117,10 @@ else: return "(" + ", ".join([repr(x) for x in t]) + ')' +repr__Tuple = gateway.app2interp(app_repr__Tuple) + def hash__Tuple(space, w_tuple): # silly-ish, but _correct_, while lacking it would be WRONG return space.len(w_tuple) -from pypy.interpreter import gateway -gateway.importall(globals()) register_all(vars()) From pedronis at codespeak.net Mon Feb 21 23:19:10 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 23:19:10 +0100 (MET) Subject: [pypy-svn] r9393 - in pypy/dist/pypy/interpreter: . test Message-ID: <20050221221910.6BDE727B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 23:19:10 2005 New Revision: 9393 Modified: pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/interpreter/test/test_gateway.py Log: removed unused importall exportall export_values Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 21 23:19:10 2005 @@ -4,8 +4,6 @@ * BuiltinCode (call interp-level code from app-level) * app2interp (embed an app-level function into an interp-level callable) * interp2app (publish an interp-level object to be visible from app-level) -* exportall (mass-call interp2app on a whole dict of objects) -* importall (mass-call app2interp on a whole dict of objects) """ @@ -446,49 +444,6 @@ fn = Function(space, code, None, defs, forcename = self.name) cache.content[self] = fn return fn - -def exportall(d, temporary=False): - """NOT_RPYTHON: Publish every function from a dict.""" - if temporary: - i2a = interp2app_temp - else: - i2a = interp2app - for name, obj in d.items(): - if isinstance(obj, types.FunctionType): - # names starting in 'app_' are supposedly already app-level - if name.startswith('app_'): - continue - # ignore tricky functions with another interp-level meaning - if name in ('__init__', '__new__'): - continue - # ignore names in '_xyz' - if name.startswith('_') and not name.endswith('_'): - continue - if 'app_'+name not in d: - d['app_'+name] = i2a(obj, name) - -def export_values(space, dic, w_namespace): - "NOT_RPYTHON" - for name, w_value in dic.items(): - if name.startswith('w_'): - if name == 'w_dict': - w_name = space.wrap('__dict__') - elif name == 'w_name': - w_name = space.wrap('__name__') - else: - w_name = space.wrap(name[2:]) - space.setitem(w_namespace, w_name, w_value) - -def importall(d, temporary=False): - """NOT_RPYTHON: Import all app_-level functions as Gateways into a dict.""" - if temporary: - a2i = app2interp_temp - else: - a2i = app2interp - for name, obj in d.items(): - if name.startswith('app_') and name[4:] not in d: - if isinstance(obj, types.FunctionType): - d[name[4:]] = a2i(obj) # # the next gateways are to be used only for Modified: pypy/dist/pypy/interpreter/test/test_gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/test/test_gateway.py (original) +++ pypy/dist/pypy/interpreter/test/test_gateway.py Mon Feb 21 23:19:10 2005 @@ -209,17 +209,5 @@ raises(gateway.OperationError,space.call_function,w_app_g3_f,w(None)) raises(gateway.OperationError,space.call_function,w_app_g3_f,w("foo")) - - def test_importall(self): - w = self.space.wrap - g = {'app_g3': app_g3} - gateway.importall(g, temporary=True) - g3 = g['g3'] - assert self.space.eq_w(g3(self.space, w('bar')), w('foobar')) - -## def test_exportall(self): -## not used any more - - def app_g3(b): return 'foo'+b From pedronis at codespeak.net Mon Feb 21 23:21:13 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 23:21:13 +0100 (MET) Subject: [pypy-svn] r9394 - pypy/dist/pypy/translator Message-ID: <20050221222113.0657B27B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 23:21:13 2005 New Revision: 9394 Modified: pypy/dist/pypy/translator/geninterplevel.py pypy/dist/pypy/translator/translator.py Log: do not change default setting globally, consider e.g a test situation etc... Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 23:21:13 2005 @@ -45,9 +45,6 @@ from pypy.tool.sourcetools import render_docstr -# change default -FlowObjSpace.builtins_can_raise_exceptions = True - # ____________________________________________________________ def c_string(s): @@ -1405,7 +1402,7 @@ # extract certain stuff like a general module maker # and put this into tools/compile_exceptions, maybe??? dic, entrypoint = exceptions_helper() - t = Translator(None, verbose=False, simplifying=True) + t = Translator(None, verbose=False, simplifying=True, builtins_can_raise_exceptions=True) gen = GenRpy(t, entrypoint) gen.moddict = dic gen.gen_source('/tmp/look.py') @@ -1422,7 +1419,7 @@ dic = None if entrypoint.__name__.endswith("_helper"): dic, entrypoint = entrypoint() - t = Translator(entrypoint, verbose=False, simplifying=True) + t = Translator(entrypoint, verbose=False, simplifying=True, builtins_can_raise_exceptions=True) gen = GenRpy(t) gen.use_fast_call = True if dic: gen.moddict = dic @@ -1442,7 +1439,7 @@ def test(): entrypoint() - t = Translator(test, verbose=False, simplifying=True) + t = Translator(test, verbose=False, simplifying=True, builtins_can_raise_exceptions=True) gen2 = GenRpy(t) gen2.gen_source("/tmp/look2.py") @@ -1472,7 +1469,7 @@ exec code in dic del dic['__builtins__'] entrypoint = dic - t = Translator(None, verbose=False, simplifying=True) + t = Translator(None, verbose=False, simplifying=True, builtins_can_raise_exceptions=True) gen = GenRpy(t, entrypoint, modname, dic) if tmpname: out = file(tmpname, 'w') Modified: pypy/dist/pypy/translator/translator.py ============================================================================== --- pypy/dist/pypy/translator/translator.py (original) +++ pypy/dist/pypy/translator/translator.py Mon Feb 21 23:21:13 2005 @@ -45,10 +45,11 @@ class Translator: - def __init__(self, func=None, verbose=False, simplifying=False): + def __init__(self, func=None, verbose=False, simplifying=False, builtins_can_raise_exceptions=False): self.entrypoint = func self.verbose = verbose self.simplifying = simplifying + self.builtins_can_raise_exceptions = builtins_can_raise_exceptions self.clear() def clear(self): @@ -74,6 +75,7 @@ func.__name__) assert not self.frozen space = FlowObjSpace() + space.builtins_can_raise_exceptions = self.builtins_can_raise_exceptions graph = space.build_flow(func) if self.simplifying: simplify_graph(graph) From pedronis at codespeak.net Mon Feb 21 23:36:56 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 23:36:56 +0100 (MET) Subject: [pypy-svn] r9395 - in pypy/dist/pypy: interpreter module translator Message-ID: <20050221223656.5D48027B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 23:36:56 2005 New Revision: 9395 Modified: pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/module/classobjinterp.py pypy/dist/pypy/module/exceptionsinterp.py pypy/dist/pypy/translator/geninterplevel.py Log: have the geninterplevel generated code use interp2app with the necessary unwrap_spec, removed the last name based heuristics from interp2app impl. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 21 23:36:56 2005 @@ -315,10 +315,6 @@ if unwrap_spec is None: unwrap_spec = getattr(func,'unwrap_spec',None) - if unwrap_spec is None and argnames == ['space', '__args__']: #xxx for geninterp - #print sys._getframe(2).f_globals['__name__'] - unwrap_spec = [ObjSpace, Arguments] - if unwrap_spec is None: unwrap_spec = [ObjSpace]+ [W_Root] * (len(argnames)-1) Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Mon Feb 21 23:36:56 2005 @@ -3,6 +3,7 @@ from pypy.interpreter.error import OperationError from pypy.interpreter.argument import Arguments +from pypy.interpreter import gateway ##SECTION## @@ -21,48 +22,17 @@ def _coerce(space, w_left, w_right): - w_0=w_3=w_4=w_5=w_6=w_7=v8=w_9=w_10=w_11=w_12=v13=w_etype=w_evalue=None + w_0=w_3=None goto = 1 # startblock while True: if goto == 1: - try: - w_0 = space.coerce(w_left, w_right) - w_3 = w_0 - goto = 5 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type - goto = 2 - else:raise # unhandled case, should not happen + w_0 = space.coerce(w_left, w_right) + w_3 = w_0 + goto = 2 if goto == 2: - w_7 = space.is_(w_6, space.w_TypeError) - v8 = space.is_true(w_7) - if v8 == True: - w_3 = space.w_None - goto = 5 - else: - assert v8 == False - w_9, w_10, w_11 = w_4, w_5, w_6 - goto = 3 - - if goto == 3: - w_12 = space.issubtype(w_11, space.w_TypeError) - v13 = space.is_true(w_12) - if v13 == True: - w_3 = space.w_None - goto = 5 - else: - assert v13 == False - w_etype, w_evalue = w_9, w_10 - goto = 4 - - if goto == 4: - raise OperationError(w_etype, w_evalue) - - if goto == 5: return w_3 fastf__coerce = _coerce @@ -743,23 +713,22 @@ w_9=v10=w_name_3=w_bases_2=w_dic_2=w_11=v12=w_bases_4=w_13=w_14=None w_name_4=w_bases_3=w_dic_3=w_15=v16=w_dic_5=w_17=w_18=w_name_5=None w_bases_5=w_dic_4=w_19=w_name_6=w_bases_6=w_dic_6=w_30=w_name_11=None - w_bases_11=w_dic_11=w_66=w_name_24=w_bases_24=w_dic_24=w_67=w_b=None - w_name_25=w_bases_25=w_dic_25=w_69=w_b_1=w_72=v73=w_name_27=w_bases_27=None - w_dic_27=w_b_2=w_74=w_75=v76=w_name_28=w_bases_28=w_dic_28=w_b_3=None - w_77=w_78=w_79=w_name_26=w_bases_26=w_dic_26=w_new_class=w_81=None - w_82=w_83=w_84=w_85=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None - w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_70=v71=None - w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_name_15=w_bases_15=w_dic_15=None - w_i_1=w_43=w_g=w_name_17=w_bases_17=w_dic_17=w_i_2=w_g_1=w_48=None - w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_2=w_49=w_50=w_name_19=None - w_bases_19=w_dic_19=w_i_4=w_g_3=w_51=w_52=v53=w_name_21=w_bases_21=None - w_dic_21=w_g_4=w_61=w_modname=w_63=v64=w_name_23=w_bases_23=w_dic_23=None - w_modname_1=w_65=w_name_20=w_bases_20=w_dic_20=w_i_5=w_i_6=w_name_16=None - w_bases_16=w_dic_16=w_44=w_45=w_46=w_59=v60=w_name_22=w_bases_22=None - w_dic_22=w_57=w_58=w_55=w_54=v56=w_name_7=w_bases_7=w_dic_7=w_20=None - w_21=w_22=w_23=v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=None - w_40=v41=w_name_10=w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=None - w_dic_8=w_29=None + w_bases_11=w_dic_11=w_65=w_name_23=w_bases_23=w_dic_23=w_66=w_b=None + w_name_24=w_bases_24=w_dic_24=w_68=w_b_1=w_71=v72=w_name_26=w_bases_26=None + w_dic_26=w_b_2=w_73=w_74=v75=w_name_27=w_bases_27=w_dic_27=w_b_3=None + w_76=w_77=w_78=w_name_25=w_bases_25=w_dic_25=w_new_class=w_80=None + w_81=w_82=w_83=w_84=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None + w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_69=v70=None + w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_g=w_name_15=w_bases_15=None + w_dic_15=w_i_1=w_g_1=w_47=w_name_17=w_bases_17=w_dic_17=w_i_2=None + w_g_2=w_48=w_49=w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_3=w_50=None + w_51=v52=w_name_20=w_bases_20=w_dic_20=w_g_4=w_60=w_modname=w_62=None + v63=w_name_22=w_bases_22=w_dic_22=w_modname_1=w_64=w_name_19=None + w_bases_19=w_dic_19=w_i_4=w_i_5=w_name_16=w_bases_16=w_dic_16=None + w_44=w_45=w_46=w_58=v59=w_name_21=w_bases_21=w_dic_21=w_56=w_57=None + w_54=w_53=v55=w_name_7=w_bases_7=w_dic_7=w_20=w_21=w_22=w_23=None + v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=w_40=v41=w_name_10=None + w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=w_dic_8=w_29=None goto = 1 # startblock while True: @@ -779,7 +748,7 @@ w_5 = fastf_type_err(space, gs_name, gs_string, w_name_2) w_6 = space.type(w_5) w_etype, w_evalue = w_6, w_5 - goto = 32 + goto = 31 if goto == 3: w_9 = space.is_(w_bases_1, space.w_None) @@ -807,7 +776,7 @@ w_13 = fastf_type_err(space, gs_bases, gs_tuple, w_bases_4) w_14 = space.type(w_13) w_etype, w_evalue = w_14, w_13 - goto = 32 + goto = 31 if goto == 6: w_15 = space.isinstance(w_dic_3, space.w_dict) @@ -824,7 +793,7 @@ w_17 = fastf_type_err(space, gs_dict, gs_dict, w_dic_5) w_18 = space.type(w_17) w_etype, w_evalue = w_18, w_17 - goto = 32 + goto = 31 if goto == 8: try: @@ -870,7 +839,7 @@ try: w_30 = space.getitem(w_dic_6, gs___module__) w_name_11, w_bases_11, w_dic_11 = w_name_6, w_bases_6, w_dic_6 - goto = 25 + goto = 24 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) = (w_name_6, @@ -895,7 +864,7 @@ assert v35 == False (w_name_14, w_bases_14, w_dic_14, w_37, w_38, w_39) = (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) - goto = 27 + goto = 26 if goto == 14: w_40 = space.issubtype(w_27, space.w_KeyError) @@ -907,217 +876,205 @@ else: assert v41 == False w_etype, w_evalue = w_25, w_26 - goto = 32 + goto = 31 if goto == 15: + w_42 = space.call_function((space.sys.get(space.str_w(gs__getframe))), w_i) try: - w_42 = space.call_function((space.sys.get(space.str_w(gs__getframe))), w_i) - (w_name_15, w_bases_15, w_dic_15, w_i_1, w_43) = (w_name_13, - w_bases_13, w_dic_13, w_i, w_42) + w_g = space.getattr(w_42, gs_f_globals) + (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1) = (w_name_13, + w_bases_13, w_dic_13, w_i, w_g) goto = 16 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_13, - w_bases_13, w_dic_13, e.w_type, e.w_value, e.w_type) - goto = 22 + w_bases_13, w_dic_13, space.w_AttributeError, e.w_value, + space.w_AttributeError) + goto = 21 else:raise # unhandled case, should not happen if goto == 16: try: - w_g = space.getattr(w_43, gs_f_globals) - (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_1) = (w_name_15, - w_bases_15, w_dic_15, w_i_1, w_g) + w_47 = space.getattr(w_g_1, gs_get) + (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, + w_48) = (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1, w_47) goto = 17 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_15, w_bases_15, w_dic_15, space.w_AttributeError, e.w_value, space.w_AttributeError) - goto = 22 + goto = 21 else:raise # unhandled case, should not happen if goto == 17: try: - w_48 = space.getattr(w_g_1, gs_get) - (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_2, - w_49) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_1, w_48) + w_49 = space.call_function(w_48, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) + (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_3, + w_50) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, w_49) goto = 18 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_17, - w_bases_17, w_dic_17, space.w_AttributeError, e.w_value, - space.w_AttributeError) - goto = 22 + w_bases_17, w_dic_17, e.w_type, e.w_value, e.w_type) + goto = 21 else:raise # unhandled case, should not happen if goto == 18: - try: - w_50 = space.call_function(w_49, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) - (w_name_19, w_bases_19, w_dic_19, w_i_4, w_g_3, - w_51) = (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_2, w_50) + w_51 = space.is_(w_50, g_object) + v52 = space.is_true(w_51) + if v52 == True: + (w_name_19, w_bases_19, w_dic_19, w_i_4) = (w_name_18, w_bases_18, + w_dic_18, w_i_3) goto = 19 - except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_18, - w_bases_18, w_dic_18, e.w_type, e.w_value, e.w_type) - goto = 22 - else:raise # unhandled case, should not happen - - if goto == 19: - w_52 = space.is_(w_51, g_object) - v53 = space.is_true(w_52) - if v53 == True: - (w_name_20, w_bases_20, w_dic_20, w_i_5) = (w_name_19, w_bases_19, - w_dic_19, w_i_4) - goto = 20 else: - assert v53 == False - (w_name_21, w_bases_21, w_dic_21, w_g_4) = (w_name_19, w_bases_19, - w_dic_19, w_g_3) - goto = 23 + assert v52 == False + (w_name_20, w_bases_20, w_dic_20, w_g_4) = (w_name_18, w_bases_18, + w_dic_18, w_g_3) + goto = 22 - if goto == 20: + if goto == 19: try: - w_i_6 = space.inplace_add(w_i_5, gi_1) - (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_20, w_bases_20, - w_dic_20, w_i_6) + w_i_5 = space.inplace_add(w_i_4, gi_1) + (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_19, w_bases_19, + w_dic_19, w_i_5) goto = 15 continue except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_OverflowError)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_20, - w_bases_20, w_dic_20, space.w_OverflowError, e.w_value, + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, + w_bases_19, w_dic_19, space.w_OverflowError, e.w_value, space.w_OverflowError) - goto = 22 + goto = 21 elif space.is_true(space.issubtype(e.w_type, space.w_FloatingPointError)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_20, - w_bases_20, w_dic_20, space.w_FloatingPointError, e.w_value, + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, + w_bases_19, w_dic_19, space.w_FloatingPointError, e.w_value, space.w_FloatingPointError) - goto = 22 + goto = 21 else:raise # unhandled case, should not happen - if goto == 21: - w_54 = space.issubtype(w_55, space.w_ValueError) - v56 = space.is_true(w_54) - if v56 == True: - w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 - goto = 25 + if goto == 20: + w_53 = space.issubtype(w_54, space.w_ValueError) + v55 = space.is_true(w_53) + if v55 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 + goto = 24 else: - assert v56 == False - w_etype, w_evalue = w_57, w_58 - goto = 32 + assert v55 == False + w_etype, w_evalue = w_56, w_57 + goto = 31 - if goto == 22: - w_59 = space.is_(w_46, space.w_ValueError) - v60 = space.is_true(w_59) - if v60 == True: + if goto == 21: + w_58 = space.is_(w_46, space.w_ValueError) + v59 = space.is_true(w_58) + if v59 == True: w_name_11, w_bases_11, w_dic_11 = w_name_16, w_bases_16, w_dic_16 - goto = 25 + goto = 24 else: - assert v60 == False - (w_name_22, w_bases_22, w_dic_22, w_57, w_58, w_55) = (w_name_16, + assert v59 == False + (w_name_21, w_bases_21, w_dic_21, w_56, w_57, w_54) = (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) - goto = 21 + goto = 20 continue - if goto == 23: - w_61 = space.getattr(w_g_4, gs_get) - w_modname = space.call_function(w_61, gs___name__, space.w_None) - w_63 = space.is_(w_modname, space.w_None) - v64 = space.is_true(w_63) - if v64 == True: - w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 - goto = 25 - else: - assert v64 == False - (w_name_23, w_bases_23, w_dic_23, w_modname_1) = (w_name_21, - w_bases_21, w_dic_21, w_modname) + if goto == 22: + w_60 = space.getattr(w_g_4, gs_get) + w_modname = space.call_function(w_60, gs___name__, space.w_None) + w_62 = space.is_(w_modname, space.w_None) + v63 = space.is_true(w_62) + if v63 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_20, w_bases_20, w_dic_20 goto = 24 + else: + assert v63 == False + (w_name_22, w_bases_22, w_dic_22, w_modname_1) = (w_name_20, + w_bases_20, w_dic_20, w_modname) + goto = 23 + + if goto == 23: + w_64 = space.setitem(w_dic_22, gs___module__, w_modname_1) + w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 + goto = 24 if goto == 24: - w_65 = space.setitem(w_dic_23, gs___module__, w_modname_1) - w_name_11, w_bases_11, w_dic_11 = w_name_23, w_bases_23, w_dic_23 + w_65 = space.iter(w_bases_11) + (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_11, w_bases_11, + w_dic_11, w_65) goto = 25 if goto == 25: - w_66 = space.iter(w_bases_11) - (w_name_24, w_bases_24, w_dic_24, w_67) = (w_name_11, w_bases_11, - w_dic_11, w_66) - goto = 26 - - if goto == 26: try: - w_b = space.next(w_67) - (w_name_25, w_bases_25, w_dic_25, w_69, w_b_1) = (w_name_24, - w_bases_24, w_dic_24, w_67, w_b) - goto = 28 + w_b = space.next(w_66) + (w_name_24, w_bases_24, w_dic_24, w_68, w_b_1) = (w_name_23, + w_bases_23, w_dic_23, w_66, w_b) + goto = 27 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): - w_name_26, w_bases_26, w_dic_26 = w_name_24, w_bases_24, w_dic_24 - goto = 31 + w_name_25, w_bases_25, w_dic_25 = w_name_23, w_bases_23, w_dic_23 + goto = 30 else:raise # unhandled case, should not happen - if goto == 27: - w_70 = space.issubtype(w_39, space.w_KeyError) - v71 = space.is_true(w_70) - if v71 == True: + if goto == 26: + w_69 = space.issubtype(w_39, space.w_KeyError) + v70 = space.is_true(w_69) + if v70 == True: (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_14, w_bases_14, w_dic_14, gi_0) goto = 15 continue else: - assert v71 == False + assert v70 == False w_etype, w_evalue = w_37, w_38 - goto = 32 + goto = 31 - if goto == 28: - w_72 = space.isinstance(w_b_1, gcls_classobj) - v73 = space.is_true(w_72) - if v73 == True: - (w_name_24, w_bases_24, w_dic_24, w_67) = (w_name_25, w_bases_25, - w_dic_25, w_69) - goto = 26 + if goto == 27: + w_71 = space.isinstance(w_b_1, gcls_classobj) + v72 = space.is_true(w_71) + if v72 == True: + (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_24, w_bases_24, + w_dic_24, w_68) + goto = 25 continue else: - assert v73 == False - (w_name_27, w_bases_27, w_dic_27, w_b_2) = (w_name_25, w_bases_25, - w_dic_25, w_b_1) - goto = 29 + assert v72 == False + (w_name_26, w_bases_26, w_dic_26, w_b_2) = (w_name_24, w_bases_24, + w_dic_24, w_b_1) + goto = 28 - if goto == 29: - w_74 = space.call_function(space.w_type, w_b_2) - w_75 = space.call_function((space.builtin.get(space.str_w(gs_callable))), w_74) - v76 = space.is_true(w_75) - if v76 == True: - (w_name_28, w_bases_28, w_dic_28, w_b_3) = (w_name_27, w_bases_27, - w_dic_27, w_b_2) - goto = 30 + if goto == 28: + w_73 = space.call_function(space.w_type, w_b_2) + w_74 = space.call_function((space.builtin.get(space.str_w(gs_callable))), w_73) + v75 = space.is_true(w_74) + if v75 == True: + (w_name_27, w_bases_27, w_dic_27, w_b_3) = (w_name_26, w_bases_26, + w_dic_26, w_b_2) + goto = 29 else: - assert v76 == False + assert v75 == False w_etype, w_evalue = space.w_TypeError, gs_base_must_be_class - goto = 32 + goto = 31 - if goto == 30: - w_77 = space.call_function(space.w_type, w_b_3) - w_78 = space.call_function(w_77, w_name_28, w_bases_28, w_dic_28) - w_79 = w_78 - goto = 33 + if goto == 29: + w_76 = space.call_function(space.w_type, w_b_3) + w_77 = space.call_function(w_76, w_name_27, w_bases_27, w_dic_27) + w_78 = w_77 + goto = 32 - if goto == 31: + if goto == 30: w_new_class = space.call_function(gbltinmethod___new__, gcls_classobj) - w_81 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_26) - w_82 = space.getattr(gdescriptor_classobj__name, gs___set__) - w_83 = space.call_function(w_82, w_new_class, w_name_26) - w_84 = space.getattr(gdescriptor_classobj__bases, gs___set__) - w_85 = space.call_function(w_84, w_new_class, w_bases_26) - w_79 = w_new_class - goto = 33 + w_80 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_25) + w_81 = space.getattr(gdescriptor_classobj__name, gs___set__) + w_82 = space.call_function(w_81, w_new_class, w_name_25) + w_83 = space.getattr(gdescriptor_classobj__bases, gs___set__) + w_84 = space.call_function(w_83, w_new_class, w_bases_25) + w_78 = w_new_class + goto = 32 - if goto == 32: + if goto == 31: raise OperationError(w_etype, w_evalue) - if goto == 33: - return w_79 + if goto == 32: + return w_78 fastf___new__ = __new__ @@ -7173,8 +7130,7 @@ m.gs__classobj = space.wrap('_classobj') space.setitem(_dic, gs___module__, gs__classobj) m.gs___new__ = space.wrap('__new__') - from pypy.interpreter.gateway import interp2app - m.gfunc___new__ = space.wrap(interp2app(f___new__)) + m.gfunc___new__ = space.wrap(gateway.interp2app(f___new__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gsm___new__ = space.wrap(gfunc___new__) space.setitem(_dic, gs___new__, gsm___new__) m.gs___slots__ = space.wrap('__slots__') @@ -7189,7 +7145,7 @@ m.gcls_classobj = space.call(space.w_type, _args) _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__classobj) - m.gfunc___new___1 = space.wrap(interp2app(f___new___1)) + m.gfunc___new___1 = space.wrap(gateway.interp2app(f___new___1, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gsm___new___1 = space.wrap(gfunc___new___1) space.setitem(_dic, gs___new__, gsm___new___1) m.gs__class = space.wrap('_class') @@ -7199,253 +7155,253 @@ _bases = space.newtuple([space.w_object]) _args = space.newtuple([gs_instance, _bases, _dic]) m.gcls_instance = space.call(space.w_type, _args) - m.gfunc_purify = space.wrap(interp2app(f_purify)) + m.gfunc_purify = space.wrap(gateway.interp2app(f_purify, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.g3tuple = space.newtuple([gcls_classobj, gcls_instance, gfunc_purify]) del m.purify m.gs___abs__ = space.wrap('__abs__') - m.gfunc_instance___abs__ = space.wrap(interp2app(f_instance___abs__)) + m.gfunc_instance___abs__ = space.wrap(gateway.interp2app(f_instance___abs__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___abs__, gfunc_instance___abs__) m.gs___add__ = space.wrap('__add__') - m.gfunc_instance___add__ = space.wrap(interp2app(f_instance___add__)) + m.gfunc_instance___add__ = space.wrap(gateway.interp2app(f_instance___add__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___add__, gfunc_instance___add__) m.gs___and__ = space.wrap('__and__') - m.gfunc_instance___and__ = space.wrap(interp2app(f_instance___and__)) + m.gfunc_instance___and__ = space.wrap(gateway.interp2app(f_instance___and__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___and__, gfunc_instance___and__) m.gs___call__ = space.wrap('__call__') - m.gfunc_instance___call__ = space.wrap(interp2app(f_instance___call__)) + m.gfunc_instance___call__ = space.wrap(gateway.interp2app(f_instance___call__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___call__, gfunc_instance___call__) m.gs___cmp__ = space.wrap('__cmp__') - m.gfunc_instance___cmp__ = space.wrap(interp2app(f_instance___cmp__)) + m.gfunc_instance___cmp__ = space.wrap(gateway.interp2app(f_instance___cmp__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___cmp__, gfunc_instance___cmp__) m.gs___coerce__ = space.wrap('__coerce__') - m.gfunc_instance___coerce__ = space.wrap(interp2app(f_instance___coerce__)) + m.gfunc_instance___coerce__ = space.wrap(gateway.interp2app(f_instance___coerce__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___coerce__, gfunc_instance___coerce__) m.gs___contains__ = space.wrap('__contains__') - m.gfunc_instance___contains__ = space.wrap(interp2app(f_instance___contains__)) + m.gfunc_instance___contains__ = space.wrap(gateway.interp2app(f_instance___contains__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___contains__, gfunc_instance___contains__) m.gs___delattr__ = space.wrap('__delattr__') - m.gfunc_instance___delattr__ = space.wrap(interp2app(f_instance___delattr__)) + m.gfunc_instance___delattr__ = space.wrap(gateway.interp2app(f_instance___delattr__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___delattr__, gfunc_instance___delattr__) m.gs___delitem__ = space.wrap('__delitem__') - m.gfunc_instance___delitem__ = space.wrap(interp2app(f_instance___delitem__)) + m.gfunc_instance___delitem__ = space.wrap(gateway.interp2app(f_instance___delitem__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___delitem__, gfunc_instance___delitem__) m.gs___div__ = space.wrap('__div__') - m.gfunc_instance___div__ = space.wrap(interp2app(f_instance___div__)) + m.gfunc_instance___div__ = space.wrap(gateway.interp2app(f_instance___div__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___div__, gfunc_instance___div__) m.gs___divmod__ = space.wrap('__divmod__') - m.gfunc_instance___divmod__ = space.wrap(interp2app(f_instance___divmod__)) + m.gfunc_instance___divmod__ = space.wrap(gateway.interp2app(f_instance___divmod__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___divmod__, gfunc_instance___divmod__) m.gs___eq__ = space.wrap('__eq__') - m.gfunc_instance___eq__ = space.wrap(interp2app(f_instance___eq__)) + m.gfunc_instance___eq__ = space.wrap(gateway.interp2app(f_instance___eq__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___eq__, gfunc_instance___eq__) m.gs___float__ = space.wrap('__float__') - m.gfunc_instance___float__ = space.wrap(interp2app(f_instance___float__)) + m.gfunc_instance___float__ = space.wrap(gateway.interp2app(f_instance___float__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___float__, gfunc_instance___float__) m.gs___floordiv__ = space.wrap('__floordiv__') - m.gfunc_instance___floordiv__ = space.wrap(interp2app(f_instance___floordiv__)) + m.gfunc_instance___floordiv__ = space.wrap(gateway.interp2app(f_instance___floordiv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___floordiv__, gfunc_instance___floordiv__) m.gs___ge__ = space.wrap('__ge__') - m.gfunc_instance___ge__ = space.wrap(interp2app(f_instance___ge__)) + m.gfunc_instance___ge__ = space.wrap(gateway.interp2app(f_instance___ge__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ge__, gfunc_instance___ge__) m.gs___getattribute__ = space.wrap('__getattribute__') - m.gfunc_instance___getattribute__ = space.wrap(interp2app(f_instance___getattribute__)) + m.gfunc_instance___getattribute__ = space.wrap(gateway.interp2app(f_instance___getattribute__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___getattribute__, gfunc_instance___getattribute__) m.gs___getitem__ = space.wrap('__getitem__') - m.gfunc_instance___getitem__ = space.wrap(interp2app(f_instance___getitem__)) + m.gfunc_instance___getitem__ = space.wrap(gateway.interp2app(f_instance___getitem__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___getitem__, gfunc_instance___getitem__) m.gs___gt__ = space.wrap('__gt__') - m.gfunc_instance___gt__ = space.wrap(interp2app(f_instance___gt__)) + m.gfunc_instance___gt__ = space.wrap(gateway.interp2app(f_instance___gt__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___gt__, gfunc_instance___gt__) m.gs___hash__ = space.wrap('__hash__') - m.gfunc_instance___hash__ = space.wrap(interp2app(f_instance___hash__)) + m.gfunc_instance___hash__ = space.wrap(gateway.interp2app(f_instance___hash__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___hash__, gfunc_instance___hash__) m.gs___hex__ = space.wrap('__hex__') - m.gfunc_instance___hex__ = space.wrap(interp2app(f_instance___hex__)) + m.gfunc_instance___hex__ = space.wrap(gateway.interp2app(f_instance___hex__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___hex__, gfunc_instance___hex__) m.gs___iadd__ = space.wrap('__iadd__') - m.gfunc_instance___iadd__ = space.wrap(interp2app(f_instance___iadd__)) + m.gfunc_instance___iadd__ = space.wrap(gateway.interp2app(f_instance___iadd__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___iadd__, gfunc_instance___iadd__) m.gs___iand__ = space.wrap('__iand__') - m.gfunc_instance___iand__ = space.wrap(interp2app(f_instance___iand__)) + m.gfunc_instance___iand__ = space.wrap(gateway.interp2app(f_instance___iand__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___iand__, gfunc_instance___iand__) m.gs___idiv__ = space.wrap('__idiv__') - m.gfunc_instance___idiv__ = space.wrap(interp2app(f_instance___idiv__)) + m.gfunc_instance___idiv__ = space.wrap(gateway.interp2app(f_instance___idiv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___idiv__, gfunc_instance___idiv__) m.gs___ifloordiv__ = space.wrap('__ifloordiv__') - m.gfunc_instance___ifloordiv__ = space.wrap(interp2app(f_instance___ifloordiv__)) + m.gfunc_instance___ifloordiv__ = space.wrap(gateway.interp2app(f_instance___ifloordiv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ifloordiv__, gfunc_instance___ifloordiv__) m.gs___ilshift__ = space.wrap('__ilshift__') - m.gfunc_instance___ilshift__ = space.wrap(interp2app(f_instance___ilshift__)) + m.gfunc_instance___ilshift__ = space.wrap(gateway.interp2app(f_instance___ilshift__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ilshift__, gfunc_instance___ilshift__) m.gs___imod__ = space.wrap('__imod__') - m.gfunc_instance___imod__ = space.wrap(interp2app(f_instance___imod__)) + m.gfunc_instance___imod__ = space.wrap(gateway.interp2app(f_instance___imod__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___imod__, gfunc_instance___imod__) m.gs___imul__ = space.wrap('__imul__') - m.gfunc_instance___imul__ = space.wrap(interp2app(f_instance___imul__)) + m.gfunc_instance___imul__ = space.wrap(gateway.interp2app(f_instance___imul__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___imul__, gfunc_instance___imul__) m.gs___int__ = space.wrap('__int__') - m.gfunc_instance___int__ = space.wrap(interp2app(f_instance___int__)) + m.gfunc_instance___int__ = space.wrap(gateway.interp2app(f_instance___int__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___int__, gfunc_instance___int__) m.gs___invert__ = space.wrap('__invert__') - m.gfunc_instance___invert__ = space.wrap(interp2app(f_instance___invert__)) + m.gfunc_instance___invert__ = space.wrap(gateway.interp2app(f_instance___invert__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___invert__, gfunc_instance___invert__) m.gs___ior__ = space.wrap('__ior__') - m.gfunc_instance___ior__ = space.wrap(interp2app(f_instance___ior__)) + m.gfunc_instance___ior__ = space.wrap(gateway.interp2app(f_instance___ior__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ior__, gfunc_instance___ior__) m.gs___ipow__ = space.wrap('__ipow__') - m.gfunc_instance___ipow__ = space.wrap(interp2app(f_instance___ipow__)) + m.gfunc_instance___ipow__ = space.wrap(gateway.interp2app(f_instance___ipow__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ipow__, gfunc_instance___ipow__) m.gs___irshift__ = space.wrap('__irshift__') - m.gfunc_instance___irshift__ = space.wrap(interp2app(f_instance___irshift__)) + m.gfunc_instance___irshift__ = space.wrap(gateway.interp2app(f_instance___irshift__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___irshift__, gfunc_instance___irshift__) m.gs___isub__ = space.wrap('__isub__') - m.gfunc_instance___isub__ = space.wrap(interp2app(f_instance___isub__)) + m.gfunc_instance___isub__ = space.wrap(gateway.interp2app(f_instance___isub__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___isub__, gfunc_instance___isub__) m.gs___iter__ = space.wrap('__iter__') - m.gfunc_instance___iter__ = space.wrap(interp2app(f_instance___iter__)) + m.gfunc_instance___iter__ = space.wrap(gateway.interp2app(f_instance___iter__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___iter__, gfunc_instance___iter__) m.gs___itruediv__ = space.wrap('__itruediv__') - m.gfunc_instance___itruediv__ = space.wrap(interp2app(f_instance___itruediv__)) + m.gfunc_instance___itruediv__ = space.wrap(gateway.interp2app(f_instance___itruediv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___itruediv__, gfunc_instance___itruediv__) m.gs___ixor__ = space.wrap('__ixor__') - m.gfunc_instance___ixor__ = space.wrap(interp2app(f_instance___ixor__)) + m.gfunc_instance___ixor__ = space.wrap(gateway.interp2app(f_instance___ixor__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ixor__, gfunc_instance___ixor__) m.gs___le__ = space.wrap('__le__') - m.gfunc_instance___le__ = space.wrap(interp2app(f_instance___le__)) + m.gfunc_instance___le__ = space.wrap(gateway.interp2app(f_instance___le__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___le__, gfunc_instance___le__) m.gs___len__ = space.wrap('__len__') - m.gfunc_instance___len__ = space.wrap(interp2app(f_instance___len__)) + m.gfunc_instance___len__ = space.wrap(gateway.interp2app(f_instance___len__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___len__, gfunc_instance___len__) m.gs___long__ = space.wrap('__long__') - m.gfunc_instance___long__ = space.wrap(interp2app(f_instance___long__)) + m.gfunc_instance___long__ = space.wrap(gateway.interp2app(f_instance___long__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___long__, gfunc_instance___long__) m.gs___lshift__ = space.wrap('__lshift__') - m.gfunc_instance___lshift__ = space.wrap(interp2app(f_instance___lshift__)) + m.gfunc_instance___lshift__ = space.wrap(gateway.interp2app(f_instance___lshift__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___lshift__, gfunc_instance___lshift__) m.gs___lt__ = space.wrap('__lt__') - m.gfunc_instance___lt__ = space.wrap(interp2app(f_instance___lt__)) + m.gfunc_instance___lt__ = space.wrap(gateway.interp2app(f_instance___lt__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___lt__, gfunc_instance___lt__) m.gs___mod__ = space.wrap('__mod__') - m.gfunc_instance___mod__ = space.wrap(interp2app(f_instance___mod__)) + m.gfunc_instance___mod__ = space.wrap(gateway.interp2app(f_instance___mod__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___mod__, gfunc_instance___mod__) m.gs___mul__ = space.wrap('__mul__') - m.gfunc_instance___mul__ = space.wrap(interp2app(f_instance___mul__)) + m.gfunc_instance___mul__ = space.wrap(gateway.interp2app(f_instance___mul__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___mul__, gfunc_instance___mul__) m.gs___ne__ = space.wrap('__ne__') - m.gfunc_instance___ne__ = space.wrap(interp2app(f_instance___ne__)) + m.gfunc_instance___ne__ = space.wrap(gateway.interp2app(f_instance___ne__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ne__, gfunc_instance___ne__) m.gs___neg__ = space.wrap('__neg__') - m.gfunc_instance___neg__ = space.wrap(interp2app(f_instance___neg__)) + m.gfunc_instance___neg__ = space.wrap(gateway.interp2app(f_instance___neg__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___neg__, gfunc_instance___neg__) m.gs___nonzero__ = space.wrap('__nonzero__') - m.gfunc_instance___nonzero__ = space.wrap(interp2app(f_instance___nonzero__)) + m.gfunc_instance___nonzero__ = space.wrap(gateway.interp2app(f_instance___nonzero__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___nonzero__, gfunc_instance___nonzero__) m.gs___oct__ = space.wrap('__oct__') - m.gfunc_instance___oct__ = space.wrap(interp2app(f_instance___oct__)) + m.gfunc_instance___oct__ = space.wrap(gateway.interp2app(f_instance___oct__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___oct__, gfunc_instance___oct__) m.gs___or__ = space.wrap('__or__') - m.gfunc_instance___or__ = space.wrap(interp2app(f_instance___or__)) + m.gfunc_instance___or__ = space.wrap(gateway.interp2app(f_instance___or__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___or__, gfunc_instance___or__) m.gs___pos__ = space.wrap('__pos__') - m.gfunc_instance___pos__ = space.wrap(interp2app(f_instance___pos__)) + m.gfunc_instance___pos__ = space.wrap(gateway.interp2app(f_instance___pos__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___pos__, gfunc_instance___pos__) m.gs___pow__ = space.wrap('__pow__') - m.gfunc_instance___pow__ = space.wrap(interp2app(f_instance___pow__)) + m.gfunc_instance___pow__ = space.wrap(gateway.interp2app(f_instance___pow__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___pow__, gfunc_instance___pow__) m.gs___radd__ = space.wrap('__radd__') - m.gfunc_instance___radd__ = space.wrap(interp2app(f_instance___radd__)) + m.gfunc_instance___radd__ = space.wrap(gateway.interp2app(f_instance___radd__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___radd__, gfunc_instance___radd__) m.gs___rand__ = space.wrap('__rand__') - m.gfunc_instance___rand__ = space.wrap(interp2app(f_instance___rand__)) + m.gfunc_instance___rand__ = space.wrap(gateway.interp2app(f_instance___rand__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rand__, gfunc_instance___rand__) m.gs___rdiv__ = space.wrap('__rdiv__') - m.gfunc_instance___rdiv__ = space.wrap(interp2app(f_instance___rdiv__)) + m.gfunc_instance___rdiv__ = space.wrap(gateway.interp2app(f_instance___rdiv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rdiv__, gfunc_instance___rdiv__) m.gs___rdivmod__ = space.wrap('__rdivmod__') - m.gfunc_instance___rdivmod__ = space.wrap(interp2app(f_instance___rdivmod__)) + m.gfunc_instance___rdivmod__ = space.wrap(gateway.interp2app(f_instance___rdivmod__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rdivmod__, gfunc_instance___rdivmod__) m.gs___repr__ = space.wrap('__repr__') - m.gfunc_instance___repr__ = space.wrap(interp2app(f_instance___repr__)) + m.gfunc_instance___repr__ = space.wrap(gateway.interp2app(f_instance___repr__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___repr__, gfunc_instance___repr__) m.gs___rfloordiv__ = space.wrap('__rfloordiv__') - m.gfunc_instance___rfloordiv__ = space.wrap(interp2app(f_instance___rfloordiv__)) + m.gfunc_instance___rfloordiv__ = space.wrap(gateway.interp2app(f_instance___rfloordiv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rfloordiv__, gfunc_instance___rfloordiv__) m.gs___rlshift__ = space.wrap('__rlshift__') - m.gfunc_instance___rlshift__ = space.wrap(interp2app(f_instance___rlshift__)) + m.gfunc_instance___rlshift__ = space.wrap(gateway.interp2app(f_instance___rlshift__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rlshift__, gfunc_instance___rlshift__) m.gs___rmod__ = space.wrap('__rmod__') - m.gfunc_instance___rmod__ = space.wrap(interp2app(f_instance___rmod__)) + m.gfunc_instance___rmod__ = space.wrap(gateway.interp2app(f_instance___rmod__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rmod__, gfunc_instance___rmod__) m.gs___rmul__ = space.wrap('__rmul__') - m.gfunc_instance___rmul__ = space.wrap(interp2app(f_instance___rmul__)) + m.gfunc_instance___rmul__ = space.wrap(gateway.interp2app(f_instance___rmul__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rmul__, gfunc_instance___rmul__) m.gs___ror__ = space.wrap('__ror__') - m.gfunc_instance___ror__ = space.wrap(interp2app(f_instance___ror__)) + m.gfunc_instance___ror__ = space.wrap(gateway.interp2app(f_instance___ror__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___ror__, gfunc_instance___ror__) m.gs___rpow__ = space.wrap('__rpow__') - m.gfunc_instance___rpow__ = space.wrap(interp2app(f_instance___rpow__)) + m.gfunc_instance___rpow__ = space.wrap(gateway.interp2app(f_instance___rpow__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rpow__, gfunc_instance___rpow__) m.gs___rrshift__ = space.wrap('__rrshift__') - m.gfunc_instance___rrshift__ = space.wrap(interp2app(f_instance___rrshift__)) + m.gfunc_instance___rrshift__ = space.wrap(gateway.interp2app(f_instance___rrshift__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rrshift__, gfunc_instance___rrshift__) m.gs___rshift__ = space.wrap('__rshift__') - m.gfunc_instance___rshift__ = space.wrap(interp2app(f_instance___rshift__)) + m.gfunc_instance___rshift__ = space.wrap(gateway.interp2app(f_instance___rshift__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rshift__, gfunc_instance___rshift__) m.gs___rsub__ = space.wrap('__rsub__') - m.gfunc_instance___rsub__ = space.wrap(interp2app(f_instance___rsub__)) + m.gfunc_instance___rsub__ = space.wrap(gateway.interp2app(f_instance___rsub__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rsub__, gfunc_instance___rsub__) m.gs___rtruediv__ = space.wrap('__rtruediv__') - m.gfunc_instance___rtruediv__ = space.wrap(interp2app(f_instance___rtruediv__)) + m.gfunc_instance___rtruediv__ = space.wrap(gateway.interp2app(f_instance___rtruediv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rtruediv__, gfunc_instance___rtruediv__) m.gs___rxor__ = space.wrap('__rxor__') - m.gfunc_instance___rxor__ = space.wrap(interp2app(f_instance___rxor__)) + m.gfunc_instance___rxor__ = space.wrap(gateway.interp2app(f_instance___rxor__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___rxor__, gfunc_instance___rxor__) m.gs___setattr__ = space.wrap('__setattr__') - m.gfunc_instance___setattr__ = space.wrap(interp2app(f_instance___setattr__)) + m.gfunc_instance___setattr__ = space.wrap(gateway.interp2app(f_instance___setattr__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___setattr__, gfunc_instance___setattr__) m.gs___setitem__ = space.wrap('__setitem__') - m.gfunc_instance___setitem__ = space.wrap(interp2app(f_instance___setitem__)) + m.gfunc_instance___setitem__ = space.wrap(gateway.interp2app(f_instance___setitem__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___setitem__, gfunc_instance___setitem__) m.gs___str__ = space.wrap('__str__') - m.gfunc_instance___str__ = space.wrap(interp2app(f_instance___str__)) + m.gfunc_instance___str__ = space.wrap(gateway.interp2app(f_instance___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___str__, gfunc_instance___str__) m.gs___sub__ = space.wrap('__sub__') - m.gfunc_instance___sub__ = space.wrap(interp2app(f_instance___sub__)) + m.gfunc_instance___sub__ = space.wrap(gateway.interp2app(f_instance___sub__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___sub__, gfunc_instance___sub__) m.gs___truediv__ = space.wrap('__truediv__') - m.gfunc_instance___truediv__ = space.wrap(interp2app(f_instance___truediv__)) + m.gfunc_instance___truediv__ = space.wrap(gateway.interp2app(f_instance___truediv__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___truediv__, gfunc_instance___truediv__) m.gs___xor__ = space.wrap('__xor__') - m.gfunc_instance___xor__ = space.wrap(interp2app(f_instance___xor__)) + m.gfunc_instance___xor__ = space.wrap(gateway.interp2app(f_instance___xor__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs___xor__, gfunc_instance___xor__) m.gs_next = space.wrap('next') - m.gfunc_instance_next = space.wrap(interp2app(f_instance_next)) + m.gfunc_instance_next = space.wrap(gateway.interp2app(f_instance_next, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_instance, gs_next, gfunc_instance_next) - m.gfunc_classobj___call__ = space.wrap(interp2app(f_classobj___call__)) + m.gfunc_classobj___call__ = space.wrap(gateway.interp2app(f_classobj___call__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_classobj, gs___call__, gfunc_classobj___call__) - m.gfunc_classobj___delattr__ = space.wrap(interp2app(f_classobj___delattr__)) + m.gfunc_classobj___delattr__ = space.wrap(gateway.interp2app(f_classobj___delattr__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_classobj, gs___delattr__, gfunc_classobj___delattr__) - m.gfunc_classobj___getattribute__ = space.wrap(interp2app(f_classobj___getattribute__)) + m.gfunc_classobj___getattribute__ = space.wrap(gateway.interp2app(f_classobj___getattribute__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_classobj, gs___getattribute__, gfunc_classobj___getattribute__) - m.gfunc_classobj___repr__ = space.wrap(interp2app(f_classobj___repr__)) + m.gfunc_classobj___repr__ = space.wrap(gateway.interp2app(f_classobj___repr__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_classobj, gs___repr__, gfunc_classobj___repr__) - m.gfunc_classobj___setattr__ = space.wrap(interp2app(f_classobj___setattr__)) + m.gfunc_classobj___setattr__ = space.wrap(gateway.interp2app(f_classobj___setattr__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_classobj, gs___setattr__, gfunc_classobj___setattr__) - m.gfunc_classobj___str__ = space.wrap(interp2app(f_classobj___str__)) + m.gfunc_classobj___str__ = space.wrap(gateway.interp2app(f_classobj___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_classobj, gs___str__, gfunc_classobj___str__) - m.gfunc_get_class_module = space.wrap(interp2app(f_get_class_module)) + m.gfunc_get_class_module = space.wrap(gateway.interp2app(f_get_class_module, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gs__ = space.wrap('?') m.gs___name__ = space.wrap('__name__') m.gs__s__s = space.wrap('%s.%s') del m.__str__ - m.gfunc_retrieve = space.wrap(interp2app(f_retrieve)) + m.gfunc_retrieve = space.wrap(gateway.interp2app(f_retrieve, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) del m.get_class_module m.gdescriptor_object___getattribute__ = space.getattr(space.w_object, gs___getattribute__) del m.retrieve - m.gfunc_set_name = space.wrap(interp2app(f_set_name)) + m.gfunc_set_name = space.wrap(gateway.interp2app(f_set_name, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gs___bases__ = space.wrap('__bases__') - m.gfunc_set_bases = space.wrap(interp2app(f_set_bases)) - m.gfunc_set_dict = space.wrap(interp2app(f_set_dict)) + m.gfunc_set_bases = space.wrap(gateway.interp2app(f_set_bases, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) + m.gfunc_set_dict = space.wrap(gateway.interp2app(f_set_dict, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gdescriptor_object___setattr__ = space.getattr(space.w_object, gs___setattr__) del m.__setattr__ m.gs___dict___must_be_a_dictionary_ob = space.wrap('__dict__ must be a dictionary object') @@ -7458,7 +7414,7 @@ m.gs___name___must_be_a_string_object = space.wrap('__name__ must be a string object') m.gdescriptor_classobj__name = space.getattr(gcls_classobj, gs__name) del m.set_name - m.gfunc_uid = space.wrap(interp2app(f_uid)) + m.gfunc_uid = space.wrap(gateway.interp2app(f_uid, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gs__class__s__s_at_0x_x_ = space.wrap('') del m.__repr__ m.gi_0 = space.newint(0) @@ -7467,9 +7423,9 @@ del m.uid m.gs___get__ = space.wrap('__get__') m.gi_1 = space.newint(1) - m.gfunc_lookup = space.wrap(interp2app(f_lookup)) + m.gfunc_lookup = space.wrap(gateway.interp2app(f_lookup, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gs_class__s_has_no_attribute__s = space.wrap('class %s has no attribute %s') - m.gfunc_mro_lookup = space.wrap(interp2app(f_mro_lookup)) + m.gfunc_mro_lookup = space.wrap(gateway.interp2app(f_mro_lookup, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) del m.__getattribute__ m.gs___mro__ = space.wrap('__mro__') del m.mro_lookup @@ -7480,7 +7436,7 @@ del m.__delattr__ m.gbltinmethod___new__ = space.getattr(space.w_object, gs___new__) m.gdescriptor_instance__class = space.getattr(gcls_instance, gs__class) - m.gfunc_instance_getattr1 = space.wrap(interp2app(f_instance_getattr1)) + m.gfunc_instance_getattr1 = space.wrap(gateway.interp2app(f_instance_getattr1, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gs___init__ = space.wrap('__init__') m.gs___init_____should_return_None = space.wrap('__init__() should return None') del m.__call__ @@ -7489,7 +7445,7 @@ del m.instance_getattr1 m.gs_instance_has_no_next___method = space.wrap('instance has no next() method') del m.next - m.gfunc__coerce = space.wrap(interp2app(f__coerce)) + m.gfunc__coerce = space.wrap(gateway.interp2app(f__coerce, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) del m.__xor__ del m._coerce del m.__truediv__ @@ -7583,7 +7539,7 @@ m.gs_instance___first_arg_must_be_cla = space.wrap('instance() first arg must be class') m.gs_instance___second_arg_must_be_di = space.wrap('instance() second arg must be dictionary or None') del m.__new__ - m.gfunc_type_err = space.wrap(interp2app(f_type_err)) + m.gfunc_type_err = space.wrap(gateway.interp2app(f_type_err, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) m.gs_name = space.wrap('name') m.gs_string = space.wrap('string') m.g0tuple = space.newtuple([]) Modified: pypy/dist/pypy/module/exceptionsinterp.py ============================================================================== --- pypy/dist/pypy/module/exceptionsinterp.py (original) +++ pypy/dist/pypy/module/exceptionsinterp.py Mon Feb 21 23:36:56 2005 @@ -3,6 +3,7 @@ from pypy.interpreter.error import OperationError from pypy.interpreter.argument import Arguments +from pypy.interpreter import gateway """Python's standard exception class hierarchy. @@ -158,7 +159,7 @@ # global object gs_EOFError # global object gcls_EOFError # global object gs___file__ -# global object gs__u_pedronis_PyPy_dist_pypy_lib__ +# global object gs__Users_pedronis_PyPy_dist_pypy_l # global object gs_TabError # global object gcls_TabError # global object gs_UnicodeEncodeError @@ -1354,8 +1355,8 @@ space.setitem(g48dict, gs_EOFError, gcls_EOFError) space.setitem(g48dict, gs_StandardError, gcls_StandardError) m.gs___file__ = space.wrap('__file__') - m.gs__u_pedronis_PyPy_dist_pypy_lib__ = space.wrap('/u/pedronis/PyPy/dist/pypy/lib/_exceptions.py') - space.setitem(g48dict, gs___file__, gs__u_pedronis_PyPy_dist_pypy_lib__) + m.gs__Users_pedronis_PyPy_dist_pypy_l = space.wrap('/Users/pedronis/PyPy/dist/pypy/lib/_exceptions.py') + space.setitem(g48dict, gs___file__, gs__Users_pedronis_PyPy_dist_pypy_l) m.gs_TabError = space.wrap('TabError') _dic = space.newdict([]) space.setitem(_dic, gs___module__, gs__exceptions) @@ -1510,19 +1511,18 @@ m.gcls_WindowsError = space.call(space.w_type, _args) space.setitem(g48dict, gs_WindowsError, gcls_WindowsError) m.gs___init__ = space.wrap('__init__') - from pypy.interpreter.gateway import interp2app - m.gfunc_UnicodeDecodeError___init__ = space.wrap(interp2app(f_UnicodeDecodeError___init__)) + m.gfunc_UnicodeDecodeError___init__ = space.wrap(gateway.interp2app(f_UnicodeDecodeError___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_UnicodeDecodeError, gs___init__, gfunc_UnicodeDecodeError___init__) m.gs___str__ = space.wrap('__str__') - m.gfunc_UnicodeDecodeError___str__ = space.wrap(interp2app(f_UnicodeDecodeError___str__)) + m.gfunc_UnicodeDecodeError___str__ = space.wrap(gateway.interp2app(f_UnicodeDecodeError___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_UnicodeDecodeError, gs___str__, gfunc_UnicodeDecodeError___str__) - m.gfunc_UnicodeEncodeError___init__ = space.wrap(interp2app(f_UnicodeEncodeError___init__)) + m.gfunc_UnicodeEncodeError___init__ = space.wrap(gateway.interp2app(f_UnicodeEncodeError___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_UnicodeEncodeError, gs___init__, gfunc_UnicodeEncodeError___init__) - m.gfunc_UnicodeEncodeError___str__ = space.wrap(interp2app(f_UnicodeEncodeError___str__)) + m.gfunc_UnicodeEncodeError___str__ = space.wrap(gateway.interp2app(f_UnicodeEncodeError___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_UnicodeEncodeError, gs___str__, gfunc_UnicodeEncodeError___str__) - m.gfunc_SyntaxError___init__ = space.wrap(interp2app(f_SyntaxError___init__)) + m.gfunc_SyntaxError___init__ = space.wrap(gateway.interp2app(f_SyntaxError___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_SyntaxError, gs___init__, gfunc_SyntaxError___init__) - m.gfunc_SyntaxError___str__ = space.wrap(interp2app(f_SyntaxError___str__)) + m.gfunc_SyntaxError___str__ = space.wrap(gateway.interp2app(f_SyntaxError___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_SyntaxError, gs___str__, gfunc_SyntaxError___str__) m.gs_filename = space.wrap('filename') space.setattr(gcls_SyntaxError, gs_filename, space.w_None) @@ -1537,24 +1537,24 @@ space.setattr(gcls_SyntaxError, gs_print_file_and_line, space.w_None) m.gs_text = space.wrap('text') space.setattr(gcls_SyntaxError, gs_text, space.w_None) - m.gfunc_EnvironmentError___init__ = space.wrap(interp2app(f_EnvironmentError___init__)) + m.gfunc_EnvironmentError___init__ = space.wrap(gateway.interp2app(f_EnvironmentError___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_EnvironmentError, gs___init__, gfunc_EnvironmentError___init__) - m.gfunc_EnvironmentError___str__ = space.wrap(interp2app(f_EnvironmentError___str__)) + m.gfunc_EnvironmentError___str__ = space.wrap(gateway.interp2app(f_EnvironmentError___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_EnvironmentError, gs___str__, gfunc_EnvironmentError___str__) - m.gfunc_SystemExit___init__ = space.wrap(interp2app(f_SystemExit___init__)) + m.gfunc_SystemExit___init__ = space.wrap(gateway.interp2app(f_SystemExit___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_SystemExit, gs___init__, gfunc_SystemExit___init__) - m.gfunc_KeyError___str__ = space.wrap(interp2app(f_KeyError___str__)) + m.gfunc_KeyError___str__ = space.wrap(gateway.interp2app(f_KeyError___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_KeyError, gs___str__, gfunc_KeyError___str__) - m.gfunc_UnicodeTranslateError___init__ = space.wrap(interp2app(f_UnicodeTranslateError___init__)) + m.gfunc_UnicodeTranslateError___init__ = space.wrap(gateway.interp2app(f_UnicodeTranslateError___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_UnicodeTranslateError, gs___init__, gfunc_UnicodeTranslateError___init__) - m.gfunc_UnicodeTranslateError___str__ = space.wrap(interp2app(f_UnicodeTranslateError___str__)) + m.gfunc_UnicodeTranslateError___str__ = space.wrap(gateway.interp2app(f_UnicodeTranslateError___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_UnicodeTranslateError, gs___str__, gfunc_UnicodeTranslateError___str__) m.gs___getitem__ = space.wrap('__getitem__') - m.gfunc_Exception___getitem__ = space.wrap(interp2app(f_Exception___getitem__)) + m.gfunc_Exception___getitem__ = space.wrap(gateway.interp2app(f_Exception___getitem__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_Exception, gs___getitem__, gfunc_Exception___getitem__) - m.gfunc_Exception___init__ = space.wrap(interp2app(f_Exception___init__)) + m.gfunc_Exception___init__ = space.wrap(gateway.interp2app(f_Exception___init__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_Exception, gs___init__, gfunc_Exception___init__) - m.gfunc_Exception___str__ = space.wrap(interp2app(f_Exception___str__)) + m.gfunc_Exception___str__ = space.wrap(gateway.interp2app(f_Exception___str__, unwrap_spec=[gateway.ObjSpace, gateway.Arguments])) space.setattr(gcls_Exception, gs___str__, gfunc_Exception___str__) m.gs_args = space.wrap('args') m.gi_0 = space.newint(0) Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Mon Feb 21 23:36:56 2005 @@ -455,8 +455,7 @@ name = self.uniquename('gfunc_' + self.trans_funcname( namehint + func.__name__)) f_name = 'f_' + name[6:] - self.initcode.append('from pypy.interpreter.gateway import interp2app') - self.initcode.append('m.%s = space.wrap(interp2app(%s))' % (name, f_name)) + self.initcode.append('m.%s = space.wrap(gateway.interp2app(%s, unwrap_spec=[gateway.ObjSpace, gateway.Arguments]))' % (name, f_name)) self.pendingfunctions.append(func) return name @@ -1152,6 +1151,7 @@ from pypy.interpreter.error import OperationError from pypy.interpreter.argument import Arguments +from pypy.interpreter import gateway ''' RPY_SEP = "#*************************************************************" From pedronis at codespeak.net Mon Feb 21 23:45:21 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 21 Feb 2005 23:45:21 +0100 (MET) Subject: [pypy-svn] r9396 - pypy/dist/pypy/interpreter Message-ID: <20050221224521.7F74B27B99@code1.codespeak.net> Author: pedronis Date: Mon Feb 21 23:45:21 2005 New Revision: 9396 Modified: pypy/dist/pypy/interpreter/gateway.py Log: removed unused arguments Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Mon Feb 21 23:45:21 2005 @@ -287,7 +287,7 @@ # When a BuiltinCode is stored in a Function object, # you get the functionality of CPython's built-in function type. - def __init__(self, func, ismethod=None, spacearg=None, unwrap_spec = None, self_type = None): + def __init__(self, func, unwrap_spec = None, self_type = None): "NOT_RPYTHON" # 'implfunc' is the interpreter-level function. # Note that this uses a lot of (construction-time) introspection. @@ -309,9 +309,6 @@ from pypy.interpreter import pycode argnames, varargname, kwargname = pycode.cpython_code_signature(func.func_code) - assert not ismethod, ("ismethod is not expected anymore") - assert not spacearg, ("spacearg is not expected anymore") - if unwrap_spec is None: unwrap_spec = getattr(func,'unwrap_spec',None) @@ -365,8 +362,7 @@ NOT_RPYTHON_ATTRIBUTES = ['_staticdefs'] - def __init__(self, f, app_name=None, - ismethod=None, spacearg=None, unwrap_spec = None): + def __init__(self, f, app_name=None, unwrap_spec = None): "NOT_RPYTHON" Wrappable.__init__(self) # f must be a function whose name does NOT start with 'app_' @@ -381,10 +377,7 @@ raise ValueError, ("function name %r suspiciously starts " "with 'app_'" % f.func_name) app_name = f.func_name - self._code = BuiltinCode(f, ismethod=ismethod, - spacearg=spacearg, - unwrap_spec=unwrap_spec, - self_type = self_type) + self._code = BuiltinCode(f, unwrap_spec=unwrap_spec, self_type = self_type) self.__name__ = f.func_name self.name = app_name self._staticdefs = list(f.func_defaults or ()) From pedronis at codespeak.net Tue Feb 22 00:08:42 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 22 Feb 2005 00:08:42 +0100 (MET) Subject: [pypy-svn] r9397 - in pypy/dist/pypy: module objspace/flow translator/tool Message-ID: <20050221230842.7DF5A27B99@code1.codespeak.net> Author: pedronis Date: Tue Feb 22 00:08:42 2005 New Revision: 9397 Modified: pypy/dist/pypy/module/classobjinterp.py pypy/dist/pypy/objspace/flow/objspace.py pypy/dist/pypy/translator/tool/tointerplevel.py Log: forgot tointerplevel Translator construction, so had to regen classobjinterp, oops Modified: pypy/dist/pypy/module/classobjinterp.py ============================================================================== --- pypy/dist/pypy/module/classobjinterp.py (original) +++ pypy/dist/pypy/module/classobjinterp.py Tue Feb 22 00:08:42 2005 @@ -22,17 +22,48 @@ def _coerce(space, w_left, w_right): - w_0=w_3=None + w_0=w_3=w_4=w_5=w_6=w_7=v8=w_9=w_10=w_11=w_12=v13=w_etype=w_evalue=None goto = 1 # startblock while True: if goto == 1: - w_0 = space.coerce(w_left, w_right) - w_3 = w_0 - goto = 2 + try: + w_0 = space.coerce(w_left, w_right) + w_3 = w_0 + goto = 5 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + w_4, w_5, w_6 = e.w_type, e.w_value, e.w_type + goto = 2 + else:raise # unhandled case, should not happen if goto == 2: + w_7 = space.is_(w_6, space.w_TypeError) + v8 = space.is_true(w_7) + if v8 == True: + w_3 = space.w_None + goto = 5 + else: + assert v8 == False + w_9, w_10, w_11 = w_4, w_5, w_6 + goto = 3 + + if goto == 3: + w_12 = space.issubtype(w_11, space.w_TypeError) + v13 = space.is_true(w_12) + if v13 == True: + w_3 = space.w_None + goto = 5 + else: + assert v13 == False + w_etype, w_evalue = w_9, w_10 + goto = 4 + + if goto == 4: + raise OperationError(w_etype, w_evalue) + + if goto == 5: return w_3 fastf__coerce = _coerce @@ -713,22 +744,23 @@ w_9=v10=w_name_3=w_bases_2=w_dic_2=w_11=v12=w_bases_4=w_13=w_14=None w_name_4=w_bases_3=w_dic_3=w_15=v16=w_dic_5=w_17=w_18=w_name_5=None w_bases_5=w_dic_4=w_19=w_name_6=w_bases_6=w_dic_6=w_30=w_name_11=None - w_bases_11=w_dic_11=w_65=w_name_23=w_bases_23=w_dic_23=w_66=w_b=None - w_name_24=w_bases_24=w_dic_24=w_68=w_b_1=w_71=v72=w_name_26=w_bases_26=None - w_dic_26=w_b_2=w_73=w_74=v75=w_name_27=w_bases_27=w_dic_27=w_b_3=None - w_76=w_77=w_78=w_name_25=w_bases_25=w_dic_25=w_new_class=w_80=None - w_81=w_82=w_83=w_84=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None - w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_69=v70=None - w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_g=w_name_15=w_bases_15=None - w_dic_15=w_i_1=w_g_1=w_47=w_name_17=w_bases_17=w_dic_17=w_i_2=None - w_g_2=w_48=w_49=w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_3=w_50=None - w_51=v52=w_name_20=w_bases_20=w_dic_20=w_g_4=w_60=w_modname=w_62=None - v63=w_name_22=w_bases_22=w_dic_22=w_modname_1=w_64=w_name_19=None - w_bases_19=w_dic_19=w_i_4=w_i_5=w_name_16=w_bases_16=w_dic_16=None - w_44=w_45=w_46=w_58=v59=w_name_21=w_bases_21=w_dic_21=w_56=w_57=None - w_54=w_53=v55=w_name_7=w_bases_7=w_dic_7=w_20=w_21=w_22=w_23=None - v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=w_40=v41=w_name_10=None - w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=w_dic_8=w_29=None + w_bases_11=w_dic_11=w_66=w_name_24=w_bases_24=w_dic_24=w_67=w_b=None + w_name_25=w_bases_25=w_dic_25=w_69=w_b_1=w_72=v73=w_name_27=w_bases_27=None + w_dic_27=w_b_2=w_74=w_75=v76=w_name_28=w_bases_28=w_dic_28=w_b_3=None + w_77=w_78=w_79=w_name_26=w_bases_26=w_dic_26=w_new_class=w_81=None + w_82=w_83=w_84=w_85=w_name_12=w_bases_12=w_dic_12=w_31=w_32=w_33=None + w_34=v35=w_name_14=w_bases_14=w_dic_14=w_37=w_38=w_39=w_70=v71=None + w_name_13=w_bases_13=w_dic_13=w_i=w_42=w_name_15=w_bases_15=w_dic_15=None + w_i_1=w_43=w_g=w_name_17=w_bases_17=w_dic_17=w_i_2=w_g_1=w_48=None + w_name_18=w_bases_18=w_dic_18=w_i_3=w_g_2=w_49=w_50=w_name_19=None + w_bases_19=w_dic_19=w_i_4=w_g_3=w_51=w_52=v53=w_name_21=w_bases_21=None + w_dic_21=w_g_4=w_61=w_modname=w_63=v64=w_name_23=w_bases_23=w_dic_23=None + w_modname_1=w_65=w_name_20=w_bases_20=w_dic_20=w_i_5=w_i_6=w_name_16=None + w_bases_16=w_dic_16=w_44=w_45=w_46=w_59=v60=w_name_22=w_bases_22=None + w_dic_22=w_57=w_58=w_55=w_54=v56=w_name_7=w_bases_7=w_dic_7=w_20=None + w_21=w_22=w_23=v24=w_name_9=w_bases_9=w_dic_9=w_25=w_26=w_27=None + w_40=v41=w_name_10=w_bases_10=w_dic_10=w_28=w_name_8=w_bases_8=None + w_dic_8=w_29=None goto = 1 # startblock while True: @@ -748,7 +780,7 @@ w_5 = fastf_type_err(space, gs_name, gs_string, w_name_2) w_6 = space.type(w_5) w_etype, w_evalue = w_6, w_5 - goto = 31 + goto = 32 if goto == 3: w_9 = space.is_(w_bases_1, space.w_None) @@ -776,7 +808,7 @@ w_13 = fastf_type_err(space, gs_bases, gs_tuple, w_bases_4) w_14 = space.type(w_13) w_etype, w_evalue = w_14, w_13 - goto = 31 + goto = 32 if goto == 6: w_15 = space.isinstance(w_dic_3, space.w_dict) @@ -793,7 +825,7 @@ w_17 = fastf_type_err(space, gs_dict, gs_dict, w_dic_5) w_18 = space.type(w_17) w_etype, w_evalue = w_18, w_17 - goto = 31 + goto = 32 if goto == 8: try: @@ -839,7 +871,7 @@ try: w_30 = space.getitem(w_dic_6, gs___module__) w_name_11, w_bases_11, w_dic_11 = w_name_6, w_bases_6, w_dic_6 - goto = 24 + goto = 25 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_IndexError)): (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) = (w_name_6, @@ -864,7 +896,7 @@ assert v35 == False (w_name_14, w_bases_14, w_dic_14, w_37, w_38, w_39) = (w_name_12, w_bases_12, w_dic_12, w_31, w_32, w_33) - goto = 26 + goto = 27 if goto == 14: w_40 = space.issubtype(w_27, space.w_KeyError) @@ -876,205 +908,217 @@ else: assert v41 == False w_etype, w_evalue = w_25, w_26 - goto = 31 + goto = 32 if goto == 15: - w_42 = space.call_function((space.sys.get(space.str_w(gs__getframe))), w_i) try: - w_g = space.getattr(w_42, gs_f_globals) - (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1) = (w_name_13, - w_bases_13, w_dic_13, w_i, w_g) + w_42 = space.call_function((space.sys.get(space.str_w(gs__getframe))), w_i) + (w_name_15, w_bases_15, w_dic_15, w_i_1, w_43) = (w_name_13, + w_bases_13, w_dic_13, w_i, w_42) goto = 16 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_13, - w_bases_13, w_dic_13, space.w_AttributeError, e.w_value, - space.w_AttributeError) - goto = 21 + w_bases_13, w_dic_13, e.w_type, e.w_value, e.w_type) + goto = 22 else:raise # unhandled case, should not happen if goto == 16: try: - w_47 = space.getattr(w_g_1, gs_get) - (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, - w_48) = (w_name_15, w_bases_15, w_dic_15, w_i_1, w_g_1, w_47) + w_g = space.getattr(w_43, gs_f_globals) + (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_1) = (w_name_15, + w_bases_15, w_dic_15, w_i_1, w_g) goto = 17 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_15, w_bases_15, w_dic_15, space.w_AttributeError, e.w_value, space.w_AttributeError) - goto = 21 + goto = 22 else:raise # unhandled case, should not happen if goto == 17: try: - w_49 = space.call_function(w_48, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) - (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_3, - w_50) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_2, w_49) + w_48 = space.getattr(w_g_1, gs_get) + (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_2, + w_49) = (w_name_17, w_bases_17, w_dic_17, w_i_2, w_g_1, w_48) goto = 18 except OperationError, e: - if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + if space.is_true(space.issubtype(e.w_type, space.w_AttributeError)): (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_17, - w_bases_17, w_dic_17, e.w_type, e.w_value, e.w_type) - goto = 21 + w_bases_17, w_dic_17, space.w_AttributeError, e.w_value, + space.w_AttributeError) + goto = 22 else:raise # unhandled case, should not happen if goto == 18: - w_51 = space.is_(w_50, g_object) - v52 = space.is_true(w_51) - if v52 == True: - (w_name_19, w_bases_19, w_dic_19, w_i_4) = (w_name_18, w_bases_18, - w_dic_18, w_i_3) + try: + w_50 = space.call_function(w_49, gs_OLD_STYLE_CLASSES_IMPL, space.w_None) + (w_name_19, w_bases_19, w_dic_19, w_i_4, w_g_3, + w_51) = (w_name_18, w_bases_18, w_dic_18, w_i_3, w_g_2, w_50) goto = 19 - else: - assert v52 == False - (w_name_20, w_bases_20, w_dic_20, w_g_4) = (w_name_18, w_bases_18, - w_dic_18, w_g_3) - goto = 22 + except OperationError, e: + if space.is_true(space.issubtype(e.w_type, space.w_Exception)): + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_18, + w_bases_18, w_dic_18, e.w_type, e.w_value, e.w_type) + goto = 22 + else:raise # unhandled case, should not happen if goto == 19: + w_52 = space.is_(w_51, g_object) + v53 = space.is_true(w_52) + if v53 == True: + (w_name_20, w_bases_20, w_dic_20, w_i_5) = (w_name_19, w_bases_19, + w_dic_19, w_i_4) + goto = 20 + else: + assert v53 == False + (w_name_21, w_bases_21, w_dic_21, w_g_4) = (w_name_19, w_bases_19, + w_dic_19, w_g_3) + goto = 23 + + if goto == 20: try: - w_i_5 = space.inplace_add(w_i_4, gi_1) - (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_19, w_bases_19, - w_dic_19, w_i_5) + w_i_6 = space.inplace_add(w_i_5, gi_1) + (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_20, w_bases_20, + w_dic_20, w_i_6) goto = 15 continue except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_OverflowError)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, - w_bases_19, w_dic_19, space.w_OverflowError, e.w_value, + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_20, + w_bases_20, w_dic_20, space.w_OverflowError, e.w_value, space.w_OverflowError) - goto = 21 + goto = 22 elif space.is_true(space.issubtype(e.w_type, space.w_FloatingPointError)): - (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_19, - w_bases_19, w_dic_19, space.w_FloatingPointError, e.w_value, + (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) = (w_name_20, + w_bases_20, w_dic_20, space.w_FloatingPointError, e.w_value, space.w_FloatingPointError) - goto = 21 + goto = 22 else:raise # unhandled case, should not happen - if goto == 20: - w_53 = space.issubtype(w_54, space.w_ValueError) - v55 = space.is_true(w_53) - if v55 == True: - w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 - goto = 24 + if goto == 21: + w_54 = space.issubtype(w_55, space.w_ValueError) + v56 = space.is_true(w_54) + if v56 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 + goto = 25 else: - assert v55 == False - w_etype, w_evalue = w_56, w_57 - goto = 31 + assert v56 == False + w_etype, w_evalue = w_57, w_58 + goto = 32 - if goto == 21: - w_58 = space.is_(w_46, space.w_ValueError) - v59 = space.is_true(w_58) - if v59 == True: + if goto == 22: + w_59 = space.is_(w_46, space.w_ValueError) + v60 = space.is_true(w_59) + if v60 == True: w_name_11, w_bases_11, w_dic_11 = w_name_16, w_bases_16, w_dic_16 - goto = 24 + goto = 25 else: - assert v59 == False - (w_name_21, w_bases_21, w_dic_21, w_56, w_57, w_54) = (w_name_16, + assert v60 == False + (w_name_22, w_bases_22, w_dic_22, w_57, w_58, w_55) = (w_name_16, w_bases_16, w_dic_16, w_44, w_45, w_46) - goto = 20 + goto = 21 continue - if goto == 22: - w_60 = space.getattr(w_g_4, gs_get) - w_modname = space.call_function(w_60, gs___name__, space.w_None) - w_62 = space.is_(w_modname, space.w_None) - v63 = space.is_true(w_62) - if v63 == True: - w_name_11, w_bases_11, w_dic_11 = w_name_20, w_bases_20, w_dic_20 - goto = 24 - else: - assert v63 == False - (w_name_22, w_bases_22, w_dic_22, w_modname_1) = (w_name_20, - w_bases_20, w_dic_20, w_modname) - goto = 23 - if goto == 23: - w_64 = space.setitem(w_dic_22, gs___module__, w_modname_1) - w_name_11, w_bases_11, w_dic_11 = w_name_22, w_bases_22, w_dic_22 - goto = 24 + w_61 = space.getattr(w_g_4, gs_get) + w_modname = space.call_function(w_61, gs___name__, space.w_None) + w_63 = space.is_(w_modname, space.w_None) + v64 = space.is_true(w_63) + if v64 == True: + w_name_11, w_bases_11, w_dic_11 = w_name_21, w_bases_21, w_dic_21 + goto = 25 + else: + assert v64 == False + (w_name_23, w_bases_23, w_dic_23, w_modname_1) = (w_name_21, + w_bases_21, w_dic_21, w_modname) + goto = 24 if goto == 24: - w_65 = space.iter(w_bases_11) - (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_11, w_bases_11, - w_dic_11, w_65) + w_65 = space.setitem(w_dic_23, gs___module__, w_modname_1) + w_name_11, w_bases_11, w_dic_11 = w_name_23, w_bases_23, w_dic_23 goto = 25 if goto == 25: + w_66 = space.iter(w_bases_11) + (w_name_24, w_bases_24, w_dic_24, w_67) = (w_name_11, w_bases_11, + w_dic_11, w_66) + goto = 26 + + if goto == 26: try: - w_b = space.next(w_66) - (w_name_24, w_bases_24, w_dic_24, w_68, w_b_1) = (w_name_23, - w_bases_23, w_dic_23, w_66, w_b) - goto = 27 + w_b = space.next(w_67) + (w_name_25, w_bases_25, w_dic_25, w_69, w_b_1) = (w_name_24, + w_bases_24, w_dic_24, w_67, w_b) + goto = 28 except OperationError, e: if space.is_true(space.issubtype(e.w_type, space.w_StopIteration)): - w_name_25, w_bases_25, w_dic_25 = w_name_23, w_bases_23, w_dic_23 - goto = 30 + w_name_26, w_bases_26, w_dic_26 = w_name_24, w_bases_24, w_dic_24 + goto = 31 else:raise # unhandled case, should not happen - if goto == 26: - w_69 = space.issubtype(w_39, space.w_KeyError) - v70 = space.is_true(w_69) - if v70 == True: + if goto == 27: + w_70 = space.issubtype(w_39, space.w_KeyError) + v71 = space.is_true(w_70) + if v71 == True: (w_name_13, w_bases_13, w_dic_13, w_i) = (w_name_14, w_bases_14, w_dic_14, gi_0) goto = 15 continue else: - assert v70 == False + assert v71 == False w_etype, w_evalue = w_37, w_38 - goto = 31 + goto = 32 - if goto == 27: - w_71 = space.isinstance(w_b_1, gcls_classobj) - v72 = space.is_true(w_71) - if v72 == True: - (w_name_23, w_bases_23, w_dic_23, w_66) = (w_name_24, w_bases_24, - w_dic_24, w_68) - goto = 25 + if goto == 28: + w_72 = space.isinstance(w_b_1, gcls_classobj) + v73 = space.is_true(w_72) + if v73 == True: + (w_name_24, w_bases_24, w_dic_24, w_67) = (w_name_25, w_bases_25, + w_dic_25, w_69) + goto = 26 continue else: - assert v72 == False - (w_name_26, w_bases_26, w_dic_26, w_b_2) = (w_name_24, w_bases_24, - w_dic_24, w_b_1) - goto = 28 - - if goto == 28: - w_73 = space.call_function(space.w_type, w_b_2) - w_74 = space.call_function((space.builtin.get(space.str_w(gs_callable))), w_73) - v75 = space.is_true(w_74) - if v75 == True: - (w_name_27, w_bases_27, w_dic_27, w_b_3) = (w_name_26, w_bases_26, - w_dic_26, w_b_2) + assert v73 == False + (w_name_27, w_bases_27, w_dic_27, w_b_2) = (w_name_25, w_bases_25, + w_dic_25, w_b_1) goto = 29 - else: - assert v75 == False - w_etype, w_evalue = space.w_TypeError, gs_base_must_be_class - goto = 31 if goto == 29: - w_76 = space.call_function(space.w_type, w_b_3) - w_77 = space.call_function(w_76, w_name_27, w_bases_27, w_dic_27) - w_78 = w_77 - goto = 32 + w_74 = space.call_function(space.w_type, w_b_2) + w_75 = space.call_function((space.builtin.get(space.str_w(gs_callable))), w_74) + v76 = space.is_true(w_75) + if v76 == True: + (w_name_28, w_bases_28, w_dic_28, w_b_3) = (w_name_27, w_bases_27, + w_dic_27, w_b_2) + goto = 30 + else: + assert v76 == False + w_etype, w_evalue = space.w_TypeError, gs_base_must_be_class + goto = 32 if goto == 30: - w_new_class = space.call_function(gbltinmethod___new__, gcls_classobj) - w_80 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_25) - w_81 = space.getattr(gdescriptor_classobj__name, gs___set__) - w_82 = space.call_function(w_81, w_new_class, w_name_25) - w_83 = space.getattr(gdescriptor_classobj__bases, gs___set__) - w_84 = space.call_function(w_83, w_new_class, w_bases_25) - w_78 = w_new_class - goto = 32 + w_77 = space.call_function(space.w_type, w_b_3) + w_78 = space.call_function(w_77, w_name_28, w_bases_28, w_dic_28) + w_79 = w_78 + goto = 33 if goto == 31: - raise OperationError(w_etype, w_evalue) + w_new_class = space.call_function(gbltinmethod___new__, gcls_classobj) + w_81 = space.call_function(gdescriptor_object___setattr__, w_new_class, gs___dict__, w_dic_26) + w_82 = space.getattr(gdescriptor_classobj__name, gs___set__) + w_83 = space.call_function(w_82, w_new_class, w_name_26) + w_84 = space.getattr(gdescriptor_classobj__bases, gs___set__) + w_85 = space.call_function(w_84, w_new_class, w_bases_26) + w_79 = w_new_class + goto = 33 if goto == 32: - return w_78 + raise OperationError(w_etype, w_evalue) + + if goto == 33: + return w_79 fastf___new__ = __new__ Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Tue Feb 22 00:08:42 2005 @@ -332,7 +332,8 @@ 'delitem': [IndexError, KeyError], 'getattr': [AttributeError], 'delattr': [AttributeError], - 'iter' : [TypeError] + 'iter' : [TypeError], + 'coerce' : [TypeError], } # continuing like above, but in a more programmatic style. def _add_exceptions(names, exc): Modified: pypy/dist/pypy/translator/tool/tointerplevel.py ============================================================================== --- pypy/dist/pypy/translator/tool/tointerplevel.py (original) +++ pypy/dist/pypy/translator/tool/tointerplevel.py Tue Feb 22 00:08:42 2005 @@ -54,7 +54,7 @@ else: entrypoint = tuple(objs) - t = Translator(None, verbose=False, simplifying=True) + t = Translator(None, verbose=False, simplifying=True, builtins_can_raise_exceptions=True) gen = GenRpy(t, entrypoint, modname, mod.__dict__) output = options.output or modname + "interp.py" From tismer at codespeak.net Tue Feb 22 13:40:22 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 22 Feb 2005 13:40:22 +0100 (MET) Subject: [pypy-svn] r9400 - pypy/dist/pypy/translator/test Message-ID: <20050222124022.89AA627B5B@code1.codespeak.net> Author: tismer Date: Tue Feb 22 13:40:22 2005 New Revision: 9400 Modified: pypy/dist/pypy/translator/test/snippet.py Log: slight rearrangements which do not change semantics. The reason was to be able to cut the source programmatically at the point where it stops to be translatable. Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Tue Feb 22 13:40:22 2005 @@ -449,16 +449,6 @@ def global_recursive_list(): return global_rl -class BadInit(object): - def update(self, k): - self.k = 1 - def __init__(self, v): - self.update(**{'k':v}) - def read(self): - return self.k - -global_bi = BadInit(1) - class MI_A(object): a = 1 class MI_B(MI_A): @@ -472,9 +462,6 @@ i = MI_D() return i.a + i.b + i.c + i.d -def global_badinit(): - return global_bi.read() - def flow_type_info(i): if isinstance(i, int): a = i + 1 @@ -575,7 +562,24 @@ e.stuff = (3, "world") return C().stuff -# --------------------(Currently) Non compillable Functions --------------------- +def _getstuff(x): + return x.stuff + +# --------------------(Currently) Non compilable Functions --------------------- + +class BadInit(object): + def update(self, k): + self.k = 1 + def __init__(self, v): + return + self.update(**{'k':v}) + def read(self): + return self.k + +global_bi = BadInit(1) + +def global_badinit(): + return global_bi.read() def _attrs(): def b(): pass @@ -583,9 +587,6 @@ b.g = 5 return b.f + b.g -def _getstuff(x): - return x.stuff - def _methodcall1(cond): if cond: x = G() From tismer at codespeak.net Tue Feb 22 14:02:35 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 22 Feb 2005 14:02:35 +0100 (MET) Subject: [pypy-svn] r9401 - in pypy/dist/pypy/translator: . test Message-ID: <20050222130235.1760B27B5B@code1.codespeak.net> Author: tismer Date: Tue Feb 22 14:02:34 2005 New Revision: 9401 Added: pypy/dist/pypy/translator/test/test_geninterp.py Modified: pypy/dist/pypy/translator/geninterplevel.py Log: lots of overhaul to geninterplevel.py, to make it compile the snippets.py . Added some 23 test cases. Some of the tests cannot run in this manner, because they would actually need to be evaluated in app space. Something to think about... Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Tue Feb 22 14:02:34 2005 @@ -112,6 +112,12 @@ self.initcode.append('m.%s = eval_helper(%r)' % (name, expr)) return name +def builtin_base(obj): + typ = type(obj) + while typ.__module__ != '__builtin__': + typ = typ.__base__ + return typ + class GenRpy: def __init__(self, translator, entrypoint=None, modname=None, moddict=None): self.translator = translator @@ -121,11 +127,24 @@ self.modname = self.trans_funcname(modname or uniquemodulename(entrypoint)) self.moddict = moddict # the dict if we translate a module + + def late_OperationError(): + self.initcode.append( + 'from pypy.interpreter.error import OperationError\n' + 'm.OperationError = OperationError') + return 'OperationError' + def late_Arguments(): + self.initcode.append( + 'from pypy.interpreter.argument import Arguments\n' + 'm.Arguments = Arguments') + return 'Arguments' + self.rpynames = {Constant(None).key: 'space.w_None', Constant(False).key: 'space.w_False', Constant(True).key: 'space.w_True', + Constant(OperationError).key: late_OperationError, + Constant(Arguments).key: late_Arguments, } - self.seennames = {} u = UniqueList self.initcode = u() # list of lines for the module's initxxx() @@ -215,6 +234,7 @@ if op.opname == "call_args": v = op.args[0] exv = self.expr(v, localnames) + self.nameof(Arguments) # trigger init fmt = ( "_args = Arguments.fromshape(space, %(shape)s, [%(data_w)s])\n" "%(res)s = space.call_args(%(func)s, _args)") @@ -285,15 +305,22 @@ def nameof(self, obj, debug=None, namehint=None): key = Constant(obj).key try: - return self.rpynames[key] + txt = self.rpynames[key] + if type(txt) is not str: + # this is a predefined constant, initialized on first use + func = txt + txt = func() + self.rpynames[key] = txt + return txt + except KeyError: if debug: stackentry = debug, obj else: stackentry = obj self.debugstack = (self.debugstack, stackentry) - if (type(obj).__module__ != '__builtin__' and - not isinstance(obj, type)): # skip user-defined metaclasses + obj_builtin_base = builtin_base(obj) + if obj_builtin_base in (object, int, long) and type(obj) is not obj_builtin_base: # assume it's a user defined thingy name = self.nameof_instance(obj) else: @@ -306,7 +333,7 @@ else: raise Exception, "nameof(%r)" % (obj,) - code=meth.im_func.func_code + code = meth.im_func.func_code if namehint and 'namehint' in code.co_varnames[:code.co_argcount]: name = meth(obj, namehint=namehint) else: @@ -357,7 +384,7 @@ value.__file__.endswith('.py') or value.__file__.endswith('.pyo')), \ "%r is not a builtin module (probably :)"%value - name = self.uniquename('mod_%s'%value.__name__) + name = self.uniquename('mod_%s' % value.__name__) self.initcode.append('import %s as _tmp' % value.__name__) self.initcode.append('m.%s = space.wrap(_tmp)' % (name)) return name @@ -455,6 +482,7 @@ name = self.uniquename('gfunc_' + self.trans_funcname( namehint + func.__name__)) f_name = 'f_' + name[6:] + self.initcode.append('from pypy.interpreter import gateway') self.initcode.append('m.%s = space.wrap(gateway.interp2app(%s, unwrap_spec=[gateway.ObjSpace, gateway.Arguments]))' % (name, f_name)) self.pendingfunctions.append(func) return name @@ -475,9 +503,10 @@ ob = self.nameof(meth.im_self) func = self.nameof(meth.im_func) typ = self.nameof(meth.im_class) - name = self.uniquename('gmeth_'+meth.im_func.__name__) + name = self.uniquename('gmeth_' + meth.im_func.__name__) + funcname = self.nameof(meth.im_func.__name__) self.initcode.append( - '%s = space.getattr(%s, %s)'%(name, ob, func)) + '%s = space.getattr(%s, %s)' % (name, ob, funcname)) return name def should_translate_attr(self, pbc, attr): @@ -517,12 +546,17 @@ 'm.%s = space.wrap(_ins)' % ( instance.__class__.__name__, name)) else: - # this seems to hardly work with the faked stuff - self.initcode.append('from types import InstanceType') - self.initcode.append('w_InstanceType = space.wrap(InstanceType)') - self.initcode.append('_tup = space.newtuple([%s])\n' - 'm.%s = space.call(w_InstanceType, _tup)' % ( - cls, name)) + if isinstance(instance.__class__, type): + self.initcode.append( + '_new = space.getattr(%s, %s)\n' + '_tup = space.newtuple([%s])\n' + 'm.%s = space.call(_new, _tup)' % ( + cls, self.nameof('__new__'), cls, name)) + else: + self.initcode.append( + '_tup = space.newtuple([%s])\n' + 'm.%s = space.call(space.w_instance, _tup)' % ( + cls, name)) self.later(initinstance()) return name @@ -591,19 +625,13 @@ if issubclass(cls, Exception): if cls.__module__ == 'exceptions': # exception are defined on the space - return 'space.w_%s'%cls.__name__ - + return 'space.w_%s' % cls.__name__ # For the moment, use old-style classes exactly when the # pypy source uses old-style classes, to avoid strange problems. if not isinstance(cls, type): assert type(cls) is type(Exception) - # self.initcode.append("import types\n" - # "m.classtype = space.wrap(types.ClassType)\n") - # metaclass = "m.classtype" - # XXX I cannot instantiate these. - # XXX using type instead, since we still inherit from exception - # XXX what is the future of classes in pypy? + metaclass = 'space.w_classobj' basenames = [self.nameof(base) for base in cls.__bases__] def initclassobj(): @@ -623,7 +651,7 @@ print "skipped staticmethod:", value continue if isinstance(value, FunctionType) and value not in self.translator.flowgraphs and self.translator.frozen: - print "skippedfunction:", value + print "skipped function:", value continue yield 'space.setattr(%s, %s, %s)' % ( @@ -710,8 +738,9 @@ if type(ret) is tuple: ret = ret[0](self, ret[1], ret[2]) return ret - assert cls.__module__ != '__builtin__', \ - "built-in class %r not found in typename_mapping" % (cls,) + assert cls.__module__ != '__builtin__', ( + "built-in class %r not found in typename_mapping " + "while compiling %s" % (cls, self.currentfunc.__name__)) return self.nameof_classobj(cls) def nameof_tuple(self, tup): @@ -727,8 +756,8 @@ for i in range(len(lis)): item = self.nameof(lis[i]) yield 'space.setitem(%s, %s, %s);' % ( - name, self.nameof(i), self.nameof(item)) - self.initcode.append('m.%s = space.newlist(%s)' % (name, self.nameof(0))) + name, self.nameof(i), item) + self.initcode.append('m.%s = space.newlist([space.w_None])' % (name,)) self.initcode.append('m.%s = space.mul(%s, %s)' % (name, name, self.nameof(len(lis)))) self.later(initlist()) return name @@ -824,7 +853,7 @@ f = self.f info = { 'modname': self.modname, - # the side-effects of this kick-start the process + # the side-effects of this is kick-start the process 'entrypoint': self.nameof(self.entrypoint), } # header @@ -1080,6 +1109,7 @@ # exceptional return block exc_cls = self.expr(block.inputargs[0], localvars) exc_val = self.expr(block.inputargs[1], localvars) + self.nameof(OperationError) # trigger init yield "raise OperationError(%s, %s)" % (exc_cls, exc_val) else: # regular return block @@ -1101,6 +1131,7 @@ # we must catch the exception raised by the last operation, # which goes to the last err%d_%d label written above. # Since we only have OperationError, we need to select: + self.nameof(OperationError) # trigger init yield "except OperationError, e:" q = "if" for link in block.exits[1:]: @@ -1148,10 +1179,6 @@ RPY_HEADER = '''#!/bin/env python # -*- coding: LATIN-1 -*- - -from pypy.interpreter.error import OperationError -from pypy.interpreter.argument import Arguments -from pypy.interpreter import gateway ''' RPY_SEP = "#*************************************************************" Added: pypy/dist/pypy/translator/test/test_geninterp.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/test/test_geninterp.py Tue Feb 22 14:02:34 2005 @@ -0,0 +1,235 @@ +""" +Description +_____________________________ + +This test is almost a copy of test_genc.py +The setup code is slightly different: +Instead of compiling single functions from +snippets.py, almost all of snippets is translated, +up to the point where they are untranslatable. +snippets has been slightly re-ordered for that. + +The idea was to create a couple of tests without much +extra work, in a sense derived from the test_genc. + +A problem with that is, that the tests actually should +be run at application level. The test code checks real +Python values,so we have to do tricks to unwrap things. +This is limited: +Some tests cannot work, since they mutate their arguments. +Some tests operate with un-unwrappable things. +Those are disabled for the moment by an 'needapp_' prefix. + +XXX think about a way to produce more tests from a common +XXX basis. Should we write generators for such tests like this? +""" +import autopath +import py +from pypy.tool.udir import udir +from pypy.translator.genc import GenC +from pypy.objspace.flow.model import * +from pypy.translator.tool.buildpyxmodule import make_module_from_c +from pypy.translator.tool.buildpyxmodule import skip_missing_compiler +from pypy.translator.geninterplevel import translate_as_module +from pypy.translator.test import snippet +from pypy.interpreter.error import OperationError +from py.code import Source + +class TestGenRpyTestCase: + objspacename = 'flow' + + def __init__(self): + from pypy.objspace.std import Space + self.space = Space() + # simply compile snippets just once + src = str(Source(snippet)) + # truncate non-compilable stuff for now: + p = src.index('Non compilable Functions') + src = src[:p] + ini = translate_as_module(src, tmpname="d:/tmp/look.py") + self.w_glob = ini(self.space) + + def build_interpfunc(self, func, *morefuncs): + # we ignore morefuncs, since they live in snippets + space =self.space + func = space.getitem(self.w_glob, space.wrap(func.__name__)) + def wrapunwrap(*args): + w_args = space.wrap(args) + try: + w_res = space.call(func, w_args) + except OperationError, e: + w_typ = e.w_type + # XXX how to unwrap an exception? + name = space.unwrap(space.getattr(w_typ, space.wrap('__name__'))) + exc = __builtins__[name] + raise exc + return space.unwrap(w_res) + return wrapunwrap + + def test_simple_func(self): + cfunc = self.build_interpfunc(snippet.simple_func) + assert cfunc(1) == 2 + + def test_while_func(self): + while_func = self.build_interpfunc(snippet.while_func) + assert while_func(10) == 55 + + def test_nested_whiles(self): + nested_whiles = self.build_interpfunc(snippet.nested_whiles) + assert nested_whiles(111, 114) == ( + '...!...!...!...!...!') + + def test_poor_man_range(self): + poor_man_range = self.build_interpfunc(snippet.poor_man_range) + assert poor_man_range(10) == range(10) + + def poor_man_rev_range(self): + poor_man_rev_range = self.build_interpfunc(snippet.poor_man_rev_range) + assert poor_man_rev_range(10) == range(9,-1,-1) + + def test_simple_id(self): + #we just want to see, if renaming of parameter works correctly + #if the first branch is the end branch + simple_id = self.build_interpfunc(snippet.simple_id) + assert simple_id(9) == 9 + + def test_branch_id(self): + branch_id = self.build_interpfunc(snippet.branch_id) + assert branch_id(1, 2, 3) == 2 + assert branch_id(0, 2, 3) == 3 + + def test_int_id(self): + int_id = self.build_interpfunc(snippet.int_id) + assert int_id(3) == 3 + + def dont_test_attrs(self): + attrs = self.build_interpfunc(snippet.attrs) + assert attrs() == 9 + + def test_builtinusage(self): + fun = self.build_interpfunc(snippet.builtinusage) + assert fun() == 4 + + def xpensive_test_sieve(self): + sieve = self.build_interpfunc(snippet.sieve_of_eratosthenes) + assert sieve() == 1028 + + def test_slice(self): + half = self.build_interpfunc(snippet.half_of_n) + assert half(10) == 5 + + def test_poly_branch(self): + poly_branch = self.build_interpfunc(snippet.poly_branch) + assert poly_branch(10) == [1,2,3]*2 + assert poly_branch(0) == ['a','b','c']*2 + + def test_and(self): + sand = self.build_interpfunc(snippet.s_and) + assert sand(5, 6) == "yes" + assert sand(5, 0) == "no" + assert sand(0, 6) == "no" + assert sand(0, 0) == "no" + + def test_yast(self): + yast = self.build_interpfunc(snippet.yast) + assert yast([1000,100,10,1]) == 1111 + assert yast(range(100)) == (99*100)/2 + + def test_with_init(self): + with_init = self.build_interpfunc(snippet.with_init) + assert with_init(0) == 0 + assert with_init(-100) == -100 + + def test_with_more_init(self): + with_more_init = self.build_interpfunc(snippet.with_more_init) + assert with_more_init(10, False) == -10 + assert with_more_init(20, True) == 20 + + def needapp_test_global_instance(self): + global_instance = self.build_interpfunc(snippet.global_instance) + assert global_instance() == 42 + + def needapp_test_global_newstyle_instance(self): + global_newstyle_instance = self.build_interpfunc(snippet.global_newstyle_instance) + assert global_newstyle_instance().a == 1 + + def needapp_test_global_recursive_list(self): + global_recursive_list = self.build_interpfunc(snippet.global_recursive_list) + lst = global_recursive_list() + assert len(lst) == 1 + assert lst[0] is lst + +## def test_global_badinit(self): +## global_badinit = self.build_interpfunc(snippet.global_badinit) +## self.assertEquals(global_badinit(), 1) + + def test_multiple_inheritance(self): + multiple_inheritance = self.build_interpfunc(snippet.multiple_inheritance) + assert multiple_inheritance() == 1+2+3+4 + + def test_call_star_args(self): + call_star_args = self.build_interpfunc(snippet.call_star_args) + assert call_star_args(42) == 52 + + def test_call_default_args(self): + call_default_args = self.build_interpfunc(snippet.call_default_args) + assert call_default_args(42) == 111+42+3 + + def test_call_default_and_star_args(self): + call_default_and_star_args = self.build_interpfunc( + snippet.call_default_and_star_args) + assert call_default_and_star_args(42) == ( + (111+42+3+0, -1000-2000-3000+2)) + + def test_call_with_star(self): + call_with_star = self.build_interpfunc(snippet.call_with_star) + assert call_with_star(()) == -15L + assert call_with_star((4,)) == -13L + assert call_with_star((4,7)) == -9L + assert call_with_star([]) == -15L + assert call_with_star([4]) == -13L + assert call_with_star([4,7]) == -9L + raises(TypeError, call_with_star, (4,7,12)) + raises(TypeError, call_with_star, [4,7,12,63]) + raises(TypeError, call_with_star, 521) + + def test_call_with_keyword(self): + call_with_keyword = self.build_interpfunc(snippet.call_with_keyword) + assert call_with_keyword(100) == 82 + + def test_call_very_complex(self): + call_very_complex = self.build_interpfunc(snippet.call_very_complex, + snippet.default_args) + assert call_very_complex(5, (3,), {}) == -12 + assert call_very_complex(5, (), {'y': 3}) == -12 + raises(TypeError, call_very_complex, 5, (3,), {'y': 4}) + + def test_finallys(self): + finallys = self.build_interpfunc(snippet.finallys) + assert finallys(['hello']) == 8 + assert finallys('X') == 8 + assert finallys([]) == 6 + assert finallys('XY') == 6 + + def needapp_test_finally2(self): + finally2 = self.build_interpfunc(snippet.finally2) + lst = range(10) + finally2(lst, 5) + assert lst == [0,1,2,3,4, 6, 6,7,8, 'done'] + dic = {} + raises(KeyError, finally2, dic, "won't find this key") + assert dic == {-1: 'done'} + + def test_bare_raise(self): + bare_raise = self.build_interpfunc(snippet.bare_raise) + assert bare_raise(range(0, 100, 10), False) == 50 + assert bare_raise(range(0, 100, 10), True) == 50 + raises(IndexError, bare_raise, range(0, 30, 10), False) + assert bare_raise(range(0, 30, 10), True) == None + + def needapp_test_get_set_del_slice(self): + fn = self.build_interpfunc(snippet.get_set_del_slice) + l = list('abcdefghij') + result = fn(l) + assert l == [3, 'c', 8, 11, 'h', 9] + assert result == ([3, 'c'], [9], [11, 'h']) From pedronis at codespeak.net Tue Feb 22 14:57:59 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 22 Feb 2005 14:57:59 +0100 (MET) Subject: [pypy-svn] r9405 - pypy/dist/pypy/translator/test Message-ID: <20050222135759.9B81E27B5D@code1.codespeak.net> Author: pedronis Date: Tue Feb 22 14:57:59 2005 New Revision: 9405 Modified: pypy/dist/pypy/translator/test/test_geninterp.py Log: use a prebuilt std space Modified: pypy/dist/pypy/translator/test/test_geninterp.py ============================================================================== --- pypy/dist/pypy/translator/test/test_geninterp.py (original) +++ pypy/dist/pypy/translator/test/test_geninterp.py Tue Feb 22 14:57:59 2005 @@ -36,17 +36,15 @@ from py.code import Source class TestGenRpyTestCase: - objspacename = 'flow' + objspacename = 'std' def __init__(self): - from pypy.objspace.std import Space - self.space = Space() # simply compile snippets just once src = str(Source(snippet)) # truncate non-compilable stuff for now: p = src.index('Non compilable Functions') src = src[:p] - ini = translate_as_module(src, tmpname="d:/tmp/look.py") + ini = translate_as_module(src, tmpname = str(udir.join("_geninterp_test.py"))) self.w_glob = ini(self.space) def build_interpfunc(self, func, *morefuncs): From tismer at codespeak.net Tue Feb 22 15:05:58 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 22 Feb 2005 15:05:58 +0100 (MET) Subject: [pypy-svn] r9407 - pypy/dist/pypy/translator/test Message-ID: <20050222140558.5783227B5D@code1.codespeak.net> Author: tismer Date: Tue Feb 22 15:05:58 2005 New Revision: 9407 Modified: pypy/dist/pypy/translator/test/test_geninterp.py Log: removed temp file Modified: pypy/dist/pypy/translator/test/test_geninterp.py ============================================================================== --- pypy/dist/pypy/translator/test/test_geninterp.py (original) +++ pypy/dist/pypy/translator/test/test_geninterp.py Tue Feb 22 15:05:58 2005 @@ -44,7 +44,7 @@ # truncate non-compilable stuff for now: p = src.index('Non compilable Functions') src = src[:p] - ini = translate_as_module(src, tmpname = str(udir.join("_geninterp_test.py"))) + ini = translate_as_module(src)#, tmpname = str(udir.join("_geninterp_test.py"))) self.w_glob = ini(self.space) def build_interpfunc(self, func, *morefuncs): From pedronis at codespeak.net Tue Feb 22 15:10:34 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 22 Feb 2005 15:10:34 +0100 (MET) Subject: [pypy-svn] r9408 - pypy/dist/pypy/translator/test Message-ID: <20050222141034.8765F27B5A@code1.codespeak.net> Author: pedronis Date: Tue Feb 22 15:10:34 2005 New Revision: 9408 Modified: pypy/dist/pypy/translator/test/test_geninterp.py Log: reactived temp file with gen code Modified: pypy/dist/pypy/translator/test/test_geninterp.py ============================================================================== --- pypy/dist/pypy/translator/test/test_geninterp.py (original) +++ pypy/dist/pypy/translator/test/test_geninterp.py Tue Feb 22 15:10:34 2005 @@ -44,7 +44,7 @@ # truncate non-compilable stuff for now: p = src.index('Non compilable Functions') src = src[:p] - ini = translate_as_module(src)#, tmpname = str(udir.join("_geninterp_test.py"))) + ini = translate_as_module(src), tmpname = str(udir.join("_geninterp_test.py"))) self.w_glob = ini(self.space) def build_interpfunc(self, func, *morefuncs): From tismer at codespeak.net Tue Feb 22 15:21:41 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 22 Feb 2005 15:21:41 +0100 (MET) Subject: [pypy-svn] r9409 - pypy/dist/pypy/translator/test Message-ID: <20050222142141.3386D27B5A@code1.codespeak.net> Author: tismer Date: Tue Feb 22 15:21:41 2005 New Revision: 9409 Modified: pypy/dist/pypy/translator/test/test_geninterp.py Log: this one is tested :-) Modified: pypy/dist/pypy/translator/test/test_geninterp.py ============================================================================== --- pypy/dist/pypy/translator/test/test_geninterp.py (original) +++ pypy/dist/pypy/translator/test/test_geninterp.py Tue Feb 22 15:21:41 2005 @@ -44,7 +44,8 @@ # truncate non-compilable stuff for now: p = src.index('Non compilable Functions') src = src[:p] - ini = translate_as_module(src), tmpname = str(udir.join("_geninterp_test.py"))) + # just in case of trouble, we produce a tempfile + ini = translate_as_module(src, tmpname = str(udir.join("_geninterp_test.py"))) self.w_glob = ini(self.space) def build_interpfunc(self, func, *morefuncs): From pedronis at codespeak.net Tue Feb 22 17:29:50 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Tue, 22 Feb 2005 17:29:50 +0100 (MET) Subject: [pypy-svn] r9410 - in pypy/dist/pypy: objspace/std translator Message-ID: <20050222162950.E81C527B57@code1.codespeak.net> Author: pedronis Date: Tue Feb 22 17:29:50 2005 New Revision: 9410 Modified: pypy/dist/pypy/objspace/std/stdtypedef.py pypy/dist/pypy/translator/genc.py Log: changes to have translate.py -no-a at least finish compilation Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Tue Feb 22 17:29:50 2005 @@ -137,6 +137,7 @@ def sliced_typeorders(typeorder, multimethod, typedef, i, local=False): + """NOT_RPYTHON""" list_of_typeorders = [typeorder] * multimethod.arity prefix = '_mm_' + multimethod.name if not local: @@ -170,6 +171,7 @@ def make_perform_trampoline(prefix, exprargs, expr, miniglobals, multimethod, selfindex=0, allow_NotImplemented_results=False): + """NOT_RPYTHON""" # mess to figure out how to put a gateway around executing expr argnames = ['_%d'%(i+1) for i in range(multimethod.arity)] explicit_argnames = multimethod.extras.get('argnames', []) @@ -241,6 +243,7 @@ return miniglobals["%s_perform_call" % prefix] def wrap_trampoline_in_gateway(func, methname, multimethod): + """NOT_RPYTHON""" unwrap_spec = [gateway.ObjSpace] + [gateway.W_Root]*multimethod.arity if multimethod.extras.get('varargs_w', False): unwrap_spec.append('args_w') @@ -251,6 +254,7 @@ return gateway.interp2app(func, app_name=methname, unwrap_spec=unwrap_spec) def slicemultimethod(space, multimethod, typedef, result, local=False): + """NOT_RPYTHON""" for i in range(len(multimethod.specialnames)): methname = multimethod.specialnames[i] if methname in result: @@ -261,6 +265,7 @@ continue def multimethod_loader(i=i, methname=methname): + """NOT_RPYTHON""" prefix, list_of_typeorders = sliced_typeorders( space.model.typeorder, multimethod, typedef, i, local=local) exprargs, expr, miniglobals, fallback = multimethod.install(prefix, list_of_typeorders, @@ -277,6 +282,7 @@ result[methname] = multimethod_loader def slicemultimethods(space, typedef): + """NOT_RPYTHON""" result = {} # import and slice all multimethods of the space.MM container for multimethod in hack_out_multimethods(space.MM.__dict__): Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Tue Feb 22 17:29:50 2005 @@ -112,6 +112,7 @@ def initcode_python(self, name, pyexpr): # generate init code that will evaluate the given Python expression + #self.initcode.append("print 'setting up', %r" % name) self.initcode.append("%s = %s" % (name, pyexpr)) def nameof_object(self, value): @@ -247,8 +248,19 @@ for key, value in content: if self.should_translate_attr(instance, key): yield '%s.%s = %s' % (name, key, self.nameof(value)) + if hasattr(instance,'__reduce_ex__'): + import copy_reg + reduced = instance.__reduce_ex__() + assert reduced[0] is copy_reg._reconstructor + state = reduced[1][2] + else: + state = None self.initcode.append('if isinstance(%s, type):' % cls) - self.initcode.append(' %s = %s.__new__(%s)' % (name, cls, cls)) + if state is not None: + #print "INST",' %s = %s.__new__(%s, %r)' % (name, cls, cls, state) + self.initcode.append(' %s = %s.__new__(%s, %r)' % (name, cls, cls, state)) + else: + self.initcode.append(' %s = %s.__new__(%s)' % (name, cls, cls)) self.initcode.append('else:') self.initcode.append(' %s = new.instance(%s)' % (name, cls)) self.later(initinstance()) @@ -337,6 +349,7 @@ InstanceType: 'types.InstanceType', type(None): 'type(None)', CodeType: 'types.CodeType', + type(sys): 'type(new)', r_int: 'int', # XXX r_uint: 'int', # XXX From tismer at codespeak.net Tue Feb 22 19:33:45 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 22 Feb 2005 19:33:45 +0100 (MET) Subject: [pypy-svn] r9412 - pypy/dist/pypy/translator Message-ID: <20050222183345.4C73227B55@code1.codespeak.net> Author: tismer Date: Tue Feb 22 19:33:44 2005 New Revision: 9412 Modified: pypy/dist/pypy/translator/geninterplevel.py Log: minor changes, safereval Modified: pypy/dist/pypy/translator/geninterplevel.py ============================================================================== --- pypy/dist/pypy/translator/geninterplevel.py (original) +++ pypy/dist/pypy/translator/geninterplevel.py Tue Feb 22 19:33:44 2005 @@ -840,7 +840,7 @@ dic = {} for line in txt.split("\n"): ign, name, value = line.split(None, 2) - dic[name] = eval(value) + dic[name] = eval(value, {}) key = (dic["filename"], dic["firstlineno"], dic["function"], uniqueno) return key @@ -1178,8 +1178,7 @@ # ____________________________________________________________ RPY_HEADER = '''#!/bin/env python -# -*- coding: LATIN-1 -*- -''' +# -*- coding: LATIN-1 -*-''' RPY_SEP = "#*************************************************************" From tismer at codespeak.net Tue Feb 22 19:34:00 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Tue, 22 Feb 2005 19:34:00 +0100 (MET) Subject: [pypy-svn] r9413 - pypy/dist/pypy/translator Message-ID: <20050222183400.4D90B27B55@code1.codespeak.net> Author: tismer Date: Tue Feb 22 19:33:59 2005 New Revision: 9413 Modified: pypy/dist/pypy/translator/genc.h Log: added missing include files Modified: pypy/dist/pypy/translator/genc.h ============================================================================== --- pypy/dist/pypy/translator/genc.h (original) +++ pypy/dist/pypy/translator/genc.h Tue Feb 22 19:33:59 2005 @@ -7,6 +7,8 @@ #include "frameobject.h" #include "structmember.h" #include "traceback.h" +#include "marshal.h" +#include "eval.h" #if !defined(MIN) #define MIN(a,b) (((a)<(b))?(a):(b)) From pedronis at codespeak.net Wed Feb 23 15:30:16 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 23 Feb 2005 15:30:16 +0100 (MET) Subject: [pypy-svn] r9455 - pypy/dist/goal Message-ID: <20050223143016.921B327B53@code1.codespeak.net> Author: pedronis Date: Wed Feb 23 15:30:16 2005 New Revision: 9455 Added: pypy/dist/goal/buildcache2.py (contents, props changed) Modified: pypy/dist/goal/translate_pypy.py Log: start of new cache filling code Added: pypy/dist/goal/buildcache2.py ============================================================================== --- (empty file) +++ pypy/dist/goal/buildcache2.py Wed Feb 23 15:30:16 2005 @@ -0,0 +1,37 @@ +import autopath + + +def buildcache(space): + space.builtin.getdict() + print "*builtin*" + #w_dic = space.builtin.w_dict + #print space.unwrap(space.call_method(w_dic,"keys")) + + space.sys.getdict() + print "*sys*" + #w_dic = space.sys.w_dict + #print space.unwrap(space.call_method(w_dic,"keys")) + + for typedef in space.model.pythontypes: + w_typ = getattr(space, 'w_' + typedef.name) + w_typ.getdict() + + print "*%s*" % typedef.name + #print w_typ.dict_w.keys() + + space.appexec([],"""(): + try: + raise ValueError + except ValueError: + pass + exec 'pass' +""") + # freeze caches? + print "cache build finished" + +if __name__ == '__main__': + from pypy.objspace.std.objspace import StdObjSpace + + space = StdObjSpace() + + buildcache(space) Modified: pypy/dist/goal/translate_pypy.py ============================================================================== --- pypy/dist/goal/translate_pypy.py (original) +++ pypy/dist/goal/translate_pypy.py Wed Feb 23 15:30:16 2005 @@ -18,6 +18,7 @@ -no-d Disable recording of debugging information """ import autopath, sys, threading, pdb, os +import buildcache2 from pypy.objspace.std.objspace import StdObjSpace, W_Object from pypy.objspace.std.intobject import W_IntObject from pypy.translator.translator import Translator @@ -30,7 +31,6 @@ from pypy.translator.tool import buildpyxmodule buildpyxmodule.enable_fast_compilation() -#from buildcache import buildcache # __________ Entry point __________ def entry_point(): @@ -38,15 +38,16 @@ w_b = W_IntObject(space, -7) return space.mul(w_a, w_b) - # __________ Main __________ def analyse(entry_point=entry_point): global t, space space = StdObjSpace() - # call the entry_point once to trigger building of all - # caches (as far as analyzing the entry_point is concerned) - entry_point() + # call cache filling code + buildcache2.buildcache(space) + # further call the entry_point once to trigger building remaining + # caches (as far as analyzing the entry_point is concerned) + entry_point() t = Translator(entry_point, verbose=True, simplifying=True) if listen_port: run_async_server() From pedronis at codespeak.net Wed Feb 23 16:28:33 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 23 Feb 2005 16:28:33 +0100 (MET) Subject: [pypy-svn] r9456 - in pypy/dist/pypy/translator: . test Message-ID: <20050223152833.C429D27B53@code1.codespeak.net> Author: pedronis Date: Wed Feb 23 16:28:33 2005 New Revision: 9456 Modified: pypy/dist/pypy/translator/genc.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_ctrans.py Log: added test about global inst with __init__ set attributes Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Wed Feb 23 16:28:33 2005 @@ -247,7 +247,8 @@ content.sort() for key, value in content: if self.should_translate_attr(instance, key): - yield '%s.%s = %s' % (name, key, self.nameof(value)) + line = '%s.%s = %s' % (name, key, self.nameof(value)) + yield line if hasattr(instance,'__reduce_ex__'): import copy_reg reduced = instance.__reduce_ex__() @@ -445,7 +446,7 @@ print >> f, self.C_HEADER # function implementations - while self.pendingfunctions: + while self.pendingfunctions or self.latercode: func = self.pendingfunctions.pop() self.gen_cfunction(func) # collect more of the latercode after each function Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Wed Feb 23 16:28:33 2005 @@ -814,3 +814,15 @@ return (a,a1,b,b1) +# constant instances with __init__ vs. __new__ + +class Thing1: + + def __init__(self): + self.thingness = 1 + +thing1 = Thing1() + +def one_thing1(): + return thing1 + Modified: pypy/dist/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_ctrans.py (original) +++ pypy/dist/pypy/translator/test/test_ctrans.py Wed Feb 23 16:28:33 2005 @@ -193,6 +193,10 @@ assert l == [3, 'c', 8, 11, 'h', 9] assert result == ([3, 'c'], [9], [11, 'h']) + def test_global_const_w_init(self): + fn = self.build_cfunc(snippet.one_thing1) + assert fn().thingness == 1 + class TestTypedTestCase: def getcompiled(self, func): @@ -292,3 +296,4 @@ assert result == list('abc') result = fn(l, 2**64) assert result == list('abc') + From pedronis at codespeak.net Wed Feb 23 17:08:35 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 23 Feb 2005 17:08:35 +0100 (MET) Subject: [pypy-svn] r9457 - in pypy/dist/pypy/translator: . test Message-ID: <20050223160835.6883E27B53@code1.codespeak.net> Author: pedronis Date: Wed Feb 23 17:08:35 2005 New Revision: 9457 Modified: pypy/dist/pypy/translator/genc.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_ctrans.py Log: reproduce copy_reg._reconstructor behavior, this should avoid calling class own __new__, this doesn't support slots way or __new__ with complex side-effects (they are very likely overkill for our purpose) Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Wed Feb 23 17:08:35 2005 @@ -240,8 +240,15 @@ self.latercode.append((gen, self.debugstack)) def nameof_instance(self, instance): - name = self.uniquename('ginst_' + instance.__class__.__name__) - cls = self.nameof(instance.__class__) + klass = instance.__class__ + name = self.uniquename('ginst_' + klass.__name__) + cls = self.nameof(klass) + if hasattr(klass, '__base__'): + base_class = klass.__base__ + base = self.nameof(base_class) + else: + base_class = None + base = cls def initinstance(): content = instance.__dict__.items() content.sort() @@ -253,15 +260,15 @@ import copy_reg reduced = instance.__reduce_ex__() assert reduced[0] is copy_reg._reconstructor + assert reduced[1][1] is base_class state = reduced[1][2] else: state = None self.initcode.append('if isinstance(%s, type):' % cls) if state is not None: - #print "INST",' %s = %s.__new__(%s, %r)' % (name, cls, cls, state) - self.initcode.append(' %s = %s.__new__(%s, %r)' % (name, cls, cls, state)) + self.initcode.append(' %s = %s.__new__(%s, %r)' % (name, base, cls, state)) else: - self.initcode.append(' %s = %s.__new__(%s)' % (name, cls, cls)) + self.initcode.append(' %s = %s.__new__(%s)' % (name, base, cls)) self.initcode.append('else:') self.initcode.append(' %s = new.instance(%s)' % (name, cls)) self.later(initinstance()) Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Wed Feb 23 17:08:35 2005 @@ -826,3 +826,12 @@ def one_thing1(): return thing1 + +class Thing2(long): + def __new__(t,v): + return long.__new__(t,v*2) + +thing2 = Thing2(2) + +def one_thing2(): + return thing2 Modified: pypy/dist/pypy/translator/test/test_ctrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_ctrans.py (original) +++ pypy/dist/pypy/translator/test/test_ctrans.py Wed Feb 23 17:08:35 2005 @@ -197,6 +197,10 @@ fn = self.build_cfunc(snippet.one_thing1) assert fn().thingness == 1 + def test_global_const_w_new(self): + fn = self.build_cfunc(snippet.one_thing2) + assert fn() == 4 + class TestTypedTestCase: def getcompiled(self, func): From pedronis at codespeak.net Wed Feb 23 17:51:05 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 23 Feb 2005 17:51:05 +0100 (MET) Subject: [pypy-svn] r9461 - pypy/dist/pypy/translator Message-ID: <20050223165105.9F80527B53@code1.codespeak.net> Author: pedronis Date: Wed Feb 23 17:51:05 2005 New Revision: 9461 Modified: pypy/dist/pypy/translator/genc.py Log: oops, we want the builtin base up the chain. Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Wed Feb 23 17:51:05 2005 @@ -244,7 +244,7 @@ name = self.uniquename('ginst_' + klass.__name__) cls = self.nameof(klass) if hasattr(klass, '__base__'): - base_class = klass.__base__ + base_class = builtin_base(instance) base = self.nameof(base_class) else: base_class = None @@ -260,7 +260,7 @@ import copy_reg reduced = instance.__reduce_ex__() assert reduced[0] is copy_reg._reconstructor - assert reduced[1][1] is base_class + assert reduced[1][1] is base_class, "not clever enough for %r vs. %r" % (base_class, reduced) state = reduced[1][2] else: state = None From tismer at codespeak.net Wed Feb 23 17:51:33 2005 From: tismer at codespeak.net (tismer at codespeak.net) Date: Wed, 23 Feb 2005 17:51:33 +0100 (MET) Subject: [pypy-svn] r9462 - pypy/dist/pypy/translator Message-ID: <20050223165133.BDC3527B53@code1.codespeak.net> Author: tismer Date: Wed Feb 23 17:51:33 2005 New Revision: 9462 Modified: pypy/dist/pypy/translator/genc.h Log: make it run under windows: PyMODINIT_FUNC is the standard for module initializers Modified: pypy/dist/pypy/translator/genc.h ============================================================================== --- pypy/dist/pypy/translator/genc.h (original) +++ pypy/dist/pypy/translator/genc.h Wed Feb 23 17:51:33 2005 @@ -268,7 +268,7 @@ #define MODULE_INITFUNC(modname) \ static PyMethodDef no_methods[] = { (char *)NULL, (PyCFunction)NULL }; \ - void init##modname(void) + PyMODINIT_FUNC init##modname(void) #define SETUP_MODULE(modname) \ PyObject *m = Py_InitModule(#modname, no_methods); \ From pedronis at codespeak.net Wed Feb 23 18:15:45 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Wed, 23 Feb 2005 18:15:45 +0100 (MET) Subject: [pypy-svn] r9463 - pypy/dist/pypy/translator Message-ID: <20050223171545.C32CC27B53@code1.codespeak.net> Author: pedronis Date: Wed Feb 23 18:15:45 2005 New Revision: 9463 Modified: pypy/dist/pypy/translator/genc.py Log: code to grab sys.std* compatible with the new python init Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Wed Feb 23 18:15:45 2005 @@ -56,7 +56,7 @@ } self.seennames = {} self.initcode = [ # list of lines for the module's initxxx() - 'import new, types', + 'import new, types, sys', 'Py_None = None', 'Py_False = False', 'Py_True = True', @@ -259,7 +259,7 @@ if hasattr(instance,'__reduce_ex__'): import copy_reg reduced = instance.__reduce_ex__() - assert reduced[0] is copy_reg._reconstructor + assert reduced[0] is copy_reg._reconstructor,"not clever enough" assert reduced[1][1] is base_class, "not clever enough for %r vs. %r" % (base_class, reduced) state = reduced[1][2] else: @@ -435,11 +435,17 @@ def nameof_file(self, fil): if fil is sys.stdin: - return 'PySys_GetObject("stdin")' + name = self.uniquename("gsys_stdin") + self.initcode_python(name, "sys.stdin") + return name if fil is sys.stdout: - return 'PySys_GetObject("stdout")' + name = self.uniquename("gsys_stdout") + self.initcode_python(name, "sys.stdout") + return name if fil is sys.stderr: - return 'PySys_GetObject("stderr")' + name = self.uniquename("gsys_stderr") + self.initcode_python(name, "sys.stderr") + return name raise Exception, 'Cannot translate an already-open file: %r' % (fil,) def gen_source(self): From pedronis at codespeak.net Thu Feb 24 00:21:03 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 00:21:03 +0100 (MET) Subject: [pypy-svn] r9473 - in pypy/dist: goal pypy/annotation pypy/interpreter Message-ID: <20050223232103.42DCD27B4B@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 00:21:03 2005 New Revision: 9473 Modified: pypy/dist/goal/buildcache2.py pypy/dist/pypy/annotation/bookkeeper.py pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/interpreter/gateway.py Log: coalesce builtin frames on unwrap_spec, fail hard on signature confusion, this is not happening anymore remove pypy_getudir for the annotator builtin id support in the annotator Modified: pypy/dist/goal/buildcache2.py ============================================================================== --- pypy/dist/goal/buildcache2.py (original) +++ pypy/dist/goal/buildcache2.py Thu Feb 24 00:21:03 2005 @@ -4,13 +4,16 @@ def buildcache(space): space.builtin.getdict() print "*builtin*" - #w_dic = space.builtin.w_dict + w_dic = space.builtin.w_dict #print space.unwrap(space.call_method(w_dic,"keys")) + space.sys.getdict() print "*sys*" - #w_dic = space.sys.w_dict + w_dic = space.sys.w_dict #print space.unwrap(space.call_method(w_dic,"keys")) + space.delitem(w_dic,space.wrap("pypy_getudir")) + print " * removed pypy_getudir" for typedef in space.model.pythontypes: w_typ = getattr(space, 'w_' + typedef.name) Modified: pypy/dist/pypy/annotation/bookkeeper.py ============================================================================== --- pypy/dist/pypy/annotation/bookkeeper.py (original) +++ pypy/dist/pypy/annotation/bookkeeper.py Thu Feb 24 00:21:03 2005 @@ -246,7 +246,7 @@ try: inputcells = args.match_signature(signature, defs_s) except ArgErr, e: - print 'IGNORED', e # hopefully temporary hack + assert False, 'ABOUT TO IGNORE %r' % e # hopefully temporary hack return SomeImpossibleValue() return self.annotator.recursivecall(func, self.position_key, inputcells) Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Thu Feb 24 00:21:03 2005 @@ -40,6 +40,9 @@ def builtin_ord(s_chr): return SomeInteger(nonneg=True) +def builtin_id(o): + return SomeInteger() + def builtin_unicode(s_obj): return SomeString() Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Thu Feb 24 00:21:03 2005 @@ -22,6 +22,7 @@ NoneNotWrapped = object() class Signature: + "NOT_RPYTHON" def __init__(self, func=None, argnames=None, varargname=None, kwargname=None, name = None): self.func = func @@ -52,6 +53,7 @@ class UnwrapSpecRecipe: + "NOT_RPYTHON" bases_order = [BaseWrappable, W_Root, ObjSpace, Arguments, object] @@ -224,58 +226,87 @@ self.space.wrap("cannot get fastscope of a BuiltinFrame")) def run(self): + try: + w_result = self._run() + except KeyboardInterrupt: + raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) + except MemoryError: + raise OperationError(self.space.w_MemoryError, self.space.w_None) + except RuntimeError, e: + raise OperationError(self.space.w_RuntimeError, + self.space.wrap("internal error" + str(e))) + if w_result is None: + w_result = self.space.w_None + return w_result + + def _run(self): """Subclasses with behavior specific for an unwrap spec are generated""" raise TypeError, "abstract" +class FuncBox(object): + pass + class BuiltinCodeSignature(Signature): + "NOT_RPYTHON" def __init__(self,*args,**kwds): + self.unwrap_spec = kwds.get('unwrap_spec') + del kwds['unwrap_spec'] Signature.__init__(self,*args,**kwds) self.setfastscope = [] self.run_args = [] self.through_scope_w = 0 self.miniglobals = {} - def make_frame_class(self, func): - setfastscope = self.setfastscope - if not setfastscope: - setfastscope = ["pass"] - setfastscope = ["def setfastscope(self, scope_w):", - #"print 'ENTER',self.code.func.__name__", - #"print scope_w" - ] + setfastscope - setfastscope = '\n '.join(setfastscope) - # Python 2.2 SyntaxError without newline: Bug #501622 - setfastscope += '\n' - d = {} - exec compile(setfastscope, '', 'exec') in self.miniglobals, d - - self.miniglobals['func'] = func - self.miniglobals['OperationError'] = OperationError - source = """if 1: - def run(self): - try: - w_result = func(%s) - except KeyboardInterrupt: - raise OperationError(self.space.w_KeyboardInterrupt, self.space.w_None) - except MemoryError: - raise OperationError(self.space.w_MemoryError, self.space.w_None) - except RuntimeError, e: - raise OperationError(self.space.w_RuntimeError, - self.space.wrap("internal error" + str(e))) - if w_result is None: - w_result = self.space.w_None - return w_result - \n""" % ','.join(self.run_args) - exec compile(source, '', 'exec') in self.miniglobals, d + def _make_unwrap_frame_class(self, cache={}): + try: + key = tuple(self.unwrap_spec) + frame_cls, box_cls, run_args = cache[key] + assert run_args == self.run_args,"unexpected: same spec, different run_args" + return frame_cls, box_cls + except KeyError: + label = '_'.join([getattr(el, '__name__', el) for el in self.unwrap_spec]) + print label + setfastscope = self.setfastscope + if not setfastscope: + setfastscope = ["pass"] + setfastscope = ["def setfastscope_UWS_%s(self, scope_w):" % label, + #"print 'ENTER',self.code.func.__name__", + #"print scope_w" + ] + setfastscope + setfastscope = '\n '.join(setfastscope) + # Python 2.2 SyntaxError without newline: Bug #501622 + setfastscope += '\n' + d = {} + exec compile(setfastscope, '', 'exec') in self.miniglobals, d + d['setfastscope'] = d['setfastscope_UWS_%s' % label] + del d['setfastscope_UWS_%s' % label] + + self.miniglobals['OperationError'] = OperationError + source = """if 1: + def _run_UWS_%s(self): + return self.box.func(%s) + \n""" % (label, ','.join(self.run_args)) + exec compile(source, '', 'exec') in self.miniglobals, d + d['_run'] = d['_run_UWS_%s' % label] + del d['_run_UWS_%s' % label] + frame_cls = type("BuiltinFrame_UWS_%s" % label, (BuiltinFrame,), d) + box_cls = type("FuncBox_UWS_%s" % label, (FuncBox,), {}) + cache[key] = frame_cls, box_cls, self.run_args + return frame_cls, box_cls + + def make_frame_class(self, func, cache={}): + frame_uw_cls, box_cls = self._make_unwrap_frame_class() + box = box_cls() + box.func = func return type("BuiltinFrame_for_%s" % self.name, - (BuiltinFrame,),d) + (frame_uw_cls,),{'box': box}) def make_builtin_frame_class(func, orig_sig, unwrap_spec): "NOT_RPYTHON" name = (getattr(func, '__module__', None) or '')+'_'+func.__name__ emit_sig = orig_sig.apply_unwrap_spec(unwrap_spec, UnwrapSpecRecipe().emit, - BuiltinCodeSignature(name=name)) + BuiltinCodeSignature(name=name, unwrap_spec=unwrap_spec)) cls = emit_sig.make_frame_class(func) return cls From pedronis at codespeak.net Thu Feb 24 02:27:54 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 02:27:54 +0100 (MET) Subject: [pypy-svn] r9474 - in pypy/dist/pypy: annotation translator Message-ID: <20050224012754.51BFB27B4B@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 02:27:54 2005 New Revision: 9474 Modified: pypy/dist/pypy/annotation/bookkeeper.py pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/translator/annrpython.py Log: improve a bit "cannot follow" message Modified: pypy/dist/pypy/annotation/bookkeeper.py ============================================================================== --- pypy/dist/pypy/annotation/bookkeeper.py (original) +++ pypy/dist/pypy/annotation/bookkeeper.py Thu Feb 24 02:27:54 2005 @@ -251,6 +251,9 @@ return self.annotator.recursivecall(func, self.position_key, inputcells) + def whereami(self): + return self.annotator.whereami(self.position_key) + def specialize_by_key(self, thing, key, name=None): key = thing, key try: Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Thu Feb 24 02:27:54 2005 @@ -74,7 +74,7 @@ def call(obj, args): #raise Exception, "cannot follow call_args%r" % ((obj, args),) - print "*** cannot follow call(%r, %r)" % (obj, args) + print "*** [%s] cannot follow call(%r, %r)" % (getbookkeeper().whereami(), obj, args) return SomeObject() Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Thu Feb 24 02:27:54 2005 @@ -292,6 +292,15 @@ if unions != oldcells: self.bindinputargs(block, unions, called_from) + def whereami(self, position_key): + fn, block, i = position_key + mod = getattr(fn, '__module__', None) + if mod is None: + mod = '?' + name = fn.__name__ + firstlineno = fn.func_code.co_firstlineno + return "(%s:%d) %s" % (mod, firstlineno, name) + def flowin(self, fn, block): #print 'Flowing', block, [self.binding(a) for a in block.inputargs] for i in range(len(block.operations)): From pedronis at codespeak.net Thu Feb 24 11:37:21 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 11:37:21 +0100 (MET) Subject: [pypy-svn] r9478 - pypy/dist/pypy/interpreter Message-ID: <20050224103721.307AA27B4C@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 11:37:20 2005 New Revision: 9478 Modified: pypy/dist/pypy/interpreter/gateway.py Log: oops, disable debugging print statement Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Thu Feb 24 11:37:20 2005 @@ -266,7 +266,7 @@ return frame_cls, box_cls except KeyError: label = '_'.join([getattr(el, '__name__', el) for el in self.unwrap_spec]) - print label + #print label setfastscope = self.setfastscope if not setfastscope: setfastscope = ["pass"] From hpk at codespeak.net Thu Feb 24 13:54:01 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 24 Feb 2005 13:54:01 +0100 (MET) Subject: [pypy-svn] r9481 - pypy/dist/pypy/objspace/std Message-ID: <20050224125401.8CF0027B4C@code1.codespeak.net> Author: hpk Date: Thu Feb 24 13:54:01 2005 New Revision: 9481 Modified: pypy/dist/pypy/objspace/std/stringobject.py Log: move the little special "def app_*" to one applevel definition and some interphooks. Modified: pypy/dist/pypy/objspace/std/stringobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/stringobject.py (original) +++ pypy/dist/pypy/objspace/std/stringobject.py Thu Feb 24 13:54:01 2005 @@ -748,24 +748,6 @@ start = start + 1 return space.wrap("".join(buf)) - - -def app_str_translate__String_ANY_ANY(s, table, deletechars=''): - """charfilter - unicode handling is not implemented - - Return a copy of the string where all characters occurring - in the optional argument deletechars are removed, and the - remaining characters have been mapped through the given translation table, - which must be a string of length 256""" - - if len(table) < 256: - raise ValueError("translation table must be 256 characters long") - - L = [ table[ord(s[i])] for i in range(len(s)) if s[i] not in deletechars ] - return ''.join(L) - -str_translate__String_ANY_ANY = gateway.app2interp(app_str_translate__String_ANY_ANY) - def str_w__String(space, w_str): return w_str._value @@ -957,36 +939,6 @@ from pypy.objspace.std import iterobject return iterobject.W_SeqIterObject(space, w_list) -def app_contains__String_ANY(self, sub): - return self.find(sub) >= 0 - -contains__String_ANY = gateway.app2interp(app_contains__String_ANY) - -def app_repr__String(s): - quote = "'" - if quote in s and '"' not in s: - quote = '"' - - repr = quote - - for c in s: - if c == '\\' or c == quote: repr += '\\'+c - elif c == '\t': repr += '\\t' - elif c == '\r': repr += '\\r' - elif c == '\n': repr += '\\n' - elif not '\x20' <= c < '\x7f': - n = ord(c) - repr += '\\x'+"0123456789abcdef"[n>>4]+"0123456789abcdef"[n&0xF] - else: - repr += c - - repr += quote - - return repr - -repr__String = gateway.app2interp(app_repr__String) - - def ord__String(space, w_str): u_str = w_str._value if len(u_str) != 1: @@ -995,30 +947,68 @@ space.wrap("ord() expected a character, but string " "of length %d found"%(len(w_str._value),))) return space.wrap(ord(u_str)) - -def app_mod__String_ANY(format, values): - import _formatting - if isinstance(values, tuple): - return _formatting.format(format, values, None) - else: - if hasattr(values, 'keys'): - return _formatting.format(format, (values,), values) - else: - return _formatting.format(format, (values,), None) - -mod__String_ANY = gateway.app2interp(app_mod__String_ANY) - - -def app_str_decode__String_ANY_ANY(str, encoding=None, errors=None): - if encoding is None and errors is None: - return unicode(str) - elif errors is None: - return unicode(str, encoding) - else: - return unicode(str, encoding, errors) + +app = gateway.applevel(r''' + def str_translate__String_ANY_ANY(s, table, deletechars=''): + """charfilter - unicode handling is not implemented + Return a copy of the string where all characters occurring + in the optional argument deletechars are removed, and the + remaining characters have been mapped through the given translation table, + which must be a string of length 256""" + + if len(table) < 256: + raise ValueError("translation table must be 256 characters long") + + L = [ table[ord(s[i])] for i in range(len(s)) if s[i] not in deletechars ] + return ''.join(L) + + def contains__String_ANY(self, sub): + return self.find(sub) >= 0 + + def repr__String(s): + quote = "'" + if quote in s and '"' not in s: + quote = '"' + repr = quote + for c in s: + if c == '\\' or c == quote: + repr += '\\'+c + elif c == '\t': repr += '\\t' + elif c == '\r': repr += '\\r' + elif c == '\n': repr += '\\n' + elif not '\x20' <= c < '\x7f': + n = ord(c) + repr += '\\x'+"0123456789abcdef"[n>>4]+"0123456789abcdef"[n&0xF] + else: + repr += c + repr += quote + return repr + + def mod__String_ANY(format, values): + import _formatting + if isinstance(values, tuple): + return _formatting.format(format, values, None) + else: + if hasattr(values, 'keys'): + return _formatting.format(format, (values,), values) + else: + return _formatting.format(format, (values,), None) + + def str_decode__String_ANY_ANY(str, encoding=None, errors=None): + if encoding is None and errors is None: + return unicode(str) + elif errors is None: + return unicode(str, encoding) + else: + return unicode(str, encoding, errors) +''') -str_decode__String_ANY_ANY = gateway.app2interp(app_str_decode__String_ANY_ANY) +str_translate__String_ANY_ANY = app.interphook('str_translate__String_ANY_ANY') +str_decode__String_ANY_ANY = app.interphook('str_decode__String_ANY_ANY') +mod__String_ANY = app.interphook('mod__String_ANY') +contains__String_ANY = app.interphook('contains__String_ANY') +repr__String = app.interphook('repr__String') # register all methods from pypy.objspace.std import stringtype From hpk at codespeak.net Thu Feb 24 13:57:38 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 24 Feb 2005 13:57:38 +0100 (MET) Subject: [pypy-svn] r9482 - pypy/dist/pypy/objspace/std Message-ID: <20050224125738.1287327B4C@code1.codespeak.net> Author: hpk Date: Thu Feb 24 13:57:37 2005 New Revision: 9482 Modified: pypy/dist/pypy/objspace/std/dictobject.py Log: transform another app_-namehack based definition (this time with appdef() because we don't need such helpers from applevel) Modified: pypy/dist/pypy/objspace/std/dictobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/dictobject.py (original) +++ pypy/dist/pypy/objspace/std/dictobject.py Thu Feb 24 13:57:37 2005 @@ -242,27 +242,27 @@ else: return w_default -# Now we only handle one implementation of dicts, this one. -# The fix is to move this to dicttype.py, and do a -# multimethod lookup mapping str to StdObjSpace.str -# This cannot happen until multimethods are fixed. See dicttype.py -def app_dictstr(currently_in_repr, d): - dict_id = id(d) - if dict_id in currently_in_repr: - return '{...}' - currently_in_repr[dict_id] = 1 - try: - items = [] - for k, v in d.iteritems(): - items.append(repr(k) + ": " + repr(v)) - return "{" + ', '.join(items) + "}" - finally: - try: - del currently_in_repr[dict_id] - except: - pass - -dictstr = gateway.app2interp(app_dictstr) +dictstr = gateway.appdef(''' + dictstr(currently_in_repr, d): + # Now we only handle one implementation of dicts, this one. + # The fix is to move this to dicttype.py, and do a + # multimethod lookup mapping str to StdObjSpace.str + # This cannot happen until multimethods are fixed. See dicttype.py + dict_id = id(d) + if dict_id in currently_in_repr: + return '{...}' + currently_in_repr[dict_id] = 1 + try: + items = [] + for k, v in d.iteritems(): + items.append(repr(k) + ": " + repr(v)) + return "{" + ', '.join(items) + "}" + finally: + try: + del currently_in_repr[dict_id] + except: + pass +''') def str__Dict(space, w_dict): if w_dict.used == 0: @@ -276,5 +276,6 @@ return dictstr(space, w_currently_in_repr, w_dict) repr__Dict = str__Dict + from pypy.objspace.std import dicttype register_all(vars(), dicttype) From pedronis at codespeak.net Thu Feb 24 15:22:15 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 15:22:15 +0100 (MET) Subject: [pypy-svn] r9483 - in pypy/dist: goal pypy/annotation pypy/interpreter pypy/objspace/std Message-ID: <20050224142215.EF44E27B53@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 15:22:15 2005 New Revision: 9483 Modified: pypy/dist/goal/buildcache2.py pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/interpreter/typedef.py pypy/dist/pypy/objspace/std/model.py pypy/dist/pypy/objspace/std/typeobject.py Log: add a list of interp typedefs to interpreter type model added missing things in std objspace model better cache filling don't confuse the annotator with {} vs None for W_TypeObject.lazyloaders => as long as type dict have been filled, we don't end up anymore in the lazy path of W_TypeObject.getdictvalue is_true for PBCs Modified: pypy/dist/goal/buildcache2.py ============================================================================== --- pypy/dist/goal/buildcache2.py (original) +++ pypy/dist/goal/buildcache2.py Thu Feb 24 15:22:15 2005 @@ -1,5 +1,6 @@ import autopath +from pypy.interpreter.typedef import interptypes def buildcache(space): space.builtin.getdict() @@ -15,6 +16,11 @@ space.delitem(w_dic,space.wrap("pypy_getudir")) print " * removed pypy_getudir" + for typedef in interptypes: + w_typ = space.gettypeobject(typedef) + w_typ.getdict() + print "*%s*" % typedef.name + for typedef in space.model.pythontypes: w_typ = getattr(space, 'w_' + typedef.name) w_typ.getdict() @@ -22,6 +28,8 @@ print "*%s*" % typedef.name #print w_typ.dict_w.keys() + space.builtin.get('file').getdict() + space.appexec([],"""(): try: raise ValueError Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Thu Feb 24 15:22:15 2005 @@ -268,7 +268,17 @@ d[func] = value return SomePBC(d) - + def is_true(pbc): + outcome = None + for c in pbc.prebuiltinstances: + if outcome is None: + outcome = bool(c) + else: + if outcome != bool(c): + return SomeBool() + return immutablevalue(outcome) + + class RPythonCallsSpace: """Pseudo Object Space providing almost no real operation. For the Arguments class: if it really needs other operations, it means Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Thu Feb 24 15:22:15 2005 @@ -413,3 +413,8 @@ ) ControlFlowException.typedef = TypeDef("ControlFlowException") + + +interptypes = [ val.typedef for name,val in globals().items() if hasattr(val, 'typedef') ] + + Modified: pypy/dist/pypy/objspace/std/model.py ============================================================================== --- pypy/dist/pypy/objspace/std/model.py (original) +++ pypy/dist/pypy/objspace/std/model.py Thu Feb 24 15:22:15 2005 @@ -27,6 +27,8 @@ from pypy.objspace.std.longtype import long_typedef from pypy.objspace.std.unicodetype import unicode_typedef from pypy.objspace.std.dictproxytype import dictproxy_typedef + from pypy.objspace.std.nonetype import none_typedef + from pypy.objspace.std.itertype import iter_typedef self.pythontypes = [value for key, value in result.__dict__.items() if not key.startswith('_')] # don't look Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Thu Feb 24 15:22:15 2005 @@ -8,7 +8,7 @@ class W_TypeObject(W_Object): from pypy.objspace.std.typetype import type_typedef as typedef - lazyloaders = None # can be overridden by specific instances + lazyloaders = {} # can be overridden by specific instances def __init__(w_self, space, name, bases_w, dict_w, overridetypedef=None): From hpk at codespeak.net Thu Feb 24 16:22:45 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 24 Feb 2005 16:22:45 +0100 (MET) Subject: [pypy-svn] r9484 - pypy/dist/pypy/objspace/std Message-ID: <20050224152245.4149827B4F@code1.codespeak.net> Author: hpk Date: Thu Feb 24 16:22:45 2005 New Revision: 9484 Modified: pypy/dist/pypy/objspace/std/floatobject.py pypy/dist/pypy/objspace/std/listobject.py pypy/dist/pypy/objspace/std/register_all.py pypy/dist/pypy/objspace/std/sliceobject.py pypy/dist/pypy/objspace/std/tupleobject.py pypy/dist/pypy/objspace/std/typeobject.py Log: moved the remaining occurences of "def app_" to applevel/appdef style definitions. Modified: pypy/dist/pypy/objspace/std/floatobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/floatobject.py (original) +++ pypy/dist/pypy/objspace/std/floatobject.py Thu Feb 24 16:22:45 2005 @@ -56,23 +56,25 @@ def float_w__Float(space, w_float): return w_float.floatval -def app_repr__Float(f): - r = "%.17g"%f - for c in r: - if c not in '-0123456789': - return r - else: - return r + '.0' -repr__Float = gateway.app2interp(app_repr__Float) +app = gateway.applevel(''' + def repr__Float(f): + r = "%.17g"%f + for c in r: + if c not in '-0123456789': + return r + else: + return r + '.0' -def app_str__Float(f): - r = "%.12g"%f - for c in r: - if c not in '-0123456789': - return r - else: - return r + '.0' -str__Float = gateway.app2interp(app_str__Float) + def str__Float(f): + r = "%.12g"%f + for c in r: + if c not in '-0123456789': + return r + else: + return r + '.0' +''') +repr__Float = app.interphook('repr__Float') +str__Float = app.interphook('str__Float') def lt__Float_Float(space, w_float1, w_float2): i = w_float1.floatval Modified: pypy/dist/pypy/objspace/std/listobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/listobject.py (original) +++ pypy/dist/pypy/objspace/std/listobject.py Thu Feb 24 16:22:45 2005 @@ -278,20 +278,21 @@ items[start+i*step] = sequence2[i] return space.w_None -def app_listrepr(currently_in_repr, l): - 'The app-level part of repr().' - list_id = id(l) - if list_id in currently_in_repr: - return '[...]' - currently_in_repr[list_id] = 1 - try: - return "[" + ", ".join([repr(x) for x in l]) + ']' - finally: +listrepr = gateway.appdef(""" + listrepr(currently_in_repr, l): + 'The app-level part of repr().' + list_id = id(l) + if list_id in currently_in_repr: + return '[...]' + currently_in_repr[list_id] = 1 try: - del currently_in_repr[list_id] - except: - pass -listrepr = gateway.app2interp(app_listrepr) + return "[" + ", ".join([repr(x) for x in l]) + ']' + finally: + try: + del currently_in_repr[list_id] + except: + pass +""") def repr__List(space, w_list): if w_list.ob_size == 0: Modified: pypy/dist/pypy/objspace/std/register_all.py ============================================================================== --- pypy/dist/pypy/objspace/std/register_all.py (original) +++ pypy/dist/pypy/objspace/std/register_all.py Thu Feb 24 16:22:45 2005 @@ -18,6 +18,8 @@ namespaces.insert(0, alt_ns) for name, obj in module_dict.items(): + if name.startswith('app_'): + print "%s: direct app definitions deprecated" % name if name.find('__')<1 or name.startswith('app_'): continue funcname, sig = name.split('__') Modified: pypy/dist/pypy/objspace/std/sliceobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/sliceobject.py (original) +++ pypy/dist/pypy/objspace/std/sliceobject.py Thu Feb 24 16:22:45 2005 @@ -24,10 +24,10 @@ registerimplementation(W_SliceObject) -def app_repr__Slice(aslice): - return 'slice(%r, %r, %r)' % (aslice.start, aslice.stop, aslice.step) - -repr__Slice = gateway.app2interp(app_repr__Slice) +repr__Slice = gateway.appdef(""" + repr__Slice(aslice): + return 'slice(%r, %r, %r)' % (aslice.start, aslice.stop, aslice.step) +""") def eq__Slice_Slice(space, w_slice1, w_slice2): # We need this because CPython considers that slice1 == slice1 Modified: pypy/dist/pypy/objspace/std/tupleobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/tupleobject.py (original) +++ pypy/dist/pypy/objspace/std/tupleobject.py Thu Feb 24 16:22:45 2005 @@ -111,13 +111,15 @@ # No more items to compare -- compare sizes return space.newbool(len(items1) > len(items2)) -def app_repr__Tuple(t): - if len(t) == 1: - return "(" + repr(t[0]) + ",)" - else: - return "(" + ", ".join([repr(x) for x in t]) + ')' +app = gateway.applevel(""" + def repr__Tuple(t): + if len(t) == 1: + return "(" + repr(t[0]) + ",)" + else: + return "(" + ", ".join([repr(x) for x in t]) + ')' +""") -repr__Tuple = gateway.app2interp(app_repr__Tuple) +repr__Tuple = app.interphook('repr__Tuple') def hash__Tuple(space, w_tuple): # silly-ish, but _correct_, while lacking it would be WRONG Modified: pypy/dist/pypy/objspace/std/typeobject.py ============================================================================== --- pypy/dist/pypy/objspace/std/typeobject.py (original) +++ pypy/dist/pypy/objspace/std/typeobject.py Thu Feb 24 16:22:45 2005 @@ -243,20 +243,19 @@ # ____________________________________________________________ -def app_abstract_mro(klass): - # abstract/classic mro - mro = [] - def fill_mro(klass): - if klass not in mro: - mro.append(klass) - assert isinstance(klass.__bases__, tuple) - for base in klass.__bases__: - fill_mro(base) - fill_mro(klass) - return mro - -abstract_mro = gateway.app2interp(app_abstract_mro) - +abstract_mro = gateway.appdef(""" + abstract_mro(klass): + # abstract/classic mro + mro = [] + def fill_mro(klass): + if klass not in mro: + mro.append(klass) + assert isinstance(klass.__bases__, tuple) + for base in klass.__bases__: + fill_mro(base) + fill_mro(klass) + return mro +""") def get_mro(space, klass): if isinstance(klass, W_TypeObject): From pedronis at codespeak.net Thu Feb 24 17:37:59 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 17:37:59 +0100 (MET) Subject: [pypy-svn] r9485 - in pypy/dist/pypy: annotation interpreter tool translator Message-ID: <20050224163759.74E9E27B4C@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 17:37:59 2005 New Revision: 9485 Added: pypy/dist/pypy/tool/ansi_print.py (contents, props changed) Modified: pypy/dist/pypy/annotation/bookkeeper.py pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/annotation/unaryop.py pypy/dist/pypy/interpreter/error.py pypy/dist/pypy/translator/annrpython.py Log: make a print using ansi terminal codes generally available, use where possible coloring for the annotation WARNINGs add a WARNING in debug mode for functions inferred to return SomeObject Modified: pypy/dist/pypy/annotation/bookkeeper.py ============================================================================== --- pypy/dist/pypy/annotation/bookkeeper.py (original) +++ pypy/dist/pypy/annotation/bookkeeper.py Thu Feb 24 17:37:59 2005 @@ -246,7 +246,7 @@ try: inputcells = args.match_signature(signature, defs_s) except ArgErr, e: - assert False, 'ABOUT TO IGNORE %r' % e # hopefully temporary hack + assert False, 'ABOUT TO IGNORE %r' % e # we should take care that we don't end up here anymore return SomeImpossibleValue() return self.annotator.recursivecall(func, self.position_key, inputcells) Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Thu Feb 24 17:37:59 2005 @@ -3,6 +3,7 @@ """ import types +from pypy.tool.ansi_print import ansi_print from pypy.annotation.model import SomeInteger, SomeObject, SomeChar, SomeBool from pypy.annotation.model import SomeList, SomeString, SomeTuple, SomeSlice from pypy.annotation.bookkeeper import getbookkeeper @@ -91,15 +92,19 @@ def builtin_getattr(s_obj, s_attr, s_default=None): if not s_attr.is_constant() or not isinstance(s_attr.const, str): - print "UN-RPYTHONIC-WARNING", \ - 'getattr(%r, %r) is not RPythonic enough' % (s_obj, s_attr) + ansi_print("UN-RPYTHONIC-WARNING " + + '[%s] getattr(%r, %r) is not RPythonic enough' % (getbookkeeper().whereami(), + s_obj, s_attr), + esc="31") # RED return SomeObject() return s_obj.getattr(s_attr) def builtin_hasattr(s_obj, s_attr): if not s_attr.is_constant() or not isinstance(s_attr.const, str): - print "UN-RPYTHONIC-WARNING", \ - 'hasattr(%r, %r) is not RPythonic enough' % (s_obj, s_attr) + ansi_print("UN-RPYTHONIC-WARNING " + + '[%s] hasattr(%r, %r) is not RPythonic enough' % (getbookkeeper().whereami(), + s_obj, s_attr), + esc="31") # RED return SomeBool() def builtin_hash(s_obj): Modified: pypy/dist/pypy/annotation/unaryop.py ============================================================================== --- pypy/dist/pypy/annotation/unaryop.py (original) +++ pypy/dist/pypy/annotation/unaryop.py Thu Feb 24 17:37:59 2005 @@ -3,6 +3,7 @@ """ from types import FunctionType +from pypy.tool.ansi_print import ansi_print from pypy.interpreter.argument import Arguments from pypy.annotation.pairtype import pair from pypy.annotation.model import SomeObject, SomeInteger, SomeBool @@ -74,7 +75,8 @@ def call(obj, args): #raise Exception, "cannot follow call_args%r" % ((obj, args),) - print "*** [%s] cannot follow call(%r, %r)" % (getbookkeeper().whereami(), obj, args) + ansi_print("*** WARNING: [%s] cannot follow call(%r, %r)" % + (getbookkeeper().whereami(), obj, args), esc="31") # RED return SomeObject() @@ -233,7 +235,8 @@ def setattr(pbc, s_attr, s_value): #raise Exception, "oops!" - print "*** WARNING: setattr not wanted on %r" % pbc + ansi_print("*** WARNING: [%s] setattr not wanted on %r" % + (getbookkeeper().whereami(), pbc), esc="31") # RED pass def call(pbc, args): Modified: pypy/dist/pypy/interpreter/error.py ============================================================================== --- pypy/dist/pypy/interpreter/error.py (original) +++ pypy/dist/pypy/interpreter/error.py Thu Feb 24 17:37:59 2005 @@ -1,3 +1,4 @@ +import autopath import os, sys AUTO_DEBUG = os.getenv('PYPY_DEBUG') @@ -123,16 +124,10 @@ # Utilities +from pypy.tool.ansi_print import ansi_print def debug_print(text, file=None): - if file is None: file = sys.stderr - text = text.rstrip() - if sys.platform != "win32" and file.isatty(): - text = ('\x1b[31m' + # ANSI color code "red" - text + - '\x1b[0m') # ANSI color code "reset" - file.write(text + '\n') - + ansi_print(text, esc="31", file=file) # ANSI color code "red" ### installing the excepthook for OperationErrors ##def operr_excepthook(exctype, value, traceback): Added: pypy/dist/pypy/tool/ansi_print.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/tool/ansi_print.py Thu Feb 24 17:37:59 2005 @@ -0,0 +1,10 @@ +import sys + +def ansi_print(text, esc, file=None): + if file is None: file = sys.stderr + text = text.rstrip() + if sys.platform != "win32" and file.isatty(): + text = ('\x1b[%sm' % esc + + text + + '\x1b[0m') # ANSI color code "reset" + file.write(text + '\n') Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Thu Feb 24 17:37:59 2005 @@ -1,6 +1,7 @@ from __future__ import generators from types import FunctionType, ClassType +from pypy.tool.ansi_print import ansi_print from pypy.annotation import model as annmodel from pypy.annotation.model import pair from pypy.annotation.factory import ListFactory, DictFactory, BlockedInference @@ -38,22 +39,35 @@ self.binding_cause_history = {} # map Variables to lists of positions # history of binding_caused_by, kept in sync with # bindingshistory + self.return_bindings = {} # map return Variables to functions # --- end of debugging information --- self.bookkeeper = Bookkeeper(self) + + def _register_returnvar(self, flowgraph, func): + if annmodel.DEBUG: + self.return_bindings[flowgraph.getreturnvar()] = func + #___ convenience high-level interface __________________ + def getflowgraph(self, func, called_by=None, call_tag=None): + flowgraph = self.translator.getflowgraph(func, called_by=called_by, call_tag=call_tag) + self._register_returnvar(flowgraph, func) + return flowgraph + + def build_types(self, func_or_flowgraph, input_arg_types, func=None): """Recursively build annotations about the specific entry point.""" if isinstance(func_or_flowgraph, FunctionGraph): flowgraph = func_or_flowgraph + self._register_returnvar(flowgraph, func) else: func = func_or_flowgraph if self.translator is None: from pypy.translator.translator import Translator self.translator = Translator(func, simplifying=True) self.translator.annotator = self - flowgraph = self.translator.getflowgraph(func) + flowgraph = self.getflowgraph(func) # make input arguments and set their type input_arg_types = list(input_arg_types) nbarg = len(flowgraph.getargs()) @@ -166,6 +180,17 @@ cause_history.append(self.binding_caused_by[arg]) self.bindings[arg] = s_value if annmodel.DEBUG: + #if arg in self.return_bindings: + # ansi_print("%s -> %s" % (self.whereami((self.return_bindings[arg], + # None, None)), + # s_value), + # esc="1") # bold + + if arg in self.return_bindings and s_value == annmodel.SomeObject(): + ansi_print("*** WARNING: %s result degenerated to SomeObject" % + self.whereami((self.return_bindings[arg],None, None)), + esc="31") # RED + self.binding_caused_by[arg] = called_from @@ -173,8 +198,7 @@ def recursivecall(self, func, position_key, inputcells): parent_fn, parent_block, parent_index = position_key - graph = self.translator.getflowgraph(func, parent_fn, - position_key) + graph = self.getflowgraph(func, parent_fn, position_key) # self.notify[graph.returnblock] is a dictionary of call # points to this func which triggers a reflow whenever the # return block of this graph has been analysed. @@ -297,8 +321,12 @@ mod = getattr(fn, '__module__', None) if mod is None: mod = '?' - name = fn.__name__ - firstlineno = fn.func_code.co_firstlineno + name = getattr(fn, '__name__', None) + if name is not None: + firstlineno = fn.func_code.co_firstlineno + else: + name = 'UNKNOWN' + firstlineno = -1 return "(%s:%d) %s" % (mod, firstlineno, name) def flowin(self, fn, block): From hpk at codespeak.net Thu Feb 24 17:47:05 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 24 Feb 2005 17:47:05 +0100 (MET) Subject: [pypy-svn] r9486 - in pypy/dist/pypy: interpreter objspace objspace/std tool Message-ID: <20050224164705.26E4E27B4C@code1.codespeak.net> Author: hpk Date: Thu Feb 24 17:47:04 2005 New Revision: 9486 Added: pypy/dist/pypy/tool/compile.py Modified: pypy/dist/pypy/interpreter/gateway.py pypy/dist/pypy/interpreter/typedef.py pypy/dist/pypy/objspace/descroperation.py pypy/dist/pypy/objspace/std/multimethod.py pypy/dist/pypy/objspace/std/stdtypedef.py Log: added a new compile2 convenience tool and made most places which used compile(source, '', 'exec') use compile2 now. compile2 uses a cache dependend on its arguments. compile2 is also a good place now to raise Errors or warnings in order to detect all the places where duplicate code (often duplicate functions with different globals) is generated. These places are interesting to revisit and "optimize" because the amount of generated code increases the amount of code to be generated. Modified: pypy/dist/pypy/interpreter/gateway.py ============================================================================== --- pypy/dist/pypy/interpreter/gateway.py (original) +++ pypy/dist/pypy/interpreter/gateway.py Thu Feb 24 17:47:04 2005 @@ -16,6 +16,7 @@ from pypy.interpreter.baseobjspace import W_Root,ObjSpace, BaseWrappable, Wrappable from pypy.interpreter.argument import Arguments from pypy.tool.cache import Cache +from pypy.tool.compile import compile2 # internal non-translatable parts: from pypy.tool.getpy import py # XXX from interpreter/ we get py.py @@ -278,7 +279,7 @@ # Python 2.2 SyntaxError without newline: Bug #501622 setfastscope += '\n' d = {} - exec compile(setfastscope, '', 'exec') in self.miniglobals, d + exec compile2(setfastscope) in self.miniglobals, d d['setfastscope'] = d['setfastscope_UWS_%s' % label] del d['setfastscope_UWS_%s' % label] @@ -287,7 +288,7 @@ def _run_UWS_%s(self): return self.box.func(%s) \n""" % (label, ','.join(self.run_args)) - exec compile(source, '', 'exec') in self.miniglobals, d + exec compile2(source) in self.miniglobals, d d['_run'] = d['_run_UWS_%s' % label] del d['_run_UWS_%s' % label] frame_cls = type("BuiltinFrame_UWS_%s" % label, (BuiltinFrame,), d) Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Thu Feb 24 17:47:04 2005 @@ -6,6 +6,7 @@ from pypy.interpreter.baseobjspace import BaseWrappable, Wrappable from pypy.interpreter.error import OperationError from pypy.tool.cache import Cache +from pypy.tool.compile import compile2 import new class TypeDef: @@ -123,7 +124,7 @@ miniglobals[cls_name] = cls check = "isinstance(obj, %s)" % cls_name expected = "%s.typedef.name" % cls_name - + source = """if 1: def descr_typecheck_%(name)s(space, w_obj, %(extra)s): obj = %(unwrap)s @@ -137,7 +138,7 @@ 'expected': expected, 'unwrap': unwrap, 'extra': ', '.join(extraargs)} - exec compile(source, '', 'exec') in miniglobals + exec compile2(source) in miniglobals return miniglobals['descr_typecheck_%s' % func.__name__] Modified: pypy/dist/pypy/objspace/descroperation.py ============================================================================== --- pypy/dist/pypy/objspace/descroperation.py (original) +++ pypy/dist/pypy/objspace/descroperation.py Thu Feb 24 17:47:04 2005 @@ -4,6 +4,7 @@ from pypy.interpreter.function import Function from pypy.interpreter.gateway import BuiltinCode from pypy.interpreter.argument import Arguments +from pypy.tool.compile import compile2 def raiseattrerror(space, w_obj, name): w_type = space.type(w_obj) @@ -588,8 +589,7 @@ DescrOperation.%(targetname)s = %(targetname)s del %(targetname)s \n""" % locals() - exec compile(source, '', 'exec') - + exec compile2(source) # add default operation implementations for all still missing ops Modified: pypy/dist/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/dist/pypy/objspace/std/multimethod.py Thu Feb 24 17:47:04 2005 @@ -1,4 +1,5 @@ +from pypy.tool.compile import compile2 class FailedToImplement(Exception): pass @@ -252,7 +253,7 @@ source = '\n'.join(bodylines) #print source #print "*"*60 - exec compile(source, '', 'exec') in miniglobals + exec compile2(source) in miniglobals func = miniglobals[funcname] self.to_install.append((target, funcname, func, source, fallback)) return func Modified: pypy/dist/pypy/objspace/std/stdtypedef.py ============================================================================== --- pypy/dist/pypy/objspace/std/stdtypedef.py (original) +++ pypy/dist/pypy/objspace/std/stdtypedef.py Thu Feb 24 17:47:04 2005 @@ -2,6 +2,7 @@ from pypy.interpreter.error import OperationError from pypy.interpreter.typedef import TypeDef, GetSetProperty, Member from pypy.objspace.std.model import MultiMethod, FailedToImplement +from pypy.tool.compile import compile2 __all__ = ['StdTypeDef', 'newmethod', 'gateway', 'GetSetProperty', 'Member', @@ -239,7 +240,7 @@ return w_res """ % (prefix, wrapper_sig, renaming, expr, multimethod.operatorsymbol, ', '.join(solid_arglist)) - exec compile(code, '', 'exec') in miniglobals + exec compile2(code, '', 'exec') in miniglobals return miniglobals["%s_perform_call" % prefix] def wrap_trampoline_in_gateway(func, methname, multimethod): Added: pypy/dist/pypy/tool/compile.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/tool/compile.py Thu Feb 24 17:47:04 2005 @@ -0,0 +1,15 @@ +from __future__ import generators +cache = {} + +def compile2(source, filename='', mode='exec', flags= + generators.compiler_flag, dont_inherit=0): + """ central compile hook for pypy initialization + purposes. + """ + key = (source, filename, mode, flags) + try: + co = cache[key] + except KeyError: + co = compile(source, filename, mode, flags) + cache[key] = co + return co From hpk at codespeak.net Thu Feb 24 17:49:09 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Thu, 24 Feb 2005 17:49:09 +0100 (MET) Subject: [pypy-svn] r9488 - pypy/dist/pypy/tool Message-ID: <20050224164909.DAE2527B4C@code1.codespeak.net> Author: hpk Date: Thu Feb 24 17:49:09 2005 New Revision: 9488 Modified: pypy/dist/pypy/tool/compile.py Log: added commented out prints for detecting duplicate code Modified: pypy/dist/pypy/tool/compile.py ============================================================================== --- pypy/dist/pypy/tool/compile.py (original) +++ pypy/dist/pypy/tool/compile.py Thu Feb 24 17:49:09 2005 @@ -9,6 +9,8 @@ key = (source, filename, mode, flags) try: co = cache[key] + #print "***** duplicate code ******* " + #print source except KeyError: co = compile(source, filename, mode, flags) cache[key] = co From pedronis at codespeak.net Thu Feb 24 19:04:44 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 19:04:44 +0100 (MET) Subject: [pypy-svn] r9490 - pypy/dist/pypy/annotation Message-ID: <20050224180444.D787C27B4C@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 19:04:44 2005 New Revision: 9490 Modified: pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/annotation/model.py Log: some more builtins Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Thu Feb 24 19:04:44 2005 @@ -3,6 +3,7 @@ """ import types +import sys from pypy.tool.ansi_print import ansi_print from pypy.annotation.model import SomeInteger, SomeObject, SomeChar, SomeBool from pypy.annotation.model import SomeList, SomeString, SomeTuple, SomeSlice @@ -44,6 +45,12 @@ def builtin_id(o): return SomeInteger() +def builtin_hex(o): + return SomeString() + +def builtin_abs(o): + return o.__class__() + def builtin_unicode(s_obj): return SomeString() @@ -167,6 +174,9 @@ def exception_init(s_self, *args): s_self.setattr(immutablevalue('args'), SomeTuple(args)) +def count(s_obj): + return SomeInteger() + # collect all functions import __builtin__ BUILTIN_ANALYZERS = {} @@ -178,4 +188,4 @@ BUILTIN_ANALYZERS[pypy.objspace.std.restricted_int.r_int] = builtin_int BUILTIN_ANALYZERS[pypy.objspace.std.restricted_int.r_uint] = restricted_uint BUILTIN_ANALYZERS[Exception.__init__.im_func] = exception_init - +BUILTIN_ANALYZERS[sys.getrefcount] = count Modified: pypy/dist/pypy/annotation/model.py ============================================================================== --- pypy/dist/pypy/annotation/model.py (original) +++ pypy/dist/pypy/annotation/model.py Thu Feb 24 19:04:44 2005 @@ -66,6 +66,7 @@ def contains(self, other): return self == other or pair(self, other).union() == self + def is_constant(self): return hasattr(self, 'const') From pedronis at codespeak.net Thu Feb 24 22:23:38 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 22:23:38 +0100 (MET) Subject: [pypy-svn] r9491 - pypy/dist/pypy/annotation Message-ID: <20050224212338.2957727B4A@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 22:23:37 2005 New Revision: 9491 Modified: pypy/dist/pypy/annotation/binaryop.py Log: improve just a bit issubtype Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Thu Feb 24 22:23:37 2005 @@ -93,7 +93,7 @@ r = SomeBool() if obj2.is_constant(): if obj1.is_constant(): - r.const = obj1.const is obj2.const + r.const = obj1.const is obj2.const # XXX HACK HACK HACK # XXX HACK HACK HACK # XXX HACK HACK HACK @@ -319,6 +319,8 @@ class __extend__(pairtype(SomeObject, SomePBC)): def issubtype((obj, pbc)): s = SomeBool() + if obj.is_constant() and pbc.is_constant(): + s.const = issubclass(obj.const, pbc.const) if hasattr(obj,'is_type_of') and pbc.is_constant(): bk = getbookkeeper() s.knowntypedata = (obj.is_type_of, bk.valueoftype(pbc.const)) From pedronis at codespeak.net Thu Feb 24 22:38:10 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 22:38:10 +0100 (MET) Subject: [pypy-svn] r9492 - pypy/dist/pypy/translator/test Message-ID: <20050224213810.D9C1127B4A@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 22:38:10 2005 New Revision: 9492 Modified: pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: failing test that shows the problems with annoting exception handling code, when there are many possible exception sources in the try ... except suite. Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Thu Feb 24 22:38:10 2005 @@ -725,6 +725,31 @@ return (e, Exc2()) return (Exc(), Exc2()) +class Exc3(Exception): + def m(self): + return 1 + +class Sp: + def o(self): + raise Exc3 + +class Mod: + def __init__(self, s): + self.s = s + + def p(self): + s = self.s + try: + s.o() + except Exc3, e: + return e.m() + return 0 + +mod = Mod(Sp()) + +def exc_deduction_our_exc_plus_others(): + return mod.p() + class BltinCode: def __init__(self, func, framecls): Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Thu Feb 24 22:38:10 2005 @@ -483,7 +483,12 @@ assert isinstance(s.items[1], annmodel.SomeInstance) assert s.items[0].knowntype is snippet.Exc assert s.items[1].knowntype is snippet.Exc2 - + + def test_exc_deduction_our_exc_plus_others(self): + a = RPythonAnnotator() + s = a.build_types(snippet.exc_deduction_our_exc_plus_others, []) + assert isinstance(s, annmodel.SomeInteger) + def test_slice_union(self): a = RPythonAnnotator() s = a.build_types(snippet.slice_union, [int]) From pedronis at codespeak.net Thu Feb 24 23:12:59 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Thu, 24 Feb 2005 23:12:59 +0100 (MET) Subject: [pypy-svn] r9495 - pypy/dist/pypy/interpreter Message-ID: <20050224221259.CCDCD27B37@code1.codespeak.net> Author: pedronis Date: Thu Feb 24 23:12:59 2005 New Revision: 9495 Modified: pypy/dist/pypy/interpreter/typedef.py Log: oops, avoid duplicates Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Thu Feb 24 23:12:59 2005 @@ -416,6 +416,6 @@ ControlFlowException.typedef = TypeDef("ControlFlowException") -interptypes = [ val.typedef for name,val in globals().items() if hasattr(val, 'typedef') ] +interptypes = [ val.typedef for name,val in globals().items() if hasattr(val,'__bases__') and hasattr(val,'typedef') ] From pedronis at codespeak.net Fri Feb 25 16:38:27 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 25 Feb 2005 16:38:27 +0100 (MET) Subject: [pypy-svn] r9502 - in pypy/dist/pypy: annotation objspace/flow translator translator/test translator/tool Message-ID: <20050225153827.6408F27B3D@code1.codespeak.net> Author: pedronis Date: Fri Feb 25 16:38:27 2005 New Revision: 9502 Modified: pypy/dist/pypy/annotation/binaryop.py pypy/dist/pypy/annotation/model.py pypy/dist/pypy/objspace/flow/flowcontext.py pypy/dist/pypy/objspace/flow/model.py pypy/dist/pypy/objspace/flow/objspace.py pypy/dist/pypy/translator/annrpython.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py pypy/dist/pypy/translator/test/test_pyrextrans.py pypy/dist/pypy/translator/tool/make_dot.py Log: - added another test involving exception handling improved annotation of ex handling code: we pass this and yesterday added test, notice that the improved logic works only on simplfied flow graph (changed some tests to respect this), (I have added code that mark a block starting exc handling, thinking I could have needed the info, right now it seems not the case) - changed a bit the way we deal with functions never returning but only raising exceptions, may want to write a test to see whether this effectively helps with the kind of code involved in multimethods failing paths. Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Fri Feb 25 16:38:27 2005 @@ -36,6 +36,10 @@ return obj1 else: result = SomeObject() + is_type_of1 = getattr(obj1, 'is_type_of', None) + is_type_of2 = getattr(obj2, 'is_type_of', None) + if is_type_of1 and is_type_of1 == is_type_of2: + result.is_type_of = is_type_of1 # try to preserve the origin of SomeObjects if obj1 == result: return obj1 @@ -292,7 +296,16 @@ if isclassdef(classdef): classdef = classdef.commonbase(d[x]) d[x] = classdef - return SomePBC(d) + result = SomePBC(d) + is_type_of1 = getattr(pbc1, 'is_type_of', None) + is_type_of2 = getattr(pbc2, 'is_type_of', None) + if is_type_of1 and is_type_of1 == is_type_of2: + result.is_type_of = is_type_of1 + return result + +class __extend__(pairtype(SomeImpossibleValue, SomeImpossibleValue)): + def union((imp1, imp2)): + return SomeImpossibleValue(benign=imp1.benign and imp2.benign) class __extend__(pairtype(SomeImpossibleValue, SomeObject)): def union((imp1, obj2)): Modified: pypy/dist/pypy/annotation/model.py ============================================================================== --- pypy/dist/pypy/annotation/model.py (original) +++ pypy/dist/pypy/annotation/model.py Fri Feb 25 16:38:27 2005 @@ -243,11 +243,13 @@ class SomeImpossibleValue(SomeObject): """The empty set. Instances are placeholders for objects that will never show up at run-time, e.g. elements of an empty list.""" + def __init__(self, benign=False): + self.benign = benign def unionof(*somevalues): "The most precise SomeValue instance that contains all the values." - s1 = SomeImpossibleValue() + s1 = SomeImpossibleValue(benign=len(somevalues)>0) for s2 in somevalues: if s1 != s2: s1 = pair(s1, s2).union() Modified: pypy/dist/pypy/objspace/flow/flowcontext.py ============================================================================== --- pypy/dist/pypy/objspace/flow/flowcontext.py (original) +++ pypy/dist/pypy/objspace/flow/flowcontext.py Fri Feb 25 16:38:27 2005 @@ -196,11 +196,11 @@ w_condition,) def guessexception(self, *classes): - outcome = self.guessbool(Constant(last_exception), + outcome = self.guessbool(Constant(last_exception, last_exception=True), cases = [None] + list(classes), replace_last_variable_except_in_first_case = [ - Constant(last_exception), # exc. class - Constant(last_exc_value)]) # exc. value + Constant(last_exception, last_exception=True), # exc. class + Constant(last_exc_value, last_exc_value=True)]) # exc. value if outcome is None: w_exc_cls, w_exc_value = None, None else: Modified: pypy/dist/pypy/objspace/flow/model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/model.py (original) +++ pypy/dist/pypy/objspace/flow/model.py Fri Feb 25 16:38:27 2005 @@ -67,11 +67,15 @@ # Constant(last_exception), see below self.exits = [] # list of Link(s) + self.exc_handler = False # block at the start of exception handling code + def __str__(self): if self.operations: txt = "block@%d" % self.operations[0].offset else: txt = "codeless block" + if self.exc_handler: + txt = text +" EH" return txt def __repr__(self): @@ -150,7 +154,7 @@ class Constant: - def __init__(self, value): + def __init__(self, value, **flags): self.value = value # a concrete value # try to be smart about constant mutable or immutable values key = type(self.value), self.value # to avoid confusing e.g. 0 and 0.0 @@ -159,7 +163,11 @@ except TypeError: key = id(self.value) self.key = key - + if not flags: + self.flags = None + else: + self.flags = flags + def __eq__(self, other): return self.__class__ is other.__class__ and self.key == other.key @@ -169,6 +177,9 @@ def __hash__(self): return hash(self.key) + def has_flag(self, flag_name): + return self.flags and flag_name in self.flags + def __repr__(self): # try to limit the size of the repr to make it more readable r = repr(self.value) @@ -177,7 +188,12 @@ r = '%s %s' % (type(self.value).__name__, self.value.__name__) elif len(r) > 60 or (len(r) > 30 and type(self.value) is not str): r = r[:20] + '...' + r[-8:] - return '(%s)' % r + if self.flags: + flags = ' '.join([':'+f for f in self.flags.keys()]) + flags = ' '+flags + else: + flags = '' + return '(%s%s)' % (r, flags) # hack! it is useful to have UNDEFINED be an instance of Constant too. # PyFrame then automatically uses this Constant as a marker for Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Fri Feb 25 16:38:27 2005 @@ -164,6 +164,11 @@ from pypy.objspace.flow import specialcase specialcase.setup(self) + def exception_match(self, w_exc_type, w_check_class): + self.executioncontext.crnt_block.exc_handler = True + return ObjSpace.exception_match(self, w_exc_type, w_check_class) + + def build_flow(self, func, constargs={}): """ """ @@ -322,7 +327,7 @@ # one specified by 'outcome', and not a subclass of it, # unless 'outcome' is Exception. if outcome is not Exception: - w_exc_cls = Constant(outcome) + w_exc_cls = Constant(outcome, last_exception=True) raise OperationError(w_exc_cls, w_exc_value) # ______________________________________________________________________ Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Fri Feb 25 16:38:27 2005 @@ -10,7 +10,6 @@ from pypy.objspace.flow.model import SpaceOperation, FunctionGraph from pypy.objspace.flow.model import last_exception, last_exc_value - class AnnotatorError(Exception): pass @@ -217,7 +216,8 @@ if graph.hasonlyexceptionreturns(): # XXX for functions with exceptions what to # do anyway? - return self.bookkeeper.immutablevalue(None) + #return self.bookkeeper.immutablevalue(None) + return annmodel.SomeImpossibleValue(benign=True) return annmodel.SomeImpossibleValue() def reflowfromposition(self, position_key): @@ -354,19 +354,32 @@ and issubclass(link.exitcase, Exception): last_exception_object = annmodel.SomeObject() last_exc_value_object = annmodel.SomeObject() - last_exc_value_vars = last_exception_object.is_type_of = [] + last_exc_value_vars = [] in_except_block = True + last_exception_unknown = True + last_exception_unused = True cells = [] renaming = dict(zip(link.args,link.target.inputargs)) for a,v in zip(link.args,link.target.inputargs): if a == Constant(last_exception): assert in_except_block + assert last_exception_unknown cells.append(last_exception_object) + last_exception_unused = False elif a == Constant(last_exc_value): assert in_except_block cells.append(last_exc_value_object) last_exc_value_vars.append(v) + elif isinstance(a, Constant) and a.has_flag('last_exception'): + assert in_except_block + assert last_exception_unused + if last_exception_unknown: + cell = last_exception_object = self.bookkeeper.immutablevalue(a.value) + else: + cell = last_exception_object + cells.append(cell) + last_exception_unknown = False else: cell = self.binding(a) if link.exitcase is True and knownvars is not None and a in knownvars \ @@ -382,6 +395,9 @@ cell.is_type_of = renamed_is_type_of cells.append(cell) + if in_except_block: + last_exception_object.is_type_of = last_exc_value_vars + self.addpendingblock(fn, link.target, cells) if block in self.notify: # reflow from certain positions when this block is done Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Fri Feb 25 16:38:27 2005 @@ -729,6 +729,10 @@ def m(self): return 1 +class Exc4(Exc3): + def m(self): + return 1 + class Sp: def o(self): raise Exc3 @@ -745,11 +749,33 @@ return e.m() return 0 +class Mod3: + def __init__(self, s): + self.s = s + + def p(self): + s = self.s + try: + s.o() + except Exc4, e1: + return e1.m() + except Exc3, e2: + try: + return e2.m() + except Exc4, e3: + return e3.m() + return 0 + + mod = Mod(Sp()) +mod3 = Mod3(Sp()) def exc_deduction_our_exc_plus_others(): return mod.p() +def exc_deduction_our_excs_plus_others(): + return mod3.p() + class BltinCode: def __init__(self, func, framecls): Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Fri Feb 25 16:38:27 2005 @@ -115,12 +115,10 @@ assert s.knowntype == int def test_lists(self): - fun = self.make_fun(snippet.poor_man_rev_range) a = RPythonAnnotator() - a.build_types(fun, [int]) + end_cell = a.build_types(snippet.poor_man_rev_range, [int]) # result should be a list of integers - assert a.gettype(fun.getreturnvar()) == list - end_cell = a.binding(fun.getreturnvar()) + assert end_cell.knowntype == list assert end_cell.s_item.knowntype == int def test_factorial(self): @@ -489,6 +487,11 @@ s = a.build_types(snippet.exc_deduction_our_exc_plus_others, []) assert isinstance(s, annmodel.SomeInteger) + def test_exc_deduction_our_excs_plus_others(self): + a = RPythonAnnotator() + s = a.build_types(snippet.exc_deduction_our_excs_plus_others, []) + assert isinstance(s, annmodel.SomeInteger) + def test_slice_union(self): a = RPythonAnnotator() s = a.build_types(snippet.slice_union, [int]) Modified: pypy/dist/pypy/translator/test/test_pyrextrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_pyrextrans.py (original) +++ pypy/dist/pypy/translator/test/test_pyrextrans.py Fri Feb 25 16:38:27 2005 @@ -108,8 +108,7 @@ class TestTypedTestCase: def getcompiled(self, func): - t = Translator(func) - t.simplify() + t = Translator(func, simplifying=True) # builds starting-types from func_defs argstypelist = [] if func.func_defaults: Modified: pypy/dist/pypy/translator/tool/make_dot.py ============================================================================== --- pypy/dist/pypy/translator/tool/make_dot.py (original) +++ pypy/dist/pypy/translator/tool/make_dot.py Fri Feb 25 16:38:27 2005 @@ -137,7 +137,11 @@ shape = "octagon" iargs = " ".join(map(repr, block.inputargs)) - data = "%s(%s)\\ninputargs: %s\\n\\n" % (name, block.__class__.__name__, iargs) + if block.exc_handler: + eh = 'EH' + else: + eh = '' + data = "%s(%s %s)\\ninputargs: %s\\n\\n" % (name, block.__class__.__name__, eh, iargs) if block.operations and self.func: maxoffs = max([op.offset for op in block.operations]) if maxoffs >= 0: From pedronis at codespeak.net Fri Feb 25 16:52:45 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 25 Feb 2005 16:52:45 +0100 (MET) Subject: [pypy-svn] r9503 - pypy/dist/pypy/objspace/flow Message-ID: <20050225155245.115D927B3D@code1.codespeak.net> Author: pedronis Date: Fri Feb 25 16:52:44 2005 New Revision: 9503 Modified: pypy/dist/pypy/objspace/flow/model.py Log: oops, typo Modified: pypy/dist/pypy/objspace/flow/model.py ============================================================================== --- pypy/dist/pypy/objspace/flow/model.py (original) +++ pypy/dist/pypy/objspace/flow/model.py Fri Feb 25 16:52:44 2005 @@ -75,7 +75,7 @@ else: txt = "codeless block" if self.exc_handler: - txt = text +" EH" + txt = txt +" EH" return txt def __repr__(self): From sanxiyn at codespeak.net Fri Feb 25 17:14:24 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Fri, 25 Feb 2005 17:14:24 +0100 (MET) Subject: [pypy-svn] r9504 - pypy/dist/pypy/translator/llvm/test Message-ID: <20050225161424.E5F7127B3D@code1.codespeak.net> Author: sanxiyn Date: Fri Feb 25 17:14:24 2005 New Revision: 9504 Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py Log: Adjust LLVM test for r9502 changes Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/test_genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Fri Feb 25 17:14:24 2005 @@ -14,9 +14,8 @@ mod.llvm_found = is_on_path("llvm-as") def compile_function(function, annotate): - t = Translator(function) + t = Translator(function, simplifying=True) a = t.annotate(annotate) - t.simplify() gen = LLVMGenerator(t) return gen.compile() From sanxiyn at codespeak.net Fri Feb 25 17:17:19 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Fri, 25 Feb 2005 17:17:19 +0100 (MET) Subject: [pypy-svn] r9505 - in pypy/dist/pypy/translator: . test Message-ID: <20050225161719.ED83527B40@code1.codespeak.net> Author: sanxiyn Date: Fri Feb 25 17:17:19 2005 New Revision: 9505 Modified: pypy/dist/pypy/translator/annrpython.py pypy/dist/pypy/translator/gencl.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_cltrans.py Log: "x in y" for GenCL. * Translate to CL's "find" * Represent tuple as cons * Annotate "x in y" as SomeBool * Tests Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Fri Feb 25 17:17:19 2005 @@ -440,6 +440,10 @@ _registeroperations(locals()) del _registeroperations + # XXX "contains" clash with SomeObject method + def consider_op_contains(self, seq, elem): + return annmodel.SomeBool() + def consider_op_newtuple(self, *args): return annmodel.SomeTuple(items = args) Modified: pypy/dist/pypy/translator/gencl.py ============================================================================== --- pypy/dist/pypy/translator/gencl.py (original) +++ pypy/dist/pypy/translator/gencl.py Fri Feb 25 17:17:19 2005 @@ -54,6 +54,10 @@ result, (arg1, arg2) = self.result, self.args cl_op = self.binary_ops[op] print "(setq", s(result), "(", cl_op, s(arg1), s(arg2), "))" + def op_contains(self): + s = self.str + result, (arg1, arg2) = self.result, self.args + print "(setq", s(result), "(not (not (find", s(arg2), s(arg1), "))))" def op_add(self): s = self.str result, (arg1, arg2) = self.result, self.args @@ -171,7 +175,10 @@ else: return "#<%r>" % (obj,) def conv(self, val): - if isinstance(val, bool): # should precedes int + if isinstance(val, tuple): + val = map(self.conv, val) + return "'(%s)" % ' '.join(val) + elif isinstance(val, bool): # should precedes int if val: return "t" else: Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Fri Feb 25 17:17:19 2005 @@ -40,6 +40,9 @@ def my_contains(seq=seqtype, elem=anytype): return elem in seq +def is_one_or_two(n=int): + return n in (1, 2) + def two_plus_two(): """Array test""" array = [0] * 3 Modified: pypy/dist/pypy/translator/test/test_cltrans.py ============================================================================== --- pypy/dist/pypy/translator/test/test_cltrans.py (original) +++ pypy/dist/pypy/translator/test/test_cltrans.py Fri Feb 25 17:17:19 2005 @@ -66,6 +66,14 @@ assert cl_bool(42) == True assert cl_bool(True) == True + def test_contains(self): + my_contains = make_cl_func(t.my_contains) + assert my_contains([1, 2, 3], 1) + assert not my_contains([1, 2, 3], 0) + is_one_or_two = make_cl_func(t.is_one_or_two) + assert is_one_or_two(2) + assert not is_one_or_two(3) + def test_array(self): cl_four = make_cl_func(t.two_plus_two) assert cl_four() == 4 From pedronis at codespeak.net Fri Feb 25 18:22:25 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 25 Feb 2005 18:22:25 +0100 (MET) Subject: [pypy-svn] r9506 - in pypy/dist/pypy: annotation translator Message-ID: <20050225172225.46C7B27B3D@code1.codespeak.net> Author: pedronis Date: Fri Feb 25 18:22:25 2005 New Revision: 9506 Modified: pypy/dist/pypy/annotation/binaryop.py pypy/dist/pypy/translator/annrpython.py Log: pbc are cached singletons, don't attach local info to them Modified: pypy/dist/pypy/annotation/binaryop.py ============================================================================== --- pypy/dist/pypy/annotation/binaryop.py (original) +++ pypy/dist/pypy/annotation/binaryop.py Fri Feb 25 18:22:25 2005 @@ -297,10 +297,6 @@ classdef = classdef.commonbase(d[x]) d[x] = classdef result = SomePBC(d) - is_type_of1 = getattr(pbc1, 'is_type_of', None) - is_type_of2 = getattr(pbc2, 'is_type_of', None) - if is_type_of1 and is_type_of1 == is_type_of2: - result.is_type_of = is_type_of1 return result class __extend__(pairtype(SomeImpossibleValue, SomeImpossibleValue)): Modified: pypy/dist/pypy/translator/annrpython.py ============================================================================== --- pypy/dist/pypy/translator/annrpython.py (original) +++ pypy/dist/pypy/translator/annrpython.py Fri Feb 25 18:22:25 2005 @@ -375,9 +375,10 @@ assert in_except_block assert last_exception_unused if last_exception_unknown: - cell = last_exception_object = self.bookkeeper.immutablevalue(a.value) - else: - cell = last_exception_object + # this modeling should be good enough + # the exc type is not seen by user code + last_exception_object.const = a.value + cell = last_exception_object cells.append(cell) last_exception_unknown = False else: From pedronis at codespeak.net Fri Feb 25 19:21:07 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Fri, 25 Feb 2005 19:21:07 +0100 (MET) Subject: [pypy-svn] r9513 - pypy/dist/pypy/translator/test Message-ID: <20050225182107.C9C3827B3D@code1.codespeak.net> Author: pedronis Date: Fri Feb 25 19:21:07 2005 New Revision: 9513 Added: pypy/dist/pypy/translator/test/test_annmm.py (contents, props changed) Log: simple tests about annotating std objspace mms (notice that without the changes on how we deal with functions only raising exceptions and not returning), these would fail. Added: pypy/dist/pypy/translator/test/test_annmm.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/test/test_annmm.py Fri Feb 25 19:21:07 2005 @@ -0,0 +1,58 @@ +import autopath + +from pypy.objspace.std.multimethod import * +from pypy.translator.annrpython import RPythonAnnotator + +class W_Root(object): + pass + +class W_Int(W_Root): + pass + +class W_Str(W_Root): + pass + + +str_w = MultiMethodTable(1, root_class=W_Root, argnames_before=['space']) +int_w = MultiMethodTable(1, root_class=W_Root, argnames_before=['space']) + + +def int_w__Int(space, w_x): + assert space == 'space' + assert isinstance(w_x, W_Int) + return 1 + +def str_w__Str(space, w_x): + assert space == 'space' + assert isinstance(w_x, W_Str) + return "string" + +int_w.register(int_w__Int, W_Int) +str_w.register(str_w__Str, W_Str) + + +def setup_module(mod): + typeorder = { + W_Int: [(W_Int, None)], + W_Str: [(W_Str, None)], + } + mod.typeorder = typeorder + mod.str_w1 = str_w.install('__str_w', [typeorder]) + mod.int_w1 = int_w.install('__int_w', [typeorder]) + + +def test_str_w_ann(): + a = RPythonAnnotator() + s1 = a.build_types(str_w1,[str, W_Str]) + s2 = a.build_types(str_w1,[str, W_Root]) + assert s1.knowntype == str + assert s2.knowntype == str + +def test_int_w_ann(): + a = RPythonAnnotator() + s1 = a.build_types(int_w1,[str, W_Int]) + s2 = a.build_types(int_w1,[str, W_Str]) + assert s1.knowntype == int + assert s2.knowntype == int + + From cfbolz at codespeak.net Fri Feb 25 19:25:17 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Fri, 25 Feb 2005 19:25:17 +0100 (MET) Subject: [pypy-svn] r9514 - in pypy/dist/pypy/translator/llvm: . test Message-ID: <20050225182517.24AC627B3D@code1.codespeak.net> Author: cfbolz Date: Fri Feb 25 19:25:16 2005 New Revision: 9514 Added: pypy/dist/pypy/translator/llvm/make_runtime.py (contents, props changed) Modified: pypy/dist/pypy/translator/llvm/genllvm.py pypy/dist/pypy/translator/llvm/list.c pypy/dist/pypy/translator/llvm/list_template.ll pypy/dist/pypy/translator/llvm/llvmbc.py pypy/dist/pypy/translator/llvm/representation.py pypy/dist/pypy/translator/llvm/test/llvmsnippet.py pypy/dist/pypy/translator/llvm/test/test_genllvm.py Log: Added support for some builtin functions/methods like len, list.reverse, list.append. Modified: pypy/dist/pypy/translator/llvm/genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/genllvm.py Fri Feb 25 19:25:16 2005 @@ -15,12 +15,13 @@ from pypy.translator.llvm import llvmbc from pypy.translator.llvm import build_llvm_module from pypy.translator.test import snippet as test +from pypy.translator.llvm.test import llvmsnippet as test2 from pypy.translator.llvm.representation import * -debug = 1 +debug = 0 def llvmcompile(transl, optimize=False): @@ -41,7 +42,6 @@ def __init__(self, transl): self.translator = transl self.annotator = self.translator.annotator -## transform.transform_allocate(self.annotator) self.global_counts = {} self.local_counts = {} self.repr_classes = [eval(s) @@ -49,12 +49,8 @@ if "Repr" in s] self.llvm_reprs = {} self.depth = 0 - try: - self.l_entrypoint = self.get_repr( - Constant(self.translator.functions[0])) - except: -## self.translator.view() - raise + self.l_entrypoint = self.get_repr( + Constant(self.translator.functions[0])) def compile(self, optimize=False): from pypy.tool.udir import udir @@ -80,9 +76,10 @@ self.global_counts[used_by] = 0 return "%%glb.%s" % used_by - def get_local_tmp(self, l_repr): - self.local_counts[l_repr] += 1 - return "%%tmp_%i" % self.local_counts[l_repr] + def get_local_tmp(self, type, l_function): + self.local_counts[l_function] += 1 + return TmpVariableRepr("tmp_%i" % self.local_counts[l_function], type, + self) def get_repr(self, obj): self.depth += 1 Modified: pypy/dist/pypy/translator/llvm/list.c ============================================================================== --- pypy/dist/pypy/translator/llvm/list.c (original) +++ pypy/dist/pypy/translator/llvm/list.c Fri Feb 25 19:25:16 2005 @@ -18,6 +18,10 @@ } } +int len(struct list* l) { + return (int) l->length; +} + struct list* newlist(struct item* value) { struct list* nlist = malloc(sizeof(struct list)); nlist->length = 1; @@ -26,10 +30,10 @@ return nlist; } -struct list* alloc_and_set(unsigned int length, struct item* init) { +struct list* alloc_and_set(int length, struct item* init) { unsigned int i = 0; struct list* nlist = malloc(sizeof(struct list)); - nlist->length = length; + nlist->length = (unsigned int)length; nlist->data = malloc(sizeof(struct item*) * length); while (i < length) { nlist->data[i] = init; @@ -82,11 +86,24 @@ a->data = newdata; } -struct list* append(struct list* a, struct item* value) { +void append(struct list* a, struct item* value) { struct item** newdata = malloc(sizeof(struct item*) * (a->length + 1)); + newdata[a->length] = value; copy(a->data, newdata, a->length); a->length += 1; free(a->data); a->data = newdata; - return a; +} + +void reverse(struct list* a) { + unsigned int lo = 0; + unsigned int hi = a->length - 1; + struct item* temp; + while (lo < hi) { + temp = a->data[lo]; + a->data[lo] = a->data[hi]; + a->data[hi] = temp; + lo += 1; + hi -= 1; + } } Modified: pypy/dist/pypy/translator/llvm/list_template.ll ============================================================================== --- pypy/dist/pypy/translator/llvm/list_template.ll (original) +++ pypy/dist/pypy/translator/llvm/list_template.ll Fri Feb 25 19:25:16 2005 @@ -1,4 +1,6 @@ -internal void %copy(%(item)s* %from, %(item)s* %to, uint %length) { + + +internal void %std.copy(%(item)s* %from, %(item)s* %to, uint %length) { entry: %tmp.25 = seteq uint %length, 0 br bool %tmp.25, label %return, label %no_exit @@ -17,6 +19,14 @@ ret void } +internal int %std.len(%std.list.%(name)s* %l) { +entry: + %tmp.1 = getelementptr %std.list.%(name)s* %l, int 0, uint 0 + %tmp.2 = load uint* %tmp.1 + %tmp.3 = cast uint %tmp.2 to int + ret int %tmp.3 +} + internal %std.list.%(name)s* %std.newlist(%(item)s %value) { entry: %tmp.0 = malloc %std.list.%(name)s @@ -29,37 +39,31 @@ ret %std.list.%(name)s* %tmp.0 } -internal %std.list.%(name)s* %std.alloc_and_set(uint %length, %(item)s %init) { +internal %std.list.%(name)s* %std.alloc_and_set(int %length, %(item)s %init) { entry: %tmp.0 = malloc %std.list.%(name)s %tmp.3 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 0 - store uint %length, uint* %tmp.3 - %tmp.6 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 1 - %tmp.7 = malloc %(item)s, uint %length - store %(item)s* %tmp.7, %(item)s** %tmp.6 - %tmp.134 = seteq uint %length, 0 - br bool %tmp.134, label %loopexit, label %no_exit + %tmp.5 = cast int %length to uint + store uint %tmp.5, uint* %tmp.3 + %tmp.7 = getelementptr %std.list.%(name)s* %tmp.0, int 0, uint 1 + %tmp.8 = malloc %(item)s, uint %tmp.5 + store %(item)s* %tmp.8, %(item)s** %tmp.7 + %tmp.165 = seteq int %length, 0 + br bool %tmp.165, label %loopexit, label %no_exit no_exit: - %i.0.0 = phi uint [ %tmp.23, %no_exit ], [ 0, %entry ] - %tmp.17 = load %(item)s** %tmp.6 - %tmp.20 = getelementptr %(item)s* %tmp.17, uint %i.0.0 - store %(item)s %init, %(item)s* %tmp.20 - %tmp.23 = add uint %i.0.0, 1 - %tmp.13 = setlt uint %tmp.23, %length - br bool %tmp.13, label %no_exit, label %loopexit + %i.0.0 = phi uint [ %tmp.26, %no_exit ], [ 0, %entry ] + %tmp.20 = load %(item)s** %tmp.7 + %tmp.23 = getelementptr %(item)s* %tmp.20, uint %i.0.0 + store %(item)s %init, %(item)s* %tmp.23 + %tmp.26 = add uint %i.0.0, 1 + %tmp.16 = setgt uint %tmp.5, %tmp.26 + br bool %tmp.16, label %no_exit, label %loopexit loopexit: ret %std.list.%(name)s* %tmp.0 } -internal %std.list.%(name)s* %std.alloc_and_set(int %length, %(item)s %init) { -entry: - %ul = cast int %length to uint - %r = call %std.list.%(name)s* %std.alloc_and_set(uint %ul, %(item)s %init) - ret %std.list.%(name)s* %r -} - internal %(item)s %std.getitem(%std.list.%(name)s* %l, int %index.1) { entry: %tmp.1 = setlt int %index.1, 0 @@ -156,8 +160,6 @@ ret %std.list.%(name)s* %tmp.0 } - - internal %std.list.%(name)s* %std.mul(%std.list.%(name)s* %a, int %times) { entry: %tmp.0 = malloc %std.list.%(name)s @@ -182,7 +184,7 @@ %i.0.0 = cast uint %indvar to int %tmp.23 = load %(item)s** %tmp.22 %tmp.26 = load %(item)s** %tmp.12 - %tmp.29 = load uint* %tmp.3 + %tmp.29 = load uint* %tmp.3 %tmp.32 = mul uint %indvar, %tmp.29 %tmp.2.i9 = seteq uint %tmp.29, 0 br bool %tmp.2.i9, label %copy.entry, label %no_exit.i @@ -191,7 +193,7 @@ %i.0.i.2 = phi uint [ %tmp.14.i, %no_exit.i ], [ 0, %no_exit ] %tmp.34.sum = add uint %i.0.i.2, %tmp.32 %tmp.7.i = getelementptr %(item)s* %tmp.26, uint %tmp.34.sum - %tmp.11.i = getelementptr %(item)s* %tmp.23, uint %i.0.i.2 + %tmp.11.i = getelementptr %(item)s* %tmp.23, uint %i.0.i.2 %tmp.12.i = load %(item)s* %tmp.11.i store %(item)s %tmp.12.i, %(item)s* %tmp.7.i %tmp.14.i = add uint %i.0.i.2, 1 @@ -238,7 +240,7 @@ br bool %tmp.2.i319, label %copy.entry9, label %no_exit.i4 no_exit.i4: - %i.0.i2.0 = phi uint [ %tmp.14.i8, %no_exit.i4 ], [ 0, %copy.entry ] + %i.0.i2.0 = phi uint [ %tmp.14.i8, %no_exit.i4 ], [ 0, %copy.entry ] %tmp.25.sum = add uint %i.0.i2.0, %tmp.3 %tmp.7.i5 = getelementptr %(item)s* %tmp.0, uint %tmp.25.sum %tmp.11.i6 = getelementptr %(item)s* %tmp.19, uint %i.0.i2.0 @@ -255,21 +257,23 @@ ret void } -internal %std.list.%(name)s* %std.append(%std.list.%(name)s* %a, %(item)s %value) { +internal void %std.append(%std.list.%(name)s* %a, %(item)s %value) { entry: %tmp.2 = getelementptr %std.list.%(name)s* %a, int 0, uint 0 %tmp.3 = load uint* %tmp.2 %tmp.3-off = add uint %tmp.3, 1 %tmp.0 = malloc %(item)s, uint %tmp.3-off - %tmp.8 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 - %tmp.9 = load %(item)s** %tmp.8 + %tmp.12 = getelementptr %(item)s* %tmp.0, uint %tmp.3 + store %(item)s %value, %(item)s* %tmp.12 + %tmp.15 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 + %tmp.16 = load %(item)s** %tmp.15 %tmp.2.i5 = seteq uint %tmp.3, 0 br bool %tmp.2.i5, label %copy.entry, label %no_exit.i no_exit.i: %i.0.i.0 = phi uint [ %tmp.14.i, %no_exit.i ], [ 0, %entry ] %tmp.7.i = getelementptr %(item)s* %tmp.0, uint %i.0.i.0 - %tmp.11.i = getelementptr %(item)s* %tmp.9, uint %i.0.i.0 + %tmp.11.i = getelementptr %(item)s* %tmp.16, uint %i.0.i.0 %tmp.12.i = load %(item)s* %tmp.11.i store %(item)s %tmp.12.i, %(item)s* %tmp.7.i %tmp.14.i = add uint %i.0.i.0, 1 @@ -278,7 +282,40 @@ copy.entry: store uint %tmp.3-off, uint* %tmp.2 - free %(item)s* %tmp.9 - store %(item)s* %tmp.0, %(item)s** %tmp.8 - ret %std.list.%(name)s* %a + free %(item)s* %tmp.16 + store %(item)s* %tmp.0, %(item)s** %tmp.15 + ret void +} + +internal void %std.reverse(%std.list.%(name)s* %a) { +entry: + %tmp.1 = getelementptr %std.list.%(name)s* %a, int 0, uint 0 + %tmp.2 = load uint* %tmp.1 + %tmp.610 = seteq uint %tmp.2, 1 + br bool %tmp.610, label %return, label %no_exit.preheader + +no_exit.preheader: + %tmp.9 = getelementptr %std.list.%(name)s* %a, int 0, uint 1 + br label %no_exit + +no_exit: + %lo.0.0 = phi uint [ 0, %no_exit.preheader ], [ %tmp.36, %no_exit ] + %tmp. = add uint %tmp.2, 4294967295 + %hi.0.0 = sub uint %tmp., %lo.0.0 + %tmp.10 = load %(item)s** %tmp.9 + %tmp.13 = getelementptr %(item)s* %tmp.10, uint %lo.0.0 + %tmp.14 = load %(item)s* %tmp.13 + %tmp.26 = getelementptr %(item)s* %tmp.10, uint %hi.0.0 + %tmp.27 = load %(item)s* %tmp.26 + store %(item)s %tmp.27, %(item)s* %tmp.13 + %tmp.30 = load %(item)s** %tmp.9 + %tmp.33 = getelementptr %(item)s* %tmp.30, uint %hi.0.0 + store %(item)s %tmp.14, %(item)s* %tmp.33 + %tmp.36 = add uint %lo.0.0, 1 + %hi.0 = add uint %hi.0.0, 4294967295 + %tmp.6 = setlt uint %tmp.36, %hi.0 + br bool %tmp.6, label %no_exit, label %return + +return: + ret void } Modified: pypy/dist/pypy/translator/llvm/llvmbc.py ============================================================================== --- pypy/dist/pypy/translator/llvm/llvmbc.py (original) +++ pypy/dist/pypy/translator/llvm/llvmbc.py Fri Feb 25 19:25:16 2005 @@ -59,11 +59,12 @@ def call(self, l_target, l_func, l_args): if l_target.llvmtype() == "void": - s = "call void %%std.%s(" % opname + s = "call void %s(" % l_func.llvmname() elif l_target.llvmtype() == "%std.void": - s = "call %std.void %%std.%s(" % opname - s = "%s = call %s %s(" % (l_target.llvmname(), l_func.rettype(), - l_func.llvmname()) + s = "call %std.void %s(" % l_func.llvmname() + else: + s = "%s = call %s %s(" % (l_target.llvmname(), l_target.llvmtype(), + l_func.llvmname()) self.instructions.append(s + ", ".join([a.typed_name() for a in l_args]) + ")") @@ -90,9 +91,9 @@ s += ", uint %i" % num self.instructions.append(s) - def getelementptr(self, target, l_ptr, adresses): - s = "%s = getelementptr %s %s, " % (target, l_ptr.llvmtype(), - l_ptr.llvmname()) + def getelementptr(self, l_target, l_ptr, adresses): + s = "%s = getelementptr %s %s, " % (l_target.llvmname(), + l_ptr.llvmtype(), l_ptr.llvmname()) adr = [] for a in adresses: if a >= 0: @@ -101,14 +102,14 @@ adr.append("int %i" % a) self.instructions.append(s + ", ".join(adr)) - def load(self, l_target, pter): - s = "%s = load %s* %s" % (l_target.llvmname(), l_target.llvmtype(), - pter) + def load(self, l_target, l_pter): + s = "%s = load %s %s" % (l_target.llvmname(), l_pter.llvmtype(), + l_pter.llvmname()) self.instructions.append(s) - def store(self, l_value, pter): - s = "store %s %s, %s* %s" % (l_value.llvmtype(), l_value.llvmname(), - l_value.llvmtype(), pter) + def store(self, l_value, l_pter): + s = "store %s %s, %s %s" % (l_value.llvmtype(), l_value.llvmname(), + l_pter.llvmtype(), l_pter.llvmname()) self.instructions.append(s) Added: pypy/dist/pypy/translator/llvm/make_runtime.py ============================================================================== --- (empty file) +++ pypy/dist/pypy/translator/llvm/make_runtime.py Fri Feb 25 19:25:16 2005 @@ -0,0 +1,91 @@ +import autopath + +import os +from pypy.tool.udir import udir +from py.process import cmdexec +from py import path + +def get_llvm_code(cfile): + include_dir = autopath.this_dir + print "include_dir", include_dir + cfile = include_dir + "/" + cfile + print cfile + bytecode = udir.join("temp.bc") + lastdir = path.local() + ops = ["llvm-gcc -c %s -o %s" % (cfile, bytecode), + "llvm-dis %s -f" % bytecode] + for op in ops: + print op + cmdexec(op) + f = udir.join("temp.ll").open("r") + return f.read() + +def remove_comments(code): + ret = [] + for line in code.split("\n"): + line = line.split(";") + ret.append(line[0].rstrip()) + return "\n".join(ret) + +def add_std(code): + with_std = [] + functions = [] + for line in code.split("\n"): + if "{" in line and "(" in line and ")" in line: + s1 = line.split("(") + s2 = s1[0].split("%") + functions.append(s2[-1]) + s2[-1] = "std." + s2[-1] + s2 = "%".join(s2) + s1[0] = s2 + with_std.append("(".join(s1)) + else: + with_std.append(line) + ret = [] + for line in with_std: + if "call" in line: + for f in functions: + if f in line: + line = line.replace(f, "std." + f) + ret.append(line) + continue + else: + ret.append(line) + return "\n".join(ret) + +def remove_alternatives(code): + for i in range(1, 10): + code = code.replace("_ALTERNATIVE%i" % i, "") + return code + +def remove_header(code): + code = code.split("implementation") + return code[1] + +def internal_functions(code): + ret = [] + for line in code.split("\n"): + if "{" in line and "(" in line and ")" in line: + ret.append("internal " + line) + else: + ret.append(line) + return "\n".join(ret) + +def make_list_template(): + code = get_llvm_code("list.c") + code = remove_comments(code) + code = add_std(code) + code = remove_header(code) + code = internal_functions(code) + code = remove_alternatives(code) + code = code.replace("%struct.list", "%std.list.%(name)s") + code = code.replace("%struct.item*", "%(item)s") + f = open(autopath.this_dir + "/list_template.ll", "w") + print (autopath.this_dir + "/list_template.ll") + f.write(code) + f.close() + + +if __name__ == '__main__': + make_list_template() + Modified: pypy/dist/pypy/translator/llvm/representation.py ============================================================================== --- pypy/dist/pypy/translator/llvm/representation.py (original) +++ pypy/dist/pypy/translator/llvm/representation.py Fri Feb 25 19:25:16 2005 @@ -27,7 +27,7 @@ annmodel.SomeInteger: "int"} -debug = 1 +debug = 0 class CompileError(exceptions.Exception): @@ -129,6 +129,19 @@ else: raise AttributeError, ("VariableRepr instance has no attribute %s" % repr(name)) +class TmpVariableRepr(LLVMRepr): + def __init__(self, name, type, gen): + if debug: + print "TmpVariableRepr: %s %s" % (type, name) + self.name = name + self.type = type + self.dependencies = sets.Set() + + def llvmname(self): + return "%" + self.name + + def llvmtype(self): + return self.type class StringRepr(LLVMRepr): def get(obj, gen): @@ -253,7 +266,17 @@ l_args = [self.gen.get_repr(arg) for arg in args] l_func.dependencies.update(l_args) lblock.spaceop(l_target, "delitem", l_args) - + + def t_op_getattr(self, l_target, args, lblock, l_func): + if isinstance(args[1], Constant) and \ + args[1].value in ["append", "reverse"]: + l_args0 = self.gen.get_repr(args[0]) + l_func.dependencies.add(l_args0) + l_method = BoundMethodRepr(l_target.type, l_args0, self, self.gen) + l_method.setup() + l_target.type = l_method + else: + raise CompileError, "List method %s not supported." % args[1].value class SimpleTypeRepr(TypeRepr): def get(obj, gen): @@ -336,26 +359,31 @@ def setup(self): self.se = True - print "ClassRepr.setup()", id(self) + if debug: + print "ClassRepr.setup()", id(self) gen = self.gen attribs = [] meth = [] - print "attributes" + if debug: + print "attributes" for key, attr in self.classdef.attrs.iteritems(): - print key, attr, attr.sources, attr.s_value, + if debug: + print key, attr, attr.sources, attr.s_value, if len(attr.sources) != 0: func = self.classdef.cls.__dict__[attr.name] meth.append((key, func)) - print "--> method" - continue - if isinstance(attr.s_value, annmodel.SomePBC) and \ + if debug: + print "--> method" + elif isinstance(attr.s_value, annmodel.SomePBC) and \ attr.s_value.knowntype is FunctionType: func = self.classdef.cls.__dict__[attr.name] meth.append((key, func)) - print "--> method" - continue - attribs.append(attr) - print "--> value" + if debug: + print "--> method" + else: + attribs.append(attr) + if debug: + print "--> value" self.l_attrs_types = [gen.get_repr(attr.s_value) for attr in attribs] self.dependencies = sets.Set(self.l_attrs_types) attributes = ", ".join([at.llvmname() for at in self.l_attrs_types]) @@ -364,7 +392,6 @@ for i, attr in enumerate(attribs): self.attr_num[attr.name] = i + 1 self.methods = dict(meth) - print "setup: ", self, self.attr_num, self.methods def op_simple_call(self, l_target, args, lblock, l_func): l_init = self.gen.get_repr(self.methods["__init__"]) @@ -381,17 +408,15 @@ if args[1].value in self.attr_num: l_args0 = self.gen.get_repr(args[0]) l_func.dependencies.add(l_args0) - pter = self.gen.get_local_tmp(l_func) - lblock.getelementptr(pter, l_args0, + l_pter = self.gen.get_local_tmp(l_target.llvmtype() + "*", l_func) + lblock.getelementptr(l_pter, l_args0, [0, self.attr_num[args[1].value]]) - lblock.load(l_target, pter) + lblock.load(l_target, l_pter) elif args[1].value in self.methods: - print "method", l_args0 = self.gen.get_repr(args[0]) - print l_args0, l_args0.typed_name() l_func.dependencies.add(l_args0) - l_method = BoundMethodRepr(self.methods[args[1].value], - l_args0, self, self.gen) + l_method = BoundMethodRepr(l_target.type, l_args0, self, self.gen) + l_method.setup() l_target.type = l_method def t_op_setattr(self, l_target, args, lblock, l_func): @@ -401,28 +426,35 @@ l_args0 = self.gen.get_repr(args[0]) l_value = self.gen.get_repr(args[2]) self.dependencies.update([l_args0, l_value]) - pter = self.gen.get_local_tmp(l_func) - lblock.getelementptr(pter, l_args0, + l_pter = self.gen.get_local_tmp(l_value.llvmtype() + "*", l_func) + lblock.getelementptr(l_pter, l_args0, [0, self.attr_num[args[1].value]]) - lblock.store(l_value, pter) + lblock.store(l_value, l_pter) class BuiltinFunctionRepr(LLVMRepr): def get(obj, gen): if isinstance(obj, Constant) and \ - type(obj.value).__name__ == 'builtin_function_or_method': - l_repr = BuiltinFunctionRepr(obj.value, gen) - return l_repr + isinstance(gen.annotator.binding(obj), annmodel.SomeBuiltin): + return BuiltinFunctionRepr(obj.value.__name__, gen) + elif isinstance(obj, annmodel.SomeBuiltin): + name = obj.analyser.__name__.replace("method_", "") + return BuiltinFunctionRepr(name, gen) return None get = staticmethod(get) - def __init__(self, bi, gen): - self.name = "%std." + bi.__name__ + def __init__(self, name, gen): + self.name = "%std." + name self.gen = gen def llvmname(self): return self.name + def op_simple_call(self, l_target, args, lblock, l_func): + l_args = [self.gen.get_repr(arg) for arg in args] + l_func.dependencies.update(l_args) + lblock.call(l_target, l_args[0], l_args[1:]) + class FunctionRepr(LLVMRepr): def get(obj, gen): if isinstance(obj, Constant) and \ @@ -506,23 +538,23 @@ lblock.phi(l_arg, l_values, ["%%block%i" % self.blocknum[l.prevblock] for l in incoming_links]) - #Create a function call for every operation in the block + #Handle SpaceOperations for op in pyblock.operations: l_target = self.gen.get_repr(op.result) self.dependencies.add(l_target) - if op.opname in INTRINSIC_OPS: - l_args = [self.gen.get_repr(arg) for arg in op.args] + l_arg0 = self.gen.get_repr(op.args[0]) + self.dependencies.add(l_arg0) + l_op = getattr(l_arg0, "op_" + op.opname, None) + if l_op is not None: + l_op(l_target, op.args, lblock, self) + elif op.opname in INTRINSIC_OPS: + l_args = [self.gen.get_repr(arg) for arg in op.args[1:]] self.dependencies.update(l_args) - lblock.spaceop(l_target, op.opname, l_args) + lblock.spaceop(l_target, op.opname, [l_arg0] + l_args) else: - l_arg0 = self.gen.get_repr(op.args[0]) - self.dependencies.add(l_arg0) - l_op = getattr(l_arg0, "op_" + op.opname, None) - if l_op is None: s = "SpaceOperation %s not supported. Target: %s " \ "Args: %s" % (op.opname, l_target, op.args) raise CompileError, s - l_op(l_target, op.args, lblock, self) #Create branches if pyblock.exitswitch is None: if pyblock.exits == (): @@ -598,24 +630,17 @@ return None get = staticmethod(get) - def __init__(self, func, l_self, l_class, gen): + def __init__(self, l_func, l_self, l_class, gen): self.gen = gen - self.func = func + self.l_func = l_func self.l_self = l_self self.l_class = l_class - self.dependencies = sets.Set([l_self, l_class]) - self.se = False + self.dependencies = sets.Set([l_self, l_class, l_func]) def setup(self): - print "setup BoundMethodRepr" - self.se = True - self.l_func = self.gen.get_repr(self.func) - self.dependencies.add(self.l_func) - + pass def t_op_simple_call(self, l_target, args, lblock, l_func): - if not self.se: - self.setup() self.l_func.op_simple_call(l_target, [self.l_func, self.l_self] + args[1:], lblock, l_func) Modified: pypy/dist/pypy/translator/llvm/test/llvmsnippet.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/llvmsnippet.py (original) +++ pypy/dist/pypy/translator/llvm/test/llvmsnippet.py Fri Feb 25 19:25:16 2005 @@ -96,6 +96,21 @@ a = [i - 5] * 12 return callee(a) +def array_len(): + a = [1] * 10 + return len(a) + +def array_append(i): + a = [0] * 3 + a.append(10) + return a[i] + +def array_reverse(i): + a = [0] * 2 + a[1] = 1 + a.reverse() + return a[i] + #class snippets class A(object): Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/test_genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Fri Feb 25 19:25:16 2005 @@ -14,8 +14,9 @@ mod.llvm_found = is_on_path("llvm-as") def compile_function(function, annotate): - t = Translator(function, simplifying=True) + t = Translator(function) a = t.annotate(annotate) + t.simplify() gen = LLVMGenerator(t) return gen.compile() @@ -155,6 +156,22 @@ f = compile_function(llvmsnippet.array_arg, [int]) assert f(5) == 0 + def test_array_len(self): + f = compile_function(llvmsnippet.array_len, []) + assert f() == 10 + + def test_array_append(self): + f = compile_function(llvmsnippet.array_append, [int]) + for i in range(3): + assert f(i) == 0 + assert f(3) == 10 + + def test_array_reverse(self): + f = compile_function(llvmsnippet.array_reverse, [int]) + assert f(0) == 1 + assert f(1) == 0 + + class TestClass(object): def setup_method(self, method): @@ -204,7 +221,15 @@ assert f(10) == 1 assert f(1) == 1 assert f(0) == 0 - + + def test_two_plus_two(self): + f = compile_function(test.two_plus_two, []) + assert f() == 4 + + def test_sieve_of_eratosthenes(self): + f = compile_function(test.sieve_of_eratosthenes, []) + assert f() == 1028 + def test_while_func(self): while_func = compile_function(test.while_func, [int]) assert while_func(10) == 55 @@ -224,13 +249,5 @@ factorial = compile_function(test.factorial, [int]) assert factorial(5) == 120 - def test_two_plus_two(self): - f = compile_function(test.two_plus_two, []) - assert f() == 4 - - def test_sieve_of_eratosthenes(self): - f = compile_function(test.sieve_of_eratosthenes, []) - assert f() == 1028 - From cfbolz at codespeak.net Fri Feb 25 19:35:55 2005 From: cfbolz at codespeak.net (cfbolz at codespeak.net) Date: Fri, 25 Feb 2005 19:35:55 +0100 (MET) Subject: [pypy-svn] r9515 - pypy/dist/pypy/translator/llvm/test Message-ID: <20050225183555.2B53527B3D@code1.codespeak.net> Author: cfbolz Date: Fri Feb 25 19:35:54 2005 New Revision: 9515 Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py Log: Redid saxiyn's change Modified: pypy/dist/pypy/translator/llvm/test/test_genllvm.py ============================================================================== --- pypy/dist/pypy/translator/llvm/test/test_genllvm.py (original) +++ pypy/dist/pypy/translator/llvm/test/test_genllvm.py Fri Feb 25 19:35:54 2005 @@ -14,9 +14,8 @@ mod.llvm_found = is_on_path("llvm-as") def compile_function(function, annotate): - t = Translator(function) + t = Translator(function, simplifying=True) a = t.annotate(annotate) - t.simplify() gen = LLVMGenerator(t) return gen.compile() From jacob at codespeak.net Fri Feb 25 20:48:37 2005 From: jacob at codespeak.net (jacob at codespeak.net) Date: Fri, 25 Feb 2005 20:48:37 +0100 (MET) Subject: [pypy-svn] r9517 - pypy/funding/negotiations Message-ID: <20050225194837.3FE7927B3D@code1.codespeak.net> Author: jacob Date: Fri Feb 25 20:48:37 2005 New Revision: 9517 Modified: pypy/funding/negotiations/pypy-association-agreement.sxw Log: Association Agreement revised in accordance with suggestions from Stephan Busemann. 2.3 also reworded. Modified: pypy/funding/negotiations/pypy-association-agreement.sxw ============================================================================== Binary files. No diff available. From sanxiyn at codespeak.net Sat Feb 26 10:14:15 2005 From: sanxiyn at codespeak.net (sanxiyn at codespeak.net) Date: Sat, 26 Feb 2005 10:14:15 +0100 (MET) Subject: [pypy-svn] r9518 - pypy/dist/pypy/module/builtin Message-ID: <20050226091415.4003127B42@code1.codespeak.net> Author: sanxiyn Date: Sat Feb 26 10:14:14 2005 New Revision: 9518 Modified: pypy/dist/pypy/module/builtin/app_functional.py Log: 22compat Modified: pypy/dist/pypy/module/builtin/app_functional.py ============================================================================== --- pypy/dist/pypy/module/builtin/app_functional.py (original) +++ pypy/dist/pypy/module/builtin/app_functional.py Sat Feb 26 10:14:14 2005 @@ -2,7 +2,7 @@ Plain Python definition of the builtin functions oriented towards functional programming. """ - +from __future__ import generators def sum(sequence, total=0): # must forbid "summing" strings, per specs of built-in 'sum' From arigo at codespeak.net Mon Feb 28 00:27:02 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 28 Feb 2005 00:27:02 +0100 (MET) Subject: [pypy-svn] r9522 - pypy/dist/pypy/translator Message-ID: <20050227232702.296C027B40@code1.codespeak.net> Author: arigo Date: Mon Feb 28 00:27:01 2005 New Revision: 9522 Modified: pypy/dist/pypy/translator/genc.py Log: Revert a change probably checked in by error Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Mon Feb 28 00:27:01 2005 @@ -459,7 +459,7 @@ print >> f, self.C_HEADER # function implementations - while self.pendingfunctions or self.latercode: + while self.pendingfunctions: func = self.pendingfunctions.pop() self.gen_cfunction(func) # collect more of the latercode after each function From arigo at codespeak.net Mon Feb 28 16:21:47 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 28 Feb 2005 16:21:47 +0100 (MET) Subject: [pypy-svn] r9523 - pypy/dist/pypy/translator Message-ID: <20050228152147.8FEFE27B4D@code1.codespeak.net> Author: arigo Date: Mon Feb 28 16:21:47 2005 New Revision: 9523 Modified: pypy/dist/pypy/translator/genc.h pypy/dist/pypy/translator/genc.py Log: genc now generates the frozen initialization bytecode as a big string literal instead of a { } array literal. This helps keep gcc memory consumption lower. Modified: pypy/dist/pypy/translator/genc.h ============================================================================== --- pypy/dist/pypy/translator/genc.h (original) +++ pypy/dist/pypy/translator/genc.h Mon Feb 28 16:21:47 2005 @@ -342,12 +342,12 @@ return 0; } -static int setup_initcode(unsigned char* frozendata, int len) +static int setup_initcode(char* frozendata, int len) { PyObject* co; PyObject* globals; PyObject* res; - co = PyMarshal_ReadObjectFromString((char*) frozendata, len); + co = PyMarshal_ReadObjectFromString(frozendata, len); if (co == NULL) return -1; if (!PyCode_Check(co)) { Modified: pypy/dist/pypy/translator/genc.py ============================================================================== --- pypy/dist/pypy/translator/genc.py (original) +++ pypy/dist/pypy/translator/genc.py Mon Feb 28 16:21:47 2005 @@ -490,8 +490,12 @@ # frozen init bytecode print >> f, self.C_FROZEN_BEGIN bytecode = self.getfrozenbytecode() + def char_repr(c): + if c in '\\"': return '\\' + c + if ' ' <= c < '\x7F': return c + return '\\%03o' % ord(c) for i in range(0, len(bytecode), 20): - print >> f, ''.join(['%d,' % ord(c) for c in bytecode[i:i+20]]) + print >> f, ''.join([char_repr(c) for c in bytecode[i:i+20]])+'\\' print >> f, self.C_FROZEN_END # the footer proper: the module init function */ @@ -826,9 +830,9 @@ C_FROZEN_BEGIN = ''' /* Frozen Python bytecode: the initialization code */ -static unsigned char frozen_initcode[] = {''' +static char frozen_initcode[] = "\\''' - C_FROZEN_END = '''};\n''' + C_FROZEN_END = '''";\n''' C_FOOTER = C_SEP + ''' From pedronis at codespeak.net Mon Feb 28 16:40:42 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 28 Feb 2005 16:40:42 +0100 (MET) Subject: [pypy-svn] r9524 - pypy/dist/pypy/interpreter Message-ID: <20050228154042.0862727B4A@code1.codespeak.net> Author: pedronis Date: Mon Feb 28 16:40:42 2005 New Revision: 9524 Modified: pypy/dist/pypy/interpreter/pycode.py pypy/dist/pypy/interpreter/typedef.py Log: use proper str list for names in code objects Modified: pypy/dist/pypy/interpreter/pycode.py ============================================================================== --- pypy/dist/pypy/interpreter/pycode.py (original) +++ pypy/dist/pypy/interpreter/pycode.py Mon Feb 28 16:40:42 2005 @@ -57,9 +57,9 @@ self.co_code = None # string: instruction opcodes self.co_consts_w = [] # list of constants used (wrapped!) self.co_names = [] # list of strings: names (for attrs..) - self.co_varnames = () # tuple of strings: local variable names - self.co_freevars = () # tuple of strings: free variable names - self.co_cellvars = () # tuple of strings: cell variable names + self.co_varnames = [] # tuple of strings: local variable names + self.co_freevars = [] # tuple of strings: free variable names + self.co_cellvars = [] # tuple of strings: cell variable names # The rest doesn't count for hash/cmp self.co_filename = "" # string: where it was loaded from #self.co_name (in base class)# string: name, for reference @@ -89,13 +89,13 @@ self.co_code = x #self.co_consts = x = code.co_names; assert isinstance(x, tuple) - self.co_names = list(x) + self.co_names = [ str(n) for n in x ] x = code.co_varnames; assert isinstance(x, tuple) - self.co_varnames = x + self.co_varnames = [ str(n) for n in x ] x = code.co_freevars; assert isinstance(x, tuple) - self.co_freevars = x + self.co_freevars = [ str(n) for n in x ] x = code.co_cellvars; assert isinstance(x, tuple) - self.co_cellvars = x + self.co_cellvars = [ str(n) for n in x ] x = code.co_filename; assert isinstance(x, str) self.co_filename = x x = code.co_name; assert isinstance(x, str) @@ -152,14 +152,21 @@ # first approximation return dis.findlabels(self.co_code) - def fget_co_consts(space, w_self): - self = space.interpclass_w(w_self) + def fget_co_consts(space, self): return space.newtuple(self.co_consts_w) - def fget_co_names(space, w_self): - self = space.interpclass_w(w_self) + def fget_co_names(space, self): return space.newtuple([space.wrap(name) for name in self.co_names]) + def fget_co_varnames(space, self): + return space.newtuple([space.wrap(name) for name in self.co_varnames]) + + def fget_co_cellvars(space, self): + return space.newtuple([space.wrap(name) for name in self.co_freevars]) + + def fget_co_freevars(space, self): + return space.newtuple([space.wrap(name) for name in self.co_cellvars]) + def descr_code__eq__(self, w_other): space = self.space other = space.interpclass_w(w_other) Modified: pypy/dist/pypy/interpreter/typedef.py ============================================================================== --- pypy/dist/pypy/interpreter/typedef.py (original) +++ pypy/dist/pypy/interpreter/typedef.py Mon Feb 28 16:40:42 2005 @@ -312,9 +312,9 @@ co_code = interp_attrproperty('co_code', cls=PyCode), co_consts = GetSetProperty(PyCode.fget_co_consts), co_names = GetSetProperty(PyCode.fget_co_names), - co_varnames = interp_attrproperty('co_varnames', cls=PyCode), - co_freevars = interp_attrproperty('co_freevars', cls=PyCode), - co_cellvars = interp_attrproperty('co_cellvars', cls=PyCode), + co_varnames = GetSetProperty(PyCode.fget_co_varnames), + co_freevars = GetSetProperty(PyCode.fget_co_freevars), + co_cellvars = GetSetProperty(PyCode.fget_co_cellvars), co_filename = interp_attrproperty('co_filename', cls=PyCode), co_name = interp_attrproperty('co_name', cls=PyCode), co_firstlineno = interp_attrproperty('co_firstlineno', cls=PyCode), From hpk at codespeak.net Mon Feb 28 16:52:02 2005 From: hpk at codespeak.net (hpk at codespeak.net) Date: Mon, 28 Feb 2005 16:52:02 +0100 (MET) Subject: [pypy-svn] r9525 - pypy/dist/pypy/objspace/std Message-ID: <20050228155202.1464E27B4A@code1.codespeak.net> Author: hpk Date: Mon Feb 28 16:52:01 2005 New Revision: 9525 Modified: pypy/dist/pypy/objspace/std/multimethod.py Log: hands-on-hack to avoid the many duplicate functions+globals which arise on multimethod construction. Maybe there is a nicer way to avoid the occurence of the duplicate definitions? Modified: pypy/dist/pypy/objspace/std/multimethod.py ============================================================================== --- pypy/dist/pypy/objspace/std/multimethod.py (original) +++ pypy/dist/pypy/objspace/std/multimethod.py Mon Feb 28 16:52:01 2005 @@ -91,6 +91,7 @@ # ____________________________________________________________ class Installer: + mmfunccache = {} prefix_memo = {} @@ -251,9 +252,19 @@ bodylines.insert(0, 'def %s(%s):' % (funcname, ', '.join(funcargs))) bodylines.append('') source = '\n'.join(bodylines) - #print source - #print "*"*60 - exec compile2(source) in miniglobals - func = miniglobals[funcname] + + # XXX find a better place (or way) to avoid duplicate functions + l = miniglobals.items() + l.sort() + l = tuple(l) + key = (source, l) + try: + func = self.mmfunccache[key] + except KeyError: + exec compile2(source) in miniglobals + func = miniglobals[funcname] + self.mmfunccache[key] = func + #else: + # print "avoided duplicate function", func self.to_install.append((target, funcname, func, source, fallback)) return func From arigo at codespeak.net Mon Feb 28 17:11:23 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 28 Feb 2005 17:11:23 +0100 (MET) Subject: [pypy-svn] r9526 - pypy/dist/goal Message-ID: <20050228161123.B5EC627B4A@code1.codespeak.net> Author: arigo Date: Mon Feb 28 17:11:23 2005 New Revision: 9526 Modified: pypy/dist/goal/translate_pypy.py Log: Disable translation of classobjinterp.py for now. Modified: pypy/dist/goal/translate_pypy.py ============================================================================== --- pypy/dist/goal/translate_pypy.py (original) +++ pypy/dist/goal/translate_pypy.py Mon Feb 28 17:11:23 2005 @@ -42,6 +42,8 @@ def analyse(entry_point=entry_point): global t, space + # disable translation of the whole of classobjinterp.py + StdObjSpace.setup_old_style_classes = lambda self: None space = StdObjSpace() # call cache filling code buildcache2.buildcache(space) From arigo at codespeak.net Mon Feb 28 17:33:53 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 28 Feb 2005 17:33:53 +0100 (MET) Subject: [pypy-svn] r9527 - pypy/dist/pypy/translator Message-ID: <20050228163353.64A0827B4A@code1.codespeak.net> Author: arigo Date: Mon Feb 28 17:33:53 2005 New Revision: 9527 Modified: pypy/dist/pypy/translator/simplify.py pypy/dist/pypy/translator/transform.py Log: Fixed comments; move the entry point function at the top of the module. Modified: pypy/dist/pypy/translator/simplify.py ============================================================================== --- pypy/dist/pypy/translator/simplify.py (original) +++ pypy/dist/pypy/translator/simplify.py Mon Feb 28 17:33:53 2005 @@ -1,8 +1,25 @@ """Flow Graph Simplification + +'Syntactic-ish' simplifications on a flow graph. + +simplify_graph() applies all simplifications defined in this file. +See also remove_direct_loops(), which is a 'de-simplification' useful +for code generators. """ from pypy.objspace.flow.model import * +def simplify_graph(graph): + """inplace-apply all the existing optimisations to the graph.""" + checkgraph(graph) + eliminate_empty_blocks(graph) + remove_implicit_exceptions(graph) + join_blocks(graph) + transform_dead_op_vars(graph) + checkgraph(graph) + +# ____________________________________________________________ + def eliminate_empty_blocks(graph): """Eliminate basic blocks that do not contain any operations. When this happens, we need to replace the preceeding link with the @@ -85,15 +102,6 @@ link.prevblock.exitswitch = None traverse(visit, graph) -def simplify_graph(graph): - """inplace-apply all the existing optimisations to the graph.""" - checkgraph(graph) - eliminate_empty_blocks(graph) - remove_implicit_exceptions(graph) - join_blocks(graph) - transform_dead_op_vars(graph) - checkgraph(graph) - def remove_direct_loops(graph): """This is useful for code generators: it ensures that no link has common input and output variables, which could occur if a block's exit Modified: pypy/dist/pypy/translator/transform.py ============================================================================== --- pypy/dist/pypy/translator/transform.py (original) +++ pypy/dist/pypy/translator/transform.py Mon Feb 28 17:33:53 2005 @@ -1,7 +1,8 @@ """Flow Graph Transformation The difference between simplification and transformation is that -transformation may introduce new space operation. +transformation is based on annotations; it runs after the annotator +completed. """ import types From arigo at codespeak.net Mon Feb 28 18:06:49 2005 From: arigo at codespeak.net (arigo at codespeak.net) Date: Mon, 28 Feb 2005 18:06:49 +0100 (MET) Subject: [pypy-svn] r9528 - in pypy/dist/pypy/objspace/flow: . test Message-ID: <20050228170649.38EBF27B40@code1.codespeak.net> Author: arigo Date: Mon Feb 28 18:06:49 2005 New Revision: 9528 Modified: pypy/dist/pypy/objspace/flow/framestate.py pypy/dist/pypy/objspace/flow/objspace.py pypy/dist/pypy/objspace/flow/test/test_framestate.py Log: FlowObjSpace support for explicit specialization: in code using global constants that are instances of SpecTag, code paths are not merged when the same variable holds a different SpecTag instance. Modified: pypy/dist/pypy/objspace/flow/framestate.py ============================================================================== --- pypy/dist/pypy/objspace/flow/framestate.py (original) +++ pypy/dist/pypy/objspace/flow/framestate.py Mon Feb 28 18:06:49 2005 @@ -117,8 +117,8 @@ # This is needed for try:except: and try:finally:, though # it makes the control flow a bit larger by duplicating the # handlers. - dont_merge_w1 = w1 in UNPICKLE_TAGS - dont_merge_w2 = w2 in UNPICKLE_TAGS + dont_merge_w1 = w1 in UNPICKLE_TAGS or isinstance(w1.value, SpecTag) + dont_merge_w2 = w2 in UNPICKLE_TAGS or isinstance(w2.value, SpecTag) if dont_merge_w1 or dont_merge_w2: raise UnionError else: @@ -128,6 +128,16 @@ # ____________________________________________________________ # +# Support for explicit specialization: in code using global constants +# that are instances of SpecTag, code paths are not merged when +# the same variable holds a different SpecTag instance. + +class SpecTag(object): + def __repr__(self): + return 'SpecTag(%d)' % id(self) + +# ____________________________________________________________ +# # We have to flatten out the state of the frame into a list of # Variables and Constants. This is done above by collecting the # locals and the items on the value stack, but the latter may contain Modified: pypy/dist/pypy/objspace/flow/objspace.py ============================================================================== --- pypy/dist/pypy/objspace/flow/objspace.py (original) +++ pypy/dist/pypy/objspace/flow/objspace.py Mon Feb 28 18:06:49 2005 @@ -29,8 +29,6 @@ full_exceptions = False - resolve_constants = True # used by the appflowspace - builtins_can_raise_exceptions = False def initialize(self): @@ -396,7 +394,7 @@ def generic_operator(self, *args_w): assert len(args_w) == arity, name+" got the wrong number of arguments" - if op and (self.resolve_constants or self.concrete_mode): + if op: args = [] for w_arg in args_w: try: Modified: pypy/dist/pypy/objspace/flow/test/test_framestate.py ============================================================================== --- pypy/dist/pypy/objspace/flow/test/test_framestate.py (original) +++ pypy/dist/pypy/objspace/flow/test/test_framestate.py Mon Feb 28 18:06:49 2005 @@ -1,8 +1,9 @@ import autopath -from pypy.objspace.flow.flowcontext import * +from py.test import raises from pypy.objspace.flow.model import * +from pypy.objspace.flow.framestate import * from pypy.interpreter.pycode import PyCode objspacename = 'flow' @@ -95,3 +96,10 @@ fs3 = fs1.union(fs2) fs3.restoreframe(frame) assert isinstance(frame.fastlocals_w[-1], Variable) # generalized + + def test_union_spectag(self): + frame = self.getframe(self.func_simple) + fs1 = FrameState(frame) + frame.fastlocals_w[-1] = Constant(SpecTag()) + fs2 = FrameState(frame) + assert fs1.union(fs2) is None # UnionError From pedronis at codespeak.net Mon Feb 28 18:12:47 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 28 Feb 2005 18:12:47 +0100 (MET) Subject: [pypy-svn] r9529 - in pypy/dist/pypy: annotation translator/test Message-ID: <20050228171247.B633E27B4A@code1.codespeak.net> Author: pedronis Date: Mon Feb 28 18:12:47 2005 New Revision: 9529 Modified: pypy/dist/pypy/annotation/builtin.py pypy/dist/pypy/translator/test/snippet.py pypy/dist/pypy/translator/test/test_annrpython.py Log: annotation for zip & bool Modified: pypy/dist/pypy/annotation/builtin.py ============================================================================== --- pypy/dist/pypy/annotation/builtin.py (original) +++ pypy/dist/pypy/annotation/builtin.py Mon Feb 28 18:12:47 2005 @@ -147,6 +147,14 @@ factory.generalize(s_iter.next()) return factory.create() +def builtin_zip(s_iterable1, s_iterable2): + factory = getbookkeeper().getfactory(ListFactory) + s_iter1 = s_iterable1.iter() + s_iter2 = s_iterable2.iter() + s_tup = SomeTuple((s_iter1.next(),s_iter2.next())) + factory.generalize(s_tup) + return factory.create() + def builtin_apply(*stuff): print "XXX ignoring apply%r" % (stuff,) return SomeObject() @@ -174,6 +182,9 @@ def exception_init(s_self, *args): s_self.setattr(immutablevalue('args'), SomeTuple(args)) +def builtin_bool(s_obj): + return SomeBool() + def count(s_obj): return SomeInteger() Modified: pypy/dist/pypy/translator/test/snippet.py ============================================================================== --- pypy/dist/pypy/translator/test/snippet.py (original) +++ pypy/dist/pypy/translator/test/snippet.py Mon Feb 28 18:12:47 2005 @@ -654,6 +654,9 @@ def simple_iter(x): return iter(x) +def simple_zip(x,y): + return zip(x,y) + def dict_copy(d): return d.copy() Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Mon Feb 28 18:12:47 2005 @@ -406,6 +406,17 @@ t = annmodel.SomeDict({}, annmodel.SomeInteger(), annmodel.SomeInteger()) s = a.build_types(snippet.simple_iter, [t]) assert isinstance(s, annmodel.SomeIterator) + + + def test_simple_zip(self): + a = RPythonAnnotator() + x = annmodel.SomeList({}, annmodel.SomeInteger()) + y = annmodel.SomeList({}, annmodel.SomeString()) + s = a.build_types(snippet.simple_zip, [x,y]) + assert s.knowntype == list + assert s.s_item.knowntype == tuple + assert s.s_item.items[0].knowntype == int + assert s.s_item.items[1].knowntype == str def test_dict_copy(self): a = RPythonAnnotator() From pedronis at codespeak.net Mon Feb 28 18:14:33 2005 From: pedronis at codespeak.net (pedronis at codespeak.net) Date: Mon, 28 Feb 2005 18:14:33 +0100 (MET) Subject: [pypy-svn] r9530 - pypy/dist/pypy/translator/test Message-ID: <20050228171433.3556B27B4A@code1.codespeak.net> Author: pedronis Date: Mon Feb 28 18:14:33 2005 New Revision: 9530 Modified: pypy/dist/pypy/translator/test/test_annrpython.py Log: white space police Modified: pypy/dist/pypy/translator/test/test_annrpython.py ============================================================================== --- pypy/dist/pypy/translator/test/test_annrpython.py (original) +++ pypy/dist/pypy/translator/test/test_annrpython.py Mon Feb 28 18:14:33 2005 @@ -407,7 +407,6 @@ s = a.build_types(snippet.simple_iter, [t]) assert isinstance(s, annmodel.SomeIterator) - def test_simple_zip(self): a = RPythonAnnotator() x = annmodel.SomeList({}, annmodel.SomeInteger())