Inheritance: EmitWrapper
        private void EmitPrivateFieldAssignment(LocalBuilder localbuilder) {
            var fieldInfo = Member as FieldInfo;
            var methodAttributes = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig;
            var methodBuilder = DynamicTypeBuilder.Current.DefineMethod("EmitPrivateFieldAssignment", methodAttributes);
            var methodBuilderILGenerator = methodBuilder.GetILGenerator();

            Type = fieldInfo.FieldType;
            methodBuilder.SetReturnType(Type);
            _assignorExpression.AcceptVisitor(Visitor, methodBuilderILGenerator);

            methodBuilderILGenerator.DeclareLocal(Type);
            methodBuilderILGenerator.Emit(OpCodes.Stloc_1);
            methodBuilderILGenerator.Emit(OpCodes.Ldtoken, Target);
            methodBuilderILGenerator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));
            methodBuilderILGenerator.Emit(OpCodes.Ldstr, Member.Name);
            methodBuilderILGenerator.EmitPushInteger(Convert.ToInt32(BindingFlags.NonPublic | BindingFlags.Static));
            methodBuilderILGenerator.Emit(OpCodes.Callvirt, typeof(Type).GetMethod("GetField", new Type[] { TypeSystem.String, typeof(BindingFlags) }));
            methodBuilderILGenerator.Emit(OpCodes.Ldnull);
            methodBuilderILGenerator.Emit(OpCodes.Ldloc_1);
            methodBuilderILGenerator.Emit(OpCodes.Callvirt, typeof(FieldInfo).GetMethod("SetValue", new Type[] { TypeSystem.Object, TypeSystem.Object }));
            methodBuilderILGenerator.Emit(OpCodes.Ldloc_1);
            methodBuilderILGenerator.Emit(OpCodes.Ret);

            ILGenerator.Emit(OpCodes.Call, methodBuilder);
        }
 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;
 }
Exemplo n.º 3
0
 protected override void EmitDecodeAndStore(IEmittingContext context, LocalBuilder collectionVar, Action emitLoadIndex, bool doNotCheckBounds)
 {
     var il = context.IL;
     il.Ldloc(collectionVar);
     ElementCodec.EmitDecode(context, doNotCheckBounds);
     il.Callvirt(addMethod);
 }
 private void DeclareParameterLocals(ParameterInfo[] parameters, LocalBuilder[] parameterLocals)
 {
     for (int i = 0; i < parameterLocals.Length; i++)
     {
         parameterLocals[i] = this.ilg.DeclareLocal(TypeLoader.GetParameterType(parameters[i]), "param" + i.ToString(CultureInfo.InvariantCulture));
     }
 }
Exemplo n.º 5
0
        private void Store(string name, System.Type type)
        {
            if (this.symbolTable.ContainsKey(name))
            {
                Emit.LocalBuilder locb = this.symbolTable[name];

                if (locb.LocalType == type)
                {
                    this.il.Emit(Emit.OpCodes.Stloc, this.symbolTable[name]);
                }
                else
                {
                    throw new System.Exception("'" + name + "' is of type " + locb.LocalType.Name + " but attempted to store value of type " + type.Name);
                }
            }
            else if (this.typefieldList.ContainsKey(name))
            {
                if (this.typefieldList[name].IsStatic)
                {
                    this.il.Emit(Emit.OpCodes.Stsfld, this.typefieldList[name]);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Stfld, this.typefieldList[name]);
                }
            }
            else
            {
                throw new System.Exception("undeclared variable '" + name + "'");
            }
        }
Exemplo n.º 6
0
        public void SetMemberValue(CodeGenerator generator, ArgBuilder targetObject, string memberName, LocalBuilder memberValue)
        {
            generator.Ldarg(targetObject);
            generator.Load(memberName);
            generator.Ldloc(memberValue);

            // Type originalType = memberValue.LocalType.IsEnum ? typeof(int) : memberValue.LocalType;
            if (memberValue.LocalType.IsValueType)
            {
                generator.Box(memberValue.LocalType.IsEnum ? typeof(int) : memberValue.LocalType);
            }
            //���ֵΪ�գ����ܵ���ToString
            generator.Load(null);
            generator.If(Cmp.NotEqualTo);
            generator.Ldloc(memberValue);

            // Type originalType = memberValue.LocalType.IsEnum ? typeof(int) : memberValue.LocalType;
            if (memberValue.LocalType.IsValueType)
            {
                generator.Box(memberValue.LocalType.IsEnum ? typeof(int) : memberValue.LocalType);
            }
            generator.Call(typeof(object).GetMethod("ToString", Type.EmptyTypes));
            generator.Else();
            generator.LoadDefaultValue(memberValue.LocalType);
            if (memberValue.LocalType.IsValueType)
            {
                generator.Box(memberValue.LocalType.IsEnum ? typeof(int) : memberValue.LocalType);
            }
            generator.EndIf();
            generator.Call(typeof(NameValueCollection).GetMethod("Add", new Type[] { typeof(string), typeof(string) }));
        }
        private static void EmitStoreLocalShortTerm(this ILGenerator ILGenerator, LocalBuilder localBuilder) {
            switch (localBuilder.LocalIndex) {
                case 0:

                    ILGenerator.Emit(OpCodes.Stloc_0);
                    break;

                case 1:

                    ILGenerator.Emit(OpCodes.Stloc_1);
                    break;

                case 2:

                    ILGenerator.Emit(OpCodes.Stloc_2);
                    break;

                case 3:

                    ILGenerator.Emit(OpCodes.Stloc_3);
                    break;

                default:

                    ILGenerator.Emit(OpCodes.Stloc_S, localBuilder);
                    break;
            }
        }
 internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
 {
     this.indexVar = indexVar;
     this.beginLabel = beginLabel;
     this.testLabel = testLabel;
     this.end = end;
 }
Exemplo n.º 9
0
 private void WriteToMemoryCell(LocalBuilder variable)
 {
     codeGenerator.Emit(OpCodes.Ldloc, Memory);
     codeGenerator.Emit(OpCodes.Ldloc, MemoryPointer);
     codeGenerator.Emit(OpCodes.Ldloc, variable);
     codeGenerator.Emit(OpCodes.Stelem_I1);
 }
Exemplo n.º 10
0
 private System.Type TypeOfExpr(Expr expr)
 {
     if (expr is StringLiteral)
     {
         return(typeof(string));
     }
     else if (expr is IntLiteral)
     {
         return(typeof(int));
     }
     else if (expr is Variable)
     {
         Variable var = (Variable)expr;
         if (this.symbolTable.ContainsKey(var.Ident))
         {
             Emit.LocalBuilder locb = this.symbolTable[var.Ident];
             return(locb.LocalType);
         }
         else
         {
             throw new System.Exception("undeclared variable '" + var.Ident + "'");
         }
     }
     else
     {
         throw new System.Exception("don't know how to calculate the type of " + expr.GetType().Name);
     }
 }
