DeclareLocal() public method

public DeclareLocal ( System localType ) : System.Reflection.Emit.LocalBuilder
localType System
return System.Reflection.Emit.LocalBuilder
コード例 #1
0
 public LocalVariableCollection(ILGenerator il, bool decode)
 {
     this.il = il;
     variables = new Dictionary<string, LocalBuilder>();
     dataPointer = il.DeclareLocal(typeof(byte*));
     remainingBytes = decode ? il.DeclareLocal(typeof(int)) : null;
 }
コード例 #2
0
        public override LocalBuilder BuildArguments(ILGenerator ilGenerator)
        {
            LocalBuilder propertyLocalBuilder = null;
            FieldBuilder contractFieldBuilder = null;
            LocalBuilder aspectArgLocalBuilder = null;
            ConstructorInfo ctorInterceptionArgs = null;
            AbstractAspectPropertyArgsWeaver methodWeaver = null;

            propertyLocalBuilder = LocalBuilderRepository.Declare(() => {
                return ilGenerator.DeclareLocal(typeof(PropertyInfo));
            });

            ctorInterceptionArgs = ArgumentType.GetConstructors()[0];
            aspectArgLocalBuilder = ilGenerator.DeclareLocal(ArgumentType);
            contractFieldBuilder = WeavingSettings.TypeDefinition.GetFieldBuilder(WeavingSettings.ContractType);
            methodWeaver = new AspectArgsGetPropertyWeaver(Member, propertyLocalBuilder, aspectWeavingSettings);
            methodWeaver.Weave(ilGenerator);
            ilGenerator.EmitLoadArg(0);
            ilGenerator.Emit(OpCodes.Ldfld, contractFieldBuilder);
            ilGenerator.EmitLoadLocal(propertyLocalBuilder);
            ilGenerator.Emit(OpCodes.Ldsfld, BindingsDependency);
            ilGenerator.Emit(OpCodes.Newobj, ctorInterceptionArgs);
            ilGenerator.EmitStoreLocal(aspectArgLocalBuilder);

            return aspectArgLocalBuilder;
        }
コード例 #3
0
        public static void FillEntity(ILGenerator generator, Type entityType, LocalBuilder entity)
        {
            //Dictionary<string, int> fields = DataPortal.FindFields(data);
            LocalBuilder fields = generator.DeclareLocal(typeof(Dictionary<string, int>));
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Call, typeof(DataPortal).GetMethod("FindFields", new Type[]{typeof(IDataRecord)}));
            generator.Emit(OpCodes.Stloc, fields);

            foreach(PropertyInfo property in entityType.GetProperties())
            {
                DbFieldAttribute fieldInfo = ReflectionHelper.GetAttribute<DbFieldAttribute>(property);
                if(fieldInfo == null)
                {
                    continue;
                }

                //int fieldIndex = DataPortal.FindField(fields, propInfo.Name);
                LocalBuilder fieldIndex = generator.DeclareLocal(typeof(Int32));
                generator.Emit(OpCodes.Ldloc, fields);
                generator.Emit(OpCodes.Ldstr, fieldInfo.FieldName);
                generator.Emit(OpCodes.Call, typeof(DataPortal).GetMethod("FindField", new Type[] { typeof(Dictionary<string, int>), typeof(string) }));
                generator.Emit(OpCodes.Stloc, fieldIndex);
                //if(fieldIndex >= 0)
                Label notFieldExists = generator.DefineLabel();
                generator.Emit(OpCodes.Ldloc, fieldIndex);
                generator.Emit(OpCodes.Ldc_I4_0);
                generator.Emit(OpCodes.Clt);
                generator.Emit(OpCodes.Brtrue_S, notFieldExists);
                {
                    FillProperty(generator, entityType, entity, property, fieldIndex);
                    generator.Emit(OpCodes.Nop);
                }
                generator.MarkLabel(notFieldExists);
            }
        }
コード例 #4
0
        public void EmitMethodBody(ILGenerator IL, MethodInfo method, FieldInfo field)
        {
            bool isStatic = false;

            ParameterInfo[] parameters = method.GetParameters();
            IL.DeclareLocal(typeof (object[]));
            IL.DeclareLocal(typeof (InvocationInfo));
            IL.DeclareLocal(typeof (Type[]));

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Callvirt, getInterceptor);

            // if (interceptor == null)
            // 		throw new NullReferenceException();

            Label skipThrow = IL.DefineLabel();

            IL.Emit(OpCodes.Dup);
            IL.Emit(OpCodes.Ldnull);
            IL.Emit(OpCodes.Bne_Un, skipThrow);

            IL.Emit(OpCodes.Newobj, notImplementedConstructor);
            IL.Emit(OpCodes.Throw);

            IL.MarkLabel(skipThrow);
            // Push the 'this' pointer onto the stack
            IL.Emit(OpCodes.Ldarg_0);

            // Push the MethodInfo onto the stack            
            Type declaringType = method.DeclaringType;
            
            IL.Emit(OpCodes.Ldtoken, method);
            if (declaringType.IsGenericType)
            {
                IL.Emit(OpCodes.Ldtoken, declaringType);
                IL.Emit(OpCodes.Call, getGenericMethodFromHandle);
            }
            else
            {
                IL.Emit(OpCodes.Call, getMethodFromHandle);
            }

            IL.Emit(OpCodes.Castclass, typeof (MethodInfo));

            PushStackTrace(IL);
            PushGenericArguments(method, IL);
            _argumentHandler.PushArguments(parameters, IL, isStatic);

            // InvocationInfo info = new InvocationInfo(...);

            IL.Emit(OpCodes.Newobj, infoConstructor);
            IL.Emit(OpCodes.Stloc_1);
            IL.Emit(OpCodes.Ldloc_1);
            IL.Emit(OpCodes.Callvirt, handlerMethod);

            SaveRefArguments(IL, parameters);
            PackageReturnType(method, IL);

            IL.Emit(OpCodes.Ret);
        }
コード例 #5
0
        public void EmitCalculateSize(ILGenerator il, Action<ILGenerator> emitLoad)
        {
            var valueIsNullOrEmptyLabel = il.DefineLabel();
            var valueHasElementsLabel = il.DefineLabel();
            var loopStartLabel = il.DefineLabel();
            var loopConditionLabel = il.DefineLabel();
            var endOfMethodLabel = il.DefineLabel();

            var iVar = il.DeclareLocal(typeof(int));          // int i
            var sumVar = il.DeclareLocal(typeof(int));        // int sum
            var elemVar = il.DeclareLocal(type);              // T elem

            emitLoad(il);                                     // if (!value)
            il.Emit(OpCodes.Brfalse, valueIsNullOrEmptyLabel);//     goto valueIsNullOrEmptyLabel

            emitLoad(il);                                     // if ((int)value.Length)
            il.Emit(OpCodes.Ldlen);                           //     goto valueHasElementsLabel
            il.Emit(OpCodes.Conv_I4);
            il.Emit(OpCodes.Brtrue, valueHasElementsLabel);

            il.MarkLabel(valueIsNullOrEmptyLabel);            // label valueIsNullOrEmptyLabel
            il.Emit_Ldc_I4(sizeof(int));                      // stack_0 = sizeof(int)
            il.Emit(OpCodes.Br, endOfMethodLabel);            // goto endOfMethodLabel

            il.MarkLabel(valueHasElementsLabel);              // label valueHasElementsLabel
            il.Emit_Ldc_I4(0);                                // i = 0
            il.Emit(OpCodes.Stloc, iVar);
            il.Emit_Ldc_I4(sizeof(int));                      // sum = sizeof(int)
            il.Emit(OpCodes.Stloc, sumVar);
            il.Emit(OpCodes.Br, loopConditionLabel);          // goto loopConditionLabel

            il.MarkLabel(loopStartLabel);                     // label loopStartLabel
            il.Emit(OpCodes.Ldloc, sumVar);                   // stack_0 = sum
            emitLoad(il);                                     // elem = value[i]
            il.Emit(OpCodes.Ldloc, iVar);
            EmitLdelem(il);
            il.Emit(OpCodes.Stloc, elemVar);
            elementCodec.EmitCalculateSize(il, elemVar);      // stack_1 = CalculateSize(elem)
            il.Emit(OpCodes.Add);                             // sum = stack_0 + stack_1
            il.Emit(OpCodes.Stloc, sumVar);
            il.Emit(OpCodes.Ldloc, iVar);                     // i++
            il.Emit_Ldc_I4(1);
            il.Emit(OpCodes.Add);
            il.Emit(OpCodes.Stloc, iVar);

            il.MarkLabel(loopConditionLabel);                 // label loopConditionLabel
            il.Emit(OpCodes.Ldloc, iVar);                     // if (i < (int)value.Length)
            emitLoad(il);                                     //     goto loopStartLabel
            il.Emit(OpCodes.Ldlen);
            il.Emit(OpCodes.Conv_I4);
            il.Emit(OpCodes.Blt, loopStartLabel);

            il.Emit(OpCodes.Ldloc, sumVar);                   // stack_0 = sum
            il.MarkLabel(endOfMethodLabel);                   // label endOfMethodLabel
        }
コード例 #6
0
ファイル: LocalVariable.cs プロジェクト: josiahdj/SDFCalc
		private LocalBuilder GetLocalBuilder(ILGenerator ilg) {
			if (localBuilder == null) {
				if (Type == Typ.Number) {
					this.localBuilder = ilg.DeclareLocal(typeof (double));
				}
				else {
					this.localBuilder = ilg.DeclareLocal(Value.type);
				}
			}
			return localBuilder;
		}
