public static GenericInstanceMethod MakeGenericMethod(this MethodReference reference, params TypeReference[] arguments) { var result = new GenericInstanceMethod(reference); foreach (var t in arguments) result.GenericArguments.Add(t); return result; }
protected override CallResult createCallResult(MethodReference method, GenericInstanceMethod gim, Block block, int callInstrIndex) { int methodId; if (!methodTokenToId.TryGetValue(method.MetadataToken.ToInt32(), out methodId)) return null; return new MyCallResult(block, callInstrIndex, methodId, gim); }
void InjectField(TypeDefinition type, FieldDefinition fieldDefinition) { var staticConstructor = type.GetStaticConstructor(); staticConstructor.Body.SimplifyMacros(); var genericInstanceMethod = new GenericInstanceMethod(forContextDefinition); if (type.IsCompilerGenerated() && type.IsNested) { genericInstanceMethod.GenericArguments.Add(type.DeclaringType.GetGeneric()); } else { genericInstanceMethod.GenericArguments.Add(type.GetGeneric()); } var instructions = staticConstructor.Body.Instructions; type.Fields.Add(fieldDefinition); var returns = instructions.Where(_ => _.OpCode == OpCodes.Ret) .ToList(); var ilProcessor = staticConstructor.Body.GetILProcessor(); foreach (var returnInstruction in returns) { var newReturn = Instruction.Create(OpCodes.Ret); ilProcessor.InsertAfter(returnInstruction, newReturn); ilProcessor.InsertBefore(newReturn, Instruction.Create(OpCodes.Call, genericInstanceMethod)); ilProcessor.InsertBefore(newReturn, Instruction.Create(OpCodes.Stsfld, fieldDefinition.GetGeneric())); returnInstruction.OpCode = OpCodes.Nop; } staticConstructor.Body.OptimizeMacros(); }
public static GenericInstanceMethod MakeGenericMethod(this MethodReference method, params TypeReference[] genericArguments) { var result = new GenericInstanceMethod(method); foreach (var argument in genericArguments) result.GenericArguments.Add(argument); return result; }
void EmitInstruction(ILGenerator il, OpCode opcode, Cecil.GenericInstanceMethod operandGeneric) { var ourType = FindType(operandGeneric.DeclaringType); Type[] opGenericArgs = operandGeneric.GenericArguments.Select((prm) => { return(FindType(prm)); }).ToArray(); Type[] opParamTypes = operandGeneric.Parameters.Select((prm) => { if (prm.ParameterType is Cecil.GenericParameter) { var genericParam = ((Cecil.GenericParameter)prm.ParameterType); return(opGenericArgs[genericParam.Position]); } return(FindType(prm.ParameterType)); }).ToArray(); var methods = ourType.GetMethods(bindingAttr: bflags_all); var ourMethod = methods.First(met => { return(met.Name == operandGeneric.Name && met.GetGenericArguments().Length == opGenericArgs.Length && met.GetParameters().Length == opParamTypes.Length); }); var metParams = ourMethod.GetParameters(); ourMethod = ourMethod.MakeGenericMethod(opGenericArgs); il.Emit(opcode, ourMethod); }
public static MethodReference MakeGenericMethod(this MethodReference self, params TypeReference[] arguments) { var method = new GenericInstanceMethod(self); foreach(var argument in arguments) method.GenericArguments.Add(argument); return method; }
MethodReference GetEquality(TypeReference typeDefinition) { if (typeDefinition.IsArray) { return null; } if (typeDefinition.IsGenericParameter) { return null; } if (typeDefinition.Namespace.StartsWith("System.Collections")) { return null; } if (typeDefinition.IsGenericInstance) { if (typeDefinition.FullName.StartsWith("System.Nullable")) { var genericInstanceMethod = new GenericInstanceMethod(NullableEqualsMethod); var typeWrappedByNullable = ((GenericInstanceType) typeDefinition).GenericArguments.First(); genericInstanceMethod.GenericArguments.Add(typeWrappedByNullable); return typeWrappedByNullable.IsGenericParameter ? ModuleDefinition.Import(genericInstanceMethod, typeWrappedByNullable.DeclaringType) : ModuleDefinition.Import(genericInstanceMethod); } } var equality = GetStaticEquality(typeDefinition); if (equality != null) { return ModuleDefinition.Import(equality); } return null; }
//that one is for normal use - like calling class members, etc public static MethodReference Instance(this MethodDefinition self) { var declaringType = self.DeclaringType.Instance(); var reference = new MethodReference(self.Name, self.ReturnType, declaringType); reference.HasThis = self.HasThis; reference.ExplicitThis = self.ExplicitThis; reference.CallingConvention = self.CallingConvention; foreach (var parameter in self.Parameters) reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); foreach (var generic_parameter in self.GenericParameters) reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference)); if (self.HasGenericParameters && !self.IsGetter && !self.IsSetter) { reference = new GenericInstanceMethod(reference); foreach (var genericParam in self.GenericParameters) if (self.DeclaringType.GenericParameters.SingleOrDefault(m => m.Name == genericParam.Name) == null) ((GenericInstanceMethod)(reference)).GenericArguments.Add(genericParam); } return reference; }
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); }
public void ExecuteWinRT() { var assemblyResolver = ModuleDefinition.AssemblyResolver; var systemRuntime = assemblyResolver.Resolve("System.Runtime"); var systemRuntimeTypes = systemRuntime.MainModule.Types; var objectDefinition = systemRuntimeTypes.First(x => x.Name == "Object"); var constructorDefinition = objectDefinition.Methods.First(x => x.IsConstructor); ObjectConstructor = ModuleDefinition.ImportReference(constructorDefinition); var objectEqualsMethodDefinition = objectDefinition.Methods.First(x => x.Name == "Equals" && x.Parameters.Count == 2); ObjectEqualsMethod = ModuleDefinition.ImportReference(objectEqualsMethodDefinition); var nullableDefinition = systemRuntimeTypes.FirstOrDefault(x => x.Name == "Nullable"); NullableEqualsMethod = ModuleDefinition.ImportReference(nullableDefinition).Resolve().Methods.First(x => x.Name == "Equals"); EqualityComparerTypeReference = systemRuntimeTypes.FirstOrDefault(x => x.Name == "EqualityComparer`1"); var actionDefinition = systemRuntimeTypes.First(x => x.Name == "Action"); ActionTypeReference = ModuleDefinition.ImportReference(actionDefinition); var actionConstructor = actionDefinition.Methods.First(x => x.IsConstructor); ActionConstructorReference = ModuleDefinition.ImportReference(actionConstructor); var systemObjectModel = assemblyResolver.Resolve("System.ObjectModel"); var systemObjectModelTypes = systemObjectModel.MainModule.Types; var propChangedInterfaceDefinition = systemObjectModelTypes.First(x => x.Name == "INotifyPropertyChanged"); PropChangedInterfaceReference = ModuleDefinition.ImportReference(propChangedInterfaceDefinition); var propChangedHandlerDefinition = systemObjectModelTypes.First(x => x.Name == "PropertyChangedEventHandler"); PropChangedHandlerReference = ModuleDefinition.ImportReference(propChangedHandlerDefinition); ComponentModelPropertyChangedEventHandlerInvokeReference = ModuleDefinition.ImportReference(propChangedHandlerDefinition.Methods.First(x => x.Name == "Invoke")); var propChangedArgsDefinition = systemObjectModelTypes.First(x => x.Name == "PropertyChangedEventArgs"); ComponentModelPropertyChangedEventConstructorReference = ModuleDefinition.ImportReference(propChangedArgsDefinition.Methods.First(x => x.IsConstructor)); var delegateDefinition = systemRuntimeTypes.First(x => x.Name == "Delegate"); var combineMethodDefinition = delegateDefinition.Methods .Single(x => x.Name == "Combine" && x.Parameters.Count == 2 && x.Parameters.All(p => p.ParameterType == delegateDefinition)); DelegateCombineMethodRef = ModuleDefinition.ImportReference(combineMethodDefinition); var removeMethodDefinition = delegateDefinition.Methods.First(x => x.Name == "Remove"); DelegateRemoveMethodRef = ModuleDefinition.ImportReference(removeMethodDefinition); var systemThreading = assemblyResolver.Resolve("System.Threading"); var interlockedDefinition = systemThreading.MainModule.Types.First(x => x.FullName == "System.Threading.Interlocked"); var genericCompareExchangeMethodDefinition = interlockedDefinition .Methods.First(x => x.IsStatic && x.Name == "CompareExchange" && x.GenericParameters.Count == 1 && x.Parameters.Count == 3); var genericCompareExchangeMethod = ModuleDefinition.ImportReference(genericCompareExchangeMethodDefinition); InterlockedCompareExchangeForPropChangedHandler = new GenericInstanceMethod(genericCompareExchangeMethod); InterlockedCompareExchangeForPropChangedHandler.GenericArguments.Add(PropChangedHandlerReference); }
public Assets([NotNull] ModuleWeaver moduleWeaver) { if (moduleWeaver == null) { throw new ArgumentNullException("moduleWeaver"); } _commands = new ConcurrentDictionary<string, CommandData>(); _moduleDefinition = moduleWeaver.ModuleDefinition; _log = moduleWeaver; var settings = moduleWeaver.Settings; _allClasses = new Lazy<List<TypeDefinition>>(()=> settings.GetAllTypes(moduleWeaver).ToList()); var types = new Types(moduleWeaver); _typeReferences = types; _typeDefinitions = types; var constructorDefinition = TypeDefinitions.Object.Methods.First(x => x.IsConstructor); _objectConstructorReference = ModuleDefinition.Import(constructorDefinition); var actionConstructor = TypeDefinitions.Action.Methods.First(x => x.IsConstructor); ActionConstructorReference = ModuleDefinition.Import(actionConstructor); var actionOfTConstructor = TypeDefinitions.ActionOfT.GetConstructors().First(); _actionOfTConstructorReference = ModuleDefinition.Import(actionOfTConstructor); var actionOfTInvokerDefinition = TypeDefinitions.ActionOfT.Methods.First(x => x.Name == "Invoke"); _actionOfTInvokeReference = ModuleDefinition.Import(actionOfTInvokerDefinition); var funcConstructor = TypeDefinitions.FuncOfT.Resolve().Methods.First(m => m.IsConstructor && m.Parameters.Count == 2); _funcOfBoolConstructorReference = ModuleDefinition.Import(funcConstructor).MakeHostInstanceGeneric(TypeReferences.Boolean); var predicateOfTConstructor = TypeDefinitions.PredicateOfT.GetConstructors().First(); _predicateOfTConstructorReference = ModuleDefinition.Import(predicateOfTConstructor); var predicateOfTInvokerDefinition = TypeDefinitions.PredicateOfT.Methods.First(x => x.Name == "Invoke"); _predicateOfTInvokeReference = ModuleDefinition.Import(predicateOfTInvokerDefinition); var delegateCombineDefinition = TypeDefinitions.Delegate.Methods.First(x => x.Name == "Combine" && x.Parameters.Count == 2); _delegateCombineMethodReference = ModuleDefinition.Import(delegateCombineDefinition); var delegateRemoveDefinition = TypeDefinitions.Delegate.Methods.First(x => x.Name == "Remove" && x.Parameters.Count == 2); _delegateRemoveMethodReference = ModuleDefinition.Import(delegateRemoveDefinition); var interlockedCompareExchangeMethodDefinition = TypeDefinitions.Interlocked.Methods.First( x => x.Name == "CompareExchange" && x.Parameters.Count == 3 && x.HasGenericParameters ); _interlockedCompareExchangeOfT = ModuleDefinition.Import(interlockedCompareExchangeMethodDefinition); _interlockedCompareExchangeOfEventHandler = new GenericInstanceMethod(_interlockedCompareExchangeOfT); _interlockedCompareExchangeOfEventHandler.GenericArguments.Add(TypeReferences.EventHandler); //_interlockedCompareExchangeOfEventHandler = if (TypeDefinitions.CommandManager != null) { var requeryEvent = TypeDefinitions.CommandManager.Resolve().Events.Single(evt => evt.Name == "RequerySuggested"); _commandManagerAddRequerySuggestedMethodReference = ModuleDefinition.Import(requeryEvent.AddMethod); _commandManagerRemoveRequerySuggestedMethodReference = ModuleDefinition.Import(requeryEvent.RemoveMethod); } _commandImplementationConstructors = GetCommandImplementationConstructors(); constructorDefinition = TypeDefinitions.ArgumentNullException.Methods.Single( x => x.IsConstructor && x.HasParameters && x.Parameters.Count == 1); _argumentNullExceptionConstructorReference = ModuleDefinition.Import(constructorDefinition); }
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; }
public static MethodReference MakeGenericMethod (this MethodReference self, params TypeReference [] arguments) { if (self.GenericParameters.Count != arguments.Length) throw new ArgumentException (); var instance = new GenericInstanceMethod (self); foreach (var argument in arguments) instance.GenericArguments.Add (argument); return instance; }
private GenericBindingContext(GenericInstanceMethod method) { var definition = method.Resolve(); for (int i = 0; i < definition.GenericParameters.Count; ++i) { var parameter = definition.GenericParameters[i]; var binding = method.GenericArguments[i]; _methodEntries.Add(new Entry(parameter.FullName, binding)); } }
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); } } }
public Instruction CallEventInvoker(PropertyDefinition propertyDefinition) { var method = typeNode.EventInvoker.MethodReference; if (method.HasGenericParameters) { var genericMethod = new GenericInstanceMethod(method); genericMethod.GenericArguments.Add(propertyDefinition.PropertyType); method = genericMethod; } return Instruction.Create(OpCodes.Callvirt, method); }
public Either<MemberReference, PropertyReferenceContainer> Convert(IAstReference astReference, ModuleDefinition module, IReferenceProvider recursive) { var methodAst = astReference as AstGenericMethodWithTypeArguments; if (methodAst == null) return null; var method = recursive.Convert(methodAst.Actual, module, recursive).As<MethodReference>(); var typeArguments = methodAst.GenericArgumentTypes.Select(a => recursive.Convert(a, module, recursive).As<TypeReference>()); var result = new GenericInstanceMethod(method); typeArguments.ForEach(result.GenericArguments.Add); return result; }
public static MethodReference MakeGeneric(this MethodReference method, params TypeReference[] args) { if (args.Length == 0) return method; if (method.GenericParameters.Count != args.Length) throw new ArgumentException("Invalid number of generic type arguments supplied"); var genericTypeRef = new GenericInstanceMethod(method); foreach (var arg in args) genericTypeRef.GenericArguments.Add(arg); return genericTypeRef; }
public MethodReference GetCallableParamListCreateMethod(AssemblyDefinition assemblyDef, MethodReference ctor, IAssemblyTracker tracker) { var tempRef = GetOrCreateRemotionInterfacesReference (assemblyDef, ctor.DeclaringType.Module, tracker); var paramListCreateReference = GetOrCreateParamList (ctor.Parameters.Count, ctor.DeclaringType.Module, tempRef); if (ctor.Parameters.Count > 0) { paramListCreateReference = new GenericInstanceMethod (paramListCreateReference); foreach (var param in ctor.Parameters) ((GenericInstanceMethod) paramListCreateReference).GenericArguments.Add (param.ParameterType); } return paramListCreateReference; }
public void WeaveConstructorCalls(IEnumerable<ConstructorCallWeave> weaves, FactoryMap factories) { MethodInfo getFactoryMethod = typeof(Factories).GetMethod("Create"); foreach (ConstructorCallWeave weave in weaves) { Factory factory = factories.GetForObjectType(weave.Constructor.DeclaringType); _log.Log("Weaving {0} in {1}", factory.ObjectType, weave.ParentMethod); MethodReference getObjectMethodReference = weave.ParentAssembly.Import(getFactoryMethod); GenericInstanceMethod methodCall = new GenericInstanceMethod(getObjectMethodReference); methodCall.GenericArguments.Add(factory.ObjectType); CilWorker worker = weave.ParentMethod.Body.CilWorker; Instruction callGetFactory = worker.Create(OpCodes.Call, methodCall); worker.Replace(weave.NewInstruction, callGetFactory); } }
public MethodReference GetCallableObjectFactoryCreateMethod(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, TypeReference instantiatedType, IAssemblyTracker tracker) { var tempRef = GetOrCreateRemotionInterfacesReference (assemblyDef, moduleDefinition, tracker); var objectFactoryReference = new TypeReference (_objectFactoryNamespace, _objectFactoryName, moduleDefinition, tempRef); var paramListReference = new TypeReference (_paramListNamespace, _paramListName, moduleDefinition, tempRef); var createReference = new MethodReference ("Create", moduleDefinition.TypeSystem.Void, objectFactoryReference); var createTypeParam = new GenericParameter ("T", createReference); createReference.GenericParameters.Add (createTypeParam); createReference.ReturnType = createTypeParam; createReference.Parameters.Add (new ParameterDefinition (moduleDefinition.TypeSystem.Boolean)); createReference.Parameters.Add (new ParameterDefinition (paramListReference)); createReference.Parameters.Add (new ParameterDefinition (new ArrayType (moduleDefinition.TypeSystem.Object))); var instanceMethod = new GenericInstanceMethod (createReference); instanceMethod.GenericArguments.Add (instantiatedType); return instanceMethod; }
public static MethodReference MakeGeneric(this MethodReference method, params TypeReference[] arguments) { if (method.GenericParameters.Count != arguments.Length) { throw new ArgumentException("Invalid number of generic type arguments supplied"); } if (arguments.Length == 0) { return method; } GenericInstanceMethod genericTypeReference = new GenericInstanceMethod(method); foreach (TypeReference argument in arguments) { genericTypeReference.GenericArguments.Add(argument); } return genericTypeReference; }
public MethodReference Resolve(MethodReference method) { var methodReference = method; if (IsDummy ()) return methodReference; var declaringType = Resolve (method.DeclaringType); var genericInstanceMethod = method as GenericInstanceMethod; if (genericInstanceMethod != null) { methodReference = new MethodReference (method.Name, method.ReturnType, declaringType); foreach (var p in method.Parameters) methodReference.Parameters.Add (new ParameterDefinition (p.Name, p.Attributes, p.ParameterType)); foreach (var gp in genericInstanceMethod.ElementMethod.GenericParameters) methodReference.GenericParameters.Add (new GenericParameter (gp.Name, methodReference)); methodReference.HasThis = method.HasThis; var m = new GenericInstanceMethod (methodReference); foreach (var ga in genericInstanceMethod.GenericArguments) { m.GenericArguments.Add (Resolve (ga)); } methodReference = m; } else { methodReference = new MethodReference (method.Name, method.ReturnType, declaringType); foreach (var gp in method.GenericParameters) methodReference.GenericParameters.Add (new GenericParameter (gp.Name, methodReference)); foreach (var p in method.Parameters) methodReference.Parameters.Add (new ParameterDefinition (p.Name, p.Attributes, p.ParameterType)); methodReference.HasThis = method.HasThis; } return methodReference; }
private static GenericInstanceMethod ConstructGenericMethod(GenericContext context, TypeReference declaringType, MethodDefinition method, IEnumerable<TypeReference> genericArguments) { MethodReference owner = new MethodReference(method.Name, method.ReturnType, declaringType) { HasThis = method.HasThis }; foreach (GenericParameter parameter in method.GenericParameters) { owner.GenericParameters.Add(new GenericParameter(parameter.Name, owner)); } foreach (ParameterDefinition definition in method.Parameters) { owner.Parameters.Add(new ParameterDefinition(definition.Name, definition.Attributes, definition.ParameterType)); } if (owner.Resolve() == null) { throw new Exception(); } GenericInstanceMethod method2 = new GenericInstanceMethod(owner); foreach (TypeReference reference3 in genericArguments) { method2.GenericArguments.Add(InflateType(context, reference3)); } return method2; }
public static TypeReference GetTypeWithGenericResolve(this ParameterDefinition definition, GenericInstanceMethod genericInstanceMethod) { var ret = definition.ParameterType; if (definition.ParameterType.IsGenericParameter) { var f = (MethodReference)definition.Method; if (f.DeclaringType is GenericInstanceType) { var position = ((GenericInstanceType)f.DeclaringType).ElementType.GenericParameters.GetIndexByName( definition.ParameterType.Name); if (position != -1) ret = ((GenericInstanceType)f.DeclaringType).GenericArguments[position]; } if (genericInstanceMethod != null) { var position = f.GetElementMethod().GenericParameters.GetIndexByName(definition.ParameterType.Name); if (position != -1) ret = genericInstanceMethod.GenericArguments[position]; } } return ret; }
public static PropertyDefinition BuildPropertyCore(Property property, TypeDefinition type) { var mod = type.Module; //从缓存中查找clr type var ptype = property.PropertyType.GetTypeReference(); var fieldInfo = new FieldDefinition("_" + property.名称, FieldAttributes.Private, ptype); type.Fields.Add(fieldInfo); // type.DefineField("_" + property.名称, ptype, FieldAttributes.Private); var propertyInfo = new PropertyDefinition(property.名称, PropertyAttributes.None, ptype) { HasThis = true }; type.Properties.Add(propertyInfo); #region 基本属性设置 if (property.Size != 100 && property.Size != 0) { propertyInfo.Size(property.Size); } //if (!string.IsNullOrEmpty(property.Expression)) //{ // propertyInfo.PersistentAlias(property.Expression); //} #endregion; #region getter //.method public hidebysig specialname instance string get_创建者() cil managedMono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName var attr = MethodAttributes.Public | MethodAttributes.HideBySig| MethodAttributes.SpecialName| MethodAttributes.FamANDAssem | MethodAttributes.Family; var setattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.FamANDAssem | MethodAttributes.Family; var getMethod = new MethodDefinition("get_" + property.名称, attr, ptype); var getMethodIl = getMethod.Body.GetILProcessor(); getMethod.Body.MaxStackSize = 8; getMethod.Body.InitLocals = true; getMethodIl.Emit(OpCodes.Ldarg_0); getMethodIl.Emit(OpCodes.Ldfld, fieldInfo); getMethodIl.Emit(OpCodes.Ret); type.Methods.Add(getMethod); propertyInfo.GetMethod = getMethod; #endregion #region 非计算类型 if (string.IsNullOrEmpty(property.Expression)) { var set = new MethodDefinition("set_" + property.名称, setattr, mod.ImportReference(typeof (void))); var para = new ParameterDefinition("value", ParameterAttributes.None, ptype); set.Parameters.Add(para); var setPropertyValue = mod.ImportReference( typeof (PersistentBase) .GetMethods( SR.BindingFlags.InvokeMethod | SR.BindingFlags.NonPublic | SR.BindingFlags.Instance) .Single(x => x.Name.StartsWith("SetPropertyValue") && x.IsGenericMethod && x.GetParameters().Length == 3) ); var setPropertyValueMethod = new GenericInstanceMethod(setPropertyValue); setPropertyValueMethod.GenericArguments.Add(ptype); //setPropertyValue = setPropertyValue.MakeGenericMethod(ptype); var setIl = set.Body.Instructions; setIl.Add(Instruction.Create(OpCodes.Ldarg_0)); setIl.Add(Instruction.Create(OpCodes.Ldstr, property.名称)); setIl.Add(Instruction.Create(OpCodes.Ldarg_0)); setIl.Add(Instruction.Create(OpCodes.Ldflda, fieldInfo)); setIl.Add(Instruction.Create(OpCodes.Ldarg_1)); setIl.Add(Instruction.Create(OpCodes.Call, setPropertyValueMethod)); setIl.Add(Instruction.Create(OpCodes.Pop)); setIl.Add(Instruction.Create(OpCodes.Ret)); propertyInfo.SetMethod = set; type.Methods.Add(set); } #endregion return propertyInfo; }
void doGenericInstanceMethod(GenericInstanceMethod genericInstanceMethod) { bool present; if (genericInstanceMethods.TryGetValue(genericInstanceMethod, out present)) return; genericInstanceMethods[genericInstanceMethod] = true; addGenericInstanceMethod(genericInstanceMethod); }
void addGenericInstanceMethod(GenericInstanceMethod genericInstanceMethod) { if (genericInstanceMethod == null) return; addMethodSpecification(genericInstanceMethod); addTypeReferences(genericInstanceMethod.GenericArguments); }
MethodReference ImportGenericInstanceMethod (SR.MethodInfo mi, ImportContext context) { SR.MethodInfo gmd = (SR.MethodInfo) mi.GetType ().GetMethod ("GetGenericMethodDefinition").Invoke (mi, null); GenericInstanceMethod gim = new GenericInstanceMethod ( ImportMethodBase (gmd, gmd.ReturnType, context)); foreach (Type genArg in GetGenericArguments (mi)) gim.GenericArguments.Add (ImportSystemType (genArg, context)); return gim; }
public TypeResolver(GenericInstanceType typeDefinitionContext, GenericInstanceMethod methodDefinitionContext) { _typeDefinitionContext = typeDefinitionContext; _methodDefinitionContext = methodDefinitionContext; }
private void ReplaceCalls(MethodBody body, Dictionary<TypeDefinition, TypeDefinition> replacements) { body.SimplifyMacros(); var calls = body.Instructions.Where(i => i.OpCode == OpCodes.Call); foreach (var call in calls) { var originalMethodReference = (MethodReference)call.Operand; var originalMethodDefinition = originalMethodReference.Resolve(); var declaringTypeReference = originalMethodReference.DeclaringType; var declaringTypeDefinition = declaringTypeReference.Resolve(); if (!originalMethodDefinition.IsStatic || !replacements.ContainsKey(declaringTypeDefinition)) continue; var replacementTypeReference = ModuleDefinition.ImportReference(replacements[declaringTypeDefinition]); if (declaringTypeReference.IsGenericInstance) { var declaringGenericType = (GenericInstanceType)declaringTypeReference; var genericType = new GenericInstanceType(replacementTypeReference); foreach (var arg in declaringGenericType.GenericArguments) { genericType.GenericArguments.Add(arg); } replacementTypeReference = ModuleDefinition.ImportReference(genericType); } var replacementMethod = replacementTypeReference.ReferenceMethod(originalMethodDefinition.Name); if (replacementMethod == null) { LogError(String.Format("Missing '{0}.{1}()' in '{2}'", declaringTypeDefinition.FullName, originalMethodDefinition.Name, replacementTypeReference.FullName)); continue; } if (!replacementMethod.Resolve().IsStatic) { LogError(String.Format("Replacement method '{0}' is not static", replacementMethod.FullName)); continue; } if (originalMethodReference.IsGenericInstance) { var originalGenericInstanceMethod = (GenericInstanceMethod)originalMethodReference; var genericInstanceMethod = new GenericInstanceMethod(replacementMethod); foreach (var arg in originalGenericInstanceMethod.GenericArguments) { genericInstanceMethod.GenericArguments.Add(arg); } call.Operand = ModuleDefinition.ImportReference(genericInstanceMethod); } else { call.Operand = replacementMethod; } } body.InitLocals = true; body.OptimizeMacros(); }
protected virtual void WriteGenericInstanceMethod(GenericInstanceMethod genericMethod) { MethodReference method = genericMethod.ElementMethod; string methodName = GetMethodName(method); WriteReference(methodName, method); if (genericMethod.HasAnonymousArgument()) { return; } WriteToken(GenericLeftBracket); Mono.Collections.Generic.Collection<TypeReference> arguments = genericMethod.GenericArguments; for (int i = 0; i < arguments.Count; i++) { if (i > 0) { WriteToken(","); WriteSpace(); } WriteReferenceAndNamespaceIfInCollision(arguments[i]); } WriteToken(GenericRightBracket); return; }
public TypeResolver(GenericInstanceMethod methodDefinitionContext) { _methodDefinitionContext = methodDefinitionContext; }
/// <summary> /// This method resolves a generic instance method. /// </summary> /// <param name="hostModule">The module in which the changes are made.</param> /// <param name="method">The generic instance method to resolve.</param> /// <param name="AddedClasses">Newly added types to lookup while resolving.</param> /// <param name="AddedMethods">Newly added methods to lookup while resolving.</param> /// <param name="TypesMap">A map of types to lookup while resolving.</param> /// <returns>The resolved generic instance method.</returns> protected static GenericInstanceMethod Resolve( ModuleDefinition hostModule, GenericInstanceMethod method, Dictionary<TypeReference, TypeDefinition> AddedClasses, Dictionary<MethodReference, MethodDefinition> AddedMethods, Dictionary<TypeReference, TypeReference> TypesMap) { if (AddedMethods.ContainsKey(method)) return (GenericInstanceMethod)((MethodReference)AddedMethods[method]); //hostModule.Import( MethodReference elementMethod = Resolve(hostModule, method.ElementMethod, AddedClasses, AddedMethods, TypesMap); GenericInstanceMethod newReference = new GenericInstanceMethod(elementMethod); foreach (TypeReference type in method.GenericArguments) { TypeReference newType = Resolve(hostModule, type, AddedClasses, TypesMap); newReference.GenericArguments.Add(newType); } if (method.ReturnType is GenericParameter) { GenericParameter g = (GenericParameter)method.ReturnType; newReference.ReturnType = elementMethod.GenericParameters[g.Position]; } return newReference; }
internal TypeResolver Nested(GenericInstanceMethod genericInstanceMethod) { return(new TypeResolver(_typeDefinitionContext as GenericInstanceType, genericInstanceMethod)); }