[pypy-svn] r68376 - in pypy/branch/improve-kwd-args/pypy: interpreter interpreter/test module/__builtin__ objspace/std translator

pedronis at codespeak.net pedronis at codespeak.net
Tue Oct 13 14:36:53 CEST 2009


Author: pedronis
Date: Tue Oct 13 14:36:52 2009
New Revision: 68376

Modified:
   pypy/branch/improve-kwd-args/pypy/interpreter/argument.py
   pypy/branch/improve-kwd-args/pypy/interpreter/test/test_argument.py
   pypy/branch/improve-kwd-args/pypy/module/__builtin__/interp_classobj.py
   pypy/branch/improve-kwd-args/pypy/objspace/std/fake.py
   pypy/branch/improve-kwd-args/pypy/translator/geninterplevel.py
Log:
(cfbolz, pedronis) improve test coverage, kill some rarely used methods



Modified: pypy/branch/improve-kwd-args/pypy/interpreter/argument.py
==============================================================================
--- pypy/branch/improve-kwd-args/pypy/interpreter/argument.py	(original)
+++ pypy/branch/improve-kwd-args/pypy/interpreter/argument.py	Tue Oct 13 14:36:52 2009
@@ -29,12 +29,6 @@
 
         make_sure_not_resized(self.arguments_w)
         self._combine_wrapped(w_stararg, w_starstararg)
-
-    def num_args(self): # only used in module/__builtin__/interp_classobj.py
-        return len(self.arguments_w)
-
-    def num_kwds(self): # only used in module/__builtin__/interp_classobj.py
-        return len(self.keywords)
         
     def __repr__(self):
         """ NOT_RPYTHON """
@@ -48,9 +42,8 @@
 
     ###  Manipulation  ###
 
-    def unpack(self): # used often
+    def unpack(self): # slowish
         "Return a ([w1,w2...], {'kw':w3...}) pair."
-        # XXX may want to change that later
         kwds_w = {}
         if self.keywords:
             for i in range(len(self.keywords)):
@@ -61,7 +54,7 @@
         "Return a new Arguments with a args_w as positional arguments."
         return Arguments(self.space, args_w, self.keywords, self.keywords_w)
 
-    def prepend(self, w_firstarg): # used often
+    def prepend(self, w_firstarg):
         "Return a new Arguments with a new argument inserted first."
         return self.replace_arguments([w_firstarg] + self.arguments_w)
 
@@ -105,9 +98,6 @@
                 self.keywords_w = self.keywords_w + keywords_w
 
     def fixedunpack(self, argcount):
-        # used by ./objspace/std/typeobject.py
-        # ./objspace/std/objecttype.py
-        # ./annotation/description.py
         """The simplest argument parsing: get the 'argcount' arguments,
         or raise a real ValueError if the length is wrong."""
         if self.keywords:
@@ -119,10 +109,6 @@
         return self.arguments_w
 
     def firstarg(self):
-        # used by
-        # ./module/_random/interp_random.py
-        # ./interpreter/gateway.py
-        # ./interpreter/function.py
         "Return the first argument for inspection."
         if self.arguments_w:
             return self.arguments_w[0]
@@ -283,26 +269,16 @@
         scopelen = len(argnames)
         has_vararg = varargname is not None
         has_kwarg = kwargname is not None
-        if has_vararg:
-            scopelen += 1
-        if has_kwarg:
-            scopelen += 1
+        scopelen += has_vararg
+        scopelen += has_kwarg
         scope_w = [None] * scopelen
-        self._match_signature(w_firstarg, scope_w, argnames, has_vararg, has_kwarg, defaults_w, blindargs)
+        self._match_signature(w_firstarg, scope_w, argnames, has_vararg,
+                              has_kwarg, defaults_w, blindargs)
         return scope_w    
 