コード例 #7
0
        static void WriteDeserializerArray(TypeBuilder typeBuilder, ILGenerator il, Type type, int tag, MethodInfo setMethod,
            int? itemLocalIndex = null)
        {
            var itemType = type.GetElementType();

            var lengthLocal = il.DeclareLocal(typeof(int));
            var arrayLocal = il.DeclareLocal(type);
            var itemLocal = il.DeclareLocal(itemType);
            var indexLocal = il.DeclareLocal(typeof(int));
            var startLabel = il.DefineLabel();
            var endLabel = il.DefineLabel();

            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Ldc_I4, tag);
            il.Emit(OpCodes.Call, GetCollectionLengthMethod);
            il.Emit(OpCodes.Stloc, lengthLocal);
            il.Emit(OpCodes.Ldloc, lengthLocal.LocalIndex);
            il.Emit(OpCodes.Newarr, itemType);
            il.Emit(OpCodes.Stloc, arrayLocal.LocalIndex);

            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Stloc, indexLocal.LocalIndex);
            il.Emit(OpCodes.Br, startLabel);
            il.MarkLabel(endLabel);

            WriteDeserializerReadValue(typeBuilder, il, itemType, 1, itemLocal.LocalIndex);

            il.Emit(OpCodes.Ldloc, arrayLocal.LocalIndex);
            il.Emit(OpCodes.Ldloc, indexLocal.LocalIndex);
            il.Emit(OpCodes.Ldloc, itemLocal.LocalIndex);
            il.Emit(OpCodes.Stelem, itemType);

            il.Emit(OpCodes.Ldloc, indexLocal.LocalIndex);
            il.Emit(OpCodes.Ldc_I4_1);
            il.Emit(OpCodes.Add);
            il.Emit(OpCodes.Stloc, indexLocal.LocalIndex);
            il.MarkLabel(startLabel);
            il.Emit(OpCodes.Ldloc, indexLocal.LocalIndex);
            il.Emit(OpCodes.Ldloc, lengthLocal.LocalIndex);
            il.Emit(OpCodes.Blt, endLabel);

            if (itemLocalIndex == null) {
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldloc, arrayLocal.LocalIndex);
                il.Emit(OpCodes.Callvirt, setMethod);
            } else {
                il.Emit(OpCodes.Ldloc, arrayLocal.LocalIndex);
                il.Emit(OpCodes.Stloc, itemLocalIndex.Value);
            }
        }
コード例 #8
0
ファイル: FuncAdapter.cs プロジェクト: plurby/Jace
        private void GenerateMethodBody(ILGenerator generator, Jace.Execution.ParameterInfo[] parameters,
            Func<Dictionary<string, double>, double> function)
        {
            Type dictionaryType = typeof(Dictionary<string, double>);
            ConstructorInfo dictionaryConstructorInfo = dictionaryType.GetConstructor(Type.EmptyTypes);

            FieldInfo functionField = typeof(FuncAdapterArguments).GetField("function",
                BindingFlags.NonPublic | BindingFlags.Instance);

            generator.DeclareLocal(dictionaryType);
            generator.DeclareLocal(typeof(double));

            generator.Emit(OpCodes.Newobj, dictionaryConstructorInfo);
            generator.Emit(OpCodes.Stloc_0);

            for (int i = 0; i < parameters.Length; i++)
            {
                Jace.Execution.ParameterInfo parameter = parameters[i];

                generator.Emit(OpCodes.Ldloc_0);
                generator.Emit(OpCodes.Ldstr, parameter.Name);

                switch (i)
                {
                    case 0:
                        generator.Emit(OpCodes.Ldarg_1);
                        break;
                    case 1:
                        generator.Emit(OpCodes.Ldarg_2);
                        break;
                    case 2:
                        generator.Emit(OpCodes.Ldarg_3);
                        break;
                    default:
                        generator.Emit(OpCodes.Ldarg, i + 1);
                        break;
                }

                if (parameter.DataType != DataType.FloatingPoint)
                    generator.Emit(OpCodes.Conv_R8);

                generator.Emit(OpCodes.Callvirt, dictionaryType.GetMethod("Add", new Type[] { typeof(string), typeof(double) }));
            }

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, functionField);
            generator.Emit(OpCodes.Ldloc_0);
            generator.Emit(OpCodes.Callvirt, function.GetType().GetMethod("Invoke"));

            generator.Emit(OpCodes.Ret);
        }
コード例 #9
0
        public void Weave(ILGenerator ilGenerator)
        {
            var typeofType = typeof(Type);
            var typeofObject = typeof(object);
            FieldBuilder contractFieldBuilder = null;
            LocalBuilder typesArrayLocalBuilder = null;
            LocalBuilder tempTypesArrayLocalBuilder = null;
            var typeofArrayOfTypes = typeofType.MakeArrayType();
            var weavingSettings = aspectWeavingSettings.WeavingSettings;
            var getTypeFromHandleMethodInfo = typeofType.GetMethod("GetTypeFromHandle");
            var localBuilderRepository = aspectWeavingSettings.LocalBuilderRepository;

            typesArrayLocalBuilder = localBuilderRepository.Declare(() => {
                return ilGenerator.DeclareLocal(typeofArrayOfTypes);
            });

            tempTypesArrayLocalBuilder = ilGenerator.DeclareLocal(typeofArrayOfTypes);
            ilGenerator.EmitPushInteger(parameters.Length);
            ilGenerator.Emit(OpCodes.Newarr, typeofType);
            ilGenerator.EmitStoreLocal(tempTypesArrayLocalBuilder);

            parameters.ForEach((parameter, i) => {
                var isByRef = parameter.IsByRef;

                if (isByRef) {
                    parameter = parameter.GetElementType();
                }

                ilGenerator.EmitLoadLocal(tempTypesArrayLocalBuilder);
                ilGenerator.EmitPushInteger(i);
                ilGenerator.Emit(OpCodes.Ldtoken, parameter);
                ilGenerator.Emit(OpCodes.Call, getTypeFromHandleMethodInfo);

                if (isByRef) {
                    ilGenerator.Emit(OpCodes.Callvirt, typeofType.GetMethod("MakeByRefType"));
                }

                ilGenerator.Emit(OpCodes.Stelem_Ref);
            });

            ilGenerator.EmitLoadLocal(tempTypesArrayLocalBuilder);
            ilGenerator.EmitStoreLocal(typesArrayLocalBuilder);
            ilGenerator.EmitLoadArg(0);
            contractFieldBuilder = weavingSettings.TypeDefinition.GetFieldBuilder(weavingSettings.ContractType);
            ilGenerator.Emit(OpCodes.Ldfld, contractFieldBuilder);
            ilGenerator.Emit(OpCodes.Callvirt, typeofObject.GetMethod("GetType"));
            ilGenerator.Emit(OpCodes.Ldstr, method.Name);
            ilGenerator.EmitLoadLocal(typesArrayLocalBuilder);
            ilGenerator.Emit(OpCodes.Callvirt, typeofType.GetMethod("GetMethod", new[] { typeof(string), typeof(Type[]) }));
            ilGenerator.EmitStoreLocal(methodLocalBuilder);
        }
コード例 #10
0
		public override void AppendWrite(ILGenerator generator, MessageField field)
		{
			var done = generator.DefineLabel();
			var tmp = generator.DeclareLocal(typeof(Nullable<>).MakeGenericType(FieldType));

			generator.Emit(OpCodes.Ldloc_0);
			generator.Emit(OpCodes.Call, Property.GetGetMethod());
			generator.Emit(OpCodes.Stloc, tmp.LocalIndex);

			generator.Emit(OpCodes.Ldloca, tmp.LocalIndex);
			generator.Emit(OpCodes.Call, typeof(Nullable<>)
				.MakeGenericType(FieldType)
				.GetProperty("HasValue")
				.GetGetMethod());

			generator.Emit(OpCodes.Brfalse_S, done);

			field.AppendGuard(generator, Property.GetGetMethod(), done);
			field.AppendHeader(generator);

			generator.Emit(OpCodes.Ldloca, tmp.LocalIndex);
			generator.Emit(OpCodes.Call, typeof(Nullable<>)
				.MakeGenericType(FieldType)
				.GetProperty("Value")
				.GetGetMethod());

			field.AppendWriteField(generator);
			generator.Emit(OpCodes.Pop);
			generator.MarkLabel(done);
		}
コード例 #11
0
 protected override void EmitNullableCast(ILGenerator ilGenerator, Type nullableType)
 {
     ilGenerator.DeclareLocal(outputType);
     ilGenerator.Emit(OpCodes.Stloc_0);
     ilGenerator.Emit(OpCodes.Ldloca_S, 0);
     ilGenerator.Emit(OpCodes.Call, nullableType.GetProperty("Value").GetGetMethod());
 }
コード例 #12
0
ファイル: LetInEndNode.cs プロジェクト: hansel0691/Tiger
        public override void Generate(ILGenerator generator, Symbols symbols)
        {
            //Save the previous variables
            var currentVariables = new List<string>();
            foreach (var item in symbols.Variables)
            {
                currentVariables.Add(item.Key);
                generator.Emit(OpCodes.Ldsfld, symbols.Variables[item.Key]);
            }

            DeclarationBlock.Generate(generator, symbols);
            InstructionsBlock.Generate(generator, symbols);

            LocalBuilder returnValue = null;
            if (InstructionsBlock.ExpressionType.Type != TypesEnumeration.Void)
            {
                returnValue = generator.DeclareLocal(symbols.GetRealType(InstructionsBlock.ExpressionType.ILName));
                generator.Emit(OpCodes.Stloc, returnValue);
            }

            currentVariables.Reverse();
            //load in the variables it's previous values
            currentVariables.ForEach(x => generator.Emit(OpCodes.Stsfld, symbols.Variables[x]));
            if (InstructionsBlock.ExpressionType.Type != TypesEnumeration.Void)
                generator.Emit(OpCodes.Ldloc, returnValue);
        }
コード例 #13
0
ファイル: OrOperatorNode.cs プロジェクト: omederos/TigerNET
        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);
        }
コード例 #14
0
		public override void Emit(IEasyMember member, ILGenerator gen)
		{
			LocalBuilder local = gen.DeclareLocal( typeof(object[]) );
			gen.Emit(OpCodes.Ldc_I4, _args.Length);
			gen.Emit(OpCodes.Newarr, typeof(object));
			gen.Emit(OpCodes.Stloc, local);
			
			for(int i=0; i < _args.Length; i++)
			{
				gen.Emit(OpCodes.Ldloc, local);
				gen.Emit(OpCodes.Ldc_I4, i);

				TypeReference reference = _args[i];

				ArgumentsUtil.EmitLoadOwnerAndReference(reference, gen);

				if (reference.Type.IsByRef)
				{
					throw new NotSupportedException();
				}

				if (reference.Type.IsValueType)
				{
					gen.Emit(OpCodes.Box, reference.Type.UnderlyingSystemType);
				}
				
				gen.Emit(OpCodes.Stelem_Ref);
			}

			gen.Emit(OpCodes.Ldloc, local);
		}
