Inheritance: MemberReference, IGenericParameterProvider, IGenericContext
        private static void SwapParameterTypes(MethodDefinition method,
            TypeDefinition targetDependency,
            TypeReference interfaceType,
            HashSet<MethodReference> modifiedMethods)
        {
            if (method.IsAbstract || !method.HasBody)
                return;

            bool modified = false;
            var parameters = method.Parameters.Cast<ParameterDefinition>();
            foreach (var parameter in parameters)
            {
                var parameterType = parameter.ParameterType;
                if (parameterType != targetDependency)
                    continue;

                parameter.ParameterType = interfaceType;
                modified = true;
            }

            if (!modified)
                return;

            modifiedMethods.Add(method);
        }
Exemple #2
0
        private AnalysisNet.Types.TypeDefinition ExtractClass(Cecil.TypeDefinition cecilType, AnalysisNet.Types.TypeKind typeKind, AnalysisNet.Types.TypeDefinitionKind typeDefinitionKind)
        {
            string name = UnmangleName(cecilType);

            AnalysisNet.Types.TypeDefinition type = new AnalysisNet.Types.TypeDefinition(name, typeKind, typeDefinitionKind);
            Cecil.TypeReference basedef           = cecilType.BaseType;

            type.IsAbstract = cecilType.IsAbstract;
            type.IsSealed   = cecilType.IsSealed;

            if (basedef != null)
            {
                type.Base = ExtractType(basedef) as AnalysisNet.Types.IBasicType;
            }

            ExtractCustomAttributes(type.Attributes, cecilType.CustomAttributes);
            ExtractGenericTypeParameters(type, cecilType);
            ExtractInterfaces(type.Interfaces, cecilType.Interfaces);
            ExtractFields(type, type.Fields, cecilType.Fields);
            ExtractMethods(type, type.Methods, cecilType.Methods);
            ExtractPropertyDefinitions(type, cecilType);
            ExtractExplicitMethodOverrides(type, cecilType);
            ExtractLayoutInformation(type, cecilType);

            return(type);
        }
        public override void ImportReferences(ModuleDefinition module)
        {
            // Import the references from the base class
            base.ImportReferences(module);

            _modifiableInterfaceType = module.ImportType<IModifiableType>();
        }
 public void FindDerivedFrom(TypeReference baseTypeRef)
 {
     foreach (var td in _module.Types) {
         if(IsDerivedFrom(td, baseTypeRef))
             Console.WriteLine (td.FullName);
     }
 }
 public Tuple<TypeDefinition, AssemblyDefinition> this[TypeReference typ, AssemblyNameReference assembly]
 {
     get
       {
     return typ == null ? null : this[assembly.BuildAssemblyQualifiedName (typ)];
       }
 }
 public EventDefinition(string name, TypeReference eventType,
     EventAttributes attrs)
     : base(name)
 {
     m_eventType = eventType;
     m_attributes = attrs;
 }
		private bool ShouldAddCast(Expression argument, List<MethodDefinition> sameNameMethods, int argumentIndex, TypeReference calledMethodParamType)
		{
			if (!argument.HasType)
			{
				return true;
			}
			TypeReference expressionType = argument.ExpressionType;
			//if (argument.ExpressionType.IsGenericParameter)
			//{
			//	return false;
			//}
			foreach (MethodDefinition method in sameNameMethods)
			{
				TypeReference parameterType = method.Parameters[argumentIndex].ParameterType;
				if (IsTypeDescendantOf(calledMethodParamType, parameterType) || calledMethodParamType.FullName == parameterType.FullName)
				{
					/// Either the called method has more specific type,
					/// or the types match.
					continue;
				}
				if (IsTypeDescendantOf(expressionType, parameterType) || expressionType.FullName == parameterType.FullName)
				{
					return true;
				}
				if (argument.CodeNodeType == CodeNodeType.LiteralExpression && ((LiteralExpression)argument).Value == null)
				{
					if (!parameterType.IsValueType)
					{
						return true;
					}
				}
			}
			return false;
		}
 public MethodDefinition createMethod(String sMethodName, MethodAttributes maMethodAttributes,
                                      TypeReference trReturnType)
 {
     var newMethod = new MethodDefinition(sMethodName, maMethodAttributes, trReturnType);
     newMethod.Body.CilWorker.Emit(OpCodes.Ret);
     return newMethod;
 }
 public TypeDefinition addType(String sTypeNameSpace, String sTypeName, TypeAttributes taTypeAttributes,
                               TypeReference trTypeReference)
 {
     var tdNewType = new TypeDefinition(sTypeName, sTypeNameSpace, taTypeAttributes, trTypeReference);
     mainModule.Types.Add(tdNewType);
     return tdNewType;
 }
