GetElementType() 공개 메소드

public GetElementType ( ) : Type
리턴 Type
 public static string GetParameterTypeName(Type t)
 {
     if (t.IsArray)
     {
         return(t.GetElementType().Name + "Array");
     }
     if (t.IsByRef)
     {
         return(t.GetElementType().Name + "Ref");
     }
     if (!ObjCTypeToMethodName.TryGetValue(GetTypeName(t), out string name))
     {
         name = t.Name;
     }
     return(name);
 }
예제 #2
0
        public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull)

            : base(tail)

        {
            Helpers.DebugAssert(arrayType != null, "arrayType should be non-null");

            Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName);

            this.itemType = arrayType.GetElementType();

#if NO_GENERICS
            Type underlyingItemType = itemType;
#else
            Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType);
#endif



            Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType, "invalid tail");

            Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer");

            if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0)
            {
                throw new ArgumentOutOfRangeException("fieldNumber");
            }

            if (!ListDecorator.CanPack(packedWireType))

            {
                if (writePacked)
                {
                    throw new InvalidOperationException("Only simple data-types can use packed encoding");
                }

                packedWireType = WireType.None;
            }

            this.fieldNumber = fieldNumber;

            this.packedWireType = packedWireType;

            if (writePacked)
            {
                options |= OPTIONS_WritePacked;
            }

            if (overwriteList)
            {
                options |= OPTIONS_OverwriteList;
            }

            if (supportNull)
            {
                options |= OPTIONS_SupportNull;
            }

            this.arrayType = arrayType;
        }
예제 #3
0
 internal static Type GetMissingType(Type type)
 {
     while (type.HasElementType)
     {
         type = type.GetElementType();
     }
     if (type.__IsMissing)
     {
         return(type);
     }
     else if (type.__ContainsMissingType)
     {
         if (type.IsGenericType)
         {
             foreach (Type arg in type.GetGenericArguments())
             {
                 Type t1 = GetMissingType(arg);
                 if (t1.__IsMissing)
                 {
                     return(t1);
                 }
             }
         }
         throw new NotImplementedException(type.FullName);
     }
     else
     {
         return(type);
     }
 }
예제 #4
0
        public ArrayDecorator(TypeModel model, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, Type arrayType, bool overwriteList, bool supportNull)
            : base(tail)
        {
            Helpers.DebugAssert(arrayType != null, "arrayType should be non-null");
            Helpers.DebugAssert(arrayType.IsArray && arrayType.GetArrayRank() == 1, "should be single-dimension array; " + arrayType.FullName);
            this.itemType = arrayType.GetElementType();
#if NO_GENERICS
            Type underlyingItemType = itemType;
#else
            Type underlyingItemType = supportNull ? itemType : (Helpers.GetUnderlyingType(itemType) ?? itemType);
#endif

            Helpers.DebugAssert(underlyingItemType == Tail.ExpectedType, "invalid tail");
            Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer");
            if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber");
            if (!ListDecorator.CanPack(packedWireType))
            {
                if (writePacked) throw new InvalidOperationException("Only simple data-types can use packed encoding");
                packedWireType = WireType.None;
            }       
            this.fieldNumber = fieldNumber;
            this.packedWireType = packedWireType;
            if (writePacked) options |= OPTIONS_WritePacked;
            if (overwriteList) options |= OPTIONS_OverwriteList;
            if (supportNull) options |= OPTIONS_SupportNull;
            this.arrayType = arrayType;
        }
예제 #5
0
        internal static bool IsReflectionOnly(Type type)
        {
            while (type.HasElementType)
            {
                type = type.GetElementType();
            }
            Assembly asm = type.Assembly;

            if (asm != null && asm.ReflectionOnly)
            {
                return(true);
            }
            if (!type.IsGenericType || type.IsGenericTypeDefinition)
            {
                return(false);
            }
            // we have a generic type instantiation, it might have ReflectionOnly type arguments
            foreach (Type arg in type.GetGenericArguments())
            {
                if (IsReflectionOnly(arg))
                {
                    return(true);
                }
            }
            return(false);
        }
예제 #6
0
		internal static bool IsReflectionOnly(Type type)
		{
			while (type.HasElementType)
			{
				type = type.GetElementType();
			}
			Assembly asm = type.Assembly;
			if (asm != null && asm.ReflectionOnly)
			{
				return true;
			}
			if (!type.IsGenericType || type.IsGenericTypeDefinition)
			{
				return false;
			}
			// we have a generic type instantiation, it might have ReflectionOnly type arguments
			foreach (Type arg in type.GetGenericArguments())
			{
				if (IsReflectionOnly(arg))
				{
					return true;
				}
			}
			return false;
		}
예제 #7
0
        private IEnumerable <Type> ExpandGenericTypes(Type t)
        {
            if (t.IsGenericTypeDefinition)
            {
                yield return(context.SystemTypes.UnboundGenericParameter);
            }

            if (t.IsArray)
            {
                foreach (var g in ExpandGenericTypes(t.GetElementType()))
                {
                    yield return(g);
                }
            }

            if (t.IsGenericType)
            {
                foreach (var genericArgument in t.GetGenericArguments())
                {
                    foreach (var g in ExpandGenericTypes(genericArgument))
                    {
                        yield return(g);
                    }
                }
            }
            yield return(t);
        }
        internal void EmitGetHelper(Operand op, Type desiredType, bool allowExplicitConversion)
        {
            if (desiredType.IsByRef)
            {
                if (op.GetReturnType(TypeMapper) != desiredType.GetElementType())
                {
                    throw new InvalidOperationException(Messages.ErrByRefTypeMismatch);
                }

                op.EmitAddressOf(this);
                return;
            }

            if ((object)op == null)
            {
                if (desiredType.IsValueType)
                {
                    throw new ArgumentNullException(nameof(op));
                }
                IL.Emit(OpCodes.Ldnull);
                return;
            }

            op.EmitGet(this);
            Convert(op, desiredType, allowExplicitConversion);
        }
예제 #9
0
        Type ParameterizeInterface(Type type, Type parameterizable)
        {
            if (parameterizable.IsGenericParameter)
            {
                var def   = type.GetGenericTypeDefinition();
                var pargs = def.GetGenericArguments();
                var rargs = type.GetGenericArguments();

                for (int i = 0; i < pargs.Length; i++)
                {
                    if (pargs[i].Name == parameterizable.Name)
                    {
                        return(rargs[i]);
                    }
                }
            }
            else if (parameterizable.IsGenericType)
            {
                var pargs = parameterizable.GetGenericArguments();
                var rargs = new Type[pargs.Length];

                for (int i = 0; i < rargs.Length; i++)
                {
                    rargs[i] = ParameterizeInterface(type, pargs[i]);
                }

                return(parameterizable.GetGenericTypeDefinition().MakeGenericType(rargs));
            }
            else if (parameterizable.IsArray)
            {
                return(ParameterizeInterface(type, parameterizable.GetElementType()).MakeArrayType());
            }

            return(parameterizable);
        }
예제 #10
0
        private static bool IsTypeBuilder(Type type)
        {
#if !NOEMIT
            return(type is TypeBuilder || (type.HasElementType && IsTypeBuilder(type.GetElementType())));
#else
            return(false);
#endif
        }
	public BindAsAttribute (Type type)
	{
		Type = type;
#if BGENERATOR
		var nullable = type.IsArray ? TypeManager.GetUnderlyingNullableType (type.GetElementType ()) : TypeManager.GetUnderlyingNullableType (type);
		IsNullable = nullable != null;
		IsValueType = IsNullable ? nullable.IsValueType : type.IsValueType;
#endif
	}
 public MultiDimensionalArrayDecorator(TypeModel model, IProtoSerializerWithWireType tail, Type arrayType, bool overwriteList, int readLengthLimit)
     : base(tail)
 {
     Helpers.DebugAssert(arrayType != null, "arrayType should be non-null");
     _rank = arrayType.GetArrayRank();
     if (_rank <= 1)
     {
         throw new ArgumentException("should be multi-dimension array; " + arrayType.FullName, nameof(arrayType));
     }
     _itemType = tail.ExpectedType;
     if (_itemType != arrayType.GetElementType())
     {
         throw new ArgumentException("Expected array type is " + arrayType.GetElementType() + " but tail type is " + _itemType);
     }
     _arrayType       = arrayType;
     _overwriteList   = overwriteList;
     _readLengthLimit = readLengthLimit;
     _listHelpers     = new ListHelpers(false, WireType.None, false, tail, true);
 }
예제 #13
0
 public ArrayDecorator(TypeModel model, IProtoSerializerWithWireType tail, bool writePacked, WireType packedWireTypeForRead, Type arrayType, bool overwriteList, int readLengthLimit, bool protoCompatibility)
     : base(tail)
 {
     Helpers.DebugAssert(arrayType != null, "arrayType should be non-null");
     if (!arrayType.IsArray || arrayType.GetArrayRank() != 1)
     {
         throw new ArgumentException("should be single-dimension array; " + arrayType.FullName, nameof(arrayType));
     }
     _itemType = tail.ExpectedType;
     if (_itemType != arrayType.GetElementType())
     {
         throw new ArgumentException("Expected array type is " + arrayType.GetElementType() + " but tail type is " + _itemType);
     }
     Helpers.DebugAssert(Tail.ExpectedType != model.MapType(typeof(byte)), "Should have used BlobSerializer");
     _writePacked        = writePacked;
     _arrayType          = arrayType;
     _overwriteList      = overwriteList;
     _protoCompatibility = protoCompatibility;
     _readLengthLimit    = readLengthLimit;
     _listHelpers        = new ListHelpers(_writePacked, packedWireTypeForRead, _protoCompatibility, tail, false);
 }
예제 #14
0
 static bool IsArrayOfGenericParameter(Type type)
 {
     if (type != null && type.IsArray)
     {
         while (type.IsArray)
         {
             type = type.GetElementType();
         }
         return(!type.__IsMissing && type.IsGenericParameter);
     }
     return(false);
 }
예제 #15
0
        void EmitGetHelper_Ref(Operand op, Type desiredType)
        {
            if (ReferenceEquals(op, null))
            {
                throw new ArgumentException("Ref argument can't be null, expected " + desiredType.Name);
            }
            if (op.GetReturnType(TypeMapper) != desiredType.GetElementType())
            {
                throw new InvalidOperationException(Properties.Messages.ErrByRefTypeMismatch);
            }

            op.EmitAddressOf(this);
        }
예제 #16
0
        bool IsSupported(Type t)
        {
            if (t.IsByRef)
            {
                return(IsSupported(t.GetElementType()));
            }

            if (unsupported.Contains(t))
            {
                return(false);
            }

            // FIXME protocols
            if (t.IsInterface)
            {
                delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `interfaces` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            if (t.IsGenericParameter || t.IsGenericType)
            {
                delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `generics` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            switch (t.Namespace)
            {
            case "System":
                switch (t.Name)
                {
                case "Object":                 // we cannot accept arbitrary NSObject (which we might not have bound) into mono
                case "Exception":
                case "IFormatProvider":
                case "Type":
                    delayed.Add(ErrorHelper.CreateWarning(1011, $"Type `{t}` is not generated because it lacks a native counterpart."));
                    unsupported.Add(t);
                    return(false);

                case "DateTime":                // FIXME: NSDateTime
                case "Decimal":                 // FIXME: NSDecimal
                case "TimeSpan":
                    delayed.Add(ErrorHelper.CreateWarning(1012, $"Type `{t}` is not generated because it lacks a marshaling code with a native counterpart."));
                    unsupported.Add(t);
                    return(false);
                }
                break;
            }
            return(true);
        }
예제 #17
0
        internal void EmitGetHelper(Operand op, Type desiredType, Conversion conv, Type from = null)
        {
            if (conv == null)
            {
                EmitGetHelper(op, desiredType, false);
                return;
            }

            EmitGetHelper_Conversion(op, desiredType.IsByRef ? desiredType.GetElementType() : desiredType, conv, from);
            if (desiredType.IsByRef)
            {
                EmitGetHelper_Ref(op, desiredType);
            }
        }
예제 #18
0
 internal static bool ContainsTypeBuilder(Type type)
 {
     while (type.HasElementType)
     {
         type = type.GetElementType();
     }
     if (!type.IsGenericType || type.IsGenericTypeDefinition)
     {
         return(type is TypeBuilder);
     }
     foreach (Type arg in type.GetGenericArguments())
     {
         if (ContainsTypeBuilder(arg))
         {
             return(true);
         }
     }
     return(type.GetGenericTypeDefinition() is TypeBuilder);
 }
예제 #19
0
 internal static bool ContainsTypeBuilder(Type type)
 {
     while (type.HasElementType)
     {
         type = type.GetElementType();
     }
     if (!type.IsGenericType || type.IsGenericTypeDefinition)
     {
         return type is TypeBuilder;
     }
     foreach (Type arg in type.GetGenericArguments())
     {
         if (ContainsTypeBuilder(arg))
         {
             return true;
         }
     }
     return type.GetGenericTypeDefinition() is TypeBuilder;
 }
예제 #20
0
        internal void EmitGetHelper(Operand op, Type desiredType, Conversion conv, Type from = null)
        {
            if (desiredType.IsPrimitive && op.ConstantValue != null)
            {
                var opType = op.GetReturnType(TypeMapper);
                if (opType.IsPrimitive && opType != desiredType)
                {
                    // hot swap literals
                    var c = op.ConstantValue;

                    object converted = null;
                    try
                    {
                        converted = Convert.ChangeType(c, System.Type.GetType(desiredType.FullName));
                    }
                    catch
                    {
                    }

                    if (converted != null)
                    {
                        Operand.FromObject(converted).EmitGet(this);
                        return;
                    }
                }
            }


            if (conv == null)
            {
                EmitGetHelper(op, desiredType, false);
                return;
            }

            EmitGetHelper_Conversion(op, desiredType.IsByRef ? desiredType.GetElementType() : desiredType, conv, from);
            if (desiredType.IsByRef)
            {
                EmitGetHelper_Ref(op, desiredType);
            }
        }
예제 #21
0
        internal static bool ContainsTypeBuilder(Type type)
        {
#if !WINRT
            while (type.HasElementType)
            {
                type = type.GetElementType();
            }
            if (!type.IsGenericType || type.IsGenericTypeDefinition)
            {
                return(type is TypeBuilder);
            }
            foreach (Type arg in type.GetGenericArguments())
            {
                if (ContainsTypeBuilder(arg))
                {
                    return(true);
                }
            }
            return(type.GetGenericTypeDefinition() is TypeBuilder);
#else
            throw new NotImplementedException();
#endif
        }
예제 #22
0
        bool IsSupported(Type t)
        {
            if (t.IsByRef)
            {
                return(IsSupported(t.GetElementType()));
            }

            if (unsupported.Contains(t))
            {
                return(false);
            }

            if (t.IsArray)
            {
                delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `arrays` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            if (t.IsPointer)
            {
                delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `unsafe pointers` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            if (t.IsGenericParameter || t.IsGenericType)
            {
                delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `generics` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            switch (t.Namespace)
            {
            case "System":
                switch (t.Name)
                {
                case "Object":                 // we cannot accept arbitrary NSObject (which we might not have bound) into mono
                case "DBNull":
                case "Exception":
                case "IFormatProvider":
                case "Type":
                    delayed.Add(ErrorHelper.CreateWarning(1011, $"Type `{t}` is not generated because it lacks a native counterpart."));
                    unsupported.Add(t);
                    return(false);

                case "DateTime":                // FIXME: NSDateTime
                case "Decimal":                 // FIXME: NSDecimal
                case "TimeSpan":
                    delayed.Add(ErrorHelper.CreateWarning(1012, $"Type `{t}` is not generated because it lacks a marshaling code with a native counterpart."));
                    unsupported.Add(t);
                    return(false);
                }
                break;
            }

            var base_type = t.BaseType;

            return((base_type == null) || base_type.Is("System", "Object") ? true : IsSupported(base_type));
        }
예제 #23
0
        void EmitGetHelper_Ref(Operand op, Type desiredType)
        {
            if (ReferenceEquals(op, null))
                throw new ArgumentException("Ref argument can't be null, expected " + desiredType.Name);
            if (op.GetReturnType(TypeMapper) != desiredType.GetElementType())
                throw new InvalidOperationException(Properties.Messages.ErrByRefTypeMismatch);

            op.EmitAddressOf(this);
        }
		private static bool IsTypeBuilder(Type type)
		{
			return type is TypeBuilder || (type.HasElementType && IsTypeBuilder(type.GetElementType()));
		}
예제 #25
0
			private static bool IsSupportedType(Type type)
			{
				// Java annotations only support one-dimensional arrays
				if (ReflectUtil.IsVector(type))
				{
					type = type.GetElementType();
				}
				return type == Types.String
					|| type == Types.Boolean
					|| type == Types.Byte
					|| type == Types.Char
					|| type == Types.Int16
					|| type == Types.Int32
					|| type == Types.Single
					|| type == Types.Int64
					|| type == Types.Double
					|| type == Types.Type
					|| type.IsEnum;
			}
예제 #26
0
				private static TypeWrapper MapType(Type type, bool isArray)
				{
					if (type == Types.String)
					{
						return CoreClasses.java.lang.String.Wrapper;
					}
					else if (type == Types.Boolean)
					{
						return PrimitiveTypeWrapper.BOOLEAN;
					}
					else if (type == Types.Byte)
					{
						return PrimitiveTypeWrapper.BYTE;
					}
					else if (type == Types.Char)
					{
						return PrimitiveTypeWrapper.CHAR;
					}
					else if (type == Types.Int16)
					{
						return PrimitiveTypeWrapper.SHORT;
					}
					else if (type == Types.Int32)
					{
						return PrimitiveTypeWrapper.INT;
					}
					else if (type == Types.Single)
					{
						return PrimitiveTypeWrapper.FLOAT;
					}
					else if (type == Types.Int64)
					{
						return PrimitiveTypeWrapper.LONG;
					}
					else if (type == Types.Double)
					{
						return PrimitiveTypeWrapper.DOUBLE;
					}
					else if (type == Types.Type)
					{
						return CoreClasses.java.lang.Class.Wrapper;
					}
					else if (type.IsEnum)
					{
						foreach (TypeWrapper tw in ClassLoaderWrapper.GetWrapperFromType(type).InnerClasses)
						{
							if (tw is EnumEnumTypeWrapper)
							{
								if (!isArray && type.IsDefined(JVM.Import(typeof(FlagsAttribute)), false))
								{
									return tw.MakeArrayType(1);
								}
								return tw;
							}
						}
						throw new InvalidOperationException();
					}
					else if (!isArray && ReflectUtil.IsVector(type))
					{
						return MapType(type.GetElementType(), true).MakeArrayType(1);
					}
					else
					{
						throw new NotImplementedException();
					}
				}
예제 #27
0
파일: ReflectUtil.cs 프로젝트: xamidi/ikvm
 internal static Type GetMissingType(Type type)
 {
     while (type.HasElementType)
     {
         type = type.GetElementType();
     }
     if (type.__IsMissing)
     {
         return type;
     }
     else if (type.__ContainsMissingType)
     {
         if (type.IsGenericType)
         {
             foreach (Type arg in type.GetGenericArguments())
             {
                 Type t1 = GetMissingType(arg);
                 if (t1.__IsMissing)
                 {
                     return t1;
                 }
             }
         }
         throw new NotImplementedException(type.FullName);
     }
     else
     {
         return type;
     }
 }
예제 #28
0
		private static bool IsPointerType(Type type)
		{
			while (type.HasElementType)
			{
				if (type.IsPointer)
				{
					return true;
				}
				type = type.GetElementType();
			}
#if STATIC_COMPILER || STUB_GENERATOR
			return type.__IsFunctionPointer;
#else
			return false;
#endif
		}
 private static bool IsTypeBuilder(Type type)
 {
     return(type is TypeBuilder || (type.HasElementType && IsTypeBuilder(type.GetElementType())));
 }
예제 #30
0
        internal void EmitGetHelper(Operand op, Type desiredType, Conversion conv, Type from = null)
        {
            if (conv == null)
            {
                EmitGetHelper(op, desiredType, false);
                return;
            }

            EmitGetHelper_Conversion(op, desiredType.IsByRef ? desiredType.GetElementType() : desiredType, conv, from);
            if (desiredType.IsByRef)
                EmitGetHelper_Ref(op, desiredType);
        }
예제 #31
0
        // the sections mentioned in comments of this method are from C# specification v1.2
        public static Conversion GetImplicit(Operand op, Type to, bool onlyStandard, ITypeMapper typeMapper)
        {
            Type from = Operand.GetType(op, typeMapper);

            Type toUnderlying = Helpers.GetNullableUnderlyingType(to);

            if (to.Equals(from))
            {
                return(new Direct(typeMapper));
            }

            Type fromUnderlying = Helpers.GetNullableUnderlyingType(@from);

            if (toUnderlying != null)
            {
                if (fromUnderlying != null)
                {
                    Conversion c = GetImplicit(new FakeTypedOperand(fromUnderlying), toUnderlying, onlyStandard, typeMapper);
                    if (c.IsValid)
                    {
                        return(new ConvertNullable(typeMapper, c));
                    }
                }
                else
                {
                    Conversion c = GetImplicit(op, toUnderlying, onlyStandard, typeMapper);
                    if (c.IsValid)
                    {
                        return(new WrapNullable(typeMapper, c));
                    }
                }
            }

            // required for arrays created from TypeBuilder-s
            if (from != null && to.IsArray && from.IsArray)
            {
                if (to.GetArrayRank() == from.GetArrayRank())
                {
                    if (to.GetElementType().Equals(from.GetElementType()))
                    {
                        return(new Direct(typeMapper));
                    }
                }
            }

            TypeCode tcFrom = Type.GetTypeCode(from);
            TypeCode tcTo   = Type.GetTypeCode(to);
            byte     ct     = _convTable[(int)tcFrom][(int)tcTo];

            // section 6.1.2 - Implicit numeric conversions
            if (from != null && (from.IsPrimitive || Helpers.AreTypesEqual(from, typeof(decimal), typeMapper)) && (to.IsPrimitive || Helpers.AreTypesEqual(to, typeof(decimal), typeMapper)))
            {
                if (ct <= I)
                {
                    if (Helpers.AreTypesEqual(from, typeof(decimal), typeMapper) || Helpers.AreTypesEqual(to, typeof(decimal), typeMapper))
                    {
                        // decimal is handled as user-defined conversion, but as it is a standard one, always enable UDC processing
                        onlyStandard = false;
                    }
                    else
                    {
                        return(new Primitive(typeMapper));
                    }
                }
            }

            IntLiteral intLit = op as IntLiteral;

            // section 6.1.3 - Implicit enumeration conversions
            if (!onlyStandard && to.IsEnum && (object)intLit != null && intLit.Value == 0)
            {
                return(new Primitive(typeMapper));
            }

            // section 6.1.4 - Implicit reference conversions
            if ((from == null || !from.IsValueType) && !to.IsValueType)
            {
                if (from == null)                 // from the null type to any reference type
                {
                    return(new Direct(typeMapper));
                }

                if (to.IsAssignableFrom(from))                  // the rest
                {
                    return(new Direct(typeMapper));
                }
            }

            if (from == null)                   // no other conversion from null type is possible
            {
                return(new Invalid(typeMapper));
            }

            // section 6.1.5 - Boxing conversions
            if (from.IsValueType)
            {
                if (to.IsAssignableFrom(from))
                {
                    return(new Boxing(typeMapper));
                }
            }

            // section 6.1.6 - Implicit constant expression conversions
            if ((object)intLit != null && Helpers.AreTypesEqual(from, typeof(int), typeMapper) && to.IsPrimitive)
            {
                int val = intLit.Value;

                switch (tcTo)
                {
                case TypeCode.SByte:
                    if (val >= sbyte.MinValue && val <= sbyte.MaxValue)
                    {
                        return(new Direct(typeMapper));
                    }
                    break;

                case TypeCode.Byte:
                    if (val >= byte.MinValue && val <= byte.MaxValue)
                    {
                        return(new Direct(typeMapper));
                    }
                    break;

                case TypeCode.Int16:
                    if (val >= short.MinValue && val <= short.MaxValue)
                    {
                        return(new Direct(typeMapper));
                    }
                    break;

                case TypeCode.UInt16:
                    if (val >= ushort.MinValue && val <= ushort.MaxValue)
                    {
                        return(new Direct(typeMapper));
                    }
                    break;

                case TypeCode.UInt32:
                    if (val >= 0)
                    {
                        return(new Direct(typeMapper));
                    }
                    break;

                case TypeCode.UInt64:
                    if (val >= 0)
                    {
                        return(new Direct(typeMapper));
                    }
                    break;
                }
            }

            // section 6.1.7 - User-defined implicit conversions (details in section 6.4.3)
            if (onlyStandard || Helpers.AreTypesEqual(from, typeof(object), typeMapper) || Helpers.AreTypesEqual(to, typeof(object), typeMapper) || from.IsInterface || to.IsInterface ||
                to.IsSubclassOf(from) || from.IsSubclassOf(to))
            {
                return(new Invalid(typeMapper));  // skip not-permitted conversion attempts (section 6.4.1)
            }
            List <UserDefined> candidates = null;

            FindCandidates(ref candidates, FindImplicitMethods(from, to, typeMapper), op, to, GetImplicit, typeMapper);

            if (candidates == null)
            {
                return(new Invalid(typeMapper));
            }

            if (candidates.Count == 1)
            {
                return(candidates[0]);
            }

            return(UserDefined.FindImplicit(candidates, @from, to, typeMapper));
        }
예제 #32
0
 void AppendCATypeName(StringBuilder sb, Type type, string typeName, bool securityCompatHack = false)
 {
     if (type.IsArray)
     {
         AppendCATypeName(sb, type.GetElementType(), null);
         sb.Append("[]");
     }
     else if (type == typeofSystemBoolean)
     {
         sb.Append("bool");
     }
     else if (type == typeofSystemSByte)
     {
         sb.Append("int8");
     }
     else if (type == typeofSystemByte)
     {
         sb.Append("uint8");
     }
     else if (type == typeofSystemChar)
     {
         sb.Append("char");
     }
     else if (type == typeofSystemInt16)
     {
         sb.Append("int16");
     }
     else if (type == typeofSystemUInt16)
     {
         sb.Append("uint16");
     }
     else if (type == typeofSystemInt32)
     {
         sb.Append("int32");
     }
     else if (type == typeofSystemUInt32)
     {
         sb.Append("uint32");
     }
     else if (type == typeofSystemInt64)
     {
         sb.Append("int64");
     }
     else if (type == typeofSystemUInt64)
     {
         sb.Append("uint64");
     }
     else if (type == typeofSystemSingle)
     {
         sb.Append("float32");
     }
     else if (type == typeofSystemDouble)
     {
         sb.Append("float64");
     }
     else if (type == typeofSystemString)
     {
         sb.Append("string");
     }
     else if (type == typeofSystemObject)
     {
         sb.Append("object");
     }
     else if (type.FullName == "System.Type" && type.Assembly.GetName().Name == "mscorlib")
     {
         sb.Append("type");
     }
     else
     {
         sb.Append("enum ");
         AppendTypeName(sb, type, typeName, false, securityCompatHack);
     }
 }
예제 #33
0
	// TODO: fine tune this so that our output is less verbose. We need to figure
	// out a way to do this while not making things confusing.
	string FormatType (Type t)
	{
		if (t == null)
			return "";

		string type = GetFullName (t);
		if (type == null)
			return t.ToString ();
		
		if (!type.StartsWith ("System.")) {
			if (type.IndexOf (".") == -1)
				return type;
			if (t.GetNamespace () == this.t.GetNamespace ())
				return t.Name;
			return type;
		}
		
		if (t.HasElementType) {
			Type et = t.GetElementType ();
			if (t.IsArray)
				return FormatType (et) + " []";
			if (t.IsPointer)
				return FormatType (et) + " *";
			if (t.IsByRef)
				return "ref " + FormatType (et);
		}
	
		switch (type) {
		case "System.Byte": return "byte";
		case "System.SByte": return "sbyte";
		case "System.Int16": return "short";
		case "System.Int32": return "int";
		case "System.Int64": return "long";
			
		case "System.UInt16": return "ushort";
		case "System.UInt32": return "uint";
		case "System.UInt64": return "ulong";
			
		case "System.Single":  return "float";
		case "System.Double":  return "double";
		case "System.Decimal": return "decimal";
		case "System.Boolean": return "bool";
		case "System.Char":    return "char";
		case "System.String":  return "string";
			
		case "System.Object":  return "object";
		case "System.Void":  return "void";
		}
	
		if (type.LastIndexOf(".") == 6)
			return type.Substring(7);

		//
		// If the namespace of the type is the namespace of what
		// we are printing (or is a member of one if its children
		// don't print it. This basically means that in C# we would
		// automatically get the namespace imported by virtue of the
		// namespace {} block.
		//	
		if (this.t.Namespace.StartsWith (t.Namespace + ".") || t.Namespace == this.t.Namespace)
			return type.Substring (t.Namespace.Length + 1);
	
		return type;
	}
예제 #34
0
        // TODO: fine tune this so that our output is less verbose. We need to figure
        // out a way to do this while not making things confusing.
        string FormatType(Type t)
        {
            if (t == null)
            {
                return("");
            }

            string type = GetFullName(t);

            if (type == null)
            {
                return(t.ToString());
            }

            if (!type.StartsWith("System."))
            {
                if (type.IndexOf(".") == -1)
                {
                    return(type);
                }
                if (t.GetNamespace() == this.t.GetNamespace())
                {
                    return(t.Name);
                }
                return(type);
            }

            if (t.HasElementType)
            {
                Type et = t.GetElementType();
                if (t.IsArray)
                {
                    return(FormatType(et) + " []");
                }
                if (t.IsPointer)
                {
                    return(FormatType(et) + " *");
                }
                if (t.IsByRef)
                {
                    return("ref " + FormatType(et));
                }
            }

            switch (type)
            {
            case "System.Byte": return("byte");

            case "System.SByte": return("sbyte");

            case "System.Int16": return("short");

            case "System.Int32": return("int");

            case "System.Int64": return("long");

            case "System.UInt16": return("ushort");

            case "System.UInt32": return("uint");

            case "System.UInt64": return("ulong");

            case "System.Single":  return("float");

            case "System.Double":  return("double");

            case "System.Decimal": return("decimal");

            case "System.Boolean": return("bool");

            case "System.Char":    return("char");

            case "System.String":  return("string");

            case "System.Object":  return("object");

            case "System.Void":  return("void");
            }

            if (type.LastIndexOf(".") == 6)
            {
                return(type.Substring(7));
            }

            //
            // If the namespace of the type is the namespace of what
            // we are printing (or is a member of one if its children
            // don't print it. This basically means that in C# we would
            // automatically get the namespace imported by virtue of the
            // namespace {} block.
            //
            if (this.t.Namespace != null && (this.t.Namespace.StartsWith(t.Namespace + ".") || t.Namespace == this.t.Namespace))
            {
                return(type.Substring(t.Namespace.Length + 1));
            }

            return(type);
        }
예제 #35
0
        string GetInternalTypeName(IKVM.Reflection.Type type)
        {
            // If true type is an array, a pointer, or is passed by reference.
            if (type.HasElementType)
            {
                var elementType = type.GetElementType();

                if (type.IsArray)
                {
                    return(GetInternalTypeName(elementType) + "[]");
                }

                return(GetInternalTypeName(elementType));
            }

            if (type.IsEnum)
            {
                return(type.FullName);
            }

            switch (IKVM.Reflection.Type.GetTypeCode(type))
            {
            case TypeCode.Object:
                if (type.FullName == "System.IntPtr")
                {
                    return("intptr");
                }
                if (type.FullName == "System.UIntPtr")
                {
                    return("uintptr");
                }
                if (type.FullName == "System.Object")
                {
                    return("object");
                }
                return(type.FullName);

            case TypeCode.Boolean:
                return("bool");

            case TypeCode.Char:
                return("char");

            case TypeCode.SByte:
                return("sbyte");

            case TypeCode.Byte:
                return("byte");

            case TypeCode.Int16:
                return("int16");

            case TypeCode.UInt16:
                return("uint16");

            case TypeCode.Int32:
                return("int");

            case TypeCode.UInt32:
                return("uint");

            case TypeCode.Int64:
                return("long");

            case TypeCode.UInt64:
                return("ulong");

            case TypeCode.Single:
                return("single");

            case TypeCode.Double:
                return("double");

            case TypeCode.String:
                return("string");

            case TypeCode.Empty:
                return("null");

            case TypeCode.DBNull:
            case TypeCode.Decimal:
            case TypeCode.DateTime:
                return(type.FullName);
            }

            throw new NotImplementedException("No implementation for " + type);
        }
예제 #36
0
 public override Type GetReturnType(ITypeMapper typeMapper) => IsReference?_type.GetElementType() : _type;
예제 #37
0
 Type GetNullable(Generator generator)
 {
     if (nullable == null)
     {
         nullable = Type.IsArray ? generator.TypeManager.GetUnderlyingNullableType(Type.GetElementType()) : generator.TypeManager.GetUnderlyingNullableType(Type);
     }
     return(nullable);
 }
예제 #38
0
 void ReadFixedArg(StringBuilder sb, ByteReader br, Type type, bool arrayElement = false)
 {
     if (type.IsArray)
     {
         int length = br.ReadInt32();
         if (length == -1 && compat == CompatLevel.None)
         {
             sb.Append("nullref");
         }
         else if (length == 0 && compat != CompatLevel.None)
         {
             throw new IKVM.Reflection.BadImageFormatException();
         }
         else
         {
             Type elementType = type.GetElementType();
             AppendCATypeName(sb, elementType, null);
             sb.AppendFormat("[{0}](", length);
             for (int i = 0; i < length; i++)
             {
                 if (i != 0)
                 {
                     sb.Append(' ');
                 }
                 if (elementType == typeofSystemObject)
                 {
                     string typeName;
                     ReadFixedArg(sb, br, ReadFieldOrPropType(sb, br, out typeName), false);
                 }
                 else
                 {
                     ReadFixedArg(sb, br, elementType, true);
                 }
             }
             sb.Append(')');
         }
     }
     else if (type.FullName == "System.Type" && type.Assembly.GetName().Name == "mscorlib")
     {
         if (!arrayElement)
         {
             AppendCATypeName(sb, type, null);
             sb.Append('(');
         }
         string typeName;
         var type1 = ReadType(br, out typeName);
         if (type1 == null)
         {
             if (typeName == null)
             {
                 sb.Append("nullref");
             }
             else
             {
                 sb.Append("class ").Append(QuoteIdentifier(typeName, true));
             }
         }
         else
         {
             AppendTypeName(sb, type1, typeName, compat != CompatLevel.None && IsNestedTypeWithNamespace(type1));
         }
         if (!arrayElement)
         {
             sb.Append(')');
         }
     }
     else if (type.Assembly == mscorlib)
     {
         if (!arrayElement)
         {
             AppendCATypeName(sb, type, null);
             sb.Append('(');
         }
         if (type == typeofSystemBoolean)
         {
             sb.Append(br.ReadByte() == 0 ? "false" : "true");
         }
         else if (type == typeofSystemByte)
         {
             sb.Append(br.ReadByte());
         }
         else if (type == typeofSystemSByte)
         {
             sb.Append(br.ReadSByte());
         }
         else if (type == typeofSystemChar)
         {
             sb.AppendFormat("0x{0:X4}", (int)br.ReadChar());
         }
         else if (type == typeofSystemInt16)
         {
             sb.Append(br.ReadInt16());
         }
         else if (type == typeofSystemUInt16)
         {
             sb.Append(br.ReadUInt16());
         }
         else if (type == typeofSystemInt32)
         {
             sb.Append(br.ReadInt32());
         }
         else if (type == typeofSystemUInt32)
         {
             sb.Append(br.ReadInt32());
         }
         else if (type == typeofSystemInt64)
         {
             sb.Append(br.ReadInt64());
         }
         else if (type == typeofSystemUInt64)
         {
             sb.Append(br.ReadInt64());
         }
         else if (type == typeofSystemSingle)
         {
             sb.Append(ToString(br.ReadSingle(), true));
         }
         else if (type == typeofSystemDouble)
         {
             sb.Append(ToString(br.ReadDouble(), true));
         }
         else if (type == typeofSystemString)
         {
             var str = br.ReadString();
             if (str == null)
             {
                 sb.Append("nullref");
             }
             else
             {
                 if (compat != CompatLevel.None)
                 {
                     int pos = str.IndexOf((char)0);
                     if (pos != -1)
                     {
                         str = str.Substring(0, pos);
                     }
                 }
                 sb.Append(QuoteIdentifier(str, true));
             }
         }
         else if (type == typeofSystemObject)
         {
             string typeName;
             ReadFixedArg(sb, br, ReadFieldOrPropType(sb, br, out typeName));
         }
         else
         {
             throw new NotImplementedException(type.FullName);
         }
         if (!arrayElement)
         {
             sb.Append(')');
         }
     }
     else if (type.__IsMissing || (compat != CompatLevel.None && typerefs.Contains(type)))
     {
         // ildasm actually tries to load the assembly, but we can't do that, so we cheat by having
         // a list of 'known' enum types
         if (type.Assembly.GetName().Name == "mscorlib")
         {
             switch (type.FullName)
             {
                 case "System.AttributeTargets":
                 case "System.Runtime.ConstrainedExecution.Consistency":
                 case "System.Runtime.ConstrainedExecution.Cer":
                 case "System.Security.Permissions.SecurityAction":
                 case "System.Security.Permissions.SecurityPermissionFlag":
                 case "System.Runtime.Versioning.ResourceScope":
                 case "System.Runtime.InteropServices.CallingConvention":
                 case "System.Runtime.InteropServices.CharSet":
                     ReadFixedArg(sb, br, typeofSystemInt32);
                     return;
                 case "System.Security.SecurityRuleSet":
                     if (compat != CompatLevel.V20)
                     {
                         ReadFixedArg(sb, br, typeofSystemByte);
                         return;
                     }
                     break;
                 case "System.Diagnostics.Tracing.EventLevel":
                 case "System.Diagnostics.Tracing.EventTask":
                 case "System.Diagnostics.Tracing.EventOpcode":
                     if (compat != CompatLevel.V20 && compat != CompatLevel.V40)
                     {
                         ReadFixedArg(sb, br, typeofSystemInt32);
                         return;
                     }
                     break;
                 case "System.Type":
                     sb.Append("type(");
                     string typeName;
                     AppendTypeName(sb, ReadType(br, out typeName), typeName);
                     sb.Append(")");
                     return;
             }
         }
         switch (br.Length)
         {
             case 1:
                 if (compat != CompatLevel.None)
                 {
                     // ildasm uses bool (???) as the underlying type in this case
                     sb.AppendFormat("bool({0})", br.ReadByte() == 0 ? "false" : "true");
                 }
                 else
                 {
                     // just guess that the enum has int8 as the underlying type
                     sb.AppendFormat("int8({0})", br.ReadSByte());
                 }
                 break;
             case 2:
                 // just guess that the enum has int16 as the underlying type
                 sb.AppendFormat("int16({0})", br.ReadInt16());
                 break;
             case 4:
                 // just guess that the enum has int32 as the underlying type
                 sb.AppendFormat("int32({0})", br.ReadInt32());
                 break;
             case 8:
                 // just guess that the enum has int64 as the underlying type
                 sb.AppendFormat("int64({0})", br.ReadInt64());
                 break;
             default:
                 throw new IKVM.Reflection.BadImageFormatException();
         }
     }
     else if (type.IsEnum)
     {
         ReadFixedArg(sb, br, type.GetEnumUnderlyingType(), arrayElement);
     }
     else
     {
         throw new NotImplementedException(type.FullName);
     }
 }
예제 #39
0
        // TODO complete mapping (only with corresponding tests)
        // TODO override with attribute ? e.g. [Obj.Name ("XAMType")]
        public static string GetTypeName(Type t)
        {
            if (t.IsByRef)
            {
                return(GetTypeName(t.GetElementType()) + "*");
            }

            if (t.IsEnum)
            {
                return(GetObjCName(t));
            }

            switch (Type.GetTypeCode(t))
            {
            case TypeCode.Object:
                switch (t.Namespace)
                {
                case "System":
                    switch (t.Name)
                    {
                    case "Object":
                    case "ValueType":
                        return("NSObject");

                    case "Void":
                        return("void");

                    default:
                        return(GetObjCName(t));
                    }

                default:
                    return(GetObjCName(t));
                }

            case TypeCode.Boolean:
                return("bool");

            case TypeCode.Char:
                return("unsigned short");

            case TypeCode.Double:
                return("double");

            case TypeCode.Single:
                return("float");

            case TypeCode.Byte:
                return("unsigned char");

            case TypeCode.SByte:
                return("signed char");

            case TypeCode.Int16:
                return("short");

            case TypeCode.Int32:
                return("int");

            case TypeCode.Int64:
                return("long long");

            case TypeCode.UInt16:
                return("unsigned short");

            case TypeCode.UInt32:
                return("unsigned int");

            case TypeCode.UInt64:
                return("unsigned long long");

            case TypeCode.String:
                return("NSString *");

            default:
                throw new NotImplementedException($"Converting type {t.Name} to a native type name");
            }
        }
예제 #40
0
        internal void ResolveListTypes(Type type, ref Type itemType, ref Type defaultType)
        {
            if (type == null) return;
            if(Helpers.GetTypeCode(type) != ProtoTypeCode.Unknown) return; // don't try this[type] for inbuilts
            if(this[type].IgnoreListHandling) return;

            // handle arrays
            if (type.IsArray)
            {
                if (type.GetArrayRank() != 1)
                {
                    throw new NotSupportedException("Multi-dimension arrays are supported");
                }
                itemType = type.GetElementType();
                if (itemType == MapType(typeof(byte)))
                {
                    defaultType = itemType = null;
                }
                else
                {
                    defaultType = type;
                }
            }
            // handle lists
            if (itemType == null) { itemType = TypeModel.GetListItemType(this, type); }

            // check for nested data (not allowed)
            if (itemType != null)
            {
                Type nestedItemType = null, nestedDefaultType = null;
                ResolveListTypes(itemType, ref nestedItemType, ref nestedDefaultType);
                if (nestedItemType != null)
                {
                    throw TypeModel.CreateNestedListsNotSupported();
                }
            }

            if (itemType != null && defaultType == null)
            {
#if WINRT
                System.Reflection.TypeInfo typeInfo = System.Reflection.IntrospectionExtensions.GetTypeInfo(type);
                if (typeInfo.IsClass && !typeInfo.IsAbstract && Helpers.GetConstructor(typeInfo, Helpers.EmptyTypes, true) != null)
#else
                if (type.IsClass && !type.IsAbstract && Helpers.GetConstructor(type, Helpers.EmptyTypes, true) != null)
#endif
                {
                    defaultType = type;
                }
                if (defaultType == null)
                {
#if WINRT
                    if (typeInfo.IsInterface)
#else
                    if (type.IsInterface)
#endif
                    {
#if NO_GENERICS
                        defaultType = typeof(ArrayList);
#else
                        Type[] genArgs;
#if WINRT
                        if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)
                            && itemType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments))
#else
                        if (type.IsGenericType && type.GetGenericTypeDefinition() == MapType(typeof(System.Collections.Generic.IDictionary<,>))
                            && itemType == MapType(typeof(System.Collections.Generic.KeyValuePair<,>)).MakeGenericType(genArgs = type.GetGenericArguments()))
#endif
                        {
                            defaultType = MapType(typeof(System.Collections.Generic.Dictionary<,>)).MakeGenericType(genArgs);
                        }
                        else
                        {
                            defaultType = MapType(typeof(System.Collections.Generic.List<>)).MakeGenericType(itemType);
                        }
#endif
                    }
                }
                // verify that the default type is appropriate
                if (defaultType != null && !Helpers.IsAssignableFrom(type, defaultType)) { defaultType = null; }
            }
        }
예제 #41
0
        public static string GetMonoName(Type t)
        {
            if (t.IsByRef)
            {
                return(GetMonoName(t.GetElementType()) + "&");
            }

            if (t.IsEnum)
            {
                return(t.FullName);
            }

            switch (Type.GetTypeCode(t))
            {
            case TypeCode.Object:
                switch (t.Namespace)
                {
                case "System":
                    switch (t.Name)
                    {
                    case "Void":
                        return("void");

                    default:
                        return("object");
                    }

                default:
                    return(t.FullName);
                }

            case TypeCode.Boolean:
                return("bool");

            case TypeCode.Char:
                return("char");

            case TypeCode.Double:
                return("double");

            case TypeCode.Single:
                return("single");

            case TypeCode.Byte:
                return("byte");

            case TypeCode.SByte:
                return("sbyte");

            case TypeCode.Int16:
                return("int16");

            case TypeCode.Int32:
                return("int");

            case TypeCode.Int64:
                return("long");

            case TypeCode.UInt16:
                return("uint16");

            case TypeCode.UInt32:
                return("uint");

            case TypeCode.UInt64:
                return("ulong");

            case TypeCode.String:
                return("string");

            default:
                throw new NotImplementedException($"Converting type {t.Name} to a mono type name");
            }
        }
예제 #42
0
파일: import.cs 프로젝트: frje/SharpLang
		TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
		{
			if (type.HasElementType) {
				var element = type.GetElementType ();
				++dtype.Position;
				var spec = ImportType (element, dtype);

				if (type.IsArray)
					return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
				if (type.IsByRef)
					return ReferenceContainer.MakeType (module, spec);
				if (type.IsPointer)
					return PointerContainer.MakeType (module, spec);

				throw new NotImplementedException ("Unknown element type " + type.ToString ());
			}

			TypeSpec compiled_type;
			if (compiled_types.TryGetValue (type, out compiled_type)) {
				if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
					return module.Compiler.BuiltinTypes.Dynamic;

				return compiled_type;
			}

			return CreateType (type, dtype, true);
		}
예제 #43
0
        // the sections mentioned in comments of this method are from C# specification v1.2
		public static Conversion GetImplicit(Operand op, Type to, bool onlyStandard, ITypeMapper typeMapper)
		{
			Type from = Operand.GetType(op, typeMapper);

            Type toUnderlying = Helpers.GetNullableUnderlyingType(to);
		    if (to.Equals(from))
		        return new Direct(typeMapper);

            Type fromUnderlying = Helpers.GetNullableUnderlyingType(@from);
		    if (toUnderlying != null)
		    {
		        if (fromUnderlying != null)
		        {
		            Conversion c = GetImplicit(new FakeTypedOperand(fromUnderlying), toUnderlying, onlyStandard, typeMapper);
		            if (c.IsValid) return new ConvertNullable(typeMapper, c);
		        }
		        else
		        {
                    Conversion c = GetImplicit(op, toUnderlying, onlyStandard, typeMapper);
                    if (c.IsValid) return new WrapNullable(typeMapper, c);
                }
		    }
            
		    // required for arrays created from TypeBuilder-s
			if (from != null && to.IsArray && from.IsArray)
			{
				if (to.GetArrayRank() == from.GetArrayRank())
				{
					if (to.GetElementType().Equals(from.GetElementType()))
						return new Direct(typeMapper);
				}
			}

			TypeCode tcFrom = Type.GetTypeCode(from);
			TypeCode tcTo = Type.GetTypeCode(to);
			byte ct = _convTable[(int)tcFrom][(int)tcTo];

			// section 6.1.2 - Implicit numeric conversions
			if (from != null && (from.IsPrimitive || Helpers.AreTypesEqual(from, typeof(decimal), typeMapper)) && (to.IsPrimitive || Helpers.AreTypesEqual(to, typeof(decimal), typeMapper)))
			{
				if (ct <= I)
				{
				    if (Helpers.AreTypesEqual(from, typeof(decimal), typeMapper) || Helpers.AreTypesEqual(to, typeof(decimal), typeMapper))
						// decimal is handled as user-defined conversion, but as it is a standard one, always enable UDC processing
						onlyStandard = false;
					else
						return new Primitive(typeMapper);
				}
			}

			IntLiteral intLit = op as IntLiteral;

			// section 6.1.3 - Implicit enumeration conversions
			if (!onlyStandard && to.IsEnum && (object)intLit != null && intLit.Value == 0)
				return new Primitive(typeMapper);

			// section 6.1.4 - Implicit reference conversions
			if ((from == null || !from.IsValueType) && !to.IsValueType)
			{
				if (from == null) // from the null type to any reference type
					return new Direct(typeMapper);

				if (to.IsAssignableFrom(from))	// the rest
					return new Direct(typeMapper);
			}

			if (from == null)	// no other conversion from null type is possible
				return new Invalid(typeMapper);

			// section 6.1.5 - Boxing conversions
			if (from.IsValueType)
			{
				if (to.IsAssignableFrom(from))
					return new Boxing(typeMapper);
			}

			// section 6.1.6 - Implicit constant expression conversions
			if ((object)intLit != null && Helpers.AreTypesEqual(from, typeof(int), typeMapper) && to.IsPrimitive)
			{
				int val = intLit.Value;

				switch (tcTo)
				{
					case TypeCode.SByte:
						if (val >= sbyte.MinValue && val <= sbyte.MaxValue)
							return new Direct(typeMapper);
						break;
					case TypeCode.Byte:
						if (val >= byte.MinValue && val <= byte.MaxValue)
                            return new Direct(typeMapper);
                        break;
					case TypeCode.Int16:
						if (val >= short.MinValue && val <= short.MaxValue)
                            return new Direct(typeMapper);
                        break;
					case TypeCode.UInt16:
						if (val >= ushort.MinValue && val <= ushort.MaxValue)
                            return new Direct(typeMapper);
                        break;
					case TypeCode.UInt32:
						if (val >= 0)
                            return new Direct(typeMapper);
                        break;
					case TypeCode.UInt64:
						if (val >= 0)
                            return new Direct(typeMapper);
                        break;
				}
			}

			// section 6.1.7 - User-defined implicit conversions (details in section 6.4.3)
			if (onlyStandard || Helpers.AreTypesEqual(from, typeof(object), typeMapper) || Helpers.AreTypesEqual(to, typeof(object), typeMapper) || from.IsInterface || to.IsInterface ||
				to.IsSubclassOf(from) || from.IsSubclassOf(to))
                return new Invalid(typeMapper);  // skip not-permitted conversion attempts (section 6.4.1)

            List<UserDefined> candidates = null;
			FindCandidates(ref candidates, FindImplicitMethods(from, to, typeMapper), op, to, GetImplicit, typeMapper);

			if (candidates == null)
                return new Invalid(typeMapper);

            if (candidates.Count == 1)
				return candidates[0];

			return UserDefined.FindImplicit(candidates, @from, to, typeMapper);
		}
예제 #44
0
파일: import.cs 프로젝트: Gobiner/ILSpy
		TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
		{
			if (type.HasElementType) {
				var element = type.GetElementType ();
				++dtype.Position;
				var spec = ImportType (element, dtype);

				if (type.IsArray)
					return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
				if (type.IsByRef)
					return ReferenceContainer.MakeType (module, spec);
				if (type.IsPointer)
					return PointerContainer.MakeType (module, spec);

				throw new NotImplementedException ("Unknown element type " + type.ToString ());
			}

			return CreateType (type, dtype, true);
		}
예제 #45
0
		private static bool IsPointerType(Type type)
		{
			while (type.HasElementType)
			{
				if (type.IsPointer)
				{
					return true;
				}
				type = type.GetElementType();
			}
			return false;
		}
예제 #46
0
        QualifiedType VisitType(IKVM.Reflection.Type managedType)
        {
            var isString = managedType.HasElementType && IKVM.Reflection.Type.GetTypeCode(
                managedType.GetElementType()) == TypeCode.String;

            if (managedType.IsByRef && isString)
            {
                managedType = managedType.GetElementType();
            }

            // If true type is an array, a pointer, or is passed by reference.
            if (managedType.HasElementType)
            {
                var managedElementType = managedType.GetElementType();
                var elementType        = VisitType(managedElementType);

                if (managedType.IsByRef || managedType.IsPointer)
                {
                    var ptrType = new PointerType(elementType)
                    {
                        Modifier = (Options.GeneratorKind == GeneratorKind.CPlusPlus) ?
                                   PointerType.TypeModifier.LVReference :
                                   PointerType.TypeModifier.Pointer
                    };

                    return(new QualifiedType(ptrType));
                }
                else if (managedType.IsArray)
                {
                    var array = new ArrayType
                    {
                        SizeType      = ArrayType.ArraySize.Variable,
                        QualifiedType = elementType
                    };

                    return(new QualifiedType(array));
                }

                throw new NotImplementedException();
            }

            CppSharp.AST.Type type       = null;
            TypeQualifiers    qualifiers = new TypeQualifiers();

            switch (IKVM.Reflection.Type.GetTypeCode(managedType))
            {
            case TypeCode.Empty:
                type = new BuiltinType(PrimitiveType.Null);
                break;

            case TypeCode.Object:
            case TypeCode.Decimal:
            case TypeCode.DateTime:
                if (managedType.FullName == "System.Void")
                {
                    type = new BuiltinType(PrimitiveType.Void);
                    break;
                }
                var currentUnit = GetTranslationUnit(CurrentAssembly);
                if (managedType.Assembly.GetName().Name != currentUnit.FileNameWithoutExtension ||
                    managedType.IsGenericType)
                {
                    type = new UnsupportedType {
                        Description = managedType.FullName
                    };
                    break;
                }
                var decl = Visit(managedType.GetTypeInfo());
                type = new TagType(decl);
                break;

            case TypeCode.DBNull:
                throw new NotSupportedException();

            case TypeCode.Boolean:
                type = new BuiltinType(PrimitiveType.Bool);
                break;

            case TypeCode.Char:
                type = new BuiltinType(PrimitiveType.WideChar);
                break;

            case TypeCode.SByte:
                type = new BuiltinType(PrimitiveType.Char);
                break;

            case TypeCode.Byte:
                type = new BuiltinType(PrimitiveType.UChar);
                break;

            case TypeCode.Int16:
                type = new BuiltinType(PrimitiveType.Short);
                break;

            case TypeCode.UInt16:
                type = new BuiltinType(PrimitiveType.UShort);
                break;

            case TypeCode.Int32:
                type = new BuiltinType(PrimitiveType.Int);
                break;

            case TypeCode.UInt32:
                type = new BuiltinType(PrimitiveType.UInt);
                break;

            case TypeCode.Int64:
                type = new BuiltinType(PrimitiveType.LongLong);
                break;

            case TypeCode.UInt64:
                type = new BuiltinType(PrimitiveType.ULongLong);
                break;

            case TypeCode.Single:
                type = new BuiltinType(PrimitiveType.Float);
                break;

            case TypeCode.Double:
                type = new BuiltinType(PrimitiveType.Double);
                break;

            case TypeCode.String:
                type = new CILType(typeof(string));
                break;
            }

            return(new QualifiedType(type, qualifiers));
        }
        // TODO complete mapping (only with corresponding tests)
        // TODO override with attribute ? e.g. [Obj.Name ("XAMType")]
        public static string GetTypeName(Type t)
        {
            if (t.IsByRef)
            {
                var et = t.GetElementType();
                if (Type.GetTypeCode(et) == TypeCode.Decimal)                  // This is boxed into NSDecimalNumber
                {
                    return(GetTypeName(et) + "_Nonnull * _Nullable");
                }

                return(GetTypeName(et) + (et.IsValueType ? " " : " _Nonnull ") + "* _Nullable");
            }

            if (t.IsEnum)
            {
                return(GetObjCName(t));
            }

            if (t.IsArray)
            {
                return(GetArrayTypeName(t.GetElementType()));
            }

            switch (Type.GetTypeCode(t))
            {
            case TypeCode.Object:
                switch (t.Namespace)
                {
                case "System":
                    switch (t.Name)
                    {
                    case "Object":
                    case "ValueType":
                        return("NSObject");

                    case "Void":
                        return("void");

                    default:
                        return(GetObjCName(t));
                    }

                default:
                    return(GetObjCName(t));
                }

            case TypeCode.Boolean:
                return("bool");

            case TypeCode.Char:
                return("unsigned short");

            case TypeCode.Double:
                return("double");

            case TypeCode.Single:
                return("float");

            case TypeCode.Byte:
                return("unsigned char");

            case TypeCode.SByte:
                return("signed char");

            case TypeCode.Int16:
                return("short");

            case TypeCode.Int32:
                return("int");

            case TypeCode.Int64:
                return("long long");

            case TypeCode.UInt16:
                return("unsigned short");

            case TypeCode.UInt32:
                return("unsigned int");

            case TypeCode.UInt64:
                return("unsigned long long");

            case TypeCode.String:
                return("NSString *");

            case TypeCode.Decimal:
                return("NSDecimalNumber *");

            default:
                throw new NotImplementedException($"Converting type {t.Name} to a native type name");
            }
        }
예제 #48
0
        bool IsSupported(Type t)
        {
            if (t.IsByRef)
            {
                return(IsSupported(t.GetElementType()));
            }

            if (t.IsArray)
            {
                return(IsSupported(t.GetElementType()));
            }

            if (unsupported.Contains(t))
            {
                return(false);
            }

            if (t.IsPointer)
            {
                Delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `unsafe pointers` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            if (t.IsGenericParameter || t.IsGenericType)
            {
                Delayed.Add(ErrorHelper.CreateWarning(1010, $"Type `{t}` is not generated because `generics` are not supported."));
                unsupported.Add(t);
                return(false);
            }

            switch (t.Namespace)
            {
            case "System":
                switch (t.Name)
                {
                case "Object":                 // we cannot accept arbitrary NSObject (which we might not have bound) into mono
                case "DBNull":
                case "Exception":
                case "Type":
                    Delayed.Add(ErrorHelper.CreateWarning(1011, $"Type `{t}` is not generated because it lacks a native counterpart."));
                    unsupported.Add(t);
                    return(false);

                case "DateTime":                 // FIXME: NSDateTime
                    Delayed.Add(ErrorHelper.CreateWarning(1012, $"Type `{t}` is not generated because it lacks a marshaling code with a native counterpart."));
                    unsupported.Add(t);
                    return(false);

                case "Decimal":
                    return(AddDecimalSupport(t));

                case "TimeSpan":
                    if (system_timespan == null)
                    {
                        system_timespan = new ProcessedType(t)
                        {
                            Assembly = GetMscorlib(t),
                        };
                        AddExtraType(system_timespan);
                    }
                    return(true);

                case "IFormatProvider":
                    if (system_iformatprovider == null)
                    {
                        system_iformatprovider = new ProcessedType(t)
                        {
                            Assembly = GetMscorlib(t),
                        };
                        AddExtraType(system_iformatprovider);
                    }
                    return(true);
                }
                break;

            case "System.Globalization":
                switch (t.Name)
                {
                case "TimeSpanStyles":                 // enum for TimeSpan support
                    if (system_globalization_timespanstyles == null)
                    {
                        system_globalization_timespanstyles = new ProcessedType(t)
                        {
                            Assembly = GetMscorlib(t),
                        };
                        AddExtraType(system_globalization_timespanstyles);
                    }
                    return(true);
                }
                break;
            }

            var base_type = t.BaseType;

            return((base_type == null) || base_type.Is("System", "Object") ? true : IsSupported(base_type));
        }
 private static bool IsTypeBuilder(Type type)
 {
     #if !NOEMIT
     return type is TypeBuilder || (type.HasElementType && IsTypeBuilder(type.GetElementType()));
     #else
     return false;
     #endif
 }