コード例 #15
0
ファイル: ElemArrayNode.cs プロジェクト: oisbel/TigerCompiler
        public override void GenCode(TypeBuilder tb, MethodBuilder mb, ILGenerator cg)
        {
            Type type = Type.EmptyTypes.GetType();

            for (int i = 0; i < Compiler.Types.Count; i++)
                if (Compiler.Types[i].name == Expr.ReturnType.Name)
                    type = Compiler.SearchType(Compiler.Types[i].typeArray);

            if (assign)
            {
                assign = false;
                LocalBuilder local = cg.DeclareLocal(type);
                cg.Emit(OpCodes.Stloc, local);
                Expr.GenCode(tb, mb, cg);//pone el array, luego el index y luego el valor para hacer stelem
                Index.GenCode(tb, mb, cg);
                cg.Emit(OpCodes.Ldloc, local);
                cg.Emit(OpCodes.Stelem, type);
            }
            else
            {
                Expr.GenCode(tb, mb, cg);
                Index.GenCode(tb, mb, cg);
                cg.Emit(OpCodes.Ldelem, type);
            }
        }
コード例 #16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="il"></param>
        /// <param name="paramAttr"></param>
        /// <param name="parameterType"></param>
        public override void EmitParameterResolution(ILGenerator il, ParameterAttribute paramAttr, Type parameterType)
        {
            ProviderDependencyAttribute attr = (ProviderDependencyAttribute) paramAttr;
            MethodInfo getHeadOfChain = GetPropertyGetter<IBuilderContext>("HeadOfChain", typeof (IBuilderStrategy));
            MethodInfo buildUp = GetMethodInfo<IBuilderStrategy>("BuildUp",
                                                                 typeof (IBuilderContext), typeof (Type), typeof (object),
                                                                 typeof (string));

            PropertyInfo prop =
                attr.ProviderHostType.GetProperty(attr.ProviderGetterProperty, BindingFlags.Static | BindingFlags.Public);
            if (prop == null)
            {
                throw new ArgumentException();
            }

            MethodInfo propInvoker = prop.GetGetMethod();
            if (propInvoker == null)
            {
                throw new ArgumentException();
            }
            Guid.NewGuid();
            MethodInfo newGuidMethod = typeof (Guid).GetMethod("NewGuid");
            MethodInfo guidToStringMethod = typeof (Guid).GetMethod("ToString", new Type[] {});
            if ((newGuidMethod == null) || (guidToStringMethod == null))
            {
                throw new ArgumentException();
            }

            //object value (declaration)
            LocalBuilder valueIndex = il.DeclareLocal(typeof (object));

            //object value = prop.GetGetMethod().Invoke(attr.ProviderHostType, null);
            //value = propInvoker.Invoke(null) (return value remains in the stack)
            il.EmitCall(OpCodes.Call, propInvoker, null);
            il.Emit(OpCodes.Stloc, valueIndex);

            //string id = Guid.NewGuid().ToString();
            //il.Emit(OpCodes.Ldtoken, typeof(Guid));
            //il.EmitCall(OpCodes.Call, newGuidMethod, null);
            //il.EmitCall(OpCodes.Call, guidToStringMethod, null);
            //il.Emit(OpCodes.Stloc, idIndex);

            // Get the head of the context chain
            il.Emit(OpCodes.Ldarg_0); // Get context onto the stack
            il.EmitCall(OpCodes.Callvirt, getHeadOfChain, null); // Now head of chain is on the stack

            // Build up parameters to the BuildUp call - context, type, existing, id
            il.Emit(OpCodes.Ldarg_0); // Push context onto stack
            EmitLoadType(il, parameterType);

            // Existing object is value
            il.Emit(OpCodes.Ldloc, valueIndex);

            // And the id
            //il.Emit(OpCodes.Ldloc,idIndex);
            il.Emit(OpCodes.Ldarg_3);

            // Call buildup on head of the chain
            il.EmitCall(OpCodes.Callvirt, buildUp, null);
        }
コード例 #17
0
        public override void generar(Emit.ILGenerator il)
        {
            Emit.LocalBuilder tmpVarLogico;

            Console.WriteLine("Generando Nodo Condicional (IF)");
            this.condicion.generar(il);

            il.Emit(Emit.OpCodes.Ldc_I4_0); //Ingreso constante 0
            il.Emit(Emit.OpCodes.Ceq);      //Comparo si es falso (es 0)
            //Almaceno este resultado en una variable temporal
            tmpVarLogico = il.DeclareLocal(typeof(bool));
            il.Emit(Emit.OpCodes.Stloc, tmpVarLogico);
            //cargo el resultado de la variable temporal
            il.Emit(Emit.OpCodes.Ldloc, tmpVarLogico);
            Emit.Label bloqueFalso = il.DefineLabel();
            //salto en caso que sea verdadero el resultado es decir es cero la evaluacion del (pila==0) hago el sino
            il.Emit(Emit.OpCodes.Brtrue, bloqueFalso);

            Entonces.generar(il);

            Emit.Label finSi = il.DefineLabel();
            il.Emit(Emit.OpCodes.Br, finSi);
            il.MarkLabel(bloqueFalso);

            if (Sino != null)
            {
                Sino.generar(il);
            }

            il.MarkLabel(finSi);
        }
コード例 #18
0
        public override LocalBuilder BuildArguments(ILGenerator ilGenerator)
        {
            var aspectArgLocalBuilder = ilGenerator.DeclareLocal(ArgumentType);
            var eventArgumentContract = Member.ToEventArgumentContract();
            var ctorInterceptionArgs = ArgumentType.GetConstructors().Single(ctor => ctor.GetParameters().Length != 0);
            var eventBrokerProperty = eventArgumentContract.GetProperty("EventBroker");
            var eventBrokerType = eventBrokerProperty.PropertyType;
            var handlerType = eventBrokerType.GetGenericArguments().First();
            var parameters = handlerType.GetInvokeMethod().GetParameters();

            ilGenerator.EmitLoadArg(1);
            ilGenerator.Emit(OpCodes.Ldind_Ref);
            ilGenerator.EmitLoadArg(3);
            ilGenerator.Emit(OpCodes.Callvirt, eventArgumentContract.GetProperty("Event").GetGetMethod());
            ilGenerator.EmitLoadArg(3);
            ilGenerator.Emit(OpCodes.Callvirt, eventArgumentContract.GetProperty("Handler").GetGetMethod());
            ilGenerator.Emit(OpCodes.Ldsfld, BindingsDependency);
            ilGenerator.EmitLoadArg(3);
            ilGenerator.Emit(OpCodes.Callvirt, eventBrokerProperty.GetGetMethod());

            parameters.ForEach(1, (arg, i) => {
                var property = ArgumentType.GetProperty("Arg{0}".Fmt(i));

                ilGenerator.EmitLoadArg(3);
                ilGenerator.Emit(OpCodes.Callvirt, property.GetGetMethod());
            });

            ilGenerator.Emit(OpCodes.Newobj, ctorInterceptionArgs);
            ilGenerator.EmitStoreLocal(aspectArgLocalBuilder);

            return aspectArgLocalBuilder;
        }
コード例 #19
0
        public virtual void GenerateMethod(PropertyInfo pi, MethodInfo mi, ILGenerator gen)
        {
            gen.DeclareLocal(typeof(Type));
            gen.EmitLdType(mi.GetGenericArguments()[0]);
            gen.Emit(OpCodes.Stloc_0);

            foreach (var scc in _pcb.ProxyCoderContext.MixinCoderContexts.SelectMany(a => a.SubjectCoderContexts))
            {
                var smes = scc.GetPerSubjectCoder<ISubjectMethodExistsPerSubjectCoder>();
                if (smes==null)
                    continue;

                var falseTarget = gen.DefineLabel();
                gen.Emit(OpCodes.Ldloc_0);
                gen.EmitLdType(scc.SubjectType);
                gen.EmitOpEqualityCall(typeof(Type));
                gen.Emit(OpCodes.Brfalse, falseTarget);
                smes.PutSubjectMethodExistsOnStack(gen);
                // Required for PE Verification
                gen.Emit(OpCodes.Castclass, mi.ReturnType);
                gen.Emit(OpCodes.Ret);
                gen.MarkLabel(falseTarget);
            }

            gen.Emit(OpCodes.Ldnull);
            gen.Emit(OpCodes.Ret);
        }
コード例 #20
0
ファイル: CodeGenerate.cs プロジェクト: josiahdj/SDFCalc
		/// <summary>
		/// Initializes the CodeGenerator infrastructure, binds the ILGenerator, 
		/// creates temporaries; resets evaluation condition caches.
		/// Ready to compile a new SDF.
		/// </summary>
		/// <param name="ilg">The ILGenerator used by all compile methods</param>
		public static void Initialize(ILGenerator ilg) {
			CodeGenerate.ilg = ilg;
			numberVariables = new Dictionary<FullCellAddr, Variable>();
			testDouble = ilg.DeclareLocal(typeof (double));
			testValue = ilg.DeclareLocal(Value.type);
			tmpFullCellAddr = ilg.DeclareLocal(FullCellAddr.type);
		}
