示例#1
0
 public WhileInfo(string condition, Label beginLabel, Label comparasionLabel) :
     this()
 {
     Condition = condition;
     BeginLabel = beginLabel;
     ComparasionLabel = comparasionLabel;
 }
 protected override Label OnDefineLabel()
 {
     var result = new Label();
     foreach (var ilEmitter in emittersField)
         result = ilEmitter.DefineLabel();
     return result;
 }
示例#3
0
 public override void RecordLabels(ILGenerator gen)
 {
     base.RecordLabels(gen);
     returnLabel = gen.DefineLabel();
     returnLabels.Add(returnLabel);
     gosubIndex = returnLabels.Count - 1;
 }
		public override void AppendGuard(ILGenerator generator, 
			MethodInfo method, Label done)
		{
			generator.Emit(OpCodes.Ldloc_0);
			generator.Emit(OpCodes.Call, method);
			generator.Emit(OpCodes.Brfalse, done);
		}
示例#5
0
文件: CodeAnd.cs 项目: nlhepler/mono
		public override void GenerateForBranch (ILGenerator gen, Label label, bool branchCase)
		{
			Label endLabel = gen.DefineLabel ();
			exp1.Generate (gen);
			
			if (exp1 is CodeConditionExpression) {
				if (branchCase)
					((CodeConditionExpression)exp1).GenerateForBranch (gen, endLabel, false);
				else
					((CodeConditionExpression)exp1).GenerateForBranch (gen, label, false);
			}
			else {
				exp1.Generate (gen);
				if (branchCase)
					gen.Emit (OpCodes.Brfalse, endLabel);
				else
					gen.Emit (OpCodes.Brfalse, label);
			}

			if (exp2 is CodeConditionExpression) {
				if (branchCase)
					((CodeConditionExpression)exp2).GenerateForBranch (gen, label, true);
				else
					((CodeConditionExpression)exp2).GenerateForBranch (gen, label, false);
			}
			else {
				exp2.Generate (gen);
				if (branchCase)
					gen.Emit (OpCodes.Brtrue, label);
				else
					gen.Emit (OpCodes.Brfalse, label);
			}
			
			gen.MarkLabel(endLabel);
		}
示例#6
0
 public ILForLoop(Label conditionLabel, Label startLoopLogicLabel, LocalBuilder counter, LocalBuilder max)
 {
     ConditionLabel = conditionLabel;
     Counter = counter;
     Max = max;
     StartLoopLogicLabel = startLoopLogicLabel;
 }
示例#7
0
 internal Label EnsureLabel(CodeGen cg) {
     if (!_initialized) {
         _label = cg.DefineLabel();
         _initialized = true;
     }
     return _label;
 }
示例#8
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);
        }
示例#9
0
    private void genCodComp(CompOp op, Emit.Label label)
    {
        switch (op)
        {
        case CompOp.Eq:
            this.il.Emit(Emit.OpCodes.Beq, label);
            break;

        case CompOp.Neq:
            this.il.Emit(Emit.OpCodes.Bne_Un, label);
            break;

        case CompOp.Gt:
            this.il.Emit(Emit.OpCodes.Bgt, label);
            break;

        case CompOp.Gte:
            this.il.Emit(Emit.OpCodes.Bge, label);
            break;

        case CompOp.Lt:
            this.il.Emit(Emit.OpCodes.Blt, label);
            break;

        case CompOp.Lte:
            this.il.Emit(Emit.OpCodes.Ble, label);
            break;
        }
    }
 internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
 {
     this.indexVar = indexVar;
     this.beginLabel = beginLabel;
     this.testLabel = testLabel;
     this.end = end;
 }
示例#11
0
 public void genWhileStatement(ref Emit.Label whileLabel, ref Emit.Label whileBody)
 {
     whileLabel = this.il.DefineLabel();
     il.Emit(Emit.OpCodes.Br, whileLabel);
     whileBody = this.il.DefineLabel();
     this.il.MarkLabel(whileBody);
 }
示例#12
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);
			}
		}
示例#13
0
        public void TestLabelEqualityOperators()
        {
            Label lb1 = new Label();
            Label lb2 = new Label();

            Assert.True(lb1 == lb2);
            Assert.False(lb1 != lb2);
        }
示例#14
0
 public override void EmitBranchFalse(CodeGen cg, Label label) {
     if (_valueIndex == _expressions.Count - 1) {
         Emit(cg, _valueIndex);
         _expressions[_valueIndex].EmitBranchFalse(cg, label);
     } else {
         base.EmitBranchFalse(cg, label);
     }
 }
示例#15
0
        public override IEnumerable<NodeBase> Expand(Context ctx, NodeBase expression, Label nextStatement)
        {
            foreach (var rule in KeyRule.Expand(ctx, Expr.GetMember(expression, "Key"), nextStatement))
                yield return rule;

            foreach (var rule in ValueRule.Expand(ctx, Expr.GetMember(expression, "Value"), nextStatement))
                yield return rule;
        }
示例#16
0
 public virtual void GenerateForBranch(ILGenerator gen, Label label, bool jumpCase)
 {
     Generate (gen);
     if (jumpCase)
         gen.Emit (OpCodes.Brtrue, label);
     else
         gen.Emit (OpCodes.Brfalse, label);
 }
示例#17
0
            public ExceptionalReturn(Label label, LocalBuilder local)
            {
                if (local == null)
                    throw new ArgumentNullException("local");

                Label = label;
                Local = local;
            }
示例#18
0
        protected DynamicMethod CreateDynamicCompareMethod(SortProperty[] sortProperties)
        {
            DynamicMethod dm = new DynamicMethod("DynamicComparison", typeof(int), new Type[] { typeof(T), typeof(T) }, typeof(DynamicComparer <T>));

            #region Generate IL for dynamic method
            ILGenerator ilGen = dm.GetILGenerator();

            System.Reflection.Emit.Label lbl = ilGen.DefineLabel();
            ilGen.DeclareLocal(typeof(int));
            Dictionary <Type, LocalBuilder> localVariables = new Dictionary <Type, LocalBuilder>();

            ilGen.Emit(OpCodes.Ldc_I4_0);
            ilGen.Emit(OpCodes.Stloc_0);

            string       propertyName;
            PropertyInfo propertyInfo;
            foreach (SortProperty property in sortProperties)
            {
                propertyName = property.Name;
                propertyInfo = typeof(T).GetProperty(propertyName);

                ilGen.Emit(OpCodes.Ldloc_0);
                ilGen.Emit(OpCodes.Brtrue_S, lbl);
                ilGen.Emit(OpCodes.Ldarg_0);
                ilGen.EmitCall(OpCodes.Callvirt, propertyInfo.GetGetMethod(), null);

                if (propertyInfo.PropertyType.IsValueType)
                {
                    if (!localVariables.ContainsKey(propertyInfo.PropertyType))
                    {
                        localVariables.Add(propertyInfo.PropertyType, ilGen.DeclareLocal(propertyInfo.PropertyType));
                    }

                    int localIndex = localVariables[propertyInfo.PropertyType].LocalIndex;

                    ilGen.Emit(OpCodes.Stloc, localIndex);
                    ilGen.Emit(OpCodes.Ldloca_S, localIndex);
                }

                ilGen.Emit(OpCodes.Ldarg_1);
                ilGen.EmitCall(OpCodes.Callvirt, propertyInfo.GetGetMethod(), null);
                ilGen.EmitCall(OpCodes.Callvirt, propertyInfo.PropertyType.GetMethod("CompareTo", new Type[] { propertyInfo.PropertyType }), null);

                if (property.Descending)
                {
                    ilGen.Emit(OpCodes.Neg);
                }

                ilGen.Emit(OpCodes.Stloc_0);
            }

            ilGen.MarkLabel(lbl);
            ilGen.Emit(OpCodes.Ldloc_0);
            ilGen.Emit(OpCodes.Ret);
            #endregion

            return(dm);
        }
示例#19
0
 public override IEnumerable<NodeBase> Expand(Context ctx, NodeBase expression, Label nextStatement)
 {
     yield return Expr.If(
         Expr.NotEqual(Literal as NodeBase, expression),
         Expr.Block(
             Expr.JumpTo(nextStatement)
         )
     );
 }
		public DynamicMethodBody MarkLabel(Label label)
		{
#if DEBUG
			Console.WriteLine("IL_{0}:", label.GetHashCode());
#endif
			Emitter.MarkLabel(label);

			return this;
		}
