protected override AssemblyDefinition Generate()
        {
            var assembly = AssemblyFactory.DefineAssembly(DllName, TargetRuntime.NET_2_0, AssemblyKind.Dll);

            var objectTypeRef = assembly.MainModule.Import(typeof (object));
            var module = assembly.MainModule;

            var xType = new TypeDefinition("X", "", TypeAttributes.Class, objectTypeRef);
            xType.GenericParameters.Add(new GenericParameter("T", xType));
            module.Types.Add(xType);
            xType.Module = module;

            var aType = new TypeDefinition("A", "", TypeAttributes.Class, null);
            var bType = new TypeDefinition("B", "", TypeAttributes.Class, null);

            var aBaseType = new GenericInstanceType(xType);
            aBaseType.GenericArguments.Add(bType);
            aType.BaseType = aBaseType;

            var bBaseType = new GenericInstanceType(xType);
            bBaseType.GenericArguments.Add(aType);
            bType.BaseType = bBaseType;

            module.Types.Add(aType);
            aType.Module = module;

            module.Types.Add(bType);
            bType.Module = module;

            return assembly;
        }
    public static MethodReference MakeHostInstanceGeneric(this MethodReference @this, params TypeReference[] genericArguments)
    {
        var genericDeclaringType = new GenericInstanceType(@this.DeclaringType);
        foreach (var genericArgument in genericArguments)
        {
            genericDeclaringType.GenericArguments.Add(genericArgument);
        }

        var reference = new MethodReference(@this.Name, @this.ReturnType, genericDeclaringType)
        {
            HasThis = @this.HasThis,
            ExplicitThis = @this.ExplicitThis,
            CallingConvention = @this.CallingConvention
        };

        foreach (var parameter in @this.Parameters)
        {
            reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
        }

        foreach (var genericParam in @this.GenericParameters)
        {
            reference.GenericParameters.Add(new GenericParameter(genericParam.Name, reference));
        }

        return reference;
    }
Ejemplo n.º 3
0
        private static void EmitArchsInit(MethodBody body, FieldReference archRef, Action<Instruction> emit)
        {
            var module = body.Method.Module;
              GenericInstanceType dictStrStrRef = (GenericInstanceType)archRef.FieldType;
              TypeReference dictOpenRef = dictStrStrRef.ElementType;
              GenericInstanceType iEqCompStrRef = new GenericInstanceType(module.Import(typeof(IEqualityComparer<>)));
              iEqCompStrRef.GenericArguments.Add(dictOpenRef.GenericParameters[0]);
              MethodReference dictStrStrCtor = CecilUtils.ImportInstanceMethodRef(module, dictStrStrRef, ".ctor", null, iEqCompStrRef);
              MethodReference dictAddRef = CecilUtils.ImportInstanceMethodRef(module, dictStrStrRef, "Add", null, dictOpenRef.GenericParameters[0], dictOpenRef.GenericParameters[1]);

            // Variables
              body.Variables.Add(new VariableDefinition(dictStrStrRef));
              int varIdx = body.Variables.Count - 1;
            Instruction varSt = CecilUtils.ShortestStloc(varIdx);
            Instruction varLd = CecilUtils.ShortestLdloc(varIdx);

            emit(Instruction.Create(OpCodes.Ldnull));
            emit(Instruction.Create(OpCodes.Newobj, dictStrStrCtor));
              emit(varSt.Clone());
              emit(varLd.Clone());
              emit(Instruction.Create(OpCodes.Stsfld, archRef));
              Action<string, string> emitAddPair = (k, v) =>
              {
              emit(varLd.Clone());
                emit(Instruction.Create(OpCodes.Ldstr, k));
                emit(Instruction.Create(OpCodes.Ldstr, v));
            emit(Instruction.Create(OpCodes.Callvirt, dictAddRef));
              };
              emitAddPair("x86", "Win32");
              emitAddPair("AMD64", "x64");
              emitAddPair("IA64", "Itanium");
              emitAddPair("ARM", "WinCE");
        }
 private TypeReference ResolveGenericParameters(TypeReference typeReference)
 {
     if (typeReference.IsGenericParameter)
     {
         GenericParameter parameter = (GenericParameter) typeReference;
         return Enumerable.ElementAt<TypeReference>(this.GenericArguments, parameter.Position);
     }
     if (typeReference.IsGenericInstance)
     {
         GenericInstanceType type = (GenericInstanceType) typeReference;
         GenericInstanceType type2 = new GenericInstanceType(this.ResolveGenericParameters(type.ElementType));
         foreach (TypeReference reference2 in type.GenericArguments)
         {
             type2.GenericArguments.Add(this.ResolveGenericParameters(reference2));
         }
         return type2;
     }
     if (typeReference.IsArray)
     {
         ArrayType type3 = (ArrayType) typeReference;
         return new ArrayType(this.ResolveGenericParameters(type3.ElementType), type3.Rank);
     }
     if (typeReference.IsPointer)
     {
         return new PointerType(this.ResolveGenericParameters(((PointerType) typeReference).ElementType));
     }
     if (typeReference.IsByReference)
     {
         return new ByReferenceType(this.ResolveGenericParameters(((ByReferenceType) typeReference).ElementType));
     }
     return typeReference;
 }
		static bool CheckGenericArgument (GenericInstanceType git)
		{
			if ((git == null) || !git.HasGenericArguments)
				return false; // should not happen with the '`1' but...

			TypeReference arg = git.GenericArguments [0];
			switch (arg.MetadataType) {
			case MetadataType.MVar:
				return (arg.IsGenericParameter && arg.IsNamed (String.Empty, "T"));
			case MetadataType.ValueType:
				return arg.IsNamed ("System", "Decimal");
			case MetadataType.Boolean:
			case MetadataType.Byte:
			case MetadataType.Char:
			case MetadataType.Double:
			case MetadataType.Single:
			case MetadataType.Int16:
			case MetadataType.Int32:
			case MetadataType.Int64:
			case MetadataType.SByte:
			case MetadataType.UInt16:
			case MetadataType.UInt32:
			case MetadataType.UInt64:
				return true;
			default:
				return false;
			}
		}
Ejemplo n.º 6
0
 public WeakEventWeaver(FieldReference eventDelegate, ModuleImporter moduleimporter)
 {
     _eventDelegate = eventDelegate.Resolve();
     _moduleimporter = moduleimporter;
     _closedGenericEventHandler = moduleimporter.GetClosedEventHandlerT(eventDelegate.FieldType.GetEventArgsType());
     _isGenericHandler = _closedGenericEventHandler.FullName.Equals(eventDelegate.FieldType.FullName);
 }