コード例 #21
0
        public override LocalBuilder BuildArguments(ILGenerator ilGenerator)
        {
            var typeDefinition = (IAspectTypeDefinition)WeavingSettings.TypeDefinition;
            var aspectArgLocalBuilder = ilGenerator.DeclareLocal(ArgumentType);
            var eventLocalBuilder = ilGenerator.DeclareLocal(typeof(EventInfo));
            var contractFieldBuilder = typeDefinition.GetFieldBuilder(WeavingSettings.ContractType);
            var eventArgumentContract = Member.ToEventArgumentContract();
            var eventBrokerProperty = eventArgumentContract.GetProperty("EventBroker");
            var eventBrokerType = eventBrokerProperty.PropertyType;
            var handlerType = eventBrokerType.GetGenericArguments().First();
            var delegateLocalBuilder = ilGenerator.DeclareLocal(handlerType);
            var delegateCtor = handlerType.GetConstructor(new[] { typeof(object), typeof(IntPtr) });
            var eventBrokerFieldBuilder = typeDefinition.GetEventFieldBuilder(Member.Name, eventBrokerType);
            var eventBrokerFieldTypeDefinition = typeDefinition.GetEventBrokerFielTypeDefinition(Member);
            var ctorInterceptionArgs = ArgumentType.GetConstructors().Single(ctor => ctor.GetParameters().Length != 0);
            var parameters = handlerType.GetInvokeMethod().GetParameters();

            ilGenerator.EmitLoadArg(1);
            ilGenerator.Emit(OpCodes.Ldftn, eventBrokerFieldTypeDefinition.Event.EventHandlerType.GetInvokeMethod());
            ilGenerator.Emit(OpCodes.Newobj, delegateCtor);
            ilGenerator.EmitStoreLocal(delegateLocalBuilder);
            ilGenerator.EmitLoadArg(0);
            ilGenerator.Emit(OpCodes.Ldfld, contractFieldBuilder);
            ilGenerator.Emit(OpCodes.Callvirt, typeof(object).GetMethod("GetType"));
            ilGenerator.Emit(OpCodes.Ldstr, Member.Name);
            ilGenerator.Emit(OpCodes.Callvirt, typeof(Type).GetMethod("GetEvent", new[] { typeof(string) }));
            ilGenerator.EmitStoreLocal(eventLocalBuilder);
            ilGenerator.EmitLoadArg(0);
            ilGenerator.Emit(OpCodes.Ldfld, contractFieldBuilder);
            ilGenerator.EmitLoadLocal(eventLocalBuilder);
            ilGenerator.EmitLoadLocal(delegateLocalBuilder);
            ilGenerator.Emit(OpCodes.Ldsfld, BindingsDependency);
            ilGenerator.EmitLoadArg(0);
            ilGenerator.Emit(OpCodes.Ldfld, eventBrokerFieldBuilder);

            parameters.ForEach(1, (arg, i) => {
                var property = ArgumentType.GetProperty("Arg{0}".Fmt(i));

                ilGenerator.EmitLoadArg(1);
                ilGenerator.Emit(OpCodes.Callvirt, property.GetGetMethod());
            });

            ilGenerator.Emit(OpCodes.Newobj, ctorInterceptionArgs);
            ilGenerator.EmitStoreLocal(aspectArgLocalBuilder);

            return aspectArgLocalBuilder;
        }
コード例 #22
0
		public void GenerateWriterMethod(Type obtype, CodeGenContext ctx, ILGenerator il)
		{
			var getTypeIDMethodInfo = typeof(Serializer).GetMethod("GetTypeID", BindingFlags.NonPublic | BindingFlags.Instance, null,
				new Type[] { typeof(object) }, null);

			var map = ctx.TypeMap;

			// arg0: Serializer, arg1: Stream, arg2: object

			var idLocal = il.DeclareLocal(typeof(ushort));

			// get TypeID from object's Type
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldarg_2);
			il.Emit(OpCodes.Call, getTypeIDMethodInfo);
			il.Emit(OpCodes.Stloc_S, idLocal);

			// write typeID
			il.Emit(OpCodes.Ldarg_1);
			il.Emit(OpCodes.Ldloc_S, idLocal);
			il.Emit(OpCodes.Call, ctx.GetWriterMethodInfo(typeof(ushort)));

			// +1 for 0 (null)
			var jumpTable = new Label[map.Count + 1];
			jumpTable[0] = il.DefineLabel();
			foreach (var kvp in map)
				jumpTable[kvp.Value.TypeID] = il.DefineLabel();

			il.Emit(OpCodes.Ldloc_S, idLocal);
			il.Emit(OpCodes.Switch, jumpTable);

			il.Emit(OpCodes.Newobj, Helpers.ExceptionCtorInfo);
			il.Emit(OpCodes.Throw);

			/* null case */
			il.MarkLabel(jumpTable[0]);
			il.Emit(OpCodes.Ret);

			/* cases for types */
			foreach (var kvp in map)
			{
				var type = kvp.Key;
				var data = kvp.Value;

				il.MarkLabel(jumpTable[data.TypeID]);

				if (data.NeedsInstanceParameter)
					il.Emit(OpCodes.Ldarg_0);

				il.Emit(OpCodes.Ldarg_1);
				il.Emit(OpCodes.Ldarg_2);
				il.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type);

				il.Emit(OpCodes.Tailcall);
				il.Emit(OpCodes.Call, data.WriterMethodInfo);

				il.Emit(OpCodes.Ret);
			}
		}
コード例 #23
0
        static void WriteSerializerArray(TypeBuilder typeBuilder, ILGenerator il, Type type, MethodInfo valueMethod,
            int? valueLocalIndex = null, OpCode? valueLocalOpCode = null)
        {
            var itemType = type.GetElementType();
            var itemLocal = il.DeclareLocal(itemType);
            var listLocal = il.DeclareLocal(type);
            var indexLocal = il.DeclareLocal(typeof(int));
            var startLabel = il.DefineLabel();
            var endLabel = il.DefineLabel();

            if (valueLocalIndex != null) il.Emit(valueLocalOpCode.Value, valueLocalIndex.Value);
            if (valueMethod != null) {
                if (valueLocalIndex == null) il.Emit(OpCodes.Ldarg_2);
                il.Emit(OpCodes.Callvirt, valueMethod);
            }

            il.Emit(OpCodes.Stloc, listLocal.LocalIndex);
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Stloc_S, indexLocal.LocalIndex);
            il.Emit(OpCodes.Br, startLabel);
            il.MarkLabel(endLabel);
            il.Emit(OpCodes.Ldloc, listLocal.LocalIndex);
            il.Emit(OpCodes.Ldloc_S, indexLocal.LocalIndex);
            il.Emit(OpCodes.Ldelem, itemType);
            il.Emit(OpCodes.Stloc, itemLocal.LocalIndex);
            if (itemType.IsComplexType()) {
                if (itemType.IsCollectionType())
                    WriteSerializerClass(typeBuilder, il, itemType, 1, null, callerType: itemType, valueLocalIndex: itemLocal.LocalIndex,
                    valueLocalOpCode: OpCodes.Ldloc);
                else
                    WriteSerializerCallClassMethod(typeBuilder, il, itemType, OpCodes.Ldloc, itemLocal.LocalIndex, 1, null,
                        needClassHeader: false);
            } else {
                WriteSerializerBytesToStream(il, itemType, OpCodes.Ldloc, itemLocal.LocalIndex, 1, null, isTargetCollection: true);
            }
            il.Emit(OpCodes.Ldloc_S, indexLocal.LocalIndex);
            il.Emit(OpCodes.Ldc_I4_1);
            il.Emit(OpCodes.Add);
            il.Emit(OpCodes.Stloc_S, indexLocal.LocalIndex);
            il.MarkLabel(startLabel);
            il.Emit(OpCodes.Ldloc_S, indexLocal.LocalIndex);
            il.Emit(OpCodes.Ldloc, listLocal.LocalIndex);
            il.Emit(OpCodes.Ldlen);
            il.Emit(OpCodes.Conv_I4);
            il.Emit(OpCodes.Blt, endLabel);
        }
コード例 #24
0
        public void Weave(ILGenerator ilGenerator)
        {
            var typeofException = typeof(Exception);
            LocalBuilder exceptionLocalBuilder = null;
            var typeofFlowBehavior = typeof(FlowBehavior);
            LocalBuilder flowBehavoiurLocalBuilder = null;
            var afterRethrowLabel = ilGenerator.DefineLabel();
            var throwFlowBehaviorLabel = ilGenerator.DefineLabel();
            var rethrowFlowBehaviorLabel = ilGenerator.DefineLabel();
            var argsImplLocalBuilder = localBuilderRepository.Get(aspectArgumentType);
            var jumpTable = new[] { throwFlowBehaviorLabel, rethrowFlowBehaviorLabel };
            var setExceptionMethodInfo = aspectArgumentType.GetProperty("Exception").GetSetMethod();
            var flowBehaviorMethodInfo = aspectArgumentType.GetProperty("FlowBehavior").GetGetMethod();

            exceptionLocalBuilder = localBuilderRepository.GetOrDeclare(typeofException, () => {
                return ilGenerator.DeclareLocal(typeofException);
            });

            flowBehavoiurLocalBuilder = localBuilderRepository.GetOrDeclare(typeofFlowBehavior, () => {
                return ilGenerator.DeclareLocal(typeofFlowBehavior);
            });

            ilGenerator.BeginCatchBlock(typeofException);
            ilGenerator.EmitStoreLocal(exceptionLocalBuilder);
            ilGenerator.EmitLoadLocal(argsImplLocalBuilder);
            ilGenerator.EmitLoadLocal(exceptionLocalBuilder);
            ilGenerator.Emit(OpCodes.Callvirt, setExceptionMethodInfo);

            catchWeavers.ForEach(weaver => weaver.Weave(ilGenerator));

            ilGenerator.EmitLoadLocal(argsImplLocalBuilder);
            ilGenerator.Emit(OpCodes.Callvirt, flowBehaviorMethodInfo);
            ilGenerator.EmitStoreLocal(flowBehavoiurLocalBuilder);
            ilGenerator.EmitLoadLocal(flowBehavoiurLocalBuilder);
            ilGenerator.EmitPushInteger(1);
            ilGenerator.Emit(OpCodes.Sub);
            ilGenerator.Emit(OpCodes.Switch, jumpTable);
            ilGenerator.Emit(OpCodes.Br_S, afterRethrowLabel);
            ilGenerator.MarkLabel(throwFlowBehaviorLabel);
            ilGenerator.EmitLoadLocal(exceptionLocalBuilder);
            ilGenerator.Emit(OpCodes.Throw);
            ilGenerator.MarkLabel(rethrowFlowBehaviorLabel);
            ilGenerator.Emit(OpCodes.Rethrow);
            ilGenerator.MarkLabel(afterRethrowLabel);
        }
