DefineMethod() публичный Метод

public DefineMethod ( string name, System attributes ) : System.Reflection.Emit.MethodBuilder
name string
attributes System
Результат System.Reflection.Emit.MethodBuilder
		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);
		}
Пример #2
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;
     }
Пример #3
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);
		}
		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);
		}
        private static void MakeProperty(TypeBuilder typeBuilder, string name, Type type)
        {
            var fieldBuilder = typeBuilder.DefineField("_" + name, type, FieldAttributes.Private);
            var propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.None, CallingConventions.HasThis, type,
                                                             null);
            var getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;

            var getter = typeBuilder.DefineMethod("get_" + name, getSetAttr, type, Type.EmptyTypes);

            var getIL = getter.GetILGenerator();
            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, fieldBuilder);
            getIL.Emit(OpCodes.Ret);

            var setter = typeBuilder.DefineMethod("set_" + name, getSetAttr, null, new[] {type});

            var setIL = setter.GetILGenerator();
            setIL.Emit(OpCodes.Ldarg_0);
            setIL.Emit(OpCodes.Ldarg_1);
            setIL.Emit(OpCodes.Stfld, fieldBuilder);
            setIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getter);
            propertyBuilder.SetSetMethod(setter);
        }
Пример #6
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;
 }
Пример #7
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);
		}
Пример #8
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;
		}
Пример #9
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;
        }
Пример #10
0
            private static void BuildProperty(TypeBuilder typeBuilder, string name, Type type)
            {
                FieldBuilder field = typeBuilder.DefineField("m" + name, type, FieldAttributes.Private);
                PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.None, type, null);

                MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;

                MethodBuilder getter = typeBuilder.DefineMethod("get_" + name, getSetAttr, type, Type.EmptyTypes);

                ILGenerator getIL = getter.GetILGenerator();
                getIL.Emit(OpCodes.Ldarg_0);
                getIL.Emit(OpCodes.Ldfld, field);
                getIL.Emit(OpCodes.Ret);

                MethodBuilder setter = typeBuilder.DefineMethod("set_" + name, getSetAttr, null, new Type[] { type });

                ILGenerator setIL = setter.GetILGenerator();
                setIL.Emit(OpCodes.Ldarg_0);
                setIL.Emit(OpCodes.Ldarg_1);
                setIL.Emit(OpCodes.Stfld, field);
                setIL.Emit(OpCodes.Ret);


                propertyBuilder.SetGetMethod(getter);
                propertyBuilder.SetSetMethod(setter);
            }
        public override void Extend(Type baseType, TypeBuilder typeBuilder)
        {
            //build field
            FieldBuilder field = typeBuilder.DefineField(FieldName, Type, FieldAttributes.Private);

            //define property
            PropertyBuilder property = typeBuilder.DefineProperty(Name, PropertyAttributes.None, Type, null);

            //build setter
            MethodBuilder setter = typeBuilder.DefineMethod("set_" + Name, MethodAttributes.Public | MethodAttributes.Virtual, null, new Type[] { Type });
            ILGenerator setterILG = setter.GetILGenerator();
            setterILG.Emit(OpCodes.Ldarg_0);
            setterILG.Emit(OpCodes.Ldarg_1);
            setterILG.Emit(OpCodes.Stfld, field);
            setterILG.Emit(OpCodes.Ret);
            property.SetSetMethod(setter);

            //build getter
            MethodBuilder getter = typeBuilder.DefineMethod("get_" + Name, MethodAttributes.Public | MethodAttributes.Virtual, Type, Type.EmptyTypes);
            ILGenerator getterILG = getter.GetILGenerator();
            getterILG.Emit(OpCodes.Ldarg_0);
            getterILG.Emit(OpCodes.Ldfld, field);
            getterILG.Emit(OpCodes.Ret);
            property.SetGetMethod(getter);
        }
Пример #12
0
        private static void CreateProperty(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);
        }
Пример #13
0
        public void DefineProperty(TypeBuilder builder, Type type, string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("propertyName");
            }

            string fieldName = Char.ToLowerInvariant(name[0]) + name.Substring(1);
            string propertyName = Char.ToUpperInvariant(name[0]) + name.Substring(1);

            FieldBuilder fieldBuilder = builder.DefineField(
                fieldName,
                type,
                FieldAttributes.Private);

            PropertyBuilder propertyBuilder = builder.DefineProperty(
                propertyName,
                PropertyAttributes.HasDefault,
                type, 
                null);

            //Getter
            MethodBuilder getMethodBuilder = builder.DefineMethod(
                "get_" + propertyName, 
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.HideBySig,
                type, 
                Type.EmptyTypes);

            ILGenerator getILGenerator = getMethodBuilder.GetILGenerator();

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

            //Setter
            MethodBuilder setMethodBuilder = builder.DefineMethod(
                "set_" + propertyName, 
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.HideBySig, 
                null,
                new Type[] { type });

            ILGenerator setILGenerator = setMethodBuilder.GetILGenerator();

            setILGenerator.Emit(OpCodes.Ldarg_0);
            setILGenerator.Emit(OpCodes.Ldarg_1);
            setILGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            setILGenerator.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getMethodBuilder);
            propertyBuilder.SetSetMethod(setMethodBuilder);
        }
