Inheritance: System.Type
		public void CreateProxiedMethod(FieldInfo field, MethodInfo method, TypeBuilder typeBuilder)
		{
			const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig |
																								MethodAttributes.Virtual;
			ParameterInfo[] parameters = method.GetParameters();

			MethodBuilder methodBuilder = typeBuilder.DefineMethod(method.Name, methodAttributes,
			                                                       CallingConventions.HasThis, method.ReturnType,
			                                                       parameters.Select(param => param.ParameterType).ToArray());

			System.Type[] typeArgs = method.GetGenericArguments();

			if (typeArgs.Length > 0)
			{
				var typeNames = new List<string>();

				for (int index = 0; index < typeArgs.Length; index++)
				{
					typeNames.Add(string.Format("T{0}", index));
				}

				methodBuilder.DefineGenericParameters(typeNames.ToArray());
			}

			ILGenerator IL = methodBuilder.GetILGenerator();

			Debug.Assert(MethodBodyEmitter != null);
			MethodBodyEmitter.EmitMethodBody(IL, method, field);
		}
Exemplo n.º 2
0
 public static void Clear()
 {
     _dynamicAssembly = null;
     _moduleBuilder = null;
     _typeBuilder = null;
     _accessorList.Clear();
 }
Exemplo n.º 3
0
 // Constructs a PropertyBuilder.  
 //
 internal PropertyBuilder(
     ModuleBuilder       mod,            // the module containing this PropertyBuilder
     String              name,           // property name
     SignatureHelper     sig,            // property signature descriptor info
     PropertyAttributes  attr,           // property attribute such as DefaultProperty, Bindable, DisplayBind, etc
     Type                returnType,     // return type of the property.
     PropertyToken       prToken,        // the metadata token for this property
     TypeBuilder         containingType) // the containing type
 {
     if (name == null)
         throw new ArgumentNullException("name");
     if (name.Length == 0)
         throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
     if (name[0] == '\0')
         throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name");
     Contract.EndContractBlock();
     
     m_name = name;
     m_moduleBuilder = mod;
     m_signature = sig;
     m_attributes = attr;
     m_returnType = returnType;
     m_prToken = prToken;
     m_tkProperty = prToken.Token;
     m_containingType = containingType;
 }
Exemplo n.º 4
0
        public override void GenerateCode(ILGenerator codeGenerator, TypeBuilder typeBuilder, ModuleBuilder moduleBuilder)
        {
            LeftOperand.GenerateCode(codeGenerator, typeBuilder, moduleBuilder);
            RightOperand.GenerateCode(codeGenerator, typeBuilder, moduleBuilder);

            Label endLabel = codeGenerator.DefineLabel();
            Label trueLabel = codeGenerator.DefineLabel();

            if (LeftOperand.ReturnType == StringType.StringInstance)
            {
                codeGenerator.Emit(OpCodes.Call, typeof(String).GetMethod("CompareTo", new Type[] { typeof(string) }));
                codeGenerator.Emit(OpCodes.Ldc_I4_0);
                codeGenerator.Emit(OpCodes.Bne_Un, trueLabel);
            }
            else
                codeGenerator.Emit(OpCodes.Bne_Un, trueLabel);

            codeGenerator.Emit(OpCodes.Ldc_I4_0);
            codeGenerator.Emit(OpCodes.Br, endLabel);

            codeGenerator.MarkLabel(trueLabel);
            codeGenerator.Emit(OpCodes.Ldc_I4_1);

            codeGenerator.MarkLabel(endLabel);
        }
Exemplo n.º 5
0
        public CodeGenerator(Expression pExpression, String pModuleName, ref LogHandler rLogHandler)
        {
            _symbolTable  = new Dictionary <String, Emit.LocalBuilder>();
            _assemblyName = new Reflect.AssemblyName(Path.GetFileNameWithoutExtension(pModuleName));

            _statement = pExpression;

            //Init Assembly
            _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, Emit.AssemblyBuilderAccess.Save);
            _moduleBuilder   = _assemblyBuilder.DefineDynamicModule(pModuleName);
            _typeBuilder     = _moduleBuilder.DefineType("PascalCompilerType");
            _methodBuilder   = _typeBuilder.DefineMethod
                               (
                "Main",
                Reflect.MethodAttributes.Static,
                typeof(void),
                Type.EmptyTypes
                               );
            _ilGenerator = _methodBuilder.GetILGenerator();

            //Actual Work
            GenerateStatement(_statement, null);
            _ilGenerator.Emit(Emit.OpCodes.Ret);

            //Finalizing Work
            _typeBuilder.CreateType();
            _moduleBuilder.CreateGlobalFunctions();
            _assemblyBuilder.SetEntryPoint(_methodBuilder);
            _assemblyBuilder.Save(pModuleName);
        }
Exemplo n.º 6
0
        public override void GenerateCode(ILGenerator generator, TypeBuilder typeBuilder)
        {
            // Declarando la etiqueta.
            Label end = generator.DefineLabel();

            //Generamos el codigo de la izquierda
            Left.GenerateCode(generator, typeBuilder);

            //Devuelve '1' en la pila si el valor de Left es distinto de cero.
            CheckIfEqualToZero(generator);
            //Guardamos el resultado en una variable, por si se salta no perderlo
            var result = generator.DeclareLocal(typeof (int));
            GetValueFromStack(generator, result);

            //Si fue igual a 1 (true), saltamos hacia el final
            generator.Emit(OpCodes.Brtrue, end);

            //Sino, Generamos el codigo de la derecha
            Right.GenerateCode(generator, typeBuilder);

            //Si llegamos aqui, entonces el resultado sera el del operador derecho (si es 1 => 1)
            CheckIfEqualToZero(generator);
            //Guardamos el resultado en la variable
            GetValueFromStack(generator, result);

            //Haciendo 'backpatch'
            generator.MarkLabel(end);

            //Guardamos el resultado en la pila
            generator.Emit(OpCodes.Ldloc, result);
        }
Exemplo n.º 7
0
#pragma warning restore 169, 414

		internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt)
		{
			this.name = name;
			this.attrs = attributes;
			this.call_conv = callingConvention;
			this.rtype = returnType;
			this.returnModReq = returnModReq;
			this.returnModOpt = returnModOpt;
			this.paramModReq = paramModReq;
			this.paramModOpt = paramModOpt;
			// The MSDN docs does not specify this, but the MS MethodBuilder
			// appends a HasThis flag if the method is not static
			if ((attributes & MethodAttributes.Static) == 0)
 				this.call_conv |= CallingConventions.HasThis;
			if (parameterTypes != null) {
				for (int i = 0; i < parameterTypes.Length; ++i)
					if (parameterTypes [i] == null)
						throw new ArgumentException ("Elements of the parameterTypes array cannot be null", "parameterTypes");

				this.parameters = new Type [parameterTypes.Length];
				System.Array.Copy (parameterTypes, this.parameters, parameterTypes.Length);
			}
			type = tb;
			table_idx = get_next_table_index (this, 0x06, true);

			((ModuleBuilder)tb.Module).RegisterToken (this, GetToken ().Token);
		}
Exemplo n.º 8
0
        private void ImplementInterfaceProperties(Type interfaceOfTypeToCreate, System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            typeBuilder.AddInterfaceImplementation(interfaceOfTypeToCreate);
            foreach (var implementedInterfaceType in interfaceOfTypeToCreate.GetInterfaces())
            {
                ImplementInterfaceProperties(implementedInterfaceType, typeBuilder);
            }

            foreach (var pi in interfaceOfTypeToCreate.GetProperties())
            {
                var backingFieldBuilder = typeBuilder.DefineField($"{interfaceOfTypeToCreate.Name}._{ToCamelCase(pi.Name)}", pi.PropertyType, FieldAttributes.Private);

                var accessorAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual | MethodAttributes.HideBySig;

                var mbGetAccessor = typeBuilder.DefineMethod($"get_{pi.Name}", accessorAttributes, pi.PropertyType, Type.EmptyTypes);
                var mbGetIL       = mbGetAccessor.GetILGenerator();
                mbGetIL.Emit(OpCodes.Ldarg_0);
                mbGetIL.Emit(OpCodes.Ldfld, backingFieldBuilder);
                mbGetIL.Emit(OpCodes.Ret);

                var mbSetAccessor = typeBuilder.DefineMethod($"set_{pi.Name}", accessorAttributes, null, new[] { pi.PropertyType });
                var mbSetIL       = mbSetAccessor.GetILGenerator();
                mbSetIL.Emit(OpCodes.Ldarg_0);
                mbSetIL.Emit(OpCodes.Ldarg_1);
                mbSetIL.Emit(OpCodes.Stfld, backingFieldBuilder);
                mbSetIL.Emit(OpCodes.Ret);

                var propertyBuilder = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.HasDefault, pi.PropertyType, null);
                propertyBuilder.SetGetMethod(mbGetAccessor);
                propertyBuilder.SetSetMethod(mbSetAccessor);
            }
        }
