[pypy-svn] r4909 - in pypy/branch/src-newobjectmodel/pypy: interpreter objspace objspace/std
arigo at codespeak.net
arigo at codespeak.net
Fri Jun 4 16:16:46 CEST 2004
Author: arigo
Date: Fri Jun 4 16:16:45 2004
New Revision: 4909
Added:
pypy/branch/src-newobjectmodel/pypy/objspace/std/stdtypedef.py
Modified:
pypy/branch/src-newobjectmodel/pypy/interpreter/baseobjspace.py
pypy/branch/src-newobjectmodel/pypy/interpreter/function.py
pypy/branch/src-newobjectmodel/pypy/objspace/descroperation.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/boolobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/booltype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/cpythonobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/default.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/dictobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/dicttype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/floatobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/floattype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/intobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/inttype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/iterobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/itertype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/listobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/listtype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/multimethod.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/noneobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/nonetype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/objectobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/objecttype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/objspace.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/register_all.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/sliceobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/slicetype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/stringobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/stringtype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/tupleobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/tupletype.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/typeobject.py
pypy/branch/src-newobjectmodel/pypy/objspace/std/typetype.py
pypy/branch/src-newobjectmodel/pypy/objspace/trivial.py
Log:
First round at fixing the standard object space to adapt it to the new,
descriptor-based object model.
Modified: pypy/branch/src-newobjectmodel/pypy/interpreter/baseobjspace.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/interpreter/baseobjspace.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/interpreter/baseobjspace.py Fri Jun 4 16:16:45 2004
@@ -161,7 +161,8 @@
def call_function(self, w_func, *args_w, **kw_w):
w_kw = self.newdict([(self.wrap(k), w_v) for k, w_v in kw_w.iteritems()])
- return self.call(w_func, self.newtuple(list(args_w)), w_kw)
+ w_args = self.newtuple(list(args_w))
+ return self.call(w_func, w_args, w_kw)
def call_method(self, w_obj, methname, *arg_w, **kw_w):
w_meth = self.getattr(w_obj, self.wrap(methname))
Modified: pypy/branch/src-newobjectmodel/pypy/interpreter/function.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/interpreter/function.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/interpreter/function.py Fri Jun 4 16:16:45 2004
@@ -47,12 +47,12 @@
# We try to give error messages following CPython's, which are
# very informative.
#
- if w_kwds is None or not space.is_true(w_kwds):
- w_kwargs = space.newdict([])
- else:
- # space.is_true() above avoids infinite recursion copy<->parse_args
- w_kwargs = space.call_method(w_kwds, "copy")
-
+ if w_kwds is not None:
+ if space.is_true(w_kwds):
+ # space.is_true() avoids infinite recursion copy<->parse_args
+ w_kwargs = space.call_method(w_kwds, "copy")
+ else:
+ w_kwargs = None
co_argcount = len(argnames) # expected formal arguments, without */**
# put as many positional input arguments into place as available
@@ -61,17 +61,19 @@
input_argcount = len(scope_w)
# check that no keyword argument conflicts with these
- for name in argnames[:input_argcount]:
- w_name = space.wrap(name)
- if space.is_true(space.contains(w_kwargs, w_name)):
- self.raise_argerr_multiple_values(name)
+ if w_kwargs is not None:
+ for name in argnames[:input_argcount]:
+ w_name = space.wrap(name)
+ if space.is_true(space.contains(w_kwargs, w_name)):
+ self.raise_argerr_multiple_values(name)
if input_argcount < co_argcount:
# not enough args, fill in kwargs or defaults if exists
def_first = co_argcount - len(self.defs_w)
for i in range(input_argcount, co_argcount):
w_name = space.wrap(argnames[i])
- if space.is_true(space.contains(w_kwargs, w_name)):
+ if (w_kwargs is not None and
+ space.is_true(space.contains(w_kwargs, w_name))):
scope_w.append(space.getitem(w_kwargs, w_name))
space.delitem(w_kwargs, w_name)
elif i >= def_first:
@@ -86,11 +88,15 @@
self.raise_argerr(w_args, w_kwds, True)
# collect extra keyword arguments into the **kwarg
- if kwargname is not None:
- # XXX this doesn't check that the keys of kwargs are strings
- scope_w.append(w_kwargs)
- elif space.is_true(w_kwargs):
- self.raise_argerr_unknown_kwds(w_kwds)
+ if w_kwargs:
+ if kwargname is not None:
+ # XXX this doesn't check that the keys of kwargs are strings
+ scope_w.append(w_kwargs)
+ elif space.is_true(w_kwargs):
+ self.raise_argerr_unknown_kwds(w_kwds)
+ else:
+ if kwargname is not None:
+ scope_w.append(space.newdict([]))
return scope_w
# helper functions to build error message for the above
@@ -170,7 +176,7 @@
def descr_function_call(self, *args_w, **kwds_w):
# XXX refactor to avoid unwrapping and rewrapping all around
space = self.space
- return self.call(space.newtuple(args_w),
+ return self.call(space.newtuple(list(args_w)),
space.newdict([(space.wrap(key), w_item)
for key, w_item in kwds_w.items()]))
@@ -211,6 +217,6 @@
def descr_method_call(self, *args_w, **kwds_w):
# XXX refactor to avoid unwrapping and rewrapping all around
space = self.space
- return self.call(space.newtuple(args_w),
+ return self.call(space.newtuple(list(args_w)),
space.newdict([(space.wrap(key), w_item)
for key, w_item in kwds_w.items()]))
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/descroperation.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/descroperation.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/descroperation.py Fri Jun 4 16:16:45 2004
@@ -86,12 +86,15 @@
w_impl = space.get(w_descr, w_obj, space.type(w_obj))
return space.call_function(w_impl, *args_w, **kwargs_w)
+ def unwrap_builtin(self, w_obj):
+ return w_obj # hook for hack by TrivialObjSpace
+
def call(space, w_obj, w_args, w_kwargs):
#print "call %r, %r, %r" %(w_obj, w_args, w_kwargs)
w_descr = space.lookup(w_obj, '__call__')
if w_descr is None:
raise OperationError(space.w_TypeError,
- space.wrap('object is not callable'))
+ space.wrap('object %r is not callable' % (w_obj,)))
return space.get_and_call(w_descr, w_obj, w_args, w_kwargs)
def get(space,w_descr,w_obj,w_type):
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/boolobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/boolobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/boolobject.py Fri Jun 4 16:16:45 2004
@@ -1,18 +1,9 @@
-"""
-Reviewed 03-06-21
-There are no new methods here, since everything is inherited
-from int, except:
-
-__repr__ tested, OK
-"""
-
from pypy.objspace.std.objspace import *
-from booltype import W_BoolType
import intobject
class W_BoolObject(W_Object):
- statictype = W_BoolType
+ from booltype import bool_typedef as typedef
def __init__(w_self, space, boolval):
W_Object.__init__(w_self, space)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/booltype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/booltype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/booltype.py Fri Jun 4 16:16:45 2004
@@ -1,34 +1,15 @@
-"""
-Reviewed 03-06-21
-"""
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.inttype import int_typedef
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
-from inttype import W_IntType
-
-class W_BoolType(W_TypeObject):
-
- typename = 'bool'
- staticbases = (W_IntType,)
-
-registerimplementation(W_BoolType)
-
-def type_new__BoolType_BoolType(space, w_basetype, w_booltype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- if len(args) == 0:
- return space.w_False, True
- elif len(args) == 1:
- arg = args[0]
- if space.is_true(arg):
- return space.w_True, True
- else:
- return space.w_False, True
+def descr__new__(space, w_booltype, w_obj=None):
+ if space.is_true(w_obj):
+ return space.w_True
else:
- raise OperationError(space.w_TypeError,
- space.wrap("bool() takes at most 1 argument"))
+ return space.w_False
+
+# ____________________________________________________________
-register_all(vars())
+bool_typedef = StdTypeDef("bool", [int_typedef],
+ __new__ = newmethod(descr__new__),
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/cpythonobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/cpythonobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/cpythonobject.py Fri Jun 4 16:16:45 2004
@@ -23,8 +23,7 @@
def __repr__(w_self):
""" representation for debugging purposes """
- return "wrap(%r)" % (w_self.cpyobj,)
-
+ return "cpyobj(%r)" % (w_self.cpyobj,)
registerimplementation(W_CPythonObject)
@@ -216,8 +215,8 @@
raise ValueError, '_arity too large'
arglist = [W_CPythonObject] + [W_ANY]*(_arity-1)
- if _name == 'getattr': _name = 'getattribute' # XXX hack
- multimethod = getattr(StdObjSpace, _name)
+ #if _name == 'getattr': _name = 'getattribute' # XXX hack
+ multimethod = getattr(StdObjSpace.MM, _name)
multimethod.register(cpython_f, *arglist)
if len(multimethod.specialnames) > 1 and _arity == 2:
@@ -302,7 +301,7 @@
wrap_exception(space)
return space.wrap(result)
-def call__CPython_ANY_ANY(space, w_obj, w_arguments, w_keywords):
+def call__CPython(space, w_obj, w_arguments, w_keywords):
# XXX temporary hack similar to objspace.trivial.call()
callable = space.unwrap(w_obj)
if hasattr(callable, 'pypy_call'):
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/default.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/default.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/default.py Fri Jun 4 16:16:45 2004
@@ -18,11 +18,12 @@
# __nonzero__ falls back to __len__
def is_true__Object(space, w_obj):
- try:
- w_len = space.len.perform_call((w_obj,))
- except FailedToImplement:
- return True # everything is True unless otherwise specified
- return space.is_true(space.ne(w_len, space.newint(0)))
+ w_descr = space.lookup(w_obj, '__len__')
+ if w_descr is None:
+ return True
+ else:
+ w_len = space.get_and_call_function(w_descr, w_obj)
+ return space.is_true(w_len)
# in-place operators fall back to their non-in-place counterpart
@@ -31,160 +32,160 @@
def default_inplace(space, w_1, w_2, baseop=_name[8:]):
op = getattr(space, baseop)
return op(w_1, w_2)
- getattr(StdObjSpace, _name).register(default_inplace,
- W_Object, W_ANY)
+ getattr(StdObjSpace.MM, _name).register(default_inplace,
+ W_Object, W_ANY)
# '__get__(descr, inst, cls)' returns 'descr' by default
-def get__Object_ANY_ANY(space, w_descr, w_inst, w_cls):
- return w_descr
+#def get__Object_ANY_ANY(space, w_descr, w_inst, w_cls):
+# return w_descr
-def is_data_descr__Object(space, w_descr):
- return 0
+#def is_data_descr__Object(space, w_descr):
+# return 0
# give objects some default attributes and a default way to complain
# about missing attributes
-def getattribute__Object_ANY(space, w_obj, w_attr):
- # XXX build a nicer error message along these lines:
- #w_type = space.type(w_obj)
- #w_typename = space.getattr(w_type, space.wrap('__name__'))
- #...
-
- w_type = space.type(w_obj)
- if space.is_true(space.eq(w_attr, space.wrap('__class__'))):
- return w_type
-
- # 1) look for descriptor
- # 2) if data descriptor, call it
- # 3) check __dict__
- # 4) if present, return that
- # 5) if descriptor found in 2), call that
- # 6) raise AttrbuteError
-
- w_descr = None
-
- from typeobject import W_TypeObject
- if isinstance(w_type, W_TypeObject): # XXX must always be true at some point
- try:
- w_descr = w_type.lookup(w_attr)
- except KeyError:
- pass
- else:
- if space.is_data_descr(w_descr):
- return space.get(w_descr, w_obj, w_type) # XXX 3rd arg is wrong
+##def getattribute__Object_ANY(space, w_obj, w_attr):
+## # XXX build a nicer error message along these lines:
+## #w_type = space.type(w_obj)
+## #w_typename = space.getattr(w_type, space.wrap('__name__'))
+## #...
+
+## w_type = space.type(w_obj)
+## if space.is_true(space.eq(w_attr, space.wrap('__class__'))):
+## return w_type
+
+## # 1) look for descriptor
+## # 2) if data descriptor, call it
+## # 3) check __dict__
+## # 4) if present, return that
+## # 5) if descriptor found in 2), call that
+## # 6) raise AttrbuteError
+
+## w_descr = None
+
+## from typeobject import W_TypeObject
+## if isinstance(w_type, W_TypeObject): # XXX must always be true at some point
+## try:
+## w_descr = w_type.lookup(w_attr)
+## except KeyError:
+## pass
+## else:
+## if space.is_data_descr(w_descr):
+## return space.get(w_descr, w_obj, w_type) # XXX 3rd arg is wrong
- try:
- w_dict = space.getdict(w_obj)
- except OperationError, e:
- if not e.match(space, space.w_TypeError): # 'unsupported type for getdict'
- raise
- else:
- if space.is_true(space.eq(w_attr, space.wrap('__dict__'))):
- return w_dict
- try:
- w_value = space.getitem(w_dict, w_attr)
- except OperationError, e:
- if not e.match(space, space.w_KeyError):
- raise
- else:
- return w_value # got a value from 'obj.__dict__[attr]'
+## try:
+## w_dict = space.getdict(w_obj)
+## except OperationError, e:
+## if not e.match(space, space.w_TypeError): # 'unsupported type for getdict'
+## raise
+## else:
+## if space.is_true(space.eq(w_attr, space.wrap('__dict__'))):
+## return w_dict
+## try:
+## w_value = space.getitem(w_dict, w_attr)
+## except OperationError, e:
+## if not e.match(space, space.w_KeyError):
+## raise
+## else:
+## return w_value # got a value from 'obj.__dict__[attr]'
- if w_descr is not None:
- return space.get(w_descr, w_obj, w_type)
+## if w_descr is not None:
+## return space.get(w_descr, w_obj, w_type)
- raise OperationError(space.w_AttributeError, w_attr)
+## raise OperationError(space.w_AttributeError, w_attr)
# set attributes, complaining about read-only ones --
# a more declarative way to define attributes would be welcome
-def setattr__Object_ANY_ANY(space, w_obj, w_attr, w_value):
-
- # 1) look for descriptor
- # 2) if data descriptor, call it
- # 3) try to set item in __dict__
-
- w_type = space.type(w_obj)
- if space.is_true(space.eq(w_attr, space.wrap('__class__'))):
- raise OperationError(space.w_AttributeError,
- space.wrap("read-only attribute"))
- if space.is_true(space.eq(w_attr, space.wrap('__dict__'))):
- raise OperationError(space.w_AttributeError,
- space.wrap("read-only attribute"))
+##def setattr__Object_ANY_ANY(space, w_obj, w_attr, w_value):
- from typeobject import W_TypeObject
- if isinstance(w_type, W_TypeObject):
- try:
- w_descr = w_type.lookup(w_attr)
- except KeyError:
- pass
- else:
- if space.is_data_descr(w_descr):
- return space.set(w_descr, w_obj, w_value)
+## # 1) look for descriptor
+## # 2) if data descriptor, call it
+## # 3) try to set item in __dict__
+
+## w_type = space.type(w_obj)
+## if space.is_true(space.eq(w_attr, space.wrap('__class__'))):
+## raise OperationError(space.w_AttributeError,
+## space.wrap("read-only attribute"))
+## if space.is_true(space.eq(w_attr, space.wrap('__dict__'))):
+## raise OperationError(space.w_AttributeError,
+## space.wrap("read-only attribute"))
+
+## from typeobject import W_TypeObject
+## if isinstance(w_type, W_TypeObject):
+## try:
+## w_descr = w_type.lookup(w_attr)
+## except KeyError:
+## pass
+## else:
+## if space.is_data_descr(w_descr):
+## return space.set(w_descr, w_obj, w_value)
- try:
- w_dict = space.getdict(w_obj)
- except OperationError, e:
- if not e.match(space, space.w_TypeError): # "unsupported type for getdict"
- raise
- raise OperationError(space.w_AttributeError, w_attr)
- else:
- space.setitem(w_dict, w_attr, w_value)
+## try:
+## w_dict = space.getdict(w_obj)
+## except OperationError, e:
+## if not e.match(space, space.w_TypeError): # "unsupported type for getdict"
+## raise
+## raise OperationError(space.w_AttributeError, w_attr)
+## else:
+## space.setitem(w_dict, w_attr, w_value)
-def delattr__Object_ANY(space, w_obj, w_attr):
- w_type = space.type(w_obj)
- if space.is_true(space.eq(w_attr, space.wrap('__class__'))):
- raise OperationError(space.w_AttributeError,
- space.wrap("read-only attribute"))
- if space.is_true(space.eq(w_attr, space.wrap('__dict__'))):
- raise OperationError(space.w_AttributeError,
- space.wrap("read-only attribute"))
-
- from typeobject import W_TypeObject
- if isinstance(w_type, W_TypeObject):
- try:
- w_descr = w_type.lookup(w_attr)
- except KeyError:
- pass
- else:
- #space.type(w_descr).lookup(space.wrap('__delete__'))
- if space.is_data_descr(w_descr):
- return space.delete(w_descr, w_obj)
+##def delattr__Object_ANY(space, w_obj, w_attr):
+## w_type = space.type(w_obj)
+## if space.is_true(space.eq(w_attr, space.wrap('__class__'))):
+## raise OperationError(space.w_AttributeError,
+## space.wrap("read-only attribute"))
+## if space.is_true(space.eq(w_attr, space.wrap('__dict__'))):
+## raise OperationError(space.w_AttributeError,
+## space.wrap("read-only attribute"))
+
+## from typeobject import W_TypeObject
+## if isinstance(w_type, W_TypeObject):
+## try:
+## w_descr = w_type.lookup(w_attr)
+## except KeyError:
+## pass
+## else:
+## #space.type(w_descr).lookup(space.wrap('__delete__'))
+## if space.is_data_descr(w_descr):
+## return space.delete(w_descr, w_obj)
- try:
- w_dict = space.getdict(w_obj)
- except OperationError, e:
- if not e.match(space, space.w_TypeError): # "unsupported type for getdict"
- raise
- raise OperationError(space.w_AttributeError, w_attr)
- else:
- try:
- space.delitem(w_dict, w_attr)
- except OperationError, e:
- if not e.match(space, space.w_KeyError):
- raise
- raise OperationError(space.w_AttributeError, w_attr)
+## try:
+## w_dict = space.getdict(w_obj)
+## except OperationError, e:
+## if not e.match(space, space.w_TypeError): # "unsupported type for getdict"
+## raise
+## raise OperationError(space.w_AttributeError, w_attr)
+## else:
+## try:
+## space.delitem(w_dict, w_attr)
+## except OperationError, e:
+## if not e.match(space, space.w_KeyError):
+## raise
+## raise OperationError(space.w_AttributeError, w_attr)
# static types
-def type__Object(space, w_obj):
- if w_obj.statictype is None:
- # XXX remove me, temporary
- return space.wrap(space.unwrap(w_obj).__class__)
- else:
- w_type = space.get_typeinstance(w_obj.statictype)
- return w_type
+##def type__Object(space, w_obj):
+## if w_obj.statictype is None:
+## # XXX remove me, temporary
+## return space.wrap(space.unwrap(w_obj).__class__)
+## else:
+## w_type = space.get_typeinstance(w_obj.statictype)
+## return w_type
# repr(), str(), hash()
-def repr__Object(space, w_obj):
- return space.wrap('<%s object at %s>'%(
- space.type(w_obj).typename, space.unwrap(space.id(w_obj))))
+##def repr__Object(space, w_obj):
+## return space.wrap('<%s object at %s>'%(
+## space.type(w_obj).typename, space.unwrap(space.id(w_obj))))
-def str__Object(space, w_obj):
- return space.repr(w_obj)
+##def str__Object(space, w_obj):
+## return space.repr(w_obj)
def hash__Object(space, w_obj):
return space.id(w_obj)
@@ -211,5 +212,13 @@
if space.is_true(space.eq(w_next, w_lookfor)):
return space.w_True
+# ugh
+
+def unwrap__ANY(space, w_obj):
+ if isinstance(w_obj, Wrappable):
+ return w_obj
+ else:
+ raise TypeError, 'cannot unwrap %r' % (w_obj,)
+
register_all(vars())
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/dictobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/dictobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/dictobject.py Fri Jun 4 16:16:45 2004
@@ -7,7 +7,6 @@
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
-from dicttype import W_DictType
from stringobject import W_StringObject
class _NoValueInCell: pass
@@ -39,7 +38,7 @@
class W_DictObject(W_Object):
- statictype = W_DictType
+ from pypy.objspace.std.dicttype import dict_typedef as typedef
def __init__(w_self, space, list_pairs_w):
W_Object.__init__(w_self, space)
@@ -125,7 +124,13 @@
cell.make_empty()
return
raise OperationError(space.w_KeyError, w_lookup)
-
+
+def is_true__Dict(space, w_dict):
+ # this must be implemented in addition to len() for dictionaries
+ # for infinite recursion reasons (is_true -> len -> call to len ->
+ # checking for keywords -> is_true etc.)
+ return not not w_dict.non_empties()
+
def len__Dict(space, w_dict):
return space.wrap(len(w_dict.non_empties()))
@@ -226,5 +231,5 @@
return "{%s}" % ', '.join(items)
repr__Dict = str__Dict = gateway.app2interp(app_str__Dict)
-register_all(vars(), W_DictType)
-
+from pypy.objspace.std import dicttype
+register_all(vars(), dicttype)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/dicttype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/dicttype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/dicttype.py Fri Jun 4 16:16:45 2004
@@ -1,40 +1,24 @@
-"""
-Reviewed 03-06-22
-"""
-
-from pypy.objspace.std.objspace import *
-from pypy.interpreter import gateway
-from typeobject import W_TypeObject
-from listobject import W_ListObject
-
-class W_DictType(W_TypeObject):
-
- typename = 'dict'
-
- dict_copy = MultiMethod('copy', 1)
- dict_items = MultiMethod('items', 1)
- dict_keys = MultiMethod('keys', 1)
- dict_values = MultiMethod('values', 1)
- 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_popitem = MultiMethod('popitem', 1)
- dict_setdefault = MultiMethod('setdefault', 3, defaults=(None,))
- dict_update = MultiMethod('update', 2)
- dict_iteritems = MultiMethod('iteritems', 1)
- dict_iterkeys = MultiMethod('iterkeys', 1)
- dict_itervalues = MultiMethod('itervalues', 1)
- dict_fromkeys = MultiMethod('fromkeys', 2, varargs=True)
- # This can return when multimethods have been fixed
- #dict_str = StdObjSpace.str
-
-registerimplementation(W_DictType)
-
-
-def type_new__DictType_DictType(space, w_basetype, w_dicttype, w_args, w_kwds):
- return space.newdict([]), True
-
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
+from pypy.objspace.std.register_all import register_all
+
+dict_copy = MultiMethod('copy', 1)
+dict_items = MultiMethod('items', 1)
+dict_keys = MultiMethod('keys', 1)
+dict_values = MultiMethod('values', 1)
+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_popitem = MultiMethod('popitem', 1)
+dict_setdefault = MultiMethod('setdefault', 3, defaults=(None,))
+dict_update = MultiMethod('update', 2)
+dict_iteritems = MultiMethod('iteritems', 1)
+dict_iterkeys = MultiMethod('iterkeys', 1)
+dict_itervalues = MultiMethod('itervalues', 1)
+#dict_fromkeys = MultiMethod('fromkeys', 2, varargs=True)
+# This can return when multimethods have been fixed
+#dict_str = StdObjSpace.str
# default application-level implementations for some operations
@@ -85,15 +69,17 @@
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
+#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
"""
@@ -104,4 +90,17 @@
return "{%s}" % ', '.join(items)
"""
gateway.importall(globals())
-register_all(vars(), W_DictType)
+register_all(vars(), globals())
+
+# ____________________________________________________________
+
+def descr__new__(space, w_dicttype, *args_w, **kwds_w):
+ from pypy.objspace.std.dictobject import W_DictObject
+ return W_DictObject(space, [])
+
+# ____________________________________________________________
+
+dict_typedef = StdTypeDef("dict", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
+dict_typedef.registermethods(globals())
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/floatobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/floatobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/floatobject.py Fri Jun 4 16:16:45 2004
@@ -1,6 +1,5 @@
from pypy.objspace.std.objspace import *
from noneobject import W_NoneObject
-from floattype import W_FloatType
##############################################################
# for the time being, all calls that are made to some external
@@ -15,7 +14,7 @@
"""This is a reimplementation of the CPython "PyFloatObject"
it is assumed that the constructor takes a real Python float as
an argument"""
- statictype = W_FloatType
+ from pypy.objspace.std.floattype import float_typedef as typedef
def __init__(w_self, space, floatval):
W_Object.__init__(w_self, space)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/floattype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/floattype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/floattype.py Fri Jun 4 16:16:45 2004
@@ -1,34 +1,18 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
-
-class W_FloatType(W_TypeObject):
-
- typename = 'float'
-
-registerimplementation(W_FloatType)
-
-
-def type_new__FloatType_FloatType(space, w_basetype, w_floattype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- if len(args) == 0:
- return space.newfloat(0), True
- elif len(args) == 1:
- arg = args[0]
- if space.is_true(space.issubtype(space.type(arg),
- space.w_str)):
- try:
- return space.newfloat(float(space.unwrap(arg))), True
- except ValueError, e:
- raise OperationError(space.w_ValueError,
- space.wrap(str(e)))
- else:
- return space.float(args[0]), True
+def descr__new__(space, w_floattype, w_value=0):
+ if space.is_true(space.isinstance(w_value, space.w_str)):
+ try:
+ return space.newfloat(float(space.unwrap(w_value)))
+ except ValueError, e:
+ raise OperationError(space.w_ValueError,
+ space.wrap(str(e)))
else:
- raise OperationError(space.w_TypeError,
- space.wrap("float() takes at most 1 argument"))
+ return space.float(w_value)
+
+# ____________________________________________________________
-register_all(vars())
+float_typedef = StdTypeDef("float", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/intobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/intobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/intobject.py Fri Jun 4 16:16:45 2004
@@ -1,5 +1,4 @@
from pypy.objspace.std.objspace import *
-from inttype import W_IntType
from noneobject import W_NoneObject
from restricted_int import r_int, LONG_BIT
@@ -19,7 +18,7 @@
"""
class W_IntObject(W_Object):
- statictype = W_IntType
+ from inttype import int_typedef as typedef
def __init__(w_self, space, intval):
W_Object.__init__(w_self, space)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/inttype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/inttype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/inttype.py Fri Jun 4 16:16:45 2004
@@ -1,32 +1,17 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
-class W_IntType(W_TypeObject):
-
- typename = 'int'
-
-registerimplementation(W_IntType)
-
-
-def type_new__IntType_IntType(space, w_basetype, w_inttype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- arglen = len(args)
-
- if arglen == 0:
- return space.newint(0), True
- elif arglen > 2:
- raise OperationError(space.w_TypeError,
- space.wrap("int() takes at most 2 arguments"))
- elif space.is_true(space.issubtype(space.type(args[0]), space.w_str)):
+def descr__new__(space, w_inttype, w_value=0, w_base=None):
+ from intobject import W_IntObject
+ if w_base == space.w_None:
+ return space.int(w_value)
+ else:
+ # XXX write the logic for int("str", base)
+ s = space.unwrap(w_value)
+ base = space.unwrap(w_base)
try:
- if arglen == 1:
- return space.newint(int(space.unwrap(args[0]))), True
- else:
- return space.newint(int(space.unwrap(args[0]),space.unwrap(args[1]))), True
+ value = int(s, base)
except TypeError, e:
raise OperationError(space.w_TypeError,
space.wrap(str(e)))
@@ -36,10 +21,10 @@
except OverflowError, e:
raise OperationError(space.w_OverflowError,
space.wrap(str(e)))
- elif arglen == 2:
- raise OperationError(space.w_TypeError,
- space.wrap("int() can't convert non-string with explicit base"))
- else:
- return space.int(args[0]), True
+ return W_IntObject(value)
+
+# ____________________________________________________________
-register_all(vars())
+int_typedef = StdTypeDef("int", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/iterobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/iterobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/iterobject.py Fri Jun 4 16:16:45 2004
@@ -5,12 +5,11 @@
for function-iteration.
"""
from pypy.objspace.std.objspace import *
-from itertype import W_SeqIterType
class W_SeqIterObject(W_Object):
- statictype = W_SeqIterType
-
+ from pypy.objspace.std.itertype import iter_typedef as typedef
+
def __init__(w_self, space, w_seq, index=0):
W_Object.__init__(w_self, space)
w_self.w_seq = w_seq
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/itertype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/itertype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/itertype.py Fri Jun 4 16:16:45 2004
@@ -1,12 +1,10 @@
"""
Reviewed 03-06-22
"""
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
+# ____________________________________________________________
-class W_SeqIterType(W_TypeObject):
-
- typename = 'SeqIterType'
-
-registerimplementation(W_SeqIterType)
+iter_typedef = StdTypeDef("sequence-iterator", [object_typedef],
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/listobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/listobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/listobject.py Fri Jun 4 16:16:45 2004
@@ -1,5 +1,4 @@
from pypy.objspace.std.objspace import *
-from listtype import W_ListType
from intobject import W_IntObject
from sliceobject import W_SliceObject
from tupleobject import W_TupleObject
@@ -10,8 +9,8 @@
class W_ListObject(W_Object):
- statictype = W_ListType
-
+ from pypy.objspace.std.listtype import list_typedef as typedef
+
def __init__(w_self, space, wrappeditems):
W_Object.__init__(w_self, space)
w_self.ob_item = []
@@ -54,7 +53,7 @@
w_item = space.next(w_iterator)
except OperationError, e:
if not e.match(space, space.w_StopIteration):
- raise
+ raise
break # done
_ins1(w_list, w_list.ob_size, w_item)
else:
@@ -535,4 +534,5 @@
};
"""
-register_all(vars(), W_ListType)
+from pypy.objspace.std import listtype
+register_all(vars(), listtype)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/listtype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/listtype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/listtype.py Fri Jun 4 16:16:45 2004
@@ -1,25 +1,25 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
from sys import maxint
-class W_ListType(W_TypeObject):
-
- typename = 'list'
-
- list_append = MultiMethod('append', 2)
- list_insert = MultiMethod('insert', 3)
- list_extend = MultiMethod('extend', 2)
- list_pop = MultiMethod('pop', 2, defaults=(-1,))
- list_remove = MultiMethod('remove', 2)
- list_index = MultiMethod('index', 4, defaults=(0,maxint))
- list_count = MultiMethod('count', 2)
- list_reverse= MultiMethod('reverse',1)
- list_sort = MultiMethod('sort', 2, defaults=(None,))
-
-registerimplementation(W_ListType)
-
-
-def type_new__ListType_ListType(space, w_basetype, w_listtype, w_args, w_kwds):
- return space.newlist([]), True
-
-register_all(vars())
+list_append = MultiMethod('append', 2)
+list_insert = MultiMethod('insert', 3)
+list_extend = MultiMethod('extend', 2)
+list_pop = MultiMethod('pop', 2, defaults=(-1,))
+list_remove = MultiMethod('remove', 2)
+list_index = MultiMethod('index', 4, defaults=(0,maxint))
+list_count = MultiMethod('count', 2)
+list_reverse= MultiMethod('reverse',1)
+list_sort = MultiMethod('sort', 2, defaults=(None,))
+
+# ____________________________________________________________
+
+def descr__new__(space, w_listtype, *args_w, **kwds_w):
+ return space.newlist([])
+
+# ____________________________________________________________
+
+list_typedef = StdTypeDef("list", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
+list_typedef.registermethods(globals())
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/multimethod.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/multimethod.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/multimethod.py Fri Jun 4 16:16:45 2004
@@ -6,7 +6,7 @@
class W_ANY:
"Catch-all in case multimethods don't find anything else."
- statictype = None
+ typedef = None
# This file defines three major classes:
@@ -364,7 +364,7 @@
# 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].statictype
+ t = types[self.bound_position].typedef
return t is self.typeclass
def __get__(self, space, cls=None):
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/noneobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/noneobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/noneobject.py Fri Jun 4 16:16:45 2004
@@ -5,10 +5,9 @@
"""
from pypy.objspace.std.objspace import *
-from nonetype import W_NoneType
class W_NoneObject(W_Object):
- statictype = W_NoneType
+ from pypy.objspace.std.nonetype import none_typedef as typedef
registerimplementation(W_NoneObject)
def unwrap__None(space, w_none):
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/nonetype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/nonetype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/nonetype.py Fri Jun 4 16:16:45 2004
@@ -1,9 +1,8 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
-class W_NoneType(W_TypeObject):
+# ____________________________________________________________
- typename = 'NoneType'
-
-registerimplementation(W_NoneType)
+none_typedef = StdTypeDef("NoneType", [object_typedef],
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/objectobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/objectobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/objectobject.py Fri Jun 4 16:16:45 2004
@@ -4,12 +4,7 @@
class W_ObjectObject(W_Object):
"""Instances of this class are what the user can directly see with an
'object()' call."""
- #statictype = W_ObjectType (hacked into place below)
-
-
-import objecttype
-W_ObjectObject.statictype = objecttype.W_ObjectType
-registerimplementation(W_ObjectObject)
+ from pypy.objspace.std.objecttype import object_typedef as typedef
# any-to-object delegation is quite trivial, because W_ObjectObject is.
@@ -18,8 +13,8 @@
delegate__ANY.result_class = W_ObjectObject
delegate__ANY.priority = PRIORITY_PARENT_TYPE
-def object_init__Object(space, w_object, w_args, w_kwds):
- pass
+#def object_init__Object(space, w_object, w_args, w_kwds):
+# pass
register_all(vars())
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/objecttype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/objecttype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/objecttype.py Fri Jun 4 16:16:45 2004
@@ -1,35 +1,41 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.descroperation import Object
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.register_all import register_all
+object_init = MultiMethod('__init__', 1, varargs=True, keywords=True)
-class W_ObjectType(W_TypeObject):
- """The single instance of W_ObjectType is what the user sees as
- '__builtin__.object'."""
+def object_init__ANY(space, w_obj, w_args, w_kwds):
+ pass
- typename = 'object'
- staticbases = ()
+register_all(vars(), globals())
- # all multimethods that we want to be visible as object.__xxx__
- # should be defined here.
+# ____________________________________________________________
- object_getattr = StdObjSpace.getattribute
- object_setattr = StdObjSpace.setattr
- object_delattr = StdObjSpace.delattr
- object_type = StdObjSpace.type
- object_repr = StdObjSpace.repr
- object_str = StdObjSpace.str
- object_hash = StdObjSpace.hash
+def descr__repr__(space, w_obj):
+ w = space.wrap
+ classname = space.unwrap(space.getattr(space.type(w_obj), w("__name__")))
+ id = space.unwrap(space.id(w_obj))
+ return w("<%s object at 0x%x>" % (classname, id))
- # this is a method in 'object' because it is not an object space operation
- object_init = MultiMethod('__init__', 1, varargs=True, keywords=True)
+def descr__str__(space, w_obj):
+ return space.repr(w_obj)
-registerimplementation(W_ObjectType)
+def descr__class__(space, w_obj):
+ return space.type(w_obj)
-
-def type_new__ObjectType_ObjectType(space, w_basetype, w_objecttype, w_args, w_kwds):
+def descr__new__(space, w_type, *args_w, **kwds_w):
# XXX 2.2 behavior: ignoring all arguments
from objectobject import W_ObjectObject
- return W_ObjectObject(space), True
+ return W_ObjectObject(space)
+# ____________________________________________________________
-register_all(vars(), W_ObjectType)
+object_typedef = StdTypeDef("object", [],
+ __getattribute__ = gateway.interp2app(Object.descr__getattribute__.im_func),
+ __setattr__ = gateway.interp2app(Object.descr__setattr__.im_func),
+ __delattr__ = gateway.interp2app(Object.descr__delattr__.im_func),
+ __str__ = gateway.interp2app(descr__str__),
+ __repr__ = gateway.interp2app(descr__repr__),
+ __class__ = GetSetProperty(descr__class__),
+ __new__ = newmethod(descr__new__),
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/objspace.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/objspace.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/objspace.py Fri Jun 4 16:16:45 2004
@@ -1,11 +1,12 @@
-from register_all import register_all
+from pypy.objspace.std.register_all import register_all
from pypy.interpreter.baseobjspace import *
-from multimethod import *
+from pypy.objspace.std.multimethod import *
+from pypy.objspace.descroperation import DescrOperation
class W_Object:
"Parent base class for wrapped objects."
- statictype = None
+ typedef = None
def __init__(w_self, space):
w_self.space = space # XXX not sure this is ever used any more
@@ -13,16 +14,10 @@
def __repr__(self):
return '<objwrapper %s(%s)>' % (
self.__class__.__name__,
- getattr(self, 'statictype', '<no statictype>')
+ #', '.join(['%s=%r' % keyvalue for keyvalue in self.__dict__.items()])
+ getattr(self, 'name', '')
)
-class W_AbstractTypeObject(W_Object):
- "Do not use. For W_TypeObject only."
-
-
-BoundMultiMethod.ASSERT_BASE_TYPE = W_Object
-MultiMethod.BASE_TYPE_OBJECT = W_AbstractTypeObject
-
# 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)
@@ -32,14 +27,14 @@
def registerimplementation(implcls):
# this function should ultimately register the implementation class somewhere
- # it may be modified to take 'statictype' instead of requiring it to be
+ # it may be modified to take 'typedef' instead of requiring it to be
# stored in 'implcls' itself
assert issubclass(implcls, W_Object)
##################################################################
-class StdObjSpace(ObjSpace):
+class StdObjSpace(ObjSpace, DescrOperation):
"""The standard object space, implementing a general-purpose object
library in Restricted Python."""
@@ -49,21 +44,21 @@
class result:
"Import here the types you want to have appear in __builtin__."
- from objecttype import W_ObjectType
- from booltype import W_BoolType
- from inttype import W_IntType
- from floattype import W_FloatType
- from tupletype import W_TupleType
- from listtype import W_ListType
- from dicttype import W_DictType
- from stringtype import W_StringType
- from typetype import W_TypeType
- from slicetype import W_SliceType
+ from objecttype import object_typedef
+ #from booltype import W_BoolType
+ from inttype import int_typedef
+ #from floattype import W_FloatType
+ #from tupletype import W_TupleType
+ #from listtype import W_ListType
+ #from dicttype import W_DictType
+ #from stringtype import W_StringType
+ from typetype import type_typedef
+ #from slicetype import W_SliceType
return [value for key, value in result.__dict__.items()
if not key.startswith('_')] # don't look
def clone_exception_hierarchy(self):
- from usertype import W_UserType
+ from pypy.objspace.std.typeobject import W_TypeObject
from pypy.interpreter import gateway
w = self.wrap
def app___init__(self, *args):
@@ -84,15 +79,12 @@
# but being able to do that depends on the existence of some
# of the exceptions...
- self.w_Exception = W_UserType(
+ self.w_Exception = W_TypeObject(
self,
- w('Exception'),
- self.newtuple([]),
- self.newdict([(w('__init__'), w_init),
- (w('__str__'), w_str)]))
-
- self.w_IndexError = self.w_StopIteration = self.w_Exception
-
+ 'Exception',
+ [],
+ {'__init__': w_init,
+ '__str__': w_str})
done = {'Exception': self.w_Exception}
# some of the complexity of the following is due to the fact
@@ -115,11 +107,11 @@
continue
else:
base = done[b.__name__]
- newtype = self.call_function(
- self.w_type,
- w(next),
- self.newtuple([base]),
- self.newdict([]))
+ newtype = W_TypeObject(
+ self,
+ next,
+ [base],
+ {})
setattr(self,
'w_' + next,
newtype)
@@ -132,7 +124,6 @@
def initialize(self):
from noneobject import W_NoneObject
from boolobject import W_BoolObject
- from cpythonobject import W_CPythonObject
# singletons
self.w_None = W_NoneObject(self)
@@ -151,10 +142,10 @@
# types
self.types_w = {}
- for typeclass in self.standard_types():
- w_type = self.get_typeinstance(typeclass)
- setattr(self, 'w_' + typeclass.typename, w_type)
- for_builtins[typeclass.typename] = w_type
+ for typedef in self.standard_types():
+ w_type = self.gettypeobject(typedef)
+ setattr(self, 'w_' + typedef.name, w_type)
+ for_builtins[typedef.name] = w_type
# exceptions
for_builtins.update(self.clone_exception_hierarchy())
@@ -165,14 +156,14 @@
for key, w_value in for_builtins.items():
self.setitem(self.w_builtins, self.wrap(key), w_value)
- def get_typeinstance(self, typeclass):
- assert typeclass.typename is not None, (
- "get_typeinstance() cannot be used for %r" % typeclass)
- # types_w maps each W_XxxType class to its unique-for-this-space instance
+ def gettypeobject(self, typedef):
+ # types_w maps each StdTypeDef instance to its
+ # unique-for-this-space W_TypeObject instance
try:
- w_type = self.types_w[typeclass]
- except:
- w_type = self.types_w[typeclass] = typeclass(self)
+ w_type = self.types_w[typedef]
+ except KeyError:
+ from pypy.objspace.std.stdtypedef import buildtypeobject
+ w_type = self.types_w[typedef] = buildtypeobject(typedef, self)
return w_type
def wrap(self, x):
@@ -207,8 +198,8 @@
wrappeditems = [self.wrap(item) for item in x]
import listobject
return listobject.W_ListObject(self, wrappeditems)
- if hasattr(type(x), '__wrap__'):
- return x.__wrap__(self)
+ if isinstance(x, Wrappable):
+ return x.__spacebind__(self)
#print "wrapping %r (%s)" % (x, type(x))
import cpythonobject
return cpythonobject.W_CPythonObject(self, x)
@@ -222,6 +213,7 @@
return floatobject.W_FloatObject(self, int_w)
def newtuple(self, list_w):
+ assert isinstance(list_w, list)
import tupleobject
return tupleobject.W_TupleObject(self, list_w)
@@ -250,37 +242,41 @@
import stringobject
return stringobject.W_StringObject(self, ''.join(chars))
- # special multimethods
+ def type(self, w_obj):
+ assert w_obj.typedef, w_obj
+ return self.gettypeobject(w_obj.typedef)
+
+ def lookup(self, w_obj, name):
+ from pypy.objspace.std.cpythonobject import W_CPythonObject
+ if not isinstance(w_obj, W_CPythonObject):
+ # usual case
+ w_type = self.type(w_obj)
+ return w_type.lookup(name)
+ else:
+ # hack
+ for cls in w_obj.cpyobj.__class__.__mro__:
+ if name in cls.__dict__:
+ return self.wrap(cls.__dict__[name])
+ return None
+
+ def unpacktuple(self, w_tuple):
+ import tupleobject
+ assert isinstance(w_tuple, tupleobject.W_TupleObject)
+ return w_tuple.wrappeditems
+
+ # special visible multimethods
delegate = DelegateMultiMethod() # delegators
unwrap = MultiMethod('unwrap', 1, []) # returns an unwrapped object
is_true = MultiMethod('nonzero', 1, []) # returns an unwrapped bool
- is_data_descr = MultiMethod('is_data_descr', 1, []) # returns an unwrapped bool
-
- getdict = MultiMethod('getdict', 1, []) # get '.__dict__' attribute
- next = MultiMethod('next', 1, []) # iterator interface
- call = MultiMethod('call', 3, [], varargs=True, keywords=True)
- getattribute = MultiMethod('getattr', 2, ['__getattribute__']) # XXX hack
- usergetattr = MultiMethod('usergetattr', 2, ['__getattr__']) # XXX hack
+ issubtype = MultiMethod('issubtype', 2, [])
- def getattr(self, w_obj, w_attr):
- try:
- return self.getattribute(w_obj, w_attr)
- except OperationError, e:
- if not e.match(self, self.w_AttributeError):
- raise
- result = self.getattr_try_harder(w_obj, w_attr)
- if result is None:
- raise
- return result
-
- def getattr_try_harder(self, *args_w):
- # this needs to be in another function so that the exception caught
- # here doesn't prevent the bare 'raise' in self.getattr() to
- # re-raise the previous OperationError with correct traceback.
- try:
- return self.usergetattr.perform_call(args_w)
- except FailedToImplement:
- return None
+ 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
def is_(self, w_one, w_two):
# XXX a bit of hacking to gain more speed
@@ -297,8 +293,9 @@
# add all regular multimethods to StdObjSpace
for _name, _symbol, _arity, _specialnames in ObjSpace.MethodTable:
- if not hasattr(StdObjSpace,_name):
- setattr(StdObjSpace, _name, MultiMethod(_symbol, _arity, _specialnames))
+ if (not hasattr(StdObjSpace.MM, _name) and # XXX!
+ not isinstance(getattr(StdObjSpace, _name, None), MultiMethod)):
+ setattr(StdObjSpace.MM, _name, MultiMethod(_symbol, _arity, _specialnames))
# import the common base W_ObjectObject as well as
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/register_all.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/register_all.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/register_all.py Fri Jun 4 16:16:45 2004
@@ -14,7 +14,7 @@
for registration.
"""
from pypy.objspace.std.objspace import StdObjSpace, W_ANY, W_Object
- namespaces = [StdObjSpace]
+ namespaces = [StdObjSpace.MM, StdObjSpace]
if alt_ns:
namespaces.insert(0, alt_ns)
@@ -53,19 +53,23 @@
def hack_func_by_name(funcname, namespaces):
for ns in namespaces:
- if hasattr(ns, funcname):
- return getattr(ns, funcname)
- import typetype
+ if isinstance(ns, dict):
+ if funcname in ns:
+ return ns[funcname]
+ else:
+ if hasattr(ns, funcname):
+ return getattr(ns, funcname)
+ #import typetype
+ #try:
+ # return getattr(typetype.W_TypeType, funcname)
+ #except AttributeError:
+ # pass # catches not only the getattr() but the typetype.W_TypeType
+ # # in case it is not fully imported yet :-((((
+ from pypy.objspace.std import objecttype
try:
- return getattr(typetype.W_TypeType, funcname)
+ return getattr(objecttype, funcname)
except AttributeError:
- pass # catches not only the getattr() but the typetype.W_TypeType
- # in case it is not fully imported yet :-((((
- import objecttype
- try:
- return getattr(objecttype.W_ObjectType, funcname)
- except AttributeError:
- pass # same comment
+ pass
raise NameError, ("trying hard but not finding a multimethod named %s" %
funcname)
@@ -109,10 +113,10 @@
from pypy.objspace.std.objspace import StdObjSpace, W_ANY
originaltable = {}
for op in OPERATORS:
- originaltable[op] = getattr(StdObjSpace, op).dispatch_table.copy()
+ originaltable[op] = getattr(StdObjSpace.MM, op).dispatch_table.copy()
for op1, op2, correspondance in OP_CORRESPONDANCES:
- mirrorfunc = getattr(StdObjSpace, op2)
+ mirrorfunc = getattr(StdObjSpace.MM, op2)
for types, functions in originaltable[op1].iteritems():
t1, t2 = types
if t1 is t2:
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/sliceobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/sliceobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/sliceobject.py Fri Jun 4 16:16:45 2004
@@ -6,11 +6,10 @@
"""
from pypy.objspace.std.objspace import *
-from slicetype import W_SliceType
class W_SliceObject(W_Object):
- statictype = W_SliceType
+ from pypy.objspace.std.slicetype import slice_typedef as typedef
def __init__(w_self, space, w_start, w_stop, w_step):
W_Object.__init__(w_self, space)
@@ -21,7 +20,8 @@
registerimplementation(W_SliceObject)
-def getattribute__Slice_ANY(space, w_slice, w_attr):
+def getattr__Slice_ANY(space, w_slice, w_attr):
+ # XXX later
if space.is_true(space.eq(w_attr, space.wrap('start'))):
if w_slice.w_start is None:
return space.w_None
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/slicetype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/slicetype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/slicetype.py Fri Jun 4 16:16:45 2004
@@ -1,40 +1,8 @@
-from pypy.objspace.std.objspace import *
-from pypy.interpreter import gateway
-from typeobject import W_TypeObject
-
-
-class W_SliceType(W_TypeObject):
-
- typename = 'slice'
-
- slice_indices = MultiMethod('indices', 2)
-
-
-registerimplementation(W_SliceType)
-
-
-def type_new__SliceType_SliceType(space, w_basetype, w_slicetype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- start = space.w_None
- stop = space.w_None
- step = space.w_None
- if len(args) == 1:
- stop, = args
- elif len(args) == 2:
- start, stop = args
- elif len(args) == 3:
- start, stop, step = args
- elif len(args) > 3:
- raise OperationError(space.w_TypeError,
- space.wrap("slice() takes at most 3 arguments"))
- else:
- raise OperationError(space.w_TypeError,
- space.wrap("slice() takes at least 1 argument"))
- return space.newslice(start, stop, step), True
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
+from pypy.objspace.std.register_all import register_all
+slice_indices = MultiMethod('indices', 2)
# default application-level implementations for some operations
@@ -108,5 +76,31 @@
return (space.unwrap(w_1), space.unwrap(w_2),
space.unwrap(w_3), space.unwrap(w_4))
+register_all(vars(), globals())
+
+# ____________________________________________________________
+
+def descr__new__(space, w_slicetype, *args_w):
+ w_start = space.w_None
+ w_stop = space.w_None
+ w_step = space.w_None
+ if len(args_w) == 1:
+ w_stop, = args_w
+ elif len(args_w) == 2:
+ w_start, w_stop = args_w
+ elif len(args_w) == 3:
+ w_start, w_stop, w_step = args_w
+ elif len(args) > 3:
+ raise OperationError(space.w_TypeError,
+ space.wrap("slice() takes at most 3 arguments"))
+ else:
+ raise OperationError(space.w_TypeError,
+ space.wrap("slice() takes at least 1 argument"))
+ return space.newslice(w_start, w_stop, w_step)
+
+# ____________________________________________________________
-register_all(vars(), W_SliceType)
+slice_typedef = StdTypeDef("slice", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
+slice_typedef.registermethods(globals())
Added: pypy/branch/src-newobjectmodel/pypy/objspace/std/stdtypedef.py
==============================================================================
--- (empty file)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/stdtypedef.py Fri Jun 4 16:16:45 2004
@@ -0,0 +1,180 @@
+from pypy.interpreter import eval, function, gateway
+from pypy.interpreter.typedef import TypeDef, GetSetProperty
+from pypy.interpreter.typedef import attrproperty, attrproperty_w
+from pypy.objspace.std.multimethod import MultiMethod
+
+__all__ = ['StdTypeDef', 'newmethod', 'gateway',
+ 'GetSetProperty', 'attrproperty', 'attrproperty_w',
+ 'MultiMethod']
+
+
+class StdTypeDef(TypeDef):
+
+ def __init__(self, name, bases, **rawdict):
+ TypeDef.__init__(self, name, **rawdict)
+ self.bases = bases
+ self.local_multimethods = []
+
+ def registermethods(self, namespace):
+ self.local_multimethods += hack_out_multimethods(namespace)
+
+ def mro(self, space):
+ assert len(self.bases) <= 1
+ if self.bases:
+ return [self] + self.bases[0].mro()
+ else:
+ return [self]
+
+def newmethod(descr_new):
+ # XXX make the result a staticmethod
+ return gateway.interp2app(descr_new)
+
+# ____________________________________________________________
+#
+# All the code below fishes from the multimethod registration tables
+# the descriptors to put into the W_TypeObjects.
+#
+
+def buildtypeobject(typedef, space):
+ # build a W_TypeObject from this StdTypeDef
+ from pypy.objspace.std.typeobject import W_TypeObject
+
+ w = space.wrap
+ rawdict = typedef.rawdict.copy()
+
+ if isinstance(typedef, StdTypeDef):
+ # get all the sliced multimethods
+ multimethods = slicemultimethods(space.__class__, typedef)
+ for name, code in multimethods.items():
+ #print typedef.name, ':', name
+ fn = function.Function(space, code, defs_w=code.getdefaults(space))
+ assert name not in rawdict, 'name clash: %s in %s_typedef' % (
+ name, typedef.name)
+ rawdict[name] = fn
+ bases_w = [space.gettypeobject(basedef) for basedef in typedef.bases]
+ else:
+ from pypy.objspace.std.objecttype import object_typedef
+ bases_w = [space.gettypeobject(object_typedef)]
+
+ # wrap everything
+ dict_w = {}
+ for descrname, descrvalue in rawdict.items():
+ dict_w[descrname] = w(descrvalue)
+
+ return W_TypeObject(space, typedef.name, bases_w, dict_w)
+
+def hack_out_multimethods(ns):
+ result = []
+ for value in ns.itervalues():
+ if isinstance(value, MultiMethod):
+ result.append(value)
+ return result
+
+def slicemultimethods(spaceclass, typeclass):
+ result = {}
+ # import and slice all multimethods of the space.MM container
+ for multimethod in (hack_out_multimethods(spaceclass.MM.__dict__) +
+ typeclass.local_multimethods):
+ for i in range(len(multimethod.specialnames)):
+ # each MultimethodCode embeds a multimethod
+ name = multimethod.specialnames[i]
+ if name in result:
+ # conflict between e.g. __lt__ and
+ # __lt__-as-reversed-version-of-__gt__
+ code = result[name]
+ if code.bound_position < i:
+ continue
+ mmframeclass = multimethod.extras.get('mmframeclass')
+ if mmframeclass is None:
+ if len(multimethod.specialnames) > 1:
+ mmframeclass = SpecialMmFrame
+ else:
+ mmframeclass = MmFrame
+ code = MultimethodCode(multimethod, mmframeclass, typeclass, i)
+ result[name] = code
+ # add some more multimethods with a special interface
+ code = MultimethodCode(spaceclass.MM.next, MmFrame, typeclass)
+ result['next'] = code
+ code = MultimethodCode(spaceclass.is_true, NonZeroMmFrame, typeclass)
+ result['__nonzero__'] = code
+ # remove the empty slices
+ for name, code in result.items():
+ if code.slice().is_empty():
+ del result[name]
+ return result
+
+class MultimethodCode(eval.Code):
+ """A code object that invokes a multimethod."""
+
+ def __init__(self, multimethod, framecls, typeclass, bound_position=0):
+ eval.Code.__init__(self, multimethod.operatorsymbol)
+ self.basemultimethod = multimethod
+ self.typeclass = typeclass
+ self.bound_position = bound_position
+ self.framecls = framecls
+ argnames = ['x%d'%(i+1) for i in range(multimethod.arity)]
+ argnames.insert(0, argnames.pop(self.bound_position))
+ varargname = kwargname = None
+ if multimethod.extras.get('varargs', False):
+ varargname = 'args'
+ if multimethod.extras.get('keywords', False):
+ kwargname = 'keywords'
+ self.sig = argnames, varargname, kwargname
+
+ def signature(self):
+ return self.sig
+
+ def getdefaults(self, space):
+ return [space.wrap(x)
+ for x in self.basemultimethod.extras.get('defaults', ())]
+
+ def slice(self):
+ return self.basemultimethod.slice(self.typeclass, self.bound_position)
+
+ def create_frame(self, space, w_globals, closure=None):
+ return self.framecls(space, self)
+
+class MmFrame(eval.Frame):
+ def run(self):
+ "Call the multimethod, raising a TypeError if not implemented."
+ mm = self.code.slice().get(self.space)
+ args = self.fastlocals_w
+ #print mm.multimethod.operatorsymbol, args
+ #print
+ w_result = mm(*args)
+ # 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
+
+class SpecialMmFrame(eval.Frame):
+ def run(self):
+ "Call the multimethods, possibly returning a NotImplemented."
+ mm = self.code.slice().get(self.space)
+ args = self.fastlocals_w
+ try:
+ return mm.perform_call(args)
+ except FailedToImplement, e:
+ if e.args:
+ raise OperationError(*e.args)
+ else:
+ return self.space.w_NotImplemented
+
+##class NextMmFrame(eval.Frame):
+## def run(self):
+## "Call the next() multimethod."
+## mm = self.code.slice().get(self.space)
+## args = self.fastlocals_w
+## try:
+## return mm(*args)
+## except NoValue:
+## raise OperationError(self.space.w_StopIteration,
+## self.space.w_None)
+
+class NonZeroMmFrame(eval.Frame):
+ def run(self):
+ "Call the is_true() multimethods."
+ mm = self.code.slice().get(self.space)
+ args = self.fastlocals_w
+ result = mm(*args)
+ return self.space.newbool(result)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/stringobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/stringobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/stringobject.py Fri Jun 4 16:16:45 2004
@@ -73,10 +73,9 @@
from pypy.objspace.std.objspace import *
from pypy.interpreter import gateway
-from stringtype import W_StringType
from intobject import W_IntObject
from sliceobject import W_SliceObject
-import slicetype
+#import slicetype
from listobject import W_ListObject
from noneobject import W_NoneObject
from tupleobject import W_TupleObject
@@ -86,7 +85,7 @@
class W_StringObject(W_Object):
- statictype = W_StringType
+ from stringtype import str_typedef as typedef
def __init__(w_self, space, str):
W_Object.__init__(w_self, space)
@@ -1005,7 +1004,6 @@
mod__String_ANY = gateway.app2interp(app_mod__String_ANY)
-# register all methods
-register_all(vars(), W_StringType)
-
-
+# register all methods
+from pypy.objspace.std import stringtype
+register_all(vars(), stringtype)
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/stringtype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/stringtype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/stringtype.py Fri Jun 4 16:16:45 2004
@@ -1,58 +1,47 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
-
-class W_StringType(W_TypeObject):
-
- typename = 'str'
-
- str_join = MultiMethod('join', 2)
- str_split = MultiMethod('split', 3, defaults=(None,-1))
- str_isdigit = MultiMethod('isdigit', 1)
- str_isalpha = MultiMethod('isalpha', 1)
- str_isspace = MultiMethod('isspace', 1)
- str_isupper = MultiMethod('isupper', 1)
- str_islower = MultiMethod('islower', 1)
- str_istitle = MultiMethod('istitle', 1)
- str_isalnum = MultiMethod('isalnum', 1)
- str_ljust = MultiMethod('ljust', 2)
- str_rjust = MultiMethod('rjust', 2)
- str_upper = MultiMethod('upper', 1)
- str_lower = MultiMethod('lower', 1)
- str_swapcase = MultiMethod('swapcase', 1)
- str_capitalize = MultiMethod('capitalize', 1)
- str_title = MultiMethod('title', 1)
- str_find = MultiMethod('find', 4, defaults=(None, None))
- str_rfind = MultiMethod('rfind', 4, defaults=(None, None))
- str_index = MultiMethod('index', 4, defaults=(None, None))
- str_rindex = MultiMethod('rindex', 4, defaults=(None, None))
- str_replace = MultiMethod('replace', 4, defaults=(-1,))
- str_zfill = MultiMethod('zfill', 2)
- str_strip = MultiMethod('strip', 2, defaults=('', ' '))
- str_rstrip = MultiMethod('rstrip', 2, defaults=('', ' '))
- str_lstrip = MultiMethod('lstrip', 2, defaults=('', ' '))
- str_center = MultiMethod('center', 2, )
- str_count = MultiMethod('count', 4, defaults=(None,None))
- 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_translate = MultiMethod('translate', 3, defaults=('',)) #unicode mimic not supported now
-
-registerimplementation(W_StringType)
-
-
-def type_new__StringType_StringType(space, w_basetype, w_stringtype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- if len(args) == 0:
- return space.newstring([]), True
- elif len(args) == 1:
- return space.str(args[0]), True
- else:
- raise OperationError(space.w_TypeError,
- space.wrap("str() takes at most 1 argument"))
-
-register_all(vars())
+str_join = MultiMethod('join', 2)
+str_split = MultiMethod('split', 3, defaults=(None,-1))
+str_isdigit = MultiMethod('isdigit', 1)
+str_isalpha = MultiMethod('isalpha', 1)
+str_isspace = MultiMethod('isspace', 1)
+str_isupper = MultiMethod('isupper', 1)
+str_islower = MultiMethod('islower', 1)
+str_istitle = MultiMethod('istitle', 1)
+str_isalnum = MultiMethod('isalnum', 1)
+str_ljust = MultiMethod('ljust', 2)
+str_rjust = MultiMethod('rjust', 2)
+str_upper = MultiMethod('upper', 1)
+str_lower = MultiMethod('lower', 1)
+str_swapcase = MultiMethod('swapcase', 1)
+str_capitalize = MultiMethod('capitalize', 1)
+str_title = MultiMethod('title', 1)
+str_find = MultiMethod('find', 4, defaults=(None, None))
+str_rfind = MultiMethod('rfind', 4, defaults=(None, None))
+str_index = MultiMethod('index', 4, defaults=(None, None))
+str_rindex = MultiMethod('rindex', 4, defaults=(None, None))
+str_replace = MultiMethod('replace', 4, defaults=(-1,))
+str_zfill = MultiMethod('zfill', 2)
+str_strip = MultiMethod('strip', 2, defaults=('', ' '))
+str_rstrip = MultiMethod('rstrip', 2, defaults=('', ' '))
+str_lstrip = MultiMethod('lstrip', 2, defaults=('', ' '))
+str_center = MultiMethod('center', 2, )
+str_count = MultiMethod('count', 4, defaults=(None,None))
+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_translate = MultiMethod('translate', 3, defaults=('',)) #unicode mimic not supported now
+
+# ____________________________________________________________
+
+def descr__new__(space, w_stringtype, w_obj=''):
+ return space.str(w_obj)
+
+# ____________________________________________________________
+
+str_typedef = StdTypeDef("str", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
+str_typedef.registermethods(globals())
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/tupleobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/tupleobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/tupleobject.py Fri Jun 4 16:16:45 2004
@@ -1,13 +1,12 @@
from pypy.objspace.std.objspace import *
-from tupletype import W_TupleType
from intobject import W_IntObject
from sliceobject import W_SliceObject
import slicetype
class W_TupleObject(W_Object):
- statictype = W_TupleType
-
+ from pypy.objspace.std.tupletype import tuple_typedef as typedef
+
def __init__(w_self, space, wrappeditems):
W_Object.__init__(w_self, space)
w_self.wrappeditems = wrappeditems # a list of wrapped values
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/tupletype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/tupletype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/tupletype.py Fri Jun 4 16:16:45 2004
@@ -1,26 +1,13 @@
-from pypy.objspace.std.objspace import *
-from typeobject import W_TypeObject
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
-class W_TupleType(W_TypeObject):
+def descr__new__(space, w_tupletype, w_items=()):
+ tuple_w = space.unpackiterable(w_items)
+ return space.newtuple(tuple_w)
- typename = 'tuple'
+# ____________________________________________________________
-registerimplementation(W_TupleType)
-
-
-def type_new__TupleType_TupleType(space, w_basetype, w_tupletype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- if len(args) == 0:
- tuple_w = []
- elif len(args) == 1:
- tuple_w = space.unpackiterable(args[0])
- else:
- raise OperationError(space.w_TypeError,
- space.wrap("tuple() takes at most 1 argument"))
- return space.newtuple(tuple_w), True
-
-register_all(vars())
+tuple_typedef = StdTypeDef("tuple", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/typeobject.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/typeobject.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/typeobject.py Fri Jun 4 16:16:45 2004
@@ -1,203 +1,185 @@
-from pypy.interpreter import eval, function
from pypy.objspace.std.objspace import *
-class W_TypeObject(W_AbstractTypeObject):
- """This class is abstract. Subclasses are defined in 'xxxtype.py' files.
- The instances of these subclasses are what the user sees as Python's
- type objects. This class defines all general type-oriented behavior
- like attribute lookup and method resolution order. Inheritance
- relationships are implemented *only* with the getbases() methods of
- W_TypeObject subclasses, *not* with interpreter-level inheritance between
- W_Xxx classes *nor* with multimethod delegation."""
-
- typename = None # to be overridden by subclasses or instances
- #statictype = W_TypeType (hacked into place below)
- staticbases = None # defaults to (W_ObjectType,)
+class W_TypeObject(W_Object):
+ from pypy.objspace.std.typetype import type_typedef as typedef
- def __init__(w_self, space):
+ def __init__(w_self, space, name, bases_w, dict_w):
W_Object.__init__(w_self, space)
- w_self.w_tpname = space.wrap(w_self.typename)
-
- def __repr__(self):
- return '<typewrapper %s(%s)>' % (
- self.__class__.__name__,
- getattr(self, 'statictype', '<no statictype>')
- )
-
- def getbases(w_self):
- parents = w_self.staticbases
- if parents is None:
- # Note: this code is duplicated in multimethod.py
- import objecttype
- parents = (objecttype.W_ObjectType,)
- basetypes = [w_self.space.get_typeinstance(parent) for parent in parents]
- return tuple(basetypes)
+ w_self.name = name
+ w_self.bases_w = bases_w
+ w_self.dict_w = dict_w
def getmro(w_self):
# XXX this is something that works not too bad right now
- # XXX do the complete mro thing later
+ # XXX do the complete mro thing later (see mro.py)
mro = [w_self]
- for w_parent in w_self.getbases():
+ for w_parent in w_self.bases_w:
mro += w_parent.getmro()
- return tuple(mro)
+ return mro
- def lookup(w_self, w_key):
+ def lookup(w_self, key):
# note that this doesn't call __get__ on the result at all
# XXX this should probably also return the (parent) class in which
# the attribute was found
+ space = w_self.space
for w_class in w_self.getmro():
try:
- return w_class.lookup_exactly_here(w_key)
+ return w_class.dict_w[key]
except KeyError:
pass
- raise KeyError
+ return None
- def lookup_exactly_here(w_self, w_key):
- space = w_self.space
- multimethods = getmultimethods(space.__class__, w_self.__class__)
- key = space.unwrap(w_key)
- if not isinstance(key, str):
- raise OperationError(space.w_TypeError,
- space.wrap('attribute name must be string'))
- try:
- code = multimethods[key]
- except KeyError:
- raise KeyError # pass on the KeyError
- if code.slice().is_empty():
- raise KeyError
- fn = function.Function(space, code, defs_w=code.getdefaults(space))
- return space.wrap(fn)
-
-
-import typetype, objecttype
-W_TypeObject.statictype = typetype.W_TypeType
-registerimplementation(W_TypeObject)
-
-
-def hack_out_multimethods(cls):
- result = []
- for base in cls.__bases__:
- result += hack_out_multimethods(base)
- for value in cls.__dict__.itervalues():
- if isinstance(value, MultiMethod):
- result.append(value)
- return result
-
-AllSlicedMultimethods = {}
-
-def getmultimethods(spaceclass, typeclass):
- try:
- multimethods = AllSlicedMultimethods[spaceclass, typeclass]
- except KeyError:
- multimethods = AllSlicedMultimethods[spaceclass, typeclass] = {}
- # import all multimethods of the type class and of the objspace
- for multimethod in (hack_out_multimethods(typeclass) +
- hack_out_multimethods(spaceclass)):
- for i in range(len(multimethod.specialnames)):
- # each MultimethodCode embeds a multimethod
- name = multimethod.specialnames[i]
- if name in multimethods:
- # conflict between e.g. __lt__ and
- # __lt__-as-reversed-version-of-__gt__
- code = multimethods[name]
- if code.bound_position < i:
- continue
- mmframeclass = multimethod.extras.get('mmframeclass')
- if mmframeclass is None:
- if len(multimethod.specialnames) > 1:
- mmframeclass = SpecialMmFrame
- else:
- mmframeclass = MmFrame
- code = MultimethodCode(multimethod, mmframeclass, typeclass, i)
- multimethods[name] = code
- # add some more multimethods with a special interface
- code = MultimethodCode(spaceclass.next, NextMmFrame, typeclass)
- multimethods['next'] = code
- code = MultimethodCode(spaceclass.is_true, NonZeroMmFrame, typeclass)
- multimethods['__nonzero__'] = code
- return multimethods
+## def lookup_exactly_here(w_self, w_key):
+## space = w_self.space
+## multimethods = getmultimethods(space.__class__, w_self.__class__)
+## key = space.unwrap(w_key)
+## if not isinstance(key, str):
+## raise OperationError(space.w_TypeError,
+## space.wrap('attribute name must be string'))
+## try:
+## code = multimethods[key]
+## except KeyError:
+## raise KeyError # pass on the KeyError
+## if code.slice().is_empty():
+## raise KeyError
+## fn = function.Function(space, code, defs_w=code.getdefaults(space))
+## return space.wrap(fn)
+
+
+##def hack_out_multimethods(cls):
+## result = []
+## for base in cls.__bases__:
+## result += hack_out_multimethods(base)
+## for value in cls.__dict__.itervalues():
+## if isinstance(value, MultiMethod):
+## result.append(value)
+## return result
+
+##AllSlicedMultimethods = {}
+
+##def getmultimethods(spaceclass, typeclass):
+## try:
+## multimethods = AllSlicedMultimethods[spaceclass, typeclass]
+## except KeyError:
+## multimethods = AllSlicedMultimethods[spaceclass, typeclass] = {}
+## # import all multimethods of the type class and of the objspace
+## for multimethod in (hack_out_multimethods(typeclass) +
+## hack_out_multimethods(spaceclass)):
+## for i in range(len(multimethod.specialnames)):
+## # each MultimethodCode embeds a multimethod
+## name = multimethod.specialnames[i]
+## if name in multimethods:
+## # conflict between e.g. __lt__ and
+## # __lt__-as-reversed-version-of-__gt__
+## code = multimethods[name]
+## if code.bound_position < i:
+## continue
+## mmframeclass = multimethod.extras.get('mmframeclass')
+## if mmframeclass is None:
+## if len(multimethod.specialnames) > 1:
+## mmframeclass = SpecialMmFrame
+## else:
+## mmframeclass = MmFrame
+## code = MultimethodCode(multimethod, mmframeclass, typeclass, i)
+## multimethods[name] = code
+## # add some more multimethods with a special interface
+## code = MultimethodCode(spaceclass.next, NextMmFrame, typeclass)
+## multimethods['next'] = code
+## code = MultimethodCode(spaceclass.is_true, NonZeroMmFrame, typeclass)
+## multimethods['__nonzero__'] = code
+## return multimethods
-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):
- eval.Code.__init__(self, multimethod.operatorsymbol)
- self.basemultimethod = multimethod
- self.typeclass = typeclass
- self.bound_position = bound_position
- self.framecls = framecls
- argnames = ['x%d'%(i+1) for i in range(multimethod.arity)]
- argnames.insert(0, argnames.pop(self.bound_position))
- varargname = kwargname = None
- if multimethod.extras.get('varargs', False):
- varargname = 'args'
- if multimethod.extras.get('keywords', False):
- kwargname = 'keywords'
- self.sig = argnames, varargname, kwargname
+## def __init__(self, multimethod, framecls, typeclass, bound_position=0):
+## eval.Code.__init__(self, multimethod.operatorsymbol)
+## self.basemultimethod = multimethod
+## self.typeclass = typeclass
+## self.bound_position = bound_position
+## self.framecls = framecls
+## argnames = ['x%d'%(i+1) for i in range(multimethod.arity)]
+## argnames.insert(0, argnames.pop(self.bound_position))
+## varargname = kwargname = None
+## if multimethod.extras.get('varargs', False):
+## varargname = 'args'
+## if multimethod.extras.get('keywords', False):
+## kwargname = 'keywords'
+## self.sig = argnames, varargname, kwargname
- def signature(self):
- return self.sig
+## def signature(self):
+## return self.sig
- def getdefaults(self, space):
- return [space.wrap(x)
- for x in self.basemultimethod.extras.get('defaults', ())]
-
- def slice(self):
- return self.basemultimethod.slice(self.typeclass, self.bound_position)
-
- def create_frame(self, space, w_globals, closure=None):
- return self.framecls(space, self)
-
-class MmFrame(eval.Frame):
- def run(self):
- "Call the multimethod, raising a TypeError if not implemented."
- mm = self.code.slice().get(self.space)
- args = self.fastlocals_w
- w_result = mm(*args)
- # 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
-
-class SpecialMmFrame(eval.Frame):
- def run(self):
- "Call the multimethods, possibly returning a NotImplemented."
- mm = self.code.slice().get(self.space)
- args = self.fastlocals_w
- try:
- return mm.perform_call(args)
- except FailedToImplement, e:
- if e.args:
- raise OperationError(*e.args)
- else:
- return self.space.w_NotImplemented
-
-class NextMmFrame(eval.Frame):
- def run(self):
- "Call the next() multimethod."
- mm = self.code.slice().get(self.space)
- args = self.fastlocals_w
- return mm(*args)
-
-class NonZeroMmFrame(eval.Frame):
- def run(self):
- "Call the is_true() multimethods."
- mm = self.code.slice().get(self.space)
- args = self.fastlocals_w
- result = mm(*args)
- return self.space.newbool(result)
-
-# see also class NewMmFrame in typetype.py
-
-
-def call__Type_ANY_ANY(space, w_type, w_args, w_kwds):
- type_new = typetype.W_TypeType.type_new.get(space)
- w_newobject, callinit = type_new(w_type, w_type, w_args, w_kwds)
- if callinit:
- import objecttype
- object_init = objecttype.W_ObjectType.object_init.get(space)
- object_init(w_newobject, w_args, w_kwds)
+## def getdefaults(self, space):
+## return [space.wrap(x)
+## for x in self.basemultimethod.extras.get('defaults', ())]
+
+## def slice(self):
+## return self.basemultimethod.slice(self.typeclass, self.bound_position)
+
+## def create_frame(self, space, w_globals, closure=None):
+## return self.framecls(space, self)
+
+##class MmFrame(eval.Frame):
+## def run(self):
+## "Call the multimethod, raising a TypeError if not implemented."
+## mm = self.code.slice().get(self.space)
+## args = self.fastlocals_w
+## w_result = mm(*args)
+## # 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
+
+##class SpecialMmFrame(eval.Frame):
+## def run(self):
+## "Call the multimethods, possibly returning a NotImplemented."
+## mm = self.code.slice().get(self.space)
+## args = self.fastlocals_w
+## try:
+## return mm.perform_call(args)
+## except FailedToImplement, e:
+## if e.args:
+## raise OperationError(*e.args)
+## else:
+## return self.space.w_NotImplemented
+
+##class NextMmFrame(eval.Frame):
+## def run(self):
+## "Call the next() multimethod."
+## mm = self.code.slice().get(self.space)
+## args = self.fastlocals_w
+## try:
+## return mm(*args)
+## except NoValue:
+## raise OperationError(self.space.w_StopIteration,
+## self.space.w_None)
+
+##class NonZeroMmFrame(eval.Frame):
+## def run(self):
+## "Call the is_true() multimethods."
+## mm = self.code.slice().get(self.space)
+## args = self.fastlocals_w
+## result = mm(*args)
+## return self.space.newbool(result)
+
+
+def call__Type(space, w_type, w_args, w_kwds):
+ args_w = space.unpacktuple(w_args)
+ # special case for type(x)
+ if (space.is_true(space.is_(w_type, space.w_type)) and
+ len(args_w) == 1 and not space.is_true(w_kwds)):
+ return space.type(args_w[0])
+ # invoke the __new__ of the type
+ w_descr = w_type.lookup('__new__')
+ w_extendedargs = space.newtuple([w_type] + args_w)
+ w_newobject = space.call(w_descr, w_extendedargs, w_kwds)
+ # maybe invoke the __init__ of the type
+ if space.is_true(space.isinstance(w_newobject, w_type)):
+ w_descr = space.lookup(w_newobject, '__init__')
+ if w_descr is not None:
+ space.get_and_call(w_descr, w_newobject, w_args, w_kwds)
return w_newobject
def issubtype__Type_Type(space, w_type1, w_type2):
@@ -206,19 +188,23 @@
def repr__Type(space, w_obj):
return space.wrap("<pypy type '%s'>" % w_obj.typename) # XXX remove 'pypy'
-def getattribute__Type_ANY(space, w_type, w_attr):
- # XXX mwh doubts this is the Right Way to do this...
- if space.is_true(space.eq(w_attr, space.wrap('__name__'))):
- return w_type.w_tpname
- if space.is_true(space.eq(w_attr, space.wrap('__mro__'))):
- return space.newtuple(list(w_type.getmro()))
- if space.is_true(space.eq(w_attr, space.wrap('__bases__'))):
- return space.newtuple(list(w_type.getbases()))
- try:
- desc = w_type.lookup(w_attr)
- except KeyError:
- raise FailedToImplement #OperationError(space.w_AttributeError,w_attr)
- return space.get(desc, space.w_None, w_type)
+def getattr__Type_ANY(space, w_type, w_name):
+ name = space.unwrap(w_name)
+ w_descr = space.lookup(w_type, name)
+ if w_descr is not None:
+ if space.is_data_descr(w_descr):
+ return space.get(w_descr,w_type,space.type(w_type))
+ w_value = w_type.lookup(name)
+ if w_value is not None:
+ # __get__(None, type): turns e.g. functions into unbound methods
+ return space.get(w_value, space.w_None, w_type)
+ if w_descr is not None:
+ return space.get(w_descr,w_type,space.type(w_type))
+ raise OperationError(space.w_AttributeError,w_name)
+
+# XXX __setattr__
+# XXX __delattr__
+# XXX __hash__ ??
register_all(vars())
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/std/typetype.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/std/typetype.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/std/typetype.py Fri Jun 4 16:16:45 2004
@@ -1,51 +1,39 @@
-from pypy.objspace.std.objspace import *
-from pypy.objspace.std.register_all import register_all
-from pypy.interpreter import eval
-from typeobject import W_TypeObject
-
-
-class NewMmFrame(eval.Frame):
- def run(self):
- "Call the __new__() method of typetype.py."
- mm = self.code.slice().get(self.space)
- args = self.fastlocals_w
- w_result, callinit = mm(*args)
- return w_result
-
-
-class W_TypeType(W_TypeObject):
- """The single instance of this class is the object the user sees as
- '__builtin__.type'."""
-
- typename = 'type'
-
- # XXX this is worth tons of comments.
- # the four arguments are (T, S, args, kw) for the expression
- # T.__new__(S, *args, **kw). There is no (known?) way to get it as
- # an unbound method, because 'type.__new__' means reading from the
- # instance 'type' of the class 'type', as opposed to reading from
- # the class 'type'.
- # Attention, this internally returns a tuple (w_result, flag),
- # where 'flag' specifies whether we would like __init__() to be called.
- type_new = MultiMethod('__new__', 2, varargs=True, keywords=True,
- mmframeclass=NewMmFrame)
-
-registerimplementation(W_TypeType)
-
-def type_new__TypeType_TypeType(space, w_basetype, w_typetype, w_args, w_kwds):
- if space.is_true(w_kwds):
- raise OperationError(space.w_TypeError,
- space.wrap("no keyword arguments expected"))
- args = space.unpackiterable(w_args)
- if len(args) == 1:
- return space.type(args[0]), False # don't call __init__() on that
- elif len(args) == 3:
- from usertype import W_UserType
- w_name, w_bases, w_dict = args
- w_usertype = W_UserType(space, w_name, w_bases, w_dict)
- return w_usertype, True
- else:
- raise OperationError(space.w_TypeError,
- space.wrap("type() takes 1 or 3 arguments"))
+from pypy.objspace.std.stdtypedef import *
+from pypy.objspace.std.objecttype import object_typedef
-register_all(vars())
+
+def descr__new__(space, w_typetype, w_name, w_bases, w_dict):
+ # XXX staticmethod-ify w_dict['__new__']
+ from pypy.objspace.std.typeobject import W_TypeObject
+ # XXX check types
+ name = space.unwrap(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:
+ key = space.unwrap(w_key)
+ assert isinstance(key, str)
+ dict_w[key] = space.getitem(w_dict, w_key)
+ return W_TypeObject(space, name, bases_w, dict_w)
+
+def descr_get__mro__(space, w_type):
+ # XXX this should be inside typeobject.py
+ return space.newtuple(w_type.getmro())
+
+def descr__dict__(space, w_type):
+ # XXX should return a <dictproxy object>
+ dictspec = []
+ for key, w_value in w_type.dict_w.items():
+ dictspec.append((space.wrap(key), w_value))
+ return space.newdict(dictspec)
+
+# ____________________________________________________________
+
+type_typedef = StdTypeDef("type", [object_typedef],
+ __new__ = newmethod(descr__new__),
+ __name__ = attrproperty('name'),
+ #__bases__ = XXX use newtuple
+ __dict__ = GetSetProperty(descr__dict__),
+ __mro__ = GetSetProperty(descr_get__mro__),
+ )
Modified: pypy/branch/src-newobjectmodel/pypy/objspace/trivial.py
==============================================================================
--- pypy/branch/src-newobjectmodel/pypy/objspace/trivial.py (original)
+++ pypy/branch/src-newobjectmodel/pypy/objspace/trivial.py Fri Jun 4 16:16:45 2004
@@ -200,6 +200,9 @@
def is_(self, w_obj1, w_obj2):
return self.unwrap(w_obj1) is self.unwrap(w_obj2)
+ def id(self, w_obj):
+ return id(self.unwrap(w_obj))
+
def unpacktuple(self, w_tuple, expected_length=None):
assert isinstance(w_tuple, tuple)
if expected_length is not None and expected_length != len(w_tuple):
@@ -250,7 +253,7 @@
is_true = operator.truth
# 'is_true' is not called 'truth' because it returns a *non-wrapped* boolean
- for _name in ('id', 'type', 'ord', 'round'):
+ for _name in ('type', 'ord', 'round'):
_auto(_name, _name, locals())
def not_(self, w_obj): # default implementation
More information about the Pypy-commit
mailing list