Пример #14
0
        public MethodWriter(TypeBuilder Parent, CodeMemberMethod Member, MethodCollection Lookup, ILMirror Mirror)
        {
            Loops = new Stack<LoopMetadata>();

            this.Member = Member;
            this.Lookup = Lookup;
            this.Mirror = Mirror;

            if(Member is CodeEntryPointMethod)
            {
                Method = Parent.DefineMethod("Main", MethodAttributes.Private | MethodAttributes.Static, typeof(void), null);
                IsEntryPoint = true;
            }
            else Method = Parent.DefineMethod(Member.Name, MethodAttributes.Public | MethodAttributes.Static, typeof(object), new[] { typeof(object[]) });
            
            Generator = Method.GetILGenerator();

            ForceString = typeof(Script).GetMethod("ForceString");
            ForceDecimal = typeof(Script).GetMethod("ForceDecimal");
            ForceLong = typeof(Script).GetMethod("ForceLong");
            ForceInt = typeof(Script).GetMethod("ForceInt");
            ForceBool = typeof(Script).GetMethod("ForceBool");
            
            Locals = new Dictionary<string, LocalBuilder>();
            Labels = new Dictionary<string, LabelMetadata>();
            
            Type Variables = typeof(Script.Variables);
            
            if(IsEntryPoint)
                GenerateEntryPointHeader(Generator);
            
            SetVariable = typeof(Script.Variables).GetMethod("SetVariable");
            GetVariable = typeof(Script.Variables).GetMethod("GetVariable");
            
            MethodInfo GetVars = typeof(Script).GetMethod("get_Vars");
            
            if(Mirror != null)
            {
                ForceString = Mirror.GrabMethod(ForceString);
                ForceDecimal = Mirror.GrabMethod(ForceDecimal);
                ForceLong = Mirror.GrabMethod(ForceLong);
                ForceInt = Mirror.GrabMethod(ForceInt);
                ForceBool = Mirror.GrabMethod(ForceBool);
                SetVariable = Mirror.GrabMethod(SetVariable);
                GetVariable = Mirror.GrabMethod(GetVariable);
                Variables = Mirror.GrabType(Variables);
                GetVars = Mirror.GrabMethod(GetVars);
            }
            
            VarsProperty = Generator.DeclareLocal(Variables);
            Generator.Emit(OpCodes.Call, GetVars);
            Generator.Emit(OpCodes.Stloc, VarsProperty);            
        }
Пример #15
0
        private static void ImplementAddInterceptionBehavior(TypeBuilder typeBuilder, FieldInfo proxyInterceptorPipelineField)
        {
            // Declaring method builder
            // Method attributes
            const MethodAttributes MethodAttributes = MethodAttributes.Private | MethodAttributes.Virtual
                | MethodAttributes.Final | MethodAttributes.HideBySig
                    | MethodAttributes.NewSlot;

            MethodBuilder methodBuilder =
                typeBuilder.DefineMethod(
                    "Microsoft.Practices.Unity.InterceptionExtension.IInterceptingProxy.AddInterceptionBehavior",
                    MethodAttributes);

            // Setting return type
            methodBuilder.SetReturnType(typeof(void));
            // Adding parameters
            methodBuilder.SetParameters(typeof(IInterceptionBehavior));
            // Parameter method
            methodBuilder.DefineParameter(1, ParameterAttributes.None, "interceptor");

            ILGenerator il = methodBuilder.GetILGenerator();
            // Writing body
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, proxyInterceptorPipelineField);
            il.Emit(OpCodes.Ldarg_1);
            il.EmitCall(OpCodes.Callvirt, InterceptionBehaviorPipelineMethods.Add, null);
            il.Emit(OpCodes.Ret);
            typeBuilder.DefineMethodOverride(methodBuilder, IInterceptingProxyMethods.AddInterceptionBehavior);
        }
	protected void SetUp () {
		AssemblyName assemblyName = new AssemblyName();
		assemblyName.Name = GetType().FullName;

		AssemblyBuilder assembly 
			= Thread.GetDomain().DefineDynamicAssembly(
				assemblyName, AssemblyBuilderAccess.Run);

		module = assembly.DefineDynamicModule("module1");
		
	    tb = module.DefineType("class1", 
							   TypeAttributes.Public);

		eb = tb.DefineEvent ("event1", EventAttributes.None, typeof (AnEvent));
		mb = 
			tb.DefineMethod ("OnAnEvent",
							 MethodAttributes.Public, typeof (void),
							 new Type [] { typeof (AnEvent) });
		ILGenerator ilgen = mb.GetILGenerator();
		ilgen.Emit (OpCodes.Ret);

		// These two are required
		eb.SetAddOnMethod (mb);
		eb.SetRemoveOnMethod (mb);
	}
Пример #17
0
 private void GenerateEquals(TypeBuilder tb, FieldInfo[] fields)
 {
     ILGenerator iLGenerator = tb.DefineMethod("Equals", MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public, typeof(bool), new Type[] { typeof(object) }).GetILGenerator();
     LocalBuilder local = iLGenerator.DeclareLocal(tb);
     Label label = iLGenerator.DefineLabel();
     iLGenerator.Emit(OpCodes.Ldarg_1);
     iLGenerator.Emit(OpCodes.Isinst, tb);
     iLGenerator.Emit(OpCodes.Stloc, local);
     iLGenerator.Emit(OpCodes.Ldloc, local);
     iLGenerator.Emit(OpCodes.Brtrue_S, label);
     iLGenerator.Emit(OpCodes.Ldc_I4_0);
     iLGenerator.Emit(OpCodes.Ret);
     iLGenerator.MarkLabel(label);
     foreach (FieldInfo info in fields)
     {
         Type fieldType = info.FieldType;
         Type type2 = typeof(EqualityComparer<>).MakeGenericType(new Type[] { fieldType });
         label = iLGenerator.DefineLabel();
         iLGenerator.EmitCall(OpCodes.Call, type2.GetMethod("get_Default"), null);
         iLGenerator.Emit(OpCodes.Ldarg_0);
         iLGenerator.Emit(OpCodes.Ldfld, info);
         iLGenerator.Emit(OpCodes.Ldloc, local);
         iLGenerator.Emit(OpCodes.Ldfld, info);
         iLGenerator.EmitCall(OpCodes.Callvirt, type2.GetMethod("Equals", new Type[] { fieldType, fieldType }), null);
         iLGenerator.Emit(OpCodes.Brtrue_S, label);
         iLGenerator.Emit(OpCodes.Ldc_I4_0);
         iLGenerator.Emit(OpCodes.Ret);
         iLGenerator.MarkLabel(label);
     }
     iLGenerator.Emit(OpCodes.Ldc_I4_1);
     iLGenerator.Emit(OpCodes.Ret);
 }