コード例 #25
0
ファイル: CodeEmitter.cs プロジェクト: Semogj/ikvm-fork
		internal void Emit(ILGenerator ilgen, OpCode opcode)
		{
			if (local == null)
			{
				// it's a temporary local that is only allocated on-demand
				local = ilgen.DeclareLocal(type);
			}
			ilgen.Emit(opcode, local);
		}
コード例 #26
0
        /// <summary>
        /// Creates local variable declarations.
        /// </summary>
        /// <param name="il">The IL generator to use.</param>
        /// <param name="method">The method to proxy.</param>
        protected override void DeclareLocals(ILGenerator il, MethodInfo method)
        {
            base.DeclareLocals(il, method);
            target = il.DeclareLocal(typeof(object));

#if DEBUG
            target.SetLocalSymInfo("target");
#endif
        }
コード例 #27
0
ファイル: VariableNode.cs プロジェクト: mirhagk/IronTuring
 public override void GenerateIL(ILGenerator il, SymbolTable st)
 {
     if (CanReduce)
         base.GenerateIL(il, st);
     var name = VariableNames[0];
     st.AddLocal(name, il.DeclareLocal(InitialValue.TypeOfExpression()));
     InitialValue.GenerateIL(il, st);
     il.Emit(OpCodes.Stloc, st.Locals[name].LocalIndex);
 }
コード例 #28
0
ファイル: PackILGenerator.cs プロジェクト: e-travel/msgpack
        public static void EmitPackCode(Type type, MethodInfo mi, ILGenerator il,
			Func<Type,MemberInfo[]> targetMemberSelector,
			Func<MemberInfo,string> memberNameFormatter,
			Func<Type, MethodInfo> lookupPackMethod)
        {
            if ((type.IsPrimitive || type.IsInterface) && !type.IsMap())
                throw new NotSupportedException ();

            Variable arg_writer = Variable.CreateArg (0);
            Variable arg_obj = Variable.CreateArg (1);

            if (!type.IsValueType) { // null check
                Label notNullLabel = il.DefineLabel ();
                il.EmitLd (arg_obj);
                il.Emit (OpCodes.Brtrue_S, notNullLabel);
                il.EmitLd (arg_writer);
                il.Emit (OpCodes.Call, typeof(MsgPackWriter).GetMethod("WriteNil", new Type[0]));
                il.Emit (OpCodes.Ret);
                il.MarkLabel (notNullLabel);
            }

            if (type.IsArray)
            {
                EmitPackArrayCode(mi, il, type, arg_writer, arg_obj, Variable.CreateLocal(il.DeclareLocal(typeof(int))), lookupPackMethod);
                goto FinallyProcess;
            }
            if (type.IsMap())
            {
                //EmitPackDictCode(mi, il, type, arg_writer, arg_obj, lookupPackMethod);
                Compiler.DictionaryILGenerator.EmitPackIL(mi, il, type, arg_writer, arg_obj, lookupPackMethod);
                goto FinallyProcess;
            }
            // MsgPackWriter.WriteMapHeader
            MemberInfo[] members = targetMemberSelector(type);
            il.EmitLd(arg_writer);
            il.EmitLdc(members.Length);
            il.Emit(OpCodes.Callvirt, typeof(MsgPackWriter).GetMethod("WriteMapHeader", new Type[] { typeof(int) }));

            for (int i = 0; i < members.Length; i++)
            {
                MemberInfo m = members[i];
                Type mt = m.GetMemberType();

                // write field-name
                il.EmitLd(arg_writer);
                il.EmitLdstr(memberNameFormatter(m));
                il.EmitLd_True();
                il.Emit(OpCodes.Call, typeof(MsgPackWriter).GetMethod("Write", new Type[] { typeof(string), typeof(bool) }));

                // write value
                EmitPackMemberValueCode(mt, il, arg_writer, arg_obj, m, null, type, mi, lookupPackMethod);
            }

            FinallyProcess:
            il.Emit (OpCodes.Ret);
        }
コード例 #29
0
        public override void Weave(ILGenerator ilGenerator)
        {
            LocalBuilder bindingLocalBuilder = null;
            var bindingsReflectedType = bindingDependency.ReflectedType;

            bindingLocalBuilder = ilGenerator.DeclareLocal(bindingsReflectedType);
            localBuilderRepository.Add(bindingLocalBuilder);
            argumentsWeaver.Weave(ilGenerator);
            weaver.Weave(ilGenerator);
        }
コード例 #30
0
        public override void GenerateCode(ILGenerator codeGenerator, TypeBuilder typeBuilder, ModuleBuilder moduleBuilder)
        {
            LetVariableBuilder = typeBuilder.DefineField(Environment.GetName(VariableName), Environment.GetCLRType(RelatedType), FieldAttributes.Static | FieldAttributes.Public);
            LocalBuilder = codeGenerator.DeclareLocal(LetVariableBuilder.FieldType);

            codeGenerator.Emit(OpCodes.Ldsfld, LetVariableBuilder);
            codeGenerator.Emit(OpCodes.Stloc, LocalBuilder);
            InitialExp.GenerateCode(codeGenerator, typeBuilder, moduleBuilder);
            codeGenerator.Emit(OpCodes.Stsfld, LetVariableBuilder);
        }
コード例 #31
0
        public virtual void GenerateReaderMethod(Serializer serializer, Type type, ILGenerator il)
        {
            var valueType = type.GetGenericArguments()[0];

            var hasValueLocal = il.DeclareLocal(typeof(bool));
            var valueLocal = il.DeclareLocal(valueType);

            var notNullLabel = il.DefineLabel();

            var data = serializer.GetIndirectData(valueType);

            // read array len
            il.Emit(OpCodes.Ldarg_1);                   // Stream
            il.Emit(OpCodes.Ldloca_S, hasValueLocal);   // &hasValue
            il.Emit(OpCodes.Call, serializer.GetDirectReader(typeof(bool)));

            // if hasValue == 0, return null
            il.Emit(OpCodes.Ldloc_S, hasValueLocal);
            il.Emit(OpCodes.Brtrue_S, notNullLabel);

            il.Emit(OpCodes.Ldarg_2);       // &value
            il.Emit(OpCodes.Initobj, type);
            il.Emit(OpCodes.Ret);

            // hasValue == 1
            il.MarkLabel(notNullLabel);

            if (data.ReaderNeedsInstance)
                il.Emit(OpCodes.Ldarg_0);   // Serializer
            il.Emit(OpCodes.Ldarg_1);       // Stream
            il.Emit(OpCodes.Ldloca_S, valueLocal);
            il.Emit(OpCodes.Call, data.ReaderMethodInfo);

            il.Emit(OpCodes.Ldarg_2);       // &value

            il.Emit(OpCodes.Ldloc_S, valueLocal);
            var constr = type.GetConstructor(new[] { valueType });
            il.Emit(OpCodes.Newobj, constr);    // new Nullable<T>(valueLocal)

            il.Emit(OpCodes.Stobj, type);       // store to &value

            il.Emit(OpCodes.Ret);
        }
コード例 #32
0
        ///<inheritdoc/>
        public override ILLocalVariable DeclareVariable(Type type, string name = null, bool pinned = false)
        {
            var localBuilder = Generator.DeclareLocal(type, pinned);

#if NETFRAMEWORK
            if (EmitDebugInfo && name != null)
            {
                localBuilder.SetLocalSymInfo(name);
            }
#endif
            return(new ILLocalVariable(localBuilder, name));
        }
コード例 #33
0
ファイル: RepitaHasta.cs プロジェクト: xiul/TinySharp
        public override void generar(Emit.ILGenerator il)
        {
            Emit.LocalBuilder tmpCondicion;
            tmpCondicion = il.DeclareLocal(typeof(bool));
            Emit.Label sentenciasRepita = il.DefineLabel();
            il.MarkLabel(sentenciasRepita);
            il.Emit(Emit.OpCodes.Nop);          //emito primera sentencia vacia

            Sentencias.generar(il);

            Condicion.generar(il);

            il.Emit(Emit.OpCodes.Stloc, tmpCondicion);  //almaceno resultado de condicion del mientras
            il.Emit(Emit.OpCodes.Ldloc, tmpCondicion);  //cargo resultado de condicion del mientras
            il.Emit(Emit.OpCodes.Brfalse, sentenciasRepita);
        }
コード例 #34
0
 /// <summary>
 /// Fill the DynamicMethod with a stub.
 /// </summary>
 public static SRE.DynamicMethod Stub(this SRE.DynamicMethod dm)
 {
     SRE.ILGenerator il = dm.GetILGenerator();
     for (int i = 0; i < 32; i++)
     {
         // Prevent mono from inlining the DynamicMethod.
         il.Emit(SRE.OpCodes.Nop);
     }
     if (dm.ReturnType != typeof(void))
     {
         il.DeclareLocal(dm.ReturnType);
         il.Emit(SRE.OpCodes.Ldloca_S, (sbyte)0);
         il.Emit(SRE.OpCodes.Initobj, dm.ReturnType);
         il.Emit(SRE.OpCodes.Ldloc_0);
     }
     il.Emit(SRE.OpCodes.Ret);
     return(dm);
 }
コード例 #35
0
        //Almacena el valor del tope de la pila en el nombre de variable proporcionado (no maneja ambito)
        public static void Almacenar(string nombre, Emit.ILGenerator _il)
        {
            if (!TablaDireccionesSimbolos.ContainsKey(nombre))
            {
                TablaDireccionesSimbolos[nombre] = _il.DeclareLocal(typeof(System.Int32));  //Solo variables enteras
            }

            Emit.LocalBuilder variableLocal = TablaDireccionesSimbolos[nombre];

            if (!variableLocal.LocalType.HasElementType) //(es una variable simple) verdadero solo en caso de vectores o matrices
            {
                _il.Emit(Emit.OpCodes.Stloc, TablaDireccionesSimbolos[nombre]);
            }
            else //es una matriz o vector y actuo acorde
            {
                throw new System.Exception("No se soportan arrays o matrices en las asignaciones");
            }
        }