Exemplo n.º 11
0
        protected override LocalBuilder CallMockedMethod(LocalBuilder generics, LocalBuilder args, LocalBuilder methodOut)
        {
            var ifResult = Body.DeclareLocal(typeof(bool));
            var indexParams = Body.DeclareLocal(typeof(IEnumerable<MethodArg>));
            var last = Body.DeclareLocal(typeof(int));

            //last = args.Length - 1;
            Body.Emit(OpCodes.Ldloc, args);
            Body.Emit(OpCodes.Call, MethodArg_Length);
            Body.Emit(OpCodes.Ldc_I4_1);
            Body.Emit(OpCodes.Sub);
            Body.Emit(OpCodes.Stloc, last);

            //indexParams = Enumerable.Take(args, last);
            Body.Emit(OpCodes.Ldloc, args);
            Body.Emit(OpCodes.Ldloc, last);
            Body.Emit(OpCodes.Call, Take);
            Body.Emit(OpCodes.Stloc, indexParams);

            // this.ObjectBase.SetIndex(indexParams, args[last].Arg);
            Body.Emit(OpCodes.Ldarg_0);
            Body.Emit(OpCodes.Ldfld, ObjBase);
            Body.Emit(OpCodes.Ldloc, indexParams);
            Body.Emit(OpCodes.Ldloc, args);
            Body.Emit(OpCodes.Ldloc, last);
            Body.Emit(OpCodes.Ldelem_Ref);
            Body.Emit(OpCodes.Ldfld, MethodArg_Arg);
            Body.Emit(OpCodes.Call, ObjectBase.Reflection.SetIndex);

            // ifResult = true
            Body.Emit(OpCodes.Ldc_I4_1);
            Body.Emit(OpCodes.Stloc, ifResult);

            return ifResult;
        }
Exemplo n.º 12
0
 internal AspectArgsMethodWeaver(MethodInfo method, LocalBuilder methodLocalBuilder, Type[] parameters, IAspectWeavingSettings aspectWeavingSettings)
 {
     this.method = method;
     this.parameters = parameters;
     this.methodLocalBuilder = methodLocalBuilder;
     this.aspectWeavingSettings = aspectWeavingSettings;
 }
Exemplo n.º 13
0
 public static void Emit_DecreaseInteger(this ILGenerator il, LocalBuilder remainingBytesVal, LocalBuilder distanceVar)
 {
     il.Emit(OpCodes.Ldloc, remainingBytesVal);
     il.Emit(OpCodes.Ldloc, distanceVar);
     il.Emit(OpCodes.Sub);
     il.Emit(OpCodes.Stloc, remainingBytesVal);
 }
 public static LocalBuilder GetPropertyValue(this ILGenerator il, PropertyInfo property, LocalBuilder target)
 {
     var x = il.DeclareLocal(property.PropertyType);
     il.LoadPropertyValue(property, target);
     il.SetLocal(x);
     return x;
 }
Exemplo n.º 15
0
        protected void UnlockRegister(LocalBuilder reg)
        {
            if (registers.ContainsKey (reg.LocalType))
                return;

            registers.Add (reg.LocalType, reg);
        }
 private void CreateObject(ClassDataContract classContract)
 {
     Type typeOfValueType = this.objectType = classContract.UnderlyingType;
     if (typeOfValueType.IsValueType && !classContract.IsNonAttributedType)
     {
         typeOfValueType = Globals.TypeOfValueType;
     }
     this.objectLocal = this.ilg.DeclareLocal(typeOfValueType, "objectDeserialized");
     if (classContract.UnderlyingType == Globals.TypeOfDBNull)
     {
         this.ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
         this.ilg.Stloc(this.objectLocal);
     }
     else if (classContract.IsNonAttributedType)
     {
         if (typeOfValueType.IsValueType)
         {
             this.ilg.Ldloca(this.objectLocal);
             this.ilg.InitObj(typeOfValueType);
         }
         else
         {
             this.ilg.New(classContract.GetNonAttributedTypeConstructor());
             this.ilg.Stloc(this.objectLocal);
         }
     }
     else
     {
         this.ilg.Call(null, XmlFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract));
         this.ilg.ConvertValue(Globals.TypeOfObject, typeOfValueType);
         this.ilg.Stloc(this.objectLocal);
     }
 }
		public override void OutputSet(NitroIL into,Type setting){
			
			if(VariableType==null){
				
				VariableType=setting;
				
			}else if(setting!=VariableType){
				
				// Overwriting the variable with something of a different type. Create a new one.
				VariableType=setting;
				Builder=null;
				
			}
			
			if(VariableType==null){
				VariableType=typeof(object);
			}
			
			if(Builder==null){
				
				Builder=into.DeclareLocal(VariableType);
				
			}
			
			into.Emit(OpCodes.Stloc,Builder);
		}
Exemplo n.º 18
0
    private System.Type TypeOfExpr(Expr expr)
    {
        if (expr is StringLiteral)
        {
            return(typeof(string));
        }
        else if (expr is IntLiteral)
        {
            return(typeof(int));
        }
        else if (expr is Variable)
        {
            Variable var = (Variable)expr;
            if (this.symbolTable.ContainsKey(var.Ident))
            {
                Emit.LocalBuilder locb = this.symbolTable[var.Ident];
                return(locb.LocalType);
            }
            else
            {
                throw new System.Exception("variable no declarada '" + var.Ident + "'");
            }
        }
        //*********************
        else if (expr is BinExpr)
        {
            return(typeof(int));
        }
        //*********************

        else
        {
            throw new System.Exception("no se puede calcular el tipo: " + expr.GetType().Name);
        }
    }
Exemplo n.º 19
0
		public static void DefineLocalVariable (string name, LocalBuilder builder)
		{
			if (symwriter != null) {
				int index = MonoDebuggerSupport.GetLocalIndex (builder);
				symwriter.DefineLocalVariable (index, name);
			}
		}
