Commits

Ronny Pfannschmidt committed a957881 Merge

merge default

Comments (0)

Files changed (21)

.hgsubstate

Empty file added.

pypy/annotation/description.py

 from pypy.interpreter.pycode import cpython_code_signature
 from pypy.interpreter.argument import rawshape
 from pypy.interpreter.argument import ArgErr
+from pypy.interpreter.function import Defaults
 from pypy.tool.sourcetools import valid_identifier
 from pypy.tool.pairtype import extendabletype
 
     overridden = False
     normalized = False
     modified   = True
-    
+
     def __init__(self, desc):
         self.descs = { desc: True }
         self.calltables = {}  # see calltable_lookup_row()
 class FunctionDesc(Desc):
     knowntype = types.FunctionType
     overridden = False
-    
+
     def __init__(self, bookkeeper, pyobj=None,
                  name=None, signature=None, defaults=None,
                  specializer=None):
                     return '_'.join(map(nameof, thing))
                 else:
                     return str(thing)[:30]
-                
+
             if key is not None and alt_name is None:
                 postfix = valid_identifier(nameof(key))
                 alt_name = "%s__%s"%(self.name, postfix)
             for x in defaults:
                 defs_s.append(self.bookkeeper.immutablevalue(x))
         try:
-            inputcells = args.match_signature(signature, defs_s)
+            inputcells = args.match_signature(signature, Defaults(defs_s))
         except ArgErr, e:
             raise TypeError, "signature mismatch: %s" % e.getmsg(self.name)
         return inputcells
 
     def bind_under(self, classdef, name):
         # XXX static methods
-        return self.bookkeeper.getmethoddesc(self, 
+        return self.bookkeeper.getmethoddesc(self,
                                              classdef,   # originclassdef,
                                              None,       # selfclassdef
                                              name)
         while name not in cdesc.classdict:
             cdesc = cdesc.basedesc
             if cdesc is None:
-                return None 
+                return None
         else:
             return cdesc
 
 class MethodDesc(Desc):
     knowntype = types.MethodType
 
-    def __init__(self, bookkeeper, funcdesc, originclassdef, 
+    def __init__(self, bookkeeper, funcdesc, originclassdef,
                  selfclassdef, name, flags={}):
         super(MethodDesc, self).__init__(bookkeeper)
         self.funcdesc = funcdesc
         # FunctionDescs, not MethodDescs.  The present method returns the
         # FunctionDesc to use as a key in that family.
         return self.funcdesc
-    
+
     def simplify_desc_set(descs):
         # Some hacking needed to make contains() happy on SomePBC: if the
         # set of MethodDescs contains some "redundant" ones, i.e. ones that
             return s_ImpossibleValue
         else:
             return self.bookkeeper.immutablevalue(value)
-    
+
     def create_new_attribute(self, name, value):
         try:
             self.read_attribute(name)
         s_self = SomePBC([self.frozendesc])
         args = args.prepend(s_self)
         return self.funcdesc.pycall(schedule, args, s_previous_result)
-    
+
     def consider_call_site(bookkeeper, family, descs, args, s_result):
         shape = rawshape(args, nextra=1)    # account for the extra 'self'
         funcdescs = [mofdesc.funcdesc for mofdesc in descs]

pypy/interpreter/argument.py

         if i == 2:
             return self.kwargname
         raise IndexError
-        
+
 
 
 class Arguments(object):
     """
     Collects the arguments of a function call.
-    
+
     Instances should be considered immutable.
     """
 
             self._combine_starstarargs_wrapped(w_starstararg)
 
     def _combine_starargs_wrapped(self, w_stararg):
-        # unpack the * arguments 
+        # unpack the * arguments
         space = self.space
         try:
             args_w = space.fixedview(w_stararg)
         if self.arguments_w:
             return self.arguments_w[0]
         return None
-        
+
     ###  Parsing for function calls  ###
 
-    def _match_signature(self, w_firstarg, scope_w, signature, defaults_w=[],
+    def _match_signature(self, w_firstarg, scope_w, signature, defaults=None,
                          blindargs=0):
         """Parse args and kwargs according to the signature of a code object,
         or raise an ArgErr in case of failure.
         """
         if jit.we_are_jitted() and self._dont_jit:
             return self._match_signature_jit_opaque(w_firstarg, scope_w,
-                                                    signature, defaults_w,
+                                                    signature, defaults,
                                                     blindargs)
         return self._really_match_signature(w_firstarg, scope_w, signature,
-                                            defaults_w, blindargs)
+                                            defaults, blindargs)
 
     @jit.dont_look_inside
     def _match_signature_jit_opaque(self, w_firstarg, scope_w, signature,
-                                    defaults_w, blindargs):
+                                    defaults, blindargs):
         return self._really_match_signature(w_firstarg, scope_w, signature,
-                                            defaults_w, blindargs)
+                                            defaults, blindargs)
 
     @jit.unroll_safe
-    def _really_match_signature(self, w_firstarg, scope_w, signature, defaults_w=[],
+    def _really_match_signature(self, w_firstarg, scope_w, signature, defaults=None,
                                 blindargs=0):
         #
         #   args_w = list of the normal actual parameters, wrapped
                 scope_w[0] = w_firstarg
                 input_argcount = 1
             else:
-                extravarargs = [ w_firstarg ]
+                extravarargs = [w_firstarg]
         else:
             upfront = 0
-        
+
         args_w = self.arguments_w
         num_args = len(args_w)
 
         elif avail > co_argcount:
             raise ArgErrCount(avail, num_kwds,
                               co_argcount, has_vararg, has_kwarg,
-                              defaults_w, 0)
+                              defaults, 0)
 
         # the code assumes that keywords can potentially be large, but that
         # argnames is typically not too large
                     num_remainingkwds -= 1
         missing = 0
         if input_argcount < co_argcount:
-            def_first = co_argcount - len(defaults_w)
+            def_first = co_argcount - (0 if defaults is None else defaults.getlen())
             for i in range(input_argcount, co_argcount):
                 if scope_w[i] is not None:
                     pass
                 elif i >= def_first:
-                    scope_w[i] = defaults_w[i-def_first]
+                    scope_w[i] = defaults.getitem(i - def_first)
                 else:
                     # error: not enough arguments.  Don't signal it immediately
                     # because it might be related to a problem with */** or
             if co_argcount == 0:
                 raise ArgErrCount(avail, num_kwds,
                               co_argcount, has_vararg, has_kwarg,
-                              defaults_w, missing)
+                              defaults, missing)
             raise ArgErrUnknownKwds(num_remainingkwds, keywords, used_keywords)
 
         if missing:
             raise ArgErrCount(avail, num_kwds,
                               co_argcount, has_vararg, has_kwarg,
-                              defaults_w, missing)
+                              defaults, missing)
 
         return co_argcount + has_vararg + has_kwarg
-    
+
 
 
     def parse_into_scope(self, w_firstarg,
-                         scope_w, fnname, signature, defaults_w=[]):
+                         scope_w, fnname, signature, defaults=None):
         """Parse args and kwargs to initialize a frame
         according to the signature of code object.
         Store the argumentvalues into scope_w.
         """
         try:
             return self._match_signature(w_firstarg,
-                                         scope_w, signature, defaults_w, 0)
+                                         scope_w, signature, defaults, 0)
         except ArgErr, e:
             raise OperationError(self.space.w_TypeError,
                                  self.space.wrap(e.getmsg(fnname)))
 
-    def _parse(self, w_firstarg, signature, defaults_w, blindargs=0):
+    def _parse(self, w_firstarg, signature, defaults, blindargs=0):
         """Parse args and kwargs according to the signature of a code object,
         or raise an ArgErr in case of failure.
         """
         scopelen = signature.scope_length()
         scope_w = [None] * scopelen
-        self._match_signature(w_firstarg, scope_w, signature, defaults_w,
+        self._match_signature(w_firstarg, scope_w, signature, defaults,
                               blindargs)
-        return scope_w    
+        return scope_w
 
 
     def parse_obj(self, w_firstarg,
-                  fnname, signature, defaults_w=[], blindargs=0):
+                  fnname, signature, defaults=None, blindargs=0):
         """Parse args and kwargs to initialize a frame
         according to the signature of code object.
         """
         try:
-            return self._parse(w_firstarg, signature, defaults_w, blindargs)
+            return self._parse(w_firstarg, signature, defaults, blindargs)
         except ArgErr, e:
             raise OperationError(self.space.w_TypeError,
-                                 self.space.wrap(e.getmsg(fnname)))        
+                                 self.space.wrap(e.getmsg(fnname)))
 
     @staticmethod
     def frompacked(space, w_args=None, w_kwds=None):
                                        self.w_starstararg)
 
 
-            
-    def _match_signature(self, w_firstarg, scope_w, signature, defaults_w=[],
+
+    def _match_signature(self, w_firstarg, scope_w, signature, defaults=None,
                          blindargs=0):
         self.combine_if_necessary()
         # _match_signature is destructive
         return Arguments._match_signature(
                self, w_firstarg, scope_w, signature,
-               defaults_w, blindargs)
+               defaults, blindargs)
 
     def unpack(self):
         self.combine_if_necessary()
         return Arguments.unpack(self)
 
-    def match_signature(self, signature, defaults_w):
+    def match_signature(self, signature, defaults):
         """Parse args and kwargs according to the signature of a code object,
         or raise an ArgErr in case of failure.
         """
-        return self._parse(None, signature, defaults_w)
+        return self._parse(None, signature, defaults)
 
     def unmatch_signature(self, signature, data_w):
         """kind of inverse of match_signature"""
             for w_key in space.unpackiterable(data_w_starargarg):
                 key = space.str_w(w_key)
                 w_value = space.getitem(data_w_starargarg, w_key)
-                unfiltered_kwds_w[key] = w_value            
+                unfiltered_kwds_w[key] = w_value
             cnt += 1
         assert len(data_w) == cnt
-        
+
         ndata_args_w = len(data_args_w)
         if ndata_args_w >= need_cnt:
             args_w = data_args_w[:need_cnt]
             for i in range(0, len(stararg_w)):
                 args_w[i + datalen] = stararg_w[i]
             assert len(args_w) == need_cnt
-            
+
         keywords = []
         keywords_w = []
         for key in need_kwds:
             keywords.append(key)
             keywords_w.append(unfiltered_kwds_w[key])
-                    
+
         return ArgumentsForTranslation(self.space, args_w, keywords, keywords_w)
 
     @staticmethod
     def frompacked(space, w_args=None, w_kwds=None):
         raise NotImplementedError("go away")
-    
+
     @staticmethod
     def fromshape(space, (shape_cnt,shape_keys,shape_star,shape_stst), data_w):
         args_w = data_w[:shape_cnt]
 #
 
 class ArgErr(Exception):
-    
+
     def getmsg(self, fnname):
         raise NotImplementedError
 
 class ArgErrCount(ArgErr):
 
     def __init__(self, got_nargs, nkwds, expected_nargs, has_vararg, has_kwarg,
-                 defaults_w, missing_args):
+                 defaults, missing_args):
         self.expected_nargs = expected_nargs
         self.has_vararg = has_vararg
         self.has_kwarg = has_kwarg
-        
-        self.num_defaults = len(defaults_w)
+
+        self.num_defaults = 0 if defaults is None else defaults.getlen()
         self.missing_args = missing_args
         self.num_args = got_nargs
         self.num_kwds = nkwds
-        
+
     def getmsg(self, fnname):
         args = None
         #args_w, kwds_w = args.unpack()
         n = self.expected_nargs
         if n == 0:
             msg = "%s() takes no argument (%d given)" % (
-                fnname, 
+                fnname,
                 nargs)
         else:
             defcount = self.num_defaults

pypy/interpreter/function.py

     assert not func.can_change_code
     return func.code
 
+class Defaults(object):
+    _immutable_fields_ = ["items[*]"]
+
+    def __init__(self, items):
+        self.items = items
+
+    def getitems(self):
+        return jit.hint(self, promote=True).items
+
+    def getitem(self, idx):
+        return self.getitems()[idx]
+
+    def getlen(self):
+        return len(self.getitems())
+
 class Function(Wrappable):
     """A function is a code object captured with some environment:
     an object space, a dictionary of globals, default arguments,
         self.code = code       # Code instance
         self.w_func_globals = w_globals  # the globals dictionary
         self.closure   = closure    # normally, list of Cell instances or None
-        self.defs_w    = defs_w     # list of w_default's
-        make_sure_not_resized(self.defs_w)
+        self.defs = Defaults(defs_w)     # wrapper around list of w_default's
         self.w_func_dict = None # filled out below if needed
         self.w_module = None
 
                 assert isinstance(code, gateway.BuiltinCode4)
                 return code.fastcall_4(self.space, self, args_w[0],
                                        args_w[1], args_w[2], args_w[3])
-        elif (nargs|PyCode.FLATPYCALL) == fast_natural_arity:
+        elif (nargs | PyCode.FLATPYCALL) == fast_natural_arity:
             assert isinstance(code, PyCode)
             if nargs < 5:
                 new_frame = self.space.createframe(code, self.w_func_globals,
                 return code.fastcall_4(self.space, self, frame.peekvalue(3),
                                        frame.peekvalue(2), frame.peekvalue(1),
                                         frame.peekvalue(0))
-        elif (nargs|Code.FLATPYCALL) == fast_natural_arity:
+        elif (nargs | Code.FLATPYCALL) == fast_natural_arity:
             assert isinstance(code, PyCode)
             return self._flat_pycall(code, nargs, frame)
-        elif fast_natural_arity&Code.FLATPYCALL:
-            natural_arity = fast_natural_arity&0xff
-            if natural_arity > nargs >= natural_arity-len(self.defs_w):
+        elif fast_natural_arity & Code.FLATPYCALL:
+            natural_arity = fast_natural_arity & 0xff
+            if natural_arity > nargs >= natural_arity - self.defs.getlen():
                 assert isinstance(code, PyCode)
                 return self._flat_pycall_defaults(code, nargs, frame,
-                                                  natural_arity-nargs)
+                                                  natural_arity - nargs)
         elif fast_natural_arity == Code.PASSTHROUGHARGS1 and nargs >= 1:
             assert isinstance(code, gateway.BuiltinCodePassThroughArguments1)
             w_obj = frame.peekvalue(nargs-1)
             w_arg = frame.peekvalue(nargs-1-i)
             new_frame.fastlocals_w[i] = w_arg
 
-        defs_w = self.defs_w
-        ndefs = len(defs_w)
-        start = ndefs-defs_to_load
+        defs = self.defs
+        ndefs = defs.getlen()
+        start = ndefs - defs_to_load
         i = nargs
         for j in xrange(start, ndefs):
-            new_frame.fastlocals_w[i] = defs_w[j]
+            new_frame.fastlocals_w[i] = defs.getitem(j)
             i += 1
         return new_frame.run()
 
         return self.w_func_dict
 
     def setdict(self, space, w_dict):
-        if not space.is_true(space.isinstance( w_dict, space.w_dict )):
-            raise OperationError( space.w_TypeError, space.wrap("setting function's dictionary to a non-dict") )
+        if not space.isinstance_w(w_dict, space.w_dict):
+            raise OperationError(space.w_TypeError,
+                space.wrap("setting function's dictionary to a non-dict")
+            )
         self.w_func_dict = w_dict
 
     def descr_function__new__(space, w_subtype, w_code, w_globals,
             w(self.code),
             w_func_globals,
             w_closure,
-            nt(self.defs_w),
+            nt(self.defs.getitems()),
             w_func_dict,
             self.w_module,
         ]
         from pypy.interpreter.pycode import PyCode
         args_w = space.unpackiterable(w_args)
         try:
-            (w_name, w_doc, w_code, w_func_globals, w_closure, w_defs_w,
+            (w_name, w_doc, w_code, w_func_globals, w_closure, w_defs,
              w_func_dict, w_module) = args_w
         except ValueError:
             # wrong args
         if space.is_w(w_func_dict, space.w_None):
             w_func_dict = None
         self.w_func_dict = w_func_dict
-        self.defs_w    = space.fixedview(w_defs_w)
+        self.defs = Defaults(space.fixedview(w_defs))
         self.w_module = w_module
 
     def fget_func_defaults(self, space):
-        values_w = self.defs_w
+        values_w = self.defs.getitems()
+        # the `None in values_w` check here is to ensure that interp-level
+        # functions with a default of NoneNotWrapped do not get their defaults
+        # exposed at applevel
         if not values_w or None in values_w:
             return space.w_None
         return space.newtuple(values_w)
 
     def fset_func_defaults(self, space, w_defaults):
         if space.is_w(w_defaults, space.w_None):
-            self.defs_w = []
+            self.defs = Defaults([])
             return
         if not space.is_true(space.isinstance(w_defaults, space.w_tuple)):
             raise OperationError( space.w_TypeError, space.wrap("func_defaults must be set to a tuple object or None") )
-        self.defs_w = space.fixedview(w_defaults)
+        self.defs = Defaults(space.fixedview(w_defaults))
 
     def fdel_func_defaults(self, space):
-        self.defs_w = []
+        self.defs = Defaults([])
 
     def fget_func_doc(self, space):
         if self.w_doc is None:
     def fget___module__(self, space):
         if self.w_module is None:
             if self.w_func_globals is not None and not space.is_w(self.w_func_globals, space.w_None):
-                self.w_module = space.call_method( self.w_func_globals, "get", space.wrap("__name__") )
+                self.w_module = space.call_method(self.w_func_globals, "get", space.wrap("__name__"))
             else:
                 self.w_module = space.w_None
         return self.w_module
     def __init__(self, func):
         assert isinstance(func, Function)
         Function.__init__(self, func.space, func.code, func.w_func_globals,
-                          func.defs_w, func.closure, func.name)
+                          func.defs.getitems(), func.closure, func.name)
         self.w_doc = func.w_doc
         self.w_func_dict = func.w_func_dict
         self.w_module = func.w_module

pypy/interpreter/gateway.py

 NoneNotWrapped = object()
 
 from pypy.tool.sourcetools import func_with_new_name
-from pypy.interpreter.error import OperationError 
+from pypy.interpreter.error import OperationError
 from pypy.interpreter import eval
 from pypy.interpreter.function import Function, Method, ClassMethod
 from pypy.interpreter.function import FunctionWithFixedCode
 from pypy.rlib import rstackovf
 from pypy.rlib.objectmodel import we_are_translated
 
-# internal non-translatable parts: 
+# internal non-translatable parts:
 import py
 
 class SignatureBuilder(object):
         dispatch = self.dispatch
         for el in unwrap_spec:
             dispatch(el, *extra)
-            
+
 class UnwrapSpecEmit(UnwrapSpecRecipe):
 
     def __init__(self):
         self.n = 0
         self.miniglobals = {}
-        
+
     def succ(self):
         n = self.n
         self.n += 1
         name = obj.__name__
         self.miniglobals[name] = obj
         return name
-    
+
 #________________________________________________________________
 
 class UnwrapSpec_Check(UnwrapSpecRecipe):
             "unwrapped %s argument %s of built-in function %r should "
             "not start with 'w_'" % (name, argname, self.func))
         app_sig.append(argname)
-        
+
     def visit__ObjSpace(self, el, app_sig):
         self.orig_arg()
 
             (argname, self.func))
         assert app_sig.varargname is None,(
             "built-in function %r has conflicting rest args specs" % self.func)
-        app_sig.varargname = argname[:-2]    
+        app_sig.varargname = argname[:-2]
 
     def visit_w_args(self, el, app_sig):
         argname = self.orig_arg()
 
     def scopenext(self):
         return "scope_w[%d]" % self.succ()
-    
+
     def visit_function(self, (func, cls)):
         self.run_args.append("%s(%s)" % (self.use(func),
                                          self.scopenext()))
     def visit_self(self, typ):
         self.run_args.append("space.descr_self_interp_w(%s, %s)" %
                              (self.use(typ), self.scopenext()))
-        
+
     def visit__Wrappable(self, typ):
         self.run_args.append("space.interp_w(%s, %s)" % (self.use(typ),
                                                          self.scopenext()))
                 "unexpected: same spec, different run_args")
             return activation_factory_cls
         except KeyError:
-            parts = []          
+            parts = []
             for el in unwrap_spec:
                 if isinstance(el, tuple):
                     parts.append(''.join([getattr(subel, '__name__', subel)
             #print label
 
             d = {}
-            source = """if 1: 
+            source = """if 1:
                 def _run(self, space, scope_w):
                     return self.behavior(%s)
                 \n""" % (', '.join(self.run_args),)
         self.finger += 1
         if self.n > 4:
             raise FastFuncNotSupported