Exemple #10
0
        /// <summary>
        /// Make minor fixes after the implementation phase.
        /// </summary>
        public void FixUp(DexTargetPackage targetPackage)
        {
            var iMethod = method.GetBaseInterfaceMethod();

            Mono.Cecil.TypeReference inheritedReturnType = null;
            //var iMethod = method.Overrides.Select(x => x.Resolve()).Where(x => x != null).FirstOrDefault(x => x.DeclaringType.IsInterface);
            if (iMethod != null)
            {
                inheritedReturnType = iMethod.ReturnType;
            }

            var baseMethod = method.GetBaseMethod();

            if (baseMethod != null)
            {
                inheritedReturnType = baseMethod.ReturnType;
            }


            if (inheritedReturnType != null)
            {
                var inheritedTargetReturnType = inheritedReturnType.GetReference(targetPackage, compiler.Module);
                if (inheritedTargetReturnType.Descriptor != dmethod.Prototype.ReturnType.Descriptor)
                {
                    dmethod.Prototype.Unfreeze();
                    dmethod.Prototype.ReturnType = inheritedTargetReturnType;
                    dmethod.Prototype.Freeze();
                    //// update the original method's return type as well,
                    //// to make sure the code generation later knows what it is handling.
                    //// TODO: this seems to be a hack. shouldn't this have been handled
                    ////       during the IL-conversion phase?
                    xMethod.SetInheritedReturnType(inheritedReturnType);
                }
            }
        }
Exemple #11
0
        public static TypeDefinition Resolve(IAssemblyResolver resolver, TypeReference type)
        {
            type = type.GetElementType ();

            var scope = type.Scope;
            switch (scope.MetadataScopeType) {
            case MetadataScopeType.AssemblyNameReference:
                var assembly = resolver.Resolve ((AssemblyNameReference) scope);
                if (assembly == null)
                    return null;

                return GetType (assembly.MainModule, type);
            case MetadataScopeType.ModuleDefinition:
                return GetType ((ModuleDefinition) scope, type);
            case MetadataScopeType.ModuleReference:
                var modules = type.Module.Assembly.Modules;
                var module_ref = (ModuleReference) scope;
                for (int i = 0; i < modules.Count; i++) {
                    var netmodule = modules [i];
                    if (netmodule.Name == module_ref.Name)
                        return GetType (netmodule, type);
                }
                break;
            }

            throw new NotSupportedException ();
        }
Exemple #12
0
 public TypeNode(string name, string parent = "", bool builtIn = false, TypeReference type = null)
 {
     Name = name;
       Type = type;
       Parent = parent;
       BuiltIn = builtIn;
 }
Exemple #13
0
 public MethodDefinition(string name, MethodAttributes attributes, TypeReference returnType)
     : base(name, returnType)
 {
     this.attributes = (ushort) attributes;
     this.HasThis = !this.IsStatic;
     this.token = new MetadataToken (TokenType.Method);
 }
Exemple #14
0
		static MethodDefinition CreateTestMethod(Emitter emitter)
		{
			TypeReference type = new TypeReference("", "Test", null, null);
			MethodDefinition test = new MethodDefinition("Test", MethodAttributes.Public, type);
			emitter(test.Body.GetILProcessor());
			return test;
		}
		public TypeDefinition GetTypeDefinition (TypeReference type)
		{
			if (type == null)
				return null;

			TypeDefinition typeDef = type as TypeDefinition;
			if (typeDef != null)
				return typeDef;

			AssemblyNameReference name = type.Scope as AssemblyNameReference;
			if (name == null) {
				GenericInstanceType gi = type as GenericInstanceType;
				return gi == null ? null : GetTypeDefinition (gi.ElementType);
			}

			AssemblyDefinition assmDef;
			try {
				assmDef = Resolve (name);
			} catch (FileNotFoundException) {
				throw new ObfuscarException ("Unable to resolve dependency:  " + name.Name);
			}

			string fullName = type.GetFullName ();
			typeDef = assmDef.MainModule.GetType (fullName);
			return typeDef;
		}
 public EmitDelegateConvert(ILEmitter preceedingCode, ILEmitter itemToConvert, TypeReference targetType)
     : base(preceedingCode)
 {
     _inner = new EmptyEmitter(preceedingCode)
                 .Call(Importer.DelegateConvertChangeType, itemToConvert, new EmptyEmitter(preceedingCode).TypeOf(targetType))
                 .CastClass(targetType);
 }
 public Tuple<TypeDefinition, AssemblyDefinition> this[TypeReference typ, AssemblyDefinition assembly]
 {
     get
       {
     return this[typ, assembly.Name];
       }
 }
Exemple #18
0
        /// <summary>
        /// Is the given attribute type ApplicationRootAttribute or derived of that type?
        /// </summary>
        private bool IsApplicationRootAttribute(TypeReference attributeType)
        {
            var typeDef = attributeType.Resolve();

            if (typeDef == null)
            {
                return(false);
            }

            // Try the cache
            bool result;

            if (isApplicationRootTypes.TryGetValue(typeDef, out result))
            {
                return(result);
            }

            // No in cache yet, find out
            if ((typeDef.Namespace == AttributeConstants.Dot42AttributeNamespace) &&
                (typeDef.Name == AttributeConstants.ApplicationRootAttributeName))
            {
                result = true;
            }
            else
            {
                // Try base type
                result = (typeDef.BaseType != null) && IsApplicationRootAttribute(typeDef.BaseType);
            }
            isApplicationRootTypes[typeDef] = result;
            return(result);
        }