Exemplo n.º 20
0
		/// <summary>
		///		Emits 'for' statement on current IL stream.
		/// </summary>
		/// <param name="il">IL generator to be emitted to.</param>
		/// <param name="count">'count' local variable which is <see cref="Int32"/> type and holds maximum loop count.</param>
		/// <param name="bodyEmitter">Delegate to emit for statement body.</param>
		public static void EmitFor( TracingILGenerator il, LocalBuilder count, Action<TracingILGenerator, LocalBuilder> bodyEmitter )
		{
			Contract.Requires( il != null );
			Contract.Requires( count != null );
			Contract.Requires( bodyEmitter != null );

			var i = il.DeclareLocal( typeof( int ), "i" );
			il.EmitLdc_I4_0();
			il.EmitAnyStloc( i );
			var forCond = il.DefineLabel( "FOR_COND" );
			il.EmitBr( forCond );
			var body = il.DefineLabel( "BODY" );
			il.MarkLabel( body );
			bodyEmitter( il, i );
			// increment
			il.EmitAnyLdloc( i );
			il.EmitLdc_I4_1();
			il.EmitAdd();
			il.EmitAnyStloc( i );
			// cond
			il.MarkLabel( forCond );
			il.EmitAnyLdloc( i );
			il.EmitAnyLdloc( count );
			il.EmitBlt( body );
		}
Exemplo n.º 21
0
        void ICanModifyContext.EmitDecls(EmitContext ec)
        {
            object var;

            if ((var = CodeGenerator.variable_defined_in_current_scope (id)) != null) {
                Type t = var.GetType ();
                if (t == typeof (FieldBuilder))
                    field_info = (FieldBuilder) var;
                else if (t == typeof (LocalBuilder))
                    local_builder = (LocalBuilder) var;
                return;
            }

            ILGenerator ig = ec.ig;
            if (parent == null || (parent.GetType () != typeof (FunctionDeclaration)
                           && parent.GetType () != typeof (FunctionExpression))) {
                FieldBuilder field_builder;
                TypeBuilder type_builder  = ec.type_builder;

                field_builder = type_builder.DefineField (id, this.type, FieldAttributes.Public | FieldAttributes.Static);
                TypeManager.Add (id, field_builder);
                field_info = field_builder;
            } else {
                local_builder = ig.DeclareLocal (type);
                TypeManager.Add (id, local_builder);
            }
        }
Exemplo n.º 22
0
 /// Generates the code that adds an object from a local variable to a dictionary also stored in a local
 /// <param name="ilGenerator"></param>
 /// <param name="dictionary"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, LocalBuilder value)
 {
     ilGenerator.Emit(OpCodes.Ldloc, dictionary);
     ilGenerator.LoadValue(key);
     ilGenerator.Emit(OpCodes.Ldloc, value);
     ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd);
 }
Exemplo n.º 23
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);
            }
        }
Exemplo n.º 24
0
    private System.Type TypeOfExpr(expr expr)
    {
        if (expr is StringLiteral)
        {
            return(typeof(string)); //setting the type of expr to type string
        }
        else if (expr is IntLiteral)
        {
            return(typeof(int)); //type to int
        }
        else if (expr is Variable)
        {
            Variable var = (Variable)expr;
            if (this.symbolTable.ContainsKey(var.Ident))
            {
                Emit.LocalBuilder locb = symbolTable[var.Ident]; //loacal variable assigned the value of symbol table at key var.Ident
                return(locb.LocalType);
            }
            else
            {
                throw new System.Exception("undeclared variable '" + var.Ident + "'");
            }
        }
        else if (expr is BinExpr)
        {
            BinExpr var = (BinExpr)expr;
            return(typeof(int));
        }

        else
        {
            throw new System.Exception("don't know how to calculate the type of " + expr.GetType().Name);
        }
    }
Exemplo n.º 25
0
 public ILForLoop(Label conditionLabel, Label startLoopLogicLabel, LocalBuilder counter, LocalBuilder max)
 {
     ConditionLabel = conditionLabel;
     Counter = counter;
     Max = max;
     StartLoopLogicLabel = startLoopLogicLabel;
 }
 public MethodCallExpression(LocalBuilder instance, string methodName, params object[] args)
     : base(args)
 {
     _instance = new Variable(instance);
     _methodName = methodName;
     LookupMethod(instance.LocalType, methodName);
 }
Exemplo n.º 27
0
		internal override void Emit (EmitContext ec, LocalBuilder local)
		{
			var member = EmitLoadMember (ec, local);

			foreach (var initializer in initializers)
				initializer.Emit (ec, member);
		}
Exemplo n.º 28
0
		/// <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);
		}
Exemplo n.º 29
0
 public static void Emit_IncreasePointer(this ILGenerator il, LocalBuilder dataPointerVar, LocalBuilder distanceVar)
 {
     il.Emit(OpCodes.Ldloc, dataPointerVar);
     il.Emit(OpCodes.Ldloc, distanceVar);
     il.Emit(OpCodes.Add);
     il.Emit(OpCodes.Stloc, dataPointerVar);
 }
 public InitializeInvokerArgumentArrayStatement(
     LocalBuilder argumentArrayLocal,
     ParameterInfo[] parameters)
 {
     _argumentArrayLocal = argumentArrayLocal;
     _parameters = parameters;
 }
Exemplo n.º 31
0
 private ReturnFixer(LocalBuilder refSlot, int argIndex, Type argType)
 {
     Debug.Assert(refSlot.LocalType.IsGenericType() && refSlot.LocalType.GetGenericTypeDefinition() == typeof(StrongBox<>));
     _refSlot = refSlot;
     _argIndex = argIndex;
     _argType = argType;
 }
Exemplo n.º 32
0
 private void CodeCall(FuncCallExpression call, List<LocalVariable> locals, List<GlobalVariable> globals, FuncParam[] parameters, ILGenerator il, List<Function> allFuncs, LocalBuilder tmpVar)
 {
     var func = FindFunc(call, allFuncs);
     foreach (var expression in call.Params)
         CodeExpression(expression, locals, globals, parameters, il, allFuncs, tmpVar);
     il.Emit(OpCodes.Call, func.Info);
 }
		internal override void Emit (EmitContext ec, LocalBuilder local)
		{
			var member = EmitLoadMember (ec, local);

			foreach (var binding in bindings)
				binding.Emit (ec, member);
		}
 public StoreOutArgumentsStatement(
     LocalBuilder argumentArrayLocal, 
     ParameterInfo[] parameters)
 {
     _argumentArrayLocal = argumentArrayLocal;
     _parameters = parameters;
 }
