Author: Ronan Lamy <[email protected]>
Branch: kill-ootype
Changeset: r65656:9483b6d294d3
Date: 2013-07-25 18:10 +0100
http://bitbucket.org/pypy/pypy/changeset/9483b6d294d3/
Log: hg rm pypy/module/clr/
diff --git a/pypy/module/clr/__init__.py b/pypy/module/clr/__init__.py
deleted file mode 100644
--- a/pypy/module/clr/__init__.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# Package initialisation
-from pypy.interpreter.mixedmodule import MixedModule
-
-import boxing_rules # with side effects
-
-class Module(MixedModule):
- """CLR module"""
-
- appleveldefs = {
- 'dotnetimporter': 'app_importer.importer'
- }
-
- interpleveldefs = {
- '_CliObject_internal': 'interp_clr.W_CliObject',
- 'call_staticmethod': 'interp_clr.call_staticmethod',
- 'load_cli_class': 'interp_clr.load_cli_class',
- 'get_assemblies_info': 'interp_clr.get_assemblies_info',
- 'AddReferenceByPartialName': 'interp_clr.AddReferenceByPartialName',
- }
-
- def startup(self, space):
- self.space.appexec([self], """(clr_module):
- import sys
- clr_module.get_assemblies_info() # load info for std assemblies
- sys.meta_path.append(clr_module.dotnetimporter())
- """)
diff --git a/pypy/module/clr/app_clr.py b/pypy/module/clr/app_clr.py
deleted file mode 100644
--- a/pypy/module/clr/app_clr.py
+++ /dev/null
@@ -1,204 +0,0 @@
-# NOT_RPYTHON
-
-class StaticMethodWrapper(object):
- __slots__ = ('class_name', 'meth_name',)
-
- def __init__(self, class_name, meth_name):
- self.class_name = class_name
- self.meth_name = meth_name
-
- def __call__(self, *args):
- import clr
- return clr.call_staticmethod(self.class_name, self.meth_name, args)
-
- def __repr__(self):
- return '<static CLI method %s.%s>' % (self.class_name, self.meth_name)
-
-
-class MethodWrapper(object):
- __slots__ = ('meth_name',)
-
- def __init__(self, meth_name):
- self.meth_name = meth_name
-
- def __get__(self, obj, type_):
- if obj is None:
- return UnboundMethod(type_, self.meth_name)
- else:
- return BoundMethod(self.meth_name, obj)
-
- def __repr__(self):
- return '%s(%s)' % (self.__class__.__name__, repr(self.meth_name))
-
-
-class UnboundMethod(object):
- __slots__ = ('im_class', 'im_name')
-
- def __init__(self, im_class, im_name):
- self.im_class = im_class
- self.im_name = im_name
-
- def __raise_TypeError(self, thing):
- raise TypeError, 'unbound method %s() must be called with %s ' \
- 'instance as first argument (got %s instead)' % \
- (self.im_name, self.im_class.__cliclass__, thing)
-
- def __call__(self, *args):
- if len(args) == 0:
- self.__raise_TypeError('nothing')
- im_self = args[0]
- if not isinstance(im_self, self.im_class):
- self.__raise_TypeError('%s instance' % im_self.__class__.__name__)
- return im_self.__cliobj__.call_method(self.im_name, args, 1) # ignore
the first arg
-
- def __repr__(self):
- return '<unbound CLI method %s.%s>' % (self.im_class.__cliclass__,
self.im_name)
-
-
-class BoundMethod(object):
- __slots__ = ('im_name', 'im_self')
-
- def __init__(self, im_name, im_self):
- self.im_name = im_name
- self.im_self = im_self
-
- def __call__(self, *args):
- return self.im_self.__cliobj__.call_method(self.im_name, args)
-
- def __repr__(self):
- return '<bound CLI method %s.%s of %s>' %
(self.im_self.__class__.__cliclass__,
- self.im_name,
- self.im_self)
-
-class StaticProperty(object):
- def __init__(self, fget=None, fset=None):
- self.fget = fget
- self.fset = fset
-
- def __get__(self, obj, type_):
- return self.fget()
-
-def _qualify(t):
- mscorlib = 'mscorlib, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'
- return '%s, %s' % (t, mscorlib)
-
-class MetaGenericCliClassWrapper(type):
- _cli_types = {
- int: _qualify('System.Int32'),
- str: _qualify('System.String'),
- bool: _qualify('System.Boolean'),
- float: _qualify('System.Double'),
- }
- _System_Object = _qualify('System.Object')
-
- def _cli_name(cls, ttype):
- if isinstance(ttype, MetaCliClassWrapper):
- return '[%s]' % ttype.__fullyqualifiedname__
- else:
- return '[%s]' % cls._cli_types.get(ttype, cls._System_Object)
-
- def __setattr__(cls, name, value):
- obj = cls.__dict__.get(name, None)
- if isinstance(obj, StaticProperty):
- obj.fset(value)
- else:
- type.__setattr__(cls, name, value)
-
- def __getitem__(cls, type_or_tuple):
- import clr
- if isinstance(type_or_tuple, tuple):
- types = type_or_tuple
- else:
- types = (type_or_tuple,)
- namespace, generic_class = cls.__cliclass__.rsplit('.', 1)
- generic_params = [cls._cli_name(t) for t in types]
- instance_class = '%s[%s]' % (generic_class, ','.join(generic_params))
- try:
- return clr.load_cli_class(cls.__assemblyname__, namespace,
instance_class)
- except ImportError:
- raise TypeError, "Cannot load type %s.%s" % (namespace,
instance_class)
-
-class MetaCliClassWrapper(type):
- def __setattr__(cls, name, value):
- obj = cls.__dict__.get(name, None)
- if isinstance(obj, StaticProperty):
- obj.fset(value)
- else:
- type.__setattr__(cls, name, value)
-
-class CliClassWrapper(object):
- __slots__ = ('__cliobj__',)
-
- def __init__(self, *args):
- import clr
- self.__cliobj__ = clr._CliObject_internal(self.__fullyqualifiedname__,
args)
-
-
-class IEnumeratorWrapper(object):
- def __init__(self, enumerator):
- self.__enumerator__ = enumerator
-
- def __iter__(self):
- return self
-
- def next(self):
- if not self.__enumerator__.MoveNext():
- raise StopIteration
- return self.__enumerator__.Current
-
-# this method need to be attached only to classes that implements IEnumerable
(see build_wrapper)
-def __iter__(self):
- return IEnumeratorWrapper(self.GetEnumerator())
-
-def wrapper_from_cliobj(cls, cliobj):
- obj = cls.__new__(cls)
- obj.__cliobj__ = cliobj
- return obj
-
-def build_wrapper(namespace, classname, assemblyname,
- staticmethods, methods, properties, indexers,
- hasIEnumerable, isClassGeneric):
- fullname = '%s.%s' % (namespace, classname)
- assembly_qualified_name = '%s, %s' % (fullname, assemblyname)
- d = {'__cliclass__': fullname,
- '__fullyqualifiedname__': assembly_qualified_name,
- '__assemblyname__': assemblyname,
- '__module__': namespace}
- for name in staticmethods:
- d[name] = StaticMethodWrapper(assembly_qualified_name, name)
- for name in methods:
- d[name] = MethodWrapper(name)
-
- # check if IEnumerable is implemented
- if hasIEnumerable:
- d['__iter__'] = __iter__
-
- assert len(indexers) <= 1
- if indexers:
- name, getter, setter, is_static = indexers[0]
- assert not is_static
- if getter:
- d['__getitem__'] = d[getter]
- if setter:
- d['__setitem__'] = d[setter]
- if isClassGeneric:
- cls = MetaGenericCliClassWrapper(classname, (CliClassWrapper,), d)
- else:
- cls = MetaCliClassWrapper(classname, (CliClassWrapper,), d)
-
- # we must add properties *after* the class has been created
- # because we need to store UnboundMethods as getters and setters
- for (name, getter, setter, is_static) in properties:
- fget = None
- fset = None
- if getter:
- fget = getattr(cls, getter)
- if setter:
- fset = getattr(cls, setter)
- if is_static:
- prop = StaticProperty(fget, fset)
- else:
- prop = property(fget, fset)
- setattr(cls, name, prop)
-
- return cls
diff --git a/pypy/module/clr/app_importer.py b/pypy/module/clr/app_importer.py
deleted file mode 100644
--- a/pypy/module/clr/app_importer.py
+++ /dev/null
@@ -1,85 +0,0 @@
-"""NOT_RPYTHON"""
-
-# Meta hooks are called at the start of Import Processing
-# Meta hooks can override the sys.path, frozen modules , built-in modules
-# To register a Meta Hook simply add importer object to sys.meta_path
-
-import sys
-import types
-
-class importer(object):
- '''
- If the importer is installed on sys.meta_path, it will
- receive a second argument, which is None for a top-level module, or
- package.__path__ for submodules or subpackages
-
- It should return a loader object if the module was found, or None if
it wasn\'t.
- If find_module() raises an exception, the caller will abort the
import.
- When importer.find_module("spam.eggs.ham") is called, "spam.eggs" has
already
- been imported and added to sys.modules.
- '''
-
- def find_module(self, fullname, path=None):
- import clr
- namespaces, classes, generics = clr.get_assemblies_info()
-
- if fullname in namespaces or fullname in classes:
- return self # fullname is a .NET Module
- else:
- return None # fullname is not a .NET Module
-
- def load_module(self, fullname):
- '''
- The load_module() must fulfill the following *before* it runs any
code:
- Note that the module object *must* be in sys.modules before the
- loader executes the module code.
-
- A If 'fullname' exists in sys.modules, the loader must use that
- else the loader must create a new module object and add it to
sys.modules.
-
- module = sys.modules.setdefault(fullname, new.module(fullname))
-
- B The __file__ attribute must be set. String say "<frozen>"
-
- C The __name__ attribute must be set. If one uses
- imp.new_module() then the attribute is set automatically.
-
- D If it\'s a package, the __path__ variable must be set. This must
- be a list, but may be empty if __path__ has no further
- significance to the importer (more on this later).
-
- E It should add a __loader__ attribute to the module, set to the
loader object.
-
- '''
- # If it is a call for a Class then return with the Class reference
- import clr
- namespaces, classes, generics = clr.get_assemblies_info()
-
- if fullname in classes:
- assemblyname = classes[fullname]
- fullname = generics.get(fullname, fullname)
- ns, classname = fullname.rsplit('.', 1)
- sys.modules[fullname] = clr.load_cli_class(assemblyname, ns,
classname)
- else: # if not a call for actual class (say for namespaces) assign an
empty module
- if fullname not in sys.modules:
- mod = CLRModule(fullname)
- mod.__file__ = "<%s>" % self.__class__.__name__
- mod.__loader__ = self
- mod.__name__ = fullname
- # add it to the modules dict
- sys.modules[fullname] = mod
-
- # if it is a PACKAGE then we are to initialize the __path__ for
the module
- # we won't deal with Packages here
- return sys.modules[fullname]
-
-class CLRModule(types.ModuleType):
- def __getattr__(self, name):
- if not name.startswith("__"):
- try:
- iname = self.__name__ + '.' + name
- __import__(iname)
- except ImportError:
- pass
- return types.ModuleType.__getattribute__(self, name)
-
diff --git a/pypy/module/clr/assemblyname.py b/pypy/module/clr/assemblyname.py
deleted file mode 100644
--- a/pypy/module/clr/assemblyname.py
+++ /dev/null
@@ -1,2 +0,0 @@
-mscorlib = 'mscorlib, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'
-System = 'System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'
diff --git a/pypy/module/clr/boxing_rules.py b/pypy/module/clr/boxing_rules.py
deleted file mode 100644
--- a/pypy/module/clr/boxing_rules.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from rpython.tool.pairtype import extendabletype
-from pypy.interpreter.baseobjspace import W_Root
-from pypy.objspace.std.intobject import W_IntObject
-from pypy.objspace.std.floatobject import W_FloatObject
-from pypy.objspace.std.boolobject import W_BoolObject
-from pypy.objspace.std.noneobject import W_NoneObject
-from pypy.objspace.std.stringobject import W_StringObject
-from rpython.translator.cli.dotnet import box
-
-class __extend__(W_Root):
- __metaclass__ = extendabletype
-
- def tocli(self):
- return box(self)
-
-class __extend__(W_IntObject):
- __metaclass__ = extendabletype
-
- def tocli(self):
- return box(self.intval)
-
-class __extend__(W_FloatObject):
- __metaclass__ = extendabletype
-
- def tocli(self):
- return box(self.floatval)
-
-class __extend__(W_NoneObject):
- __metaclass__ = extendabletype
-
- def tocli(self):
- return None
-
-class __extend__(W_BoolObject):
- __metaclass__ = extendabletype
-
- def tocli(self):
- return box(self.boolval)
-
-class __extend__(W_StringObject):
- __metaclass__ = extendabletype
-
- def tocli(self):
- return box(self._value)
-
-##from pypy.objspace.fake.objspace import W_Object as W_Object_Fake
-##from rpython.rlib.nonconst import NonConstant
-
-##class __extend__(W_Object_Fake):
-## __metaclass__ = extendabletype
-
-## def tocli(self):
-## return NonConstant(None)
diff --git a/pypy/module/clr/interp_clr.py b/pypy/module/clr/interp_clr.py
deleted file mode 100644
--- a/pypy/module/clr/interp_clr.py
+++ /dev/null
@@ -1,364 +0,0 @@
-import os.path
-from pypy.module.clr import assemblyname
-from pypy.interpreter.baseobjspace import W_Root, W_Root
-from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.gateway import interp2app, unwrap_spec, ApplevelClass
-from pypy.interpreter.typedef import TypeDef
-from rpython.rtyper.ootypesystem import ootype
-from rpython.translator.cli.dotnet import CLR, box, unbox, NativeException,
native_exc,\
- new_array, init_array, typeof
-
-System = CLR.System
-Assembly = CLR.System.Reflection.Assembly
-TargetInvocationException =
NativeException(CLR.System.Reflection.TargetInvocationException)
-AmbiguousMatchException =
NativeException(CLR.System.Reflection.AmbiguousMatchException)
-
-def get_method(space, b_type, name, b_paramtypes):
- try:
- method = b_type.GetMethod(name, b_paramtypes)
- except AmbiguousMatchException:
- msg = 'Multiple overloads for %s could match'
- raise operationerrfmt(space.w_TypeError, msg, name)
- if method is None:
- msg = 'No overloads for %s could match'
- raise operationerrfmt(space.w_TypeError, msg, name)
- return method
-
-def get_constructor(space, b_type, b_paramtypes):
- try:
- ctor = b_type.GetConstructor(b_paramtypes)
- except AmbiguousMatchException:
- msg = 'Multiple constructors could match'
- raise OperationError(space.w_TypeError, space.wrap(msg))
- if ctor is None:
- msg = 'No overloads for constructor could match'
- raise OperationError(space.w_TypeError, space.wrap(msg))
- return ctor
-
-def rewrap_args(space, w_args, startfrom):
- args = space.unpackiterable(w_args)
- paramlen = len(args)-startfrom
- b_args = new_array(System.Object, paramlen)
- b_paramtypes = new_array(System.Type, paramlen)
- for i in range(startfrom, len(args)):
- j = i-startfrom
- b_obj = py2cli(space, args[i])
- b_args[j] = b_obj
- if b_obj is None:
- b_paramtypes[j] = typeof(System.Object) # we really can't be more
precise
- else:
- b_paramtypes[j] = b_obj.GetType() # XXX: potentially inefficient
- return b_args, b_paramtypes
-
-
-def call_method(space, b_obj, b_type, name, w_args, startfrom):
- b_args, b_paramtypes = rewrap_args(space, w_args, startfrom)
- b_meth = get_method(space, b_type, name, b_paramtypes)
- try:
- # for an explanation of the box() call, see the log message for
revision 35167
- b_res = box(b_meth.Invoke(b_obj, b_args))
- except TargetInvocationException, e:
- b_inner = native_exc(e).get_InnerException()
- message = str(b_inner.get_Message())
- # TODO: use the appropriate exception, not StandardError
- raise OperationError(space.w_StandardError, space.wrap(message))
- if b_meth.get_ReturnType().get_Name() == 'Void':
- return space.w_None
- else:
- return cli2py(space, b_res)
-
-@unwrap_spec(typename=str, methname=str)
-def call_staticmethod(space, typename, methname, w_args):
- """
- Call a .NET static method.
-
- Parameters:
-
- - typename: the fully qualified .NET name of the class
- containing the method (e.g. ``System.Math``)
-
- - methname: the name of the static method to call (e.g. ``Abs``)
-
- - args: a list containing the arguments to be passed to the
- method.
- """
- b_type = System.Type.GetType(typename) # XXX: cache this!
- return call_method(space, None, b_type, methname, w_args, 0)
-
-def py2cli(space, w_obj):
- try:
- cliobj = space.getattr(w_obj, space.wrap('__cliobj__'))
- except OperationError, e:
- if e.match(space, space.w_AttributeError):
- # it hasn't got a __cloobj__
- return w_obj.tocli()
- else:
- raise
- else:
- if isinstance(cliobj, W_CliObject):
- return cliobj.b_obj # unwrap it!
- else:
- # this shouldn't happen! Fallback to the default impl
- return w_obj.tocli()
-
-def cli2py(space, b_obj):
- # TODO: support other types and find the most efficient way to
- # select the correct case
- if b_obj is None:
- return space.w_None
-
- w_obj = unbox(b_obj, W_Root)
- if w_obj is not None:
- return w_obj # it's already a wrapped object!
-
- b_type = b_obj.GetType()
- if b_type == typeof(System.Int32):
- intval = unbox(b_obj, ootype.Signed)
- return space.wrap(intval)
- elif b_type == typeof(System.Double):
- floatval = unbox(b_obj, ootype.Float)
- return space.wrap(floatval)
- elif b_type == typeof(System.Boolean):
- boolval = unbox(b_obj, ootype.Bool)
- return space.wrap(boolval)
- elif b_type == typeof(System.String):
- strval = unbox(b_obj, ootype.String)
- return space.wrap(strval)
- else:
- namespace, classname = split_fullname(b_type.ToString())
- assemblyname = b_type.get_Assembly().get_FullName()
- w_cls = load_cli_class(space, assemblyname, namespace, classname)
- cliobj = W_CliObject(space, b_obj)
- return wrapper_from_cliobj(space, w_cls, cliobj)
-
-def split_fullname(name):
- lastdot = name.rfind('.')
- if lastdot < 0:
- return '', name
- return name[:lastdot], name[lastdot+1:]
-
-def wrap_list_of_tuples(space, lst):
- list_w = []
- for (a,b,c,d) in lst:
- items_w = [space.wrap(a), space.wrap(b), space.wrap(c), space.wrap(d)]
- list_w.append(space.newtuple(items_w))
- return space.newlist(list_w)
-
-def wrap_list_of_pairs(space, lst):
- list_w = []
- for (a,b) in lst:
- items_w = [space.wrap(a), space.wrap(b)]
- list_w.append(space.newtuple(items_w))
- return space.newlist(list_w)
-
-def wrap_list_of_strings(space, lst):
- list_w = [space.wrap(s) for s in lst]
- return space.newlist(list_w)
-
-def get_methods(space, b_type):
- methods = []
- staticmethods = []
- b_methodinfos = b_type.GetMethods()
- for i in range(len(b_methodinfos)):
- b_meth = b_methodinfos[i]
- if b_meth.get_IsPublic():
- if b_meth.get_IsStatic():
- staticmethods.append(str(b_meth.get_Name()))
- else:
- methods.append(str(b_meth.get_Name()))
- w_staticmethods = wrap_list_of_strings(space, staticmethods)
- w_methods = wrap_list_of_strings(space, methods)
- return w_staticmethods, w_methods
-
-def get_properties(space, b_type):
- properties = []
- indexers = {}
- b_propertyinfos = b_type.GetProperties()
- for i in range(len(b_propertyinfos)):
- b_prop = b_propertyinfos[i]
- get_name = None
- set_name = None
- is_static = False
- if b_prop.get_CanRead():
- get_meth = b_prop.GetGetMethod()
- get_name = get_meth.get_Name()
- is_static = get_meth.get_IsStatic()
- if b_prop.get_CanWrite():
- set_meth = b_prop.GetSetMethod()
- if set_meth:
- set_name = set_meth.get_Name()
- is_static = set_meth.get_IsStatic()
- b_indexparams = b_prop.GetIndexParameters()
- if len(b_indexparams) == 0:
- properties.append((b_prop.get_Name(), get_name, set_name,
is_static))
- else:
- indexers[b_prop.get_Name(), get_name, set_name, is_static] = None
- w_properties = wrap_list_of_tuples(space, properties)
- w_indexers = wrap_list_of_tuples(space, indexers.keys())
- return w_properties, w_indexers
-
-class _CliClassCache:
- def __init__(self):
- self.cache = {}
-
- def put(self, fullname, cls):
- assert fullname not in self.cache
- self.cache[fullname] = cls
-
- def get(self, fullname):
- return self.cache.get(fullname, None)
-CliClassCache = _CliClassCache()
-
-class _AssembliesInfo:
- w_namespaces = None
- w_classes = None
- w_generics = None
- w_info = None # a tuple containing (w_namespaces, w_classes, w_generics)
-AssembliesInfo = _AssembliesInfo()
-
-def save_info_for_assembly(space, b_assembly):
- info = AssembliesInfo
- b_types = b_assembly.GetTypes()
- w_assemblyName = space.wrap(b_assembly.get_FullName())
- for i in range(len(b_types)):
- b_type = b_types[i]
- namespace = b_type.get_Namespace()
- fullname = b_type.get_FullName()
- if '+' in fullname:
- # it's an internal type, skip it
- continue
- if namespace is not None:
- # builds all possible sub-namespaces
- # (e.g. 'System', 'System.Windows', 'System.Windows.Forms')
- chunks = namespace.split(".")
- temp_name = chunks[0]
- space.setitem(info.w_namespaces, space.wrap(temp_name),
space.w_None)
- for chunk in chunks[1:]:
- temp_name += "."+chunk
- space.setitem(info.w_namespaces, space.wrap(temp_name),
space.w_None)
- if b_type.get_IsGenericType():
- index = fullname.rfind("`")
- assert index >= 0
- pyName = fullname[0:index]
- space.setitem(info.w_classes, space.wrap(pyName), w_assemblyName)
- space.setitem(info.w_generics, space.wrap(pyName),
space.wrap(fullname))
- else:
- space.setitem(info.w_classes, space.wrap(fullname), w_assemblyName)
-
-
-def save_info_for_std_assemblies(space):
- # in theory we should use Assembly.Load, but it doesn't work with
- # pythonnet because it thinks it should use the Load(byte[]) overload
- b_mscorlib = Assembly.LoadWithPartialName(assemblyname.mscorlib)
- b_System = Assembly.LoadWithPartialName(assemblyname.System)
- save_info_for_assembly(space, b_mscorlib)
- save_info_for_assembly(space, b_System)
-
-def get_assemblies_info(space):
- info = AssembliesInfo
- if info.w_info is None:
- info.w_namespaces = space.newdict()
- info.w_classes = space.newdict()
- info.w_generics = space.newdict()
- info.w_info = space.newtuple([info.w_namespaces, info.w_classes,
info.w_generics])
- save_info_for_std_assemblies(space)
- return info.w_info
-
-#_______________________________________________________________________________
-# AddReference* methods
-
-# AddReference', 'AddReferenceByName', 'AddReferenceByPartialName',
'AddReferenceToFile', 'AddReferenceToFileAndPath'
-
-@unwrap_spec(name=str)
-def AddReferenceByPartialName(space, name):
- b_assembly = Assembly.LoadWithPartialName(name)
- if b_assembly is not None:
- save_info_for_assembly(space, b_assembly)
-
-
-@unwrap_spec(assemblyname=str, namespace=str, classname=str)
-def load_cli_class(space, assemblyname, namespace, classname):
- """
- Load the given .NET class into the PyPy interpreter and return a
- Python class referencing to it.
-
- Parameters:
-
- - namespace: the full name of the namespace containing the
- class (e.g., ``System.Collections``).
-
- - classname: the name of the class in the specified namespace
- (e.g. ``ArrayList``). """
- fullname = '%s.%s' % (namespace, classname)
- w_cls = CliClassCache.get(fullname)
- if w_cls is None:
- w_cls = build_cli_class(space, namespace, classname, fullname,
assemblyname)
- CliClassCache.put(fullname, w_cls)
- return w_cls
-
-def build_cli_class(space, namespace, classname, fullname, assemblyname):
- assembly_qualified_name = '%s, %s' % (fullname, assemblyname)
- b_type = System.Type.GetType(assembly_qualified_name)
- if b_type is None:
- raise operationerrfmt(space.w_ImportError,
- "Cannot load .NET type: %s", fullname)
-
- # this is where we locate the interfaces inherited by the class
- # set the flag hasIEnumerable if IEnumerable interface has been by the
class
- hasIEnumerable = b_type.GetInterface("System.Collections.IEnumerable") is
not None
-
- # this is where we test if the class is Generic
- # set the flag isClassGeneric
- isClassGeneric = False
- if b_type.get_IsGenericType():
- isClassGeneric = True
-
- w_staticmethods, w_methods = get_methods(space, b_type)
- w_properties, w_indexers = get_properties(space, b_type)
- return build_wrapper(space,
- space.wrap(namespace),
- space.wrap(classname),
- space.wrap(assemblyname),
- w_staticmethods,
- w_methods,
- w_properties,
- w_indexers,
- space.wrap(hasIEnumerable),
- space.wrap(isClassGeneric))
-
-
-class W_CliObject(W_Root):
- def __init__(self, space, b_obj):
- self.space = space
- self.b_obj = b_obj
-
- @unwrap_spec(name=str, startfrom=int)
- def call_method(self, name, w_args, startfrom=0):
- return call_method(self.space, self.b_obj, self.b_obj.GetType(), name,
w_args, startfrom)
-
-@unwrap_spec(typename=str)
-def cli_object_new(space, w_subtype, typename, w_args):
- b_type = System.Type.GetType(typename)
- b_args, b_paramtypes = rewrap_args(space, w_args, 0)
- b_ctor = get_constructor(space, b_type, b_paramtypes)
- try:
- b_obj = b_ctor.Invoke(b_args)
- except TargetInvocationException, e:
- b_inner = native_exc(e).get_InnerException()
- message = str(b_inner.get_Message())
- # TODO: use the appropriate exception, not StandardError
- raise OperationError(space.w_StandardError, space.wrap(message))
- return space.wrap(W_CliObject(space, b_obj))
-
-W_CliObject.typedef = TypeDef(
- '_CliObject_internal',
- __new__ = interp2app(cli_object_new),
- call_method = interp2app(W_CliObject.call_method),
- )
-
-path, _ = os.path.split(__file__)
-app_clr = os.path.join(path, 'app_clr.py')
-app = ApplevelClass(file(app_clr).read())
-del path, app_clr
-build_wrapper = app.interphook("build_wrapper")
-wrapper_from_cliobj = app.interphook("wrapper_from_cliobj")
diff --git a/pypy/module/clr/test/__init__.py b/pypy/module/clr/test/__init__.py
deleted file mode 100644
--- a/pypy/module/clr/test/__init__.py
+++ /dev/null
@@ -1,1 +0,0 @@
-#
diff --git a/pypy/module/clr/test/test_clr.py b/pypy/module/clr/test/test_clr.py
deleted file mode 100644
--- a/pypy/module/clr/test/test_clr.py
+++ /dev/null
@@ -1,292 +0,0 @@
-from pypy.module.clr.assemblyname import mscorlib
-
-def skip_if_not_pythonnet():
- import py
- try:
- import clr
- except ImportError:
- py.test.skip('Must use pythonnet to access .NET libraries')
-
-skip_if_not_pythonnet()
-
-class AppTestDotnet:
- spaceconfig = dict(usemodules=('clr',))
-
- def setup_class(cls):
- cls.w_mscorlib = cls.space.wrap(mscorlib)
-
- def test_cliobject(self):
- import clr
- obj = clr._CliObject_internal('System.Collections.ArrayList', [])
- max_index = obj.call_method('Add', [42])
- assert max_index == 0
-
- def test_cache(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- ArrayList2 = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- assert ArrayList is ArrayList2
-
- def test_load_fail(self):
- import clr
- raises(ImportError, clr.load_cli_class, self.mscorlib, 'Foo', 'Bar')
-
- def test_ArrayList(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- obj.Add(42)
- obj.Add(43)
- total = obj.get_Item(0) + obj.get_Item(1)
- assert total == 42+43
-
- def test_ArrayList_error(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- raises(StandardError, obj.get_Item, 0)
-
- def test_float_conversion(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- obj.Add(42.0)
- item = obj.get_Item(0)
- assert isinstance(item, float)
-
- def test_bool_conversion(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- obj.Add(True)
- obj.Add(False)
- t = obj.get_Item(0)
- f = obj.get_Item(1)
- assert t and isinstance(t, bool)
- assert not f and isinstance(f, bool)
- obj.Add(42)
- assert obj.Contains(42)
-
- def test_getitem(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- obj.Add(42)
- assert obj[0] == 42
-
- def test_property(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- obj.Add(42)
- assert obj.Count == 1
- obj.Capacity = 10
- assert obj.Capacity == 10
-
- def test_unboundmethod(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- ArrayList.Add(obj, 42)
- assert obj.get_Item(0) == 42
-
- def test_unboundmethod_typeerror(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- raises(TypeError, ArrayList.Add)
- raises(TypeError, ArrayList.Add, 0)
-
- def test_overload(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList()
- for i in range(10):
- obj.Add(i)
- assert obj.IndexOf(7) == 7
- assert obj.IndexOf(7, 0, 5) == -1
-
- def test_wrong_overload(self):
- import clr
- Math = clr.load_cli_class(self.mscorlib, 'System', 'Math')
- raises(TypeError, Math.Abs, "foo")
-
- def test_wrong_overload_ctor(self):
- from System.Collections import ArrayList
- raises(TypeError, ArrayList, "foo")
-
- def test_staticmethod(self):
- import clr
- Math = clr.load_cli_class(self.mscorlib, 'System', 'Math')
- res = Math.Abs(-42)
- assert res == 42
- assert type(res) is int
- res = Math.Abs(-42.0)
- assert res == 42.0
- assert type(res) is float
-
- def test_constructor_args(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- obj = ArrayList(42)
- assert obj.Capacity == 42
-
- def test_None_as_null(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- Hashtable = clr.load_cli_class(self.mscorlib, 'System.Collections',
'Hashtable')
- x = ArrayList()
- x.Add(None)
- assert x[0] is None
- y = Hashtable()
- assert y["foo"] is None
-
- def test_pass_opaque_arguments(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- class Foo:
- pass
- obj = Foo()
- x = ArrayList()
- x.Add(obj)
- obj2 = x[0]
- assert obj is obj2
-
- def test_string_wrapping(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- x = ArrayList()
- x.Add("bar")
- s = x[0]
- assert s == "bar"
-
- def test_static_property(self):
- import clr
- import os
- Environment = clr.load_cli_class(self.mscorlib, 'System',
'Environment')
- assert Environment.CurrentDirectory == os.getcwd()
- Environment.CurrentDirectory == '/'
- assert Environment.CurrentDirectory == os.getcwd()
-
- def test_GetEnumerator(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- x = ArrayList()
- enum = x.GetEnumerator()
- assert enum.MoveNext() is False
-
- def test_iteration_arrayList(self):
- import clr
- ArrayList = clr.load_cli_class(self.mscorlib, 'System.Collections',
'ArrayList')
- x = ArrayList()
- x.Add(1)
- x.Add(2)
- x.Add(3)
- x.Add(4)
- sum = 0
- for i in x:
- sum += i
- assert sum == 1+2+3+4
-
- def test_iteration_stack(self):
- import clr
- Stack = clr.load_cli_class(self.mscorlib, 'System.Collections',
'Stack')
- obj = Stack()
- obj.Push(1)
- obj.Push(54)
- obj.Push(21)
- sum = 0
- for i in obj:
- sum += i
- assert sum == 1+54+21
-
- def test_load_generic_class(self):
- import clr
- ListInt = clr.load_cli_class(self.mscorlib,
"System.Collections.Generic", "List`1[System.Int32]")
- x = ListInt()
- x.Add(42)
- x.Add(4)
- x.Add(4)
- sum = 0
- for i in x:
- sum += i
- assert sum == 42+4+4
-
- def test_generic_class_typeerror(self):
- import clr
- ListInt = clr.load_cli_class(self.mscorlib,
"System.Collections.Generic", "List`1[System.Int32]")
- x = ListInt()
- raises(TypeError, x.Add, "test")
-
- def test_generic_dict(self):
- import clr
- genDictIntStr = clr.load_cli_class(self.mscorlib,
- "System.Collections.Generic",
-
"Dictionary`2[System.Int32,System.String]")
- x = genDictIntStr()
- x[1] = "test"
- x[2] = "rest"
- assert x[1] == "test"
- assert x[2] == "rest"
- raises(TypeError, x.__setitem__, 3, 3)
- raises(TypeError, x.__setitem__, 4, 4.453)
- raises(TypeError, x.__setitem__, "test", 3)
-
- def test_generic_metaclass_list(self):
- import clr
- from System.Collections.Generic import List
- import System.Int32
- lst = List[System.Int32]()
- lst.Add(42)
- assert lst[0] == 42
- raises(TypeError, lst.Add, "test")
-
- lst = List[int]()
- lst.Add(42)
- assert lst[0] == 42
- raises(TypeError, lst.Add, "test")
-
- def test_generic_metaclass_dict(self):
- import clr
- from System.Collections.Generic import Dictionary
- import System.Int32
- import System.String
- d1 = Dictionary[System.Int32, System.String]()
- d1[42]="test"
- assert d1[42] == "test"
- raises(TypeError, d1.__setitem__, 42, 42)
-
- d1 = Dictionary[int, str]()
- d1[42]="test"
- assert d1[42] == "test"
- raises(TypeError, d1.__setitem__, 42, 42)
-
- def test_generic_metaclass_object(self):
- import clr
- from System.Collections.Generic import List
- class Foo(object):
- pass
- lst = List[Foo]()
- f = Foo()
- lst.Add(f)
- assert lst[0] is f
-
- def test_generic_metaclass_typeerror(self):
- import clr
- from System.Collections.Generic import List
- raises(TypeError, "List[int, int]")
-
- def test_py2cli_cliobjects(self):
- from System.IO import StreamReader, MemoryStream
- mem = MemoryStream(100)
- sr = StreamReader(mem) # does not raise
-
- def test_external_assemblies(self):
- import clr
- clr.AddReferenceByPartialName('System.Xml')
- from System.IO import StringReader
- from System.Xml import XmlReader
- buffer = StringReader("<foo>test</foo>")
- xml = XmlReader.Create(buffer)
- xml.ReadStartElement("foo")
- assert xml.ReadString() == 'test'
- xml.ReadEndElement()
diff --git a/pypy/module/clr/test/test_importer.py
b/pypy/module/clr/test/test_importer.py
deleted file mode 100644
--- a/pypy/module/clr/test/test_importer.py
+++ /dev/null
@@ -1,76 +0,0 @@
-from pypy.module.clr.test.test_clr import skip_if_not_pythonnet
-
-skip_if_not_pythonnet()
-
-class AppTestDotnet:
- spaceconfig = dict(usemodules=('clr',))
-
- def test_list_of_namespaces_and_classes(self):
- import clr
- ns, classes, generics = clr.get_assemblies_info()
-
- assert 'System' in ns
- assert 'System.Collections' in ns
- assert 'System.Runtime' in ns
- assert 'System.Runtime.InteropServices' in ns
-
- assert 'System' not in classes
- assert 'System.Math' in classes
- assert 'System.Collections.ArrayList' in classes
-
- assert 'System.Collections.Generic.List' in classes
- assert generics['System.Collections.Generic.List'] ==
'System.Collections.Generic.List`1'
-
- def test_import_hook_simple(self):
- mscorlib = 'mscorlib, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'
- import clr
- import System.Math
-
- assert System.Math.Abs(-5) == 5
- assert System.Math.Pow(2, 5) == 2**5
-
- Math = clr.load_cli_class(mscorlib, 'System', 'Math')
- assert Math is System.Math
-
- import System
- a = System.Collections.Stack()
- a.Push(3)
- a.Push(44)
- sum = 0
- for i in a:
- sum += i
- assert sum == 3+44
-
- import System.Collections.ArrayList
- ArrayList = clr.load_cli_class(mscorlib, 'System.Collections',
'ArrayList')
- assert ArrayList is System.Collections.ArrayList
-
- def test_ImportError(self):
- def fn():
- import non_existent_module
- raises(ImportError, fn)
-
- def test_import_twice(self):
- import System
- s1 = System
- import System
- assert s1 is System
-
- def test_lazy_import(self):
- import System
- System.Runtime.InteropServices # does not raise attribute error
-
- def test_generic_class_import(self):
- import System.Collections.Generic.List
-
- def test_import_from(self):
- from System.Collections import ArrayList
-
- def test_AddReferenceByPartialName(self):
- import clr
- clr.AddReferenceByPartialName('System.Xml')
- import System.Xml.XmlReader # does not raise
-
- def test_AddReference_early(self):
- import clr
- clr.AddReferenceByPartialName('System.Xml')
diff --git a/pypy/module/clr/test/test_interp_clr.py
b/pypy/module/clr/test/test_interp_clr.py
deleted file mode 100644
--- a/pypy/module/clr/test/test_interp_clr.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from pypy.module.clr.interp_clr import split_fullname
-
-def test_split_fullname():
- split = split_fullname
- assert split('Foo') == ('', 'Foo')
- assert split('System.Foo') == ('System', 'Foo')
- assert split('System.Foo.Bar') == ('System.Foo', 'Bar')
- assert split('System.Foo.A+B') == ('System.Foo', 'A+B')
- assert split('System.') == ('System', '')
-
_______________________________________________
pypy-commit mailing list
[email protected]
http://mail.python.org/mailman/listinfo/pypy-commit