コード例 #36
0
    public void GenerateStatement(Statement _statement)
    {
        if (_statement is StatementSequence)
        {
            StatementSequence _StatementSequence = (StatementSequence)_statement;
            GenerateStatement(_StatementSequence.Left);
            GenerateStatement(_StatementSequence.Right);
        }

        else if (_statement is DeclareVariable)
        {
            // declare a variable in symbol table
            DeclareVariable declare = (DeclareVariable)_statement;
            tblIdentifier[declare.Identifier] =
                _ILGenerator.DeclareLocal(GetExpressionType(declare.Expression));

            // set the initial value
            Assignment assign = new Assignment();
            assign.Identifier = declare.Identifier;
            assign.Expression = declare.Expression;
            GenerateStatement(assign);
        }

        else if (_statement is Assignment)
        {
            Assignment assign = (Assignment)_statement;
            GenerateExpression(assign.Expression,
                               GetExpressionType(assign.Expression));
            if (GetExpressionType(assign.Expression) == typeof(ArithmaticExpression))
            {
                SaveIdentifier(assign.Identifier, typeof(Int32));
            }
            else
            {
                SaveIdentifier(assign.Identifier,
                               GetExpressionType(assign.Expression));
            }
        }

        else if (_statement is DeclareFunction)
        {
            GenerateStatementMethod(_statement);
        }

        else if (_statement is Write)
        {
            // for print keyword, call .net method for printscreen
            GenerateExpression(((Write)_statement).Expression,
                               typeof(string));
            _ILGenerator.Emit(OpCodes.Call,
                              typeof(System.Console).GetMethod("WriteLine",
                                                               new System.Type[] { typeof(string) }));
        }

        else if (_statement is ReadInput)
        {
            // call the readline method and parse input method
            _ILGenerator.Emit(OpCodes.Call,
                              typeof(System.Console).GetMethod("ReadLine",
                                                               BindingFlags.Public | BindingFlags.Static,
                                                               null, new System.Type[] { }, null));
            _ILGenerator.Emit(OpCodes.Call,
                              typeof(int).GetMethod("Parse",
                                                    BindingFlags.Public | BindingFlags.Static,
                                                    null, new System.Type[] { typeof(string) }, null));
            // store the input value in local builder
            SaveIdentifier(((ReadInput)_statement).Identifier, typeof(int));
        }
        else if (_statement is IfThenElse)
        {
            //IfThenElse ifThenElse = (IfThenElse)stmt;
            //RelationalExpression relExpr = (RelationalExpression)ifThenElse.If;
            //// if, left side only
            //il.Emit(OpCodes.Stloc, symbolTable[relExpr.Left.ToString()]);
            //Label lblIf = il.DefineLabel();
            //il.Emit(OpCodes.Br, lblIf);
            //// then
            //Label lblThen = il.DefineLabel();
            //il.MarkLabel(lblThen);
        }

        else if (_statement is While)
        {
            While _while  = (While)_statement;
            Label lblTest = _ILGenerator.DefineLabel();
            Label lblEnd  = _ILGenerator.DefineLabel();

            if (_while.Operand == RelationalOperands.GreaterThan)
            {
                _ILGenerator.MarkLabel(lblTest);
                GenerateExpression(_while.LeftExpression, typeof(int));
                GenerateExpression(_while.RightExpression, typeof(int));
                _ILGenerator.Emit(OpCodes.Cgt);
                _ILGenerator.Emit(OpCodes.Brfalse, lblEnd);
                GenerateStatement(_while.Body);
                _ILGenerator.Emit(OpCodes.Br, lblTest);

                _ILGenerator.MarkLabel(lblEnd);
            }
            else if (_while.Operand == RelationalOperands.EqualTo)
            {
                _ILGenerator.MarkLabel(lblTest);
                GenerateExpression(_while.LeftExpression, typeof(int));
                GenerateExpression(_while.RightExpression, typeof(int));
                _ILGenerator.Emit(OpCodes.Ceq);
                _ILGenerator.Emit(OpCodes.Brfalse, lblEnd);
                GenerateStatement(_while.Body);
                _ILGenerator.Emit(OpCodes.Br, lblTest);

                _ILGenerator.MarkLabel(lblEnd);
            }
            else if (_while.Operand == RelationalOperands.LessThan)
            {
                _ILGenerator.MarkLabel(lblTest);
                GenerateExpression(_while.LeftExpression, typeof(int));
                GenerateExpression(_while.RightExpression, typeof(int));
                _ILGenerator.Emit(OpCodes.Clt);
                _ILGenerator.Emit(OpCodes.Brfalse, lblEnd);
                GenerateStatement(_while.Body);
                _ILGenerator.Emit(OpCodes.Br, lblTest);

                _ILGenerator.MarkLabel(lblEnd);
            }
        }
        else if (_statement is IfThen)
        {
            #region
            //////Label body = il.DefineLabel();

            //////il.Emit(OpCodes.Ldc_I4, 1000);



            /*
             * // var x = 0;
             * // if x < 5 then
             * //    print "less than 5";
             * // endif;
             *
             * IfThen ifThen = (IfThen)stmt;
             * // jump to test
             *
             *
             * // **test** if x LessThan 5? (do the test)
             * il.MarkLabel(test);
             * GenExpr(ifThen.LeftExpression, typeof(int));
             *
             */

            //Label greaterThan = il.DefineLabel();

            //IfThen ifThen = (IfThen)stmt;
            //GenExpr(ifThen.LeftExpression, typeof(int));
            //GenExpr(ifThen.RightExpression, typeof(int));
            //if (ifThen.Operand == RelationalOperands.GreaterThan)
            //{
            //
            //}
            #endregion

            IfThen ifThen  = (IfThen)_statement;
            Label  lblElse = _ILGenerator.DefineLabel();
            Label  lblEnd  = _ILGenerator.DefineLabel();

            #region GreaterThan
            if (ifThen.Operand == RelationalOperands.GreaterThan)
            {
                GenerateExpression(ifThen.LeftExpression, typeof(int));
                GenerateExpression(ifThen.RightExpression, typeof(int));
                _ILGenerator.Emit(OpCodes.Cgt);
                _ILGenerator.Emit(OpCodes.Brfalse, lblElse);
                GenerateStatement(ifThen.ThenBody);
                _ILGenerator.Emit(OpCodes.Br, lblEnd);

                _ILGenerator.MarkLabel(lblElse);
                GenerateStatement(ifThen.ElseBody);

                _ILGenerator.MarkLabel(lblEnd);
            }
            #endregion
            #region EqualTo
            else if (ifThen.Operand == RelationalOperands.EqualTo)
            {
                GenerateExpression(ifThen.LeftExpression, typeof(int));
                GenerateExpression(ifThen.RightExpression, typeof(int));
                _ILGenerator.Emit(OpCodes.Ceq);
                _ILGenerator.Emit(OpCodes.Brfalse, lblElse);
                GenerateStatement(ifThen.ThenBody);
                _ILGenerator.Emit(OpCodes.Br, lblEnd);

                _ILGenerator.MarkLabel(lblElse);
                GenerateStatement(ifThen.ElseBody);

                _ILGenerator.MarkLabel(lblEnd);
            }
            #endregion
            #region LessThan
            else if (ifThen.Operand == RelationalOperands.LessThan)
            {
                GenerateExpression(ifThen.LeftExpression, typeof(int));
                GenerateExpression(ifThen.RightExpression, typeof(int));
                _ILGenerator.Emit(OpCodes.Clt);
                _ILGenerator.Emit(OpCodes.Brfalse, lblElse);
                GenerateStatement(ifThen.ThenBody);
                _ILGenerator.Emit(OpCodes.Br, lblEnd);

                _ILGenerator.MarkLabel(lblElse);
                GenerateStatement(ifThen.ElseBody);

                _ILGenerator.MarkLabel(lblEnd);
            }
            #endregion

            #region

            /*
             * Label gtTrue = il.DefineLabel();
             * Label gtFalse = il.DefineLabel();
             *
             *
             */
            #endregion
        }
        else if (_statement is For)
        {
            // example:
            // for x = 0 to 100 do
            //   print "hello";
            // end;

            // x = 0
            For        forLoop = (For)_statement;
            Assignment assign  = new Assignment();
            assign.Identifier = forLoop.Identifier;
            assign.Expression = forLoop.From;
            GenerateStatement(assign);
            // jump to the test
            Label test = _ILGenerator.DefineLabel();
            _ILGenerator.Emit(OpCodes.Br, test);

            // body statement
            Label body = _ILGenerator.DefineLabel();
            _ILGenerator.MarkLabel(body);
            GenerateStatement(forLoop.Body);

            // increase x
            _ILGenerator.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]);
            _ILGenerator.Emit(OpCodes.Ldc_I4, 1);
            _ILGenerator.Emit(OpCodes.Add);
            SaveIdentifier(forLoop.Identifier, typeof(int));

            // check if x is equal to 100
            _ILGenerator.MarkLabel(test);
            _ILGenerator.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]);
            GenerateExpression(forLoop.To, typeof(int));
            _ILGenerator.Emit(OpCodes.Blt, body);
        }

        else
        {
            ExceptionHandler("unable to generate " + _statement.GetType().Name);
        }
    }