Exemple #19
0
        public static string PickMemoryTypeSuffix(TypeReference type, bool isStore)
        {
            switch (type.FullName) {
                case "System.Byte":
                    if (isStore)
                        return "8";
                    else
                        return "8_u";

                case "System.SByte":
                    return "8";

                case "System.UInt16":
                    if (isStore)
                        return "16";
                    else
                        return "16_u";

                case "System.Int16":
                    return "16";

                // FIXME: i8 or i16 for char?
            }

            return "";
        }
Exemple #20
0
        public Cecil.MethodDefinition MethodDefinition(AnalysisNet.Types.MethodDefinition methodDefinition)
        {
            Cecil.MethodDefinition cecilMethodDefinition = new Cecil.MethodDefinition(methodDefinition.Name, 0, Context.CurrentModule.TypeSystem.Void);
            GenerateMethodAttributes(methodDefinition, cecilMethodDefinition);
            cecilMethodDefinition.CreateGenericParameters(methodDefinition.GenericParameters.Count);

            Cecil.TypeReference returnType = ReferenceGenerator.TypeReference(methodDefinition.ReturnType);
            cecilMethodDefinition.ReturnType = returnType;
            AddConstraintsToGenericParameters(methodDefinition, cecilMethodDefinition);

            Cecil.TypeReference  typeRef        = ReferenceGenerator.TypeReference(methodDefinition.ContainingType);
            Cecil.TypeDefinition containingType = typeRef.Resolve();
            cecilMethodDefinition.DeclaringType = containingType as Cecil.TypeDefinition;

            SetOverrides(methodDefinition, cecilMethodDefinition);
            SetCustomAttributes(methodDefinition.Attributes, cecilMethodDefinition.CustomAttributes);
            IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.ParameterDefinition> parameterDefinitions = CreateParameters(methodDefinition, cecilMethodDefinition);

            if (methodDefinition.HasBody)
            {
                cecilMethodDefinition.Body.MaxStackSize = methodDefinition.Body.MaxStack;
                cecilMethodDefinition.Body.InitLocals   = methodDefinition.Body.LocalVariables.Count > 0;
                IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.Cil.VariableDefinition> variableDefinitions = CreateLocalVariables(methodDefinition, cecilMethodDefinition);
                InstructionGenerator instructionGenerator = new InstructionGenerator(ReferenceGenerator);

                // analysis-net instruction -> [cecil instruction]
                IDictionary <AnalysisNet.Bytecode.Instruction, IList <Cecil.Cil.Instruction> > mapInstructions = instructionGenerator.CreateInstructions(methodDefinition, cecilMethodDefinition, variableDefinitions, parameterDefinitions);

                CreateExceptionHandlers(mapInstructions, methodDefinition.Body, cecilMethodDefinition.Body);
            }

            return(cecilMethodDefinition);
        }
 private DynamicIndexerExpression(Expression target, ExpressionCollection indices, TypeReference expressionType, IEnumerable<Instruction> instructions)
     :base(instructions)
 {
     this.Target = target;
     this.Indices = indices;
     this.ExpressionType = expressionType;
 }
Exemple #22
0
 public JSInvocationExpression CreateInstanceOfType(TypeReference type)
 {
     return JSInvocationExpression.InvokeStatic(
         Dot(new JSFakeMethod("CreateInstanceOfType", type, new[] { TypeSystem.Object }, MethodTypes)),
         new[] { new JSTypeOfExpression(type) }
     );
 }
Exemple #23
0
        public string create(TypeReference typeRef)
        {
            if (typeRef.IsGenericInstance) {
                var git = (GenericInstanceType)typeRef;
                if (git.ElementType.FullName == "System.Nullable`1" &&
                    git.GenericArguments.Count == 1 && git.GenericArguments[0] != null) {
                    typeRef = git.GenericArguments[0];
                }
            }

            string prefix = getPrefix(typeRef);

            var elementType = typeRef.GetElementType();
            if (elementType is GenericParameter)
                return genericParamNameCreator.create();

            NameCreator nc;
            var typeFullName = typeRef.FullName;
            if (typeNames.TryGetValue(typeFullName, out nc))
                return nc.create();

            var name = elementType.FullName;
            var parts = name.Replace('/', '.').Split(new char[] { '.' });
            var newName = parts[parts.Length - 1];
            int tickIndex = newName.LastIndexOf('`');
            if (tickIndex > 0)
                newName = newName.Substring(0, tickIndex);

            return addTypeName(typeFullName, newName, prefix).create();
        }
 public TypeReference convert(TypeReference typeRef)
 {
     if (typeRef == null)
         return null;
     typeRef = new TypeReferenceConverter(this).convert(typeRef);
     return tryGetTypeDefinition(typeRef);
 }
 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;
 }