示例#21
0
		public override void GenerateForBranch (ILGenerator gen, Label label, bool branchCase)
		{
			exp1.Generate (gen);
			exp2.Generate (gen);
			if (branchCase)
				gen.Emit (OpCodes.Bgt, label);
			else
				gen.Emit (OpCodes.Ble, label);
		}
示例#22
0
文件: CodeWhen.cs 项目: nickchal/pash
		void GenerateCondition (ILGenerator gen, Label falseLabel)
		{
			if (condition is CodeConditionExpression)
				((CodeConditionExpression)condition).GenerateForBranch (gen, falseLabel, false);
			else {
				condition.Generate (gen);
				gen.Emit (OpCodes.Brfalse, falseLabel);
			}
		}
示例#23
0
		internal virtual void EmitBranch(CodeGen g, BranchSet branchSet, Label label)
		{
			if (g == null)
				throw new ArgumentNullException("g");
			if (branchSet == null)
				throw new ArgumentNullException("branchSet");

			EmitGet(g);
			g.IL.Emit(branchSet.brTrue, label);
		}
      protected override void ExecuteInitialize()
      {
        _currProfiler = _currFuncCode.Profiler;
        _globalContext = null;
        _deoptimizer = _ilGen.DefineLabel();

        Debug.Assert(JSRuntime.Instance.Configuration.EnableSpeculativeJIT && _currProfiler != null && _currFuncCode.IsHot && _currProfiler != null, "Invalid situation! Speculation conditions are not correct!");

        base.ExecuteInitialize();
      }
示例#25
0
        public void PosTest1()
        {
            Label label1 = new Label();
            Label label2 = new Label();
            int la1hash = label1.GetHashCode();
            int la2hash = label2.GetHashCode();
            Assert.Equal(la1hash, 0);

            Assert.Equal(la1hash, la2hash);
        }
示例#26
0
 public void Emit_Or_Shortcut(parse_tree.boolean2 left, parse_tree.boolean_expression right)
 {
     System.Reflection.Emit.Label l2 = gen.DefineLabel();
     left.emit_code(this, 0);
     gen.Emit(OpCodes.Dup);
     gen.Emit(System.Reflection.Emit.OpCodes.Brtrue, l2);
     right.emit_code(this, 0);
     Emit_Or();
     gen.MarkLabel(l2);
 }
        protected override AssemblyDebugging CreateAssembly()
        {
            using (var assembly = DebuggingTests.CreateDebuggingAssembly("MethodThatCreatesSwitch"))
            {
                using (var type = DebuggingTests.CreateDebuggingType(
                    assembly, assembly.Builder.GetDynamicModule(assembly.Builder.GetName().Name),
                    "SimpleClass"))
                {
                    using (var ctor = type.GetMethodDebugging(
                        type.Builder.DefineConstructor(
                            MethodAttributes.Public | MethodAttributes.SpecialName |
                            MethodAttributes.RTSpecialName | MethodAttributes.HideBySig,
                            CallingConventions.Standard, Type.EmptyTypes)))
                    {
                        ctor.Emit(OpCodes.Ldarg_0);
                        var objectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
                        ctor.Emit(OpCodes.Call, objectCtor);
                        ctor.Emit(OpCodes.Ret);
                    }

                    using (var method = type.GetMethodDebugging(
                        type.Builder.DefineMethod("GenerateSwitch",
                        MethodAttributes.HideBySig | MethodAttributes.Public,
                        typeof(string), new Type[] { typeof(int) })))
                    {
                        var defaultCase = method.DefineLabel();
                        var endOfMethod = method.DefineLabel();

                        method.Emit(OpCodes.Ldarg_1);
                        var jumpTable = new Label[] { method.DefineLabel(), method.DefineLabel() };
                        method.Emit(OpCodes.Switch, jumpTable);

                        method.Emit(OpCodes.Br_S, defaultCase);

                        method.MarkLabel(jumpTable[0]);
                        method.Emit(OpCodes.Ldstr, "It's zero.");
                        method.Emit(OpCodes.Br_S, endOfMethod);

                        method.MarkLabel(jumpTable[1]);
                        method.Emit(OpCodes.Ldstr, "It's one.");
                        method.Emit(OpCodes.Br_S, endOfMethod);

                        method.MarkLabel(defaultCase);
                        method.Emit(OpCodes.Ldstr, "It's something else.");

                        method.MarkLabel(endOfMethod);
                        method.Emit(OpCodes.Ret);
                    }

                    type.Builder.CreateType();
                }

                return assembly;
            }
        }
示例#28
0
		private void GenerateIsSameValueComparison()
		{
			EmitHelper emit = Context.MethodBuilder.Emitter;

			if (_skipSetterOnNoChange)
				_afterNotificationLabel = emit.DefineLabel();
			else
				_isSameValueBuilder = emit.DeclareLocal(typeof(bool));

			MethodInfo op_InequalityMethod =
				Context.CurrentProperty.PropertyType.GetMethod("op_Inequality",
					new Type[]
						{
							Context.CurrentProperty.PropertyType,
							Context.CurrentProperty.PropertyType
						});

			if (op_InequalityMethod == null)
			{
				if (Context.CurrentProperty.PropertyType.IsValueType || !_useReferenceEquals)
				{
					emit
						.ldarg_0
						.callvirt  (Context.CurrentProperty.GetGetMethod(true))
						.ldarg_1
						.ceq
						.end();
				}
				else
				{
					emit
						.ldarg_0
						.callvirt  (Context.CurrentProperty.GetGetMethod(true))
						.ldarg_1
						.call      (typeof(object), "ReferenceEquals", typeof(object), typeof(object))
						.end();
				}
			}
			else
			{
				emit
					.ldarg_0
					.callvirt (Context.CurrentProperty.GetGetMethod(true))
					.ldarg_1
					.call     (op_InequalityMethod)
					.ldc_i4_0
					.ceq
					.end();
			}

			if (_skipSetterOnNoChange)
				emit.brtrue(_afterNotificationLabel);
			else
				emit.stloc(_isSameValueBuilder);
		}
示例#29
0
 public ForInfo(string variable, Number from, Number to, int step,
                Label beginLabel, Label comparasionLabel) :
                    this()
 {
     Variable = variable;
     From = from;
     To = to;
     Step = step;
     BeginLabel = beginLabel;
     ComparasionLabel = comparasionLabel;
 }
 internal override void TranslateToConditionalBranch(ILGenerator il, bool branchIfTrue, Label label, bool shortForm){
   Label exit = il.DefineLabel();
   if (branchIfTrue){
     this.operand1.TranslateToConditionalBranch(il, true, label, shortForm);
     this.operand2.TranslateToConditionalBranch(il, true, label, shortForm);
   }else{
     this.operand1.TranslateToConditionalBranch(il, true, exit, shortForm);
     this.operand2.TranslateToConditionalBranch(il, false, label, shortForm);
     il.MarkLabel(exit);
   }
 }
示例#31
0
		public DynamicMethodBody Emit(OpCode opcode, Label arg)
		{
			ExecutePreEmitActions();
	#if DEBUG
						Console.WriteLine("\t{0} IL_{1}", opcode, arg.GetHashCode());
				#endif
			
			Emitter.Emit(opcode, arg);

			return this;
		}
示例#32
0
        public override void Switch(Label[] jumpTable)
        {
            var emitLabels = new EmitLabel[jumpTable.Length];

            for (int i = 0; i < jumpTable.Length; ++i)
            {
                emitLabels[i] = GetEmitLabel(jumpTable[i]);
            }

            generator.Emit(OpCodes.Switch, emitLabels);
        }
示例#33
0
        public override IEnumerable<NodeBase> Expand(Context ctx, NodeBase expression, Label nextStatement)
        {
            for (var idx = 0; idx < ElementRules.Count; idx++)
            {
                var fieldName = string.Format("Item{0}", idx + 1);
                var rules = ElementRules[idx].Expand(ctx, Expr.GetMember(expression, fieldName), nextStatement);

                foreach (var rule in rules)
                    yield return rule;
            }
        }