Exemplo n.º 35
0
    public void storeVariable(Symbol s, bool isref, uint scope, string proc_actual)
    {
        Symbol aux;
        int    tipo = 0;

        if (scope == 0)
        {
            aux = symtab.getSymbol(s.Name);
        }
        else
        {
            aux = symtab.getSymbol(proc_actual, s.Name, ref tipo);
        }

        if (aux != null)
        {
            /*
             * Porque puede ser que estemos usando
             * una variable global dentro de un metodo
             * hay que comprobar tb el tipo
             */
            if (scope == 0 || tipo == 0)
            {
                this.il.Emit(Emit.OpCodes.Stsfld, (Emit.FieldBuilder)fbuilderTable[aux.Name]);
            }
            //tipo = 1 parametro
            else if (tipo == 1)
            {
                Param f = (Param)aux;
                if (f.Reference)
                {
                    this.genStInd(f);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Starg_S, (short)f.Offset);
                }
            }
            else
            {
                Hashtable         h = (Hashtable)lbuilderTable[proc_actual];
                Emit.LocalBuilder l = (Emit.LocalBuilder)h[s.Name];
                if (l == null)
                {
                    return;
                }
                if (isref)
                {
                    this.genStInd(s);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Stloc, l);
                }
            }
        }
    }
Exemplo n.º 36
0
        private void ValidateSymbolType(String pName, Type pExpectedType)
        {
            Emit.LocalBuilder localBuilder = GetValueFromSymbolTable(pName, -1);

            if (localBuilder.LocalType != pExpectedType)
            {
                String ErrMSg = "Variable {0} is of type {1}, but type {2} cannot be stored in it";
                throw new Exception(String.Format(ErrMSg, pName, localBuilder.LocalType.Name, pExpectedType.Name));
            }
        }
Exemplo n.º 37
0
    private void ADD_EMIT()
    {
        //this.il.Emit(Emit.OpCodes.Ldc_I4, ((IntLiteral)whole[0]).Value);
        //this.il.Emit(Emit.OpCodes.Ldc_I4, ((IntLiteral)whole[2]).Value);
        //this.il.Emit(Emit.OpCodes.Add);

        if (whole[0] is IntLiteral)
        {
            this.il.Emit(Emit.OpCodes.Ldc_I4, ((IntLiteral)whole[0]).Value);//pushes the value of passed expression on integer type stack
        }
        else
        {
            string            ident = ((Variable)whole[0]).Ident;
            Emit.LocalBuilder locb  = this.symbolTable[ident];
            this.il.Emit(Emit.OpCodes.Ldloc, locb);
        }

        for (int len = 2; len < whole.Count; len = len + 2)
        {
            if (whole[len] is IntLiteral)
            {
                this.il.Emit(Emit.OpCodes.Ldc_I4, ((IntLiteral)whole[len]).Value);    //pushes the value of passed expression on integer type stack
            }
            else
            {
                string            ident = ((Variable)whole[len]).Ident;
                Emit.LocalBuilder locb  = this.symbolTable[ident];
                this.il.Emit(Emit.OpCodes.Ldloc, locb);
            }



            if ((whole[len - 1]).Equals(BinOp.add))
            {
                this.il.Emit(Emit.OpCodes.Add);
            }
            else if ((whole[len - 1]).Equals(BinOp.minus))
            {
                this.il.Emit(Emit.OpCodes.Sub);
            }
            else if ((whole[len - 1]).Equals(BinOp.multiply))
            {
                this.il.Emit(Emit.OpCodes.Mul);
            }
            else if ((whole[len - 1]).Equals(BinOp.divide))
            {
                this.il.Emit(Emit.OpCodes.Div);
            }
        }
    }
Exemplo n.º 38
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");
            }
        }
Exemplo n.º 39
0
        public Emit.LocalBuilder GetValueFromSymbolTable(String pIdentifier, Int32 pIndex)
        {
            if (!_symbolTable.ContainsKey(pIdentifier))
            {
                throw new Exception("Undeclared variable '" + pIdentifier + "'");
            }

            if (pIndex != -1)
            {
                //Array with Index pIndex
                Emit.LocalBuilder local = _symbolTable[pIdentifier];
                return(_symbolTable[pIdentifier]);
            }
            else
            {
                return(_symbolTable[pIdentifier]);
            }
        }
Exemplo n.º 40
0
        private System.Type TypeOfExpr(Expr expr)
        {
            if (expr is StringLiteral)
            {
                return(typeof(string));
            }
            else if (expr is IntLiteral)
            {
                return(typeof(int));
            }
            else if (expr is BinExpr)
            {
                return(TypeOfExpr(((BinExpr)expr).Right));
            }

            else if (expr is Variable)
            {
                Variable var = (Variable)expr;
                if (this.symbolTable.ContainsKey(var.Ident))
                {
                    Emit.LocalBuilder locb = this.symbolTable[var.Ident];
                    return(locb.LocalType);
                }
                else
                {
                    throw new System.Exception("undeclared variable '" + var.Ident + "'");
                }
            }
            else if (expr is MethodCall)
            {
                MethodCall callMethod = (MethodCall)expr;
                if (callMethod.returnType == null && !callMethod.IsConstrutor)
                {
                    callMethod.returnType = GetMethodInfo(callMethod).ReturnParameter.ParameterType;
                }

                return(callMethod.returnType);
            }

            else
            {
                throw new System.Exception("don't know how to calculate the type of " + expr.GetType().Name);
            }
        }
Exemplo n.º 41
0
    private void Store(string name, System.Type type)
    {
        if (this.symbolTable.ContainsKey(name))
        {
            Emit.LocalBuilder locb = this.symbolTable[name];

            if (locb.LocalType == type)
            {
                this.il.Emit(Emit.OpCodes.Stloc, this.symbolTable[name]);
            }
            else
            {
                throw new System.Exception("'" + name + "' es del tipo " + locb.LocalType.Name + " pero se intenta almacenar el tipo " + type.Name);
            }
        }
        else
        {
            throw new System.Exception("variable no declarada '" + name + "'");
        }
    }
Exemplo n.º 42
0
        private void Store(string Id)
        {
            int Position;

            if ((Position = checkStackParams(Id)) >= 0)
            {
                AssemblerGenerator.Emit(Emit.OpCodes.Starg, Position + 1);
            }
            else
            {
                Emit.LocalBuilder LocVar = VariableBuilder(Id);
                if (LocVar == null)
                {
                    throw new System.Exception("Использование необъявленной переменной.");
                }
                else
                {
                    AssemblerGenerator.Emit(Emit.OpCodes.Stloc, LocVar);
                }
            }
        }