Ejemplo n.º 7
0
        public TypeReference ResolveConstituentType(TypeReference sourceType)
        {
            if (sourceType == null) throw new ArgumentNullException("sourceType");

              sourceType = Import(sourceType);

              if (sourceType is GenericParameter) {
            return _map[sourceType.Name];
              }

              {
            var sourceTypeAsGenericInstance = sourceType as GenericInstanceType;
            if (sourceTypeAsGenericInstance != null) {
              var targetType = new GenericInstanceType(sourceTypeAsGenericInstance.ElementType);
              foreach (TypeReference sourceArgument in sourceTypeAsGenericInstance.GenericArguments) {
            var targetArgument = ResolveConstituentType(sourceArgument);
            targetType.GenericArguments.Add(targetArgument);
              }
              return targetType;
            }
              }

              {
            var sourceTypeAsArray = sourceType as ArrayType;
            if (sourceTypeAsArray != null) {
              return new ArrayType(ResolveConstituentType(sourceTypeAsArray.ElementType));
            }
              }

              {
            var sourceTypeAsReference = sourceType as ByReferenceType;
            if (sourceTypeAsReference != null) {
              return new ByReferenceType(ResolveConstituentType(sourceTypeAsReference.ElementType));
            }
              }

              {
            var sourceTypeAsOptional = sourceType as OptionalModifierType;
            if (sourceTypeAsOptional != null) {
              return new OptionalModifierType(ResolveConstituentType(sourceTypeAsOptional.ElementType), ResolveConstituentType(sourceTypeAsOptional.ModifierType));
            }
              }

              {
            var sourceTypeAsRequired = sourceType as RequiredModifierType;
            if (sourceTypeAsRequired != null) {
              return new RequiredModifierType(ResolveConstituentType(sourceTypeAsRequired.ElementType), ResolveConstituentType(sourceTypeAsRequired.ModifierType));
            }
              }

              // TODO:
              //FunctionPointerType?
              //SentinelType??

              // PinnedType is never used as a parameter (TODO: or is it?)
              // PointerType never has a generic element type

              return sourceType;
        }
Ejemplo n.º 8
0
 public static int RecursiveGenericDepthFor(GenericInstanceType type)
 {
     if (type == null)
     {
         return 0;
     }
     return RecursiveGenericDepthFor(type, !type.HasGenericArguments ? 0 : 1);
 }
    private static void AddICollectionTProxy(ModuleDefinition moduleDefinition, TypeDefinition type, GenericInstanceType collectionT)
    {
        var itemType = collectionT.GenericArguments[0];
        var itemArray = itemType.MakeArrayType();

        var proxyType = CreateProxy(moduleDefinition, type);
        TypeReference proxyTypeRef = proxyType;
        if (type.HasGenericParameters)
            proxyTypeRef = proxyType.MakeGenericInstanceType(type.GenericParameters.Select(gp => new GenericParameter(gp.Position, gp.Type, gp.Module)).ToArray());

        var field = proxyType.Fields[0];
        var fieldRef = new FieldReference(field.Name, field.FieldType, proxyTypeRef);

        var countProperty = type.Properties.First(p => p.Name == "Count" || p.Name == "System.Collections.ICollection.Count");
        MethodReference countMethod = countProperty.GetMethod;
        MethodReference copyToMethod = type.Methods.First(p => p.Name == "CopyTo" || p.Name == "System.Collections.ICollection.CopyTo");

        if (type.HasGenericParameters)
        {
            countMethod = countMethod.MakeHostInstanceGeneric(type.GenericParameters.Select(gp => new GenericParameter(gp.Position, gp.Type, gp.Module)).ToArray());
            copyToMethod = copyToMethod.MakeHostInstanceGeneric(type.GenericParameters.Select(gp => new GenericParameter(gp.Position, gp.Type, gp.Module)).ToArray());
        }

        var getMethod = new MethodDefinition("get_Items", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, itemArray);
        var getMethodBody = getMethod.Body;

        var localItems = new VariableDefinition("items", itemArray);
        getMethodBody.Variables.Add(localItems);

        getMethodBody.SimplifyMacros();
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldfld, fieldRef));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Callvirt, countMethod));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Newarr, itemType));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Stloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldfld, fieldRef));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldlen));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Conv_I4));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Callvirt, copyToMethod));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ret));
        getMethodBody.InitLocals = true;
        getMethodBody.OptimizeMacros();

        proxyType.Methods.Add(getMethod);

        var property = new PropertyDefinition("Items", PropertyAttributes.None, itemArray);
        property.GetMethod = getMethod;
        var debuggerBrowsableAttribute = new CustomAttribute(ReferenceFinder.DebuggerBrowsableAttributeCtor);
        debuggerBrowsableAttribute.ConstructorArguments.Add(new CustomAttributeArgument(ReferenceFinder.DebuggerBrowsableStateType, DebuggerBrowsableState.RootHidden));
        property.CustomAttributes.Add(debuggerBrowsableAttribute);
        proxyType.Properties.Add(property);

        AddDebuggerTypeProxyAttribute(type, proxyType);
    }
Ejemplo n.º 10
0
        private AnalysisNet.Types.IType ExtractType(Cecil.GenericInstanceType typeref)
        {
            AnalysisNet.Types.BasicType genericTyperef = (AnalysisNet.Types.BasicType)ExtractType(typeref.ElementType);
            AnalysisNet.Types.IType[]   arguments      = typeref.GenericArguments.Select(argumentref => ExtractType(argumentref)).ToArray();
            AnalysisNet.Types.BasicType instancedType  = AnalysisNet.Extensions.Instantiate(genericTyperef, arguments);
            instancedType.Resolve(host);

            return(instancedType);
        }
Ejemplo n.º 11
0
 private static int RecursiveGenericDepthFor(GenericInstanceType type, int depth)
 {
     int maximumDepth = 0;
     foreach (TypeReference reference in type.GenericArguments)
     {
         maximumDepth = MaximumDepthFor(depth, reference, maximumDepth);
     }
     return (depth + maximumDepth);
 }
Ejemplo n.º 12
0
 private static GenericInstanceType ConstructGenericType(GenericContext context, TypeDefinition typeDefinition, IEnumerable<TypeReference> genericArguments)
 {
     GenericInstanceType type = new GenericInstanceType(typeDefinition);
     foreach (TypeReference reference in genericArguments)
     {
         type.GenericArguments.Add(InflateType(context, reference));
     }
     return type;
 }
Ejemplo n.º 13
0
 public MemberResolver(TypeReference target, ModuleDefinition targetModule = null)
 {
     if (target == null) throw new ArgumentNullException("target");
       Target = target;
       Module = targetModule ?? Target.Module;
       Source = Target.Resolve();
       TargetWithArguments = Target as GenericInstanceType;
       _map = new GenericParametersMap(Source, TargetWithArguments);
 }
Ejemplo n.º 14
0
 private static GenericInstanceType GetGenericInstanceType(TypeDefinition type, Collection<GenericParameter> parameters)
 {
     var genericInstanceType = new GenericInstanceType(type);
     foreach (var genericParameter in parameters)
     {
         genericInstanceType.GenericArguments.Add(genericParameter);
     }
     return genericInstanceType;
 }
Ejemplo n.º 15
0
		private static GenericInstanceType NewGenericInstanceTypeWithArgumentsFrom(TypeReference referenceType, GenericInstanceType argumentSource)
		{
			GenericInstanceType replacementTypeReference = new GenericInstanceType(referenceType);
			foreach (TypeReference argument in argumentSource.GenericArguments)
			{
				replacementTypeReference.GenericArguments.Add(argument);
			}
			return replacementTypeReference;
		}
Ejemplo n.º 16
0
 public static MethodReference AsMethodOfGenericTypeInstance(this MethodDefinition methodDef, GenericInstanceType genericInstanceType)
 {
     if (!genericInstanceType.ElementType.IsEqualTo(methodDef.DeclaringType)) {
         throw new ArgumentException("The generic instance type doesn't match the method's declaring type.", "genericInstanceType");
     }
     var methodRef = methodDef.Clone();
     methodRef.DeclaringType = genericInstanceType;
     return methodRef;
 }