Exemplo n.º 9
0
 public ILDynamicMethodDebugImpl(string name, Type delegateType, Type thisType)
 {
     _delegateType = delegateType;
     _expectedLength = 64;
     var mi = delegateType.GetMethod("Invoke");
     var uniqueName = ILDynamicTypeDebugImpl.UniqueName(name);
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(uniqueName), AssemblyBuilderAccess.RunAndSave, DynamicILDirectoryPath.DynamicIL);
     _moduleBuilder = _assemblyBuilder.DefineDynamicModule(uniqueName + ".dll", true);
     var sourceCodeFileName = Path.Combine(DynamicILDirectoryPath.DynamicIL, uniqueName + ".il");
     _symbolDocumentWriter = _moduleBuilder.DefineDocument(sourceCodeFileName, SymDocumentType.Text, SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
     _sourceCodeWriter = new SourceCodeWriter(sourceCodeFileName, _symbolDocumentWriter);
     Type[] parameterTypes;
     if (thisType != null)
     {
         parameterTypes = new[] { thisType }.Concat(mi.GetParameters().Select(pi => pi.ParameterType)).ToArray();
     }
     else
     {
         parameterTypes = mi.GetParameters().Select(pi => pi.ParameterType).ToArray();
     }
     _sourceCodeWriter.StartMethod(name, mi.ReturnType, parameterTypes, MethodAttributes.Static);
     _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, typeof(object), Type.EmptyTypes);
     _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder);
     _dynamicMethod = _typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Static, mi.ReturnType, parameterTypes);
     for (int i = 0; i < parameterTypes.Length; i++)
     {
         _dynamicMethod.DefineParameter(i + 1, ParameterAttributes.In, string.Format("arg{0}", i));
     }
 }
Exemplo n.º 10
0
#pragma warning restore 169, 414

		internal EventBuilder (TypeBuilder tb, string eventName, EventAttributes eventAttrs, Type eventType) {
			name = eventName;
			attrs = eventAttrs;
			type = eventType;
			typeb = tb;
			table_idx = get_next_table_index (this, 0x14, true);
		}
Exemplo n.º 11
0
 public MethodGen(Emit.TypeBuilder typeBuilder, Collections.Dictionary <string, Emit.FieldBuilder> typefieldList, string dllProbeDirectory, TypeGen parent)
 {
     this.typeBuilder       = typeBuilder;
     this.dllProbeDirectory = dllProbeDirectory;
     this.typefieldList     = typefieldList;
     this.parent            = parent;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeBuilderHelper"/> class
        /// with the specified parameters.
        /// </summary>
        /// <param name="assemblyBuilder">Associated <see cref="AssemblyBuilderHelper"/>.</param>
        /// <param name="typeBuilder">A <see cref="TypeBuilder"/></param>
        public TypeBuilderHelper(AssemblyBuilderHelper assemblyBuilder, System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            Assembly    = assemblyBuilder ?? throw new ArgumentNullException(nameof(assemblyBuilder));
            TypeBuilder = typeBuilder ?? throw new ArgumentNullException(nameof(typeBuilder));

            TypeBuilder.SetCustomAttribute(Assembly.ReflectionExtensionsAttribute);
        }
Exemplo n.º 13
0
		private FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties)
		{
			FieldInfo[] array = new FieldBuilder[properties.Length];
			for (int i = 0; i < properties.Length; i++)
			{
				DynamicProperty dynamicProperty = properties[i];
				FieldBuilder fieldBuilder = tb.DefineField("_" + dynamicProperty.Name, dynamicProperty.Type, FieldAttributes.Private);
				PropertyBuilder propertyBuilder = tb.DefineProperty(dynamicProperty.Name, PropertyAttributes.HasDefault, dynamicProperty.Type, null);
				MethodBuilder methodBuilder = tb.DefineMethod("get_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, dynamicProperty.Type, Type.EmptyTypes);
				ILGenerator iLGenerator = methodBuilder.GetILGenerator();
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
				iLGenerator.Emit(OpCodes.Ret);
				MethodBuilder methodBuilder2 = tb.DefineMethod("set_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, null, new Type[]
				{
					dynamicProperty.Type
				});
				ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldarg_1);
				iLGenerator2.Emit(OpCodes.Stfld, fieldBuilder);
				iLGenerator2.Emit(OpCodes.Ret);
				propertyBuilder.SetGetMethod(methodBuilder);
				propertyBuilder.SetSetMethod(methodBuilder2);
				array[i] = fieldBuilder;
			}
			return array;
		}
Exemplo n.º 14
0
        private static void ImplementInterfaceMethod(TypeBuilder newType, MethodInfo interfaceMethod)
        {
            ParameterInfo[] parameters = interfaceMethod.GetParameters();
            Type[] parameterTypes = new Type[parameters.Length];
            for (int idx = 0; idx < parameters.Length; idx++)
                parameterTypes[idx] = parameters[idx].ParameterType;

            MethodBuilder newMethod = newType.DefineMethod(
                interfaceMethod.DeclaringType.Name + "." + interfaceMethod.Name,
                MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
                interfaceMethod.ReturnType, parameterTypes
            );

            MethodInfo baseMethod = newType.BaseType.GetMethod(interfaceMethod.Name, parameterTypes);

            for (int i = 0; i < parameters.Length; i++)
                newMethod.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);

            ILGenerator ilGen = newMethod.GetILGenerator();

            for (int i = 0; i <= parameterTypes.Length; i++)
                ilGen.Emit(OpCodes.Ldarg_S, (byte)i);

            ilGen.Emit(OpCodes.Call, baseMethod);
            ilGen.Emit(OpCodes.Ret);

            newType.DefineMethodOverride(newMethod, interfaceMethod);
        }
