GetGenericTypeDefinition() public method

public GetGenericTypeDefinition ( ) : Type
return Type
Ejemplo n.º 1
0
        public static bool IsDictionaryOrListInterface(RuntimeTypeModel model, Type type, out Type defaultType)
        {
            defaultType = null;
            if (!Helpers.IsInterface(type))
            {
                return(false);
            }
            Type[] genArgs;
            var    itemType = TypeModel.GetListItemType(model, type);

#if WINRT
            TypeInfo typeInfo = type.GetTypeInfo();
            if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary <,>) &&
                itemType == typeof(System.Collections.Generic.KeyValuePair <,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments))
#else
            if (type.IsGenericType && type.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.IDictionary <,>)) &&
                itemType == model.MapType(typeof(System.Collections.Generic.KeyValuePair <,>)).MakeGenericType(genArgs = type.GetGenericArguments()))
#endif
            {
                defaultType = model.MapType(typeof(System.Collections.Generic.Dictionary <,>)).MakeGenericType(genArgs);
                return(true);
            }
#if WINRT
            if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList <>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments))
#else
            if (type.IsGenericType && type.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.IList <>)).MakeGenericType(genArgs = type.GetGenericArguments()))
#endif
            {
                defaultType = model.MapType(typeof(System.Collections.Generic.List <>)).MakeGenericType(genArgs);
                return(true);
            }
            return(false);
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
0
        private static void TestEnumerableListPatterns(TypeModel model, BasicList candidates, Type iType)
        {
#if WINRT
            TypeInfo iTypeInfo = iType.GetTypeInfo();
            if (iTypeInfo.IsGenericType)
            {
                Type typeDef = iTypeInfo.GetGenericTypeDefinition();
                if (typeDef == typeof(System.Collections.Generic.ICollection <>) || typeDef.GetTypeInfo().FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
                {
                    Type[] iTypeArgs = iTypeInfo.GenericTypeArguments;
                    if (!candidates.Contains(iTypeArgs[0]))
                    {
                        candidates.Add(iTypeArgs[0]);
                    }
                }
            }
#elif !NO_GENERICS
            if (iType.IsGenericType)
            {
                Type typeDef = iType.GetGenericTypeDefinition();
                if (typeDef == model.MapType(typeof(System.Collections.Generic.IEnumerable <>)) ||
                    typeDef == model.MapType(typeof(System.Collections.Generic.ICollection <>)) ||
                    typeDef.FullName == "System.Collections.Concurrent.IProducerConsumerCollection`1")
                {
                    Type[] iTypeArgs = iType.GetGenericArguments();
                    if (!candidates.Contains(iTypeArgs[0]))
                    {
                        candidates.Add(iTypeArgs[0]);
                    }
                }
            }
#endif
        }
Ejemplo n.º 4
0
        protected string GetTypeMetadataName(Type current)
        {
            current = (current.IsGenericType && !current.IsGenericTypeDefinition) ?
                      current.GetGenericTypeDefinition() : current;

            return(GetAssemblyIdentifier(current).Name + ".t" + current.MetadataToken.ToString("x"));
        }
Ejemplo n.º 5
0
    public Type GetUnderlyingNullableType(Type type)
    {
        if (!type.IsConstructedGenericType)
        {
            return(null);
        }

        var gt = type.GetGenericTypeDefinition();

        if (gt.Assembly != CorlibAssembly)
        {
            return(null);
        }

        if (gt.Namespace != "System")
        {
            return(null);
        }

        if (gt.Name != "Nullable`1")
        {
            return(null);
        }

        return(type.GenericTypeArguments [0]);
    }
Ejemplo n.º 6
0
 static bool IsNestedTypeWithNamespace(Type type)
 {
     if (!type.IsNested)
     {
         return(false);
     }
     if (type.IsConstructedGenericType)
     {
         type = type.GetGenericTypeDefinition();
     }
     return(type.__Namespace != null);
 }
Ejemplo n.º 7
0
        private static bool CheckDictionaryAccessors(TypeModel model, Type pair, Type value)
        {
#if NO_GENERICS
            return(false);
#elif WINRT
            TypeInfo finalType = pair.GetTypeInfo();
            return(finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair <,>) &&
                   finalType.GenericTypeArguments[1] == value);
#else
            return(pair.IsGenericType && pair.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.KeyValuePair <,>)) &&
                   pair.GetGenericArguments()[1] == value);
#endif
        }
Ejemplo n.º 8
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;
 }
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
0
        void FindInheritedInterfaceMethods(Type type, HashSet <string> masters, HashSet <MethodInfo> result)
        {
            if (!type.IsTypeBuilder())
            {
                foreach (var i in type.GetInterfaces())
                {
                    FindInheritedInterfaceMethods(i, masters, result);
                }

                foreach (var mi in type.GetMethods())
                {
                    var master = mi.GetReflectedName();

                    if (mi.DeclaringType == type && !masters.Contains(master))
                    {
                        result.Add(mi);
                        masters.Add(master);
                    }
                }
            }
            else if (type.IsGenericType)
            {
                var def = type.GetGenericTypeDefinition();

                foreach (var i in def.GetInterfaces())
                {
                    FindInheritedInterfaceMethods(ParameterizeInterface(type, i), masters, result);
                }

                foreach (var mi in def.GetMethods())
                {
                    var master = mi.GetReflectedName();

                    if (mi.DeclaringType == def && !masters.Contains(master))
                    {
                        result.Add(TypeBuilder.GetMethod(type, mi));
                        masters.Add(master);
                    }
                }
            }
        }
Ejemplo n.º 11
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
        }
Ejemplo n.º 12
0
 static bool IsNestedTypeWithNamespace(Type type)
 {
     if (!type.IsNested)
     {
         return false;
     }
     if (type.IsConstructedGenericType)
     {
         type = type.GetGenericTypeDefinition();
     }
     return type.__Namespace != null;
 }
Ejemplo n.º 13
0
 bool Compare(Type a, Type b)
 {
     return(a == b ||
            a.IsGenericType && b.IsGenericType &&
            a.GetGenericTypeDefinition() == b.GetGenericTypeDefinition());
 }
Ejemplo n.º 14
0
		// NOTE when this is called on a remapped type, the "warped" underlying type name is returned.
		// E.g. GetName(typeof(object)) returns "cli.System.Object".
		internal static string GetName(Type type)
		{
			Debug.Assert(!type.Name.EndsWith("[]") && !AttributeHelper.IsJavaModule(type.Module));

			string name = type.FullName;

			if (name == null)
			{
				// generic type parameters don't have a full name
				return null;
			}

			if (type.IsGenericType && !type.ContainsGenericParameters)
			{
				System.Text.StringBuilder sb = new System.Text.StringBuilder();
				sb.Append(MangleTypeName(type.GetGenericTypeDefinition().FullName));
				sb.Append("_$$$_");
				string sep = "";
				foreach (Type t1 in type.GetGenericArguments())
				{
					Type t = t1;
					sb.Append(sep);
					// NOTE we can't use ClassLoaderWrapper.GetWrapperFromType() here to get t's name,
					// because we might be resolving a generic type that refers to a type that is in
					// the process of being constructed.
					//
					// For example:
					//   class Base<T> { } 
					//   class Derived : Base<Derived> { }
					//
					while (ReflectUtil.IsVector(t))
					{
						t = t.GetElementType();
						sb.Append('A');
					}
					if (PrimitiveTypeWrapper.IsPrimitiveType(t))
					{
						sb.Append(ClassLoaderWrapper.GetWrapperFromType(t).SigName);
					}
					else
					{
						string s;
						if (ClassLoaderWrapper.IsRemappedType(t) || AttributeHelper.IsJavaModule(t.Module))
						{
							s = ClassLoaderWrapper.GetWrapperFromType(t).Name;
						}
						else
						{
							s = DotNetTypeWrapper.GetName(t);
						}
						// only do the mangling for non-generic types (because we don't want to convert
						// the double underscores in two adjacent _$$$_ or _$$$$_ markers)
						if (s.IndexOf("_$$$_") == -1)
						{
							s = s.Replace("__", "$$005F$$005F");
							s = s.Replace(".", "__");
						}
						sb.Append('L').Append(s);
					}
					sep = "_$$_";
				}
				sb.Append("_$$$$_");
				return sb.ToString();
			}

			if (AttributeHelper.IsNoPackagePrefix(type)
				&& name.IndexOf('$') == -1)
			{
				return name.Replace('+', '$');
			}

			return MangleTypeName(name);
		}
Ejemplo n.º 15
0
 internal static bool IsPackedArgsContainer(Type type)
 {
     return type.IsGenericType
         && type.GetGenericTypeDefinition() == typeofMHA;
 }
Ejemplo n.º 16
0
        protected virtual JSExpression GetTypeIdentifier(Type type, MethodBase methodScope = null, Type typeScope = null, JSExpression thisScope = null, ICollection <Type> typesInScope = null)
        {
            if (IsIgnoredType(type))
            {
                throw new InvalidOperationException("type is marked as ignored and cannot be referenced");
            }

            if (typesInScope != null)
            {
                var idx = typesInScope.IndexOf(type);
                if (idx != -1)
                {
                    return(JSFactory.Identifier("t" + idx));
                }
            }

            if (type.IsArray)
            {
                var genericArray = context.ReflectionUniverse.GetType("System.Array`1");
                return(GetTypeIdentifier(
                           genericArray.MakeGenericType(type.GetElementType()),
                           methodScope,
                           typeScope,
                           thisScope,
                           typesInScope));
            }
            else if (type.IsGenericParameter)
            {
                if (type.DeclaringMethod != null ||

                    // For static methods on generic classes, the type arguments are passed to
                    // the method at the call site rather than wired through the generic class type.
                    // So, the type argument is available as an argument in the closure of the
                    // javascript function, which is why we emit an identifier.

                    (methodScope != null && methodScope.IsStatic && type.DeclaringType.GetGenericTypeDefinition() == methodScope.DeclaringType))
                {
                    return(new JSIdentifier {
                        Name = type.Name
                    });
                }
                else if (thisScope == null)
                {
                    return
                        ((IsInScope(type.DeclaringType, typeScope)) ?
                         JSFactory.Identifier(GetSimpleName(type)) :

                         // to my awareness, this only happens when you do "typeof(C<>)", ie not specifying any args
                         GetTypeIdentifier(context.SystemTypes.UnboundGenericParameter));
                }
                else
                {
                    var metadataName = GetTypeMetadataName(typeScope);
                    return(new JSArrayLookupExpression
                    {
                        Array = JSFactory.Identifier(thisScope, "constructor", "GenericArguments", metadataName),
                        Indexer = new JSNumberLiteral {
                            Value = typeScope.GetGenericArguments().IndexOf(type)
                        }
                    });
                }
            }
            else if (type.IsGenericType)
            {
                return(new JSCallExpression
                {
                    Function = JSFactory.Identifier(
                        GetAssemblyIdentifier(type), type.GetGenericTypeDefinition().FullName),
                    Arguments = type
                                .GetGenericArguments()
                                .Select(
                        g => GetTypeIdentifier(g, methodScope, typeScope, thisScope, typesInScope))
                                .ToList()
                });
            }
            else
            {
                return(new JSCallExpression
                {
                    Function = JSFactory.Identifier(GetAssemblyIdentifier(type), type.FullName)
                });
            }
        }
Ejemplo n.º 17
0
        public static void GetFullNameForStackTrace(StringBuilder sb, MethodBase mi)
        {
            var declaringType = mi.DeclaringType;

            if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
            {
                declaringType = declaringType.GetGenericTypeDefinition();
            }

            // Get generic definition
            var bindingflags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

            foreach (var m in declaringType.GetMethods(bindingflags))
            {
                if (m.MetadataToken == mi.MetadataToken)
                {
                    mi = m;
                    break;
                }
            }

            sb.Append(declaringType.ToString());

            sb.Append(".");
            sb.Append(mi.Name);

            if (mi.IsGenericMethod)
            {
                Type[] gen_params = mi.GetGenericArguments();
                sb.Append("[");
                for (int j = 0; j < gen_params.Length; j++)
                {
                    if (j > 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append(gen_params [j].Name);
                }
                sb.Append("]");
            }

            ParameterInfo[] p = mi.GetParameters();

            sb.Append(" (");
            for (int i = 0; i < p.Length; ++i)
            {
                if (i > 0)
                {
                    sb.Append(", ");
                }

                Type pt = p[i].ParameterType;
                if (pt.IsGenericType && !pt.IsGenericTypeDefinition)
                {
                    pt = pt.GetGenericTypeDefinition();
                }

                sb.Append(pt.ToString());

                if (p [i].Name != null)
                {
                    sb.Append(" ");
                    sb.Append(p [i].Name);
                }
            }
            sb.Append(")");
        }
Ejemplo n.º 18
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; }
            }
        }
Ejemplo n.º 19
0
        private static object CreateListInstance(Type listType, Type itemType)
        {
            Type concreteListType = listType;

            if (listType.IsArray)
            {
                return(Array.CreateInstance(itemType, 0));
            }

#if WINRT
            TypeInfo listTypeInfo = listType.GetTypeInfo();
            if (!listTypeInfo.IsClass || listTypeInfo.IsAbstract ||
                Helpers.GetConstructor(listTypeInfo, Helpers.EmptyTypes, true) == null)
#else
            if (!listType.IsClass || listType.IsAbstract ||
                Helpers.GetConstructor(listType, Helpers.EmptyTypes, true) == null)
#endif
            {
                string fullName;
                bool   handled = false;
#if WINRT
                if (listTypeInfo.IsInterface &&
#else
                if (listType.IsInterface &&
#endif
                    (fullName = listType.FullName) != null && fullName.IndexOf("Dictionary", System.StringComparison.Ordinal) >= 0) // have to try to be frugal here...
                {
#if !NO_GENERICS
#if WINRT
                    TypeInfo finalType = listType.GetTypeInfo();
                    if (finalType.IsGenericType && finalType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary <,>))
                    {
                        Type[] genericTypes = listType.GenericTypeArguments;
                        concreteListType = typeof(System.Collections.Generic.Dictionary <,>).MakeGenericType(genericTypes);
                        handled          = true;
                    }
#else
                    if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary <,>))
                    {
                        Type[] genericTypes = listType.GetGenericArguments();
                        concreteListType = typeof(System.Collections.Generic.Dictionary <,>).MakeGenericType(genericTypes);
                        handled          = true;
                    }
#endif
#endif
#if !SILVERLIGHT && !WINRT && !PORTABLE
                    if (!handled && listType == typeof(IDictionary))
                    {
                        concreteListType = typeof(Hashtable);
                        handled          = true;
                    }
#endif
                }
#if !NO_GENERICS
                if (!handled)
                {
                    concreteListType = typeof(System.Collections.Generic.List <>).MakeGenericType(itemType);
                    handled          = true;
                }
#endif

#if !SILVERLIGHT && !WINRT && !PORTABLE
                if (!handled)
                {
                    concreteListType = typeof(ArrayList);
                    handled          = true;
                }
#endif
            }
            return(Activator.CreateInstance(concreteListType));
        }
Ejemplo n.º 20
0
		TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
		{
			TypeSpec spec;
			if (import_cache.TryGetValue (type, out spec)) {
				if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
					if (dtype.IsDynamicObject (this))
						return module.Compiler.BuiltinTypes.Dynamic;

					return spec;
				}

				if (!spec.IsGeneric || type.IsGenericTypeDefinition)
					return spec;

				if (!dtype.HasDynamicAttribute (this))
					return spec;

				// We've found same object in the cache but this one has a dynamic custom attribute
				// and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
				// Do type resolve process again in that case

				// TODO: Handle cases where they still unify
			}

			if (IsMissingType (type)) {
				spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
				spec.MemberCache = MemberCache.Empty;
				import_cache.Add (type, spec);
				return spec;
			}

			if (type.IsGenericType && !type.IsGenericTypeDefinition) {
				var type_def = type.GetGenericTypeDefinition ();

				// Generic type definition can also be forwarded
				if (compiled_types.TryGetValue (type_def, out spec))
					return spec;

				var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
				if (declaringType == null) {
					// Simple case, no nesting
					spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
					spec = spec.MakeGenericType (module, targs);
				} else {
					//
					// Nested type case, converting .NET types like
					// A`1.B`1.C`1<int, long, string> to typespec like
					// A<int>.B<long>.C<string>
					//
					var nested_hierarchy = new List<TypeSpec> ();
					while (declaringType.IsNested) {
						nested_hierarchy.Add (declaringType);
						declaringType = declaringType.DeclaringType;
					}

					int targs_pos = 0;
					if (declaringType.Arity > 0) {
						spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
						targs_pos = spec.Arity;
					} else {
						spec = declaringType;
					}

					for (int i = nested_hierarchy.Count; i != 0; --i) {
						var t = nested_hierarchy [i - 1];
						spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
						if (t.Arity > 0) {
							spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
							targs_pos += t.Arity;
						}
					}

					string name = type.Name;
					int index = name.IndexOf ('`');
					if (index > 0)
						name = name.Substring (0, index);

					spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
					if (spec == null)
						return null;

					if (spec.Arity > 0) {
						spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
					}
				}

				// Don't add generic type with dynamic arguments, they can interfere with same type
				// using object type arguments
				if (!spec.HasDynamicElement) {

					// Add to reading cache to speed up reading
					if (!import_cache.ContainsKey (type))
						import_cache.Add (type, spec);
				}

				return spec;
			}

			Modifiers mod;
			MemberKind kind;

			var ma = type.Attributes;
			switch (ma & TypeAttributes.VisibilityMask) {
			case TypeAttributes.Public:
			case TypeAttributes.NestedPublic:
				mod = Modifiers.PUBLIC;
				break;
			case TypeAttributes.NestedPrivate:
				mod = Modifiers.PRIVATE;
				break;
			case TypeAttributes.NestedFamily:
				mod = Modifiers.PROTECTED;
				break;
			case TypeAttributes.NestedFamORAssem:
				mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
				break;
			default:
				mod = Modifiers.INTERNAL;
				break;
			}

			if ((ma & TypeAttributes.Interface) != 0) {
				kind = MemberKind.Interface;
			} else if (type.IsGenericParameter) {
				kind = MemberKind.TypeParameter;
			} else {
				var base_type = type.BaseType;
				if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
					kind = MemberKind.Class;
				} else {
					kind = DetermineKindFromBaseType (base_type);
					if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
						mod |= Modifiers.SEALED;
					}
				}

				if (kind == MemberKind.Class) {
					if ((ma & TypeAttributes.Sealed) != 0) {
						mod |= Modifiers.SEALED;
						if ((ma & TypeAttributes.Abstract) != 0)
							mod |= Modifiers.STATIC;
					} else if ((ma & TypeAttributes.Abstract) != 0) {
						mod |= Modifiers.ABSTRACT;
					}
				}
			}

			var definition = new ImportedTypeDefinition (type, this);
			TypeSpec pt;

			if (kind == MemberKind.Enum) {
				const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
					BindingFlags.Instance |
					BindingFlags.Public | BindingFlags.NonPublic;

				var type_members = type.GetFields (underlying_member);
				foreach (var type_member in type_members) {
					spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
					break;
				}

				if (spec == null)
					kind = MemberKind.Class;

			} else if (kind == MemberKind.TypeParameter) {
				spec = CreateTypeParameter (type, declaringType);
			} else if (type.IsGenericTypeDefinition) {
				definition.TypeParameters = CreateGenericParameters (type, declaringType);
			} else if (compiled_types.TryGetValue (type, out pt)) {
				//
				// Same type was found in inside compiled types. It's
				// either build-in type or forward referenced typed
				// which point into just compiled assembly.
				//
				spec = pt;
				BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
				if (bts != null)
					bts.SetDefinition (definition, type, mod);
			}

			if (spec == null)
				spec = new TypeSpec (kind, declaringType, definition, type, mod);

			import_cache.Add (type, spec);

			if (kind == MemberKind.TypeParameter) {
				if (canImportBaseType)
					ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);

				return spec;
			}

			//
			// Two stage setup as the base type can be inflated declaring type or
			// another nested type inside same declaring type which has not been
			// loaded, therefore we can import a base type of nested types once
			// the types have been imported
			//
			if (canImportBaseType)
				ImportTypeBase (spec, type);

			return spec;
		}
Ejemplo n.º 21
0
        internal static void ResolveListTypes(RuntimeTypeModel model, 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
            }
            // handle arrays
            if (type.IsArray)
            {
                itemType = type.GetElementType();
                if (itemType == model.MapType(typeof(byte)))
                {
                    defaultType = itemType = null;
                }
                else
                {
                    defaultType = type;
                }
            }
            // handle lists
            if (itemType == null)
            {
                itemType = TypeModel.GetListItemType(model, type);
            }

            if (itemType != null && defaultType == null)
            {
#if WINRT
                TypeInfo typeInfo = type.GetTypeInfo();
                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 && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary <,>) &&
                            itemType == typeof(System.Collections.Generic.KeyValuePair <,>).MakeGenericType(genArgs = typeInfo.GenericTypeArguments))
#else
                        if (type.IsGenericType && type.GetGenericTypeDefinition() == model.MapType(typeof(System.Collections.Generic.IDictionary <,>)) &&
                            itemType == model.MapType(typeof(System.Collections.Generic.KeyValuePair <,>)).MakeGenericType(genArgs = type.GetGenericArguments()))
#endif
                        {
                            defaultType = model.MapType(typeof(System.Collections.Generic.Dictionary <,>)).MakeGenericType(genArgs);
                        }
                        else
                        {
                            defaultType = model.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;
                }
            }
        }