示例#34
0
		public override void Branch( TracingILGenerator il, Label @else )
		{
			il.TraceWriteLine( "// Brnc->: {0}", this );
			foreach ( var expression in this._expressions )
			{
				expression.LoadValue( il, false );
				il.EmitBrfalse( @else );
			}

			il.TraceWriteLine( "// ->Brnc: {0}", this );
		}
 private void EnsureLabelAndValue()
 {
     if (!this._labelDefined)
     {
         this._labelDefined = true;
         this._label        = this._ilg.DefineLabel();
         if ((this._node != null) && (this._node.Type != typeof(void)))
         {
             this._value = this._ilg.DeclareLocal(this._node.Type);
         }
     }
 }
示例#36
0
 public override IEnumerable<NodeBase> Expand(Context ctx, NodeBase expression, Label nextStatement)
 {
     yield return Expr.If(
         Expr.Or(
             Expr.Less(expression, RangeStartRule.Literal as NodeBase),
             Expr.Greater(expression, RangeEndRule.Literal as NodeBase)
         ),
         Expr.Block(
             Expr.JumpTo(nextStatement)
         )
     );
 }
 private void CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] requiredElements, Label throwMissingRequiredMembersLabel)
 {
     for (int i = 0; i < requiredElements.Length; i++)
     {
         this.ilg.Load(expectedElements.GetLocal(i));
         this.ilg.Load(requiredElements[i]);
         this.ilg.And();
         this.ilg.Load(0);
         this.ilg.Ceq();
         this.ilg.Brfalse(throwMissingRequiredMembersLabel);
     }
 }
示例#38
0
 public void emitGetProperty(ILGenerator il, System.Reflection.Emit.Label cancel)
 {
     System.Reflection.Emit.Label miOK = il.DefineLabel();
     il.Emit(OpCodes.Dup);                               //duplicate instance
     il.Emit(OpCodes.Ldstr, Tokens [Tokens.Length - 1]); //load member name
     il.Emit(OpCodes.Call, CompilerServices.miGetMembIinfoWithRefx);
     il.Emit(OpCodes.Dup);
     il.Emit(OpCodes.Brtrue, miOK);
     il.Emit(OpCodes.Pop);             //pop dup instance
     il.Emit(OpCodes.Br, cancel);
     il.MarkLabel(miOK);
     il.Emit(OpCodes.Call, CompilerServices.miGetValWithRefx);
 }
示例#39
0
        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);
        }
示例#40
0
        private void BeginOverrideMethods(TypeBuilder typeBuilder)
        {
            MethodBuilder methodBuilder = typeBuilder.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(bool), new Type[1]
            {
                typeof(object)
            });

            methodBuilder.DefineParameter(1, ParameterAttributes.None, "obj");
            this._EqualsGenerator = methodBuilder.GetILGenerator();
            this._EqualsGenerator.DeclareLocal(typeof(bool));
            this._EqualsGenerator.Emit(OpCodes.Nop);
            this._EqualsGenerator.Emit(OpCodes.Ldarg_1);
            this._EndLabel = this._EqualsGenerator.DefineLabel();
            this._EqualsGenerator.Emit(OpCodes.Isinst, (Type)typeBuilder);
            this._EqualsGenerator.Emit(OpCodes.Brfalse, this._EndLabel);
        }
示例#41
0
 public void Emit_And_Shortcut(parse_tree.boolean_parseable left,
                               parse_tree.boolean2 right,
                               bool left_negated)
 {
     System.Reflection.Emit.Label l2 = gen.DefineLabel();
     left.emit_code(this, 0);
     if (left_negated)
     {
         Emit_Not();
     }
     gen.Emit(OpCodes.Dup);
     gen.Emit(System.Reflection.Emit.OpCodes.Brfalse, l2);
     right.emit_code(this, 0);
     Emit_And();
     gen.MarkLabel(l2);
 }
示例#42
0
        public void emitGetTarget(ILGenerator il, System.Reflection.Emit.Label cancel)
        {
            if (IsTemplateBinding)
            {
                System.Reflection.Emit.Label nextLogicParent = il.DefineLabel();
                il.MarkLabel(nextLogicParent);
                il.Emit(OpCodes.Callvirt, CompilerServices.miGetLogicalParent);
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Brfalse, cancel);
                il.Emit(OpCodes.Isinst, typeof(TemplatedControl));
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Brfalse, nextLogicParent);
            }
            else if (LevelsUp > 0)                 //go upward in logical tree
            {
                il.Emit(OpCodes.Ldc_I4, LevelsUp); //push arg 2 of goUpLevels
                il.Emit(OpCodes.Callvirt, CompilerServices.miGoUpLevels);
                //test if null
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Brfalse, cancel);
            }

            if (!string.IsNullOrEmpty(Tokens [0]))               //find by name
            {
                il.Emit(OpCodes.Ldstr, Tokens [0]);
                il.Emit(OpCodes.Callvirt, CompilerServices.miFindByName);
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Brfalse, cancel);
            }

            for (int i = 1; i < Tokens.Length - 1; i++)
            {
                System.Reflection.Emit.Label miOK = il.DefineLabel();
                il.Emit(OpCodes.Dup);                 //duplicate instance
                il.Emit(OpCodes.Ldstr, Tokens [i]);   //load member name
                il.Emit(OpCodes.Call, CompilerServices.miGetMembIinfoWithRefx);
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Brtrue, miOK);
                il.Emit(OpCodes.Pop);                 //pop dup instance
                il.Emit(OpCodes.Br, cancel);
                il.MarkLabel(miOK);
                il.Emit(OpCodes.Call, CompilerServices.miGetValWithRefx);
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Brfalse, cancel);
            }
        }
示例#43
0
 private void EndOverrideMethods(Type parentType)
 {
     this._EqualsGenerator.Emit(OpCodes.Ldarg_0);
     this._EqualsGenerator.Emit(OpCodes.Ldarg_1);
     this._EqualsGenerator.Emit(OpCodes.Call, parentType.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public));
     System.Reflection.Emit.Label label1 = this._EqualsGenerator.DefineLabel();
     this._EqualsGenerator.Emit(OpCodes.Br_S, label1);
     this._EqualsGenerator.MarkLabel(this._EndLabel);
     this._EqualsGenerator.Emit(OpCodes.Ldc_I4_0);
     this._EqualsGenerator.MarkLabel(label1);
     this._EqualsGenerator.Emit(OpCodes.Stloc_0);
     System.Reflection.Emit.Label label2 = this._EqualsGenerator.DefineLabel();
     this._EqualsGenerator.Emit(OpCodes.Br_S, label2);
     this._EqualsGenerator.MarkLabel(label2);
     this._EqualsGenerator.Emit(OpCodes.Ldloc_0);
     this._EqualsGenerator.Emit(OpCodes.Ret);
     this._EqualsGenerator = (ILGenerator)null;
 }
示例#44
0
        private static IEnumerable <CodeInstruction> Transpiler(
            IEnumerable <CodeInstruction> instructions,
            ILGenerator il)
        {
            MethodInfo             methodInfo = AccessTools.Method(typeof(UpgradeReadyTroopsPatch), "templateProhibitsUpgrade");
            MethodInfo             getMethod1 = AccessTools.Property(typeof(CharacterObject), "UpgradeTargets").GetGetMethod();
            MethodInfo             getMethod2 = AccessTools.Property(typeof(BasicCultureObject), "IsBandit").GetGetMethod();
            List <CodeInstruction> source     = new List <CodeInstruction>(instructions);
            object operand = (object)null;

            for (int index = 0; index < source.Count; ++index)
            {
                if (operand == null && source[index].opcode == OpCodes.Stloc_S && (source[index - 1].opcode == OpCodes.Ldelem_Ref && source[index - 2].opcode == OpCodes.Ldloc_S) && (source[index - 3].opcode == OpCodes.Callvirt && source[index - 3].operand as MethodInfo == getMethod1))
                {
                    operand = source[index].operand;
                }
                if (operand != null && source[index].opcode == OpCodes.Stloc_S && (source[index - 1].opcode == OpCodes.Callvirt && source[index - 1].operand as MethodInfo == getMethod2))
                {
                    List <System.Reflection.Emit.Label> labels = source[index + 1].labels;
                    source[index + 1].labels = (List <System.Reflection.Emit.Label>)null;
                    source.Insert(index + 1, new CodeInstruction(OpCodes.Ldarg_1)
                    {
                        labels = labels
                    });
                    source.Insert(index + 2, new CodeInstruction(OpCodes.Ldloc_S, operand));
                    source.Insert(index + 3, new CodeInstruction(OpCodes.Call, (object)methodInfo));
                    System.Reflection.Emit.Label label = il.DefineLabel();
                    source.Insert(index + 4, new CodeInstruction(OpCodes.Brfalse_S, (object)label));
                    source.Insert(index + 5, new CodeInstruction(OpCodes.Ldc_I4_0));
                    source.Insert(index + 6, new CodeInstruction(OpCodes.Stloc_S, source[index].operand));
                    source.Insert(index + 7, new CodeInstruction(OpCodes.Nop)
                    {
                        labels = new List <System.Reflection.Emit.Label>()
                        {
                            label
                        }
                    });
                    return(source.AsEnumerable <CodeInstruction>());
                }
            }
            int num = (int)MessageBox.Show("Party AI Overhaul and Commands: Failed to make AI troop upgrading adhere to recruitment templates. This is not a critical bug, you may continue playing without this feature.");

            return(source.AsEnumerable <CodeInstruction>());
        }