Exemplo n.º 43
0
        private void Load(string Id)
        {
            int Position = checkStackParams(Id);

            if (Position >= 0)
            {
                AssemblerGenerator.Emit(Emit.OpCodes.Ldarg, Position + 1);
            }
            else
            {
                Emit.LocalBuilder LocVar = VariableBuilder(Id);

                if (LocVar == null)
                {
                    throw new System.Exception("Использование необъявленной переменной.");
                }
                else
                {
                    CurrentTopStackType = LocVar.LocalType;
                    AssemblerGenerator.Emit(Emit.OpCodes.Ldloc, LocVar);
                }
            }
        }
 public static int GetLocalIndex(SRE.LocalBuilder local)
 {
     return(get_local_index(local));
 }
Exemplo n.º 45
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);
        }
    }
Exemplo n.º 46
0
    public void loadVariable(Symbol s, bool isref, uint scope, string proc_actual)
    {
        Symbol aux;
        int    tipo = 0;

        if (scope == 0)
        {
            aux = symtab.getSymbol(s.Name);
        }
        else
        {
            aux = symtab.getSymbol(proc_actual, s.Name, ref tipo);
        }

        /*
         * Si la cadena coincide con el nombre del procedimiento
         * o de otra variable, debemos tratarlo como un literal
         *
         * Las constantes las tratamos como literales, ya que en mono
         * no esta implementado el metodo getRawConstantValue para obtener
         * el valor. Dado que en compilacion no dejamos asignar valores,
         * no se notara a no ser que se mire el codigo generado.
         */
        if (aux != null && !s.Literal && !(aux is Constant))
        {
            if (scope == 0)
            {
                if (isref)
                {
                    this.il.Emit(Emit.OpCodes.Ldsflda, (Emit.FieldBuilder)fbuilderTable[aux.Name]);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Ldsfld, (Emit.FieldBuilder)fbuilderTable[aux.Name]);
                }
            }
            //tipo = 1 parametro
            else if (tipo == 1)
            {
                Param f = (Param)aux;
                this.genLdArg(f.Offset);
                if (isref)
                {
                    this.genLdInd(f);
                }
            }
            else
            {
                Hashtable h = (Hashtable)lbuilderTable[proc_actual];
                if (h == null)
                {
                    return;
                }
                Emit.LocalBuilder l = (Emit.LocalBuilder)h[s.Name];
                if (l == null)
                {
                    return;
                }
                if (isref)
                {
                    this.il.Emit(Emit.OpCodes.Ldloca, l);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Ldloc, l);
                }
            }
        }
        else
        {
            switch (s.Type.toString())
            {
            case "INT":
                if (aux != null && aux is Constant)
                {
                    Constant cnt = (Constant)aux;
                    this.il.Emit(Emit.OpCodes.Ldc_I4, Int32.Parse(cnt.Value));
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Ldc_I4, Int32.Parse(s.Name));
                }
                break;

            case "CHAR":
                if (aux != null && aux is Constant)
                {
                    Constant cnt = (Constant)aux;
                    this.il.Emit(Emit.OpCodes.Ldc_I4, Char.Parse(cnt.Value));
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Ldc_I4, Char.Parse(s.Name));
                }
                break;

            case "STRING":
                if (aux != null && aux is Constant)
                {
                    Constant cnt = (Constant)aux;
                    this.il.Emit(Emit.OpCodes.Ldstr, cnt.Value);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Ldstr, s.Name);
                }
                break;

            case "REAL":
                if (aux != null && aux is Constant)
                {
                    Constant cnt = (Constant)aux;
                    string   str = cnt.Value.Replace('.', ',');
                    this.il.Emit(Emit.OpCodes.Ldc_R8, Double.Parse(str));
                }
                else
                {
                    string str = s.Name.Replace('.', ',');
                    this.il.Emit(Emit.OpCodes.Ldc_R8, Double.Parse(str));
                }
                break;

            case "BOOLEAN":
                if (aux != null && aux is Constant)
                {
                    Constant cnt = (Constant)aux;
                    if (cnt.Value == "true")
                    {
                        this.il.Emit(Emit.OpCodes.Ldc_I4, 1);
                    }
                    else
                    {
                        this.il.Emit(Emit.OpCodes.Ldc_I4, 0);
                    }
                }
                else
                {
                    if (s.Name == "true")
                    {
                        this.il.Emit(Emit.OpCodes.Ldc_I4, 1);
                    }
                    else
                    {
                        this.il.Emit(Emit.OpCodes.Ldc_I4, 0);
                    }
                }
                break;
            }
        }
    }
Exemplo n.º 47
0
        public virtual void Emit(OpCode opcode, LocalBuilder local)
        {
            if (local == null)
            {
                throw new ArgumentNullException(nameof(local));
            }
            if (local.ilgen != this)
            {
                throw new ArgumentException(SR.Argument_UnmatchedMethodForLocal, nameof(local));
            }

            uint pos = local.position;

            if ((opcode == OpCodes.Ldloca_S || opcode == OpCodes.Ldloc_S || opcode == OpCodes.Stloc_S) && pos > 255)
            {
                throw new InvalidOperationException(SR.InvalidOperation_BadInstructionOrIndexOutOfBound);
            }

            bool load_addr = false;
            bool is_store  = false;
            bool is_load   = false;

            make_room(6);

            /* inline the code from ll_emit () to optimize il code size */
            if (opcode.StackBehaviourPop == StackBehaviour.Pop1)
            {
                cur_stack--;
                is_store = true;
            }
            else if (opcode.StackBehaviourPush == StackBehaviour.Push1 || opcode.StackBehaviourPush == StackBehaviour.Pushi)
            {
                cur_stack++;
                is_load = true;
                if (cur_stack > max_stack)
                {
                    max_stack = cur_stack;
                }
                load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
            }
            if (load_addr)
            {
                if (pos < 256)
                {
                    code[code_len++] = (byte)0x12;
                    code[code_len++] = (byte)pos;
                }
                else
                {
                    code[code_len++] = (byte)0xfe;
                    code[code_len++] = (byte)0x0d;
                    code[code_len++] = (byte)(pos & 0xff);
                    code[code_len++] = (byte)((pos >> 8) & 0xff);
                }
            }
            else
            {
                if (is_store)
                {
                    if (pos < 4)
                    {
                        code[code_len++] = (byte)(0x0a + pos);
                    }
                    else if (pos < 256)
                    {
                        code[code_len++] = (byte)0x13;
                        code[code_len++] = (byte)pos;
                    }
                    else
                    {
                        code[code_len++] = (byte)0xfe;
                        code[code_len++] = (byte)0x0e;
                        code[code_len++] = (byte)(pos & 0xff);
                        code[code_len++] = (byte)((pos >> 8) & 0xff);
                    }
                }
                else if (is_load)
                {
                    if (pos < 4)
                    {
                        code[code_len++] = (byte)(0x06 + pos);
                    }
                    else if (pos < 256)
                    {
                        code[code_len++] = (byte)0x11;
                        code[code_len++] = (byte)pos;
                    }
                    else
                    {
                        code[code_len++] = (byte)0xfe;
                        code[code_len++] = (byte)0x0c;
                        code[code_len++] = (byte)(pos & 0xff);
                        code[code_len++] = (byte)((pos >> 8) & 0xff);
                    }
                }
                else
                {
                    ll_emit(opcode);
                }
            }
        }