Ejemplo n.º 17
0
 private static TypeReference GenericReferenceFor(TypeReference type)
 {
     var instance = new GenericInstanceType(type);
     foreach (var param in type.GenericParameters)
     {
         instance.GenericArguments.Add(param);
     }
     return instance;
 }
        public bool CreateNewObjectMethod(AssemblyDefinition assembly, 
                                        MethodDefinition templateMethod, 
                                        IAssemblyTracker tracker, 
                                        INewTransformerInfoWrapper infoWrapper)
        {
            MethodDefinition factoryMethod = null;
              if ((factoryMethod = infoWrapper.GetFactoryMethod (templateMethod, assembly, tracker)) != null)
              {
            if (factoryMethod.GenericParameters.Count != 1 || factoryMethod.Parameters.Count != 1 || !factoryMethod.IsStatic)
              throw new ArgumentException ("Factory method to create object does not have correct signature [public static T Create<T> (ParamList)]");

            TypeReference returnType = templateMethod.DeclaringType;
            if (templateMethod.DeclaringType.HasGenericParameters)
            {
              returnType = new GenericInstanceType (templateMethod.DeclaringType);
              foreach (var a in templateMethod.DeclaringType.GenericParameters.ToArray ())
              {
            returnType.GenericParameters.Add (a);
            ((GenericInstanceType) returnType).GenericArguments.Add (a);
              }
            }

            var importedFactoryMethod = templateMethod.Module.Import (factoryMethod);
            var genericInstanceMethod = new GenericInstanceMethod (importedFactoryMethod);
            genericInstanceMethod.GenericArguments.Add (templateMethod.DeclaringType);

            var paramlistDef = factoryMethod.Parameters[0].ParameterType.Resolve ();
            var importedParamListCreateMethod = templateMethod.Module.Import (SearchParamListFactoryMethod (paramlistDef, templateMethod));

            if (importedParamListCreateMethod == null)
              throw new ArgumentException ("Factory method: no corresponding 'create' method could have been found. [argument count]");

            var newObjectMethod = new MethodDefinition (
                                                    infoWrapper.GetWrapperMethodName (templateMethod),
                                                    MethodAttributes.Public | MethodAttributes.Static, returnType
                                                    );
            var instructions = newObjectMethod.Body.Instructions;

            foreach (var param in templateMethod.Parameters)
            {
              newObjectMethod.Parameters.Add (param);
              instructions.Add (Instruction.Create (OpCodes.Ldarg, param));
            }

            instructions.Add(Instruction.Create (OpCodes.Call, importedParamListCreateMethod));
            instructions.Add(Instruction.Create (OpCodes.Call, genericInstanceMethod));

            instructions.Add (Instruction.Create (OpCodes.Ret));
            newObjectMethod.Body.OptimizeMacros ();

            newObjectMethod.IsHideBySig = true;
            templateMethod.DeclaringType.Methods.Add (newObjectMethod);
            return true;
              }
              return false;
        }
Ejemplo n.º 19
0
 public static TypeReference GetGenericInstantiationIfGeneric(this TypeReference definition)
 {
     if (!definition.HasGenericParameters) return definition;
     var instType = new GenericInstanceType(definition);
     foreach (var parameter in definition.GenericParameters)
     {
         instType.GenericArguments.Add(parameter);
     }
     return instType;
 }
Ejemplo n.º 20
0
        public static TypeReference MakeGenericType(this TypeReference self, params TypeReference[] arguments)
        {
            if (self.GenericParameters.Count != arguments.Length)
                throw new ArgumentException();

            var instance = new GenericInstanceType(self);
            foreach (var argument in arguments)
                instance.GenericArguments.Add(argument);

            return instance;
        }
Ejemplo n.º 21
0
        public static MethodReference Bind(this MethodReference method, GenericInstanceType genericType)
        {
            var reference = new MethodReference(method.Name, method.ReturnType, genericType);
            reference.HasThis = method.HasThis;
            reference.ExplicitThis = method.ExplicitThis;
            reference.CallingConvention = method.CallingConvention;

            foreach (var parameter in method.Parameters)
                reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));

            return reference;
        }
