Ejemplo n.º 1
0
def type_to_typelist(type_obj):
    if type_obj.IsArray:
        return PythonScraper.type_to_typelist(tuple)
    elif type_obj == Void:
        return PythonScraper.type_to_typelist(type(None))
    elif not PythonOps.IsPythonType(clr.GetPythonType(type_obj)):
        raise NonPythonTypeException

    return PythonScraper.type_to_typelist(clr.GetPythonType(type_obj))
Ejemplo n.º 2
0
def validate_clr_types(signature_types, var_signature=False):
    if not isinstance(signature_types, tuple):
        signature_types = (signature_types, )
    for t in signature_types:
        if type(t) is type(
                System.IComparable
        ):  # type overloaded on generic arity, eg IComparable and IComparable[T]
            t = t[()]  # select non-generic version
        clr_type = clr.GetClrType(t)
        if t == Void:
            raise TypeError("Void cannot be used in signature")
        is_typed = clr.GetPythonType(clr_type) == t
        # is_typed needs to be weakened until the generated type
        # gets explicitly published as the underlying CLR type
        is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__
                                in [ClrInterface, ClrClass])
        if not is_typed:
            raise Exception, "Invalid CLR type %s" % str(t)
        if not var_signature:
            if clr_type.IsByRef:
                raise TypeError(
                    "Byref can only be used as arguments and locals")
            # ArgIterator is not present in Silverlight
            if hasattr(System, "ArgIterator") and t == System.ArgIterator:
                raise TypeError(
                    "Stack-referencing types can only be used as arguments and locals"
                )
Ejemplo n.º 3
0
 def map_pinvoke_methods(self, new_type):
     pythonType = clr.GetPythonType(new_type)
     for function_info in self.get_typed_methods():
         function = function_info.function
         if hasattr(function, "DllImportAttributeDecorator"):
             # Overwrite the Python function with the pinvoke_method
             pinvoke_method = getattr(pythonType, function.func_name)
             setattr(self, function.func_name, pinvoke_method)
Ejemplo n.º 4
0
 def init_2D_var_arr_from_data(cls, init_var, dist_array):
    
    distType = dist_array.GetType().GetElementType()
    baseType = clr.GetPythonType(Distribution.GetDomainType(dist_array[0,0].GetType()))
    bt = InitArray._upcast_type(baseType)
    da = Distribution[bt].Array[distType](dist_array)
    datype = type(da)
    init_var.InitialiseTo[datype](da)
Ejemplo n.º 5
0
 def _get_target_info(f):
     if type(f) == clr.GetPythonType(
             IronPython.Runtime.Types.BuiltinMethodDescriptor):
         f = f._BuiltinMethodDescriptor___template
     if type(f) == clr.GetPythonType(
             IronPython.Runtime.Types.BuiltinFunction):
         if len(f.Targets) != 1:
             raise ValueError("Ambiguous function specification. You may " + \
                              "be missing type parameters for a generic " + \
                              "or overloaded function.")
         r = {
             'target': f.Targets[0],
             'name': f._BuiltinFunction__Name,
             'declaring_type': f.DeclaringType,
         }
         return r
     raise TypeError("Incompatible type " + repr(type(f)) +
                     ". Please see the documentation for allowable types")
Ejemplo n.º 6
0
def TestCalls(t):
    t = clr.GetPythonType(t)
    for i in range(1, counter):
        n = "Test_%d" % i
        r = getattr(t, n)()
        if trace: print r

        n = "TestRef_%d" % i
        r = getattr(t, n)()
        if trace: print r
Ejemplo n.º 7
0
 def _create_jagged_2D_arr_of_dist(cls, jagged_lengths, init_func):
     
     distType = type(init_func())
     length = len(jagged_lengths)
     t = clr.GetPythonType(System.Type.MakeArrayType(distType, 2))
     result = System.Array.CreateInstance(t, length)
     for i in range(0, length):
           l1 =  jagged_lengths[i][0]
           l2 =  jagged_lengths[i][1]
           result[i] =  System.Array.CreateInstance(distType, l1, l2)         
           for j in range(0, l1):
                for k in range(0, l2):
                   result[i][j,k] = init_func()                                            
     return result