Exemplo n.º 48
0
        public virtual void Emit(OpCode opcode, LocalBuilder local)
        {
            if (local == null)
            {
                throw new ArgumentNullException("local");
            }
            if (local.ilgen != this)
            {
                throw new ArgumentException("Trying to emit a local from a different ILGenerator.");
            }

            uint pos       = local.position;
            bool load_addr = false;
            bool is_store  = false;
            bool is_load   = false;

            make_room(6);

            /* inline the code from ll_emit () to optimize il code size */
            if (opcode.StackBehaviourPop == StackBehaviour.Pop1)
            {
                cur_stack--;
                is_store = true;
            }
            else if (opcode.StackBehaviourPush == StackBehaviour.Push1 || opcode.StackBehaviourPush == StackBehaviour.Pushi)
            {
                cur_stack++;
                is_load = true;
                if (cur_stack > max_stack)
                {
                    max_stack = cur_stack;
                }
                load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
            }
            if (load_addr)
            {
                if (pos < 256)
                {
                    code [code_len++] = (byte)0x12;
                    code [code_len++] = (byte)pos;
                }
                else
                {
                    code [code_len++] = (byte)0xfe;
                    code [code_len++] = (byte)0x0d;
                    code [code_len++] = (byte)(pos & 0xff);
                    code [code_len++] = (byte)((pos >> 8) & 0xff);
                }
            }
            else
            {
                if (is_store)
                {
                    if (pos < 4)
                    {
                        code [code_len++] = (byte)(0x0a + pos);
                    }
                    else if (pos < 256)
                    {
                        code [code_len++] = (byte)0x13;
                        code [code_len++] = (byte)pos;
                    }
                    else
                    {
                        code [code_len++] = (byte)0xfe;
                        code [code_len++] = (byte)0x0e;
                        code [code_len++] = (byte)(pos & 0xff);
                        code [code_len++] = (byte)((pos >> 8) & 0xff);
                    }
                }
                else if (is_load)
                {
                    if (pos < 4)
                    {
                        code [code_len++] = (byte)(0x06 + pos);
                    }
                    else if (pos < 256)
                    {
                        code [code_len++] = (byte)0x11;
                        code [code_len++] = (byte)pos;
                    }
                    else
                    {
                        code [code_len++] = (byte)0xfe;
                        code [code_len++] = (byte)0x0c;
                        code [code_len++] = (byte)(pos & 0xff);
                        code [code_len++] = (byte)((pos >> 8) & 0xff);
                    }
                }
                else
                {
                    ll_emit(opcode);
                }
            }
        }
Exemplo n.º 49
0
 /// <summary>
 /// Pops the current value from the top of the evaluation stack and stores it
 /// in a the local variable list at a specified index.
 /// </summary>
 /// <param name="il">The instance of <see cref="ILGenerator"/>.</param>
 /// <param name="localBuilder">The instance of <see cref="LocalBuilder"/>.</param>
 /// <returns>The instance of <see cref="ILGenerator"/>.</returns>
 public static System.Reflection.Emit.ILGenerator Stloc(this System.Reflection.Emit.ILGenerator il, System.Reflection.Emit.LocalBuilder localBuilder)
 {
     il.Emit(System.Reflection.Emit.OpCodes.Stloc, localBuilder);
     return(il);
 }
Exemplo n.º 50
0
 public virtual void Emit(OpCode opcode, LocalBuilder local)
 {
 }