Exemplo n.º 15
0
        private static FieldInfo[] GenerateProperties(TypeBuilder tb, IDictionary<string, Type> properties)
        {
            const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            FieldInfo[] fields = new FieldBuilder[properties.Count];
            int i = 0;
            foreach (string key in properties.Keys)
            {
                string name = key;
                Type type = properties[key];
                FieldBuilder fb = tb.DefineField("_" + key, type, FieldAttributes.Public);
                PropertyBuilder pb = tb.DefineProperty(key, PropertyAttributes.HasDefault, type, null);
                
                MethodBuilder mbGet = tb.DefineMethod("get_" + name, getSetAttr, type, Type.EmptyTypes);
                ILGenerator genGet = mbGet.GetILGenerator(8);
                genGet.Emit(OpCodes.Ldarg_0);
                genGet.Emit(OpCodes.Ldfld, fb);
                genGet.Emit(OpCodes.Ret);
                pb.SetGetMethod(mbGet);

                MethodBuilder mbSet = tb.DefineMethod("set_" + name, getSetAttr, null, new Type[] { type });
                ILGenerator genSet = mbSet.GetILGenerator(8);
                genSet.Emit(OpCodes.Ldarg_0);
                genSet.Emit(OpCodes.Ldarg_1);
                genSet.Emit(OpCodes.Stfld, fb);
                genSet.Emit(OpCodes.Ret);
                pb.SetSetMethod(mbSet);

                fields[i] = fb;
            }

            return fields;
        }
		public AbstractProxyBuilder(ModuleBuilder moduleBuilder, string className, Type interfaceType, Type innerType)
		{
			Verify.ArgumentNotNull(moduleBuilder, "moduleBuilder");
			Verify.ArgumentNotNull(className, "className");
			Verify.ArgumentNotNull(interfaceType, "interfaceType");
			Verify.ArgumentNotNull(innerType, "innerType");

			if (!interfaceType.IsInterface) {
				throw new ArgumentException("must be an interface type", "interfaceType");
			}

			_errorMessages = new List<string>();
			_moduleBuilder = moduleBuilder;
			_className = className;
			_interfaceType = interfaceType;
			_innerType = innerType;

			_typeBuilder = _moduleBuilder.DefineType(
				_className,
				TypeAttributes.Public |
				TypeAttributes.Class |
				TypeAttributes.AutoClass |
				TypeAttributes.AnsiClass |
				TypeAttributes.BeforeFieldInit |
				TypeAttributes.AutoLayout,
				typeof(object),
				new Type[] {_interfaceType});

			_innerFieldBuilder = _typeBuilder.DefineField("inner", _innerType, FieldAttributes.Private);
		}
 public InterfaceImplementation(
     TypeBuilder typeBuilder,
     Type @interface,
     FieldBuilder proxyInterceptionPipelineField,
     bool explicitImplementation)
     : this(typeBuilder, @interface, proxyInterceptionPipelineField, explicitImplementation, null)
 { }
		public void ImplementProxy(TypeBuilder typeBuilder)
		{
			typeBuilder.AddInterfaceImplementation(typeof (IProxy));
			InterceptorField = typeBuilder
				.DefineField("__interceptor",
							 typeof (Proxy.DynamicProxy.IInterceptor),
							 FieldAttributes.Private);
			var getterMethod = typeBuilder
				.DefineMethod("get_Interceptor",
							  InterceptorMethodsAttributes,
							  CallingConventions.HasThis,
							  typeof (Proxy.DynamicProxy.IInterceptor),
							  new System.Type[0]);
			getterMethod.SetImplementationFlags(MethodImplAttributes.IL);
			var il = getterMethod.GetILGenerator();
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldfld, InterceptorField);
			il.Emit(OpCodes.Ret);
			var setterMethod = typeBuilder
				.DefineMethod("set_Interceptor",
							  InterceptorMethodsAttributes,
							  CallingConventions.HasThis,
							  typeof (void),
							  new[] {typeof (Proxy.DynamicProxy.IInterceptor)});
			setterMethod.SetImplementationFlags(MethodImplAttributes.IL);
			il = setterMethod.GetILGenerator();
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldarg_1);
			il.Emit(OpCodes.Stfld, InterceptorField);
			il.Emit(OpCodes.Ret);
			var originalSetter = typeof (IProxy).GetMethod("set_Interceptor");
			var originalGetter = typeof (IProxy).GetMethod("get_Interceptor");
			typeBuilder.DefineMethodOverride(setterMethod, originalSetter);
			typeBuilder.DefineMethodOverride(getterMethod, originalGetter);
		}
Exemplo n.º 19
0
        private void CompileMainClass(Node ActiveNode)
        {
            Emit.TypeBuilder _TypeBuilder =
                TypeTable[ActiveNode.Nodes[1].Value];

            Emit.MethodBuilder MethBuilder = _TypeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
            this.AssemblerGenerator = MethBuilder.GetILGenerator();
            CurrentType             = _TypeBuilder;
            OpenBlockVariables();
            CreateCode(ActiveNode.Nodes[14]);


            CreateCode(ActiveNode.Nodes[15]);
            CloseBlockVariables();
            // Отладочные команды
            AssemblerGenerator.Emit(Emit.OpCodes.Ldstr, "Programm was finished. Press Enter key to quit...");
            AssemblerGenerator.Emit(Emit.OpCodes.Call,
                                    typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
            AssemblerGenerator.Emit(Emit.OpCodes.Call,
                                    typeof(System.Console).GetMethod("ReadLine", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { }, null));
            AssemblerGenerator.Emit(Emit.OpCodes.Pop);
            AssemblerGenerator.Emit(Emit.OpCodes.Ret);

            CreatedTypeTable[ActiveNode.Nodes[1].Value] = _TypeBuilder.CreateType();

            ModBuilder.CreateGlobalFunctions();
            AsmBuilder.SetEntryPoint(MethBuilder);
        }
        /// <summary>
        /// Creates a <see cref="MethodBuilder"/> and implements a default wrapper.
        /// </summary>
        /// <param name="owner">The type that will own this method.</param>
        /// <param name="interfaceType">Type of interface implemented by the <paramref name="owner"/>.</param>
        /// <param name="overrideMethod">Method to override.</param>
        /// <param name="fieldBuilders">Fields specified by the <see paramref="owner"/>.</param>
        /// <returns>MethodBuilder with an already implemented wrapper.</returns>
        public MethodBuilder GenerateInvocation(TypeBuilder owner, Type interfaceType, MethodInfo overrideMethod, IEnumerable<FieldBuilder> fieldBuilders)
        {
            var result = owner.DefineMethod
                    (
                        overrideMethod.Name,
                        MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final |
                        MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                        overrideMethod.ReturnType,
                        overrideMethod.GetParameters().OrderBy(p => p.Position).Select(t => t.ParameterType).ToArray()
                    );

            result.SetImplementationFlags(MethodImplAttributes.AggressiveInlining);

            var generator = result.GetILGenerator();
            var fieldName = LibraryInterfaceMapper.GetFieldNameForMethodInfo(overrideMethod);
            var field = fieldBuilders.First(f => f.Name == fieldName);
            var parameters = overrideMethod.GetParameters();
            OnInvokeBegin(owner, interfaceType, generator, overrideMethod);
            generator.Emit(OpCodes.Ldarg_0); //  this
            generator.Emit(OpCodes.Ldfld, field); // MethodNameProc _glMethodName. Initialized by constructor.
            foreach (var item in parameters.Where(p => !p.IsRetval).Select((p, i) => new { Type = p, Index = i }))
            {
                generator.Emit(OpCodes.Ldarg, item.Index + 1);
            }

            generator.EmitCall(OpCodes.Callvirt, field.FieldType.GetMethod("Invoke"), null);

            OnInvokeEnd(owner, interfaceType, generator, overrideMethod);

            generator.Emit(OpCodes.Ret);

            owner.DefineMethodOverride(result, overrideMethod);

            return result;
        }
Exemplo n.º 21
0
        private static void BuildStringProperty(TypeBuilder typeBuilder, string property)
        {
            //implement properties from interface
            FieldBuilder fieldBuilder = typeBuilder.DefineField(property.ToLower(), typeof(string), FieldAttributes.Private);
            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(property, PropertyAttributes.HasDefault, typeof(string), null);
            const MethodAttributes getSetAttributes = MethodAttributes.Public | MethodAttributes.SpecialName |
                                                      MethodAttributes.HideBySig | MethodAttributes.Virtual;
            //define 'get' accessor
            MethodBuilder getPropertyBuilder = typeBuilder.DefineMethod("get_" + property, getSetAttributes, typeof(string),
                                                                        Type.EmptyTypes);
            //create IL code for get
            ILGenerator genusGetIL = getPropertyBuilder.GetILGenerator();
            genusGetIL.Emit(OpCodes.Ldarg_0);
            genusGetIL.Emit(OpCodes.Ldfld, fieldBuilder);
            genusGetIL.Emit(OpCodes.Ret);

            //define 'set' accessor
            MethodBuilder setPropertyBuilder = typeBuilder.DefineMethod("set_" + property, getSetAttributes, null,
                                                                        new[] { typeof(String) });
            //create IL code for set
            ILGenerator genusSetIL = setPropertyBuilder.GetILGenerator();
            genusSetIL.Emit(OpCodes.Ldarg_0);
            genusSetIL.Emit(OpCodes.Ldarg_1);
            genusSetIL.Emit(OpCodes.Stfld, fieldBuilder);
            genusSetIL.Emit(OpCodes.Ret);

            //map get and set to property 'methods'
            propertyBuilder.SetGetMethod(getPropertyBuilder);
            propertyBuilder.SetSetMethod(setPropertyBuilder);
        }
Exemplo n.º 22
0
    public CodeGen(Stmt stmt, string moduleName)
    {
        if (IO.Path.GetFileName(moduleName) != moduleName)
        {
            throw new System.Exception("can only output into current directory!");
        }

        Reflect.AssemblyName name        = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName));
        Emit.AssemblyBuilder asmb        = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save);
        Emit.ModuleBuilder   modb        = asmb.DefineDynamicModule(moduleName);
        Emit.TypeBuilder     typeBuilder = modb.DefineType("Foo");

        Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);

        // CodeGenerator
        this.il          = methb.GetILGenerator();
        this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>();

        // Go Compile!
        this.GenStmt(stmt);

        il.Emit(Emit.OpCodes.Ret);
        typeBuilder.CreateType();
        modb.CreateGlobalFunctions();
        asmb.SetEntryPoint(methb);
        asmb.Save(moduleName);
        this.symbolTable = null;
        this.il          = null;
    }