Пример #18
0
        private static void ImplementInterfaceMethod(TypeBuilder newType, MethodInfo interfaceMethod)
        {
            var parameters = interfaceMethod.GetParameters();
            var parameterTypes = (from p in parameters select p.ParameterType).ToArray();

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

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

            // parameter 0 is 'this', so we start at index 1
            for (int i = 0; i < parameters.Length; i++)
            {
                newMethod.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);
            }

            // load all arguments (including 'this') in proper order, then call and return
            var ilGenerator = newMethod.GetILGenerator();
            for (int i = 0; i <= parameterTypes.Length; i++)
            {
                ilGenerator.Emit(OpCodes.Ldarg_S, (byte)i);
            }
            ilGenerator.Emit(OpCodes.Call, baseMethod);
            ilGenerator.Emit(OpCodes.Ret);

            // finally, hook the new method up to the interface mapping
            newType.DefineMethodOverride(newMethod, interfaceMethod);
        }
        private void ImplementBaseSetter(TypeBuilder typeBuilder)
        {
            var setterBuilder = typeBuilder.DefineMethod(
                "SetBasePropertyValue", MethodAttributes.Public | MethodAttributes.HideBySig, typeof(void),
                new[] { typeof(string), typeof(object) });
            var gen = setterBuilder.GetILGenerator();

            var labels = new Label[_baseSetters.Count];

            for (var i = 0; i < _baseSetters.Count; i++)
            {
                labels[i] = gen.DefineLabel();
                gen.Emit(OpCodes.Ldarg_1);
                gen.Emit(OpCodes.Ldstr, _baseSetters[i].Name);
                gen.Emit(OpCodes.Call, _stringEquals);
                gen.Emit(OpCodes.Brfalse_S, labels[i]);
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldarg_2);
                gen.Emit(OpCodes.Castclass, _baseSetters[i].PropertyType);
                gen.Emit(OpCodes.Call, _baseSetters[i].GetSetMethod(true));
                gen.Emit(OpCodes.Ret);
                gen.MarkLabel(labels[i]);
            }
            gen.Emit(OpCodes.Newobj, _invalidOperationConstructor);
            gen.Emit(OpCodes.Throw);
        }
        private static void AddContainmentEntitiesMethod(TypeBuilder typeBuilder, Type parentType, PropertyInfo propertyInfo)
        {
            var methodBuilder = typeBuilder.DefineMethod("Get" + propertyInfo.Name, MethodAttributes.Public , typeof(IHttpActionResult), new[] { typeof(long) });
            var keyParameter = methodBuilder.DefineParameter(1, ParameterAttributes.None, "key");

            var dynamicEnableQueryAttribute = typeof(DynamicEnableQueryAttribute).GetConstructor(Type.EmptyTypes);
            if (dynamicEnableQueryAttribute == null)
            {
                throw new ArgumentException();
            }
            methodBuilder.SetCustomAttribute(new CustomAttributeBuilder(dynamicEnableQueryAttribute, new object[0]));

            var fromODataUriAttribute = typeof(FromODataUriAttribute).GetConstructor(Type.EmptyTypes);
            if (fromODataUriAttribute == null)
            {
                throw new ArgumentException();
            }
            keyParameter.SetCustomAttribute(new CustomAttributeBuilder(fromODataUriAttribute, new object[0]));

            var getContainedEntityMethodInfo = parentType.GetMethod("GetContainedEntity", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(propertyInfo.PropertyType.GetGenericArguments());

            var generator = methodBuilder.GetILGenerator();

            // push "this"
            generator.Emit(OpCodes.Ldarg_0);
            // push "key"
            generator.Emit(OpCodes.Ldarg_1);
            // push propertyName
            generator.Emit(OpCodes.Ldstr, propertyInfo.Name);
            // call
            generator.Emit(OpCodes.Call, getContainedEntityMethodInfo);
            generator.Emit(OpCodes.Ret);
        }
Пример #21
0
        /// <summary>
        /// Implements a method as a no operation method. Method can be virtual, abstract or not.
        /// </summary>
        /// <param name="tB">The <see cref="TypeBuilder"/> for the new type.</param>
        /// <param name="method">The method to implement.</param>
        /// <param name="isVirtual">Defaults to false: the method is sealed. True to keep the method virtual. </param>
        /// <returns>The <see cref="MethodBuilder"/> to enable, for instance, creation of custom attributes on the method.</returns>
        public static MethodBuilder ImplementEmptyStubMethod( TypeBuilder tB, MethodInfo method, bool isVirtual = false )
        {
            if( tB == null ) throw new ArgumentNullException( "tB" );
            if( method == null ) throw new ArgumentNullException( "method" );

            ParameterInfo[] parameters = method.GetParameters();
            Type[] parametersTypes = ReflectionHelper.CreateParametersType( parameters );
            Type returnType = method.ReturnType;

            MethodAttributes mA = method.Attributes & ~(MethodAttributes.Abstract | MethodAttributes.VtableLayoutMask);
            if( isVirtual ) mA |= MethodAttributes.Virtual;
            MethodBuilder mB = tB.DefineMethod( method.Name, mA );
            if( method.ContainsGenericParameters )
            {
                int i = 0;

                Type[] genericArguments = method.GetGenericArguments();
                string[] names = genericArguments.Select( t => String.Format( "T{0}", i++ ) ).ToArray();

                var genericParameters = mB.DefineGenericParameters( names );
                for( i = 0; i < names.Length; ++i )
                {
                    var genericTypeArgument = genericArguments[i].GetTypeInfo();
                    GenericTypeParameterBuilder genericTypeBuilder = genericParameters[i];


                    genericTypeBuilder.SetGenericParameterAttributes( genericTypeArgument.GenericParameterAttributes );
                    genericTypeBuilder.SetInterfaceConstraints( genericTypeArgument.GetGenericParameterConstraints() );
                }
            }
            mB.SetReturnType( method.ReturnType );
            mB.SetParameters( ReflectionHelper.CreateParametersType( parameters ) );
            EmitEmptyImplementation( mB, returnType, parameters );
            return mB;
        }
Пример #22
0
        internal static void CreateReadOnlyLazyProperty(TypeBuilder tb, PropertyInfo property, ILGenerator ctor, bool isInterfaceImplementation = true)
        {
            var propertyName = property.Name;
            var propertyType = property.PropertyType;

            //backing field
            var lazyType = typeof(Lazy<>).MakeGenericType(propertyType);
            var fb = tb.DefineField("_backing_" + propertyName, lazyType, FieldAttributes.Private);

            //property
            var pb = tb.DefineProperty(propertyName, PropertyAttributes.None, propertyType, null);

            //getter
            var getterAttributes = isInterfaceImplementation ? InterfaceImplementationAttributes : OverrideAttributes;
            var getMethod = tb.DefineMethod("get_" + propertyName, getterAttributes, propertyType, Type.EmptyTypes);
            var getIL = getMethod.GetILGenerator();
            getIL.DeclareLocal(propertyType);
            getIL.Emit(OpCodes.Nop);
            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, fb);
            getIL.EmitCall(OpCodes.Callvirt, lazyType.GetProperty("Value").GetGetMethod(), null);
            getIL.Emit(OpCodes.Stloc_0);
            getIL.Emit(OpCodes.Nop); //originally a br.s to the next line
            getIL.Emit(OpCodes.Ldloc_0);
            getIL.Emit(OpCodes.Ret);

            //combine getter and property
            pb.SetGetMethod(getMethod);

            //initialize Lazy<T> in .ctor
            ctor.Emit(OpCodes.Ldarg_0);
            ctor.Emit(OpCodes.Newobj, lazyType.GetConstructor(Type.EmptyTypes));
            ctor.Emit(OpCodes.Stfld, fb);
        }