-    def parse(self, fnname, signature, defaults_w=[], blindargs=0):
-        # used by geninterped code
-        # and ./objspace/std/fake.py
-        """Parse args and kwargs to initialize a frame
-        according to the signature of code object.
-        """
-        return self.parse_obj(None, fnname, signature, defaults_w,
-                              blindargs)
 
     def parse_obj(self, w_firstarg,
                   fnname, signature, defaults_w=[], blindargs=0):
-        # used by ./interpreter/gateway.py
         """Parse args and kwargs to initialize a frame
         according to the signature of code object.
         """
@@ -314,18 +290,11 @@
 
     @staticmethod
     def frompacked(space, w_args=None, w_kwds=None):
-        # used by
-        # ./module/_stackless/interp_coroutine.py
-        # ./module/thread/os_thread.py
-        # ./objspace/fake/checkmodule.py
-        # ./interpreter/gateway.py
-        # ./interpreter/baseobjspace.py
         """Convenience static method to build an Arguments
            from a wrapped sequence and a wrapped dictionary."""
         return Arguments(space, [], w_stararg=w_args, w_starstararg=w_kwds)
 
     def topacked(self):
-        # used by ./module/_stackless/interp_coroutine.py
         """Express the Argument object as a pair of wrapped w_args, w_kwds."""
         space = self.space
         args_w, kwds_w = self.unpack()
@@ -435,10 +404,6 @@
     
     @staticmethod
     def fromshape(space, (shape_cnt,shape_keys,shape_star,shape_stst), data_w):
-        # used by
-        # ./rpython/callparse.py
-        # ./rpython/rbuiltin.py
-        # ./annotation/bookkeeper.py
         args_w = data_w[:shape_cnt]
         p = end_keys = shape_cnt + len(shape_keys)
         if shape_star:
@@ -456,7 +421,6 @@
                                        w_starstar)
 
     def flatten(self):