コード例 #37
0
    public void GenerateStatementMethod(Statement _statement)
    {
        #region Statement
        if (_statement is StatementSequence)
        {
            StatementSequence _StatementSequence = (StatementSequence)_statement;
            GenerateStatementMethod(_StatementSequence.Left);
            GenerateStatementMethod(_StatementSequence.Right);
        }
        #endregion

        #region Declare Variable
        else if (_statement is DeclareVariable)
        {
            // declare a variable in symbol table
            DeclareVariable declare = (DeclareVariable)_statement;
            tblIdentifier[declare.Identifier] =
                _ILMethod.DeclareLocal(GetExpressionTypeMethod(declare.Expression));

            // set the initial value
            Assignment assign = new Assignment();
            assign.Identifier = declare.Identifier;
            assign.Expression = declare.Expression;
            GenerateStatementMethod(assign);
        }
        #endregion

        #region Assignment
        else if (_statement is Assignment)
        {
            Assignment assign = (Assignment)_statement;
            GenerateExpressionMethod(assign.Expression, GetExpressionTypeMethod(assign.Expression));
            if (GetExpressionTypeMethod(assign.Expression) == typeof(ArithmaticExpression))
            {
                SaveIdentifierMethod(assign.Identifier, typeof(Int32));
            }
            else
            {
                SaveIdentifierMethod(assign.Identifier,
                                     GetExpressionTypeMethod(assign.Expression));
            }
        }
        #endregion

        else if (_statement is DeclareFunction)
        {
            DeclareFunction _DeclareFunction = (DeclareFunction)_statement;

            string strFunctionName = _DeclareFunction.FunctionName;

            Type   ParameterType1  = GetExpressionTypeMethod(_DeclareFunction.Parameter1.Expression);
            Type   ParameterType2  = GetExpressionTypeMethod(_DeclareFunction.Parameter2.Expression);
            Type   ParameterType3  = GetExpressionTypeMethod(_DeclareFunction.Parameter3.Expression);
            Type[] InputParameters = { ParameterType1, ParameterType2, ParameterType3 };

            Type ReturnType = typeof(void);
            if (_DeclareFunction.ReturnType == "void")
            {
                ReturnType = typeof(void);
            }
            else if (_DeclareFunction.ReturnType == "string")
            {
                ReturnType = typeof(string);
            }
            else if (_DeclareFunction.ReturnType == "numeric")
            {
                ReturnType = typeof(int);
            }



            //FieldBuilder Parameter1 = _typeBuilder.DefineField(_DeclareFunction.Parameter1.Identifier, ParameterType1, FieldAttributes.Private);
            //FieldBuilder Parameter2 = _typeBuilder.DefineField(_DeclareFunction.Parameter2.Identifier, ParameterType2, FieldAttributes.Private);
            //FieldBuilder Parameter3 = _typeBuilder.DefineField(_DeclareFunction.Parameter3.Identifier, ParameterType3, FieldAttributes.Private);

            MethodBuilder NewMethod =
                _typeBuilder.DefineMethod
                    (strFunctionName,
                    MethodAttributes.Static,
                    ReturnType,
                    InputParameters);

            //ParameterBuilder poolRefBuilder = NewMethod.DefineParameter(1, ParameterAttributes.In, _DeclareFunction.Parameter1.Identifier);

            _ILMethod = NewMethod.GetILGenerator();


            //tblArguments[_DeclareFunction.Parameter0.Identifier] = _ILMethod.

            tblArguments[_DeclareFunction.Parameter1.Identifier] = _ILMethod.DeclareLocal(ParameterType1);
            GenerateExpressionMethod(_DeclareFunction.Parameter1.Expression, ParameterType1);
            //_ILMethod.Emit(OpCodes.Starg, 0);

            tblArguments[_DeclareFunction.Parameter1.Identifier] = _ILMethod.DeclareLocal(ParameterType2);
            GenerateExpressionMethod(_DeclareFunction.Parameter1.Expression, ParameterType2);
            //_ILMethod.Emit(OpCodes.Starg, 1);

            tblArguments[_DeclareFunction.Parameter2.Identifier] = _ILMethod.DeclareLocal(ParameterType3);
            GenerateExpressionMethod(_DeclareFunction.Parameter2.Expression, ParameterType3);
            //_ILMethod.Emit(OpCodes.Starg, 2);

            //GenerateStatementMethod(_DeclareFunction.Body);
            //_ILMethod.Emit(OpCodes.Ret);
        }

        #region write-read
        else if (_statement is Write)
        {
            // for print keyword, call .net method for printscreen
            GenerateExpressionMethod(((Write)_statement).Expression,
                                     typeof(string));
            _ILMethod.Emit(OpCodes.Call,
                           typeof(System.Console).GetMethod("WriteLine",
                                                            new System.Type[] { typeof(string) }));
        }

        else if (_statement is ReadInput)
        {
            // call the readline method and parse input method
            _ILMethod.Emit(OpCodes.Call,
                           typeof(System.Console).GetMethod("ReadLine",
                                                            BindingFlags.Public | BindingFlags.Static,
                                                            null, new System.Type[] { }, null));
            _ILMethod.Emit(OpCodes.Call,
                           typeof(int).GetMethod("Parse",
                                                 BindingFlags.Public | BindingFlags.Static,
                                                 null, new System.Type[] { typeof(string) }, null));
            // store the input value in local builder
            SaveIdentifierMethod(((ReadInput)_statement).Identifier, typeof(int));
        }
        #endregion

        #region While
        else if (_statement is While)
        {
            While _while  = (While)_statement;
            Label lblTest = _ILMethod.DefineLabel();
            Label lblEnd  = _ILMethod.DefineLabel();

            if (_while.Operand == RelationalOperands.GreaterThan)
            {
                _ILMethod.MarkLabel(lblTest);
                GenerateExpressionMethod(_while.LeftExpression, typeof(int));
                GenerateExpressionMethod(_while.RightExpression, typeof(int));
                _ILMethod.Emit(OpCodes.Cgt);
                _ILMethod.Emit(OpCodes.Brfalse, lblEnd);
                GenerateStatementMethod(_while.Body);
                _ILMethod.Emit(OpCodes.Br, lblTest);

                _ILMethod.MarkLabel(lblEnd);
            }
            else if (_while.Operand == RelationalOperands.EqualTo)
            {
                _ILMethod.MarkLabel(lblTest);
                GenerateExpressionMethod(_while.LeftExpression, typeof(int));
                GenerateExpressionMethod(_while.RightExpression, typeof(int));
                _ILMethod.Emit(OpCodes.Ceq);
                _ILMethod.Emit(OpCodes.Brfalse, lblEnd);
                GenerateStatementMethod(_while.Body);
                _ILMethod.Emit(OpCodes.Br, lblTest);

                _ILMethod.MarkLabel(lblEnd);
            }
            else if (_while.Operand == RelationalOperands.LessThan)
            {
                _ILMethod.MarkLabel(lblTest);
                GenerateExpressionMethod(_while.LeftExpression, typeof(int));
                GenerateExpressionMethod(_while.RightExpression, typeof(int));
                _ILMethod.Emit(OpCodes.Clt);
                _ILMethod.Emit(OpCodes.Brfalse, lblEnd);
                GenerateStatementMethod(_while.Body);
                _ILMethod.Emit(OpCodes.Br, lblTest);

                _ILMethod.MarkLabel(lblEnd);
            }
        }
        #endregion

        #region If-Then
        else if (_statement is IfThen)
        {
            IfThen ifThen  = (IfThen)_statement;
            Label  lblElse = _ILMethod.DefineLabel();
            Label  lblEnd  = _ILMethod.DefineLabel();

            #region GreaterThan
            if (ifThen.Operand == RelationalOperands.GreaterThan)
            {
                GenerateExpressionMethod(ifThen.LeftExpression, typeof(int));
                GenerateExpressionMethod(ifThen.RightExpression, typeof(int));
                _ILMethod.Emit(OpCodes.Cgt);
                _ILMethod.Emit(OpCodes.Brfalse, lblElse);
                GenerateStatementMethod(ifThen.ThenBody);
                _ILMethod.Emit(OpCodes.Br, lblEnd);

                _ILMethod.MarkLabel(lblElse);
                GenerateStatementMethod(ifThen.ElseBody);

                _ILMethod.MarkLabel(lblEnd);
            }
            #endregion
            #region EqualTo
            else if (ifThen.Operand == RelationalOperands.EqualTo)
            {
                GenerateExpressionMethod(ifThen.LeftExpression, typeof(int));
                GenerateExpressionMethod(ifThen.RightExpression, typeof(int));
                _ILMethod.Emit(OpCodes.Ceq);
                _ILMethod.Emit(OpCodes.Brfalse, lblElse);
                GenerateStatementMethod(ifThen.ThenBody);
                _ILMethod.Emit(OpCodes.Br, lblEnd);

                _ILMethod.MarkLabel(lblElse);
                GenerateStatementMethod(ifThen.ElseBody);

                _ILMethod.MarkLabel(lblEnd);
            }
            #endregion
            #region LessThan
            else if (ifThen.Operand == RelationalOperands.LessThan)
            {
                GenerateExpressionMethod(ifThen.LeftExpression, typeof(int));
                GenerateExpressionMethod(ifThen.RightExpression, typeof(int));
                _ILMethod.Emit(OpCodes.Clt);
                _ILMethod.Emit(OpCodes.Brfalse, lblElse);
                GenerateStatementMethod(ifThen.ThenBody);
                _ILMethod.Emit(OpCodes.Br, lblEnd);

                _ILMethod.MarkLabel(lblElse);
                GenerateStatementMethod(ifThen.ElseBody);

                _ILMethod.MarkLabel(lblEnd);
            }
            #endregion
        }
        #endregion

        #region for
        else if (_statement is For)
        {
            For        forLoop = (For)_statement;
            Assignment assign  = new Assignment();
            assign.Identifier = forLoop.Identifier;
            assign.Expression = forLoop.From;
            GenerateStatementMethod(assign);

            Label test = _ILMethod.DefineLabel();
            _ILMethod.Emit(OpCodes.Br, test);

            Label body = _ILMethod.DefineLabel();
            _ILMethod.MarkLabel(body);
            GenerateStatementMethod(forLoop.Body);

            _ILMethod.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]);
            _ILMethod.Emit(OpCodes.Ldc_I4, 1);
            _ILMethod.Emit(OpCodes.Add);
            SaveIdentifierMethod(forLoop.Identifier, typeof(int));

            _ILMethod.MarkLabel(test);
            _ILMethod.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]);
            GenerateExpressionMethod(forLoop.To, typeof(int));
            _ILMethod.Emit(OpCodes.Blt, body);
        }
        #endregion

        else
        {
            ExceptionHandler("unable to generate " + _statement.GetType().Name);
        }
    }