Пример #23
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);
        }
Пример #24
0
        public ILGenerator CreateFunction(TypeBuilder a_TypeBuilder, string a_Name, MethodAttributes a_MethodAttributes, Type a_ReturnType, Type[] a_Parameters)
        {
            MethodBuilder methodBuilder = a_TypeBuilder.DefineMethod(a_Name, a_MethodAttributes, a_ReturnType, a_Parameters);
            ILGenerator ilGenerator = methodBuilder.GetILGenerator();

            return ilGenerator;
        }
        private static void WriteProperty(Type parentType, TypeBuilder builder, string name, Type type)
        {
            const BindingFlags BindingFlag = BindingFlags.Public | BindingFlags.Instance;
            const MethodAttributes MethodAttribute = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot;

            string getName = "get_" + name;
            string setName = "set_" + name;

            MethodInfo parentGetMethod = parentType.GetMethod(getName, BindingFlag);
            MethodBuilder implementedGetMethod = builder.DefineMethod(getName, MethodAttribute, type, Type.EmptyTypes);
            ILGenerator getIl = implementedGetMethod.GetILGenerator();
            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Call, parentGetMethod);
            getIl.Emit(OpCodes.Ret);

            MethodInfo interfaceGetMethod = authorizeAttributeType.GetMethod(getName, BindingFlag);
            builder.DefineMethodOverride(implementedGetMethod, interfaceGetMethod);

            MethodInfo parentSetMethod = parentType.GetMethod(setName, BindingFlag);
            MethodBuilder implementedSetMethod = builder.DefineMethod(setName, MethodAttribute, typeof(void), new[] { type });
            ILGenerator setIl = implementedSetMethod.GetILGenerator();
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Call, parentSetMethod);
            setIl.Emit(OpCodes.Ret);

            MethodInfo interfaceSetMethod = authorizeAttributeType.GetMethod(setName, BindingFlag);
            builder.DefineMethodOverride(implementedSetMethod, interfaceSetMethod);
        }
Пример #26
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;
		}
Пример #27
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);
        }
Пример #28
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);
        }
Пример #29
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));
     }
 }
        /// <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;
        }
Пример #31
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);
        }
        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);
        }
Пример #33
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("SC");

        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);

        this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { }, null));
        this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
        il.Emit(Emit.OpCodes.Ret);
        typeBuilder.CreateType();
        modb.CreateGlobalFunctions();
        asmb.SetEntryPoint(methb);
        asmb.Save(moduleName);
        this.symbolTable = null;
        this.il          = null;
    }