-        # used by ./objspace/flow/objspace.py
         """ Argument <-> list of w_objects together with "shape" information """
         shape_cnt, shape_keys, shape_star, shape_stst = self._rawshape()
         data_w = self.arguments_w + [self.keywords_w[self.keywords.index(key)]
@@ -480,7 +444,6 @@
         return shape_cnt, tuple(shape_keys), shape_star, shape_stst # shape_keys are sorted
 
 def rawshape(args, nextra=0):
-    # used by ./annotation/description.py
     return args._rawshape(nextra)
 
 

Modified: pypy/branch/improve-kwd-args/pypy/interpreter/test/test_argument.py
==============================================================================
--- pypy/branch/improve-kwd-args/pypy/interpreter/test/test_argument.py	(original)
+++ pypy/branch/improve-kwd-args/pypy/interpreter/test/test_argument.py	Tue Oct 13 14:36:52 2009
@@ -49,6 +49,48 @@
     w_dict = dict
 
 class TestArgumentsNormal(object):
+
+    def test_create(self):
+        space = DummySpace()
+        args_w = []
+        args = Arguments(space, args_w)
+        assert args.arguments_w is args_w
+        assert args.keywords is None
+        assert args.keywords_w is None
+
+        assert args.firstarg() is None
+
+        args = Arguments(space, args_w, w_stararg=["*"],
+                         w_starstararg={"k": 1})
+        assert args.arguments_w == ["*"]
+        assert args.keywords == ["k"]
+        assert args.keywords_w == [1]
+
+        assert args.firstarg() == "*"
+
+    def test_prepend(self):
+        space = DummySpace()
+        args = Arguments(space, ["0"])
+        args1 = args.prepend("thingy")
+        assert args1 is not args
+        assert args1.arguments_w == ["thingy", "0"]
+        assert args1.keywords is args.keywords
+        assert args1.keywords_w is args.keywords_w
+
+    def test_fixedunpacked(self):
+        space = DummySpace()
+        
+        args = Arguments(space, [], ["k"], [1])
+        py.test.raises(ValueError, args.fixedunpack, 1)
+
+        args = Arguments(space, ["a", "b"])
+        py.test.raises(ValueError, args.fixedunpack, 0)
+        py.test.raises(ValueError, args.fixedunpack, 1)        
+        py.test.raises(ValueError, args.fixedunpack, 3)
+        py.test.raises(ValueError, args.fixedunpack, 4)
+
+        assert args.fixedunpack(2) == ['a', 'b']
+    
     def test_match0(self):
         space = DummySpace()
         args = Arguments(space, [])
@@ -228,6 +270,129 @@
             py.test.raises(ArgErrUnknownKwds, args._match_signature, None, l,
                            ["a", "b"], blindargs=2)
 
+    def test_args_parsing(self):
+        space = DummySpace()
+        args = Arguments(space, [])
+
+        calls = []
+
+        def _match_signature(w_firstarg, scope_w, argnames, has_vararg=False,
+                             has_kwarg=False, defaults_w=[], blindargs=0):
+            calls.append((w_firstarg, scope_w, argnames, has_vararg,
+                          has_kwarg, defaults_w, blindargs))
+        args._match_signature = _match_signature
+
+        scope_w = args.parse_obj(None, "foo", (["a", "b"], None, None))
+        assert len(calls) == 1
+        assert calls[0] == (None, [None, None], ["a", "b"], False, False,
+                            [], 0)
+        assert calls[0][1] is scope_w
+        calls = []
+            
+        scope_w = args.parse_obj(None, "foo", (["a", "b"], "args", None),
+                                 blindargs=1)
+        assert len(calls) == 1
+        assert calls[0] == (None, [None, None, None], ["a", "b"], True, False,
+                            [], 1)
+        calls = []
+
+        scope_w = args.parse_obj(None, "foo", (["a", "b"], "args", "kw"),
+                             defaults_w=['x', 'y'])
+        assert len(calls) == 1
+        assert calls[0] == (None, [None, None, None, None], ["a", "b"],
+                            True, True,
+                            ["x", "y"], 0)
+        calls = []
+        
+        scope_w = args.parse_obj("obj", "foo", (["a", "b"], "args", "kw"),
+                             defaults_w=['x', 'y'], blindargs=1)
+        assert len(calls) == 1
+        assert calls[0] == ("obj", [None, None, None, None], ["a", "b"],
+                            True, True,
+                            ["x", "y"], 1)
+
+        class FakeArgErr(ArgErr):
+
+            def getmsg(self, fname):
+                return "msg "+fname
+
+        def _match_signature(*args):
+            raise FakeArgErr()
+        args._match_signature = _match_signature
+
+
+        excinfo = py.test.raises(OperationError, args.parse_obj, "obj", "foo",
+                       (["a", "b"], None, None))
+        assert excinfo.value.w_type is TypeError
+        assert excinfo.value.w_value == "msg foo"
+
+
+    def test_args_parsing_into_scope(self):
+        space = DummySpace()
+        args = Arguments(space, [])
+
+        calls = []
+
+        def _match_signature(w_firstarg, scope_w, argnames, has_vararg=False,
+                             has_kwarg=False, defaults_w=[], blindargs=0):
+            calls.append((w_firstarg, scope_w, argnames, has_vararg,
+                          has_kwarg, defaults_w, blindargs))
+        args._match_signature = _match_signature
+
+        scope_w = [None, None]
+        args.parse_into_scope(None, scope_w, "foo", (["a", "b"], None, None))
+        assert len(calls) == 1
+        assert calls[0] == (None, scope_w, ["a", "b"], False, False,
+                            [], 0)
+        assert calls[0][1] is scope_w
+        calls = []
+
+        scope_w = [None, None, None, None]
+        args.parse_into_scope(None, scope_w, "foo", (["a", "b"], "args", "kw"),
+                              defaults_w=['x', 'y'])
+        assert len(calls) == 1
+        assert calls[0] == (None, scope_w, ["a", "b"],
+                            True, True,
+                            ["x", "y"], 0)
+        calls = []
+
+        scope_w = [None, None, None, None]        
+        args.parse_into_scope("obj", scope_w, "foo", (["a", "b"],
+                                                      "args", "kw"),
+                              defaults_w=['x', 'y'])
+        assert len(calls) == 1
+        assert calls[0] == ("obj", scope_w, ["a", "b"],
+                            True, True,
+                            ["x", "y"], 0)
+
+        class FakeArgErr(ArgErr):
+
+            def getmsg(self, fname):
+                return "msg "+fname
+
+        def _match_signature(*args):
+            raise FakeArgErr()
+        args._match_signature = _match_signature
+
+
+        excinfo = py.test.raises(OperationError, args.parse_into_scope,
+                                 "obj", [None, None], "foo",
+                                 (["a", "b"], None, None))
+        assert excinfo.value.w_type is TypeError
+        assert excinfo.value.w_value == "msg foo"
+
+    def test_topacked_frompacked(self):
+        space = DummySpace()
+        args = Arguments(space, [1], ['a', 'b'], [2, 3])
+        w_args, w_kwds = args.topacked()
+        assert w_args == (1,)
+        assert w_kwds == {'a': 2, 'b': 3}
+        args1 = Arguments.frompacked(space, w_args, w_kwds)
+        assert args.arguments_w == [1]
+        assert set(args.keywords) == set(['a', 'b'])
+        assert args.keywords_w[args.keywords.index('a')] == 2
+        assert args.keywords_w[args.keywords.index('b')] == 3        
+                                 
 
 def make_arguments_for_translation(space, args_w, keywords_w={},
                                    w_stararg=None, w_starstararg=None):

Modified: pypy/branch/improve-kwd-args/pypy/module/__builtin__/interp_classobj.py
==============================================================================
--- pypy/branch/improve-kwd-args/pypy/module/__builtin__/interp_classobj.py	(original)
+++ pypy/branch/improve-kwd-args/pypy/module/__builtin__/interp_classobj.py	Tue Oct 13 14:36:52 2009
@@ -176,7 +176,7 @@
                 raise OperationError(
                     space.w_TypeError,
                     space.wrap("__init__() should return None"))
-        elif __args__.num_args() or __args__.num_kwds():
+        elif __args__.arguments_w or __args__.keywords:
             raise OperationError(
                     space.w_TypeError,
                     space.wrap("this constructor takes no arguments"))

Modified: pypy/branch/improve-kwd-args/pypy/objspace/std/fake.py
==============================================================================
--- pypy/branch/improve-kwd-args/pypy/objspace/std/fake.py	(original)
+++ pypy/branch/improve-kwd-args/pypy/objspace/std/fake.py	Tue Oct 13 14:36:52 2009
@@ -137,7 +137,7 @@
         frame = func.space.createframe(self, func.w_func_globals,
                                         func.closure)
         sig = self.signature()
-        scope_w = args.parse(func.name, sig, func.defs_w)
+        scope_w = args.parse_obj(None, func.name, sig, func.defs_w)
         frame.setfastscope(scope_w)
         return frame.run()
     

Modified: pypy/branch/improve-kwd-args/pypy/translator/geninterplevel.py
==============================================================================
--- pypy/branch/improve-kwd-args/pypy/translator/geninterplevel.py	(original)
+++ pypy/branch/improve-kwd-args/pypy/translator/geninterplevel.py	Tue Oct 13 14:36:52 2009
@@ -1269,7 +1269,7 @@
 
             print >> f, '    defaults_w = [%s]' % ", ".join(name_of_defaults)
 
-            print >> f, '    %s__args__.parse(funcname, signature, defaults_w)' % (
+            print >> f, '    %s__args__.parse_obj(None, funcname, signature, defaults_w)' % (
                 tupassstr(fast_args),)
             print >> f, '    return %s(%s)' % (fast_name, ', '.join(["space"]+fast_args))
 



More information about the Pypy-commit mailing list