Exemplo n.º 23
0
 private static FieldBuilder CréeAttributs(TypeBuilder constructeurDeType, DataColumn colonne)
 {
     FieldBuilder champBldr = null;
     PropertyBuilder constructeurPropriété;
     #region Création de l'attribut
     champBldr = constructeurDeType.DefineField(colonne.ColumnName.ToLower(), colonne.DataType, FieldAttributes.Private);
     #endregion
     #region Création de la Propriété associée
     constructeurPropriété = constructeurDeType.DefineProperty(colonne.ColumnName, System.Reflection.PropertyAttributes.HasDefault, colonne.DataType, null);
     // Choix des attributs
     MethodAttributes attrGetSet = MethodAttributes.Public |
        MethodAttributes.SpecialName | MethodAttributes.HideBySig;
     #region Définition du "getter".
     MethodBuilder constructeurGet = constructeurDeType.DefineMethod("get_" + colonne.ColumnName, attrGetSet, colonne.DataType, Type.EmptyTypes);
     ILGenerator champGetIL = constructeurGet.GetILGenerator();
     champGetIL.Emit(OpCodes.Ldarg_0);
     champGetIL.Emit(OpCodes.Ldfld, champBldr);
     champGetIL.Emit(OpCodes.Ret);
     #endregion
     #region Définition du "setter".
     MethodBuilder constructeurSet = constructeurDeType.DefineMethod("set_" + colonne.ColumnName, attrGetSet, null, new Type[] { colonne.DataType });
     ILGenerator champSetIL = constructeurSet.GetILGenerator();
     champSetIL.Emit(OpCodes.Ldarg_0);
     champSetIL.Emit(OpCodes.Ldarg_1);
     champSetIL.Emit(OpCodes.Stfld, champBldr);
     champSetIL.Emit(OpCodes.Ret);
     #endregion
     #region Association des accesseurs à la propriété
     constructeurPropriété.SetGetMethod(constructeurGet);
     constructeurPropriété.SetSetMethod(constructeurSet);
     #endregion
     #endregion
     return champBldr;
     }
Exemplo n.º 24
0
		public void ImplementProxy(TypeBuilder typeBuilder)
		{
			// Implement the IProxy interface
			typeBuilder.AddInterfaceImplementation(typeof (IProxy));

			field = typeBuilder.DefineField("__interceptor", typeof (IInterceptor), FieldAttributes.Private);

			// Implement the getter
			MethodBuilder getterMethod = typeBuilder.DefineMethod("get_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof(IInterceptor), new System.Type[0]);
			getterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL);

			ILGenerator IL = getterMethod.GetILGenerator();

			// This is equivalent to:
			// get { return __interceptor;
			IL.Emit(OpCodes.Ldarg_0);
			IL.Emit(OpCodes.Ldfld, field);
			IL.Emit(OpCodes.Ret);

			// Implement the setter
			MethodBuilder setterMethod = typeBuilder.DefineMethod("set_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof (void), new[] {typeof (IInterceptor)});

			setterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL);
			IL = setterMethod.GetILGenerator();
			IL.Emit(OpCodes.Ldarg_0);
			IL.Emit(OpCodes.Ldarg_1);
			IL.Emit(OpCodes.Stfld, field);
			IL.Emit(OpCodes.Ret);

			MethodInfo originalSetter = typeof (IProxy).GetMethod("set_Interceptor");
			MethodInfo originalGetter = typeof (IProxy).GetMethod("get_Interceptor");

			typeBuilder.DefineMethodOverride(setterMethod, originalSetter);
			typeBuilder.DefineMethodOverride(getterMethod, originalGetter);
		}
Exemplo n.º 25
0
		public static MethodBuilder GenerateStaticSerializerStub(TypeBuilder tb, Type type)
		{
			var mb = tb.DefineMethod("Serialize", MethodAttributes.Public | MethodAttributes.Static, null, new Type[] { typeof(Stream), type });
			mb.DefineParameter(1, ParameterAttributes.None, "stream");
			mb.DefineParameter(2, ParameterAttributes.None, "value");
			return mb;
		}
Exemplo n.º 26
0
        private void DefineClassVaribale(Emit.TypeBuilder typeBuilder, TypeDeclaration _type)
        {
            fieldList = new Dictionary <string, Emit.FieldBuilder>();
            Emit.FieldBuilder classVariable;
            foreach (KeyValuePair <string, Type> para in _type.instanceVariable)
            {
                classVariable = typeBuilder.DefineField(para.Key,
                                                        para.Value,
                                                        FieldAttributes.Private);
                fieldList.Add(para.Key, classVariable);
            }
            foreach (KeyValuePair <string, Type> para in _type.classVariable)
            {
                classVariable = typeBuilder.DefineField(para.Key,
                                                        para.Value,
                                                        FieldAttributes.Private | FieldAttributes.Static);

                fieldList.Add(para.Key, classVariable);
            }

            //mthdIL.Emit(OpCodes.Ldarg_0);
            //mthdIL.Emit(OpCodes.Ldarg_0);
            //mthdIL.Emit(OpCodes.Ldfld, balanceAmtBldr);
            //mthdIL.Emit(OpCodes.Ldarg_2);
            //mthdIL.Emit(OpCodes.Add);
        }
Exemplo n.º 27
0
 public TypeGen(TypeDeclaration typeDec, Emit.ModuleBuilder modb, string dllProbeDirectory, AssemblyGen parent)
 {
     methodList   = new List <System.Reflection.Emit.MethodBuilder>();
     typeBuilder  = modb.DefineType(typeDec.TypeName, TypeAttributes.Public);
     this.parent  = parent;
     this.typeDec = typeDec;
 }
 /// <summary>
 /// Creates a new instance of the method builder.
 /// </summary>
 /// <param name="typeBuilder">The type builder to use.</param>
 /// <param name="aopProxyGenerator">
 /// The <see cref="IAopProxyTypeGenerator"/> implementation to use.
 /// </param>
 /// <param name="targetMethods">
 /// 
 /// </param>
 /// <param name="index">index of the introduction to delegate call to</param>
 public IntroductionProxyMethodBuilder(
     TypeBuilder typeBuilder, IAopProxyTypeGenerator aopProxyGenerator,
     IDictionary targetMethods, int index)
     : base(typeBuilder, aopProxyGenerator, true, targetMethods)
 {
     this.index = index;
 }
Exemplo n.º 29
0
        public static void DefineInterface(TypeBuilder typeBuilder, Type interfaceType, Type implementType,
            Action<ILGenerator, MethodInfo, MethodInfo> ilGenerator)
        {
            var proxyMethodBuilder = new ProxyMethodBuilder(typeBuilder);
            InterfaceMapping mapping = implementType.GetInterfaceMap(interfaceType);
            for (int i = 0; i < mapping.InterfaceMethods.Length; i++)
                mapping.TargetMethods[i] = proxyMethodBuilder.DefineMethod(mapping.InterfaceMethods[i],
                    il => ilGenerator(il, mapping.InterfaceMethods[i], mapping.TargetMethods[i]));

            foreach (PropertyInfo propertyInfo in interfaceType.GetProperties())
            {
                MethodBuilder getMethodBuilder = null;
                MethodInfo getMethodInfo = propertyInfo.GetGetMethod();
                if (getMethodInfo != null)
                    getMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, getMethodInfo);

                MethodBuilder setMethodBuilder = null;
                MethodInfo setMethodInfo = propertyInfo.GetSetMethod();
                if (setMethodInfo != null)
                    setMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, setMethodInfo);

                ProxyBuilderHelper.DefineProperty(typeBuilder, propertyInfo, getMethodBuilder, setMethodBuilder);
            }

            foreach (EventInfo eventInfo in interfaceType.GetEvents())
            {
                var addMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, eventInfo.GetAddMethod());
                var removeMethodBuilder = (MethodBuilder)GetTargetMethodInfo(ref mapping, eventInfo.GetRemoveMethod());
                ProxyBuilderHelper.DefineEvent(typeBuilder, eventInfo, addMethodBuilder, removeMethodBuilder);
            }
        }
 public Type CreateType(TypeBuilder typeBuilder)
 {
     Type proxyType = typeBuilder.CreateType();
     ((AssemblyBuilder)typeBuilder.Assembly).Save("ProxyAssembly.dll");
     AssemblyAssert.IsValidAssembly("ProxyAssembly.dll");
     return proxyType;
 }