Пример #34
0
        private static void CreateProperty(System.Reflection.Emit.TypeBuilder tb, string propertyName, Type propertyType, bool required)
        {
            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);
        }
Пример #35
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);
 }
Пример #36
0
    public static Type BuildPropertyObject(System.Collections.Generic.IEnumerable <System.Collections.Generic.KeyValuePair <string, Type> > obj)
    {
        string nameOfDLL      = "magic.dll";
        string nameOfAssembly = "magic_Assembly";
        string nameOfModule   = "magic_Module";
        string nameOfType     = "magic_Type";

        System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName {
            Name = nameOfAssembly
        };
        System.Reflection.Emit.AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave);
        System.Reflection.Emit.ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(nameOfModule, nameOfDLL);
        System.Reflection.Emit.TypeBuilder     typeBuilder     = moduleBuilder.DefineType(nameOfType, System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class);
        foreach (var prop in obj)
        {
            string Name     = prop.Key;
            Type   DataType = prop.Value;
            System.Reflection.Emit.FieldBuilder    field               = typeBuilder.DefineField("_" + Name, DataType, System.Reflection.FieldAttributes.Private);
            System.Reflection.Emit.PropertyBuilder propertyBuilder     = typeBuilder.DefineProperty(Name, System.Reflection.PropertyAttributes.SpecialName, DataType, null);
            System.Reflection.MethodAttributes     methodAttributes    = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName;
            System.Reflection.Emit.MethodBuilder   methodBuilderGetter = typeBuilder.DefineMethod("get_" + Name, methodAttributes, DataType, new Type[] { });
            System.Reflection.Emit.MethodBuilder   methodBuilderSetter = typeBuilder.DefineMethod("set_" + Name, methodAttributes, typeof(void), new Type[] { DataType });
            System.Reflection.Emit.ILGenerator     ilGeneratorGetter   = methodBuilderGetter.GetILGenerator();
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ret);
            System.Reflection.Emit.ILGenerator ilGeneratorSetter = methodBuilderSetter.GetILGenerator();
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ret);
            propertyBuilder.SetGetMethod(methodBuilderGetter);
            propertyBuilder.SetSetMethod(methodBuilderSetter);
        }
        // Yes! you must do this, it should not be needed but it is!
        Type dynamicType = typeBuilder.CreateType();

        // Save to file
        assemblyBuilder.Save(nameOfDLL);
        return(dynamicType);
    }
Пример #37
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);
        }
Пример #38
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);
        }
Пример #39
0
        private void AddGetter(System.Reflection.Emit.TypeBuilder typeBuilder, PropertyBuilder propertyBuilder)
        {
            MethodBuilder propertyGetter = typeBuilder.DefineMethod("get_" + _propertyInfo.Name,
                                                                    MethodAttributes.Public |
                                                                    MethodAttributes.SpecialName |
                                                                    MethodAttributes.HideBySig,
                                                                    _propertyInfo.PropertyType, Type.EmptyTypes);
            var ilGenerator = propertyGetter.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldfld, _aggregate);
            MethodInfo getter = _propertyInfo.GetAccessors().First(accessor => accessor.ReturnType != typeof(void));

            ilGenerator.Emit(OpCodes.Callvirt, getter);
            ilGenerator.Emit(OpCodes.Ret);
            propertyBuilder.SetGetMethod(propertyGetter);
        }
Пример #40
0
        private void inicializar(string nombreCodigoFuente, string nombrePrograma)
        {
            if (TablaDireccionesSimbolos.Count > 0)
            {
                throw new System.Exception("ERROR-0002: Tabla de direcciones de variables ha sido inicializada previamente");
            }

            String rutaEjecutable = IO.Path.GetDirectoryName(nombrePrograma);

            //Describo el identificador unico del ensamblado que se esta generando
            nombre = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(nombrePrograma));

            //Creo la representacion basica del ensamblado creado de forma dinamica (assembly)
            if (rutaEjecutable.Length > 0)
            {
                asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave, rutaEjecutable);
            }
            else
            {
                asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave);
            }



            Console.WriteLine("Common Runtime usado para generar el ejecutable del programa: " + asmb.ImageRuntimeVersion);
            Console.WriteLine("Se esta ejecutando el compilador bajo el CLR version {0}", Environment.Version);

            //Defino un nuevo modulo de .net de forma dinamica
            modb = asmb.DefineDynamicModule(IO.Path.GetFileName(nombrePrograma), false);

            //Creo una nueva clase en el Il Generator stream
            typeBuilder = modb.DefineType("pseudoGenerado");

            //Debido a que los programas en este tiny solo cuentan con un unico metodo principal (Main) de forma estructurada
            //como un truco defino el metodo Main en un objeto por defecto para ejecutar todas las acciones
            //expresadas por el lenguaje alli.
            //formato: NOMBRE -> Main   TIPO-> Static  RETORNA-> void  PARAMETROS-> vacios
            methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.HideBySig | Reflect.MethodAttributes.Static | Reflect.MethodAttributes.Public, typeof(void), System.Type.EmptyTypes);

            //Inicializo/Creo el generador/stream de codigo IL con el metodo donde generare el codigo actualmente
            this.il = methb.GetILGenerator();

            //Para iniciar el programa Emito una primera instruccion vacia (no hace nada)
            il.Emit(Emit.OpCodes.Nop);
        }