Exemple #26
0
 /// <summary>
 /// Gets the human readable name of the given type.
 /// </summary>
 public static string GetShortTypeName(TypeReference type, bool includeGenericParameters, bool includeGenericArguments)
 {
     if (type.IsNested)
     {
         var result = GetShortTypeName(type.DeclaringType, includeGenericParameters, includeGenericArguments) + "." + StripGenericParameterCount(type.Name);
         if (includeGenericParameters) result += GetGenericParameters(type);
         return result;
     }
     if (type.IsArray)
     {
         return GetShortTypeName(((ArrayType)type).ElementType) + "[]";
     }
     if (type.IsGenericParameter) return type.Name;
     if (type.IsGenericInstance)
     {
         var git = (GenericInstanceType)type;
         var arguments = includeGenericArguments ?
             git.GenericArguments.Select(x => GetShortTypeName(x, includeGenericParameters, includeGenericArguments)) :
             git.ElementType.GenericParameters.Select(x => x.Name);
         return GetShortTypeName(git.ElementType, false, false) + '<' + string.Join(",", arguments) + '>';
     }
     if (type.IsByReference)
     {
         return "ref " + GetShortTypeName(((ByReferenceType)type).ElementType);
     }
     var fullName = type.FullName;
     string replacement;
     if (typeReplacements.TryGetValue(fullName, out replacement))
         return replacement;
     var prefix = (type.DeclaringType != null) ? GetShortTypeName(type.DeclaringType) + "." : string.Empty;
     var name = StripGenericParameterCount(type.Name);
     if (includeGenericParameters) name += GetGenericParameters(type);
     return prefix + name;
 }
Exemple #27
0
        private AnalysisNet.IInstruction ProcessConversion(Cecil.Cil.Instruction op)
        {
            AnalysisNetBytecode.ConvertOperation operation = OperationHelper.ToConvertOperation(op.OpCode.Code);
            bool overflow = OperationHelper.PerformsOverflowCheck(op.OpCode.Code);
            bool unsigned = OperationHelper.OperandsAreUnsigned(op.OpCode.Code);

            Cecil.TypeReference     cciType = op.Operand as Cecil.TypeReference;
            AnalysisNet.Types.IType ourType = OperationHelper.GetOperationType(op.OpCode.Code);

            if (operation == AnalysisNetBytecode.ConvertOperation.Box)
            {
                ourType = typeExtractor.ExtractType(cciType);
            }
            else if (operation == AnalysisNetBytecode.ConvertOperation.Conv)
            {
                ourType = OperationHelper.GetOperationType(op.OpCode.Code);
            }
            else if (operation == AnalysisNetBytecode.ConvertOperation.Cast)
            {
                ourType = typeExtractor.ExtractType(op.Operand as Cecil.TypeReference);
            }

            AnalysisNetBytecode.ConvertInstruction instruction = new AnalysisNetBytecode.ConvertInstruction((uint)op.Offset, operation, ourType)
            {
                OverflowCheck    = overflow,
                UnsignedOperands = unsigned
            };
            return(instruction);
        }
Exemple #28
0
        private Cecil.FieldDefinition CreateFieldDefinition(AnalysisNet.Types.FieldDefinition fieldDefinition)
        {
            Cecil.FieldAttributes fieldAttribute = Cecil.FieldAttributes.Public;
            if (fieldDefinition.IsStatic)
            {
                fieldAttribute |= Cecil.FieldAttributes.Static;
            }

            Cecil.TypeReference   fieldType  = ReferenceGenerator.TypeReference(fieldDefinition.Type);
            Cecil.FieldDefinition cecilField = new Cecil.FieldDefinition(fieldDefinition.Name, fieldAttribute, fieldType);

            if (fieldDefinition.Value != null)
            {
                cecilField.Constant    = fieldDefinition.Value.Value;
                cecilField.HasConstant = true;
            }

            byte[] newArray = new byte[fieldDefinition.InitialValue.Length];
            Array.Copy(fieldDefinition.InitialValue, newArray, newArray.Length);
            cecilField.InitialValue = newArray;

            if (newArray.Length > 0)
            {
                cecilField.Attributes |= Cecil.FieldAttributes.HasFieldRVA;
            }

            return(cecilField);
        }
 public BinaryExpression(BinaryOperator @operator, Expression left, Expression right,
     TypeReference expressionType, TypeSystem typeSystem, IEnumerable<Instruction> instructions, bool isOverridenOperation = false)
     : this(@operator, left, right, DetermineIsChecked(instructions), instructions, isOverridenOperation)
 {
     this.ExpressionType = expressionType;
     this.typeSystem = typeSystem;
 }