Exemplo n.º 31
0
 /// <summary>
 /// 动态创建类的属性
 /// </summary>
 /// <param name="tb">承载该属性的类型</param>
 /// <param name="properityName">属性名,首字母应大写</param>
 /// <param name="properityType">属性数据类型</param>
 public static FieldBuilder createProperty(TypeBuilder tb, string propertyName, Type propertyType)
 {
     //定义属性对应的私有字段
     FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
     //定义属性
     PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
     //定义与属性相关的get方法
     MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
         MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
         propertyType,
         Type.EmptyTypes);
     ILGenerator getIL = getPropMthdBldr.GetILGenerator();//获取il 生成器
     getIL.Emit(OpCodes.Ldarg_0);
     getIL.Emit(OpCodes.Ldfld, fieldBuilder);
     getIL.Emit(OpCodes.Ret);
     //定义与属性相关的set方法
     MethodBuilder setPropMthdBldr = tb.DefineMethod("set_" + propertyName,
         MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
         null, new Type[] { propertyType });
     ILGenerator setIL = setPropMthdBldr.GetILGenerator();
     /*
      * OpCodes.Ldarg_0:Ldarg是加载方法参数的意思。这里Ldarg_0事实上是对当前对象的引用即this。
      * 因为类的实例方法(非静态方法)在调用时,this 是会作为第一个参数传入的。
      */
     setIL.Emit(OpCodes.Ldarg_0);
     setIL.Emit(OpCodes.Ldarg_1);//OpCodes.Ldarg_1:加载参数列表的第一个参数了。
     setIL.Emit(OpCodes.Stfld, fieldBuilder);//OpCodes.Stfld:用新值替换在对象引用或指针的字段中存储的值。
     setIL.Emit(OpCodes.Ret);
     //把get/set方法和属性联系起来
     propertyBuilder.SetGetMethod(getPropMthdBldr);
     propertyBuilder.SetSetMethod(setPropMthdBldr);
     return fieldBuilder;
 }
Exemplo n.º 32
0
        private static void CreateProperty(string name, TypeBuilder tb, MethodInfo bgcmi, MethodInfo bscmi)
        {
            // define getter
            var gmb = tb.DefineMethod("get_" + name,
                MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                typeof(string),
                null);

            var g = gmb.GetILGenerator();
            g.Emit(OpCodes.Ldarg_0);
            g.Emit(OpCodes.Ldstr, name);
            g.Emit(OpCodes.Call, bgcmi);
            g.Emit(OpCodes.Ret);

            // define setter
            var smb = tb.DefineMethod("set_" + name,
                MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                null,
                new Type[] { typeof(string) });

            g = smb.GetILGenerator();
            g.Emit(OpCodes.Ldarg_0);
            g.Emit(OpCodes.Ldstr, name);
            g.Emit(OpCodes.Ldarg_1);
            g.Emit(OpCodes.Call, bscmi);
            g.Emit(OpCodes.Ret);

            // define properties
            var pb = tb.DefineProperty(name, PropertyAttributes.None, typeof(string), null);
            pb.SetGetMethod(gmb);
            pb.SetSetMethod(smb);
        }
        public static EventBrokerResolvedType ResolveType(IMemberMap<EventInfo> memberMap, TypeBuilder typeBuilder)
        {
            Type[] @params = null;
            Type delegateType = null;
            Type[] delegateParameters = null;
            var @event = memberMap.ContractMember;
            var declaringType = memberMap.ContractType;
            var invokeMethod = @event.GetInvokeMethod();
            var invokeReturnType = invokeMethod.ReturnType;
            var eventBrokerResolvedType = new EventBrokerResolvedType(@event) {
                DecalringType = declaringType
            };

            if (invokeMethod.GetDelegateParams(out @params, out delegateParameters)) {
                delegateType = @params.GetDelegateType(true);
                eventBrokerResolvedType.EventInterceptionContractArgs = @event.ToEventArgumentContract(@params);
                eventBrokerResolvedType.EventInterceptionArgs = declaringType.MakeGenericFunctionAspectArgsEvent(@params);
                eventBrokerResolvedType.EventBrokerBaseClassType = declaringType.MakeGenericEventBrokerBaseClassFunctionBinding(@params);
                eventBrokerResolvedType.EventBrokerInvokeDelegateType = typeof(Func<,>).MakeGenericType(new[] { eventBrokerResolvedType.EventInterceptionContractArgs, invokeReturnType });
            }
            else {
                delegateType = delegateParameters.GetDelegateType(false);
                eventBrokerResolvedType.EventInterceptionContractArgs = @event.ToEventArgumentContract(delegateParameters);
                eventBrokerResolvedType.EventInterceptionArgs = declaringType.MakeGenericActionAspectArgsEvent(delegateParameters);
                eventBrokerResolvedType.EventBrokerBaseClassType = declaringType.MakeGenericEventBrokerBaseClassActionType(delegateParameters);
                eventBrokerResolvedType.EventBrokerInvokeDelegateType = typeof(Action<>).MakeGenericType(new[] { eventBrokerResolvedType.EventInterceptionContractArgs });
            }

            eventBrokerResolvedType.Arguments = delegateParameters;
            eventBrokerResolvedType.EventBrokerFieldType = typeof(IEventBroker<>).MakeGenericType(delegateType);

            return eventBrokerResolvedType;
        }
Exemplo n.º 34
0
        private static void CreateProperty(System.Reflection.Emit.TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder   getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator     getIl           = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                                MethodAttributes.Public |
                                MethodAttributes.SpecialName |
                                MethodAttributes.HideBySig,
                                null, new[] { propertyType });

            ILGenerator setIl          = setPropMthdBldr.GetILGenerator();
            Label       modifyProperty = setIl.DefineLabel();
            Label       exitSet        = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
Exemplo n.º 35
0
		private FieldInfo[] GenerateProperties( TypeBuilder tb , DynamicProperty[] properties ) {
			FieldInfo[] fields = new FieldBuilder[properties.Length];
			for ( int i = 0 ; i < properties.Length ; i++ ) {
				DynamicProperty dp = properties[i];
				FieldBuilder fb = tb.DefineField( "_" + dp.Name , dp.Type , FieldAttributes.Private );
				PropertyBuilder pb = tb.DefineProperty( dp.Name , PropertyAttributes.HasDefault , dp.Type , null );
				MethodBuilder mbGet = tb.DefineMethod( "get_" + dp.Name ,
				                                       MethodAttributes.Public | MethodAttributes.SpecialName |
				                                       MethodAttributes.HideBySig ,
				                                       dp.Type , Type.EmptyTypes );
				ILGenerator genGet = mbGet.GetILGenerator();
				genGet.Emit( OpCodes.Ldarg_0 );
				genGet.Emit( OpCodes.Ldfld , fb );
				genGet.Emit( OpCodes.Ret );
				MethodBuilder mbSet = tb.DefineMethod( "set_" + dp.Name ,
				                                       MethodAttributes.Public | MethodAttributes.SpecialName |
				                                       MethodAttributes.HideBySig ,
				                                       null , new[] { dp.Type } );
				ILGenerator genSet = mbSet.GetILGenerator();
				genSet.Emit( OpCodes.Ldarg_0 );
				genSet.Emit( OpCodes.Ldarg_1 );
				genSet.Emit( OpCodes.Stfld , fb );
				genSet.Emit( OpCodes.Ret );
				pb.SetGetMethod( mbGet );
				pb.SetSetMethod( mbSet );
				fields[i] = fb;
			}
			return fields;
		}