Пример #41
0
        private void AddSetter(System.Reflection.Emit.TypeBuilder typeBuilder, PropertyBuilder propertyBuilder)
        {
            MethodBuilder propertySetter = typeBuilder.DefineMethod("set_" + _propertyInfo.Name,
                                                                    MethodAttributes.Public |
                                                                    MethodAttributes.SpecialName |
                                                                    MethodAttributes.HideBySig,
                                                                    null, new Type[] { _propertyInfo.PropertyType });
            var propertySetterIl = propertySetter.GetILGenerator();

            propertySetterIl.Emit(OpCodes.Ldarg_0);
            propertySetterIl.Emit(OpCodes.Ldfld, _aggregate);
            propertySetterIl.Emit(OpCodes.Ldarg_1);
            MethodInfo setter = _propertyInfo.GetAccessors().First(accessor => accessor.ReturnType == typeof(void));

            propertySetterIl.Emit(OpCodes.Callvirt, setter);
            propertySetterIl.Emit(OpCodes.Ret);
            propertyBuilder.SetSetMethod(propertySetter);
        }
Пример #42
0
        public Emit.MethodBuilder GenerateCode(MethodDeclaration methodDec)
        {
            MethodAttributes methodAttributes = MethodAttributes.Public;

            if (methodDec.IsStatic)
            {
                methodAttributes = methodAttributes | MethodAttributes.Static;
            }

            //Type[] types = { typeof(string) };

            //Emit.MethodBuilder methb = typeBuilder.DefineMethod(methodDec.MethodName, methodAttributes, typeof(void), types);
            Emit.MethodBuilder methb = typeBuilder.DefineMethod(methodDec.MethodName, methodAttributes, typeof(void), System.Type.EmptyTypes);

            child = new CodeGen(methb, methodDec, typefieldList, dllProbeDirectory, this);
            child.GenerateCode();
            return(methb);
        }
Пример #43
0
        protected override void OnPropertyGenerationComplete(TypeDefinition proxyType)
        {
            const string initPropertyWrappersMethodName = "InitPropertyWrappers";

            var initPropertyWrappersMethod = proxyType.DefineMethod(
                initPropertyWrappersMethodName,
                MethodAttributes.Static | MethodAttributes.Private,
                null, Type.EmptyTypes);

            var il = initPropertyWrappersMethod.GetILGenerator();

            this.initPropertyWrapperIlAction.ForEach(m => m(il));
            il.Emit(OpCodes.Ret);

            var cctor = proxyType.DefineTypeInitializer();

            var cctorIl = cctor.GetILGenerator();

            cctorIl.Emit(OpCodes.Call, initPropertyWrappersMethod);
            cctorIl.Emit(OpCodes.Ret);
        }
Пример #44
0
        /// <summary>
        ///   CreateMethod
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <param name="typeBuilder"></param>
        private static void CreateMethod(this MethodInfo methodInfo, System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            // Define the method
            var methodBuilder = typeBuilder.DefineMethod(methodInfo.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual, methodInfo.ReturnType, methodInfo.GetParameters().Select(parameterInfo => parameterInfo.ParameterType).ToArray());

            // The ILGenerator class is used to put op-codes (similar to assembly) into the method
            // ReSharper disable once InconsistentNaming
            var IL = methodBuilder.GetILGenerator();

            // If there's a return type, create a default value or null to return
            if (methodInfo.ReturnType != typeof(void))
            {
                var localBuilder = IL.DeclareLocal(methodInfo.ReturnType); // this declares the local object,
                // int, long, float, ect
                IL.Emit(OpCodes.Ldloc, localBuilder);                      // load the value on the stack to return
            }

            IL.Emit(OpCodes.Ret); // return

            // We need to associate our new type's method with the setter method in the interface
            typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);
        }
Пример #45
0
    public CodeGen(stmt stmt, string moduleName, int count)
    {
        if (IO.Path.GetFileName(moduleName) != moduleName)
        {
            throw new System.Exception("can only output into current directory!");
        }
        stmts = stmt;

        Reflect.AssemblyName name        = new Reflect.AssemblyName("FAJF"); //name of the assembly
        Emit.AssemblyBuilder asmb        = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save);
        Emit.ModuleBuilder   modb        = asmb.DefineDynamicModule(moduleName);
        Emit.TypeBuilder     typeBuilder = modb.DefineType("resister"); //name of the class

        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>();
        counting         = 0;
        counter          = count;
        counters         = 0;



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

        il.Emit(Emit.OpCodes.Ret);
        typeBuilder.CreateType();
        modb.CreateGlobalFunctions();
        asmb.SetEntryPoint(methb);
        asmb.Save(moduleName);
        // this.il.EmitWriteLine("press any key to continue");

        this.symbolTable = null;
        this.il          = null;
        System.Diagnostics.Process.Start(moduleName);
    }