示例#45
0
    public void genEndForStatement(uint scope, string proc_actual, string varControl, Symbol fin,
                                   ref Emit.Label forLabel, ref Emit.Label forBody)
    {
        int    tipo  = 0;
        Symbol store = symtab.getSymbol(proc_actual, varControl, ref tipo);

        /* Si no existen procedimientos */
        if (proc_actual == "" && store == null)
        {
            store = symtab.getSymbol(varControl);
        }
        this.loadVariable(store, false, scope, proc_actual);
        this.il.Emit(Emit.OpCodes.Ldc_I4, 1);
        this.il.Emit(Emit.OpCodes.Add);
        this.storeVariable(store, false, scope, proc_actual);
        this.il.MarkLabel(forLabel);
        this.loadVariable(store, false, scope, proc_actual);
        this.loadVariable(fin, false, scope, proc_actual);
        this.il.Emit(Emit.OpCodes.Ble, forBody);
    }
示例#46
0
    public void genForStatement(uint scope, string proc_actual, string varControl, Symbol ini,
                                ref Emit.Label forLabel, ref Emit.Label forBody)
    {
        int tipo = 0;

        this.loadVariable(ini, false, scope, proc_actual);
        Symbol store = symtab.getSymbol(proc_actual, varControl, ref tipo);

        /* Si no existen procedimientos */
        if (proc_actual == "" && store == null)
        {
            store = symtab.getSymbol(varControl);
        }
        /* store debe estar definido o fallar en pasadas anteriores */
        this.storeVariable(store, false, scope, proc_actual);
        forLabel = this.il.DefineLabel();
        this.il.Emit(Emit.OpCodes.Br, forLabel);
        forBody = this.il.DefineLabel();
        this.il.MarkLabel(forBody);
    }
示例#47
0
        // Creates a dymamic class to perform the cast
        protected void CreateCasterObject()
        {
            TypeBuilder tb;

            lock (GetType()){
                tb = AssemblySupport.ModBuilder.DefineType("CasterClass" + _classNumber++,
                                                           TypeAttributes.Class | TypeAttributes.Public);
                tb.DefineDefaultConstructor(MethodAttributes.Public);
            }
            Type[] parameterTypes = new Type[1];
            parameterTypes[0] = typeof(Object);
            // The event handler method, Calls the "LoggerBase"
            // method to do the actual logging
            MethodBuilder mb = tb.DefineMethod("DoCast", MethodAttributes.Public,
                                               typeof(Object), parameterTypes);
            ILGenerator gen = mb.GetILGenerator();

            System.Reflection.Emit.Label l = gen.DefineLabel();
            gen.DeclareLocal(_castType);
            // Load object to cast
            gen.Emit(OpCodes.Ldarg_1);
            // Do the cast
            gen.Emit(OpCodes.Castclass, _castType);
            // Save result of cast
            gen.Emit(OpCodes.Stloc_0);
            // Branch?
            gen.Emit(OpCodes.Br_S, l);
            gen.MarkLabel(l);
            // Get result of cast
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
            Type type = tb.CreateType();

            // Only method is "DoCast", do this to
            // avoid using the name so that we don't have a problem with the
            // obfuscator
            _castingMethod = type.GetMethods(BindingFlags.Public
                                             | BindingFlags.Instance
                                             | BindingFlags.DeclaredOnly)[0];
            _castingObject = Activator.CreateInstance(type);
        }
示例#48
0
        private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

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

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

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

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();

            System.Reflection.Emit.Label modifyProperty = setIl.DefineLabel();
            System.Reflection.Emit.Label exitSet        = setIl.DefineLabel();

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

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

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
示例#49
0
        private void GenerateEquals(TypeBuilder tb, FieldInfo[] fields)
        {
            MethodBuilder mb = tb.DefineMethod(
                "Equals",
                MethodAttributes.Public | MethodAttributes.ReuseSlot |
                MethodAttributes.Virtual | MethodAttributes.HideBySig,
                typeof(bool),
                new[] { typeof(object) });
            ILGenerator  gen   = mb.GetILGenerator();
            LocalBuilder other = gen.DeclareLocal(tb);

            System.Reflection.Emit.Label next = gen.DefineLabel();
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Isinst, tb);
            gen.Emit(OpCodes.Stloc, other);
            gen.Emit(OpCodes.Ldloc, other);
            gen.Emit(OpCodes.Brtrue_S, next);
            gen.Emit(OpCodes.Ldc_I4_0);
            gen.Emit(OpCodes.Ret);
            gen.MarkLabel(next);
            foreach (FieldInfo field in fields)
            {
                Type ft = field.FieldType;
                Type ct = typeof(EqualityComparer <>).MakeGenericType(ft);
                next = gen.DefineLabel();
                gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Ldfld, field);
                gen.Emit(OpCodes.Ldloc, other);
                gen.Emit(OpCodes.Ldfld, field);
                gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new[] { ft, ft }), null);
                gen.Emit(OpCodes.Brtrue_S, next);
                gen.Emit(OpCodes.Ldc_I4_0);
                gen.Emit(OpCodes.Ret);
                gen.MarkLabel(next);
            }
            gen.Emit(OpCodes.Ldc_I4_1);
            gen.Emit(OpCodes.Ret);
        }