Exemplo n.º 36
0
        private void GenerateFunction(TypeBuilder typeBuilder, out MethodBuilder methodBuilder)
        {
            methodBuilder = null;
            ProgramDeclBlock pdb = this.expr as ProgramDeclBlock;
            if (pdb != null)
            {
                foreach (var function in pdb.Statements)
                {
                    var functionDecl = function as BlockDeclExpr;
                    if (functionDecl != null)
                    {
                        bool isMain = functionDecl.IsMain;
                        var parameters = functionDecl.Parameters;

                        Expr mainFunctionParameters = null;

                        if (isMain)
                        {
                            mainFunctionParameters =
                                GenerateMainMethod(
                                    typeBuilder,
                                    functionDecl,
                                    parameters,
                                    mainFunctionParameters,
                                    out methodBuilder);
                        }
                    }
                }
            }
        }
Exemplo n.º 37
0
		public PropertyEmitter(TypeBuilder owner, string name, Type propertyType, FieldBuilder propertyChangedField) {
			this.owner = owner;
			this.propertyChangedField = propertyChangedField;
			fieldBuilder = owner.DefineField(String.Format("<{0}>", name), propertyType, FieldAttributes.Private);
			getterBuilder = owner.DefineMethod(String.Format("get_{0}", name), MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.HideBySig|MethodAttributes.SpecialName, propertyType, Type.EmptyTypes);
			ILGenerator getterIl = getterBuilder.GetILGenerator();
			getterIl.Emit(OpCodes.Ldarg_0);
			getterIl.Emit(OpCodes.Ldfld, fieldBuilder);
			getterIl.Emit(OpCodes.Ret);
			setterBuilder = owner.DefineMethod(String.Format("set_{0}", name), MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.HideBySig|MethodAttributes.SpecialName, typeof(void), new[] {propertyType});
			ILGenerator setterIl = setterBuilder.GetILGenerator();
			setterIl.Emit(OpCodes.Ldarg_0);
			setterIl.Emit(OpCodes.Ldarg_1);
			setterIl.Emit(OpCodes.Stfld, fieldBuilder);
			if (propertyChangedField != null) {
				setterIl.Emit(OpCodes.Ldarg_0);
				setterIl.Emit(OpCodes.Dup);
				setterIl.Emit(OpCodes.Ldfld, propertyChangedField);
				setterIl.Emit(OpCodes.Ldstr, name);
				setterIl.Emit(OpCodes.Call, proxyBase_NotifyPropertyChanged);
			}
			setterIl.Emit(OpCodes.Ret);
			propertyBuilder = owner.DefineProperty(name, PropertyAttributes.None, propertyType, null);
			propertyBuilder.SetGetMethod(getterBuilder);
			propertyBuilder.SetSetMethod(setterBuilder);
		}
Exemplo n.º 38
0
        static void DefineDelegateFieldAndOverride(TypeBuilder tb, int numArgs)
        {
            Type fieldType = FuncTypeHelpers.GetFFuncType(numArgs);
            string fieldName = "_fn" + numArgs;
            FieldBuilder fb = tb.DefineField(fieldName, fieldType, FieldAttributes.Public);

            MethodBuilder mb = tb.DefineMethod("invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, typeof(object), CreateObjectTypeArray(numArgs));
            ILGenerator gen = mb.GetILGenerator();

            Label eqLabel = gen.DefineLabel();

            //  this._fni == null ?
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, fb);
            gen.Emit(OpCodes.Ldnull);
            gen.Emit(OpCodes.Beq, eqLabel);
            //Not equal to Null, invoke it.
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, fb);
            for (int i = 0; i < numArgs; i++)
                gen.Emit(OpCodes.Ldarg, i+1);
            gen.Emit(OpCodes.Call,fb.FieldType.GetMethod("Invoke"));

            gen.Emit(OpCodes.Ret);

            gen.MarkLabel(eqLabel);
            // Equal to Null: throw WrongArityException
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Call, Method_AFn_WrongArityException);
            gen.Emit(OpCodes.Throw);
        }
Exemplo n.º 39
0
 public ProxyClassBuildingContext(Type interfaceType, string path, TypeBuilder builder, ProxyClassFieldCache fields)
 {
     Fields = fields;
     Builder = builder;
     Path = path;
     InterfaceType = interfaceType;
 }
Exemplo n.º 40
0
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, ILGenerator il)
        {
            var evt = config.DynamicMembers.OfType <DynamicEvent>().Where(p => p.MemberName == "PropertyChanged").FirstOrDefault();

            if (evt == null)
            {
#if NETSTANDARD1_6
                throw new MissingMemberException($"Missiong member PropertyChanged on type {typeBuilder.Name}.");
#else
                throw new MissingMemberException(typeBuilder.Name, "PropertyChanged");
#endif
            }

            var endLabel = il.DefineLabel();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, evt.BackingField);
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Ceq);
            il.Emit(OpCodes.Brtrue_S, endLabel);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, evt.BackingField);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Newobj, typeof(PropertyChangedEventArgs).GetConstructor(new[] { typeof(string) }));
            il.Emit(OpCodes.Callvirt, typeof(PropertyChangedEventHandler).GetMethod("Invoke"));

            il.MarkLabel(endLabel);
            il.Emit(OpCodes.Ret);
        }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, convention.TargetsField.Field);
            il.Emit(OpCodes.Ret);
        }
Exemplo n.º 42
0
 private Emit.MethodBuilder GenerateMethod(Emit.TypeBuilder typeBuilder, MethodDeclaration method)
 {
     Emit.MethodBuilder methb = typeBuilder.DefineMethod(method.MethodName, Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
     this.il          = methb.GetILGenerator();
     this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>();
     this.GenStmt(method.stmt);
     return(methb);
 }
Exemplo n.º 43
0
 public TypeBuilder(
     string TypeName,
     TypeAttributes TypeAttribute)
 {
     myAsmBuilder =
         AssemblyBuilder.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.Run);
     myModBuilder  = myAsmBuilder.DefineDynamicModule(myAsmName.Name);
     myTypeBuilder = myModBuilder.DefineType(TypeName, TypeAttribute);
 }
Exemplo n.º 44
0
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.EmitCall(OpCodes.Callvirt, convention.GetValueEntiresTypedMethod.Method, null);
            il.Emit(OpCodes.Ret);
        }
Exemplo n.º 45
0
        public TypeBuilder Inicialize(string typeName, TypeAttributes typeAttributes, Type[] implementedInterfaces)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentException("Parameter cannot be empty!", nameof(typeName));
            }

            _typeBuilder = _moduleBuilder.DefineType(typeName, typeAttributes, null, implementedInterfaces);
            return(this);
        }
Exemplo n.º 46
0
 private void CompileClassDecl(Node ActiveNode)
 {
     Emit.TypeBuilder _TypeBuilder = TypeTable[ActiveNode.Nodes[1].Value];
     CurrentType = _TypeBuilder;
     OpenBlockVariables();
     CreateCode(ActiveNode.Nodes[3]);
     CloseBlockVariables();
     CreateCode(ActiveNode.Nodes[4]);
     CreatedTypeTable[ActiveNode.Nodes[1].Value] = _TypeBuilder.CreateType();
 }
Exemplo n.º 47
0
        ///// <summary>
        ///// Creates a delegate that does type conversion and calls the method represented by this
        ///// object.
        ///// </summary>
        ///// <param name="argumentTypes"> The types of the arguments that will be passed to the delegate. </param>
        ///// <returns> A delegate that does type conversion and calls the method represented by this
        ///// object. </returns>
        //internal BinderDelegate CreateBinder<T>()
        //{
        //    // Delegate types have an Invoke method containing the relevant parameters.
        //    MethodInfo adapterInvokeMethod = typeof(T).GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance);
        //    if (adapterInvokeMethod == null)
        //        throw new ArgumentException("The type parameter T must be delegate type.", "T");

        //    // Get the argument types.
        //    Type[] argumentTypes = adapterInvokeMethod.GetParameters().Select(p => p.ParameterType).ToArray();

        //    // Create the binder.
        //    return this.callBinder.CreateBinder(argumentTypes);
        //}