Exemple #30
0
        internal static Type GetActualType(this MemberType memberType)
        {
            Mono.Cecil.TypeReference typeReference = null;
            object         type           = memberType.Annotations.First();
            TypeDefinition typeDefinition = type as TypeDefinition;

            if (typeDefinition != null)
            {
                return(typeDefinition.GetActualType());
            }

            typeReference = type as Mono.Cecil.TypeReference;

            if (typeReference != null)
            {
                if (typeReference.HasGenericParameters)
                {
                    Type[] parameters  = new Type[typeReference.GenericParameters.Count];
                    Type   genericType = typeReference.GetActualType();
                    var    simpleType  = memberType.Target as SimpleType;

                    simpleType.TypeArguments
                    .ForEach((p, i) => {
                        Type parameterType = p.GetActualType();
                        parameters[i]      = parameterType;
                    });

                    return(genericType.MakeGenericType(parameters));
                }

                return(typeReference.GetActualType());
            }

            return(null);
        }
Exemple #31
0
        public void InsertInstruction()
        {
            var object_ref = new TypeReference ("System", "Object", null, false);
            var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref);
            var body = new MethodBody (method);

            var il = body.GetILProcessor ();

            var first = il.Create (OpCodes.Nop);
            var second = il.Create (OpCodes.Nop);
            var third = il.Create (OpCodes.Nop);

            body.Instructions.Add (first);
            body.Instructions.Add (third);

            Assert.IsNull (first.Previous);
            Assert.AreEqual (third, first.Next);
            Assert.AreEqual (first, third.Previous);
            Assert.IsNull (third.Next);

            body.Instructions.Insert (1, second);

            Assert.IsNull (first.Previous);
            Assert.AreEqual (second, first.Next);
            Assert.AreEqual (first, second.Previous);
            Assert.AreEqual (third, second.Next);
            Assert.AreEqual (second, third.Previous);
            Assert.IsNull (third.Next);
        }
Exemple #32
0
        public static string PickTypeKeyword(TypeReference type)
        {
            // FIXME
            switch (type.FullName) {
                case "System.Void":
                    return "void";

                case "System.Boolean":
                case "System.Int32":
                case "System.UInt32":
                    return "i32";

                case "System.Int64":
                case "System.UInt64":
                    return "i64";

                case "System.Single":
                    return "f32";

                case "System.Double":
                    return "f64";

                case "System.Byte":
                case "System.UInt16":
                case "System.SByte":
                case "System.Int16":
                    return "i32";
            }

            return null;
        }
		public ArrayCreationExpression(TypeReference type, InitializerExpression initializer, IEnumerable<Instruction> instructions)
            :base(instructions)
		{
            this.ElementType = type;
            this.Initializer = initializer;
            this.Dimensions = new ExpressionCollection();
        }
Exemple #34
0
 public JSInvocationExpression Coalesce(JSExpression left, JSExpression right, TypeReference expectedType)
 {
     return JSInvocationExpression.InvokeStatic(
         Dot("Coalesce", expectedType),
         new[] { left, right }, true
     );
 }
        public static string[] GetPackedArrayArgumentNames (MethodInfo method, out TypeReference packedArrayAttributeType) {
            packedArrayAttributeType = null;

            AttributeGroup packedArrayAttribute;
            if (
                (method != null) &&
                ((packedArrayAttribute = method.Metadata.GetAttribute("JSIL.Meta.JSPackedArrayArgumentsAttribute")) != null)
            ) {
                var result = new List<string>();

                foreach (var entry in packedArrayAttribute.Entries) {
                    packedArrayAttributeType = entry.Type;

                    var argumentNames = entry.Arguments[0].Value as IList<CustomAttributeArgument>;
                    if (argumentNames == null)
                        throw new ArgumentException("Arguments to JSPackedArrayArguments must be strings");

                    foreach (var attributeArgument in argumentNames) {
                        var argumentName = attributeArgument.Value as string;
                        if (argumentName == null)
                            throw new ArgumentException("Arguments to JSPackedArrayArguments must be strings");

                        result.Add(argumentName);
                    }
                }

                return result.ToArray();
            }

            return null;
        }
Exemple #36
0
        public static bool ContainsPositionalGenericParameter(TypeReference type)
        {
            type = DereferenceType(type);

            var gp = type as GenericParameter;
            var git = type as GenericInstanceType;
            var at = type as ArrayType;
            var byref = type as ByReferenceType;

            if (gp != null)
                return IsPositionalGenericParameter(gp);

            if (git != null) {
                var elt = git.ElementType;

                foreach (var ga in git.GenericArguments) {
                    if (IsPositionalGenericParameter(ga))
                        return true;
                }

                return IsPositionalGenericParameter(elt);
            }

            if (at != null)
                return IsPositionalGenericParameter(at.ElementType);

            if (byref != null)
                return IsPositionalGenericParameter(byref.ElementType);

            return false;
        }
 public OptionalModifierType(TypeReference modifierType, TypeReference type)
     : base(type)
 {
     Mixin.CheckModifier (modifierType, type);
     this.modifier_type = modifierType;
     this.etype = MD.ElementType.CModOpt;
 }