-        
+
     def nextarg(self):
         arg = "w%d" % self.succ()
         self.args.append(arg)
                     raise FastFuncNotSupported
             d = {}
             unwrap_info.miniglobals['func'] = func
-            source = """if 1: 
+            source = """if 1:
                 def fastfunc_%s_%d(%s):
                     return func(%s)
                 \n""" % (func.__name__, narg,
         # 'w_args' for rest arguments passed as wrapped tuple
         # str,int,float: unwrap argument as such type
         # (function, cls) use function to check/unwrap argument of type cls
-        
+
         # 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)
         else:
             assert descrmismatch is None, (
                 "descrmismatch without a self-type specified")
- 
+
 
         orig_sig = SignatureBuilder(func, argnames, varargname, kwargname)
         app_sig = SignatureBuilder(func)
         space = func.space
         activation = self.activation
         scope_w = args.parse_obj(w_obj, func.name, self.sig,
-                                 func.defs_w, self.minargs)
+                                 func.defs, self.minargs)
         try:
             w_result = activation._run(space, scope_w)
         except DescrMismatch:
             if not we_are_translated():
                 raise
             raise e
-        except KeyboardInterrupt: 
+        except KeyboardInterrupt:
             raise OperationError(space.w_KeyboardInterrupt,
-                                 space.w_None) 
-        except MemoryError: 
+                                 space.w_None)
+        except MemoryError:
             raise OperationError(space.w_MemoryError, space.w_None)
         except rstackovf.StackOverflow, e:
             rstackovf.check_stack_overflow()
 class BuiltinCode0(BuiltinCode):
     _immutable_ = True
     fast_natural_arity = 0
-    
+
     def fastcall_0(self, space, w_func):
         try:
             w_result = self.fastfunc_0(space)
 class BuiltinCode1(BuiltinCode):
     _immutable_ = True
     fast_natural_arity = 1
-    
+
     def fastcall_1(self, space, w_func, w1):
         try:
             w_result = self.fastfunc_1(space, w1)
 class BuiltinCode2(BuiltinCode):
     _immutable_ = True
     fast_natural_arity = 2
-    
+
     def fastcall_2(self, space, w_func, w1, w2):
         try:
             w_result = self.fastfunc_2(space, w1, w2)
 class BuiltinCode3(BuiltinCode):
     _immutable_ = True
     fast_natural_arity = 3
-    
+
     def fastcall_3(self, space, func, w1, w2, w3):
         try:
             w_result = self.fastfunc_3(space, w1, w2, w3)
 class BuiltinCode4(BuiltinCode):
     _immutable_ = True
     fast_natural_arity = 4
-    
+
     def fastcall_4(self, space, func, w1, w2, w3, w4):
         try:
             w_result = self.fastfunc_4(space, w1, w2, w3, w4)
     NOT_RPYTHON_ATTRIBUTES = ['_staticdefs']
 
     instancecache = {}
-    
+
     def __new__(cls, f, app_name=None, unwrap_spec = None,
                 descrmismatch=None, as_classmethod=False):
 
         return fn
 
 
-# 
-# the next gateways are to be used only for 
-# temporary/initialization purposes 
-     
-class interp2app_temp(interp2app): 
+#
+# the next gateways are to be used only for
+# temporary/initialization purposes
+
+class interp2app_temp(interp2app):
     "NOT_RPYTHON"
-    def getcache(self, space): 
+    def getcache(self, space):
         return self.__dict__.setdefault(space, GatewayCache(space))
 
 
-# and now for something completely different ... 
+# and now for something completely different ...
 #
 
 class ApplevelClass:
         from pypy.interpreter.module import Module
         return Module(space, space.wrap(name), self.getwdict(space))
 
-    def wget(self, space, name): 
-        w_globals = self.getwdict(space) 
+    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):
-            if not isinstance(space, ObjSpace): 
+            if not isinstance(space, ObjSpace):
                 raise TypeError("first argument must be a space instance.")
             # redirect if the space handles this specially
             # XXX can this be factored a bit less flow space dependently?
                                                       args.arguments_w)
             return space.call_args(w_func, args)
         def get_function(space):
-            w_func = self.wget(space, name) 
+            w_func = self.wget(space, name)
             return space.unwrap(w_func)
         appcaller = func_with_new_name(appcaller, name)
         appcaller.get_function = get_function
     myfunc = appdef('''myfunc(x, y):
                            return x+y
                     ''')
-    """ 
-    if not isinstance(source, str): 
+    """
+    if not isinstance(source, str):
         source = py.std.inspect.getsource(source).lstrip()
         while source.startswith('@py.test.mark.'):
             # these decorators are known to return the same function
             # object, we may ignore them
             assert '\n' in source
             source = source[source.find('\n') + 1:].lstrip()
-        assert source.startswith("def "), "can only transform functions" 
+        assert source.startswith("def "), "can only transform functions"
         source = source[4:]
     p = source.find('(')
     assert p >= 0

pypy/interpreter/pycode.py

         self._init_flags()
         # Precompute what arguments need to be copied into cellvars
         self._args_as_cellvars = []
-        
+
         if self.co_cellvars:
             argcount = self.co_argcount
             assert argcount >= 0     # annotator hint
 
     def signature(self):
         return self._signature
-    
+
     @classmethod
     def _from_code(cls, space, code, hidden_applevel=False, code_hook=None):
         """ Initialize the code object from a real (CPython) one.
                       list(code.co_cellvars),
                       hidden_applevel, cpython_magic)
 
