public void EmitIL(ILGenerator body, FieldInfo tape, FieldInfo ptr) { body.Emit(OpCodes.Ldsfld, ptr); body.Emit(OpCodes.Ldc_I4_1); body.Emit(OpCodes.Sub); body.Emit(OpCodes.Stsfld, ptr); }
public override void GenCode(TypeBuilder tb, MethodBuilder mb, ILGenerator cg) { Type type = Type.EmptyTypes.GetType(); for (int i = 0; i < Compiler.Types.Count; i++) if (Compiler.Types[i].name == Expr.ReturnType.Name) type = Compiler.SearchType(Compiler.Types[i].typeArray); if (assign) { assign = false; LocalBuilder local = cg.DeclareLocal(type); cg.Emit(OpCodes.Stloc, local); Expr.GenCode(tb, mb, cg);//pone el array, luego el index y luego el valor para hacer stelem Index.GenCode(tb, mb, cg); cg.Emit(OpCodes.Ldloc, local); cg.Emit(OpCodes.Stelem, type); } else { Expr.GenCode(tb, mb, cg); Index.GenCode(tb, mb, cg); cg.Emit(OpCodes.Ldelem, type); } }
public void Emit(ILGenerator il) { for (var i = 0; i < _arguments.Length; i++) { _arguments[i].Emit(il); } if (_method.IsStatic) { il.Emit(OpCodes.Call, _method); } else if (_method.IsVirtual) { il.Emit(OpCodes.Callvirt, _method); } else { il.Emit(OpCodes.Call, _method); } if (_method.ReturnType.IsValueType) { il.Emit(OpCodes.Unbox_Any, _method.ReturnType); } else if (_method.ReturnType != typeof(object)) { il.Emit(OpCodes.Castclass, _method.ReturnType); } }
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); }
/// <summary> /// ConvertTopArgType 发射类型转换的代码,将堆栈顶部的参数转换为目标类型。 /// </summary> public static void ConvertTopArgType(ILGenerator ilGenerator, Type source, Type dest) { if (!dest.IsAssignableFrom(source)) { if (dest.IsClass) { if (source.IsValueType) { ilGenerator.Emit(OpCodes.Box, dest); } else { ilGenerator.Emit(OpCodes.Castclass, dest); } } else { if (source.IsValueType) { ilGenerator.Emit(OpCodes.Castclass, dest); } else { ilGenerator.Emit(OpCodes.Unbox_Any, dest); } } } }
public void Emit(ILGenerator il) { switch (_index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: il.Emit(OpCodes.Ldarg_S, _index); break; } }
public override void Emit(ILGenerator il, int amount = 1) { il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldc_I4, amount); il.Emit(OpCodes.Sub); il.Emit(OpCodes.Stloc_0); }
/// <summary> /// Emit a call to get the value. /// </summary> /// <param name="il">The IL generator to use.</param> public void EmitGetValue(ILGenerator il) { if (FieldInfo != null) il.Emit(OpCodes.Ldfld, FieldInfo); else il.Emit(OpCodes.Callvirt, MethodInfo); }
private void EmitInvokerBody (ILGenerator generator, MethodInfo methodInfo, Type returnType, Type nativeReturnType, Type[] parameterTypes, Type[] nativeParameterTypes) { bool isNotVoid = (returnType != typeof(void)); // Creates local variables for by-ref parameters ByRefParameter[] byRefLocalVariables = CreateLocalVariableForByRefParameters (generator, methodInfo.GetParameters ()); bool hasByRef = byRefLocalVariables.Any (p => p.LocalBuilder != null && !p.IsOut); // To store result before return LocalBuilder result = (isNotVoid && hasByRef) ? CreateLocalBuilderForInvocationResult(generator, returnType, nativeReturnType) : null; // For by-ref parameters passed as reference (without [out] attribute), we first set the value of local variables this.EmitNativeToManagedMarshallingForByRefParameters (generator, nativeParameterTypes, byRefLocalVariables); // Loads the parameters on the stack. // - For regular parameter, values are directly loaded on the stack // - For by-ref parameters, local variables are loaded instead. EmitParametersLoadingOnStack (generator, parameterTypes, nativeParameterTypes, byRefLocalVariables, 2); // Make the call with the delegate generator.Emit (OpCodes.Call, methodInfo); // Unwrap result if needed if (isNotVoid) { UnwrapResultOfInvocation(generator, result, returnType, nativeReturnType, hasByRef); } // Marshal by-ref local variables to their corresponding parameters this.EmitManagedToNativeMarshallingForByRefParameters (generator, nativeParameterTypes, byRefLocalVariables); if (isNotVoid && hasByRef) { // Load the result on the stack generator.Emit (OpCodes.Ldloc, result); } }
/// <summary> /// 二項演算のコンパイル /// </summary> /// <param name="ilgen">IL Generator</param> /// <param name="expr">二項演算</param> static void CompileBinOpExpr(ILGenerator ilgen, MBinOpExpr expr) { CompileExpr(ilgen, expr.Lhs); CompileExpr(ilgen, expr.Rhs); switch (expr.OpType) { case BinOpType.Add: ilgen.Emit(OpCodes.Add); break; case BinOpType.Sub: ilgen.Emit(OpCodes.Sub); break; case BinOpType.Mul: ilgen.Emit(OpCodes.Mul); break; case BinOpType.Div: ilgen.Emit(OpCodes.Div); break; case BinOpType.Gt: CompileGtExpr(ilgen); break; case BinOpType.Eq: CompileEqExpr(ilgen); break; default: throw new NotImplementedException(); } }
public Generator(Statement stmt, string moduleName) { var path = Path.GetFileNameWithoutExtension(moduleName); var assemblyName = new AssemblyName(path); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save); var moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName); var typeBuilder = moduleBuilder.DefineType(moduleName); var methodBuilder = typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), Type.EmptyTypes); // CodeGenerator ilgenerator = methodBuilder.GetILGenerator(); symbolsTable = new Dictionary<string, LocalBuilder>(); // Go Compile! GenerateStatements(stmt); ilgenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadKey", BindingFlags.Public | BindingFlags.Static, null, new Type[] { }, null)); ilgenerator.Emit(OpCodes.Ret); typeBuilder.CreateType(); moduleBuilder.CreateGlobalFunctions(); assemblyBuilder.SetEntryPoint(methodBuilder); assemblyBuilder.Save(moduleName); symbolsTable = null; ilgenerator = null; }
/// <summary> /// Emits a load indirect opcode of the appropriate type for a value or object reference. /// Pops a pointer off the evaluation stack, dereferences it and loads /// a value of the specified type. /// </summary> /// <param name="gen"></param> /// <param name="type"></param> public static void EmitLoadIndirectOpCodeForType(ILGenerator gen, Type type) { if (type.IsEnum) { EmitLoadIndirectOpCodeForType(gen, GetUnderlyingTypeOfEnum(type)); return; } if (type.IsByRef) { throw new NotSupportedException("Cannot load ByRef values"); } else if (type.IsPrimitive) { OpCode opCode = LdindOpCodesDictionary.Instance[type]; if (Object.ReferenceEquals(opCode, LdindOpCodesDictionary.EmptyOpCode)) { throw new ArgumentException("Type " + type + " could not be converted to a OpCode"); } gen.Emit(opCode); } else if (type.IsValueType) { gen.Emit(OpCodes.Ldobj, type); } else { gen.Emit(OpCodes.Ldind_Ref); } }
public static void CreateDefaultMethodImplementation(MethodInfo methodInfo, ILGenerator il) { if (typeof (Task).IsAssignableFrom(methodInfo.ReturnType)) { if (methodInfo.ReturnType.IsTaskT()) { var taskType = methodInfo.ReturnType.GetTaskType(); il.EmitDefaultValue(taskType); var fromResult = taskFromResult.MakeGenericMethod(taskType); il.Emit(OpCodes.Call, fromResult); } else { il.Emit(OpCodes.Ldnull); var fromResult = taskFromResult.MakeGenericMethod(typeof (object)); il.Emit(OpCodes.Call, fromResult); } } else if (methodInfo.ReturnType != typeof (void)) { il.EmitDefaultValue(methodInfo.ReturnType); } // Return il.Emit(OpCodes.Ret); }
/// <summary> /// /// </summary> /// <param name="il"></param> /// <param name="paramAttr"></param> /// <param name="parameterType"></param> public override void EmitParameterResolution(ILGenerator il, ParameterAttribute paramAttr, Type parameterType) { ProviderDependencyAttribute attr = (ProviderDependencyAttribute) paramAttr; MethodInfo getHeadOfChain = GetPropertyGetter<IBuilderContext>("HeadOfChain", typeof (IBuilderStrategy)); MethodInfo buildUp = GetMethodInfo<IBuilderStrategy>("BuildUp", typeof (IBuilderContext), typeof (Type), typeof (object), typeof (string)); PropertyInfo prop = attr.ProviderHostType.GetProperty(attr.ProviderGetterProperty, BindingFlags.Static | BindingFlags.Public); if (prop == null) { throw new ArgumentException(); } MethodInfo propInvoker = prop.GetGetMethod(); if (propInvoker == null) { throw new ArgumentException(); } Guid.NewGuid(); MethodInfo newGuidMethod = typeof (Guid).GetMethod("NewGuid"); MethodInfo guidToStringMethod = typeof (Guid).GetMethod("ToString", new Type[] {}); if ((newGuidMethod == null) || (guidToStringMethod == null)) { throw new ArgumentException(); } //object value (declaration) LocalBuilder valueIndex = il.DeclareLocal(typeof (object)); //object value = prop.GetGetMethod().Invoke(attr.ProviderHostType, null); //value = propInvoker.Invoke(null) (return value remains in the stack) il.EmitCall(OpCodes.Call, propInvoker, null); il.Emit(OpCodes.Stloc, valueIndex); //string id = Guid.NewGuid().ToString(); //il.Emit(OpCodes.Ldtoken, typeof(Guid)); //il.EmitCall(OpCodes.Call, newGuidMethod, null); //il.EmitCall(OpCodes.Call, guidToStringMethod, null); //il.Emit(OpCodes.Stloc, idIndex); // Get the head of the context chain il.Emit(OpCodes.Ldarg_0); // Get context onto the stack il.EmitCall(OpCodes.Callvirt, getHeadOfChain, null); // Now head of chain is on the stack // Build up parameters to the BuildUp call - context, type, existing, id il.Emit(OpCodes.Ldarg_0); // Push context onto stack EmitLoadType(il, parameterType); // Existing object is value il.Emit(OpCodes.Ldloc, valueIndex); // And the id //il.Emit(OpCodes.Ldloc,idIndex); il.Emit(OpCodes.Ldarg_3); // Call buildup on head of the chain il.EmitCall(OpCodes.Callvirt, buildUp, null); }
protected override void EmitNullableCast(ILGenerator ilGenerator, Type nullableType) { ilGenerator.DeclareLocal(outputType); ilGenerator.Emit(OpCodes.Stloc_0); ilGenerator.Emit(OpCodes.Ldloca_S, 0); ilGenerator.Emit(OpCodes.Call, nullableType.GetProperty("Value").GetGetMethod()); }
public override void Emit(ILGenerator gen, bool labelSetAlready) { if (!labelSetAlready) MarkLabel(gen); MarkSequencePoint(gen); numericExpression.Emit(gen); gen.Emit(OpCodes.Call, typeof(BuiltIns).GetMethod("Round")); // We need to subtract one from the expression. OnGoto starts // counting at 1 and switch starts counting at 0. gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Sub); List<Label> destinations = new List<Label>(); foreach (string target in targets) { destinations.Add(labels[target]); } gen.Emit(OpCodes.Switch, destinations.ToArray()); // if the integer was larger than number of labels, then // switch falls thru to next statement. An On-Goto should // output BAD VALUE IN xx error. gen.Emit(OpCodes.Ldstr, line.Label); BuiltInsMethodCall.BadValueError().Emit(gen); }
public override void AppendRead(ILGenerator il, MessageField field) { il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldarg_1); field.AppendReadField(il); il.Emit(OpCodes.Call, property.GetSetMethod()); }
public override void LoadReference(ILGenerator gen) { if (Position == -1) { throw new ApplicationException("ArgumentReference unitialized"); } switch(Position) { case 0: gen.Emit(OpCodes.Ldarg_0); break; case 1: gen.Emit(OpCodes.Ldarg_1); break; case 2: gen.Emit(OpCodes.Ldarg_2); break; case 3: gen.Emit(OpCodes.Ldarg_3); break; default: gen.Emit(OpCodes.Ldarg, Position); break; } }
public override void Store(ILGenerator il) { if (field.IsStatic) il.Emit(OpCodes.Stsfld, field); else il.Emit(OpCodes.Stfld, field); }
public override void Load(ILGenerator il) { if (field.IsStatic) il.Emit(OpCodes.Ldsfld, field); else il.Emit(OpCodes.Ldfld, field); }
private void op_storeb(ILGenerator il) { MethodInfo setByteCheckedMI = typeof(ZMachine).GetMethod("SetByteChecked", BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo setByteMI = typeof(ZMachine).GetMethod("SetByte", BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo trapMemoryMI = typeof(ZMachine).GetMethod("TrapMemory", BindingFlags.NonPublic | BindingFlags.Instance); il.Emit(OpCodes.Ldarg_0); LoadOperand(il, 0); LoadOperand(il, 1); il.Emit(OpCodes.Add); il.Emit(OpCodes.Stloc, zm.TempWordLocal); il.Emit(OpCodes.Ldloc, zm.TempWordLocal); il.Emit(OpCodes.Conv_U2); LoadOperand(il, 2); MethodInfo impl = setByteCheckedMI; if (operandTypes[0] != OperandType.Variable && operandTypes[1] != OperandType.Variable) { int address = (ushort)operandValues[0] + operandValues[1]; if (address > 64 && address < zm.RomStart) impl = setByteMI; } il.Emit(OpCodes.Call, impl); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldloc, zm.TempWordLocal); il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Call, trapMemoryMI); }
private void CompileMainClass(Node ActiveNode) { Emit.TypeBuilder _TypeBuilder = TypeTable[ActiveNode.Nodes[1].Value]; Emit.MethodBuilder MethBuilder = _TypeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); this.AssemblerGenerator = MethBuilder.GetILGenerator(); CurrentType = _TypeBuilder; OpenBlockVariables(); CreateCode(ActiveNode.Nodes[14]); CreateCode(ActiveNode.Nodes[15]); CloseBlockVariables(); // Отладочные команды AssemblerGenerator.Emit(Emit.OpCodes.Ldstr, "Programm was finished. Press Enter key to quit..."); AssemblerGenerator.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) })); AssemblerGenerator.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { }, null)); AssemblerGenerator.Emit(Emit.OpCodes.Pop); AssemblerGenerator.Emit(Emit.OpCodes.Ret); CreatedTypeTable[ActiveNode.Nodes[1].Value] = _TypeBuilder.CreateType(); ModBuilder.CreateGlobalFunctions(); AsmBuilder.SetEntryPoint(MethBuilder); }
private void GenerateILCode(ILGenerator gen) { if (target.Instructions == null) return; foreach (var inst in target.Instructions) { switch (inst.OpCode.Name) { case "ldarg": case "ldloc": case "stloc": case "ldc.i4": gen.Emit(inst.OpCode, inst.IntValue); break; case "ldc.r4": gen.Emit(inst.OpCode, (inst).FloatValue); break; case "ldstr": gen.Emit(inst.OpCode, inst.Value.ToString()); break; case "add": case "mul": case "div": case "sub": case "ret": gen.Emit(inst.OpCode); break; } } }
private static void EmitInitField(ILGenerator il, FieldBuilder fb, Type type) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); il.Emit(OpCodes.Stfld, fb); }
public override void Generate(ILGenerator generator, Symbols symbols) { //Save the previous variables var currentVariables = new List<string>(); foreach (var item in symbols.Variables) { currentVariables.Add(item.Key); generator.Emit(OpCodes.Ldsfld, symbols.Variables[item.Key]); } DeclarationBlock.Generate(generator, symbols); InstructionsBlock.Generate(generator, symbols); LocalBuilder returnValue = null; if (InstructionsBlock.ExpressionType.Type != TypesEnumeration.Void) { returnValue = generator.DeclareLocal(symbols.GetRealType(InstructionsBlock.ExpressionType.ILName)); generator.Emit(OpCodes.Stloc, returnValue); } currentVariables.Reverse(); //load in the variables it's previous values currentVariables.ForEach(x => generator.Emit(OpCodes.Stsfld, symbols.Variables[x])); if (InstructionsBlock.ExpressionType.Type != TypesEnumeration.Void) generator.Emit(OpCodes.Ldloc, returnValue); }
internal override void TranslateToILCall(ILGenerator il, Type rtype, ASTList argList, bool construct, bool brackets){ if (this.defaultMember != null && construct && brackets){ base.TranslateToILCall(il, rtype, argList, construct, brackets); return; } JSGlobalField gf = this.member as JSGlobalField; if (gf != null && gf.IsLiteral && argList.count == 1){ Type t = Convert.ToType((IReflect)gf.value); argList[0].TranslateToIL(il, t); Convert.Emit(this, il, t, rtype); return; } this.TranslateToILWithDupOfThisOb(il); argList.TranslateToIL(il, typeof(Object[])); if (construct) il.Emit(OpCodes.Ldc_I4_1); else il.Emit(OpCodes.Ldc_I4_0); if (brackets) il.Emit(OpCodes.Ldc_I4_1); else il.Emit(OpCodes.Ldc_I4_0); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.callValueMethod); Convert.Emit(this, il, Typeob.Object, rtype); }
public override LocalBuilder BuildArguments(ILGenerator ilGenerator) { LocalBuilder propertyLocalBuilder = null; FieldBuilder contractFieldBuilder = null; LocalBuilder aspectArgLocalBuilder = null; ConstructorInfo ctorInterceptionArgs = null; AbstractAspectPropertyArgsWeaver methodWeaver = null; propertyLocalBuilder = LocalBuilderRepository.Declare(() => { return ilGenerator.DeclareLocal(typeof(PropertyInfo)); }); ctorInterceptionArgs = ArgumentType.GetConstructors()[0]; aspectArgLocalBuilder = ilGenerator.DeclareLocal(ArgumentType); contractFieldBuilder = WeavingSettings.TypeDefinition.GetFieldBuilder(WeavingSettings.ContractType); methodWeaver = new AspectArgsGetPropertyWeaver(Member, propertyLocalBuilder, aspectWeavingSettings); methodWeaver.Weave(ilGenerator); ilGenerator.EmitLoadArg(0); ilGenerator.Emit(OpCodes.Ldfld, contractFieldBuilder); ilGenerator.EmitLoadLocal(propertyLocalBuilder); ilGenerator.Emit(OpCodes.Ldsfld, BindingsDependency); ilGenerator.Emit(OpCodes.Newobj, ctorInterceptionArgs); ilGenerator.EmitStoreLocal(aspectArgLocalBuilder); return aspectArgLocalBuilder; }
/// <summary>Generates IL that loads a Type on the stack.</summary> /// <param name="generator"><see cref="ILGenerator"/> to write to.</param> /// <param name="type"><see cref="Type"/> to load.</param> public static void GenerateLoadType(ILGenerator generator, Type type) { System.Data.Test.Astoria.TestUtil.CheckArgumentNotNull(generator, "generator"); System.Data.Test.Astoria.TestUtil.CheckArgumentNotNull(type, "type"); generator.Emit(OpCodes.Ldtoken, type); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); }
private static void EmitCastToReference(ILGenerator il, Type type) { if (type.IsValueType) il.Emit (OpCodes.Unbox_Any, type); else il.Emit (OpCodes.Castclass, type); }
public override void GenerateCode(ILGenerator generator, TypeBuilder typeBuilder) { // Declarando la etiqueta. Label end = generator.DefineLabel(); //Generamos el codigo de la izquierda Left.GenerateCode(generator, typeBuilder); //Devuelve '1' en la pila si el valor de Left es distinto de cero. CheckIfEqualToZero(generator); //Guardamos el resultado en una variable, por si se salta no perderlo var result = generator.DeclareLocal(typeof (int)); GetValueFromStack(generator, result); //Si fue igual a 1 (true), saltamos hacia el final generator.Emit(OpCodes.Brtrue, end); //Sino, Generamos el codigo de la derecha Right.GenerateCode(generator, typeBuilder); //Si llegamos aqui, entonces el resultado sera el del operador derecho (si es 1 => 1) CheckIfEqualToZero(generator); //Guardamos el resultado en la variable GetValueFromStack(generator, result); //Haciendo 'backpatch' generator.MarkLabel(end); //Guardamos el resultado en la pila generator.Emit(OpCodes.Ldloc, result); }
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); }
protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il) { var convention = config.Conventions.OfType <TransactionProxyConvention>().First(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, convention.TargetsField.Field); il.Emit(OpCodes.Ret); }
protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il) { var convention = config.Conventions.OfType <TransactionProxyConvention>().First(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Callvirt, convention.GetValueEntiresTypedMethod.Method, null); il.Emit(OpCodes.Ret); }
/// <summary> /// Emit return wrap (according to InternalType calling convention) /// </summary> private void EmitRetWrap(Type returnType) { if (returnType == typeof(void)) { EmitVoidValue(); } else { EmitWrap(returnType); } _g.Emit(OpCodes.Ret); }
protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il) { var convention = config.Conventions.OfType <TransactionProxyConvention>().First(); var method = typeof(ITransactionProxy <>).MakeGenericType(convention.ItemType).GetMethod("SetTargets"); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, typeof(IEnumerable <>).MakeGenericType(convention.ItemType)); il.EmitCall(OpCodes.Callvirt, method, null); il.Emit(OpCodes.Ret); }
/// <summary> /// Emit a reference to an arbitrary object. Note that the references "leak." /// </summary> public static int EmitGetReference <T>(this SRE.ILGenerator il, int id) { Type t = typeof(T); il.Emit(SRE.OpCodes.Ldc_I4, id); il.Emit(SRE.OpCodes.Call, _GetReference); if (t.IsValueType) { il.Emit(SRE.OpCodes.Unbox_Any, t); } return(id); }
public void Intercept(DynamicMember parent, System.Reflection.Emit.MethodBuilder builder, System.Reflection.Emit.ILGenerator generator, ref Label returnLabel) { var prop = parent as DynamicProperty; var hasMultipleValuesProperty = prop.DynamicTypeBuilder.DynamicMembers.OfType <DynamicProperty>().FirstOrDefault(p => p.MemberName == $"{prop.MemberName}_HasMultipleValues"); if (hasMultipleValuesProperty == null) { return; } generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4_0); generator.Emit(OpCodes.Call, hasMultipleValuesProperty.PropertySetMethod); generator.Emit(OpCodes.Nop); }
public CodeGen(Stmt stmt, string moduleName) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } Reflect.AssemblyName name = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName)); Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); Emit.TypeBuilder typeBuilder = modb.DefineType("Foo"); Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>(); // Go Compile! this.GenStmt(stmt); il.Emit(Emit.OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); this.symbolTable = null; this.il = null; }
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); }
public CodeGenerator(Expression pExpression, String pModuleName, ref LogHandler rLogHandler) { _symbolTable = new Dictionary <String, Emit.LocalBuilder>(); _assemblyName = new Reflect.AssemblyName(Path.GetFileNameWithoutExtension(pModuleName)); _statement = pExpression; //Init Assembly _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, Emit.AssemblyBuilderAccess.Save); _moduleBuilder = _assemblyBuilder.DefineDynamicModule(pModuleName); _typeBuilder = _moduleBuilder.DefineType("PascalCompilerType"); _methodBuilder = _typeBuilder.DefineMethod ( "Main", Reflect.MethodAttributes.Static, typeof(void), Type.EmptyTypes ); _ilGenerator = _methodBuilder.GetILGenerator(); //Actual Work GenerateStatement(_statement, null); _ilGenerator.Emit(Emit.OpCodes.Ret); //Finalizing Work _typeBuilder.CreateType(); _moduleBuilder.CreateGlobalFunctions(); _assemblyBuilder.SetEntryPoint(_methodBuilder); _assemblyBuilder.Save(pModuleName); }
/// <summary> /// Fill the DynamicMethod with a stub. /// </summary> public static SRE.DynamicMethod Stub(this SRE.DynamicMethod dm) { SRE.ILGenerator il = dm.GetILGenerator(); for (int i = 0; i < 32; i++) { // Prevent mono from inlining the DynamicMethod. il.Emit(SRE.OpCodes.Nop); } if (dm.ReturnType != typeof(void)) { il.DeclareLocal(dm.ReturnType); il.Emit(SRE.OpCodes.Ldloca_S, (sbyte)0); il.Emit(SRE.OpCodes.Initobj, dm.ReturnType); il.Emit(SRE.OpCodes.Ldloc_0); } il.Emit(SRE.OpCodes.Ret); return(dm); }
private static Func <IServiceFactory, IQuery <TResult>, Task <TResult> > CreateDelegate <TResult>(Type queryType) { // Define the signature of the dynamic method. var dynamicMethod = new System.Reflection.Emit.DynamicMethod("Sql", typeof(Task <TResult>), new[] { typeof(IServiceFactory), typeof(IQuery <TResult>) }); System.Reflection.Emit.ILGenerator generator = dynamicMethod.GetILGenerator(); // Create the closed generic query handler type. Type queryHandlerType = typeof(IQueryHandler <,>).MakeGenericType(queryType, typeof(TResult)); // Get the MethodInfo that represents the HandleAsync method. MethodInfo method = queryHandlerType.GetMethod("HandleAsync"); // Push the service factory onto the evaluation stack. generator.Emit(OpCodes.Ldarg_0); // Push the query handler type onto the evaluation stack. generator.Emit(OpCodes.Ldtoken, queryHandlerType); generator.Emit(OpCodes.Call, GetTypeFromHandleMethod); // Call the GetInstance method and push the query handler // instance onto the evaluation stack. generator.Emit(OpCodes.Callvirt, GetInstanceMethod); // Since the GetInstance method returns an object, // we need to cast it to the actual query handler type. generator.Emit(OpCodes.Castclass, queryHandlerType); // Push the query onto the evaluation stack. generator.Emit(OpCodes.Ldarg_1); // The query is passed in as an IQuery<TResult> instance // and we need to cast it to the actual query type. generator.Emit(OpCodes.Castclass, queryType); // Call the Sql method and push the Task<TResult> // onto the evaluation stack. generator.Emit(OpCodes.Callvirt, method); // Mark the end of the dynamic method. generator.Emit(OpCodes.Ret); var getQueryHandlerDelegate = dynamicMethod.CreateDelegate(typeof(Func <IServiceFactory, IQuery <TResult>, Task <TResult> >)); return((Func <IServiceFactory, IQuery <TResult>, Task <TResult> >)getQueryHandlerDelegate); }
private int GetSize(string target) { Type targetType = Type.GetType(target, false); if (targetType == null) { return(-1); } SRE.DynamicMethod dm = new SRE.DynamicMethod("", typeof(int), null); SRE.ILGenerator gen = dm.GetILGenerator(); gen.Emit(SRE.OpCodes.Sizeof, targetType); gen.Emit(SRE.OpCodes.Ret); SizeDM del = (SizeDM)dm.CreateDelegate(typeof(SizeDM)); return(del()); }
public override void generar(Emit.ILGenerator il) { if (!TinyCompiler.generador.GeneradorCodigo.TablaDireccionesSimbolos.ContainsKey(Nombre.Texto)) { throw new System.Exception("ERROR-0007 fallo en analisis semantico Variable no declarada encontrada durante generacion '" + Nombre.Texto + "'"); } else { il.Emit(Emit.OpCodes.Ldloc, TinyCompiler.generador.GeneradorCodigo.TablaDireccionesSimbolos[Nombre.Texto]); } }
public static Type BuildPropertyObject(System.Collections.Generic.IEnumerable <System.Collections.Generic.KeyValuePair <string, Type> > obj) { string nameOfDLL = "magic.dll"; string nameOfAssembly = "magic_Assembly"; string nameOfModule = "magic_Module"; string nameOfType = "magic_Type"; System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName { Name = nameOfAssembly }; System.Reflection.Emit.AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave); System.Reflection.Emit.ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(nameOfModule, nameOfDLL); System.Reflection.Emit.TypeBuilder typeBuilder = moduleBuilder.DefineType(nameOfType, System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class); foreach (var prop in obj) { string Name = prop.Key; Type DataType = prop.Value; System.Reflection.Emit.FieldBuilder field = typeBuilder.DefineField("_" + Name, DataType, System.Reflection.FieldAttributes.Private); System.Reflection.Emit.PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(Name, System.Reflection.PropertyAttributes.SpecialName, DataType, null); System.Reflection.MethodAttributes methodAttributes = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName; System.Reflection.Emit.MethodBuilder methodBuilderGetter = typeBuilder.DefineMethod("get_" + Name, methodAttributes, DataType, new Type[] { }); System.Reflection.Emit.MethodBuilder methodBuilderSetter = typeBuilder.DefineMethod("set_" + Name, methodAttributes, typeof(void), new Type[] { DataType }); System.Reflection.Emit.ILGenerator ilGeneratorGetter = methodBuilderGetter.GetILGenerator(); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldfld, field); ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ret); System.Reflection.Emit.ILGenerator ilGeneratorSetter = methodBuilderSetter.GetILGenerator(); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_1); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Stfld, field); ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ret); propertyBuilder.SetGetMethod(methodBuilderGetter); propertyBuilder.SetSetMethod(methodBuilderSetter); } // Yes! you must do this, it should not be needed but it is! Type dynamicType = typeBuilder.CreateType(); // Save to file assemblyBuilder.Save(nameOfDLL); return(dynamicType); }
private void CompileMethodDecl(Node ActiveNode) { OpenBlockVariables(); OpenParametersBlock(); // Разбираем список переменных CreateCode(ActiveNode.Nodes[4]); // Создаём объявление метода Emit.MethodBuilder Method; if (FormalIds.Count == 0) { Method = CurrentType.DefineMethod(ActiveNode.Nodes[2].Value, Reflect.MethodAttributes.Public, TypeByTypeId(ActiveNode.Nodes[1]), System.Type.EmptyTypes); System.Type Tst = System.Type.GetType(ActiveNode.Nodes[1].Nodes[0].Value); } else { Collections.List <System.Type> FormalParameters = new Collections.List <System.Type>(); for (int i = 0; i < FormalIds.Count; i++) { FormalParameters.Add(TypeByTypeId(FormalTypes[i])); } Method = CurrentType.DefineMethod(ActiveNode.Nodes[2].Value, Reflect.MethodAttributes.Public, TypeByTypeId(ActiveNode.Nodes[1]), FormalParameters.ToArray()); } this.AssemblerGenerator = Method.GetILGenerator(); // Обнуляем список формальных параметров FormalTypes = new Collections.List <Node>(); FormalIds = new Collections.List <Node>(); // Вызываем разбор объявлений переменных CreateCode(ActiveNode.Nodes[7]); // Вызываем разбор тела метода CreateCode(ActiveNode.Nodes[8]); CreateCode(ActiveNode.Nodes[10]); // Завершаем метод AssemblerGenerator.Emit(Emit.OpCodes.Ret); CloseBlockVariables(); CloseParametersBLock(); }
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); }
public void TestCallingParentsMethod() { var c = new TestChild(); Assert.AreEqual("child", c.Test()); var m = typeof(TestChild).GetMethod("Test").GetBaseDefinition(); Assert.AreEqual(typeof(TestBase), m.DeclaringType); Assert.AreEqual(typeof(TestBase).GetMethod("Test"), m); Assert.AreEqual("child", m.Invoke(c, new object[0])); Assert.AreEqual("child", ((TestBase)c).Test()); var dm = new System.Reflection.Emit.DynamicMethod( "", typeof(string), new Type[] { typeof(TestBase) }, typeof(YamlNodeTest)); System.Reflection.Emit.ILGenerator ilgen = dm.GetILGenerator(); ilgen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0); ilgen.Emit(System.Reflection.Emit.OpCodes.Call, typeof(TestBase).GetMethod("Test")); ilgen.Emit(System.Reflection.Emit.OpCodes.Ret); var callTest = (Call)dm.CreateDelegate(typeof(Call)); Assert.AreEqual("base", callTest.Invoke(c)); }
private void inicializar(string nombreCodigoFuente, string nombrePrograma) { if (TablaDireccionesSimbolos.Count > 0) { throw new System.Exception("ERROR-0002: Tabla de direcciones de variables ha sido inicializada previamente"); } String rutaEjecutable = IO.Path.GetDirectoryName(nombrePrograma); //Describo el identificador unico del ensamblado que se esta generando nombre = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(nombrePrograma)); //Creo la representacion basica del ensamblado creado de forma dinamica (assembly) if (rutaEjecutable.Length > 0) { asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave, rutaEjecutable); } else { asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave); } Console.WriteLine("Common Runtime usado para generar el ejecutable del programa: " + asmb.ImageRuntimeVersion); Console.WriteLine("Se esta ejecutando el compilador bajo el CLR version {0}", Environment.Version); //Defino un nuevo modulo de .net de forma dinamica modb = asmb.DefineDynamicModule(IO.Path.GetFileName(nombrePrograma), false); //Creo una nueva clase en el Il Generator stream typeBuilder = modb.DefineType("pseudoGenerado"); //Debido a que los programas en este tiny solo cuentan con un unico metodo principal (Main) de forma estructurada //como un truco defino el metodo Main en un objeto por defecto para ejecutar todas las acciones //expresadas por el lenguaje alli. //formato: NOMBRE -> Main TIPO-> Static RETORNA-> void PARAMETROS-> vacios methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.HideBySig | Reflect.MethodAttributes.Static | Reflect.MethodAttributes.Public, typeof(void), System.Type.EmptyTypes); //Inicializo/Creo el generador/stream de codigo IL con el metodo donde generare el codigo actualmente this.il = methb.GetILGenerator(); //Para iniciar el programa Emito una primera instruccion vacia (no hace nada) il.Emit(Emit.OpCodes.Nop); }
//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"); } }
public override void Emit(IEasyMember member, System.Reflection.Emit.ILGenerator gen) { if (_reference != null) { ArgumentsUtil.EmitLoadOwnerAndReference(_reference, gen); } else if (_expression != null) { _expression.Emit(member, gen); } else { if (member.ReturnType != typeof(void)) { OpCodeUtil.EmitLoadOpCodeForDefaultValueOfType(gen, member.ReturnType); } } gen.Emit(OpCodes.Ret); }
protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il) { var convention = config.Conventions.OfType <TransactionProxyConvention>().First(); var listCtor = convention.TargetsField.MemberType.GetConstructor(new[] { typeof(IEnumerable <>).MakeGenericType(convention.ItemType) }); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Newobj, listCtor); il.Emit(OpCodes.Stfld, convention.TargetsField.Field); il.Emit(OpCodes.Ldarg_0); il.EmitCall(OpCodes.Callvirt, typeof(ICommitable).GetMethod("Rollback"), null); il.Emit(OpCodes.Ret); }
public void Compile(Program Program, string moduleName) { if (System.IO.Path.GetFileName(moduleName) != moduleName) { throw new Exception("can only output into current directory!"); } // Deal with arguments Type[] argTypes = new Type[Program.Variables.Length]; for (int i = 0; i < Program.Variables.Length; i++) { argTypes[i] = typeof(int); m_ArgTable.Add(Program.Variables[i].Name, i); } AssemblyName name = new AssemblyName(System.IO.Path.GetFileNameWithoutExtension(moduleName)); AssemblyBuilder asmb = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save); ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); TypeBuilder typeBuilder = modb.DefineType("Prog.Program", TypeAttributes.Public); MethodBuilder methb = typeBuilder.DefineMethod("Function", MethodAttributes.Static | MethodAttributes.Public, typeof(int), argTypes); for (int i = 0; i < Program.Variables.Length; i++) { methb.DefineParameter(i + 1, ParameterAttributes.HasDefault, Program.Variables[i].Name); } // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Dictionary <string, LocalBuilder>(); // Go Compile GenerateStatement(Program.TopNode); il.Emit(OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); this.symbolTable = null; this.il = null; }
public CodeGen(stmt stmt, string moduleName, int count) { if (IO.Path.GetFileName(moduleName) != moduleName) { throw new System.Exception("can only output into current directory!"); } stmts = stmt; Reflect.AssemblyName name = new Reflect.AssemblyName("FAJF"); //name of the assembly Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save); Emit.ModuleBuilder modb = asmb.DefineDynamicModule(moduleName); Emit.TypeBuilder typeBuilder = modb.DefineType("resister"); //name of the class Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); // CodeGenerator this.il = methb.GetILGenerator(); this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>(); counting = 0; counter = count; counters = 0; // Go Compile! this.GenStmt(stmt); il.Emit(Emit.OpCodes.Ret); typeBuilder.CreateType(); modb.CreateGlobalFunctions(); asmb.SetEntryPoint(methb); asmb.Save(moduleName); // this.il.EmitWriteLine("press any key to continue"); this.symbolTable = null; this.il = null; System.Diagnostics.Process.Start(moduleName); }
public CodeGenerator(Statement statement, string fileName) { string strFileName = Path.GetFileNameWithoutExtension(fileName); #region Define Assembly //AssemblyName _AssemblyName = new AssemblyName(Path.GetFileNameWithoutExtension(fileName)); AssemblyName _AssemblyName = new AssemblyName(strFileName); AppDomain currentDomain = AppDomain.CurrentDomain; AssemblyBuilder _AssemblyBuilder = currentDomain.DefineDynamicAssembly(_AssemblyName, AssemblyBuilderAccess.Save); #endregion #region Define Module ModuleBuilder _ModuleBuilder = _AssemblyBuilder.DefineDynamicModule(fileName); #endregion _typeBuilder = _ModuleBuilder.DefineType("CodeGenerator"); MethodBuilder _MethodBuilder = _typeBuilder.DefineMethod ("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes); _ILGenerator = _MethodBuilder.GetILGenerator(); tblIdentifier = new Dictionary <string, System.Reflection.Emit.LocalBuilder>(); tblArguments = new Dictionary <string, System.Reflection.Emit.LocalBuilder>(); // CIL generation GenerateStatement(statement); _ILGenerator.Emit(OpCodes.Ret); _typeBuilder.CreateType(); _ModuleBuilder.CreateGlobalFunctions(); _AssemblyBuilder.SetEntryPoint(_MethodBuilder); _AssemblyBuilder.Save(fileName); tblIdentifier = null; _ILGenerator = null; }
public override void Emit(IEasyMember member, System.Reflection.Emit.ILGenerator gen) { gen.Emit(OpCodes.Nop); }
public void GenerateStatement(Statement _statement) { if (_statement is StatementSequence) { StatementSequence _StatementSequence = (StatementSequence)_statement; GenerateStatement(_StatementSequence.Left); GenerateStatement(_StatementSequence.Right); } else if (_statement is DeclareVariable) { // declare a variable in symbol table DeclareVariable declare = (DeclareVariable)_statement; tblIdentifier[declare.Identifier] = _ILGenerator.DeclareLocal(GetExpressionType(declare.Expression)); // set the initial value Assignment assign = new Assignment(); assign.Identifier = declare.Identifier; assign.Expression = declare.Expression; GenerateStatement(assign); } else if (_statement is Assignment) { Assignment assign = (Assignment)_statement; GenerateExpression(assign.Expression, GetExpressionType(assign.Expression)); if (GetExpressionType(assign.Expression) == typeof(ArithmaticExpression)) { SaveIdentifier(assign.Identifier, typeof(Int32)); } else { SaveIdentifier(assign.Identifier, GetExpressionType(assign.Expression)); } } else if (_statement is DeclareFunction) { GenerateStatementMethod(_statement); } else if (_statement is Write) { // for print keyword, call .net method for printscreen GenerateExpression(((Write)_statement).Expression, typeof(string)); _ILGenerator.Emit(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) })); } else if (_statement is ReadInput) { // call the readline method and parse input method _ILGenerator.Emit(OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", BindingFlags.Public | BindingFlags.Static, null, new System.Type[] { }, null)); _ILGenerator.Emit(OpCodes.Call, typeof(int).GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null, new System.Type[] { typeof(string) }, null)); // store the input value in local builder SaveIdentifier(((ReadInput)_statement).Identifier, typeof(int)); } else if (_statement is IfThenElse) { //IfThenElse ifThenElse = (IfThenElse)stmt; //RelationalExpression relExpr = (RelationalExpression)ifThenElse.If; //// if, left side only //il.Emit(OpCodes.Stloc, symbolTable[relExpr.Left.ToString()]); //Label lblIf = il.DefineLabel(); //il.Emit(OpCodes.Br, lblIf); //// then //Label lblThen = il.DefineLabel(); //il.MarkLabel(lblThen); } else if (_statement is While) { While _while = (While)_statement; Label lblTest = _ILGenerator.DefineLabel(); Label lblEnd = _ILGenerator.DefineLabel(); if (_while.Operand == RelationalOperands.GreaterThan) { _ILGenerator.MarkLabel(lblTest); GenerateExpression(_while.LeftExpression, typeof(int)); GenerateExpression(_while.RightExpression, typeof(int)); _ILGenerator.Emit(OpCodes.Cgt); _ILGenerator.Emit(OpCodes.Brfalse, lblEnd); GenerateStatement(_while.Body); _ILGenerator.Emit(OpCodes.Br, lblTest); _ILGenerator.MarkLabel(lblEnd); } else if (_while.Operand == RelationalOperands.EqualTo) { _ILGenerator.MarkLabel(lblTest); GenerateExpression(_while.LeftExpression, typeof(int)); GenerateExpression(_while.RightExpression, typeof(int)); _ILGenerator.Emit(OpCodes.Ceq); _ILGenerator.Emit(OpCodes.Brfalse, lblEnd); GenerateStatement(_while.Body); _ILGenerator.Emit(OpCodes.Br, lblTest); _ILGenerator.MarkLabel(lblEnd); } else if (_while.Operand == RelationalOperands.LessThan) { _ILGenerator.MarkLabel(lblTest); GenerateExpression(_while.LeftExpression, typeof(int)); GenerateExpression(_while.RightExpression, typeof(int)); _ILGenerator.Emit(OpCodes.Clt); _ILGenerator.Emit(OpCodes.Brfalse, lblEnd); GenerateStatement(_while.Body); _ILGenerator.Emit(OpCodes.Br, lblTest); _ILGenerator.MarkLabel(lblEnd); } } else if (_statement is IfThen) { #region //////Label body = il.DefineLabel(); //////il.Emit(OpCodes.Ldc_I4, 1000); /* * // var x = 0; * // if x < 5 then * // print "less than 5"; * // endif; * * IfThen ifThen = (IfThen)stmt; * // jump to test * * * // **test** if x LessThan 5? (do the test) * il.MarkLabel(test); * GenExpr(ifThen.LeftExpression, typeof(int)); * */ //Label greaterThan = il.DefineLabel(); //IfThen ifThen = (IfThen)stmt; //GenExpr(ifThen.LeftExpression, typeof(int)); //GenExpr(ifThen.RightExpression, typeof(int)); //if (ifThen.Operand == RelationalOperands.GreaterThan) //{ // //} #endregion IfThen ifThen = (IfThen)_statement; Label lblElse = _ILGenerator.DefineLabel(); Label lblEnd = _ILGenerator.DefineLabel(); #region GreaterThan if (ifThen.Operand == RelationalOperands.GreaterThan) { GenerateExpression(ifThen.LeftExpression, typeof(int)); GenerateExpression(ifThen.RightExpression, typeof(int)); _ILGenerator.Emit(OpCodes.Cgt); _ILGenerator.Emit(OpCodes.Brfalse, lblElse); GenerateStatement(ifThen.ThenBody); _ILGenerator.Emit(OpCodes.Br, lblEnd); _ILGenerator.MarkLabel(lblElse); GenerateStatement(ifThen.ElseBody); _ILGenerator.MarkLabel(lblEnd); } #endregion #region EqualTo else if (ifThen.Operand == RelationalOperands.EqualTo) { GenerateExpression(ifThen.LeftExpression, typeof(int)); GenerateExpression(ifThen.RightExpression, typeof(int)); _ILGenerator.Emit(OpCodes.Ceq); _ILGenerator.Emit(OpCodes.Brfalse, lblElse); GenerateStatement(ifThen.ThenBody); _ILGenerator.Emit(OpCodes.Br, lblEnd); _ILGenerator.MarkLabel(lblElse); GenerateStatement(ifThen.ElseBody); _ILGenerator.MarkLabel(lblEnd); } #endregion #region LessThan else if (ifThen.Operand == RelationalOperands.LessThan) { GenerateExpression(ifThen.LeftExpression, typeof(int)); GenerateExpression(ifThen.RightExpression, typeof(int)); _ILGenerator.Emit(OpCodes.Clt); _ILGenerator.Emit(OpCodes.Brfalse, lblElse); GenerateStatement(ifThen.ThenBody); _ILGenerator.Emit(OpCodes.Br, lblEnd); _ILGenerator.MarkLabel(lblElse); GenerateStatement(ifThen.ElseBody); _ILGenerator.MarkLabel(lblEnd); } #endregion #region /* * Label gtTrue = il.DefineLabel(); * Label gtFalse = il.DefineLabel(); * * */ #endregion } else if (_statement is For) { // example: // for x = 0 to 100 do // print "hello"; // end; // x = 0 For forLoop = (For)_statement; Assignment assign = new Assignment(); assign.Identifier = forLoop.Identifier; assign.Expression = forLoop.From; GenerateStatement(assign); // jump to the test Label test = _ILGenerator.DefineLabel(); _ILGenerator.Emit(OpCodes.Br, test); // body statement Label body = _ILGenerator.DefineLabel(); _ILGenerator.MarkLabel(body); GenerateStatement(forLoop.Body); // increase x _ILGenerator.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]); _ILGenerator.Emit(OpCodes.Ldc_I4, 1); _ILGenerator.Emit(OpCodes.Add); SaveIdentifier(forLoop.Identifier, typeof(int)); // check if x is equal to 100 _ILGenerator.MarkLabel(test); _ILGenerator.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]); GenerateExpression(forLoop.To, typeof(int)); _ILGenerator.Emit(OpCodes.Blt, body); } else { ExceptionHandler("unable to generate " + _statement.GetType().Name); } }
public void GenerateStatementMethod(Statement _statement) { #region Statement if (_statement is StatementSequence) { StatementSequence _StatementSequence = (StatementSequence)_statement; GenerateStatementMethod(_StatementSequence.Left); GenerateStatementMethod(_StatementSequence.Right); } #endregion #region Declare Variable else if (_statement is DeclareVariable) { // declare a variable in symbol table DeclareVariable declare = (DeclareVariable)_statement; tblIdentifier[declare.Identifier] = _ILMethod.DeclareLocal(GetExpressionTypeMethod(declare.Expression)); // set the initial value Assignment assign = new Assignment(); assign.Identifier = declare.Identifier; assign.Expression = declare.Expression; GenerateStatementMethod(assign); } #endregion #region Assignment else if (_statement is Assignment) { Assignment assign = (Assignment)_statement; GenerateExpressionMethod(assign.Expression, GetExpressionTypeMethod(assign.Expression)); if (GetExpressionTypeMethod(assign.Expression) == typeof(ArithmaticExpression)) { SaveIdentifierMethod(assign.Identifier, typeof(Int32)); } else { SaveIdentifierMethod(assign.Identifier, GetExpressionTypeMethod(assign.Expression)); } } #endregion else if (_statement is DeclareFunction) { DeclareFunction _DeclareFunction = (DeclareFunction)_statement; string strFunctionName = _DeclareFunction.FunctionName; Type ParameterType1 = GetExpressionTypeMethod(_DeclareFunction.Parameter1.Expression); Type ParameterType2 = GetExpressionTypeMethod(_DeclareFunction.Parameter2.Expression); Type ParameterType3 = GetExpressionTypeMethod(_DeclareFunction.Parameter3.Expression); Type[] InputParameters = { ParameterType1, ParameterType2, ParameterType3 }; Type ReturnType = typeof(void); if (_DeclareFunction.ReturnType == "void") { ReturnType = typeof(void); } else if (_DeclareFunction.ReturnType == "string") { ReturnType = typeof(string); } else if (_DeclareFunction.ReturnType == "numeric") { ReturnType = typeof(int); } //FieldBuilder Parameter1 = _typeBuilder.DefineField(_DeclareFunction.Parameter1.Identifier, ParameterType1, FieldAttributes.Private); //FieldBuilder Parameter2 = _typeBuilder.DefineField(_DeclareFunction.Parameter2.Identifier, ParameterType2, FieldAttributes.Private); //FieldBuilder Parameter3 = _typeBuilder.DefineField(_DeclareFunction.Parameter3.Identifier, ParameterType3, FieldAttributes.Private); MethodBuilder NewMethod = _typeBuilder.DefineMethod (strFunctionName, MethodAttributes.Static, ReturnType, InputParameters); //ParameterBuilder poolRefBuilder = NewMethod.DefineParameter(1, ParameterAttributes.In, _DeclareFunction.Parameter1.Identifier); _ILMethod = NewMethod.GetILGenerator(); //tblArguments[_DeclareFunction.Parameter0.Identifier] = _ILMethod. tblArguments[_DeclareFunction.Parameter1.Identifier] = _ILMethod.DeclareLocal(ParameterType1); GenerateExpressionMethod(_DeclareFunction.Parameter1.Expression, ParameterType1); //_ILMethod.Emit(OpCodes.Starg, 0); tblArguments[_DeclareFunction.Parameter1.Identifier] = _ILMethod.DeclareLocal(ParameterType2); GenerateExpressionMethod(_DeclareFunction.Parameter1.Expression, ParameterType2); //_ILMethod.Emit(OpCodes.Starg, 1); tblArguments[_DeclareFunction.Parameter2.Identifier] = _ILMethod.DeclareLocal(ParameterType3); GenerateExpressionMethod(_DeclareFunction.Parameter2.Expression, ParameterType3); //_ILMethod.Emit(OpCodes.Starg, 2); //GenerateStatementMethod(_DeclareFunction.Body); //_ILMethod.Emit(OpCodes.Ret); } #region write-read else if (_statement is Write) { // for print keyword, call .net method for printscreen GenerateExpressionMethod(((Write)_statement).Expression, typeof(string)); _ILMethod.Emit(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) })); } else if (_statement is ReadInput) { // call the readline method and parse input method _ILMethod.Emit(OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", BindingFlags.Public | BindingFlags.Static, null, new System.Type[] { }, null)); _ILMethod.Emit(OpCodes.Call, typeof(int).GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null, new System.Type[] { typeof(string) }, null)); // store the input value in local builder SaveIdentifierMethod(((ReadInput)_statement).Identifier, typeof(int)); } #endregion #region While else if (_statement is While) { While _while = (While)_statement; Label lblTest = _ILMethod.DefineLabel(); Label lblEnd = _ILMethod.DefineLabel(); if (_while.Operand == RelationalOperands.GreaterThan) { _ILMethod.MarkLabel(lblTest); GenerateExpressionMethod(_while.LeftExpression, typeof(int)); GenerateExpressionMethod(_while.RightExpression, typeof(int)); _ILMethod.Emit(OpCodes.Cgt); _ILMethod.Emit(OpCodes.Brfalse, lblEnd); GenerateStatementMethod(_while.Body); _ILMethod.Emit(OpCodes.Br, lblTest); _ILMethod.MarkLabel(lblEnd); } else if (_while.Operand == RelationalOperands.EqualTo) { _ILMethod.MarkLabel(lblTest); GenerateExpressionMethod(_while.LeftExpression, typeof(int)); GenerateExpressionMethod(_while.RightExpression, typeof(int)); _ILMethod.Emit(OpCodes.Ceq); _ILMethod.Emit(OpCodes.Brfalse, lblEnd); GenerateStatementMethod(_while.Body); _ILMethod.Emit(OpCodes.Br, lblTest); _ILMethod.MarkLabel(lblEnd); } else if (_while.Operand == RelationalOperands.LessThan) { _ILMethod.MarkLabel(lblTest); GenerateExpressionMethod(_while.LeftExpression, typeof(int)); GenerateExpressionMethod(_while.RightExpression, typeof(int)); _ILMethod.Emit(OpCodes.Clt); _ILMethod.Emit(OpCodes.Brfalse, lblEnd); GenerateStatementMethod(_while.Body); _ILMethod.Emit(OpCodes.Br, lblTest); _ILMethod.MarkLabel(lblEnd); } } #endregion #region If-Then else if (_statement is IfThen) { IfThen ifThen = (IfThen)_statement; Label lblElse = _ILMethod.DefineLabel(); Label lblEnd = _ILMethod.DefineLabel(); #region GreaterThan if (ifThen.Operand == RelationalOperands.GreaterThan) { GenerateExpressionMethod(ifThen.LeftExpression, typeof(int)); GenerateExpressionMethod(ifThen.RightExpression, typeof(int)); _ILMethod.Emit(OpCodes.Cgt); _ILMethod.Emit(OpCodes.Brfalse, lblElse); GenerateStatementMethod(ifThen.ThenBody); _ILMethod.Emit(OpCodes.Br, lblEnd); _ILMethod.MarkLabel(lblElse); GenerateStatementMethod(ifThen.ElseBody); _ILMethod.MarkLabel(lblEnd); } #endregion #region EqualTo else if (ifThen.Operand == RelationalOperands.EqualTo) { GenerateExpressionMethod(ifThen.LeftExpression, typeof(int)); GenerateExpressionMethod(ifThen.RightExpression, typeof(int)); _ILMethod.Emit(OpCodes.Ceq); _ILMethod.Emit(OpCodes.Brfalse, lblElse); GenerateStatementMethod(ifThen.ThenBody); _ILMethod.Emit(OpCodes.Br, lblEnd); _ILMethod.MarkLabel(lblElse); GenerateStatementMethod(ifThen.ElseBody); _ILMethod.MarkLabel(lblEnd); } #endregion #region LessThan else if (ifThen.Operand == RelationalOperands.LessThan) { GenerateExpressionMethod(ifThen.LeftExpression, typeof(int)); GenerateExpressionMethod(ifThen.RightExpression, typeof(int)); _ILMethod.Emit(OpCodes.Clt); _ILMethod.Emit(OpCodes.Brfalse, lblElse); GenerateStatementMethod(ifThen.ThenBody); _ILMethod.Emit(OpCodes.Br, lblEnd); _ILMethod.MarkLabel(lblElse); GenerateStatementMethod(ifThen.ElseBody); _ILMethod.MarkLabel(lblEnd); } #endregion } #endregion #region for else if (_statement is For) { For forLoop = (For)_statement; Assignment assign = new Assignment(); assign.Identifier = forLoop.Identifier; assign.Expression = forLoop.From; GenerateStatementMethod(assign); Label test = _ILMethod.DefineLabel(); _ILMethod.Emit(OpCodes.Br, test); Label body = _ILMethod.DefineLabel(); _ILMethod.MarkLabel(body); GenerateStatementMethod(forLoop.Body); _ILMethod.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]); _ILMethod.Emit(OpCodes.Ldc_I4, 1); _ILMethod.Emit(OpCodes.Add); SaveIdentifierMethod(forLoop.Identifier, typeof(int)); _ILMethod.MarkLabel(test); _ILMethod.Emit(OpCodes.Ldloc, tblIdentifier[forLoop.Identifier]); GenerateExpressionMethod(forLoop.To, typeof(int)); _ILMethod.Emit(OpCodes.Blt, body); } #endregion else { ExceptionHandler("unable to generate " + _statement.GetType().Name); } }
public void Intercept(DynamicMember parent, System.Reflection.Emit.MethodBuilder builder, System.Reflection.Emit.ILGenerator generator, ref Label returnLabel) { var prop = parent as DynamicProperty; var originalReturn = returnLabel; bool valueType = false; var compareMethod = prop.MemberType.GetMethod("op_Equality", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); if (compareMethod == null) { compareMethod = typeof(object).GetMethod("Equals", BindingFlags.Static | BindingFlags.Public); valueType = true; } generator.Emit(OpCodes.Nop); generator.Emit(OpCodes.Ldarg_1); if (valueType) { generator.Emit(OpCodes.Box, prop.MemberType); } if (!prop.IsOverride) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, prop.BackingField); } else { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Call, prop.PropertyGetMethod); } if (valueType) { generator.Emit(OpCodes.Box, prop.MemberType); } var endlabel = generator.DefineLabel(); generator.Emit(OpCodes.Call, compareMethod); generator.Emit(OpCodes.Ldc_I4_0); generator.Emit(OpCodes.Ceq); generator.Emit(OpCodes.Brfalse_S, returnLabel); generator.Emit(OpCodes.Br_S, endlabel); returnLabel = generator.DefineLabel(); generator.MarkLabel(returnLabel); var raiseMethod = prop.DynamicTypeBuilder.DynamicMembers .OfType <RaisePropertyChangedMethod>() .Select(p => p.Method) .OfType <MethodInfo>() .FirstOrDefault(); if (raiseMethod == null) { raiseMethod = prop.DynamicTypeBuilder.BaseType.GetMethod("OnPropertyChanged", BindingFlags.NonPublic | BindingFlags.Instance); } if (raiseMethod == null) { #if (SILVERLIGHT) throw new MissingMemberException(string.Format("Missing Member {1} on type {0}", builder.DeclaringType.Name, "PropertyChanged")); #else throw new MissingMemberException(builder.DeclaringType.Name, "PropertyChanged"); #endif } generator.Emit(OpCodes.Nop); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldstr, prop.MemberName); generator.Emit(OpCodes.Callvirt, raiseMethod); generator.Emit(OpCodes.Br_S, originalReturn); generator.MarkLabel(endlabel); }
public override void Emit(IEasyMember member, System.Reflection.Emit.ILGenerator gen) { gen.Emit(OpCodes.Br_S, _label.Reference); }