Exemple #38
0
        public Cecil.MethodReference MethodReference(AnalysisNet.Types.IMethodReference methodReference)
        {
            if (methodsCache.TryGetValue(methodReference, out Cecil.MethodReference cecilMethodReference))
            {
                return(cecilMethodReference);
            }

            Cecil.TypeReference dummyReturnType = Context.CurrentModule.TypeSystem.Void;
            Cecil.TypeReference declaringType   = TypeReference(methodReference.ContainingType);

            string name = methodReference.Name;

            cecilMethodReference = new Cecil.MethodReference(name, dummyReturnType, declaringType)
            {
                HasThis = !methodReference.IsStatic
            };

            if (methodReference.GenericParameterCount > 0)
            {
                cecilMethodReference.CreateGenericParameters(methodReference.GenericParameterCount);
                MapGenericParameters(cecilMethodReference, methodReference);
                // should we add constraints?
                if (methodReference.GenericArguments.Count == 0)
                {
                    Cecil.GenericInstanceMethod instantiated = new Cecil.GenericInstanceMethod(cecilMethodReference);
                    instantiated.GenericArguments.AddRange(cecilMethodReference.GenericParameters);
                    cecilMethodReference = instantiated;
                }
                else
                {
                    IEnumerable <Cecil.TypeReference> arguments    = methodReference.GenericArguments.Select(ga => TypeReference(ga));
                    Cecil.GenericInstanceMethod       instantiated = new Cecil.GenericInstanceMethod(cecilMethodReference);
                    instantiated.GenericArguments.AddRange(arguments);
                    cecilMethodReference = instantiated;
                }
            }

            cecilMethodReference.ReturnType = TypeReference(methodReference.ReturnType);

            foreach (AnalysisNet.Types.IMethodParameterReference parameter in methodReference.Parameters)
            {
                Cecil.ParameterDefinition cecilParam = new Cecil.ParameterDefinition(TypeReference(parameter.Type));
                if (parameter.Kind == AnalysisNet.Types.MethodParameterKind.In)
                {
                    cecilParam.IsIn = true;
                }
                else if (parameter.Kind == AnalysisNet.Types.MethodParameterKind.Out)
                {
                    cecilParam.IsOut = true;
                }

                cecilMethodReference.Parameters.Add(cecilParam);
            }

            cecilMethodReference          = Context.CurrentModule.ImportReference(cecilMethodReference);
            methodsCache[methodReference] = cecilMethodReference;

            return(cecilMethodReference);
        }
Exemple #39
0
 public static IndexBase.TypeReference ToIndexBaseTypeReference(this Mono.Cecil.TypeReference typeReference)
 {
     return(new IndexBase.TypeReference
     {
         AssemblyName = typeReference.Module.Assembly.Name.Name,
         FullName = typeReference.FullName
     });
 }
Exemple #40
0
        private AnalysisNet.IInstruction ProcessSizeof(Cecil.Cil.Instruction op)
        {
            Cecil.TypeReference     cciType = op.Operand as Cecil.TypeReference;
            AnalysisNet.Types.IType ourType = typeExtractor.ExtractType(cciType);

            AnalysisNetBytecode.SizeofInstruction instruction = new AnalysisNetBytecode.SizeofInstruction((uint)op.Offset, ourType);
            return(instruction);
        }
Exemple #41
0
        public static string ToTypeScriptType(this Mono.Cecil.TypeReference typeReference)
        {
            typeReference = GetNullableType(typeReference);

            if (genericTypeMap == null)
            {
                genericTypeMap = typeMap
                                 .ToDictionary(item => "<" + item.Key + ">", item => "<" + item.Value + ">");

                typeMap
                .ToDictionary(item => item.Key + "[]", item => item.Value + "[]")
                .Each(x => genericTypeMap.Add(x.Key, x.Value));
            }

            var fromName = typeReference.FullName;

            // translate / in nested classes into underscores
            fromName = fromName.Replace("/", "_");

            if (typeMap.ContainsKey(fromName))
            {
                return(typeMap[fromName]);
            }

            var genericType = genericTypeMap.FirstOrDefault(x => fromName.Contains(x.Key));

            if (!genericType.Equals(default(System.Collections.Generic.KeyValuePair <string, string>)))
            {
                fromName = fromName.Replace(genericType.Key, genericType.Value);
            }

            fromName = fromName
                       .StripGenericTick();

            // To lazy to figure out the Mono.Cecil way (or if there is a way), but do
            // some string search/replace on types for example:
            //
            // turn
            //      Windows.Foundation.Collections.IMapView<System.String,System.Object>;
            // into
            //      Windows.Foundation.Collections.IMapView<string,any>;
            //
            typeMap.Each(item =>
            {
                fromName = fromName.Replace(item.Key, item.Value);
            });

            // If it's an array type return it as such.
            var genericTypeArgName = "";

            if (IsTypeArray(typeReference, out genericTypeArgName))
            {
                return(genericTypeArgName + "[]");
            }

            // remove the generic bit
            return(fromName);
        }