Ejemplo n.º 22
0
 public static bool IsEqualTo(this GenericInstanceType a, GenericInstanceType b)
 {
     if (a.GenericArguments.Count != b.GenericArguments.Count) {
         return false;
     }
     for (int i = 0; i < a.GenericArguments.Count; i++) {
         if (!IsEqualTo(a.GenericArguments[i], b.GenericArguments[i])) {
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 23
0
        /*
        public static MethodReference BindDefinition(this MethodReference method, TypeReference genericTypeDefinition)
        {
            if (!genericTypeDefinition.HasGenericParameters)
                return method;

            var genericDeclaration = new GenericInstanceType(genericTypeDefinition);
            foreach (var parameter in genericTypeDefinition.GenericParameters)
            {
                genericDeclaration.GenericArguments.Add(parameter);
            }
            var reference = new MethodReference(method.Name, method.ReturnType, genericDeclaration);
            reference.HasThis = method.HasThis;
            reference.ExplicitThis = method.ExplicitThis;
            reference.CallingConvention = method.CallingConvention;

            foreach (var parameter in method.Parameters)
                reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));

            return reference;
        }
        */
        public static FieldReference BindDefinition(this FieldReference field, TypeReference genericTypeDefinition)
        {
            if (!genericTypeDefinition.HasGenericParameters)
                return field;

            var genericDeclaration = new GenericInstanceType(genericTypeDefinition);
            foreach (var parameter in genericTypeDefinition.GenericParameters)
            {
                genericDeclaration.GenericArguments.Add(parameter);
            }
            var reference = new FieldReference(field.Name, field.FieldType, genericDeclaration);
            return reference;
        }
Ejemplo n.º 24
0
        public void GenericInstanceEquality () {
            var git1 = new GenericInstanceType(T1);
            var git1_2 = new GenericInstanceType(T1_2);
            var git2 = new GenericInstanceType(T2);

            // FIXME: Is this correct?
            Assert.IsFalse(TypeUtil.TypesAreEqual(git1, T1, true));
            Assert.IsTrue(TypeUtil.TypesAreEqual(git1, T1, false));

            Assert.IsTrue(TypeUtil.TypesAreEqual(git1, git1));
            Assert.IsTrue(TypeUtil.TypesAreEqual(git1, git1_2));
            Assert.IsFalse(TypeUtil.TypesAreEqual(git1, git2));
        }
Ejemplo n.º 25
0
 public static TypeReference MakeGenericType(TypeReference self, params TypeReference[] arguments)
 {
     if (self.GenericParameters.Count != arguments.Length)
     {
         throw new ArgumentException();
     }
     GenericInstanceType type = new GenericInstanceType(self);
     foreach (TypeReference reference in arguments)
     {
         type.GenericArguments.Add(reference);
     }
     return type;
 }
 internal static void ProcessGenericType(GenericInstanceType type, InflatedCollectionCollector generics, GenericInstanceMethod contextMethod, CollectionMode mode)
 {
     bool flag = generics.TypeDeclarations.Add(type);
     if (((mode != CollectionMode.Types) || flag) && ((mode != CollectionMode.MethodsAndTypes) || generics.TypeMethodDeclarations.Add(type)))
     {
         GenericContext genericContext = new GenericContext(type, contextMethod);
         Unity.Cecil.Visitor.Extensions.Accept(type.ElementType.Resolve(), new GenericContextAwareDeclarationOnlyVisitor(generics, genericContext, CollectionMode.Types));
         foreach (GenericInstanceType type2 in Enumerable.OfType<GenericInstanceType>(type.GenericArguments))
         {
             ProcessGenericType(Inflater.InflateType(genericContext, type2), generics, null, mode);
         }
     }
 }
Ejemplo n.º 27
0
    public static FieldReference GetGeneric(this FieldDefinition definition)
    {
        if (definition.DeclaringType.HasGenericParameters)
        {
            var declaringType = new GenericInstanceType(definition.DeclaringType);
            foreach (var parameter in definition.DeclaringType.GenericParameters)
            {
                declaringType.GenericArguments.Add(parameter);
            }
            return new FieldReference(definition.Name, definition.FieldType, declaringType);
        }

        return definition;
    }
Ejemplo n.º 28
0
        public Either<MemberReference, PropertyReferenceContainer> Convert(IAstReference astReference, ModuleDefinition module, IReferenceProvider recursive)
        {
            var generic = astReference as AstGenericTypeWithArguments;
            if (generic == null)
                return null;

            var primary = recursive.Convert(generic.PrimaryType, module, recursive).As<TypeReference>();
            var arguments = generic.TypeArguments.Select(a => recursive.Convert(a, module, recursive).As<TypeReference>());

            var result = new GenericInstanceType(primary);
            arguments.ForEach(result.GenericArguments.Add);

            return result;
        }
Ejemplo n.º 29
0
        public static TypeReference GetGeneric(this TypeDefinition definition)
        {
            if (definition.HasGenericParameters)
            {
                var genericInstanceType = new GenericInstanceType(definition);
                foreach (var parameter in definition.GenericParameters)
                {
                    genericInstanceType.GenericArguments.Add(parameter);
                }
                return genericInstanceType;
            }

            return definition;
        }
Ejemplo n.º 30
0
		void PrepareImports ()
		{
			if (imported)
				return;

			var corlib = Context.GetAssembly ("mscorlib");

			void_type = Import (corlib, "System.Void");

			var monomac = Context.GetAssembly ("MonoMac");

			var dictionary = Import (corlib, "System.Collections.Generic.Dictionary`2");

			var intptr = Import (corlib, "System.IntPtr");
			var method_desc = Import (monomac, "MonoMac.ObjCRuntime.MethodDescription");

			var dic_i_md = new GenericInstanceType (dictionary);
			dic_i_md.GenericArguments.Add (intptr);
			dic_i_md.GenericArguments.Add (method_desc);
			dictionary_intptr_methoddesc = dic_i_md;

			dictionary_intptr_methoddesc_ctor = Import (".ctor", dic_i_md, false, void_type, Import (corlib, "System.Int32"));

			dictionary_intptr_methoddesc_set_item = Import ("set_Item", dic_i_md, false, void_type,
				dictionary.GenericParameters [0],
				dictionary.GenericParameters [1]);

			methoddesc_ctor = Import (".ctor", method_desc, false, void_type,
				Import (corlib, "System.Reflection.MethodBase"),
				Import (monomac, "MonoMac.ObjCRuntime.ArgumentSemantic"));

			var selector = Import (monomac, "MonoMac.ObjCRuntime.Selector");

			selector_get_handle = Import ("GetHandle", selector, true, intptr, Import (corlib, "System.String"));
			selector_init = new FieldReference ("Init", selector, intptr);

			var methodbase = Import (corlib, "System.Reflection.MethodBase");

			methodbase_get_method_from_handle = Import ("GetMethodFromHandle", methodbase, true, methodbase, Import (corlib, "System.RuntimeMethodHandle"));

			var type = Import (corlib, "System.Type");

			type_get_type_from_handle = Import ("GetTypeFromHandle", type, true, type, Import (corlib, "System.RuntimeTypeHandle"));

			var @class = Import (monomac, "MonoMac.ObjCRuntime.Class");

			class_register_methods = Import ("RegisterMethods", @class, true, void_type, type, dic_i_md);

			imported = true;
		}
Ejemplo n.º 31
0
        public static TypeReference MakeGenericIfRequired(this TypeReference typeReference)
        {
            if (typeReference.HasGenericParameters)
            {
                var genericDeclaringType = new GenericInstanceType(typeReference);
                foreach (var genericParameter in typeReference.GenericParameters)
                {
                    genericDeclaringType.GenericArguments.Add(genericParameter);
                }

                typeReference = genericDeclaringType;
            }

            return typeReference;
        }
Ejemplo n.º 32
0
        private TypeReference ReadTypeSignature(ElementType etype)
        {
            ElementType type3 = etype;

            switch (type3)
            {
            case ElementType.Void:
                return(this.TypeSystem.Void);

            case ElementType.Boolean:
            case ElementType.Char:
            case ElementType.I1:
            case ElementType.U1:
            case ElementType.I2:
            case ElementType.U2:
            case ElementType.I4:
            case ElementType.U4:
            case ElementType.I8:
            case ElementType.U8:
            case ElementType.R4:
            case ElementType.R8:
            case ElementType.String:
            case (ElementType.Array | ElementType.Boolean | ElementType.Void):
            case (ElementType.Boolean | ElementType.ByRef | ElementType.I4):
                break;

            case ElementType.Ptr:
                return(new PointerType(this.ReadTypeSignature()));

            case ElementType.ByRef:
                return(new ByReferenceType(this.ReadTypeSignature()));

            case ElementType.ValueType:
            {
                TypeReference typeDefOrRef = this.GetTypeDefOrRef(this.ReadTypeTokenSignature());
                typeDefOrRef.IsValueType = true;
                return(typeDefOrRef);
            }

            case ElementType.Class:
                return(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()));

            case ElementType.Var:
                return(this.GetGenericParameter(GenericParameterType.Type, base.ReadCompressedUInt32()));

            case ElementType.Array:
                return(this.ReadArrayTypeSignature());

            case ElementType.GenericInst:
            {
                bool                flag         = base.ReadByte() == 0x11;
                TypeReference       typeDefOrRef = this.GetTypeDefOrRef(this.ReadTypeTokenSignature());
                GenericInstanceType instance     = new GenericInstanceType(typeDefOrRef);
                this.ReadGenericInstanceSignature(typeDefOrRef, instance);
                if (flag)
                {
                    instance.IsValueType = true;
                    typeDefOrRef.GetElementType().IsValueType = true;
                }
                return(instance);
            }

            case ElementType.TypedByRef:
                return(this.TypeSystem.TypedReference);

            case ElementType.I:
                return(this.TypeSystem.IntPtr);

            case ElementType.U:
                return(this.TypeSystem.UIntPtr);

            case ElementType.FnPtr:
            {
                FunctionPointerType method = new FunctionPointerType();
                this.ReadMethodSignature(method);
                return(method);
            }

            case ElementType.Object:
                return(this.TypeSystem.Object);

            case ElementType.SzArray:
                return(new ArrayType(this.ReadTypeSignature()));

            case ElementType.MVar:
                return(this.GetGenericParameter(GenericParameterType.Method, base.ReadCompressedUInt32()));

            case ElementType.CModReqD:
                return(new RequiredModifierType(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()), this.ReadTypeSignature()));

            case ElementType.CModOpt:
                return(new OptionalModifierType(this.GetTypeDefOrRef(this.ReadTypeTokenSignature()), this.ReadTypeSignature()));

            default:
                if (type3 == ElementType.Sentinel)
                {
                    return(new SentinelType(this.ReadTypeSignature()));
                }
                if (type3 != ElementType.Pinned)
                {
                    break;
                }
                return(new PinnedType(this.ReadTypeSignature()));
            }
            return(this.GetPrimitiveType(etype));
        }
Ejemplo n.º 33
0
        /*
         *      // Check if 'type' has some decorations applied to it
         *              if (type is Mono.Cecil.TypeSpecification) {
         *                      // Go through all levels of 'indirection', 'array dimensions'
         *                      // and 'generic types' - in the end, we should get the actual
         *                      // type of the ReturnType (but all data about its array
         *                      // dimensions, levels of indirection and even its generic
         *                      // parameters is correctly stored within ArrayCount and
         *                      // ArrayDimensions, PointerNestingLevel and GenericArguments
         *                      // respectively).
         *                      if (type is ArrayType) {
         *                              // This return type is obviously an array - add the rank
         *                              ArrayType at = (ArrayType) type;
         *                              if (arrays == null)
         *                                      arrays = new Stack<int>();
         *                              arrays.Push(at.Rank);
         *                              type = at.ElementType;
         *                      } else else if (type is Mono.Cecil.ReferenceType) {
         *                              Mono.Cecil.ReferenceType rt = (Mono.Cecil.ReferenceType) type;
         *                              byRef = true;
         *                              type = rt.ElementType;
         *                      } else if (type is PointerType) {
         *                              // The type is a pointer
         *                              PointerType pt = (PointerType) type;
         ++pointerNestingLevel;
         *                              type = pt.ElementType;
         *                              // Go down one level
         *                      } else {
         *                              // TODO: Check if we loose some relevant info here
         *                              type = ((TypeSpecification)type).ElementType;
         *                      }*/
        public static DomReturnType GetReturnType(TypeReference typeReference)
        {
            if (typeReference == null)
            {
                return(new DomReturnType(DomReturnType.Void.ToInvariantString()));
            }

            if (typeReference is Mono.Cecil.GenericInstanceType)
            {
                Mono.Cecil.GenericInstanceType genType = (Mono.Cecil.GenericInstanceType)typeReference;
                DomReturnType result = GetReturnType(genType.ElementType);

                foreach (TypeReference typeRef in genType.GenericArguments)
                {
                    DomReturnType param = GetReturnType(typeRef);

                    foreach (IReturnTypePart part in result.Parts)
                    {
                        if (part.Tag is TypeDefinition)
                        {
                            TypeDefinition typeDef = (TypeDefinition)part.Tag;
                            foreach (TypeReference typeParam in typeDef.GenericParameters)
                            {
                                if (typeParam.Name == param.Name)
                                {
                                    part.AddTypeParameter(param);
                                    goto skip;
                                }
                            }
                        }
                    }
                    result.AddTypeParameter(param);
                    skip :;
                }
                return(result);
            }

            if (typeReference is Mono.Cecil.ArrayType)
            {
                Mono.Cecil.ArrayType arrType = (Mono.Cecil.ArrayType)typeReference;
                DomReturnType        result  = GetReturnType(arrType.ElementType);
                result.ArrayDimensions++;
                result.SetDimension(result.ArrayDimensions - 1, arrType.Rank - 1);
                return(result);
            }

            if (typeReference is Mono.Cecil.PointerType)
            {
                Mono.Cecil.PointerType ptrType = (Mono.Cecil.PointerType)typeReference;
                DomReturnType          result  = GetReturnType(ptrType.ElementType);
                if (result.ArrayDimensions > 0)
                {
                    result.ArrayPointerNestingLevel++;
                }
                else
                {
                    result.PointerNestingLevel++;
                }
                return(result);
            }
            if (typeReference is Mono.Cecil.ByReferenceType)
            {
                return(GetReturnType(((Mono.Cecil.ByReferenceType)typeReference).ElementType));
            }

            if (typeReference is Mono.Cecil.TypeDefinition)
            {
                Mono.Cecil.TypeDefinition typeDefinition = (Mono.Cecil.TypeDefinition)typeReference;
                DomReturnType             result;
                if (typeDefinition.DeclaringType != null)
                {
                    result = GetReturnType(typeDefinition.DeclaringType);
                    result.Parts.Add(new ReturnTypePart(typeDefinition.Name));
                    result.Tag = typeDefinition;
                }
                else
                {
                    result           = new DomReturnType(typeDefinition.Name);
                    result.Namespace = typeDefinition.Namespace;
                    result.Tag       = typeDefinition;
                }
                return(result);
            }

            return(new DomReturnType(DomCecilType.RemoveGenericParamSuffix(typeReference.FullName)));
        }
Ejemplo n.º 34
0
        private TypeReference ImportTypeSpecification(TypeReference type, ImportGenericContext context)
        {
            switch (type.etype)
            {
            case ElementType.SzArray:
            {
                ArrayType arrayType = (ArrayType)type;
                return(new ArrayType(ImportType(arrayType.ElementType, context)));
            }

            case ElementType.Ptr:
            {
                PointerType pointerType = (PointerType)type;
                return(new PointerType(ImportType(pointerType.ElementType, context)));
            }

            case ElementType.ByRef:
            {
                ByReferenceType byReferenceType = (ByReferenceType)type;
                return(new ByReferenceType(ImportType(byReferenceType.ElementType, context)));
            }

            case ElementType.Pinned:
            {
                PinnedType pinnedType = (PinnedType)type;
                return(new PinnedType(ImportType(pinnedType.ElementType, context)));
            }

            case ElementType.Sentinel:
            {
                SentinelType sentinelType = (SentinelType)type;
                return(new SentinelType(ImportType(sentinelType.ElementType, context)));
            }

            case ElementType.FnPtr:
            {
                FunctionPointerType functionPointerType  = (FunctionPointerType)type;
                FunctionPointerType functionPointerType2 = new FunctionPointerType
                {
                    HasThis           = functionPointerType.HasThis,
                    ExplicitThis      = functionPointerType.ExplicitThis,
                    CallingConvention = functionPointerType.CallingConvention,
                    ReturnType        = ImportType(functionPointerType.ReturnType, context)
                };
                if (!functionPointerType.HasParameters)
                {
                    return(functionPointerType2);
                }
                for (int j = 0; j < functionPointerType.Parameters.Count; j++)
                {
                    functionPointerType2.Parameters.Add(new ParameterDefinition(ImportType(functionPointerType.Parameters[j].ParameterType, context)));
                }
                return(functionPointerType2);
            }

            case ElementType.CModOpt:
            {
                OptionalModifierType optionalModifierType = (OptionalModifierType)type;
                return(new OptionalModifierType(ImportType(optionalModifierType.ModifierType, context), ImportType(optionalModifierType.ElementType, context)));
            }

            case ElementType.CModReqD:
            {
                RequiredModifierType requiredModifierType = (RequiredModifierType)type;
                return(new RequiredModifierType(ImportType(requiredModifierType.ModifierType, context), ImportType(requiredModifierType.ElementType, context)));
            }

            case ElementType.Array:
            {
                ArrayType arrayType2 = (ArrayType)type;
                ArrayType arrayType3 = new ArrayType(ImportType(arrayType2.ElementType, context));
                if (arrayType2.IsVector)
                {
                    return(arrayType3);
                }
                Collection <ArrayDimension> dimensions  = arrayType2.Dimensions;
                Collection <ArrayDimension> dimensions2 = arrayType3.Dimensions;
                dimensions2.Clear();
                for (int k = 0; k < dimensions.Count; k++)
                {
                    ArrayDimension arrayDimension = dimensions[k];
                    dimensions2.Add(new ArrayDimension(arrayDimension.LowerBound, arrayDimension.UpperBound));
                }
                return(arrayType3);
            }

            case ElementType.GenericInst:
            {
                GenericInstanceType        genericInstanceType  = (GenericInstanceType)type;
                GenericInstanceType        genericInstanceType2 = new GenericInstanceType(ImportType(genericInstanceType.ElementType, context));
                Collection <TypeReference> genericArguments     = genericInstanceType.GenericArguments;
                Collection <TypeReference> genericArguments2    = genericInstanceType2.GenericArguments;
                for (int i = 0; i < genericArguments.Count; i++)
                {
                    genericArguments2.Add(ImportType(genericArguments[i], context));
                }
                return(genericInstanceType2);
            }

            case ElementType.Var:
            {
                GenericParameter genericParameter2 = (GenericParameter)type;
                if (genericParameter2.DeclaringType == null)
                {
                    throw new InvalidOperationException();
                }
                return(context.TypeParameter(genericParameter2.DeclaringType.FullName, genericParameter2.Position));
            }

            case ElementType.MVar:
            {
                GenericParameter genericParameter = (GenericParameter)type;
                if (genericParameter.DeclaringMethod == null)
                {
                    throw new InvalidOperationException();
                }
                return(context.MethodParameter(context.NormalizeMethodName(genericParameter.DeclaringMethod), genericParameter.Position));
            }

            default:
                throw new NotSupportedException(type.etype.ToString());
            }
        }
Ejemplo n.º 35
0
        private Cecil.TypeReference TypeReference(AnalysisNet.Types.IBasicType basicType)
        {
            if (typesCache.TryGetValue(basicType, out Cecil.TypeReference cecilTypeReference))
            {
                return(cecilTypeReference);
            }

            Cecil.TypeReference platformType = TypeReferenceToPlatformType(basicType);
            if (platformType != null)
            {
                typesCache[basicType] = platformType;
                return(platformType);
            }

            string nmspace = basicType.ContainingNamespace;
            string name    = basicType.MetadataName();

            Cecil.ModuleDefinition module = ResolveModule(basicType);
            Cecil.IMetadataScope   scope  = module ?? ResolveScope(basicType);
            if (module == null && scope == null)
            {
                throw new NotImplementedException();
            }

            cecilTypeReference = new Cecil.TypeReference(nmspace, name, module, scope);
            if (basicType.TypeKind == AnalysisNet.Types.TypeKind.ValueType)
            {
                cecilTypeReference.IsValueType = true;
            }

            if (basicType.ContainingType != null)
            {
                cecilTypeReference.DeclaringType = TypeReference(basicType.ContainingType);
                cecilTypeReference.Namespace     = string.Empty;
            }

            if (basicType.GenericParameterCount > 0)
            {
                Cecil.GenericInstanceType instantiated = null;
                // should we add constraints?
                cecilTypeReference.CreateGenericParameters(basicType.GenericParameterCount);
                MapGenericParameters(cecilTypeReference, basicType);
                // call it before instantiating it
                cecilTypeReference = ImportTypeReference(cecilTypeReference);

                if (basicType.GenericArguments.Count == 0)
                {
                    instantiated = cecilTypeReference.MakeGenericInstanceType(cecilTypeReference.GenericParameters.ToArray());
                }
                else
                {
                    Cecil.TypeReference[] arguments = basicType.GenericArguments.Select(ga => TypeReference(ga)).ToArray();
                    instantiated = cecilTypeReference.MakeGenericInstanceType(arguments);
                }

                cecilTypeReference = instantiated;
            }
            else
            {
                cecilTypeReference = ImportTypeReference(cecilTypeReference);
            }

            typesCache[basicType] = cecilTypeReference;
            return(cecilTypeReference);
        }
Ejemplo n.º 36
0
        TypeReference ImportTypeSpecification(TypeReference type, ImportGenericContext context)
        {
            switch (type.etype)
            {
            case ElementType.SzArray:
                var vector = (ArrayType)type;
                return(new ArrayType(ImportType(vector.ElementType, context)));

            case ElementType.Ptr:
                var pointer = (PointerType)type;
                return(new PointerType(ImportType(pointer.ElementType, context)));

            case ElementType.ByRef:
                var byref = (ByReferenceType)type;
                return(new ByReferenceType(ImportType(byref.ElementType, context)));

            case ElementType.Pinned:
                var pinned = (PinnedType)type;
                return(new PinnedType(ImportType(pinned.ElementType, context)));

            case ElementType.Sentinel:
                var sentinel = (SentinelType)type;
                return(new SentinelType(ImportType(sentinel.ElementType, context)));

            case ElementType.FnPtr:
                var fnptr          = (FunctionPointerType)type;
                var imported_fnptr = new FunctionPointerType()
                {
                    HasThis           = fnptr.HasThis,
                    ExplicitThis      = fnptr.ExplicitThis,
                    CallingConvention = fnptr.CallingConvention,
                    ReturnType        = ImportType(fnptr.ReturnType, context),
                };

                if (!fnptr.HasParameters)
                {
                    return(imported_fnptr);
                }

                for (int i = 0; i < fnptr.Parameters.Count; i++)
                {
                    imported_fnptr.Parameters.Add(new ParameterDefinition(
                                                      ImportType(fnptr.Parameters [i].ParameterType, context)));
                }

                return(imported_fnptr);

            case ElementType.CModOpt:
                var modopt = (OptionalModifierType)type;
                return(new OptionalModifierType(
                           ImportType(modopt.ModifierType, context),
                           ImportType(modopt.ElementType, context)));

            case ElementType.CModReqD:
                var modreq = (RequiredModifierType)type;
                return(new RequiredModifierType(
                           ImportType(modreq.ModifierType, context),
                           ImportType(modreq.ElementType, context)));

            case ElementType.Array:
                var array          = (ArrayType)type;
                var imported_array = new ArrayType(ImportType(array.ElementType, context));
                if (array.IsVector)
                {
                    return(imported_array);
                }

                var dimensions          = array.Dimensions;
                var imported_dimensions = imported_array.Dimensions;

                imported_dimensions.Clear();

                for (int i = 0; i < dimensions.Count; i++)
                {
                    var dimension = dimensions [i];

                    imported_dimensions.Add(new ArrayDimension(dimension.LowerBound, dimension.UpperBound));
                }

                return(imported_array);

            case ElementType.GenericInst:
                var instance          = (GenericInstanceType)type;
                var element_type      = ImportType(instance.ElementType, context);
                var imported_instance = new GenericInstanceType(element_type);

                var arguments          = instance.GenericArguments;
                var imported_arguments = imported_instance.GenericArguments;

                for (int i = 0; i < arguments.Count; i++)
                {
                    imported_arguments.Add(ImportType(arguments [i], context));
                }

                return(imported_instance);

            case ElementType.Var:
                var var_parameter = (GenericParameter)type;
                if (var_parameter.DeclaringType == null)
                {
                    throw new InvalidOperationException();
                }
                return(context.TypeParameter(var_parameter.DeclaringType.FullName, var_parameter.Position));

            case ElementType.MVar:
                var mvar_parameter = (GenericParameter)type;
                if (mvar_parameter.DeclaringMethod == null)
                {
                    throw new InvalidOperationException();
                }
                return(context.MethodParameter(mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position));
            }

            throw new NotSupportedException(type.etype.ToString());
        }
Ejemplo n.º 37
0
        private TypeReference ReadTypeSignature(ElementType etype)
        {
            switch (etype)
            {
            case ElementType.ValueType:
            {
                TypeReference typeDefOrRef2 = GetTypeDefOrRef(ReadTypeTokenSignature());
                typeDefOrRef2.KnownValueType();
                return(typeDefOrRef2);
            }

            case ElementType.Class:
                return(GetTypeDefOrRef(ReadTypeTokenSignature()));

            case ElementType.Ptr:
                return(new PointerType(ReadTypeSignature()));

            case ElementType.FnPtr:
            {
                FunctionPointerType functionPointerType = new FunctionPointerType();
                ReadMethodSignature(functionPointerType);
                return(functionPointerType);
            }

            case ElementType.ByRef:
                return(new ByReferenceType(ReadTypeSignature()));

            case ElementType.Pinned:
                return(new PinnedType(ReadTypeSignature()));

            case ElementType.SzArray:
                return(new ArrayType(ReadTypeSignature()));

            case ElementType.Array:
                return(ReadArrayTypeSignature());

            case ElementType.CModOpt:
                return(new OptionalModifierType(GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature()));

            case ElementType.CModReqD:
                return(new RequiredModifierType(GetTypeDefOrRef(ReadTypeTokenSignature()), ReadTypeSignature()));

            case ElementType.Sentinel:
                return(new SentinelType(ReadTypeSignature()));

            case ElementType.Var:
                return(GetGenericParameter(GenericParameterType.Type, base.ReadCompressedUInt32()));

            case ElementType.MVar:
                return(GetGenericParameter(GenericParameterType.Method, base.ReadCompressedUInt32()));

            case ElementType.GenericInst:
            {
                bool                num                 = base.ReadByte() == 17;
                TypeReference       typeDefOrRef        = GetTypeDefOrRef(ReadTypeTokenSignature());
                GenericInstanceType genericInstanceType = new GenericInstanceType(typeDefOrRef);
                ReadGenericInstanceSignature(typeDefOrRef, genericInstanceType);
                if (num)
                {
                    genericInstanceType.KnownValueType();
                    typeDefOrRef.GetElementType().KnownValueType();
                }
                return(genericInstanceType);
            }

            case ElementType.Object:
                return(TypeSystem.Object);

            case ElementType.Void:
                return(TypeSystem.Void);

            case ElementType.TypedByRef:
                return(TypeSystem.TypedReference);

            case ElementType.I:
                return(TypeSystem.IntPtr);

            case ElementType.U:
                return(TypeSystem.UIntPtr);

            default:
                return(GetPrimitiveType(etype));
            }
        }
        private static GenericInstanceType ResolveIfNeeded(IGenericInstance genericInstanceMethod, IGenericInstance genericInstanceType, GenericInstanceType genericInstanceType1)
        {
            if (!ContainsGenericParameters(genericInstanceType1))
            {
                return(genericInstanceType1);
            }

            var newGenericInstance = new GenericInstanceType(genericInstanceType1.ElementType);

            foreach (var genericArgument in genericInstanceType1.GenericArguments)
            {
                if (!genericArgument.IsGenericParameter)
                {
                    newGenericInstance.GenericArguments.Add(ResolveIfNeeded(genericInstanceMethod, genericInstanceType, genericArgument));
                    continue;
                }

                var genParam = (GenericParameter)genericArgument;

                switch (genParam.Type)
                {
                case GenericParameterType.Type: {
                    if (genericInstanceType == null)
                    {
                        throw new NotSupportedException();
                    }

                    newGenericInstance.GenericArguments.Add(genericInstanceType.GenericArguments[genParam.Position]);
                }
                break;

                case GenericParameterType.Method: {
                    if (genericInstanceMethod == null)
                    {
                        newGenericInstance.GenericArguments.Add(genParam);
                    }
                    else
                    {
                        newGenericInstance.GenericArguments.Add(genericInstanceMethod.GenericArguments[genParam.Position]);
                    }
                }
                break;
                }
            }

            return(newGenericInstance);
        }
Ejemplo n.º 39
0
        private TypeReference GetFixedReturnType(TypeReference type)
        {
            if (type == null)
            {
                return(null);
            }

            if (type.IsOptionalModifier)
            {
                OptionalModifierType omt          = (OptionalModifierType)type;
                TypeReference        fixedElement = GetFixedReturnType(omt.ElementType);
                return(new OptionalModifierType(omt.ModifierType, fixedElement));
            }

            if (type.IsRequiredModifier)
            {
                RequiredModifierType rmt          = (RequiredModifierType)type;
                TypeReference        fixedElement = GetFixedReturnType(rmt.ElementType);
                return(new RequiredModifierType(rmt.ModifierType, fixedElement));
            }

            if (type.IsGenericParameter)
            {
                return(GetActualType(type));
            }
            if (type.IsArray)
            {
                ArrayType     at               = (ArrayType)type;
                int           rank             = at.Rank;
                TypeReference arrayElementType = at.ElementType;
                arrayElementType = GetFixedReturnType(arrayElementType);
                return(new ArrayType(arrayElementType, rank));
            }

            if (type.IsPointer)
            {
                TypeReference fixedElement = GetFixedReturnType(((PointerType)type).ElementType);
                return(new PointerType(fixedElement));
            }

            if (type.IsByReference)
            {
                TypeReference fixedElement = GetFixedReturnType(((ByReferenceType)type).ElementType);
                return(new ByReferenceType(fixedElement));
            }


            if (type.IsGenericInstance && DeclaringType.IsGenericInstance)
            {
                GenericInstanceType result = type as GenericInstanceType;
                GenericInstanceType declaringTypeGenericInstance = DeclaringType as GenericInstanceType;
                TypeReference       declaringElementType         = DeclaringType.GetElementType();
                for (int i = 0; i < result.GenericArguments.Count; i++)
                {
                    GenericParameter currentParam = result.GenericArguments[i] as GenericParameter;
                    if (currentParam != null && currentParam.Owner == declaringElementType)
                    {
                        if (declaringTypeGenericInstance.PostionToArgument.ContainsKey(currentParam.Position))
                        {
                            result.ReplaceGenericArgumentAt(i, declaringTypeGenericInstance.PostionToArgument[currentParam.position]);
                        }
                    }
                }
                return(result);
            }

            return(type);
        }
Ejemplo n.º 40
0
        static public FieldReference Reference(this GenericInstanceType genericInstanceType, FieldReference field)
        {
            var _fieldReference = new FieldReference(field.Name, field.FieldType, genericInstanceType);

            return(_fieldReference);
        }
Ejemplo n.º 41
0
        private static TypeDefinitionTreatment GenerateRedirectionInformation(TypeDefinition type, out Collection <MethodDefinition> redirectedMethods, out Collection <KeyValuePair <InterfaceImplementation, InterfaceImplementation> > redirectedInterfaces)
        {
            bool implementsProjectedInterface = false;

            redirectedMethods    = null;
            redirectedInterfaces = null;

            foreach (var implementedInterface in type.Interfaces)
            {
                if (IsRedirectedType(implementedInterface.InterfaceType))
                {
                    implementsProjectedInterface = true;
                    break;
                }
            }

            if (!implementsProjectedInterface)
            {
                return(TypeDefinitionTreatment.NormalType);
            }

            var allImplementedInterfaces = new HashSet <TypeReference> (new TypeReferenceEqualityComparer());

            redirectedMethods    = new Collection <MethodDefinition> ();
            redirectedInterfaces = new Collection <KeyValuePair <InterfaceImplementation, InterfaceImplementation> > ();

            foreach (var @interface in type.Interfaces)
            {
                var interfaceType = @interface.InterfaceType;

                if (IsRedirectedType(interfaceType))
                {
                    allImplementedInterfaces.Add(interfaceType);
                    CollectImplementedInterfaces(interfaceType, allImplementedInterfaces);
                }
            }

            foreach (var implementedInterface in type.Interfaces)
            {
                var interfaceType = implementedInterface.InterfaceType;
                if (IsRedirectedType(implementedInterface.InterfaceType))
                {
                    var etype           = interfaceType.GetElementType();
                    var unprojectedType = new TypeReference(etype.Namespace, etype.Name, etype.Module, etype.Scope)
                    {
                        DeclaringType = etype.DeclaringType,
                        projection    = etype.projection
                    };

                    RemoveProjection(unprojectedType);

                    var genericInstanceType = interfaceType as GenericInstanceType;
                    if (genericInstanceType != null)
                    {
                        var genericUnprojectedType = new GenericInstanceType(unprojectedType);
                        foreach (var genericArgument in genericInstanceType.GenericArguments)
                        {
                            genericUnprojectedType.GenericArguments.Add(genericArgument);
                        }

                        unprojectedType = genericUnprojectedType;
                    }

                    var unprojectedInterface = new InterfaceImplementation(unprojectedType);
                    redirectedInterfaces.Add(new KeyValuePair <InterfaceImplementation, InterfaceImplementation> (implementedInterface, unprojectedInterface));
                }
            }

            // Interfaces don't inherit methods of the interfaces they implement
            if (!type.IsInterface)
            {
                foreach (var implementedInterface in allImplementedInterfaces)
                {
                    RedirectInterfaceMethods(implementedInterface, redirectedMethods);
                }
            }

            return(TypeDefinitionTreatment.RedirectImplementedMethods);
        }
Ejemplo n.º 42
0
        public void WriteTypeSignature(TypeReference type)
        {
            if (type == null)
            {
                throw new ArgumentNullException();
            }
            ElementType etype = type.etype;

            switch (etype)
            {
            case ElementType.Var:
            case ElementType.MVar:
            {
                GenericParameter obj = (GenericParameter)type;
                WriteElementType(etype);
                int position = obj.Position;
                if (position == -1)
                {
                    throw new NotSupportedException();
                }
                base.WriteCompressedUInt32((uint)position);
                break;
            }

            case ElementType.GenericInst:
            {
                GenericInstanceType genericInstanceType = (GenericInstanceType)type;
                WriteElementType(ElementType.GenericInst);
                WriteElementType(genericInstanceType.IsValueType ? ElementType.ValueType : ElementType.Class);
                base.WriteCompressedUInt32(MakeTypeDefOrRefCodedRID(genericInstanceType.ElementType));
                WriteGenericInstanceSignature(genericInstanceType);
                break;
            }

            case ElementType.Ptr:
            case ElementType.ByRef:
            case ElementType.Sentinel:
            case ElementType.Pinned:
            {
                TypeSpecification typeSpecification = (TypeSpecification)type;
                WriteElementType(etype);
                WriteTypeSignature(typeSpecification.ElementType);
                break;
            }

            case ElementType.FnPtr:
            {
                FunctionPointerType method = (FunctionPointerType)type;
                WriteElementType(ElementType.FnPtr);
                WriteMethodSignature(method);
                break;
            }

            case ElementType.CModReqD:
            case ElementType.CModOpt:
            {
                IModifierType type2 = (IModifierType)type;
                WriteModifierSignature(etype, type2);
                break;
            }

            case ElementType.Array:
            {
                ArrayType arrayType = (ArrayType)type;
                if (!arrayType.IsVector)
                {
                    WriteArrayTypeSignature(arrayType);
                }
                else
                {
                    WriteElementType(ElementType.SzArray);
                    WriteTypeSignature(arrayType.ElementType);
                }
                break;
            }

            case ElementType.None:
                WriteElementType(type.IsValueType ? ElementType.ValueType : ElementType.Class);
                base.WriteCompressedUInt32(MakeTypeDefOrRefCodedRID(type));
                break;

            default:
                if (TryWriteElementType(type))
                {
                    break;
                }
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 43
0
        TypeReference ImportTypeSpecification(TypeReference type, IGenericContext context)
        {
            switch (type.etype)
            {
            case ElementType.SzArray:
                var vector = (ArrayType)type;
                return(new ArrayType(ImportType(vector.ElementType, context)));

            case ElementType.Ptr:
                var pointer = (PointerType)type;
                return(new PointerType(ImportType(pointer.ElementType, context)));

            case ElementType.ByRef:
                var byref = (ByReferenceType)type;
                return(new ByReferenceType(ImportType(byref.ElementType, context)));

            case ElementType.Pinned:
                var pinned = (PinnedType)type;
                return(new PinnedType(ImportType(pinned.ElementType, context)));

            case ElementType.Sentinel:
                var sentinel = (SentinelType)type;
                return(new SentinelType(ImportType(sentinel.ElementType, context)));

            case ElementType.CModOpt:
                var modopt = (OptionalModifierType)type;
                return(new OptionalModifierType(
                           ImportType(modopt.ModifierType, context),
                           ImportType(modopt.ElementType, context)));

            case ElementType.CModReqD:
                var modreq = (RequiredModifierType)type;
                return(new RequiredModifierType(
                           ImportType(modreq.ModifierType, context),
                           ImportType(modreq.ElementType, context)));

            case ElementType.Array:
                var array          = (ArrayType)type;
                var imported_array = new ArrayType(ImportType(array.ElementType, context));
                if (array.IsVector)
                {
                    return(imported_array);
                }

                var dimensions          = array.Dimensions;
                var imported_dimensions = imported_array.Dimensions;

                imported_dimensions.Clear();

                for (int i = 0; i < dimensions.Count; i++)
                {
                    var dimension = dimensions [i];

                    imported_dimensions.Add(new ArrayDimension(dimension.LowerBound, dimension.UpperBound));
                }

                return(imported_array);

            case ElementType.GenericInst:
                var instance          = (GenericInstanceType)type;
                var element_type      = ImportType(instance.ElementType, context);
                var imported_instance = new GenericInstanceType(element_type);

                var arguments          = instance.GenericArguments;
                var imported_arguments = imported_instance.GenericArguments;

                for (int i = 0; i < arguments.Count; i++)
                {
                    imported_arguments.Add(ImportType(arguments [i], context));
                }

                return(imported_instance);

            case ElementType.Var:
                if (context == null || context.Type == null)
                {
                    throw new InvalidOperationException();
                }

                return(((TypeReference)context.Type).GetElementType().GenericParameters [((GenericParameter)type).Position]);

            case ElementType.MVar:
                if (context == null || context.Method == null)
                {
                    throw new InvalidOperationException();
                }

                return(context.Method.GenericParameters [((GenericParameter)type).Position]);
            }

            throw new NotSupportedException(type.etype.ToString());
        }