Ejemplo n.º 8
0
def validate_clr_types(signature_types, var_signature = False):
	if not hasattr(signature_types, "__iter__"):
		signature_types = (signature_types,)
	for t in signature_types:
		clr_type = clr.GetClrType(t)
		if t == Void: 
			raise TypeError("Void cannot be used in signature")
		if clr.GetPythonType(clr_type) != t:
			raise Exception, "Invalid CLR type %s" % str(t)
		if not var_signature:
			if clr_type.IsByRef:
				raise TypeError("Byref can only be used as arguments and locals")
			# ArgIterator is not present in Silverlight
			if hasattr(System, "ArgIterator") and t == System.ArgIterator:
				raise TypeError("Stack-referencing types can only be used as arguments and locals")
Ejemplo n.º 9
0
 def init_jagged_var_arr_from_data(cls, init_var, dist_array):
     
     length1 = dist_array.Length
     #look for 1st non empty value and get distribution type etc
     isFound = False
     for i in range(0,length1):
       if isFound:break
       length2 = dist_array[i].Length
       for j in range(0,length2):
           if (dist_array[i][j] != None):
               d = dist_array[i][j]
               distType = type(d)
               isFound = True
               break
     baseType = clr.GetPythonType(Distribution.GetDomainType(d.GetType()))
     bt = InitArray._upcast_type(baseType)
     da = Distribution[bt].Array[distType](dist_array)
     datype = type(da)
     init_var.InitialiseTo[datype](da)
Ejemplo n.º 10
0
 def init_2D_jagged_var_arr_from_data(cls, init_var, dist_array):
     
     length1 = dist_array.GetLength(0)
     length2 = dist_array.GetLength(1)
     isFound = False
     for i in range(0,length1):
       if isFound:break
       for j in range(0,length2):
          if isFound:break
          length3 = dist_array[i,j].Length
          for k in range(0,length3):
             if (dist_array[i,j][k] != None):
                d = dist_array[i,j][k]
                distType = type(d)
                isFound = True
                break
     baseType = clr.GetPythonType(Distribution.GetDomainType(d.GetType()))
     bt = InitArray._upcast_type(baseType)
     da = Distribution[bt].Array[distType](dist_array)
     datype = type(da)
     init_var.InitialiseTo[datype](da)
Ejemplo n.º 11
0
    def test_mutable_Valuetypes(self):
        self.load_iron_python_test()
        from IronPythonTest import MySize, BaseClass

        direct_vt = MySize(1, 2)
        embedded_vt = BaseClass()
        embedded_vt.Width = 3
        embedded_vt.Height = 4

        # Read access should still succeed.
        self.assertEqual(direct_vt.width, 1)
        self.assertEqual(embedded_vt.size.width, 3)
        self.assertEqual(embedded_vt.Size.width, 3)

        # But writes to value type fields should fail with ValueError.
        success = 0
        try:
            direct_vt.width = 5
        except ValueError:
            success = 1
        self.assertTrue(success == 0 and direct_vt.width == 1)

        success = 0
        try:
            embedded_vt.size.width = 5
        except ValueError:
            success = 1
        self.assertTrue(success == 0 and embedded_vt.size.width == 3)

        success = 0
        try:
            embedded_vt.Size.width = 5
        except ValueError:
            success = 1
        self.assertTrue(success == 0 and embedded_vt.Size.width == 3)

        import clr
        # ensure .GetType() and calling the helper w/ the type work
        self.assertEqual(clr.GetClrType(str), ''.GetType())
        # and ensure we're not just auto-converting back on both of them
        self.assertEqual(clr.GetClrType(str), str)
        self.assertEqual(clr.GetClrType(str) != str, False)

        # as well as GetPythonType
        import System
        self.assertEqual(clr.GetPythonType(System.Int32), int)
        self.assertEqual(clr.GetPythonType(clr.GetClrType(int)), int)

        # verify we can't create *Ops classes
        from IronPython.Runtime.Operations import DoubleOps
        self.assertRaises(TypeError, DoubleOps)

        # setting mro to an invalid value should result in
        # bases still being correct
        class foo(object):
            pass

        class bar(foo):
            pass

        class baz(foo):
            pass

        def changeBazBase():
            baz.__bases__ = (foo, bar)  # illegal MRO

        self.assertRaises(TypeError, changeBazBase)

        self.assertEqual(baz.__bases__, (foo, ))
        self.assertEqual(baz.__mro__, (baz, foo, object))

        d = {}
        d[None, 1] = 2
        self.assertEqual(d, {(None, 1): 2})
Ejemplo n.º 12
0
def get_descriptor_type(descriptor):
    if hasattr(descriptor, 'PropertyType'):
        return clr.GetPythonType(descriptor.PropertyType)
    elif hasattr(descriptor, 'FieldType'):
        return clr.GetPythonType(descriptor.FieldType)
    return object