Exemple #42
0
 public void Add(Mono.Cecil.TypeReference type)
 {
     // Add all methods of type.
     Mono.Cecil.TypeDefinition type_defintion = type.Resolve();
     foreach (Mono.Cecil.MethodDefinition definition in type_defintion.Methods)
     {
         Add(definition);
     }
 }
 /// <summary>
 /// Create an argument for an annotation.
 /// </summary>
 private static AnnotationArgument CreateAnnotationArgument(string name, TypeReference valueType, object value, DexTargetPackage targetPackage, XModule module)
 {
     if (valueType.IsSystemType())
     {
         // Convert .NET type reference to Dex type reference
         value = ((TypeReference)value).GetReference(targetPackage, module);
     }
     return(new AnnotationArgument(name, value));
 }
Exemple #44
0
 public override void Visit(Model.Bytecode.InitObjInstruction instruction)
 {
     Cecil.Cil.OpCode    op   = Cecil.Cil.OpCodes.Initobj;
     Cecil.TypeReference type = referenceGenerator.TypeReference(instruction.Type);
     Result = new List <Mono.Cecil.Cil.Instruction>()
     {
         processor.Create(op, type)
     };
 }
Exemple #45
0
 private static bool IsNullable(this Mono.Cecil.TypeReference typeReference)
 {
     // TODO: is there a better way to determine if it's a Nullable?
     if (typeReference.Namespace == "System" && typeReference.Name == "Nullable`1")
     {
         return(true);
     }
     return(false);
 }
Exemple #46
0
        private Cecil.TypeReference ImportTypeReference(Cecil.TypeReference typeReference)
        {
            if (typeReference.Module == null || typeReference.Module != Context.CurrentModule)
            {
                typeReference = Context.CurrentModule.ImportReference(typeReference);
            }

            return(typeReference);
        }
Exemple #47
0
 private void SetDeclaringType(AnalysisNet.Types.TypeDefinition typeDefinition, Cecil.TypeDefinition cecilDef)
 {
     Cecil.TypeReference declaringTypeRef = typeDefinition.ContainingType == null ? null : ReferenceGenerator.TypeReference(typeDefinition.ContainingType);
     if (declaringTypeRef != null)
     {
         Cecil.TypeDefinition declaringType = declaringTypeRef.Resolve();
         declaringType.NestedTypes.Add(cecilDef);
         cecilDef.DeclaringType = declaringType;
     }
 }
Exemple #48
0
        public static TypeDefinition ToDef(this Mono.Cecil.TypeReference tr)
        {
            var res = tr.Resolve();

            if (res == null)
            {
                throw new InvalidOperationException();
            }
            return(res);
        }
                public NetTypeReference Visit(TypeReference type, ResolveData data)
                {
                    var typeDef = type.Resolve();

                    if (typeDef == null)
                    {
                        throw new ImportException(string.Format("Cannot resolve type {0}", type.FullName));
                    }
                    return(Visit(typeDef, data));
                }
Exemple #50
0
        /// <summary>
        /// Gets the type definition containing all the methods for the given type.
        /// </summary>
        /// <returns></returns>
        TypeDefinition GetMethodTypeDefinition(TypeReference typeReference)
        {
            if (typeReference is ArrayType)
            {
                // Return ArrayType
                return(corlib.MainModule.GetType(typeof(Array).FullName));
            }

            // Default: resolve to get real type
            return(typeReference.Resolve());
        }
Exemple #51
0
        private static MethodReference ResolveGenericMethod(TypeReference typeReference, MethodReference method)
        {
            var genericInstanceType = typeReference as GenericInstanceType;

            if (genericInstanceType != null)
            {
                return(method.MakeGeneric(genericInstanceType.GenericArguments.ToArray()));
            }

            return(method);
        }
Exemple #52
0
        public Type FindType(Cecil.TypeReference typeRef)
        {
            var type = resolver.FindType(typeRef);

            if (type == null)
            {
                throw new Exception(String.Format("Cannot resolve type {0}", typeRef));
            }

            return(type);
        }
Exemple #53
0
        public static string PrintShortType(this Mono.Cecil.TypeReference type)
        {
            var ginst = type as GenericInstanceType;

            if (ginst != null)
            {
                return(string.Format("{0}<{1}>", type.Name,
                                     ginst.GenericArguments.Select(w => w.Name).Aggregate((a, b) => a + ", " + b)));
            }
            return(type.Name);
        }