-    
+
     def _compute_flatcall(self):
         # Speed hack!
         self.fast_natural_arity = eval.Code.HOPELESS
             return
         if self.co_argcount > 0xff:
             return
-        
+
         self.fast_natural_arity = eval.Code.FLATPYCALL | self.co_argcount
 
     def funcrun(self, func, args):
                                       fresh_virtualizable=True)
         args_matched = args.parse_into_scope(None, fresh_frame.fastlocals_w,
                                              func.name,
-                                             sig, func.defs_w)
+                                             sig, func.defs)
         fresh_frame.init_cells()
         return frame.run()
 
         sig = self._signature
         # speed hack
         fresh_frame = jit.hint(frame, access_directly=True,
-                                      fresh_virtualizable=True)        
+                                      fresh_virtualizable=True)
         args_matched = args.parse_into_scope(w_obj, fresh_frame.fastlocals_w,
                                              func.name,
-                                             sig, func.defs_w)
+                                             sig, func.defs)
         fresh_frame.init_cells()
         return frame.run()
 
 
     def fget_co_consts(self, space):
         return space.newtuple(self.co_consts_w)
-    
+
     def fget_co_names(self, space):
         return space.newtuple(self.co_names_w)
 
         return space.newtuple([space.wrap(name) for name in self.co_cellvars])
 
     def fget_co_freevars(self, space):
-        return space.newtuple([space.wrap(name) for name in self.co_freevars])    
+        return space.newtuple([space.wrap(name) for name in self.co_freevars])
 
     def descr_code__eq__(self, w_other):
         space = self.space
         new_inst = mod.get('code_new')
         w        = space.wrap
         tup      = [
-            w(self.co_argcount), 
-            w(self.co_nlocals), 
-            w(self.co_stacksize), 
+            w(self.co_argcount),
+            w(self.co_nlocals),
+            w(self.co_stacksize),
             w(self.co_flags),
-            w(self.co_code), 
-            space.newtuple(self.co_consts_w), 
-            space.newtuple(self.co_names_w), 
-            space.newtuple([w(v) for v in self.co_varnames]), 
+            w(self.co_code),
+            space.newtuple(self.co_consts_w),
+            space.newtuple(self.co_names_w),
+            space.newtuple([w(v) for v in self.co_varnames]),
             w(self.co_filename),
-            w(self.co_name), 
+            w(self.co_name),
             w(self.co_firstlineno),
-            w(self.co_lnotab), 
+            w(self.co_lnotab),
             space.newtuple([w(v) for v in self.co_freevars]),
             space.newtuple([w(v) for v in self.co_cellvars]),
             w(self.magic),

pypy/interpreter/test/test_argument.py

 import py
-from pypy.interpreter.argument import Arguments, ArgumentsForTranslation, ArgErr
-from pypy.interpreter.argument import ArgErrUnknownKwds, ArgErrMultipleValues
-from pypy.interpreter.argument import ArgErrCount, rawshape, Signature
+from pypy.interpreter.argument import (Arguments, ArgumentsForTranslation,
+    ArgErr, ArgErrUnknownKwds, ArgErrMultipleValues, ArgErrCount, rawshape,
+    Signature)
 from pypy.interpreter.error import OperationError
+from pypy.interpreter.function import Defaults
 
 
 class TestSignature(object):
         return list(it)
 
     def listview(self, it):
-        return list(it)        
+        return list(it)
 
     def unpackiterable(self, it):
         return list(it)
 
     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, 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, [])
         py.test.raises(ArgErr, args._match_signature, None, l, Signature(["a"], "*"))
         args = Arguments(space, [])
         l = [None]
-        args._match_signature(None, l, Signature(["a"]), defaults_w=[1])
+        args._match_signature(None, l, Signature(["a"]), defaults=Defaults([1]))
         assert l == [1]
         args = Arguments(space, [])
         l = [None]
                 py.test.raises(ArgErr, args._match_signature, firstarg, l, Signature(["a", "b", "c", "d", "e"], "*"))
                 l = [None, None, None, None, None]
                 args = Arguments(space, arglist, w_stararg=starargs)
-                args._match_signature(firstarg, l, Signature(["a", "b", "c", "d", "e"]), defaults_w=[1])
+                args._match_signature(firstarg, l, Signature(["a", "b", "c", "d", "e"]), defaults=Defaults([1]))
                 assert l == [4, 5, 6, 7, 1]
                 for j in range(len(values)):
                     l = [None] * (j + 1)
             assert len(keywords) == len(keywords_w)
             args = Arguments(space, [1, 2], keywords[:], keywords_w[:], w_starstararg=w_kwds)
             l = [None, None, None]
-            args._match_signature(None, l, Signature(["a", "b", "c"]), defaults_w=[4])
+            args._match_signature(None, l, Signature(["a", "b", "c"]), defaults=Defaults([4]))
             assert l == [1, 2, 3]
             args = Arguments(space, [1, 2], keywords[:], keywords_w[:], w_starstararg=w_kwds)
             l = [None, None, None, None]
-            args._match_signature(None, l, Signature(["a", "b", "b1", "c"]), defaults_w=[4, 5])
+            args._match_signature(None, l, Signature(["a", "b", "b1", "c"]), defaults=Defaults([4, 5]))
             assert l == [1, 2, 4, 3]
             args = Arguments(space, [1, 2], keywords[:], keywords_w[:], w_starstararg=w_kwds)
             l = [None, None, None, None]
-            args._match_signature(None, l, Signature(["a", "b", "c", "d"]), defaults_w=[4, 5])
+            args._match_signature(None, l, Signature(["a", "b", "c", "d"]), defaults=Defaults([4, 5]))
             assert l == [1, 2, 3, 5]
             args = Arguments(space, [1, 2], keywords[:], keywords_w[:], w_starstararg=w_kwds)
             l = [None, None, None, None]
             py.test.raises(ArgErr, args._match_signature, None, l,
-                           Signature(["c", "b", "a", "d"]), defaults_w=[4, 5])
+                           Signature(["c", "b", "a", "d"]), defaults=Defaults([4, 5]))
             args = Arguments(space, [1, 2], keywords[:], keywords_w[:], w_starstararg=w_kwds)
             l = [None, None, None, None]
             py.test.raises(ArgErr, args._match_signature, None, l,
-                           Signature(["a", "b", "c1", "d"]), defaults_w=[4, 5])
+                           Signature(["a", "b", "c1", "d"]), defaults=Defaults([4, 5]))
             args = Arguments(space, [1, 2], keywords[:], keywords_w[:], w_starstararg=w_kwds)
             l = [None, None, None]
             args._match_signature(None, l, Signature(["a", "b"], None, "**"))
         calls = []
 
         def _match_signature(w_firstarg, scope_w, signature,
-                             defaults_w=[], blindargs=0):
+                             defaults=None, blindargs=0):
+            defaults = [] if defaults is None else defaults.getitems()
             calls.append((w_firstarg, scope_w, signature.argnames, signature.has_vararg(),
-                          signature.has_kwarg(), defaults_w, blindargs))
+                          signature.has_kwarg(), defaults, blindargs))
         args._match_signature = _match_signature
 
         scope_w = args.parse_obj(None, "foo", Signature(["a", "b"], None, None))
                             [], 0)
         assert calls[0][1] is scope_w
         calls = []