示例#50
0
        public void LeaveDataOnStackBetweenBranches_OldSchool()
        {
            var dm = new System.Reflection.Emit.DynamicMethod("foo", typeof(int), null);
            var il = dm.GetILGenerator();

            System.Reflection.Emit.Label b0 = il.DefineLabel(), b1 = il.DefineLabel(), b2 = il.DefineLabel();
            il.Emit(System.Reflection.Emit.OpCodes.Ldstr, "abc");
            il.Emit(System.Reflection.Emit.OpCodes.Br, b0); // jump to b0 with "abc"

            il.MarkLabel(b1);                               // incoming: 3
            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_4);
            il.EmitCall(System.Reflection.Emit.OpCodes.Call, typeof(Math).GetMethod("Max", new[] { typeof(int), typeof(int) }), null);
            il.Emit(System.Reflection.Emit.OpCodes.Br, b2); // jump to b2 with 4

            il.MarkLabel(b0);                               // incoming: "abc"
            il.EmitCall(System.Reflection.Emit.OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(), null);
            il.Emit(System.Reflection.Emit.OpCodes.Br, b1); // jump to b1 with 3

            il.MarkLabel(b2);                               // incoming: 4
            il.Emit(System.Reflection.Emit.OpCodes.Ret);
            int i = ((Func <int>)dm.CreateDelegate(typeof(Func <int>)))();

            Assert.AreEqual(4, i);
        }
 public virtual new void Emit(OpCode opcode, Label label)
 {
 }
        private static void CreateProperty(TypeBuilder tb, FieldBuilder dynamicRangeDomainValidation, string propertyName, Type propertyType, FeatureLayerInfo layerInfo, Field field, int order, bool isKey)
        {
            // Create the private data backed property i.e. (private int _myProperty)
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            // Create the public property i.e. (public int MyProperty { get { return _myProperty; } set{ _myPropety = value; } })
            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

            string displayName = null;

            if (field != null)
            {
                displayName = field.Alias;
            }
            if (string.IsNullOrEmpty(displayName))
            {
                displayName = _fieldMapping.KeyOfValue(propertyName);
            }
            if (!string.IsNullOrEmpty(displayName))
            {
                // Add DisplayAttribute to property [DisplayAttribute(Name = displayName)]
                Type                   displayAttribute = typeof(DisplayAttribute);
                PropertyInfo           info             = displayAttribute.GetProperty("Name");
                PropertyInfo           info2            = displayAttribute.GetProperty("AutoGenerateField");
                PropertyInfo           info3            = displayAttribute.GetProperty("Order");
                CustomAttributeBuilder cabuilder        = new CustomAttributeBuilder(
                    displayAttribute.GetConstructor(new Type[] { }),
                    new object[] { },
                    new PropertyInfo[] { info, info2, info3 }, new object[] { displayName, !isKey, order });
                propertyBuilder.SetCustomAttribute(cabuilder);
            }
            if (isKey)
            {
                // Add KeyAttribute to property [KeyAttribute]
                CustomAttributeBuilder cabuilder = new CustomAttributeBuilder(
                    typeof(KeyAttribute).GetConstructor(new Type[] { }),
                    new object[] { });
                propertyBuilder.SetCustomAttribute(cabuilder);
            }

            if (field != null)
            {
                if (!field.Nullable && field.Type != Field.FieldType.GlobalID)
                {
                    // Add Required to property using standard validation error [Required()]
                    CustomAttributeBuilder requiredCABuilder = new CustomAttributeBuilder(
                        typeof(System.ComponentModel.DataAnnotations.RequiredAttribute).GetConstructor(new Type[] { }),
                        new object[] { });
                    propertyBuilder.SetCustomAttribute(requiredCABuilder);
                }

                // Add AllowEdit to property and allow an initial value
                PropertyInfo           allowEditInfo         = typeof(EditableAttribute).GetProperty("AllowEdit");
                PropertyInfo           allowInitialValueInfo = typeof(EditableAttribute).GetProperty("AllowInitialValue");
                CustomAttributeBuilder allowEditCABuilder    = new CustomAttributeBuilder(
                    typeof(EditableAttribute).GetConstructor(new Type[] { typeof(bool) }),
                    new object[] { field.Editable },
                    new PropertyInfo[] { allowEditInfo, allowInitialValueInfo }, new object[] { field.Editable, true });
                propertyBuilder.SetCustomAttribute(allowEditCABuilder);


                // Add MaximumLength to property
                if (field.Type == Field.FieldType.String && field.Length > 0)
                {
                    PropertyInfo           maximumLengthInfo = typeof(StringLengthAttribute).GetProperty("MaximumLength");
                    CustomAttributeBuilder cabuilder         = new CustomAttributeBuilder(
                        typeof(StringLengthAttribute).GetConstructor(new Type[] { typeof(int) }),
                        new object[] { field.Length },
                        new PropertyInfo[] { maximumLengthInfo }, new object[] { field.Length });
                    propertyBuilder.SetCustomAttribute(cabuilder);
                }
            }

            if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
            {
                // Add DisplayAttribute to property [DisplayFormatAttribute(DataFormatString = "m/dd/YYYY")]
                PropertyInfo           info      = typeof(DisplayFormatAttribute).GetProperty("DataFormatString");
                CustomAttributeBuilder cabuilder = new CustomAttributeBuilder(
                    typeof(DisplayFormatAttribute).GetConstructor(new Type[] { }),
                    new object[] { },
                    new PropertyInfo[] { info }, new object[] { System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern });
                propertyBuilder.SetCustomAttribute(cabuilder);
            }

            MethodBuilder getPropMthdBldr =
                tb.DefineMethod("get_" + propertyName,
                                MethodAttributes.Public |
                                MethodAttributes.SpecialName |
                                MethodAttributes.HideBySig,
                                propertyType, Type.EmptyTypes);

            ILGenerator getIL = getPropMthdBldr.GetILGenerator();

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

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

            ILGenerator setIL = setPropMthdBldr.GetILGenerator();

            // for feature layer range domain validation is added to the setter call.
            if (dynamicRangeDomainValidation != null)
            {
                // Labels are used to jump ahead to a specific line of code.
                // for example if an if statement returns false then you will want to jump
                // over the code that would execute if the condition was true because you don't
                // want that code to get executed.

                // An un-named temp variable that the compiler needs
                // in order to store the resulting boolean from the if statement.
                setIL.DeclareLocal(typeof(bool)); // Stloc_0
                System.Reflection.Emit.Label endIfLabel = setIL.DefineLabel();

                setIL.Emit(OpCodes.Ldarg_0);                               // load this instance
                setIL.Emit(OpCodes.Ldfld, dynamicRangeDomainValidation);   // load this field
                setIL.Emit(OpCodes.Ldnull);                                // load a null value
                setIL.Emit(OpCodes.Ceq);                                   // compare equality
                setIL.Emit(OpCodes.Stloc_0);                               // store the result of the equality check. note: setIL.DeclareLocal(typeof(bool)) must be declared.
                setIL.Emit(OpCodes.Ldloc_0);                               // load the result of the equality check
                setIL.Emit(OpCodes.Brtrue_S, endIfLabel);                  // if true execute the next argument. if false jump to the else if statement label.
                setIL.Emit(OpCodes.Ldarg_0);
                setIL.Emit(OpCodes.Ldfld, dynamicRangeDomainValidation);
                setIL.Emit(OpCodes.Ldarg_0);
                setIL.Emit(OpCodes.Ldstr, field != null ? field.FieldName : "");
                setIL.Emit(OpCodes.Ldarg_1);
                setIL.Emit(OpCodes.Box, propertyType);
                setIL.Emit(OpCodes.Callvirt, typeof(Action <object, string, object>).GetMethod("Invoke", new Type[] { typeof(object), typeof(string), typeof(object) }));
                setIL.MarkLabel(endIfLabel);
            }
            setIL.Emit(OpCodes.Ldarg_0);
            setIL.Emit(OpCodes.Ldarg_1);
            setIL.Emit(OpCodes.Stfld, fieldBuilder);
            setIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
示例#53
0
        private void CompileStatement(Node ActiveNode)
        {
            if (ActiveNode.Nodes[0].TypeToken == TokenType.KW_IF)
            {
                Emit.Label ElseLabel = this.AssemblerGenerator.DefineLabel();

                Emit.Label EndIfElseLabel = this.AssemblerGenerator.DefineLabel();

                // Вычисляем логическое значение
                CreateCode(ActiveNode.Nodes[2]);
                // Если false -  переход на метку "ИНАЧЕ"
                this.AssemblerGenerator.Emit(Emit.OpCodes.Brfalse, ElseLabel);

                // Разбираем блок "ЕСЛИ"
                CreateCode(ActiveNode.Nodes[4]);

                // Переход на метку "Конец блока иначе"
                this.AssemblerGenerator.Emit(Emit.OpCodes.Br, EndIfElseLabel);

                // Ставим метку "ИНАЧЕ"
                this.AssemblerGenerator.MarkLabel(ElseLabel);

                // Разбираем блок "Иначе"
                CreateCode(ActiveNode.Nodes[6]);

                // Ставим метку "Конец блока иначе"
                this.AssemblerGenerator.MarkLabel(EndIfElseLabel);
            }

            if (ActiveNode.Nodes[0].TypeToken == TokenType.KW_WHILE)
            {
                Emit.Label TestCycleLabel = this.AssemblerGenerator.DefineLabel();
                Emit.Label EndCycleLabel  = this.AssemblerGenerator.DefineLabel();

                // Начало цикла
                AssemblerGenerator.MarkLabel(TestCycleLabel);

                // Вычисляем логическое выражение
                CreateCode(ActiveNode.Nodes[2]);

                // Если false переходим на конец цикла
                this.AssemblerGenerator.Emit(Emit.OpCodes.Brfalse, EndCycleLabel);

                // Тело цикла
                CreateCode(ActiveNode.Nodes[4]);


                // Переход на начало цикла
                this.AssemblerGenerator.Emit(Emit.OpCodes.Br, TestCycleLabel);
                // Метка конца цикла
                this.AssemblerGenerator.MarkLabel(EndCycleLabel);
            }

            if (ActiveNode.Nodes[0].TypeToken == TokenType.KW_SYSTEM)
            {
                CreateCode(ActiveNode.Nodes[6]);

                this.AssemblerGenerator.Emit(Emit.OpCodes.Call,
                                             typeof(System.Convert).GetMethod("ToString", new System.Type[] { typeof(int) }));

                this.AssemblerGenerator.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
            }

            if (ActiveNode.Nodes[0].TypeToken == TokenType.O_P_BRACKET)
            {
                OpenBlockVariables();
                CreateCode(ActiveNode.Nodes[1]);
                CloseBlockVariables();
            }

            if ((ActiveNode.Nodes[0].TypeToken == TokenType.ID) && (ActiveNode.Nodes[1].TypeToken == TokenType.OP_EQUAL))
            {
                CreateCode(ActiveNode.Nodes[2]);
                Store(ActiveNode.Nodes[0].Value);
            }

            if ((ActiveNode.Nodes[0].TypeToken == TokenType.ID) && (ActiveNode.Nodes[1].TypeToken == TokenType.O_S_BRACKET))
            {
                Load(ActiveNode.Nodes[0].Value);

                CreateCode(ActiveNode.Nodes[2]);

                CreateCode(ActiveNode.Nodes[5]);

                AssemblerGenerator.Emit(Emit.OpCodes.Stelem_I4);
            }
        }
示例#54
0
文件: CodeGen.cs 项目: slb1988/cs143
    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 DeclareVar)
        {
            // declare a local
            DeclareVar declare = (DeclareVar)stmt;
            this.symbolTable[declare.Ident] = this.il.DeclareLocal(this.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)
        {
            Assign assign = (Assign)stmt;
            this.GenExpr(assign.Expr, this.TypeOfExpr(assign.Expr));
            this.Store(assign.Ident, this.TypeOfExpr(assign.Expr));
        }
        else if (stmt is Print)
        {
            // the "print" statement is an alias for System.Console.WriteLine.
            // it uses the string case
            this.GenExpr(((Print)stmt).Expr, typeof(string));
            this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
        }

        else if (stmt is ReadInt)
        {
            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(((ReadInt)stmt).Ident, typeof(int));
        }
        else if (stmt is ForLoop)
        {
            // example:
            // for x = 0 to 100 do
            //   print "hello";
            // end;

            // x = 0
            ForLoop forLoop = (ForLoop)stmt;
            Assign  assign  = new Assign();
            assign.Ident = forLoop.Ident;
            assign.Expr  = forLoop.From;
            this.GenStmt(assign);
            // jump to the test
            Emit.Label test = this.il.DefineLabel();
            this.il.Emit(Emit.OpCodes.Br, test);

            // statements in the body of the for loop
            Emit.Label body = this.il.DefineLabel();
            this.il.MarkLabel(body);
            this.GenStmt(forLoop.Body);

            // to (increment the value of x)
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.il.Emit(Emit.OpCodes.Ldc_I4, 1);
            this.il.Emit(Emit.OpCodes.Add);
            this.Store(forLoop.Ident, typeof(int));

            // **test** does x equal 100? (do the test)
            this.il.MarkLabel(test);
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.GenExpr(forLoop.To, typeof(int));
            this.il.Emit(Emit.OpCodes.Blt, body);
        }
        else
        {
            throw new System.Exception("don't know how to gen a " + stmt.GetType().Name);
        }
    }