Exemple #54
0
        public static bool IsSimilarType(Type thisType, Mono.Cecil.TypeReference type)
        {
            // Ignore any 'ref' types
            if (thisType.IsByRef)
            {
                thisType = thisType.GetElementType();
            }
            if (type.IsByReference)
            {
                if (type.IsArray)
                {
                    var array_type = type as ArrayType;
                    type = array_type.ElementType;
                }
                else
                {
                    type = type.GetElementType();
                }
            }

            // Handle array types
            if (thisType.IsArray && type.IsArray)
            {
                Mono.Cecil.ArrayType at = type as Mono.Cecil.ArrayType;
                // Dimensions must be the same.
                if (thisType.GetArrayRank() != at.Rank)
                {
                    return(false);
                }
                // Base type of array must be the same.
                var array_type = type as ArrayType;
                return(IsSimilarType(thisType.GetElementType(), array_type.ElementType));
            }
            if (thisType.IsArray && !type.IsArray)
            {
                return(false);
            }
            if (type.IsArray && !thisType.IsArray)
            {
                return(false);
            }

            // If the types are identical, or they're both generic parameters
            // or the special 'T' type, treat as a match
            // Match also if thisType is generic and type can be unified with thisType.
            if (thisType.Name == type.Name || // identical types.
                ((thisType.IsGenericParameter || thisType == typeof(T)) && (type.IsGenericParameter || type.Name.Equals("T"))) || // using "T" as matching generic type.
                IsUnifiableMono(thisType, type))
            {
                return(true);
            }

            return(false);
        }
Exemple #55
0
 public TYPE(Mono.Cecil.TypeReference mono_type)
 {
     _cil_type                = mono_type.SwapInBclType();
     _cil_type_llvm           = _cil_type.ToTypeRef();
     _verification_type       = METAHELPER.InitVerificationType(_cil_type);
     _storage_type            = _verification_type;
     _storage_type_llvm       = _storage_type.ToTypeRef();
     _stack_verification_type = METAHELPER.InitStackVerificationType(_verification_type, _cil_type);
     _intermediate_type       = _stack_verification_type;
     _intermediate_type_llvm  = _stack_verification_type.ToTypeRef();
 }
Exemple #56
0
 protected static IList GetArgumentsToBaseConstructor(MC.CustomAttribute att, MC.TypeReference baseType)
 {
     if (att.AttributeType.FullName == baseType.FullName)
     {
         return(att.ConstructorArguments.Select(arg => arg.Value).ToList());
     }
     else
     {
         //FIXME: Implement
         throw new NotImplementedException();
     }
 }
Exemple #57
0
        public static int GetArrayInfo(Mono.Cecil.TypeReference type, out Mono.Cecil.TypeReference elementType)
        {
            elementType = type;
            int rank = 0;

            while (type.IsArray)
            {
                rank++;
                elementType = type = type.GetElementType();
            }
            return(rank);
        }
Exemple #58
0
 protected static IList GetArgumentsToBaseConstructor(MC.CustomAttribute att, MC.TypeReference baseType)
 {
     if (att.Constructor.DeclaringType.FullName == baseType.FullName)
     {
         return(att.ConstructorParameters);
     }
     else
     {
         //FIXME: Implement
         throw new NotImplementedException();
     }
 }
Exemple #59
0
        private bool IsDelegate(Cecil.TypeDefinition cecilType)
        {
            Cecil.TypeReference baseType = cecilType.BaseType;

            if (baseType == null)
            {
                return(false);
            }

            Cecil.IMetadataScope coreLibrary = cecilType.Module.TypeSystem.CoreLibrary;

            return(coreLibrary.Equals(baseType.Scope) && baseType.Namespace == "System" && baseType.Name == "MulticastDelegate");
        }
Exemple #60
0
        public AnalysisNet.Types.IType ExtractType(Cecil.TypeReference typeReference)
        {
            return(performanceCache.GetOrCreate(typeReference, (cacheEntry) =>
            {
                AnalysisNet.Types.IType result = null;

                if (typeReference is Cecil.ArrayType arrayType)
                {
                    result = ExtractType(arrayType);
                }
                else if (typeReference is Cecil.ByReferenceType byReferenceType)
                {
                    result = ExtractType(byReferenceType);
                }
                else if (typeReference is Cecil.PointerType pointerType)
                {
                    result = ExtractType(pointerType);
                }
                else if (typeReference is Cecil.GenericParameter genericParameterType)
                {
                    result = ExtractType(genericParameterType);
                }
                else if (typeReference is Cecil.FunctionPointerType functionPointerType)
                {
                    result = ExtractType(functionPointerType);
                }
                else if (typeReference is Cecil.GenericInstanceType genericInstanceType)
                {
                    result = ExtractType(genericInstanceType);
                }
                else
                {
                    // named type reference
                    result = ExtractNonGenericInstanceType(typeReference);
                }

                if (result is AnalysisNet.Types.BasicType)
                {
                    AnalysisNet.Types.BasicType basicType = result as AnalysisNet.Types.BasicType;
                    basicType.Resolve(host);

                    if (basicType.GenericType is AnalysisNet.Types.BasicType)
                    {
                        basicType = basicType.GenericType as AnalysisNet.Types.BasicType;
                        basicType.Resolve(host);
                    }
                }

                return result;
            }));
        }