Пример #46
0
        /// <summary>
        /// Generate the declaration for the IgnoresAccessChecksToAttribute type.
        /// This attribute will be both defined and used in the dynamic assembly.
        /// Each usage identifies the name of the assembly containing non-public
        /// types the dynamic assembly needs to access.  Normally those types
        /// would be inaccessible, but this attribute allows them to be visible.
        /// It works like a reverse InternalsVisibleToAttribute.
        /// This method returns the ConstructorInfo of the generated attribute.
        /// </summary>
        public static ConstructorInfo AddToModule(ModuleBuilder mb)
        {
            TypeBuilder attributeTypeBuilder =
                mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute",
                              TypeAttributes.Public | TypeAttributes.Class,
                              typeof(Attribute));

            // Create backing field as:
            // private string assemblyName;
            FieldBuilder assemblyNameField =
                attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private);

            // Create ctor as:
            // public IgnoresAccessChecksToAttribute(string)
            ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public,
                                                                                           CallingConventions.HasThis,
                                                                                           new Type[] { assemblyNameField.FieldType });

            ILGenerator il = constructorBuilder.GetILGenerator();

            // Create ctor body as:
            // this.assemblyName = {ctor parameter 0}
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg, 1);
            il.Emit(OpCodes.Stfld, assemblyNameField);

            // return
            il.Emit(OpCodes.Ret);

            // Define property as:
            // public string AssemblyName {get { return this.assemblyName; } }
            _ = attributeTypeBuilder.DefineProperty(
                "AssemblyName",
                PropertyAttributes.None,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod(
                "get_AssemblyName",
                MethodAttributes.Public,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            // Generate body:
            // return this.assemblyName;
            il = getterMethodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, assemblyNameField);
            il.Emit(OpCodes.Ret);

            // Generate the AttributeUsage attribute for this attribute type:
            // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
            TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo();

            // Find the ctor that takes only AttributeTargets
            ConstructorInfo attributeUsageConstructorInfo =
                attributeUsageTypeInfo.DeclaredConstructors
                .Single(c => c.GetParameters().Count() == 1 &&
                        c.GetParameters()[0].ParameterType == typeof(AttributeTargets));

            // Find the property to set AllowMultiple
            PropertyInfo allowMultipleProperty =
                attributeUsageTypeInfo.DeclaredProperties
                .Single(f => string.Equals(f.Name, "AllowMultiple"));

            // Create a builder to construct the instance via the ctor and property
            CustomAttributeBuilder customAttributeBuilder =
                new CustomAttributeBuilder(attributeUsageConstructorInfo,
                                           new object[] { AttributeTargets.Assembly },
                                           new PropertyInfo[] { allowMultipleProperty },
                                           new object[] { true });

            // Attach this attribute instance to the newly defined attribute type
            attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder);

            // Make the TypeInfo real so the constructor can be used.
            return(attributeTypeBuilder.CreateTypeInfo() !.DeclaredConstructors.Single());
        }
Пример #47
0
    public void genMethod(Symbol s)
    {
        System.Type[] parameters;
        System.Type   returnType = null;
        Procedure     p          = null;

        //Debemos poner el ret correcto
        if (this.il != null)
        {
            this.il.Emit(Emit.OpCodes.Ret);
        }

        if (s is Procedure)
        {
            p = (Procedure)s;
        }

        if (s is Function)
        {
            Function f = (Function)s;
            returnType = getSystemTypeFormat(f.TypeReturn);
            p          = (Procedure)f;
        }

        parameters = new System.Type[p.Parameters.Count];

        int i    = 0;
        int cont = p.Parameters.Count;

        object[] keys = new object[cont];
        p.Parameters.Keys.CopyTo(keys, 0);
        Array.Reverse(keys);

        for (i = 0; i < cont; i++)
        {
            Param param = (Param)p.Parameters[keys[i]];
            parameters[i] = getSystemTypeFormat(param.Type);
            if (param.Reference)
            {
                parameters[i] = parameters[i].MakeByRefType();
            }
        }

        this.methb = typeBuilder.DefineMethod(s.Name,
                                              Reflect.MethodAttributes.Public | Reflect.MethodAttributes.Static,
                                              returnType,
                                              parameters);

        mbuilderTable.Add(s.Name, methb);

        this.il = methb.GetILGenerator();

        //Local variables
        if (p.Locales.Count > 0)
        {
            Hashtable h = new Hashtable();

            foreach (Symbol local in p.Locales.Values)
            {
                Emit.LocalBuilder lbuilder = this.il.DeclareLocal(getSystemTypeFormat(local.Type));
                h.Add(local.Name, lbuilder);
            }
            lbuilderTable.Add(s.Name, h);
        }
    }