コード例 #38
0
        internal void WriteSetPropertyValueMethod(System.Reflection.Emit.ILGenerator il)
        {
            var allProperties = Properties.Where(w => w.PropertySetter != null).ToArray();

            var helper = new Helper.ILEmitter(this.GetType(), this.TypeBuilder, il);

            il.DeclareLocal(typeof(bool));

            for (int i = 0; i < allProperties.Length; i++)
            {
                il.DeclareLocal(typeof(bool));
            }


            helper.Nop();
            helper.Ldarg1();
            helper.Call(typeof(string), "IsNullOrWhiteSpace", typeof(string));

            var label = helper.DefineLabel();

            helper.BrFalse(label);

            var endlabel = helper.DefineLabel();


            helper.Nop();
            helper.Ldarg0();
            helper.Call(typeof(object), "GetType");
            helper.Ldarg1();
            helper.Newobj(typeof(Exceptions.EmptyOrNullPropertyNameException), typeof(Type), typeof(string));
            helper.Throw();

            helper.MarkLabel(label);


            var mcallStringEquals = typeof(string).GetMethod("Equals", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static,
                                                             null, new[] { typeof(string), typeof(string) }, null);


            var plabel = helper.DefineLabel();


            foreach (var p in allProperties)
            {
                helper.MarkLabel(plabel);
                plabel = helper.DefineLabel();

                helper.Ldarg1();
                helper.LdStr(p.Name);
                helper.Call(mcallStringEquals);
                helper.BrFalse(plabel);

                helper.Nop();
                helper.Ldarg0();
                helper.Ldarg2();
                helper.CastOrUnBox(p.Type);
                helper.Call(p.PropertySetter);
                helper.Nop();
                helper.Nop();
                helper.Br(endlabel);
            }

            helper.MarkLabel(plabel);

            helper.Nop();
            helper.Ldarg0();
            helper.Call(typeof(object), "GetType");
            helper.Ldarg1();
            helper.Newobj(typeof(Exceptions.PropertyNotFoundException), typeof(Type), typeof(string));
            helper.Throw();


            helper.MarkLabel(endlabel);
            helper.Ret();
        }
コード例 #39
0
ファイル: CodeGenerator.cs プロジェクト: sameerms/compiler
 public void DeclareSymbolInTable(String pIdentifier, Type pType)
 {
     _symbolTable[pIdentifier] = _ilGenerator.DeclareLocal(pType);
 }
コード例 #40
0
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention               = config.Conventions.OfType <TransactionProxyConvention>().First();
            var addValueMethod           = typeof(TransactionProxyHelper).GetMethod("AddValue", BindingFlags.Static | BindingFlags.Public);
            var getValueMethod           = typeof(TransactionProxyHelper).GetMethod("GetValue", BindingFlags.Static | BindingFlags.Public);
            var setCollectionValueMethod = typeof(TransactionProxyHelper).GetMethod("SetCollectionValue", BindingFlags.Static | BindingFlags.Public);


            var listType           = typeof(IEnumerable <>).MakeGenericType(config.BaseType);
            var enumeratorType     = typeof(IEnumerator <>).MakeGenericType(config.BaseType);
            var enumeratorVariable = il.DeclareLocal(enumeratorType);
            var currentVariable    = il.DeclareLocal(config.BaseType);

            foreach (var item in convention.TransactionProxyProperties)
            {
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Newobj, item.ValuesProperty.MemberType.GetConstructor(new Type[] { }));
                il.Emit(OpCodes.Stfld, item.ValuesProperty.BackingField);
            }


            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, convention.TargetsField.Field);
            il.EmitCall(OpCodes.Callvirt, listType.GetMethod("GetEnumerator"), null);
            il.Emit(OpCodes.Stloc, enumeratorVariable);

            var loopLabel = il.DefineLabel();
            var nextLabel = il.DefineLabel();

            var tryBlock = il.BeginExceptionBlock();

            il.MarkLabel(loopLabel);
            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.EmitCall(OpCodes.Callvirt, typeof(IEnumerator).GetMethod("MoveNext"), null);
            il.Emit(OpCodes.Brfalse, nextLabel);

            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.EmitCall(OpCodes.Callvirt, enumeratorType.GetProperty("Current").GetGetMethod(), null);
            il.Emit(OpCodes.Stloc, currentVariable);

            foreach (var item in convention.TransactionProxyProperties)
            {
                il.Emit(OpCodes.Ldloc, currentVariable);
                il.EmitCall(OpCodes.Callvirt, item.Property.GetGetMethod(true), null);
                il.Emit(OpCodes.Ldloc, currentVariable);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, item.ValuesProperty.BackingField);
                il.EmitCall(OpCodes.Call, addValueMethod.MakeGenericMethod(item.Property.PropertyType, config.BaseType), null);
            }

            il.Emit(OpCodes.Br, loopLabel);

            var endFinally = il.DefineLabel();

            il.BeginFinallyBlock();
            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Ceq);
            il.Emit(OpCodes.Brtrue_S, endFinally);
            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.EmitCall(OpCodes.Callvirt, typeof(IDisposable).GetMethod("Dispose"), null);
            il.MarkLabel(endFinally);
            il.EndExceptionBlock();

            il.MarkLabel(nextLabel);

            foreach (var item in convention.TransactionProxyProperties)
            {
                Type itemType;
                if (IsCollectionType(item.Property.PropertyType, out itemType))
                {
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, item.ValuesProperty.BackingField);
                    il.Emit(OpCodes.Ldarg_0);
                    il.EmitCall(OpCodes.Callvirt, item.Property.GetGetMethod(true), null);
                    il.EmitCall(OpCodes.Call, setCollectionValueMethod.MakeGenericMethod(itemType, item.Property.PropertyType, config.BaseType), null);
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, item.ValuesProperty.BackingField);
                    il.EmitCall(OpCodes.Call, getValueMethod.MakeGenericMethod(item.Property.PropertyType, config.BaseType), null);
                    il.EmitCall(OpCodes.Callvirt, item.Property.GetSetMethod(true), null);
                }

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, item.ValuesProperty.BackingField);
                il.EmitCall(OpCodes.Callvirt, item.ValuesProperty.BackingField.FieldType.GetProperty("Count").GetGetMethod(), null);
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Ceq);
                il.Emit(OpCodes.Ldc_I4_0);
                il.Emit(OpCodes.Ceq);
                il.EmitCall(OpCodes.Callvirt, item.HasMultipleValuesProperty.PropertySetMethod, null);
            }

            il.Emit(OpCodes.Ret);
        }
コード例 #41
0
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            var listType           = typeof(IEnumerable <>).MakeGenericType(config.BaseType);
            var enumeratorType     = typeof(IEnumerator <>).MakeGenericType(config.BaseType);
            var enumeratorVariable = il.DeclareLocal(enumeratorType);
            var currentVariable    = il.DeclareLocal(config.BaseType);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, convention.TargetsField.Field);
            il.EmitCall(OpCodes.Callvirt, listType.GetMethod("GetEnumerator"), null);
            il.Emit(OpCodes.Stloc, enumeratorVariable);

            var loopLabel = il.DefineLabel();
            var nextLabel = il.DefineLabel();

            var tryBlock = il.BeginExceptionBlock();

            il.MarkLabel(loopLabel);
            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.EmitCall(OpCodes.Callvirt, typeof(IEnumerator).GetMethod("MoveNext"), null);
            il.Emit(OpCodes.Brfalse, nextLabel);

            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.EmitCall(OpCodes.Callvirt, enumeratorType.GetProperty("Current").GetGetMethod(), null);
            il.Emit(OpCodes.Stloc, currentVariable);

            foreach (var item in convention.TransactionProxyProperties)
            {
                var done = il.DefineLabel();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, item.HasMultipleValuesProperty.BackingField);
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Ceq);
                il.Emit(OpCodes.Brtrue_S, done);

                il.Emit(OpCodes.Ldloc, currentVariable);
                il.Emit(OpCodes.Ldarg_0);
                il.EmitCall(OpCodes.Callvirt, item.Property.GetGetMethod(true), null);
                il.EmitCall(OpCodes.Callvirt, item.Property.GetSetMethod(true), null);

                il.MarkLabel(done);
            }

            il.Emit(OpCodes.Br, loopLabel);

            var endFinally = il.DefineLabel();

            il.BeginFinallyBlock();
            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Ceq);
            il.Emit(OpCodes.Brtrue_S, endFinally);
            il.Emit(OpCodes.Ldloc, enumeratorVariable);
            il.EmitCall(OpCodes.Callvirt, typeof(IDisposable).GetMethod("Dispose"), null);
            il.MarkLabel(endFinally);
            il.EndExceptionBlock();

            il.MarkLabel(nextLabel);

            il.Emit(OpCodes.Ret);
        }
コード例 #42
0
    private void GenStmt(stmt stmt)
    {
        if (stmt is sequence)
        {
            sequence seq = (sequence)stmt;
            this.GenStmt(seq.first);
            this.GenStmt(seq.second);
        }

        else if (stmt is DeclareS)
        {
            // declare a local
            counting++;
            DeclareS declare = (DeclareS)stmt;
            this.symbolTable[declare.Ident] = il.DeclareLocal(TypeOfExpr(declare.Expr));

            // set the initial value
            assign assign = new assign();
            assign.Ident = declare.Ident;
            assign.Expr  = declare.Expr;
            this.GenStmt(assign);
        }

        else if (stmt is assign)
        {
            counting++;
            assign assign = (assign)stmt;
            counters = 0;
            this.GenExpr(assign.Expr, this.TypeOfExpr(assign.Expr));

            this.Store(assign.Ident, this.TypeOfExpr(assign.Expr));
        }
        else if (stmt is display)
        {
            // the "display" statement is an alias for System.Console.WriteLine.
            // it uses the string case
            counting++;
            this.GenExpr(((display)stmt).Expr, typeof(string));

            this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
        }
        else if (stmt is Just_Declare)
        {
            counting++;
            Just_Declare declare = (Just_Declare)stmt;
            this.symbolTable[declare.Ident] = this.il.DeclareLocal(typeof(int));


            //this.Store(declare.Ident, typeof(int));
        }

        else if (stmt is acquire)
        {
            counting++;
            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(int).GetMethod("Parse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { typeof(string) }, null));
            this.Store(((acquire)stmt).Ident, typeof(int)); // stores the identifier in stack
        }
        else
        {
            throw new System.Exception("don't know how to gen a " + stmt.GetType().Name);
        }
    }
コード例 #43
0
ファイル: ILManipulator.cs プロジェクト: riQQ/HarmonyX
 public List <CodeInstruction> GetInstructions(SRE.ILGenerator il)
 {
     Prepare(vDef => il.DeclareLocal(vDef.VariableType.ResolveReflection()), il.DefineLabel);
     return(codeInstructions.ToList());
 }