Exemplo n.º 51
0
        //public static readonly System.Reflection.MethodInfo NameValueCollectionOpImplicitMethodInfo = typeof(NameValueCollection).GetMethod("op_Implicit",new Type[] { typeof(StringContainer)});
        /// <summary>
        /// 把parameters中的值转换为Model属性中相应类型的值
        /// </summary>
        /// <param name="methodIL"></param>
        /// <param name="model"></param>
        /// <param name="propertyInfo"></param>
        /// <param name="parametersGetItem"></param>
        public static void ConvertPropertyString(ILGenerator methodIL, System.Reflection.Emit.LocalBuilder model,
                                                 System.Reflection.PropertyInfo propertyInfo, System.Reflection.MethodInfo parametersGetItem)
        {
            Type propertyType = propertyInfo.PropertyType;
            bool isNullable   = false;

            if (propertyInfo.PropertyType
#if (NET40 || NET451 || NET461)
                .IsGenericType
#endif
#if NETCORE
                .GetTypeInfo().IsGenericType
#endif
                && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                isNullable   = true;
                propertyType = propertyInfo.PropertyType.GetGenericArguments()[0];
            }
            if (propertyType == typeof(System.String))
            {
                if (!propertyInfo.GetSetMethod().IsStatic)
                {
                    methodIL.Emit(OpCodes.Ldloc, model);                               //model
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //model,nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //model,nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[typeof(String).TypeHandle]);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
                else
                {
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[typeof(String).TypeHandle]);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
            }
            else if (propertyType == typeof(System.Int32) ||
                     propertyType == typeof(System.Int16) ||
                     propertyType == typeof(System.Int64) ||
                     propertyType == typeof(System.UInt32) ||
                     propertyType == typeof(System.UInt16) ||
                     propertyType == typeof(System.UInt64) ||
                     propertyType == typeof(System.Byte) ||
                     propertyType == typeof(System.SByte) ||
                     propertyType == typeof(System.Single) ||
                     propertyType == typeof(System.Double) ||
                     propertyType == typeof(System.Decimal) ||
                     propertyType == typeof(System.DateTime) ||
                     propertyType == typeof(System.DateTimeOffset) ||
                     propertyType == typeof(System.Char) ||
                     propertyType == typeof(System.Boolean) ||
                     propertyType == typeof(System.Guid)
                     )
            {
                if (!propertyInfo.GetSetMethod().IsStatic)
                {
                    methodIL.Emit(OpCodes.Ldloc, model);
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[propertyInfo.PropertyType.TypeHandle]);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
                }
                else
                {
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[propertyInfo.PropertyType.TypeHandle]);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
                if (isNullable)
                {
                    //var temp = methodIL.DeclareLocal(propertyType);
                    //var temp1 = methodIL.DeclareLocal(propertyInfo.PropertyType);
                    //var success = methodIL.DeclareLocal(typeof(Boolean));
                    //var elseCase = methodIL.DefineLabel();
                    //var endCase = methodIL.DefineLabel();
                    //methodIL.Emit(OpCodes.Ldarg_1);//nvc
                    //methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);//nvc,key
                    //methodIL.Emit(OpCodes.Callvirt, parametersGetItem);//string
                    ////string,temp
                    //methodIL.Emit(OpCodes.Ldloca_S,temp);
                    ////bool
                    //methodIL.Emit(OpCodes.Call, propertyType.GetMethod("TryParse", new Type[] { typeof(string), propertyType.MakeByRefType() }));
                    //methodIL.Emit(OpCodes.Stloc_S,success);
                    //methodIL.Emit(OpCodes.Ldloc_S,success);
                    ////
                    //methodIL.Emit(OpCodes.Brfalse_S,elseCase);
                    ////model
                    //methodIL.Emit(OpCodes.Ldarg_0);
                    ////model,temp
                    //methodIL.Emit(OpCodes.Ldloc,temp);
                    ////model.property=new Type();
                    //methodIL.Emit(OpCodes.Newobj,propertyInfo.PropertyType.GetConstructor(new Type[] { propertyType}));
                    ////model.property.setMethod(temp);
                    //methodIL.Emit(OpCodes.Callvirt,propertyInfo.GetSetMethod());
                    //methodIL.Emit(OpCodes.Br_S,endCase);

                    //methodIL.MarkLabel(elseCase);

                    //methodIL.Emit(OpCodes.Ldarg_0);
                    //methodIL.Emit(OpCodes.Ldloca_S,temp1);
                    //methodIL.Emit(OpCodes.Initobj,propertyInfo.PropertyType);
                    //methodIL.Emit(OpCodes.Ldloc_S,temp1);
                    //methodIL.Emit(OpCodes.Callvirt,propertyInfo.GetSetMethod());
                    //methodIL.MarkLabel(endCase);
                }
                else
                {
                    //methodIL.Emit(OpCodes.Ldarg_1);//nvc
                    //methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);//nvc,key
                    //methodIL.Emit(OpCodes.Callvirt, parametersGetItem);//string
                    //var temp = methodIL.DeclareLocal(propertyInfo.PropertyType);


                    ////methodIL.Emit(OpCodes.Ldc_I4_0);
                    ////methodIL.Emit(OpCodes.Stloc,temp);

                    ////string,&temp
                    //methodIL.Emit(OpCodes.Ldloca_S, temp);
                    ////bool
                    //methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("TryParse", new Type[] { typeof(string), propertyInfo.PropertyType.MakeByRefType() }));
                    ////
                    //methodIL.Emit(OpCodes.Pop);
                    //if (!propertyInfo.GetSetMethod().IsStatic)
                    //{
                    //    //model
                    //    methodIL.Emit(OpCodes.Ldarg_0);
                    //}
                    ////model,temp
                    //methodIL.Emit(OpCodes.Ldloc, temp);
                    ////model.property=temp
                    //methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
            }
        }
Exemplo n.º 52
0
        /// <summary>
        ///  把parameters中的值转换为Model字段中相应类型的值
        /// </summary>
        /// <param name="methodIL"></param>
        /// <param name="model"></param>
        /// <param name="fieldInfo"></param>
        /// <param name="parametersGetItem"></param>
        public static void ConvertFieldString(ILGenerator methodIL, System.Reflection.Emit.LocalBuilder model,
                                              System.Reflection.FieldInfo fieldInfo, System.Reflection.MethodInfo parametersGetItem)
        {
            Type fieldType  = fieldInfo.FieldType;
            bool isNullable = false;

            if (fieldInfo.FieldType
#if (NET40 || NET451 || NET461)
                .IsGenericType
#endif
#if NETCORE
                .GetTypeInfo().IsGenericType
#endif
                && fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                isNullable = true;
                fieldType  = fieldInfo.FieldType.GetGenericArguments()[0];
            }
            if (fieldType == typeof(System.String))
            {
                //model
                methodIL.Emit(OpCodes.Ldloc, model);
                methodIL.Emit(OpCodes.Ldarg_0);                                    //model,nvc
                methodIL.Emit(OpCodes.Ldstr, fieldInfo.Name);                      //model,nvc,key
                methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[typeof(String).TypeHandle]);
                //model.field=string
                methodIL.Emit(OpCodes.Stfld, fieldInfo);
            }
            else if (fieldType == typeof(System.Int32) ||
                     fieldType == typeof(System.Int16) ||
                     fieldType == typeof(System.Int64) ||
                     fieldType == typeof(System.UInt32) ||
                     fieldType == typeof(System.UInt16) ||
                     fieldType == typeof(System.UInt64) ||
                     fieldType == typeof(System.Byte) ||
                     fieldType == typeof(System.SByte) ||
                     fieldType == typeof(System.Single) ||
                     fieldType == typeof(System.Double) ||
                     fieldType == typeof(System.Decimal) ||
                     fieldType == typeof(System.DateTime) ||
                     fieldType == typeof(System.DateTimeOffset) ||
                     fieldType == typeof(System.Char) ||
                     fieldType == typeof(System.Boolean) ||
                     fieldType == typeof(System.Guid)
                     )
            {
                //model
                methodIL.Emit(OpCodes.Ldloc, model);
                methodIL.Emit(OpCodes.Ldarg_0);                                    //model,nvc
                methodIL.Emit(OpCodes.Ldstr, fieldInfo.Name);                      //model,nvc,key
                methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[fieldInfo.FieldType.TypeHandle]);
                //model.field=string
                methodIL.Emit(OpCodes.Stfld, fieldInfo);
                //如果是泛型
                if (isNullable)
                {
                    //var temp = methodIL.DeclareLocal(fieldType);
                    //var success = methodIL.DeclareLocal(typeof(Boolean));
                    //var elseCase = methodIL.DefineLabel();
                    //var endCase = methodIL.DefineLabel();
                    //methodIL.Emit(OpCodes.Ldarg_1);//nvc
                    //methodIL.Emit(OpCodes.Ldstr, fieldInfo.Name);//nvc,key
                    //methodIL.Emit(OpCodes.Callvirt, parametersGetItem);//call ,string
                    ////string,&temp
                    //methodIL.Emit(OpCodes.Ldloca_S,temp);
                    ////bool
                    //methodIL.Emit(OpCodes.Call, fieldType.GetMethod("TryParse", new Type[] { typeof(string), fieldType.MakeByRefType() }));
                    //methodIL.Emit(OpCodes.Stloc_S, success);
                    //methodIL.Emit(OpCodes.Ldloc_S,success);
                    ////
                    //methodIL.Emit(OpCodes.Brfalse_S, elseCase);
                    //    //model
                    //    methodIL.Emit(OpCodes.Ldarg_0);
                    //    //model,temp
                    //    methodIL.Emit(OpCodes.Ldloc,temp);
                    //    //model.filed=new Type();
                    //    methodIL.Emit(OpCodes.Newobj,fieldInfo.FieldType.GetConstructor(new Type[]{ fieldType}));
                    //    //model.field=temp;
                    //    methodIL.Emit(OpCodes.Stfld,fieldInfo);
                    //methodIL.Emit(OpCodes.Br_S,endCase);
                    //methodIL.MarkLabel(elseCase);

                    //    methodIL.Emit(OpCodes.Ldarg_0);
                    //    methodIL.Emit(OpCodes.Ldflda,fieldInfo);
                    //    methodIL.Emit(OpCodes.Initobj, fieldInfo.FieldType);

                    //methodIL.MarkLabel(endCase);
                }
                else
                {
                    //methodIL.Emit(OpCodes.Ldarg_1);//nvc
                    //methodIL.Emit(OpCodes.Ldstr, fieldInfo.Name);//key
                    //methodIL.Emit(OpCodes.Callvirt, parametersGetItem);//call ,string
                    //                                                   //get:string,model
                    //methodIL.Emit(OpCodes.Ldarg_0);
                    ////get:string,&model.field
                    //methodIL.Emit(OpCodes.Ldflda, fieldInfo);
                    ////bool
                    //methodIL.Emit(OpCodes.Call, fieldType.GetMethod("TryParse", new Type[] { typeof(string), fieldType.MakeByRefType() }));
                    ////
                    //methodIL.Emit(OpCodes.Pop);
                }
            }
            else if (fieldType == typeof(NFinal.Http.HttpMultipart.HttpFile))
            {
            }
            else if (fieldType == typeof(System.IO.Stream))
            {
            }
        }
Exemplo n.º 53
0
        internal void Emit(OpCode opCode, LocalBuilder builder)
        {
            var real = Mscorlib.GetType("System.Reflection.Emit.LocalBuilder");

            this.Invoke("Emit", new Type[] { typeof(OpCode), real }, opCode, builder.Inner);
        }
Exemplo n.º 54
0
        static IEnumerable <CodeInstruction> XPiler(IEnumerable <CodeInstruction> instructions, SRE.ILGenerator generator)
        {
            var codes = instructions.ToList();

            //var gen = generator.GetCecilGen();
            SRE.LocalBuilder localAtmo = null;
            var atmoGetItem            = AccessTools.PropertyGetter(typeof(List <Atmosphere>), "Item");

            if (Patch.Debug)
            {
                Log($"List<Atmosphere>[] getter:{atmoGetItem.FullDescription()}");
            }
            //Find local atmosphere LocalBuilder
            for (int index = 160; index < codes.Count; index++)
            {
                if (codes[index].opcode == SRE.OpCodes.Callvirt &&
                    atmoGetItem.Equals(codes[index].operand))
                {
                    localAtmo = codes[++index].operand as SRE.LocalBuilder;
                    break;
                }
            }
            var fieldPlayerEnteredTiles = AccessTools.Field(typeof(Assets.Scripts.TileSystem), nameof(Assets.Scripts.TileSystem.PlayerEnteredTiles));

            //Insert extra check in the if statement
            for (int index = 165; index < codes.Count; index++)
            {
                //														/-------   Add This   -------\
                //if(!TileSystem.PlayerEnteredTiles.Contains(Vector2Int) && !atmosphere.IsValidThing())
                //find LoadField TileSystem.PlayerEnteredTiles
                if (codes[index].opcode == SRE.OpCodes.Ldsfld &&
                    fieldPlayerEnteredTiles.Equals(codes[index].operand))
                {
                    //Sanity Check
                    //check if callvirt List<vector2Int>.Contains()
                    if (codes[index + 2].opcode == SRE.OpCodes.Callvirt &&
                        typeof(List <UnityEngine.Vector2Int>).GetMethod("Contains").Equals(codes[index + 2].operand))
                    {
                        //we start 3 codes later
                        index += 3;
                        var truLabel = generator.DefineLabel();
                        var jmpLabel = generator.DefineLabel();
                        // jmp to jmpLabel if true
                        codes.Insert(index++, new CodeInstruction(SRE.OpCodes.Brtrue_S, truLabel));
                        // load atmosphere local
                        codes.Insert(index++, new CodeInstruction(SRE.OpCodes.Ldloc_S, localAtmo));
                        // callvirt bool Atmosphere.IsValidThing()
                        codes.Insert(index++, new CodeInstruction(SRE.OpCodes.Callvirt,
                                                                  AccessTools.Method(
                                                                      typeof(Atmosphere),
                                                                      nameof(Atmosphere.IsValidThing))));
                        index += 2;
                        // add our label to point to this instruction
                        codes.Insert(index++, new CodeInstruction(SRE.OpCodes.Br_S, jmpLabel));
                        codes.Insert(index, new CodeInstruction(SRE.OpCodes.Ldc_I4_0));
                        codes[index++].labels.Add(truLabel);
                        codes[index].labels.Add(jmpLabel);
                        break;
                    }
                }
            }
            return(codes);
        }
Exemplo n.º 55
0
 /// <summary>Puts the specified instruction onto the Microsoft intermediate language (MSIL) stream followed by the index of the given local variable.</summary>
 /// <param name="opcode">The MSIL instruction to be emitted onto the stream. </param>
 /// <param name="local">A local variable. </param>
 /// <exception cref="T:System.ArgumentException">The parent method of the <paramref name="local" /> parameter does not match the method associated with this <see cref="T:System.Reflection.Emit.ILGenerator" />. </exception>
 /// <exception cref="T:System.ArgumentNullException">
 /// <paramref name="local" /> is null. </exception>
 /// <exception cref="T:System.InvalidOperationException">
 /// <paramref name="opcode" /> is a single-byte instruction, and <paramref name="local" /> represents a local variable with an index greater than Byte.MaxValue. </exception>
 /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
 public static ILGenerator FluentEmit(this ILGenerator generator, System.Reflection.Emit.OpCode opcode, System.Reflection.Emit.LocalBuilder local)
 {
     generator.Emit(opcode, local);
     return(generator);
 }