Пример #48
0
        private MethodBuilder _Compile(FluentMethodBuilder method, int index)
        {
            var compiledMethodType = method._Precompile();

            MethodAttributes methodAttributes = MethodAttributes.Public;

            if (method.IsStatic)
            {
                methodAttributes |= MethodAttributes.Static;
            }
            else
            {
                methodAttributes |= MethodAttributes.Virtual;
            }

            // the originalParameterTypes don't include a Box<> or ByRef because
            // they come from a field.
            Type[] originalParameterTypes;

            // the parameterTypesForDelegate may have Box<> types.
            Type[] parameterTypesForDelegate;

            // the parameterTypesForGeneratedMethod will replace Box<> parameter by ref parameters.
            Type[] parameterTypesForGeneratedMethod;

            int parameterCount = method._parameters.Count;
            int parameterIndex = -1;

            using (var enumerator = method._parameters.GetEnumerator())
            {
                if (!method.IsStatic)
                {
                    parameterCount--;
                    enumerator.MoveNext();
                }

                originalParameterTypes           = new Type[parameterCount];
                parameterTypesForDelegate        = new Type[parameterCount];
                parameterTypesForGeneratedMethod = new Type[parameterCount];

                while (enumerator.MoveNext())
                {
                    parameterIndex++;
                    var pair = enumerator.Current;
                    var fieldInfoAndSourcePair = pair.Key;
                    var parameterExpression    = pair.Value;

                    var fieldType     = fieldInfoAndSourcePair.Key.FieldType;
                    var parameterType = parameterExpression.Type;
                    originalParameterTypes[parameterIndex]    = fieldType;
                    parameterTypesForDelegate[parameterIndex] = parameterType;

                    var parameterTypeForGeneratedMethod = fieldType;
                    if (parameterExpression.IsByRef || fieldType != parameterType)
                    {
                        parameterTypeForGeneratedMethod = fieldType.MakeByRefType();
                    }

                    parameterTypesForGeneratedMethod[parameterIndex] = parameterTypeForGeneratedMethod;
                }
            }

            var methodBuilder = _type.DefineMethod(method.Name, methodAttributes, method.ReturnType, parameterTypesForGeneratedMethod);

            foreach (var interfaceType in _interfaceTypes)
            {
                var methodToOverride = interfaceType.GetMethod(method.Name, originalParameterTypes);
                if (methodToOverride != null)
                {
                    _type.DefineMethodOverride(methodBuilder, methodToOverride);
                }
            }

            var methodGenerator = methodBuilder.GetILGenerator();

            int count = originalParameterTypes.Length;

            if (!method.IsStatic)
            {
                count++;
            }

            if (method._respectVisibility)
            {
                if (method.IsStatic)
                {
                    method._Compile(null, methodBuilder);
                }
                else
                {
                    var allParameterTypes = new Type[parameterTypesForGeneratedMethod.Length + 1];
                    allParameterTypes[0] = _type;
                    parameterTypesForGeneratedMethod.CopyTo(allParameterTypes, 1);

                    var otherMethod = _type.DefineMethod("." + method._delegateIndex, MethodAttributes.Static, method.ReturnType, allParameterTypes);
                    method._Compile(null, otherMethod);
                    _EmitDirectCall(methodBuilder, otherMethod, allParameterTypes.Length);
                }
            }
            else
            {
                methodGenerator.Emit(OpCodes.Ldsfld, _delegatesField);
                methodGenerator.Emit(OpCodes.Ldc_I4, index);
                methodGenerator.Emit(OpCodes.Ldelem, compiledMethodType);

                var locals = new List <LocalBuilder>();
                _GeneratePreCall(method, originalParameterTypes, methodGenerator, count, locals, parameterTypesForDelegate);

                methodGenerator.Emit(OpCodes.Callvirt, compiledMethodType.GetMethod("Invoke"));

                if (locals.Count > 0)
                {
                    _GeneratePosCall(method, originalParameterTypes, methodGenerator, count, locals, parameterTypesForDelegate);
                }

                methodGenerator.Emit(OpCodes.Ret);
            }

            return(methodBuilder);
        }
Пример #49
0
        private void GenerateProxyMethods(IEnumerable <Type> interfaces, TypeDefinition proxyType)
        {
            var methodsExcludingGetters = interfaces
                                          .SelectMany(x => x.GetMethods().Except(x.GetProperties().SelectMany(GetPropertyMethods)));

            foreach (var targetMethod in methodsExcludingGetters)
            {
                var baseDef = this.proxyBaseTypeDef;
                if (BaseTypeHasMatchingPublicMethod(baseDef, targetMethod))
                {
                    continue;
                }

                var genArgMapping = new Dictionary <Type, Type>();

                if (targetMethod.DeclaringType == null)
                {
                    throw new InvalidOperationException($"{targetMethod} has no declaring type.");
                }

                if (targetMethod.DeclaringType.IsGenericType)
                {
                    var declTypeGenArgs = targetMethod.DeclaringType
                                          .GetGenericArguments()
                                          .Zip(targetMethod.DeclaringType.GetGenericTypeDefinition().GetGenericArguments(),
                                               (a, p) => new { a, p });

                    foreach (var declTypeGenArg in declTypeGenArgs)
                    {
                        genArgMapping.Add(declTypeGenArg.p, declTypeGenArg.a);
                    }
                }

                Func <Type, Type> typeReplacer =
                    t => TypeUtils.ReplaceInGenericArguments(t, x => genArgMapping.SafeGet(x, x));
                var parameters = targetMethod.GetParameters();
                var paramTypes = parameters.Select(x => x.ParameterType).ToArray();
                var method     = proxyType.DefineMethod(targetMethod.Name,
                                                        MethodAttributes.NewSlot
                                                        | MethodAttributes.HideBySig
                                                        | MethodAttributes.Virtual
                                                        | MethodAttributes.Public,
                                                        targetMethod.ReturnType,
                                                        paramTypes);

                CopyGenericMethodParameters(targetMethod, method, genArgMapping, typeReplacer);

                AdjustParameterTypes(parameters, typeReplacer, method);

                var proxyOnGetMethod = baseDef
                                       .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
                                       .FirstOrDefault(x => x.Name == "OnInvokeMethod");

                if (proxyOnGetMethod == null)
                {
                    var message =
                        $"Unable to generate proxy for {targetMethod.GetFullNameWithSignature()} because {baseDef.FullName}.OnInvokeMethod() is missing.";
                    throw new MissingMethodException(message);
                }

                GenerateInvokeMethodIl(method, paramTypes, parameters, proxyOnGetMethod);
            }
        }
Пример #50
0
 /// <summary>
 /// Adds a new method to the class, with the given name and method signature.
 /// </summary>
 /// <param name="name">The name of the method. name cannot contain embedded nulls. </param>
 /// <param name="attributes">The attributes of the method. </param>
 /// <param name="returnType">The return type of the method.</param>
 /// <param name="parameterTypes">The types of the parameters of the method.</param>
 /// <returns>The defined method.</returns>
 public MethodBuilderHelper DefineMethod(
     string name, MethodAttributes attributes, Type returnType, params Type[] parameterTypes)
 {
     return(new MethodBuilderHelper(this, _typeBuilder.DefineMethod(name, attributes, returnType, parameterTypes)));
 }