示例#55
0
        public EvalDelegate CreateDelegate()
        {
            var type = module.Find(evalClassName, isReflectionName: true);

            Debug.Assert(type != null);
            var method = type?.FindMethod(evalMethodName);

            Debug.Assert(method?.Body != null);
            if (!(method?.Body is CilBody body))
            {
                return(null);
            }
            if (method.ReturnType.ElementType != ElementType.Boolean)
            {
                return(null);
            }
            if (body.HasExceptionHandlers)
            {
                return(null);
            }

            Debug.Assert(method.MethodSig.Params.Count == evalDelegateParamTypes.Length);
            if (method.MethodSig.Params.Count != evalDelegateParamTypes.Length)
            {
                return(null);
            }
            var dm  = new SRE.DynamicMethod("compiled filter expr", typeof(bool), evalDelegateParamTypes, typeof(FilterExpressionMethods), skipVisibility: false);
            var ilg = dm.GetILGenerator();

            var labelsDict = new Dictionary <Instruction, SRE.Label>();
            var instrs     = body.Instructions;

            for (int i = 0; i < instrs.Count; i++)
            {
                var instr = instrs[i];
                switch (instr.Operand)
                {
                case Instruction targetInstr:
                    if (!labelsDict.ContainsKey(targetInstr))
                    {
                        labelsDict.Add(targetInstr, ilg.DefineLabel());
                    }
                    break;

                case IList <Instruction> targetInstrs:
                    foreach (var targetInstr in targetInstrs)
                    {
                        if (!labelsDict.ContainsKey(targetInstr))
                        {
                            labelsDict.Add(targetInstr, ilg.DefineLabel());
                        }
                    }
                    break;
                }
            }

            Dictionary <Local, SRE.LocalBuilder> localsDict = null;

            if (body.Variables.Count > 0)
            {
                localsDict = new Dictionary <Local, SRE.LocalBuilder>(body.Variables.Count);
                foreach (var local in body.Variables)
                {
                    var lb = ilg.DeclareLocal(Import(local.Type), local.Type.IsPinned);
                    if (local.Index != lb.LocalIndex)
                    {
                        return(null);
                    }
                    if (local.Name != null)
                    {
                        lb.SetLocalSymInfo(local.Name);
                    }
                    localsDict.Add(local, lb);
                }
            }

            foreach (var instr in body.Instructions)
            {
                if (labelsDict.TryGetValue(instr, out var label))
                {
                    ilg.MarkLabel(label);
                }
                if (!toReflectionOpCode.TryGetValue(instr.OpCode, out var sreOpCode))
                {
                    return(null);
                }
                switch (instr.OpCode.OperandType)
                {
                case OperandType.InlineBrTarget:
                case OperandType.ShortInlineBrTarget:
                    var targetInstr = (Instruction)instr.Operand;
                    ilg.Emit(sreOpCode, labelsDict[targetInstr]);
                    break;

                case OperandType.InlineSwitch:
                    var targets    = (IList <Instruction>)instr.Operand;
                    var newTargets = new SRE.Label[targets.Count];
                    for (int i = 0; i < newTargets.Length; i++)
                    {
                        newTargets[i] = labelsDict[targets[i]];
                    }
                    ilg.Emit(sreOpCode, newTargets);
                    break;

                case OperandType.InlineNone:
                    ilg.Emit(sreOpCode);
                    break;

                case OperandType.InlineI:
                    ilg.Emit(sreOpCode, (int)instr.Operand);
                    break;

                case OperandType.InlineI8:
                    ilg.Emit(sreOpCode, (long)instr.Operand);
                    break;

                case OperandType.InlineR:
                    ilg.Emit(sreOpCode, (double)instr.Operand);
                    break;

                case OperandType.ShortInlineR:
                    ilg.Emit(sreOpCode, (float)instr.Operand);
                    break;

                case OperandType.ShortInlineI:
                    if (instr.OpCode.Code == Code.Ldc_I4_S)
                    {
                        ilg.Emit(sreOpCode, (sbyte)instr.Operand);
                    }
                    else
                    {
                        ilg.Emit(sreOpCode, (byte)instr.Operand);
                    }
                    break;

                case OperandType.InlineString:
                    ilg.Emit(sreOpCode, (string)instr.Operand);
                    break;

                case OperandType.InlineVar:
                case OperandType.ShortInlineVar:
                    Parameter p;
                    switch (instr.OpCode.Code)
                    {
                    case Code.Ldarg:
                    case Code.Ldarga:
                    case Code.Starg:
                        p = (Parameter)instr.Operand;
                        if (p.Index > ushort.MaxValue)
                        {
                            return(null);
                        }
                        ilg.Emit(sreOpCode, (short)p.Index);
                        break;

                    case Code.Ldarg_S:
                    case Code.Ldarga_S:
                    case Code.Starg_S:
                        p = (Parameter)instr.Operand;
                        if (p.Index > byte.MaxValue)
                        {
                            return(null);
                        }
                        ilg.Emit(sreOpCode, (byte)p.Index);
                        break;

                    case Code.Ldloc:
                    case Code.Ldloca:
                    case Code.Stloc:
                    case Code.Ldloc_S:
                    case Code.Ldloca_S:
                    case Code.Stloc_S:
                        ilg.Emit(sreOpCode, localsDict[(Local)instr.Operand]);
                        break;

                    default:
                        return(null);
                    }
                    break;

                case OperandType.InlineMethod:
                    var m = Import((IMethod)instr.Operand);
                    if (m is SR.ConstructorInfo ci)
                    {
                        ilg.Emit(sreOpCode, ci);
                    }
                    else
                    {
                        ilg.Emit(sreOpCode, (SR.MethodInfo)m);
                    }
                    break;

                case OperandType.InlineTok:
                case OperandType.InlineType:
                case OperandType.InlineField:
                case OperandType.InlinePhi:
                case OperandType.InlineSig:
                default:
                    return(null);
                }
            }

            return((EvalDelegate)dm.CreateDelegate(typeof(EvalDelegate)));
        }
示例#56
0
 public label_pair(ILGenerator gen)
 {
     l2 = gen.DefineLabel();
     l3 = gen.DefineLabel();
 }
 public virtual new void MarkLabel(Label loc)
 {
 }
示例#58
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 DeclareVar)
        {
            // declare a local
            DeclareVar declare = (DeclareVar)stmt;
            this.symbolTable[declare.Ident] = this.il.DeclareLocal(this.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)
        {
            Assign assign = (Assign)stmt;
            this.GenExpr(assign.Expr, this.TypeOfExpr(assign.Expr));
            this.Store(assign.Ident, this.TypeOfExpr(assign.Expr));
        }
        else if (stmt is Print)
        {
            // the "print" statement is an alias for System.Console.WriteLine.
            // it uses the string case
            this.GenExpr(((Print)stmt).Expr, typeof(string));
            this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
        }

        else if (stmt is ReadInt)
        {
            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(((ReadInt)stmt).Ident, typeof(int));
        }
        //*******************
        else if (stmt is mcIf)
        {
            mcIf mcif = (mcIf)stmt;
            //this.GenExpr(mcif.compExpr, typeof(int));
            Emit.Label Else   = this.il.DefineLabel();
            Emit.Label Then   = this.il.DefineLabel();
            Emit.Label Salida = this.il.DefineLabel();
            if (mcif.compExpr is CompExpr)
            {
                CompExpr compExpr = (CompExpr)mcif.compExpr;
                this.GenExpr(compExpr.Left, typeof(int));
                this.GenExpr(compExpr.Rigth, typeof(int));
                genCodComp(compExpr.Op, Then);
            }
            else
            {
                GenExpr(mcif.compExpr, typeof(string));
                this.il.Emit(Emit.OpCodes.Ldc_I4, 0);
                this.il.Emit(Emit.OpCodes.Bne_Un, Then);
            }
            if (mcif.Else != null)
            {
                this.il.Emit(Emit.OpCodes.Br, Else);
            }
            else
            {
                this.il.Emit(Emit.OpCodes.Br, Salida);
            }
            this.il.MarkLabel(Then);
            GenStmt(mcif.Then);
            this.il.Emit(Emit.OpCodes.Br, Salida);
            this.il.MarkLabel(Else);
            if (mcif.Else != null)
            {
                GenStmt(mcif.Else);
            }
            this.il.MarkLabel(Salida);
        }
        else if (stmt is WhileLoop)
        {
            WhileLoop  whileLoop = (WhileLoop)stmt;
            Emit.Label Body      = this.il.DefineLabel();
            Emit.Label Salida    = this.il.DefineLabel();
            Emit.Label Cond      = this.il.DefineLabel();
            this.il.MarkLabel(Cond);
            if (whileLoop.Cond is CompExpr)
            {
                CompExpr compExpr = (CompExpr)whileLoop.Cond;
                this.GenExpr(compExpr.Left, typeof(int));
                this.GenExpr(compExpr.Rigth, typeof(int));
                genCodComp(compExpr.Op, Body);
            }
            else
            {
                GenExpr(whileLoop.Cond, typeof(string));
                this.il.Emit(Emit.OpCodes.Ldc_I4, 0);
                this.il.Emit(Emit.OpCodes.Bne_Un, Body);
            }
            this.il.Emit(Emit.OpCodes.Br, Salida);
            this.il.MarkLabel(Body);
            GenStmt(whileLoop.Body);
            this.il.Emit(Emit.OpCodes.Br, Cond);
            this.il.MarkLabel(Salida);
        }
        //*******************
        else if (stmt is ForLoop)
        {
            // example:
            // for x = 0 to 100 do
            //   print "hello";
            // end;

            // x = 0
            ForLoop forLoop = (ForLoop)stmt;
            Assign  assign  = new Assign();
            assign.Ident = forLoop.Ident;
            assign.Expr  = forLoop.From;
            this.GenStmt(assign);
            // jump to the test
            Emit.Label test = this.il.DefineLabel();
            this.il.Emit(Emit.OpCodes.Br, test);

            // statements in the body of the for loop
            Emit.Label body = this.il.DefineLabel();
            this.il.MarkLabel(body);
            this.GenStmt(forLoop.Body);

            // to (increment the value of x)
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.il.Emit(Emit.OpCodes.Ldc_I4, 1);
            this.il.Emit(Emit.OpCodes.Add);
            this.Store(forLoop.Ident, typeof(int));

            // **test** does x equal 100? (do the test)
            this.il.MarkLabel(test);
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.GenExpr(forLoop.To, typeof(int));
            this.il.Emit(Emit.OpCodes.Blt, body);
        }
        else
        {
            throw new System.Exception("imposible generar: " + stmt.GetType().Name);
        }
    }
示例#59
0
 internal Label(int number, System.Reflection.Emit.Label ilabel)
 {
     Number = number;
     ILabel = ilabel;
 }
示例#60
0
        public static void ResolveBindings(List <Binding> Bindings)
        {
            if (Bindings == null)
            {
                return;
            }
            if (Bindings.Count == 0)
            {
                return;
            }
            //#if DEBUG_BINDING
            //			Debug.WriteLine ("Resolve Bindings => " + this.ToString ());
            //#endif
            //grouped bindings by Instance of Source
            Dictionary <object, List <Binding> > resolved = new Dictionary <object, List <Binding> > ();

            foreach (Binding b in Bindings)
            {
                if (b.Resolved)
                {
                    continue;
                }
                if (b.Source.Member.MemberType == MemberTypes.Event)
                {
                    if (b.Expression.StartsWith("{"))
                    {
                        CompilerServices.CompileEventSource(b);
                        continue;
                    }
                    if (!b.TryFindTarget())
                    {
                        continue;
                    }
                    //register handler for event
                    if (b.Target.Method == null)
                    {
                        Debug.WriteLine("\tError: Handler Method not found: " + b.ToString());
                        continue;
                    }
                    try {
                        MethodInfo addHandler = b.Source.Event.GetAddMethod();
                        Delegate   del        = Delegate.CreateDelegate(b.Source.Event.EventHandlerType, b.Target.Instance, b.Target.Method);
                        addHandler.Invoke(b.Source.Instance, new object [] { del });

#if DEBUG_BINDING
                        Debug.WriteLine("\tHandler binded => " + b.ToString());
#endif
                        b.Resolved = true;
                    } catch (Exception ex) {
                        Debug.WriteLine("\tERROR: " + ex.ToString());
                    }
                    continue;
                }

                if (!b.TryFindTarget())
                {
                    continue;
                }

                //group Bindings by target instanceq
                List <Binding> bindings = null;
                if (!resolved.TryGetValue(b.Target.Instance, out bindings))
                {
                    bindings = new List <Binding> ();
                    resolved [b.Target.Instance] = bindings;
                }
                bindings.Add(b);
                b.Resolved = true;
            }

            MethodInfo stringEquals = typeof(string).GetMethod
                                          ("Equals", new Type [3] {
                typeof(string), typeof(string), typeof(StringComparison)
            });
            Type             target_Type     = Bindings [0].Source.Instance.GetType();
            EventInfo        ei              = typeof(IValueChange).GetEvent("ValueChanged");
            MethodInfo       evtInvoke       = ei.EventHandlerType.GetMethod("Invoke");
            ParameterInfo [] evtParams       = evtInvoke.GetParameters();
            Type             handlerArgsType = evtParams [1].ParameterType;
            Type []          args            = { typeof(object), typeof(object), handlerArgsType };
            FieldInfo        fiNewValue      = typeof(ValueChangeEventArgs).GetField("NewValue");
            FieldInfo        fiMbName        = typeof(ValueChangeEventArgs).GetField("MemberName");

            //group;only one dynMethods by target (valuechanged event source)
            //changed value name tested in switch
            //IEnumerable<Binding[]> groupedByTarget = resolved.GroupBy (g => g.Target.Instance, g => g, (k, g) => g.ToArray ());
            foreach (List <Binding> grouped in resolved.Values)
            {
                int  i           = 0;
                Type source_Type = grouped [0].Target.Instance.GetType();

                DynamicMethod dm = null;
                ILGenerator   il = null;

                System.Reflection.Emit.Label [] jumpTable = null;
                System.Reflection.Emit.Label    endMethod = new System.Reflection.Emit.Label();

                #region Retrieve EventHandler parameter type
                //EventInfo ei = targetType.GetEvent ("ValueChanged");
                //no dynamic update if ValueChanged interface is not implemented
                if (source_Type.GetInterfaces().Contains(typeof(IValueChange)))
                {
                    dm = new DynamicMethod(grouped [0].CreateNewDynMethodId(),
                                           MethodAttributes.Family | MethodAttributes.FamANDAssem | MethodAttributes.NewSlot,
                                           CallingConventions.Standard,
                                           typeof(void),
                                           args,
                                           target_Type, true);

                    il = dm.GetILGenerator(256);

                    endMethod = il.DefineLabel();
                    jumpTable = new System.Reflection.Emit.Label [grouped.Count];
                    for (i = 0; i < grouped.Count; i++)
                    {
                        jumpTable [i] = il.DefineLabel();
                    }
                    il.DeclareLocal(typeof(string));
                    il.DeclareLocal(typeof(object));

                    il.Emit(OpCodes.Nop);
                    il.Emit(OpCodes.Ldarg_0);
                    //il.Emit(OpCodes.Isinst, sourceType);
                    //push new value onto stack
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Ldfld, fiNewValue);
                    il.Emit(OpCodes.Stloc_1);
                    //push name
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Ldfld, fiMbName);
                    il.Emit(OpCodes.Stloc_0);
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Brfalse, endMethod);
                }
                #endregion

                i = 0;
                foreach (Binding b in grouped)
                {
                    #region initialize target with actual value
                    object targetValue = null;
                    if (b.Target.Member != null)
                    {
                        if (b.Target.Member.MemberType == MemberTypes.Property)
                        {
                            targetValue = b.Target.Property.GetGetMethod().Invoke(b.Target.Instance, null);
                        }
                        else if (b.Target.Member.MemberType == MemberTypes.Field)
                        {
                            targetValue = b.Target.Field.GetValue(b.Target.Instance);
                        }
                        else if (b.Target.Member.MemberType == MemberTypes.Method)
                        {
                            MethodInfo mthSrc = b.Target.Method;
                            if (mthSrc.IsDefined(typeof(ExtensionAttribute), false))
                            {
                                targetValue = mthSrc.Invoke(null, new object [] { b.Target.Instance });
                            }
                            else
                            {
                                targetValue = mthSrc.Invoke(b.Target.Instance, null);
                            }
                        }
                        else
                        {
                            throw new Exception("unandled source member type for binding");
                        }
                    }
                    else if (string.IsNullOrEmpty(b.Expression))
                    {
                        targetValue = grouped [0].Target.Instance;                        //empty binding exp=> bound to target object by default
                    }
                    //TODO: handle other dest type conversions
                    if (b.Source.Property.PropertyType == typeof(string))
                    {
                        if (targetValue == null)
                        {
                            //set default value
                        }
                        else
                        {
                            targetValue = targetValue.ToString();
                        }
                    }
                    try {
                        if (targetValue != null)
                        {
                            b.Source.Property.GetSetMethod().Invoke
                                (b.Source.Instance, new object [] { b.Source.Property.PropertyType.Cast(targetValue) });
                        }
                        else
                        {
                            b.Source.Property.GetSetMethod().Invoke
                                (b.Source.Instance, new object [] { targetValue });
                        }
                    } catch (Exception ex) {
                        Debug.WriteLine(ex.ToString());
                    }
                    #endregion

                    //if no dyn update, skip jump table
                    if (il == null)
                    {
                        continue;
                    }

                    il.Emit(OpCodes.Ldloc_0);
                    if (b.Target.Member != null)
                    {
                        il.Emit(OpCodes.Ldstr, b.Target.Member.Name);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldstr, b.Expression.Split('/').LastOrDefault());
                    }
                    il.Emit(OpCodes.Ldc_I4_4);                     //StringComparison.Ordinal
                    il.Emit(OpCodes.Callvirt, stringEquals);
                    il.Emit(OpCodes.Brtrue, jumpTable [i]);
                    i++;
                }

                if (il == null)
                {
                    continue;
                }

                il.Emit(OpCodes.Br, endMethod);

                i = 0;
                foreach (Binding b in grouped)
                {
                    il.MarkLabel(jumpTable [i]);


                    //load 2 times to check first for null
                    il.Emit(OpCodes.Ldloc_1);
                    il.Emit(OpCodes.Ldloc_1);

                    System.Reflection.Emit.Label labSetValue = il.DefineLabel();
                    il.Emit(OpCodes.Brtrue, labSetValue);
                    //if null
                    il.Emit(OpCodes.Unbox_Any, b.Source.Property.PropertyType);
                    il.Emit(OpCodes.Callvirt, b.Source.Property.GetSetMethod());
                    il.Emit(OpCodes.Br, endMethod);

                    il.MarkLabel(labSetValue);
                    //new value not null

                    //by default, source value type is deducted from target member type to allow
                    //memberless binding, if targetMember exists, it will be used to determine target
                    //value type for conversion
                    Type sourceValueType = b.Source.Property.PropertyType;
                    if (b.Target.Member != null)
                    {
                        if (b.Target.Member.MemberType == MemberTypes.Property)
                        {
                            sourceValueType = b.Target.Property.PropertyType;
                        }
                        else if (b.Target.Member.MemberType == MemberTypes.Field)
                        {
                            sourceValueType = b.Target.Field.FieldType;
                        }
                        else
                        {
                            throw new Exception("unhandle target member type in binding");
                        }
                    }



                    if (b.Source.Property.PropertyType == typeof(string))
                    {
                        MemberReference tostring = new MemberReference(b.Source.Instance);
                        if (!tostring.TryFindMember("ToString"))
                        {
                            throw new Exception("ToString method not found");
                        }
                        il.Emit(OpCodes.Callvirt, tostring.Method);
                    }
                    else if (!sourceValueType.IsValueType)
                    {
                        il.Emit(OpCodes.Castclass, sourceValueType);
                    }
                    else if (b.Source.Property.PropertyType != sourceValueType)
                    {
                        il.Emit(OpCodes.Callvirt, CompilerServices.GetConvertMethod(b.Source.Property.PropertyType));
                    }
                    else
                    {
                        il.Emit(OpCodes.Unbox_Any, b.Source.Property.PropertyType);
                    }

                    il.Emit(OpCodes.Callvirt, b.Source.Property.GetSetMethod());

                    //il.BeginCatchBlock (typeof (Exception));
                    //il.Emit (OpCodes.Pop);
                    //il.EndExceptionBlock ();

                    il.Emit(OpCodes.Br, endMethod);
                    i++;
                }
                il.MarkLabel(endMethod);
                il.Emit(OpCodes.Pop);
                il.Emit(OpCodes.Ret);

                Delegate   del        = dm.CreateDelegate(ei.EventHandlerType, Bindings [0].Source.Instance);
                MethodInfo addHandler = ei.GetAddMethod();
                addHandler.Invoke(grouped [0].Target.Instance, new object [] { del });
            }
        }