#if !XBOX
        /// <summary>
        /// Compile the ClrFunction's Binder methods to IL
        /// </summary>
        /// <param name="typeBuilder">The TypeBuilder to attach the compiled Binder methods to</param>
        public void CompileBinder(System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            if (this.callBinder != null)
            {
                this.callBinder.Compile(this.Engine, typeBuilder);
            }
            if (this.constructBinder != null)
            {
                this.constructBinder.Compile(this.Engine, typeBuilder);
            }
        }
Exemplo n.º 48
0
        public override void GenerateCode(ModuleBuilder moduleBuilder, System.Reflection.Emit.TypeBuilder program, ILGenerator generator)
        {
            var END = generator.DefineLabel();
            var T   = generator.DefineLabel(); /* true */
            var F   = generator.DefineLabel(); /* false */

            //--------------------------------------------------
            // [Stack Status]
            // 1. l_operand
            // (...)
            //--------------------------------------------------
            this.LeftOperandNode.GenerateCode(moduleBuilder, program, generator);

            //--------------------------------------------------
            // [Stack Status]
            // (...)
            //--------------------------------------------------
            generator.Emit(OpCodes.Brfalse, F);

            //--------------------------------------------------
            // [Stack Status]
            // 1. r_operand
            // (...)
            //--------------------------------------------------
            this.RightOperandNode.GenerateCode(moduleBuilder, program, generator);

            //--------------------------------------------------
            // [Stack Status]
            // (...)
            //--------------------------------------------------
            generator.Emit(OpCodes.Brfalse, F);

            generator.MarkLabel(T);

            //--------------------------------------------------
            // [Stack Status]
            // 1. 1 { true }
            // (...)
            //--------------------------------------------------
            generator.Emit(OpCodes.Ldc_I4, 1);

            generator.Emit(OpCodes.Br, END);

            generator.MarkLabel(F);

            //--------------------------------------------------
            // [Stack Status]
            // 1. 0 { false }
            // (...)
            //--------------------------------------------------
            generator.Emit(OpCodes.Ldc_I4, 0);

            generator.MarkLabel(END);
        }
Exemplo n.º 49
0
 public ILCodeGen(string name)
 {
     this.symtab        = Symboltable.Instance;
     this.program_name  = name;
     this.asname        = new Reflect.AssemblyName(name);
     this.asmb          = System.AppDomain.CurrentDomain.DefineDynamicAssembly(asname, Emit.AssemblyBuilderAccess.Save);
     this.modb          = asmb.DefineDynamicModule(name);
     this.typeBuilder   = modb.DefineType("fpc2IL");
     this.mbuilderTable = new Hashtable();
     this.fbuilderTable = new Hashtable();
     this.lbuilderTable = new Hashtable();
 }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            var method = typeof(ITransactionProxy <>).MakeGenericType(convention.ItemType).GetMethod("SetTargets");

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Castclass, typeof(IEnumerable <>).MakeGenericType(convention.ItemType));
            il.EmitCall(OpCodes.Callvirt, method, null);
            il.Emit(OpCodes.Ret);
        }
Exemplo n.º 51
0
        public override void CreateDeclarations(System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            this.BaseMethod = typeBuilder.BaseType.GetMethods().OfType <MethodInfo>()
                              .Where(p => p.Name == this.MemberName)
                              .FirstOrDefault(p =>
                                              p.ReturnType == this.MemberType &&
                                              p.GetParameters().Length == this.ArgumentTypes.Count &&
                                              p.GetParameters().Select((x, i) => new { Index = i, Type = x.ParameterType }).All(x => this.ArgumentTypes[x.Index] == x.Type));

            if (BaseMethod != null && !BaseMethod.IsVirtual)
            {
                throw new MemberCreationException(this.MemberName, "The method has to be declared virtual on the base class.");
            }
            else if (BaseMethod != null)
            {
                IsOverride = true;
            }

            MethodAttributes methodAttributes = MethodAttributes.Public;

            if (IsProtected)
            {
                methodAttributes = MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
            }
            else
            {
                methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
            }

            var implementationAttributes = MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            Method = typeBuilder.DefineMethod(this.MemberName, methodAttributes);
            ImplementationMethod = typeBuilder.DefineMethod(string.Format("{0}_Implementation", this.MemberName), implementationAttributes);

            var genericParameters = GetGenericArguments().ToList();

            if (genericParameters.Any())
            {
                this._genericParameters.AddRange(Method.DefineGenericParameters(genericParameters.ToArray()));
                this._genericImplementationParameters.AddRange(ImplementationMethod.DefineGenericParameters(genericParameters.ToArray()));
            }

            this.Method.SetReturnType(TypeLookup(this.MemberType));
            this.Method.SetParameters(TypeLookup(this.ArgumentTypes).ToArray());

            this.ImplementationMethod.SetReturnType(ImplementationTypeLookup(this.MemberType));
            this.ImplementationMethod.SetParameters(ImplementationTypeLookup(this.ArgumentTypes).ToArray());

            if (IsOverride)
            {
                typeBuilder.DefineMethodOverride(this.Method, this.BaseMethod);
            }
        }
Exemplo n.º 52
0
        private static void CreateProperty(System.Reflection.Emit.TypeBuilder tb, string propertyName, Type propertyType, bool required)
        {
            if (propertyType.IsByRef)
            {
                //avoids an exception in code below when by ref parameters are used
                propertyType = propertyType.GetElementType();
            }

            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder   getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
                                                              MethodAttributes.Public | MethodAttributes.SpecialName |
                                                              MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                                MethodAttributes.Public |
                                MethodAttributes.SpecialName |
                                MethodAttributes.HideBySig,
                                null, new[] { propertyType });

            ILGenerator setIl          = setPropMthdBldr.GetILGenerator();
            Label       modifyProperty = setIl.DefineLabel();
            Label       exitSet        = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            Type[]          ctorParams     = { };
            ConstructorInfo contructorInfo = typeof(DataMemberAttribute).GetConstructor(ctorParams);

            CustomAttributeBuilder customAttrBuilder = new CustomAttributeBuilder(contructorInfo, new object[] { });

            //TODO: set IsRequired here ??

            propertyBuilder.SetCustomAttribute(customAttrBuilder);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
Exemplo n.º 53
0
        /// <summary>
        ///   AddConstructor
        /// </summary>
        /// <param name="typeBuilder"></param>
        /// <param name="backingFields"></param>
        private static void CreateConstructor(System.Reflection.Emit.TypeBuilder typeBuilder, IReadOnlyList <dynamic> backingFields)
        {
            #region Constructor

            //--------------------------------------------------------------------

            // Constructor:  (Default)
            // <code>
            //  .custom instance void [Newtonsoft.Json]Newtonsoft.Json.JsonConverterAttribute::.ctor(class [mscorlib]System.Type) = { type(<NameSpace>.PayloadComplexTypeConverter) }
            //   .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
            //  {
            //  }
            // </code>

            // Attribute:
            // [JsonConverter(typeof(PayloadComplexTypeConverter))]
            // Ctor attributes

            /* Uncomment if needing similar functionality for nested duck types */
            // Attribute:
            // [JsonConverterAttribute()]
            //var jsonConverterAttr = typeof(JsonConverterAttribute).GetConstructor(new [] { typeof(Type) });
            //if (jsonConverterAttr != null) {
            //  // ReSharper disable once InconsistentNaming
            //  var jsonConverterCABuilder = new CustomAttributeBuilder(
            //    jsonConverterAttr,
            //    new object[] { typeof(PayloadComplexTypeConverter) }
            //  );
            //  typeBuilder.SetCustomAttribute(jsonConverterCABuilder);
            //}

            var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new[] { typeof(string), typeof(string), typeof(Dictionary <string, Type>) });
            var ctorIl             = constructorBuilder.GetILGenerator();

            // Now, we'll load the current instance ref in arg 0, along
            // with the value of parameter "x" stored in arg X, into stfld.

            for (var x = 0; x < backingFields.Count; x++)
            {
                ctorIl.Emit(OpCodes.Ldarg_0);
                ctorIl.Emit(OpCodes.Ldarg_S, x + 1);
                ctorIl.Emit(OpCodes.Stfld, backingFields[x]);
            }

            // Our work complete, we return.

            ctorIl.Emit(OpCodes.Ret);

            //--------------------------------------------------------------------

            #endregion Constructor
        }