-            
+
         scope_w = args.parse_obj(None, "foo", Signature(["a", "b"], "args", None),
                                  blindargs=1)
         assert len(calls) == 1
         calls = []
 
         scope_w = args.parse_obj(None, "foo", Signature(["a", "b"], "args", "kw"),
-                             defaults_w=['x', 'y'])
+                             defaults=Defaults(['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", Signature(["a", "b"], "args", "kw"),
-                             defaults_w=['x', 'y'], blindargs=1)
+                             defaults=Defaults(['x', 'y']), blindargs=1)
         assert len(calls) == 1
         assert calls[0] == ("obj", [None, None, None, None], ["a", "b"],
                             True, True,
         calls = []
 
         def _match_signature(w_firstarg, scope_w, signature,
-                             defaults_w=[], blindargs=0):
+                             defaults=None, blindargs=0):
+            defaults = [] if defaults is None else defaults.getitems()
             calls.append((w_firstarg, scope_w, signature.argnames, signature.has_vararg(),
-                          signature.has_kwarg(), defaults_w, blindargs))
+                          signature.has_kwarg(), defaults, blindargs))
         args._match_signature = _match_signature
 
         scope_w = [None, None]
 
         scope_w = [None, None, None, None]
         args.parse_into_scope(None, scope_w, "foo", Signature(["a", "b"], "args", "kw"),
-                              defaults_w=['x', 'y'])
+                              defaults=Defaults(['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]        
+        scope_w = [None, None, None, None]
         args.parse_into_scope("obj", scope_w, "foo", Signature(["a", "b"],
                                                       "args", "kw"),
-                              defaults_w=['x', 'y'])
+                              defaults=Defaults(['x', 'y']))
         assert len(calls) == 1
         assert calls[0] == ("obj", scope_w, ["a", "b"],
                             True, True,
         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        
+        assert args.keywords_w[args.keywords.index('b')] == 3
 
         args = Arguments(space, [1])
         w_args, w_kwds = args.topacked()
     def test_missing_args(self):
         # got_nargs, nkwds, expected_nargs, has_vararg, has_kwarg,
         # defaults_w, missing_args
-        err = ArgErrCount(1, 0, 0, False, False, [], 0)
+        err = ArgErrCount(1, 0, 0, False, False, Defaults([]), 0)
         s = err.getmsg('foo')
         assert s == "foo() takes no argument (1 given)"
-        err = ArgErrCount(0, 0, 1, False, False, [], 1)
+        err = ArgErrCount(0, 0, 1, False, False, Defaults([]), 1)
         s = err.getmsg('foo')
         assert s == "foo() takes exactly 1 argument (0 given)"
-        err = ArgErrCount(3, 0, 2, False, False, [], 0)
+        err = ArgErrCount(3, 0, 2, False, False, Defaults([]), 0)
         s = err.getmsg('foo')
         assert s == "foo() takes exactly 2 arguments (3 given)"
-        err = ArgErrCount(1, 0, 2, True, False, [], 1)
+        err = ArgErrCount(1, 0, 2, True, False, Defaults([]), 1)
         s = err.getmsg('foo')
         assert s == "foo() takes at least 2 arguments (1 given)"
-        err = ArgErrCount(3, 0, 2, True, False, ['a'], 0)
+        err = ArgErrCount(3, 0, 2, True, False, Defaults(['a']), 0)
         s = err.getmsg('foo')
         assert s == "foo() takes at most 2 arguments (3 given)"
-        err = ArgErrCount(0, 1, 2, True, False, ['a'], 1)
+        err = ArgErrCount(0, 1, 2, True, False, Defaults(['a']), 1)
         s = err.getmsg('foo')
         assert s == "foo() takes at least 1 argument (1 given)"
-        err = ArgErrCount(2, 1, 1, False, True, [], 0)
+        err = ArgErrCount(2, 1, 1, False, True, Defaults([]), 0)
         s = err.getmsg('foo')
         assert s == "foo() takes exactly 1 argument (3 given)"
 
 
         args = make_arguments_for_translation(space, [1])
         sig = Signature(['a', 'b', 'c'], None, None)
-        data = args.match_signature(sig, [2, 3])
+        data = args.match_signature(sig, Defaults([2, 3]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
 
         args = make_arguments_for_translation(space, [1], {'c': 3, 'b': 2})
         sig = Signature(['a', 'b', 'c'], None, None)
-        data = args.match_signature(sig, [])
+        data = args.match_signature(sig, Defaults([]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
         args = make_arguments_for_translation(space, [1], {'c': 5})
         sig = Signature(['a', 'b', 'c'], None, None)
-        data = args.match_signature(sig, [2, 3])
+        data = args.match_signature(sig, Defaults([2, 3]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
         args = make_arguments_for_translation(space, [1], {'c': 5, 'd': 7})
         sig = Signature(['a', 'b', 'c'], None, 'kw')
-        data = args.match_signature(sig, [2, 3])
+        data = args.match_signature(sig, Defaults([2, 3]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
         args = make_arguments_for_translation(space, [1,2,3,4,5], {'e': 5, 'd': 7})
         sig = Signature(['a', 'b', 'c'], 'r', 'kw')
-        data = args.match_signature(sig, [2, 3])
+        data = args.match_signature(sig, Defaults([2, 3]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
                                        w_stararg=[1],
                                        w_starstararg={'c': 5, 'd': 7})
         sig = Signature(['a', 'b', 'c'], None, 'kw')
-        data = args.match_signature(sig, [2, 3])
+        data = args.match_signature(sig, Defaults([2, 3]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
                                        w_stararg=[3,4,5],
                                        w_starstararg={'e': 5, 'd': 7})
         sig = Signature(['a', 'b', 'c'], 'r', 'kw')
-        data = args.match_signature(sig, [2, 3])
+        data = args.match_signature(sig, Defaults([2, 3]))
         new_args = args.unmatch_signature(sig, data)
         assert args.unpack() == new_args.unpack()
 
         assert rawshape(args) == (2, ('g', ), True, True)
 
     def test_copy_and_shape(self):
-        space = DummySpace()        
+        space = DummySpace()
         args = ArgumentsForTranslation(space, ['a'], ['x'], [1],
                                        ['w1'], {'y': 'w2'})
         args1 = args.copy()

pypy/interpreter/test/test_gateway.py

 # -*- coding: utf-8 -*-
 
 from pypy.conftest import gettestobjspace
-from pypy.interpreter import gateway
+from pypy.interpreter import gateway, argument
 from pypy.interpreter.gateway import ObjSpace, W_Root
-from pypy.interpreter import argument
+from pypy.interpreter.function import Defaults
 import py
 import sys
 
 class FakeFunc(object):
-
     def __init__(self, space, name):
         self.space = space
         self.name = name
-        self.defs_w = []
+        self.defs = Defaults([])
 
-class TestBuiltinCode: 
+class TestBuiltinCode:
     def test_signature(self):
         def c(space, w_x, w_y, hello_w):
             pass
         w_result = code.funcrun(FakeFunc(self.space, "c"), args)
         assert self.space.eq_w(w_result, w(1020))
 
-class TestGateway: 
+class TestGateway:
 
     def test_app2interp(self):
         w = self.space.wrap
             return a+b
         g3 = gateway.app2interp_temp(noapp_g3, gateway.applevel_temp)
         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 g3(space, w_a, w_b):
             return space.add(w_a, w_b)
         app_g3 = gateway.interp2app_temp(g3)
-        w_app_g3 = space.wrap(app_g3) 
+        w_app_g3 = space.wrap(app_g3)
         assert self.space.eq_w(
-            space.call(w_app_g3, 
+            space.call(w_app_g3,
                        space.newtuple([w('foo'), w('bar')]),
                        space.newdict()),
             w('foobar'))
         assert self.space.eq_w(
             space.call_function(w_app_g3, w('foo'), w('bar')),
             w('foobar'))
-        
+
     def test_interp2app_unwrap_spec(self):
         space = self.space
         w = space.wrap
         def g3(space, w_a, w_b):
-            return space.add(w_a, w_b)        
+            return space.add(w_a, w_b)
         app_g3 = gateway.interp2app_temp(g3,
                                          unwrap_spec=[gateway.ObjSpace,
                                                       gateway.W_Root,
                                                       gateway.W_Root])
-        w_app_g3 = space.wrap(app_g3) 
+        w_app_g3 = space.wrap(app_g3)
         assert self.space.eq_w(
-            space.call(w_app_g3, 
+            space.call(w_app_g3,
                        space.newtuple([w('foo'), w('bar')]),
                        space.newdict()),
             w('foobar'))
         app_A = gateway.interp2app(A.f)
         app_B = gateway.interp2app(B.f)
         assert app_A is not app_B
-        
+
     def test_interp2app_unwrap_spec_nonnegint(self):
         space = self.space
         w = space.wrap
         space = self.space
         w = space.wrap
         def g3_args_w(space, args_w):
-            return space.add(args_w[0], args_w[1])        
+            return space.add(args_w[0], args_w[1])
         app_g3_args_w = gateway.interp2app_temp(g3_args_w,
                                          unwrap_spec=[gateway.ObjSpace,
                                                       'args_w'])
-        w_app_g3_args_w = space.wrap(app_g3_args_w) 
+        w_app_g3_args_w = space.wrap(app_g3_args_w)
         assert self.space.eq_w(
-            space.call(w_app_g3_args_w, 
+            space.call(w_app_g3_args_w,
                        space.newtuple([w('foo'), w('bar')]),
                        space.newdict()),
             w('foobar'))
         def g3_ss(space, s0, s1):
             if s1 is None:
                 return space.wrap(42)
-            return space.wrap(s0+s1)       
+            return space.wrap(s0+s1)
         app_g3_ss = gateway.interp2app_temp(g3_ss,
                                          unwrap_spec=[gateway.ObjSpace,
                                                       str, 'str_or_None'])
-        w_app_g3_ss = space.wrap(app_g3_ss) 
+        w_app_g3_ss = space.wrap(app_g3_ss)
         assert self.space.eq_w(
-            space.call(w_app_g3_ss, 
+            space.call(w_app_g3_ss,
                        space.newtuple([w('foo'), w('bar')]),
                        space.newdict()),
             w('foobar'))
         space = self.space
         w = space.wrap
         def g3_if(space, i0, f1):
-            return space.wrap(i0+f1)       
+            return space.wrap(i0+f1)
         app_g3_if = gateway.interp2app_temp(g3_if,
                                          unwrap_spec=[gateway.ObjSpace,
                                                       int,float])
-        w_app_g3_if = space.wrap(app_g3_if) 
+        w_app_g3_if = space.wrap(app_g3_if)
         assert self.space.eq_w(
-            space.call(w_app_g3_if, 
+            space.call(w_app_g3_if,
                        space.newtuple([w(1), w(1.0)]),
                        space.newdict()),
             w(2.0))
         w_app_g3_ll = space.wrap(app_g3_ll)
         w_big = w(gateway.r_longlong(10**10))
         assert space.eq_w(
-            space.call(w_app_g3_ll, 
+            space.call(w_app_g3_ll,
                        space.newtuple([w_big]),
                        space.newdict()),
             w(gateway.r_longlong(3 * 10**10)))
         app_g3_idx = gateway.interp2app_temp(g3_idx,
                                          unwrap_spec=[gateway.ObjSpace,
                                                       'index'])
-        w_app_g3_idx = space.wrap(app_g3_idx) 
+        w_app_g3_idx = space.wrap(app_g3_idx)
         assert space.eq_w(
             space.call_function(w_app_g3_idx, w(123)),
             w(124))
                                                       int])
         w_app_g3_i = space.wrap(app_g3_i)
         assert space.eq_w(space.call_function(w_app_g3_i,w(1)),w(1))
-        assert space.eq_w(space.call_function(w_app_g3_i,w(1L)),w(1))        
+        assert space.eq_w(space.call_function(w_app_g3_i,w(1L)),w(1))
         raises(gateway.OperationError,space.call_function,w_app_g3_i,w(sys.maxint*2))
         raises(gateway.OperationError,space.call_function,w_app_g3_i,w(None))
         raises(gateway.OperationError,space.call_function,w_app_g3_i,w("foo"))
         raises(gateway.OperationError,space.call_function,w_app_g3_s,w(None))
         raises(gateway.OperationError,space.call_function,w_app_g3_s,w(1))
         raises(gateway.OperationError,space.call_function,w_app_g3_s,w(1.0))
-        
+
         app_g3_f = gateway.interp2app_temp(g3_id,
                                          unwrap_spec=[gateway.ObjSpace,
                                                       float])
         w_app_g3_f = space.wrap(app_g3_f)
         assert space.eq_w(space.call_function(w_app_g3_f,w(1.0)),w(1.0))
         assert space.eq_w(space.call_function(w_app_g3_f,w(1)),w(1.0))
-        assert space.eq_w(space.call_function(w_app_g3_f,w(1L)),w(1.0))        
+        assert space.eq_w(space.call_function(w_app_g3_f,w(1L)),w(1.0))
         raises(gateway.OperationError,space.call_function,w_app_g3_f,w(None))
         raises(gateway.OperationError,space.call_function,w_app_g3_f,w("foo"))
 
             called.append(w_func)
             return fastcall_2(space, w_func, w_a, w_b)
 
-        w_app_f.code.fastcall_2 = witness_fastcall_2    
-    
+        w_app_f.code.fastcall_2 = witness_fastcall_2
+
         w_res = space.appexec([w_app_f, w_3], """(f, x):
         class A(object):
            m = f # not a builtin function, so works as method
         """)
 
         assert space.is_true(w_res)
-        assert called == [w_app_f, w_app_f]       
-        
+        assert called == [w_app_f, w_app_f]
+
     def test_plain(self):
         space = self.space
 
 
         w_res = space.call_args(w_g, args)
         assert space.is_true(space.eq(w_res, space.wrap(('g', -1, 0))))
-        
+
         w_self = space.wrap('self')
 
         args0 = argument.Arguments(space, [space.wrap(0)])
 
 
 class TestPassThroughArguments:
-    
+
     def test_pass_trough_arguments0(self):
         space = self.space
 
         called = []
-        
+
         def f(space, __args__):
             called.append(__args__)
             a_w, _ = __args__.unpack()
 
         w_res = space.call_args(w_f, args)
         assert space.is_true(space.eq(w_res, space.wrap(('f', 7))))
-        
+
         # white-box check for opt
         assert called[0] is args
 
         space = self.space
 
         called = []
-        
+
         def g(space, w_self, __args__):
             called.append(__args__)
             a_w, _ = __args__.unpack()
         w_res = space.call_args(w_g, args)
         assert space.is_true(space.eq(w_res, space.wrap(('g', 'self', 0))))
         # no opt in this case
-        assert len(called) == 2      
+        assert len(called) == 2
         assert called[0] == 'funcrun'
         called = []
 
         w_res = space.call_function(w_g, w_self)
         assert space.is_true(space.eq(w_res, space.wrap(('g', 'self'))))
         assert len(called) == 1
-        assert isinstance(called[0], argument.Arguments)        
+        assert isinstance(called[0], argument.Arguments)
         called = []
-        
+
         w_res = space.appexec([w_g], """(g):
         return g('self', 11)
         """)
         assert space.is_true(space.eq(w_res, space.wrap(('g', 'self', 11))))
         assert len(called) == 1
-        assert isinstance(called[0], argument.Arguments)                
+        assert isinstance(called[0], argument.Arguments)
         called = []
 
         w_res = space.appexec([w_g], """(g):
         clash = dict.__new__.func_code.co_varnames[0]
 
         dict(**{clash: 33})
-        dict.__new__(dict, **{clash: 33})        
+        dict.__new__(dict, **{clash: 33})
 
     def test_dict_init(self):
         d = {}
         clash = dict.update.func_code.co_varnames[0]
 
         d.update(**{clash: 33})
-        dict.update(d, **{clash: 33})        
-        
+        dict.update(d, **{clash: 33})
+

pypy/interpreter/test/test_main.py

 from cStringIO import StringIO
 
-import py 
+import py
 from pypy.tool.udir import udir
 from pypy.interpreter.baseobjspace import OperationError
 from pypy.interpreter import main
 testresultoutput = '11\n'
 
 def checkoutput(space, expected_output,f,*args):
-    w_oldout = space.sys.get('stdout') 
+    w_oldout = space.sys.get('stdout')
     capturefn = udir.join('capturefile')
-    capturefile = capturefn.open('w') 
+    capturefile = capturefn.open('w')
     w_sys = space.sys.getmodule('sys')
     space.setattr(w_sys, space.wrap("stdout"), space.wrap(capturefile))
     try:
         f(*(args + (space,)))
     finally:
         space.setattr(w_sys, space.wrap("stdout"), w_oldout)
-    capturefile.close() 
+    capturefile.close()
     assert capturefn.read(mode='rU') == expected_output
 
 testfn = udir.join('tmp_hello_world.py')
 testmodule = 'tmp_hello_module'
 testpackage = 'tmp_package'
 
-class TestMain: 
+class TestMain:
     def setup_class(cls):
         testfn.write(testcode, 'w')
         udir.join(testmodule + '.py').write(testmodulecode, 'w')

pypy/module/cpyext/eval.py

     w_code = compiling.compile(space, w_source, filename, mode)
     return compiling.eval(space, w_code, w_globals, w_locals)
 
+@cpython_api([CONST_STRING], rffi.INT_real, error=-1)
+def PyRun_SimpleString(space, command):
+    """This is a simplified interface to PyRun_SimpleStringFlags() below,
+    leaving the PyCompilerFlags* argument set to NULL."""
+    command = rffi.charp2str(command)
+    run_string(space, command, "<string>", Py_file_input,
+               space.w_None, space.w_None)
+    return 0
+
 @cpython_api([CONST_STRING, rffi.INT_real,PyObject, PyObject], PyObject)
 def PyRun_String(space, source, start, w_globals, w_locals):
     """This is a simplified interface to PyRun_StringFlags() below, leaving

pypy/module/cpyext/stubs.py

     "???" as the filename."""
     raise NotImplementedError
 
-@cpython_api([rffi.CCHARP], rffi.INT_real, error=-1)
-def PyRun_SimpleString(space, command):
-    """This is a simplified interface to PyRun_SimpleStringFlags() below,
-    leaving the PyCompilerFlags* argument set to NULL."""
-    raise NotImplementedError
-
 @cpython_api([rffi.CCHARP, PyCompilerFlags], rffi.INT_real, error=-1)
 def PyRun_SimpleStringFlags(space, command, flags):
     """Executes the Python source code from command in the __main__ module

pypy/module/cpyext/test/test_eval.py

 
         assert space.int_w(w_res) == 10
 
+    def test_run_simple_string(self, space, api):
+        def run(code):
+            buf = rffi.str2charp(code)
+            try:
+                return api.PyRun_SimpleString(buf)
+            finally:
+                rffi.free_charp(buf)
+
+        assert 0 == run("42 * 43")
+        
+        assert -1 == run("4..3 * 43")
+        
+        assert api.PyErr_Occurred()
+        api.PyErr_Clear()
+        
     def test_run_string(self, space, api):
         def run(code, start, w_globals, w_locals):
             buf = rffi.str2charp(code)

pypy/module/pypyjit/test_pypy_c/test_pypy_c_new.py

         log = self.run(main, [1000], threshold=400)
         assert log.result == 1000 * 999 / 2
         loop, = log.loops_by_filename(self.filepath)
-        assert loop.match_by_id('getitem', opcode='BINARY_SUBSCR', expected_src="""
-            i43 = int_lt(i25, 0)
-            guard_false(i43, descr=<Guard9>)
-            i44 = int_ge(i25, i39)
-            guard_false(i44, descr=<Guard10>)
-            i45 = int_mul(i25, i33)
+        assert loop.match("""
+            i16 = int_ge(i11, i12)
+            guard_false(i16, descr=<Guard3>)
+            i17 = int_mul(i11, i14)
+            i18 = int_add(i15, i17)
+            i20 = int_add(i11, 1)
+            i21 = force_token()
+            setfield_gc(p4, i20, descr=<.* .*W_AbstractSeqIterObject.inst_index .*>)
+            i23 = int_lt(i18, 0)
+            guard_false(i23, descr=<Guard4>)
+            i25 = int_ge(i18, i9)
+            guard_false(i25, descr=<Guard5>)
+            i26 = int_mul(i18, i10)
+            i27 = int_add_ovf(i7, i26)
+            guard_no_overflow(descr=<Guard6>)
+            --TICK--
+            jump(p0, p1, p2, p3, p4, p5, p6, i27, i18, i9, i10, i20, i12, p13, i14, i15, descr=<Loop0>)
         """)
-        assert loop.match_by_id('for', opcode='FOR_ITER', expected_src="""
-            i23 = int_ge(i11, i12)
-            guard_false(i23, descr=<Guard3>)
-            i24 = int_mul(i11, i14)
-            i25 = int_add(i15, i24)
-            i27 = int_add(i11, 1)
-            # even if it's a the end of the loop, the jump still belongs to
-            # the FOR_ITER opcode
-            jump(p0, p1, p2, p3, p4, p5, p6, i46, i25, i39, i33, i27, i12, p13, i14, i15, p16, i17, i18, p19, p20, i21, i22, descr=<Loop0>)
-        """)
-
 
     def test_exception_inside_loop_1(self):
         def main(n):
         where x and y can be either constants or variables. There are cases in
         which the second guard is proven to be always true.
         """
-        
+
         for a, b, res, opt_expected in (('2000', '2000', 20001000, True),
                                         ( '500',  '500', 15001500, True),
                                         ( '300',  '600', 16001700, False),
         test only checks that we get the expected result, not that any
         optimization has been applied.
         """
-        ops = ('<', '>', '<=', '>=', '==', '!=')        
+        ops = ('<', '>', '<=', '>=', '==', '!=')
         for op1 in ops:
             for op2 in ops:
                 for a,b in ((500, 500), (300, 600)):
         test only checks that we get the expected result, not that any
         optimization has been applied.
         """
-        ops = ('<', '>', '<=', '>=', '==', '!=')        
+        ops = ('<', '>', '<=', '>=', '==', '!=')
         for op1 in ops:
             for op2 in ops:
                 for a,b in ((500, 500), (300, 600)):
             while i < 640 * 480:
                 assert len(img) == 3*350*480
                 assert len(intimg) == 640*480
-                assert i >= 0
                 l = l + img[i]
                 intimg[i] = (intimg[i-640] + l)
                 i += 1
         assert loop.match("""
             i13 = int_lt(i8, 307200)
             guard_true(i13, descr=<Guard3>)
-        # the bound check guard on img has been killed (thanks to the 1st and 2nd asserts)
+        # the bound check guard on img has been killed (thanks to the asserts)
             i14 = getarrayitem_raw(i10, i8, descr=<.*ArrayNoLengthDescr>)
             i15 = int_add_ovf(i9, i14)
             guard_no_overflow(descr=<Guard4>)
             i17 = int_sub(i8, 640)
-        # the bound check guard on intimg has been killed (thanks to the 3rd assert)
+        # the bound check guard on intimg has been killed (thanks to the asserts)
             i18 = getarrayitem_raw(i11, i17, descr=<.*ArrayNoLengthDescr>)
             i19 = int_add_ovf(i18, i15)
             guard_no_overflow(descr=<Guard5>)
             --TICK--
             jump(p0, p1, p2, p3, p4, p5, p6, p7, i28, i15, i10, i11, descr=<Loop0>)
         """)
+
+    def test_func_defaults(self):
+        def main(n):
+            i = 1
+            while i < n:
+                i += len(xrange(i)) / i
+            return i
+
+        log = self.run(main, [10000])
+        assert log.result == 10000
+        loop, = log.loops_by_filename(self.filepath)
+        assert loop.match("""
+            i10 = int_lt(i5, i6)
+            guard_true(i10, descr=<Guard3>)
+            # This can be improved if the JIT realized the lookup of i5 produces
+            # a constant and thus can be removed entirely
+            i12 = int_sub(i5, 1)
+            i13 = uint_floordiv(i12, i7)
+            i15 = int_add(i13, 1)
+            i17 = int_lt(i15, 0)
+            guard_false(i17, descr=<Guard4>)
+            i18 = int_floordiv(i15, i5)
+            i19 = int_xor(i15, i5)
+            i20 = int_mod(i15, i5)
+            i21 = int_is_true(i20)
+            i22 = int_add_ovf(i5, i18)
+            guard_no_overflow(descr=<Guard5>)
+            --TICK--
+            jump(p0, p1, p2, p3, p4, i22, i6, i7, p8, p9, descr=<Loop0>)
+        """)

pypy/objspace/std/bytearrayobject.py

 from pypy.interpreter import gateway
 from pypy.interpreter.argument import Signature
 from pypy.interpreter.buffer import RWBuffer
+from pypy.interpreter.function import Defaults
 from pypy.objspace.std.bytearraytype import (
     makebytearraydata_w, getbytevalue,
     new_bytearray
 registerimplementation(W_BytearrayObject)
 
 init_signature = Signature(['source', 'encoding', 'errors'], None, None)
-init_defaults = [None, None, None]
+init_defaults = Defaults([None, None, None])
 
 def init__Bytearray(space, w_bytearray, __args__):
     # this is on the silly side

pypy/objspace/std/dictmultiobject.py

 from pypy.objspace.std.model import registerimplementation, W_Object
 from pypy.objspace.std.register_all import register_all
 from pypy.interpreter import gateway
+from pypy.interpreter.argument import Signature
 from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.argument import Signature
+from pypy.interpreter.function import Defaults
 from pypy.module.__builtin__.__init__ import BUILTIN_TO_INDEX, OPTIMIZED_BUILTINS
 
 from pypy.rlib.objectmodel import r_dict, we_are_translated
         assert self.r_dict_content is None
         self.r_dict_content = r_dict(self.space.eq_w, self.space.hash_w)
         return self.r_dict_content
-        
+
 
     def initialize_content(w_self, list_pairs_w):
         for w_k, w_v in list_pairs_w:
 
     def impl_fallback_delitem(self, w_key):
         del self.r_dict_content[w_key]
-        
+
     def impl_fallback_length(self):
         return len(self.r_dict_content)
 
     def __init__(self, space):
         self.space = space
         self.content = {}
-        
+
     def impl_setitem(self, w_key, w_value):
         space = self.space
         if space.is_w(space.type(w_key), space.w_str):
             raise KeyError
         else:
             self._as_rdict().impl_fallback_delitem(w_key)
-        
+
     def impl_length(self):
         return len(self.content)
 
 
 
 init_signature = Signature(['seq_or_map'], None, 'kwargs')
-init_defaults = [None]
+init_defaults = Defaults([None])
 
 def update1(space, w_dict, w_data):
     if space.findattr(w_data, space.wrap("keys")) is None:
         w_dict.delitem(w_key)
     except KeyError:
         space.raise_key_error(w_key)
-    
+
 def len__DictMulti(space, w_dict):
     return space.wrap(w_dict.length())
 
     return space.w_True
 
 def characterize(space, w_a, w_b):
-    """ (similar to CPython) 
+    """ (similar to CPython)
     returns the smallest key in acontent for which b's value is different or absent and this value """
     w_smallest_diff_a_key = None
     w_its_value = None
     w_rightdiff, w_rightval = characterize(space, w_right, w_left)
     if w_rightdiff is None:
         # w_leftdiff is not None, w_rightdiff is None
-        return space.w_True 
+        return space.w_True
     w_res = space.lt(w_leftdiff, w_rightdiff)
     if (not space.is_true(w_res) and
-        space.eq_w(w_leftdiff, w_rightdiff) and 
+        space.eq_w(w_leftdiff, w_rightdiff) and
         w_rightval is not None):
         w_res = space.lt(w_leftval, w_rightval)
     return w_res

pypy/objspace/std/fake.py

         frame = func.space.createframe(self, func.w_func_globals,
                                         func.closure)
         sig = self.signature()
-        scope_w = args.parse_obj(None, func.name, sig, func.defs_w)
+        scope_w = args.parse_obj(None, func.name, sig, func.defs.getitems())
         frame.setfastscope(scope_w)
         return frame.run()
-    
+
 
 class CPythonFakeFrame(eval.Frame):
 

pypy/objspace/std/listobject.py

 
 from pypy.objspace.std import slicetype
 from pypy.interpreter import gateway, baseobjspace
+from pypy.interpreter.function import Defaults
 from pypy.rlib.listsort import TimSort
 from pypy.interpreter.argument import Signature
 
 
 
 init_signature = Signature(['sequence'], None, None)
-init_defaults = [None]
+init_defaults = Defaults([None])
 
 def init__List(space, w_list, __args__):
     # this is on the silly side

pypy/objspace/std/setobject.py

 from pypy.interpreter.error import OperationError
 from pypy.interpreter import gateway
 from pypy.interpreter.argument import Signature
+from pypy.interpreter.function import Defaults
 from pypy.objspace.std.settype import set_typedef as settypedef
 from pypy.objspace.std.frozensettype import frozenset_typedef as frozensettypedef
 
     # make sure that Base is used for Set and Frozenset in multimethod
     # declarations
     @classmethod
-    def is_implementation_for(cls, typedef): 
+    def is_implementation_for(cls, typedef):
         if typedef is frozensettypedef or typedef is settypedef:
             assert cls is W_BaseSetObject
             return True
 cmp__Frozenset_frozensettypedef = cmp__Set_settypedef
 
 init_signature = Signature(['some_iterable'], None, None)
-init_defaults = [None]
+init_defaults = Defaults([None])
 def init__Set(space, w_set, __args__):
     w_iterable, = __args__.parse_obj(
             None, 'set',
                 del currently_in_repr[set_id]
             except:
                 pass
-""", filename=__file__) 
+""", filename=__file__)
 
 setrepr = app.interphook("setrepr")
 

pypy/rpython/callparse.py

 from pypy.interpreter.argument import ArgumentsForTranslation, ArgErr
+from pypy.interpreter.function import Defaults
 from pypy.annotation import model as annmodel
 from pypy.rpython import rtuple
 from pypy.rpython.error import TyperError
         for x in graph.defaults:
             defs_h.append(ConstHolder(x))
     try:
-        holders = arguments.match_signature(signature, defs_h)
+        holders = arguments.match_signature(signature, Defaults(defs_h))
     except ArgErr, e:
         raise TyperError, "signature mismatch: %s" % e.getmsg(graph.name)
 
             v = self._emit(repr, hop)
             cache[repr] = v
             return v
-    
+
 
 class VarHolder(Holder):
 
         assert self.is_tuple()
         n = len(self.s_obj.items)
         return tuple([ItemHolder(self, i) for i in range(n)])
-        
+
     def _emit(self, repr, hop):
         return hop.inputarg(repr, arg=self.num)
 
 
     def type(self, item):
         return type(item)
-    
+

pypy/tool/release/force-builds.py

 ]
 
 def main():
+    #XXX: handle release tags
+    #XXX: handle validity checks
     branch = sys.argv[1]
-    if (not branch.startswith('/branch/') and not branch.startswith('/tag/') and
-        not branch.startswith('/release/')):
-        branch = '/branch/' + branch
-
     lock = defer.DeferredLock()
     requests = []
     def ebList(err):

pypy/translator/geninterplevel.py

     self.initcode.append1('%s = %s(%r)' % (
         name, unique, repr(value) ) )
 
-def bltinmod_helper(self, mod):    
+def bltinmod_helper(self, mod):
     name = self.uniquename("mod_%s" % mod.__name__)
     unique = self.uniquenameofprebuilt("bltinmod_helper", bltinmod_helper)
     self.initcode.append1(
         self.modname = self.trans_funcname(modname or
                         uniquemodulename(entrypoint))
         self.moddict = moddict # the dict if we translate a module
-        
+
         def late_OperationError():
             self.initcode.append1(
                 'from pypy.interpreter.error import OperationError as gOperationError')
             def _issubtype(cls1, cls2):
                 raise TypeError, "this dummy should *not* be reached"
             __builtin__._issubtype = _issubtype
-        
+
         class bltinstub: