GetGenericArguments() public method

public GetGenericArguments ( ) : Type[]
return Type[]
Esempio n. 1
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
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        private JSExpression GetGenericTypeMetadataName(Type type)
        {
            var n = GetTypeMetadataName(type);

            if (!type.IsGenericTypeDefinition)
            {
                return(JSFactory.Literal(n));
            }

            var ga    = type.GetGenericArguments().Select(a => JSFactory.Identifier(GetSimpleName(a), "GenericTypeMetadataName"));
            var gaStr = ga.Aggregate((a, b) => new JSBinaryExpression {
                Left = a, Right = b, Operator = "+"
            });

            return(new JSBinaryExpression
            {
                Left = JSFactory.Literal(n + "<"),
                Operator = "+",
                Right = new JSBinaryExpression
                {
                    Left = gaStr,
                    Operator = "+",
                    Right = JSFactory.Literal(">")
                }
            });
        }
Esempio n. 4
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);
        }
Esempio n. 5
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);
        }
Esempio n. 6
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);
     }
 }
Esempio n. 7
0
 private JSArrayLiteral GetGenericArgumentsArray(Type type, Type typeScope)
 {
     return(new JSArrayLiteral
     {
         Inline = true,
         Values = type
                  .GetGenericArguments()
                  .Select(t => GetTypeIdentifier(t, typeScope: typeScope))
                  .ToList()
     });
 }
Esempio n. 8
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
        }
Esempio 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);
 }
Esempio n. 10
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;
 }
Esempio 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
        }
Esempio n. 12
0
        static bool CheckIsIReadOnlyCollectionExactly(Type t)
#endif
        {
            if (t != null && t.IsGenericType && t.Name.StartsWith("IReadOnlyCollection`", StringComparison.Ordinal))
            {
#if WINRT
                Type[] typeArgs = t.GenericTypeArguments;
                if (typeArgs.Length != 1 && typeArgs[0].GetTypeInfo().Equals(t))
                {
                    return(false);
                }
#else
                Type[] typeArgs = t.GetGenericArguments();
                if (typeArgs.Length != 1 && typeArgs[0] != t)
                {
                    return(false);
                }
#endif

                return(true);
            }
            return(false);
        }
Esempio n. 13
0
        internal static ClassLoaderWrapper GetGenericClassLoader(TypeWrapper wrapper)
        {
            Type type = wrapper.TypeAsTBD;

            Debug.Assert(type.IsGenericType);
            Debug.Assert(!type.ContainsGenericParameters);

            List <ClassLoaderWrapper> list = new List <ClassLoaderWrapper>();

            list.Add(AssemblyClassLoader.FromAssembly(type.Assembly));
            foreach (Type arg in type.GetGenericArguments())
            {
                ClassLoaderWrapper loader = GetWrapperFromType(arg).GetClassLoader();
                if (!list.Contains(loader) && loader != bootstrapClassLoader)
                {
                    list.Add(loader);
                }
            }
            ClassLoaderWrapper[] key            = list.ToArray();
            ClassLoaderWrapper   matchingLoader = GetGenericClassLoaderByKey(key);

            matchingLoader.RegisterInitiatingLoader(wrapper);
            return(matchingLoader);
        }
Esempio n. 14
0
 internal override TypeWrapper GetWrapperFromAssemblyType(Type type)
 {
     // we have to special case the fake types here
     if (type.IsGenericType && !type.IsGenericTypeDefinition)
     {
         TypeWrapper outer = ClassLoaderWrapper.GetWrapperFromType(type.GetGenericArguments()[0]);
         foreach (TypeWrapper inner in outer.InnerClasses)
         {
             if (inner.TypeAsTBD == type)
             {
                 return(inner);
             }
             foreach (TypeWrapper inner2 in inner.InnerClasses)
             {
                 if (inner2.TypeAsTBD == type)
                 {
                     return(inner2);
                 }
             }
         }
         return(null);
     }
     return(base.GetWrapperFromAssemblyType(type));
 }
        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; }
            }
        }
Esempio n. 16
0
 public FieldInfo ResolveField(int metadataToken)
 {
     return(this.module.ResolveField(metadataToken,
                                     type.IsGenericType ? type.GetGenericArguments() : null, method.IsGenericMethod ? method.GetGenericArguments() : null));
 }
Esempio n. 17
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;
                }
            }
        }
Esempio n. 18
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;
 }
Esempio n. 19
0
        void WriteIL(LineWriter lw, MethodBase mb, MethodBody body, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            ParameterInfo[] parameters = mb.GetParameters();
            int             level      = lw.Column;

            byte[] code = body.GetILAsByteArray();
            lw.GoToColumn(level);
            lw.WriteLine("// Code size       {0} (0x{0:x})", code.Length);
            lw.GoToColumn(level);
            lw.WriteLine(".maxstack  {0}", body.MaxStackSize);

            IList <LocalVariableInfo> locals = body.LocalVariables;

            if (locals.Count != 0)
            {
                lw.GoToColumn(level);
                lw.Write(".locals ");
                if (body.InitLocals)
                {
                    lw.Write("init ");
                }
                lw.Write("(");
                bool first = true;
                foreach (var local in locals)
                {
                    if (!first)
                    {
                        lw.WriteLine(",");
                        lw.GoToColumn(level + 9);
                    }
                    first = false;
                    WriteSignatureType(lw, local.LocalType, TypeLocation.Local);
                    if (local.IsPinned)
                    {
                        lw.Write(" pinned");
                    }
                    WriteCustomModifiers(lw, local.__GetCustomModifiers());
                    lw.Write(" V_{0}", local.LocalIndex);
                }
                lw.WriteLine(")");
            }

            var exceptions  = new List <ExceptionHandlingClause>();
            var exceptions2 = new List <ExceptionHandlingClause>();

            SortExceptions(body.ExceptionHandlingClauses, exceptions, exceptions2);

            Stack <ExceptionHandlingClause> activeExceptions = new Stack <ExceptionHandlingClause>();
            ExceptionHandlingClause         currentException = null;
            bool extraNewLine      = false;
            int  nextFlatException = 0;
            int  nextException     = 0;
            bool handler           = false;
            int  pos = 0;

            while (pos < code.Length)
            {
                if (extraNewLine)
                {
                    lw.WriteLine();
                    extraNewLine = false;
                }
                if (currentException != null)
                {
                    if (currentException.HandlerOffset == pos)
                    {
                        switch (currentException.Flags)
                        {
                        case ExceptionHandlingClauseOptions.Clause:
                            lw.GoToColumn(level - 2);
                            if (currentException.TryOffset + currentException.TryLength == pos)
                            {
                                lw.WriteLine("}  // end .try");
                            }
                            else
                            {
                                lw.WriteLine("}  // end handler");
                            }
                            lw.GoToColumn(level - 2);
                            lw.Write("catch ");
                            if (currentException.CatchType.__IsMissing || !currentException.CatchType.IsGenericType)
                            {
                                WriteTypeDefOrRef(lw, currentException.CatchType);
                            }
                            else
                            {
                                WriteSignatureType(lw, currentException.CatchType);
                            }
                            lw.WriteLine(" ");
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("{");
                            handler = true;
                            break;

                        case ExceptionHandlingClauseOptions.Finally:
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("}  // end .try");
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("finally");
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("{");
                            break;

                        case ExceptionHandlingClauseOptions.Fault:
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("}  // end .try");
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("fault");
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("{");
                            break;

                        case ExceptionHandlingClauseOptions.Filter:
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("}  // end filter");
                            lw.GoToColumn(level - 2);
                            lw.WriteLine("{  // handler");
                            handler = true;
                            break;

                        default:
                            throw new IKVM.Reflection.BadImageFormatException();
                        }
                    }
                    else if (currentException.FilterOffset == pos && pos != 0)
                    {
                        lw.GoToColumn(level - 2);
                        if (handler)
                        {
                            lw.WriteLine("}  // end handler");
                        }
                        else
                        {
                            lw.WriteLine("}  // end .try");
                        }
                        lw.GoToColumn(level - 2);
                        lw.WriteLine("filter");
                        lw.GoToColumn(level - 2);
                        lw.WriteLine("{");
                    }
                }
                while (nextException < exceptions.Count &&
                       exceptions[nextException].TryOffset == pos)
                {
                    activeExceptions.Push(currentException);
                    ExceptionHandlingClause prevException = currentException;
                    currentException = exceptions[nextException++];
                    if (prevException != null && currentException.TryOffset == prevException.TryOffset && currentException.TryLength == prevException.TryLength)
                    {
                        // another handler for the same block
                        continue;
                    }
                    handler = false;
                    lw.GoToColumn(level);
                    lw.WriteLine(".try");
                    lw.GoToColumn(level);
                    lw.WriteLine("{");
                    level += 2;
                }
                lw.GoToColumn(level);
                int currPos = pos;
                lw.Write("IL_{0:x4}:  ", pos);
                int   level1      = lw.Column;
                short opcodeValue = code[pos++];
                if (opcodeValue == 0xFE)
                {
                    opcodeValue = (short)(0xFE00 + code[pos++]);
                }
                OpCode opcode = opcodes[opcodeValue + 512];
                lw.Write("{0}", opcode.Name);
                switch (opcode.OperandType)
                {
                case OperandType.InlineNone:
                    break;

                case OperandType.InlineBrTarget:
                    lw.GoToColumn(level1 + 11);
                    lw.Write("IL_{0:x4}", ReadInt32(code, ref pos) + pos);
                    break;

                case OperandType.ShortInlineBrTarget:
                    lw.GoToColumn(level1 + 11);
                    lw.Write("IL_{0:x4}", (sbyte)code[pos++] + pos);
                    break;

                case OperandType.InlineMethod:
                {
                    lw.GoToColumn(level1 + 11);
                    int        token = ReadInt32(code, ref pos);
                    MethodBase methodOrConstructor = ResolveMethod(token, genericTypeArguments, genericMethodArguments);
                    if ((methodOrConstructor.CallingConvention & CallingConventions.Any) == CallingConventions.VarArgs)
                    {
                        CustomModifiers[] customModifiers;
                        Type[]            optionalParameterTypes = ResolveOptionalParameterTypes(token, genericTypeArguments, genericMethodArguments, out customModifiers);
                        WriteInlineMethod(lw, methodOrConstructor, optionalParameterTypes, customModifiers);
                    }
                    else
                    {
                        WriteInlineMethod(lw, methodOrConstructor, Type.EmptyTypes, null);
                    }
                }
                break;

                case OperandType.InlineField:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineField(lw, ResolveField(ReadInt32(code, ref pos), genericTypeArguments, genericMethodArguments));
                    break;

                case OperandType.InlineI:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineI(lw, ReadInt32(code, ref pos));
                    break;

                case OperandType.InlineI8:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineI8(lw, ReadInt64(code, ref pos));
                    break;

                case OperandType.ShortInlineI:
                    lw.GoToColumn(level1 + 11);
                    lw.Write("{0}", (sbyte)code[pos++]);
                    break;

                case OperandType.InlineR:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineR(lw, ReadDouble(code, ref pos), false);
                    break;

                case OperandType.ShortInlineR:
                    lw.GoToColumn(level1 + 11);
                    WriteShortInlineR(lw, ReadSingle(code, ref pos), false);
                    break;

                case OperandType.InlineType:
                    if (opcode == OpCodes.Constrained)
                    {
                        // "constrained." is too long to fit in the opcode column
                        lw.Write(" ");
                    }
                    else
                    {
                        lw.GoToColumn(level1 + 11);
                    }
                    WriteInlineType(lw, ReadInt32(code, ref pos), genericTypeArguments, genericMethodArguments);
                    break;

                case OperandType.InlineTok:
                {
                    int token = ReadInt32(code, ref pos);
                    switch (token >> 24)
                    {
                    case 0x01:
                    case 0x02:
                        lw.GoToColumn(level1 + 11);
                        WriteTypeDefOrRef(lw, ResolveType(token, genericTypeArguments, genericMethodArguments));
                        break;

                    case 0x1B:
                    {
                        Type type = ResolveType(token, genericTypeArguments, genericMethodArguments);
                        if (type.IsGenericTypeDefinition)
                        {
                            // HACK because typeof(Foo<>).MakeGenericType(typeof(Foo<>).GetGenericArguments()) == typeof(Foo<>)
                            // we need to inflate the builder here
                            type = type.MakeGenericType(type.GetGenericArguments());
                        }
                        lw.GoToColumn(level1 + 11);
                        WriteSignatureType(lw, type);
                        break;
                    }

                    case 0x04:
                    case 0x06:
                    case 0x0A:
                    case 0x2B:
                    {
                        MemberInfo member = ResolveMember(token, genericTypeArguments, genericMethodArguments);
                        if (member is FieldInfo)
                        {
                            lw.GoToColumn(level1 + 11);
                            lw.Write("field ");
                            WriteInlineField(lw, (FieldInfo)member);
                        }
                        else
                        {
                            var mb1 = (MethodBase)member;
                            lw.GoToColumn(level1 + 11);
                            if (mb1.__IsMissing || !mb1.IsGenericMethod || compat != CompatLevel.V20)
                            {
                                lw.Write("method ");
                            }
                            WriteInlineMethod(lw, mb1, Type.EmptyTypes, null);
                        }
                        break;
                    }

                    default:
                        throw new NotImplementedException("token type = " + (token >> 24));
                    }
                }
                break;

                case OperandType.InlineVar:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineVar(lw, mb, opcode, parameters, ReadInt16(code, ref pos));
                    break;

                case OperandType.ShortInlineVar:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineVar(lw, mb, opcode, parameters, code[pos++]);
                    break;

                case OperandType.InlineString:
                    lw.GoToColumn(level1 + 11);
                    WriteInlineString(lw, module.ResolveString(ReadInt32(code, ref pos)), level);
                    break;

                case OperandType.InlineSwitch:
                {
                    lw.GoToColumn(level1 + 11);
                    lw.WriteLine("( ");
                    int count  = ReadInt32(code, ref pos);
                    int offset = pos + 4 * count;
                    for (int i = 0; i < count - 1; i++)
                    {
                        lw.GoToColumn(level + 22);
                        lw.WriteLine("IL_{0:x4},", offset + ReadInt32(code, ref pos));
                    }
                    lw.GoToColumn(level + 22);
                    lw.Write("IL_{0:x4})", offset + ReadInt32(code, ref pos));
                }
                break;

                case OperandType.InlineSig:
                    lw.GoToColumn(level1 + 11);
                    WriteStandAloneMethodSig(lw, module.__ResolveStandAloneMethodSig(ReadInt32(code, ref pos), genericTypeArguments, genericMethodArguments), false, false);
                    break;

                default:
                    throw new InvalidOperationException();
                }
                lw.WriteLine();

                if (opcode == OpCodes.Leave || opcode == OpCodes.Leave_S)
                {
                    if (pos < code.Length)
                    {
                        lw.WriteLine();
                    }
                }
                else if (opcode != OpCodes.Switch && opcode != OpCodes.Rethrow && opcode != OpCodes.Endfilter && opcode != OpCodes.Endfinally)
                {
                    switch (opcode.FlowControl)
                    {
                    case FlowControl.Branch:
                    case FlowControl.Cond_Branch:
                    case FlowControl.Throw:
                    case FlowControl.Return:
                        extraNewLine = true;
                        break;
                    }
                }
                if (nextFlatException < exceptions2.Count && exceptions2[nextFlatException].HandlerOffset + exceptions2[nextFlatException].HandlerLength == currPos)
                {
                    if (extraNewLine && pos < code.Length)
                    {
                        extraNewLine = false;
                        lw.WriteLine();
                    }
                    lw.GoToColumn(level);
                    if (exceptions2[nextFlatException].FilterOffset == 0)
                    {
                        lw.Write(".try IL_{0:x4} to IL_{1:x4} catch ", exceptions2[nextFlatException].TryOffset, exceptions2[nextFlatException].TryOffset + exceptions2[nextFlatException].TryLength);
                        if (exceptions2[nextFlatException].CatchType.__IsMissing || !exceptions2[nextFlatException].CatchType.IsGenericType)
                        {
                            WriteTypeDefOrRef(lw, exceptions2[nextFlatException].CatchType);
                        }
                        else
                        {
                            WriteSignatureType(lw, exceptions2[nextFlatException].CatchType);
                        }
                        lw.WriteLine(" handler IL_{0:x4} to IL_{1:x4}", exceptions2[nextFlatException].HandlerOffset, exceptions2[nextFlatException].HandlerOffset + exceptions2[nextFlatException].HandlerLength);
                    }
                    else
                    {
                        lw.WriteLine(".try IL_{0:x4} to IL_{1:x4} filter IL_{2:x4} handler IL_{3:x4} to IL_{4:x4}",
                                     exceptions2[nextFlatException].TryOffset, exceptions2[nextFlatException].TryOffset + exceptions2[nextFlatException].TryLength,
                                     exceptions2[nextFlatException].FilterOffset,
                                     exceptions2[nextFlatException].HandlerOffset, exceptions2[nextFlatException].HandlerOffset + exceptions2[nextFlatException].HandlerLength);
                    }
                    nextFlatException++;
                }

                while (currentException != null && currentException.HandlerOffset + currentException.HandlerLength == pos)
                {
                    ExceptionHandlingClause prevException = currentException;
                    currentException = activeExceptions.Pop();
                    if (currentException == null || currentException.TryOffset != prevException.TryOffset || currentException.TryLength != prevException.TryLength)
                    {
                        if (extraNewLine && pos < code.Length)
                        {
                            extraNewLine = false;
                            lw.WriteLine();
                        }
                        level -= 2;
                        lw.GoToColumn(level);
                        lw.WriteLine("}  // end handler");
                        handler = false;
                    }
                    else
                    {
                        handler = true;
                    }
                }
            }
        }
Esempio n. 20
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);
		}
Esempio n. 21
0
	void GetTypeName (StringBuilder sb, Type t)
	{
		sb.Append (RemoveGenericArity (t.Name));
		sb.Append (FormatGenericParams (t.GetGenericArguments ()));
	}
Esempio n. 22
0
        internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            if (model == null || declaredType == null)
            {
                return(false);
            }
#if WINRT || COREFX
            TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if (!declaredTypeInfo.IsGenericType)
            {
                return(false);
            }

#if WINRT || COREFX
            Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
            case 1:
                effectiveType = typeArgs;
                break;     // fine

            case 2:
                Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair <,>));
                if (kvp == null)
                {
                    return(false);
                }
                kvp           = kvp.MakeGenericType(typeArgs);
                effectiveType = new Type[] { kvp };
                break;

            default:
                return(false);    // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null)
            {
                return(false);                                                        // no IReadOnlyCollection<T> found
            }
            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int    i    = name.IndexOf('`');
            if (i <= 0)
            {
                return(false);
            }
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.Assembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.Assembly);
            }
            if (outerType == null)
            {
                return(false);
            }

#if WINRT
            foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0 ||
                    method.GetGenericArguments().Length != typeArgs.Length)
                {
                    continue;
                }

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType)
            {
                return(false);
            }


            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null)
            {
                return(false);
            }

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType)
            {
                return(false);
            }

            if (!(finish.ReturnType == declaredType || Helpers.IsAssignableFrom(declaredType, finish.ReturnType)))
            {
                return(false);
            }

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable <>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return(true);
        }
Esempio n. 23
0
        protected ListDecorator(TypeModel model, Type declaredType, Type concreteType, IProtoSerializer tail, int fieldNumber, bool writePacked, WireType packedWireType, bool returnList, bool overwriteList, bool supportNull)
            : base(tail)
        {
            if (returnList)
            {
                options |= OPTIONS_ReturnList;
            }
            if (overwriteList)
            {
                options |= OPTIONS_OverwriteList;
            }
            if (supportNull)
            {
                options |= OPTIONS_SupportNull;
            }
            if ((writePacked || packedWireType != WireType.None) && fieldNumber <= 0)
            {
                throw new ArgumentOutOfRangeException("fieldNumber");
            }
            if (!CanPack(packedWireType))
            {
                if (writePacked)
                {
                    throw new InvalidOperationException("Only simple data-types can use packed encoding");
                }
                packedWireType = WireType.None;
            }

            this.fieldNumber = fieldNumber;
            if (writePacked)
            {
                options |= OPTIONS_WritePacked;
            }
            this.packedWireType = packedWireType;
            if (declaredType == null)
            {
                throw new ArgumentNullException("declaredType");
            }
            if (declaredType.IsArray)
            {
                throw new ArgumentException("Cannot treat arrays as lists", "declaredType");
            }
            this.declaredType = declaredType;
            this.concreteType = concreteType;

            Type[] genericTypes = declaredType.GetGenericArguments();
            if (genericTypes.Length == 1)
            {
                this.itemType = declaredType.GetGenericArguments()[0];
            }
            else
            {
                this.itemType = Tail.ExpectedType;
            }

            // look for a public list.Add(typedObject) method
            if (RequireAdd)
            {
                bool isList;
                add = TypeModel.ResolveListAdd(model, declaredType, tail.ExpectedType, out isList);
                if (isList)
                {
                    options |= OPTIONS_IsList;
                    string fullName = declaredType.FullName;
                    if (fullName != null && fullName.StartsWith("System.Data.Linq.EntitySet`1[["))
                    { // see http://stackoverflow.com/questions/6194639/entityset-is-there-a-sane-reason-that-ilist-add-doesnt-set-assigned
                        options |= OPTIONS_SuppressIList;
                    }
                }
                if (add == null)
                {
                    throw new InvalidOperationException("Unable to resolve a suitable Add method for " + declaredType.FullName);
                }
            }
        }
Esempio n. 24
0
        void GenerateCode(Type type)
        {
            if (type.IsGenericType && !type.IsGenericTypeDefinition)
                return; // generate nothing.

            var implprops = new List<PropertyInfo> ();
            var miscprops = new List<PropertyInfo> ();
            foreach (var p in type.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
                if (targets.Contains (p.PropertyType) && !p.PropertyType.IsEnum)
                    implprops.Add (p);
                else
                    miscprops.Add (p);
            }

            output.WriteLine ("// generic ordinal type for " + type);
            string template = @"
            public {10}partial class {0} : {1} {2}
            {{
            {7} impl;

            // constructor, if not abstract.
            {9}

            // impl-to-wrapper constructor
            internal protected {8} ({7} impl) {6}
            {{
            this.impl = impl;
            {11}
            Initialize ();
            }}

            // initializer
            void Initialize ()
            {{
            // repeat for all auto (new-Android-type) properties
            {3}
            }}

            // explicit conversion operator
            public static explicit operator {7} ({0} source)
            {{
            return source.impl;
            }}

            // For a property whose type is wrapper for Android type, just make it auto property (use private set for get-only ones)
            {4}

            // Non-Android properties follow.
            {5}
            }}
            ";

            var actx = android_ass.GetType ("Android.Content.Context");
            var aaset = android_ass.GetType ("Android.Util.IAttributeSet");
            // somehow GetConstructor() returns weird results, so this workarounds that.
            string args =
                type.GetConstructors ().Any (c => c.GetParameters ().Length == 1 && c.GetParameters () [0].ParameterType.FullName == actx.FullName) ? "XamlView.CurrentContext" :
                type.GetConstructors ().Any (c => c.GetParameters ().Length == 2 && c.GetParameters () [0].ParameterType.FullName == actx.FullName && c.GetParameters () [1].ParameterType.FullName == aaset.FullName) ? "XamlView.CurrentContext, null" :
                "";
            //if (type.Name == "SlidingDrawer") foreach (var ccc in type.GetConstructors ()) Console.WriteLine ("!!!! " + ccc + " / " +  type.GetConstructor (new Type [] {actx}).GetParameters ().Length);
            string publicConstructor = type.IsAbstract ? String.Empty : String.Format (@"
            public {0} ()
            : this (new {1} ({2}))
            {{

            }}", type.NonGenericName (), type.CSFullName (), args);

            string templateInit = @"
            if (impl.{0} != null)
                {0} = Extensions.GetWrappedItem<{1}> (impl.{0});";
            var isw = new StringWriter () { NewLine = "\n" };
            foreach (var p in implprops)
                if (!p.IsAbstract ())
                    isw.WriteLine (templateInit, p.Name, p.PropertyType.CSName ());

            string templateImplProp = @"
            public {3}{0} {1} {{ get; {2}set; }}";
            var dpsw = new StringWriter () { NewLine = "\n" };
            foreach (var p in implprops)
                dpsw.WriteLine (templateImplProp, p.PropertyType.CSSwitchName (), p.Name, p.IsSetterPublic () ? null : "internal ", GetModifier (p));

            string templateOrdProp1 = @"
            public {3}{0} {1} {{
            get {{ return {4}; }}
            {2}
            }}";
            string templateOrdProp2 = @"
            public {3}{0} {1} {{ get; {5} }}";
            var nsw = new StringWriter () { NewLine = "\n" };
            foreach (var p in miscprops) {
                var setter = String.Format ("set {{ impl.{0} = value; }}", p.Name);
                nsw.WriteLine (p.IsAbstract () ? templateOrdProp2 : templateOrdProp1, p.PropertyType.CSSwitchName (), p.Name, p.IsSetterPublic () ? setter : null, GetModifier (p), GetValueExpression (p), p.IsSetterPublic () ? "set;" : null);
            }

            string gconsts = null;
            foreach (var arg in type.GetGenericArguments ()) {
                var gca = String.Join (",", (from t in arg.GetGenericParameterConstraints () select t.CSSwitchName ()).ToArray ());
                gconsts += String.IsNullOrEmpty (gca) ? null : "where " + arg.Name + " : " + gca;
            }

            // FIXME: write custom attributes
            bool callBase = targets.Contains (type.BaseType);
            output.WriteLine (template, type.CSName (), type.BaseType.CSSwitchName (), gconsts, isw, dpsw, nsw, callBase ? " : base (impl)" : null, type.CSFullName (), type.NonGenericName (), publicConstructor, type.IsAbstract ? "abstract " : null, callBase ? null : "XamlView.Register (impl, this);");
        }
Esempio n. 25
0
        public void OutlineType()
        {
            bool first;

            OutlineAttributes();
            o.Write(GetTypeVisibility(t));

            if (t.IsClass && !t.IsSubclassOf(type_multicast_delegate))
            {
                if (t.IsSealed)
                {
                    o.Write(t.IsAbstract ? " static" : " sealed");
                }
                else if (t.IsAbstract)
                {
                    o.Write(" abstract");
                }
            }

            o.Write(" ");
            o.Write(GetTypeKind(t));
            o.Write(" ");

            Type [] interfaces = (Type [])Comparer.Sort(TypeGetInterfaces(t, declared_only));
            Type    parent     = t.BaseType;

            if (t.IsSubclassOf(type_multicast_delegate))
            {
                MethodInfo method;

                method = t.GetMethod("Invoke");

                o.Write(FormatType(method.ReturnType));
                o.Write(" ");
                o.Write(GetTypeName(t));
                o.Write(" (");
                OutlineParams(method.GetParameters());
                o.Write(")");

                WriteGenericConstraints(t.GetGenericArguments());

                o.WriteLine(";");
                return;
            }

            o.Write(GetTypeName(t));
            if (((parent != null && parent != type_object && parent != type_value_type) || interfaces.Length != 0) && !t.IsEnum)
            {
                first = true;
                o.Write(" : ");

                if (parent != null && parent != type_object && parent != type_value_type)
                {
                    o.Write(FormatType(parent));
                    first = false;
                }

                foreach (Type intf in interfaces)
                {
                    if (!first)
                    {
                        o.Write(", ");
                    }
                    first = false;

                    o.Write(FormatType(intf));
                }
            }

            if (t.IsEnum)
            {
                Type underlyingType = t.GetEnumUnderlyingType();
                if (underlyingType != type_int)
                {
                    o.Write(" : {0}", FormatType(underlyingType));
                }
            }
            WriteGenericConstraints(t.GetGenericArguments());
            o.WriteLine(" {");
            o.Indent++;

            if (t.IsEnum)
            {
                bool is_first = true;
                foreach (FieldInfo fi in t.GetFields(BindingFlags.Public | BindingFlags.Static))
                {
                    if (!is_first)
                    {
                        o.WriteLine(",");
                    }
                    is_first = false;
                    o.Write(fi.Name);
                }
                o.WriteLine();
                o.Indent--; o.WriteLine("}");
                return;
            }

            first = true;

            foreach (ConstructorInfo ci in t.GetConstructors(DefaultFlags))
            {
                if (!ShowMember(ci))
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

                OutlineMemberAttribute(ci);
                OutlineConstructor(ci);

                o.WriteLine();
            }


            first = true;

            foreach (MethodInfo m in Comparer.Sort(t.GetMethods(DefaultFlags)))
            {
                if (!ShowMember(m))
                {
                    continue;
                }

                if ((m.Attributes & MethodAttributes.SpecialName) != 0)
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

                OutlineMemberAttribute(m);
                OutlineMethod(m);

                o.WriteLine();
            }

            first = true;

            foreach (MethodInfo m in t.GetMethods(DefaultFlags))
            {
                if (!ShowMember(m))
                {
                    continue;
                }

                if ((m.Attributes & MethodAttributes.SpecialName) == 0)
                {
                    continue;
                }
                if (!(m.Name.StartsWith("op_")))
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

                OutlineMemberAttribute(m);
                OutlineOperator(m);

                o.WriteLine();
            }

            first = true;

            foreach (PropertyInfo pi in Comparer.Sort(t.GetProperties(DefaultFlags)))
            {
                if (!((pi.CanRead && ShowMember(pi.GetGetMethod(true))) ||
                      (pi.CanWrite && ShowMember(pi.GetSetMethod(true)))))
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

                OutlineMemberAttribute(pi);
                OutlineProperty(pi);

                o.WriteLine();
            }

            first = true;

            foreach (FieldInfo fi in t.GetFields(DefaultFlags))
            {
                if (!ShowMember(fi))
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

                OutlineMemberAttribute(fi);
                OutlineField(fi);

                o.WriteLine();
            }

            first = true;

            foreach (EventInfo ei in Comparer.Sort(t.GetEvents(DefaultFlags)))
            {
                if (!ShowMember(ei.GetAddMethod(true)))
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

                OutlineMemberAttribute(ei);
                OutlineEvent(ei);

                o.WriteLine();
            }

            first = true;

            foreach (Type ntype in Comparer.Sort(t.GetNestedTypes(DefaultFlags)))
            {
                if (!ShowMember(ntype))
                {
                    continue;
                }

                if (first)
                {
                    o.WriteLine();
                }
                first = false;

#if STATIC
                new Outline(universe, mscorlib, ntype, o, declared_only, show_private, filter_obsolete).OutlineType();
#else
                new Outline(ntype, o, declared_only, show_private, filter_obsolete).OutlineType();
#endif
            }

            o.Indent--; o.WriteLine("}");
        }
Esempio n. 26
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;
		}
Esempio n. 27
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);
        }
Esempio n. 28
0
		TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
		{
			var tparams = type.GetGenericArguments ();

			int parent_owned_count;
			if (type.IsNested) {
				parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;

				//
				// System.Reflection duplicates parent type parameters for each
				// nested type with slightly modified properties (eg. different owner)
				// This just makes things more complicated (think of cloned constraints)
				// therefore we remap any nested type owned by parent using `type_cache'
				// to the single TypeParameterSpec
				//
				if (declaringType != null && parent_owned_count > 0) {
					int read_count = 0;
					while (read_count != parent_owned_count) {
						var tparams_count = declaringType.Arity;
						if (tparams_count != 0) {
							var parent_tp = declaringType.MemberDefinition.TypeParameters;
							read_count += tparams_count;
							for (int i = 0; i < tparams_count; i++) {
								import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
							}
						}

						declaringType = declaringType.DeclaringType;
					}
				}			
			} else {
				parent_owned_count = 0;
			}

			if (tparams.Length - parent_owned_count == 0)
				return null;

			return CreateGenericParameters (parent_owned_count, tparams);
		}
Esempio n. 29
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;
     }
 }
Esempio n. 30
0
 internal override TypeWrapper GetWrapperFromAssemblyType(Type type)
 {
     // we have to special case the fake types here
     if (type.IsGenericType && !type.IsGenericTypeDefinition)
     {
         TypeWrapper outer = ClassLoaderWrapper.GetWrapperFromType(type.GetGenericArguments()[0]);
         foreach (TypeWrapper inner in outer.InnerClasses)
         {
             if (inner.TypeAsTBD == type)
             {
                 return inner;
             }
             foreach (TypeWrapper inner2 in inner.InnerClasses)
             {
                 if (inner2.TypeAsTBD == type)
                 {
                     return inner2;
                 }
             }
         }
         return null;
     }
     return base.GetWrapperFromAssemblyType(type);
 }
Esempio n. 31
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));
        }
Esempio n. 32
0
 void GetTypeName(StringBuilder sb, Type t)
 {
     sb.Append(RemoveGenericArity(t.Name));
     sb.Append(FormatGenericParams(t.GetGenericArguments()));
 }
Esempio n. 33
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)
                });
            }
        }