Exemplo n.º 54
0
        private void AddGetter(System.Reflection.Emit.TypeBuilder typeBuilder, FieldBuilder fieldBuilder, PropertyBuilder propertyBuilder)
        {
            MethodBuilder propertyGetter = typeBuilder.DefineMethod("get_" + _propertyName,
                                                                    MethodAttributes.Public |
                                                                    MethodAttributes.SpecialName |
                                                                    MethodAttributes.HideBySig,
                                                                    _propertyType, Type.EmptyTypes);
            var ilGenerator = propertyGetter.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
            ilGenerator.Emit(OpCodes.Ret);
            propertyBuilder.SetGetMethod(propertyGetter);
        }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            var listCtor = convention.TargetsField.MemberType.GetConstructor(new[] { typeof(IEnumerable <>).MakeGenericType(convention.ItemType) });

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Newobj, listCtor);
            il.Emit(OpCodes.Stfld, convention.TargetsField.Field);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCall(OpCodes.Callvirt, typeof(ICommitable).GetMethod("Rollback"), null);
            il.Emit(OpCodes.Ret);
        }
Exemplo n.º 56
0
        /// <summary>把lcpi参数里的属性加入到myTypeBuilder中。注意:该操作会将其它成员清除掉,其功能有待完善。</summary>
        /// <param name="typeBuilder">类型构造器的实例。</param>
        /// <param name="cpis">里面包含属性列表的信息。</param>
        private static void AddPropertyToTypeBuilder(System.Reflection.Emit.TypeBuilder typeBuilder, List <CustPropertyInfo> cpis)
        {
            PropertyBuilder  custNamePropBldr;
            MethodBuilder    custNameGetPropMthdBldr;
            MethodBuilder    custNameSetPropMthdBldr;
            MethodAttributes getSetAttr;
            ILGenerator      custNameGetIL;
            ILGenerator      custNameSetIL;

            // 属性Set和Get方法要一个专门的属性。这里设置为Public。
            getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            // 添加属性到myTypeBuilder。
            foreach (CustPropertyInfo cpi in cpis)
            {
                // 定义字段。
                FieldBuilder customerNameBldr = typeBuilder.DefineField(cpi.FieldName, Type.GetType(cpi.Type), FieldAttributes.Private);
                customerNameBldr.SetConstant("11111111");

                // 定义属性。 最后一个参数为null,因为属性没有参数。
                custNamePropBldr = typeBuilder.DefineProperty(cpi.PropertyName, PropertyAttributes.HasDefault, Type.GetType(cpi.Type), null);
                custNamePropBldr.SetConstant("111111111");

                // 定义Get方法。
                custNameGetPropMthdBldr = typeBuilder.DefineMethod(cpi.GetPropertyMethodName, getSetAttr, Type.GetType(cpi.Type), Type.EmptyTypes);
                custNameGetIL           = custNameGetPropMthdBldr.GetILGenerator();
                try
                {
                    custNameGetIL.Emit(OpCodes.Ldarg_0);
                    //custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
                    custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
                    custNameGetIL.Emit(OpCodes.Ret);
                }
                catch
                {
                }

                //定义Set方法。
                custNameSetPropMthdBldr = typeBuilder.DefineMethod(cpi.SetPropertyMethodName, getSetAttr, null, new Type[] { Type.GetType(cpi.Type) });
                custNameSetIL           = custNameSetPropMthdBldr.GetILGenerator();
                custNameSetIL.Emit(OpCodes.Ldarg_0);
                custNameSetIL.Emit(OpCodes.Ldarg_1);
                custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
                custNameSetIL.Emit(OpCodes.Ret);
                //custNamePropBldr.SetConstant("ceshi");
                //把创建的两个方法(Get,Set)加入到PropertyBuilder中。
                custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
                custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
            }
        }
Exemplo n.º 57
0
        private void AddSetter(System.Reflection.Emit.TypeBuilder typeBuilder, FieldBuilder fieldBuilder, PropertyBuilder propertyBuilder)
        {
            MethodBuilder propertySetter = typeBuilder.DefineMethod("set_" + _propertyName,
                                                                    MethodAttributes.Public |
                                                                    MethodAttributes.SpecialName |
                                                                    MethodAttributes.HideBySig,
                                                                    null, new Type[] { _propertyType });
            var propertySetterIl = propertySetter.GetILGenerator();

            propertySetterIl.Emit(OpCodes.Ldarg_0);
            propertySetterIl.Emit(OpCodes.Ldarg_1);
            propertySetterIl.Emit(OpCodes.Stfld, fieldBuilder);
            propertySetterIl.Emit(OpCodes.Ret);
            propertyBuilder.SetSetMethod(propertySetter);
        }
Exemplo n.º 58
0
        public static Type CompileResultType(List <FieldInfo> listOfFields, string typeName)
        {
            System.Reflection.Emit.TypeBuilder tb = GetTypeBuilder(typeName);
            ConstructorBuilder constructor        = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
            foreach (var field in listOfFields)
            {
                CreateProperty(tb, field.Name, field.Type);
            }

            Type objectType = tb.CreateType();

            return(objectType);
        }
Exemplo n.º 59
0
        /// <summary>
        /// Create property with explicit implementation of getter and setter, with no method defined.
        /// </summary>
        private PropertyDefinition AddProperty(TypeDefinition declaringType,
                                               string name,
                                               TypeReference propertyType,
                                               string explicitPrefix,
                                               PropertyInfo overridedProp)
        {
            var proxyPropDef = declaringType.DefineProperty(explicitPrefix + name,
                                                            PropertyAttributes.None | PropertyAttributes.SpecialName,
                                                            propertyType,
                                                            null);
            const MethodAttributes methodAttributes = MethodAttributes.Private
                                                      | MethodAttributes.HideBySig
                                                      | MethodAttributes.NewSlot
                                                      | MethodAttributes.Virtual
                                                      | MethodAttributes.Final
                                                      | MethodAttributes.SpecialName;

            var overridedGetMethod = overridedProp.GetGetMethod();

            if (overridedGetMethod != null)
            {
                var proxyPropGetter = declaringType.DefineMethod(
                    $"{explicitPrefix}get_{name}",
                    methodAttributes,
                    propertyType,
                    Type.EmptyTypes);
                declaringType.DefineMethodOverride(proxyPropGetter, overridedGetMethod);

                proxyPropDef.SetGetMethod(proxyPropGetter);
            }

            var overridedSetMethod = overridedProp.GetSetMethod();

            if (overridedSetMethod != null)
            {
                var proxyPropSetter = declaringType.DefineMethod(
                    $"{explicitPrefix}set_{name}",
                    methodAttributes,
                    null,
                    new[] { propertyType });

                proxyPropSetter.DefineParameter(0, ParameterAttributes.None, "value");
                declaringType.DefineMethodOverride(proxyPropSetter, overridedSetMethod);
                proxyPropDef.SetSetMethod(proxyPropSetter);
            }

            return(proxyPropDef);
        }
Exemplo n.º 60
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeBuilderHelper"/> class
        /// with the specified parameters.
        /// </summary>
        /// <param name="assemblyBuilder">Associated <see cref="AssemblyBuilderHelper"/>.</param>
        /// <param name="typeBuilder">A <see cref="TypeBuilder"/></param>
        public TypeBuilderHelper(AssemblyBuilderHelper assemblyBuilder, System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            if (assemblyBuilder == null)
            {
                throw new ArgumentNullException("assemblyBuilder");
            }
            if (typeBuilder == null)
            {
                throw new ArgumentNullException("typeBuilder");
            }

            _assembly    = assemblyBuilder;
            _typeBuilder = typeBuilder;

            _typeBuilder.SetCustomAttribute(_assembly.BLToolkitAttribute);
        }