public CilEmitter(string programName) { string exePath = String.Format("{0}/{1}.exe", Program.ExecutionDir, programName); this.exePath = exePath; AssemblyName assemblyName = new AssemblyName { Name = Path.GetFileNameWithoutExtension(exePath) }; string dir = Path.GetDirectoryName(exePath); string moduleName = Path.GetFileName(exePath); assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save, dir); ModuleBuilder moduleBuilder = assembly.DefineDynamicModule(assemblyName + "Module", moduleName, true); program = moduleBuilder.DefineType(moduleName, TypeAttributes.Class | TypeAttributes.Public); ConstructorBuilder cctor = program.DefineConstructor(MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); ilGeneratorConstructor = cctor.GetILGenerator(); ilGeneratorConstructor.BeginScope(); }
public void StartBlock(Scope Scope, Action <CILEmitter> ScopeCode) { generator.BeginScope(); CILEmitter next = new CILEmitter(generator, mainType, currentMethod, Scope, parameters, this); ScopeCode(next); generator.EndScope(); }
public void BeginScope() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Static); ILGenerator generator = method.GetILGenerator(); generator.BeginScope(); VerifyDeclareLocal(generator); }
public TypeBuilder InitGlobalScope() { globalScope = Module.DefineType("Global_Scope", TypeAttributes.Class | TypeAttributes.Public); cctor = globalScope.DefineConstructor(MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); il_cctor = cctor.GetILGenerator(); il_cctor.BeginScope(); return(globalScope); }
public TypeBuilder InitProgramClass(string programName) { program = module.DefineType(programName, TypeAttributes.Class | TypeAttributes.Public); cctor = program.DefineConstructor(MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); il_cctor = cctor.GetILGenerator(); il_cctor.BeginScope(); return(program); }
internal override void TranslateToIL(ILGenerator il, Type rtype) { //This assumes that rtype == Void.class this.context.EmitLineInfo(il); Globals.ScopeStack.Push(new WithObject(Globals.ScopeStack.Peek(), new JSObject(null, false))); bool savedInsideProtectedRegion = compilerGlobals.InsideProtectedRegion; compilerGlobals.InsideProtectedRegion = true; Label lab = il.DefineLabel(); compilerGlobals.BreakLabelStack.Push(lab); compilerGlobals.ContinueLabelStack.Push(lab); this.obj.TranslateToIL(il, Typeob.Object); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptWithMethod); // JScriptWith returns the with object as an 'Object' (used by the debugger EE) // define a local named 'with()' that the debugger EE will use to bind to the with object LocalBuilder withObj = null; if (context.document.debugOn) { il.BeginScope(); // used by the debugger to mark a with block withObj = il.DeclareLocal(Typeob.Object); withObj.SetLocalSymInfo("with()"); il.Emit(OpCodes.Stloc, withObj); } else { il.Emit(OpCodes.Pop); } il.BeginExceptionBlock(); this.block.TranslateToILInitializer(il); this.block.TranslateToIL(il, Typeob.Void); il.BeginFinallyBlock(); if (context.document.debugOn) { // null the local used by the debugger EE il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Stloc, withObj); } this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.popScriptObjectMethod); il.Emit(OpCodes.Pop); il.EndExceptionBlock(); if (context.document.debugOn) { il.EndScope(); // used by the debugger to mark a with block } il.MarkLabel(lab); compilerGlobals.BreakLabelStack.Pop(); compilerGlobals.ContinueLabelStack.Pop(); compilerGlobals.InsideProtectedRegion = savedInsideProtectedRegion; Globals.ScopeStack.Pop(); }
//translate statements public override AstNode VisitBlock(Block ast) { m_ilgen.BeginScope(); foreach (var s in ast.Statements) { Visit(s); } m_ilgen.EndScope(); return(ast); }
internal override void TranslateToIL(ILGenerator il, Type rtype) { base.context.EmitLineInfo(il); base.Globals.ScopeStack.Push(new WithObject(base.Globals.ScopeStack.Peek(), new JSObject(null, false))); bool insideProtectedRegion = base.compilerGlobals.InsideProtectedRegion; base.compilerGlobals.InsideProtectedRegion = true; Label item = il.DefineLabel(); base.compilerGlobals.BreakLabelStack.Push(item); base.compilerGlobals.ContinueLabelStack.Push(item); this.obj.TranslateToIL(il, Typeob.Object); base.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptWithMethod); LocalBuilder local = null; if (base.context.document.debugOn) { il.BeginScope(); local = il.DeclareLocal(Typeob.Object); local.SetLocalSymInfo("with()"); il.Emit(OpCodes.Stloc, local); } else { il.Emit(OpCodes.Pop); } il.BeginExceptionBlock(); this.block.TranslateToILInitializer(il); this.block.TranslateToIL(il, Typeob.Void); il.BeginFinallyBlock(); if (base.context.document.debugOn) { il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Stloc, local); } base.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.popScriptObjectMethod); il.Emit(OpCodes.Pop); il.EndExceptionBlock(); if (base.context.document.debugOn) { il.EndScope(); } il.MarkLabel(item); base.compilerGlobals.BreakLabelStack.Pop(); base.compilerGlobals.ContinueLabelStack.Pop(); base.compilerGlobals.InsideProtectedRegion = insideProtectedRegion; base.Globals.ScopeStack.Pop(); }
public void PosTest2() { MethodBuilder method = TestTypeBuilder.DefineMethod("PosTest2_Method", DefaultMethodAttribute); ILGenerator generator = method.GetILGenerator(); LocalBuilder arg = generator.DeclareLocal(typeof(ILGeneratorEmit2)); generator.Emit(OpCodes.Ldnull, arg); generator.BeginScope(); generator.Emit(OpCodes.Ldarg_0, arg); generator.Emit(OpCodes.Nop, arg); // Try emit opcode which takes multiple args generator.Emit(OpCodes.Add, arg); }
public void PosTest2() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic); MethodBuilder method = type.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static); ILGenerator generator = method.GetILGenerator(); LocalBuilder arg = generator.DeclareLocal(typeof(ILGeneratorEmit2)); generator.Emit(OpCodes.Ldnull, arg); generator.BeginScope(); generator.Emit(OpCodes.Ldarg_0, arg); generator.Emit(OpCodes.Nop, arg); // Try emit opcode which takes multiple args generator.Emit(OpCodes.Add, arg); }
public override void Compile(ILGenerator il) { SymbolTable.PushScope(); il.BeginScope(); EmitDebugInfo(il, 0, true); if (Options.Debug) { il.Emit(OpCodes.Nop); //To step correctly } if (Variables != null) { Variables.Compile(il); } Statements.Compile(il); il.EndScope(); SymbolTable.PopScope(); EmitDebugInfo(il, 1, true); }
public void PosTest2() { MethodBuilder method = TestTypeBuilder.DefineMethod("PosTest2_Method", DefaultMethodAttribute); ILGenerator generator = method.GetILGenerator(); generator.BeginScope(); int index = 0; VerificationHelper(generator, typeof(int), index++, "002.1"); VerificationHelper(generator, typeof(object), index++, "002.2"); VerificationHelper(generator, typeof(TestClassLocal1), index++, "002.3"); VerificationHelper(generator, typeof(TestStructLocal1), index++, "002.4"); VerificationHelper(generator, typeof(TestDelegateLocal1), index++, "002.5"); VerificationHelper(generator, typeof(TestEnumLocal1), index++, "002.6"); VerificationHelper(generator, typeof(TestExceptionLocal1), index++, "002.7"); VerificationHelper(generator, typeof(void), index++, "002.8"); }
public override void OpenScope() { ig.BeginScope(); }
/// <summary> /// Generate an assembly in IL that creates controls, and display in the panel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void generateButton_Click(object sender, System.EventArgs e) { // Create the assembly name AssemblyName assemName = new AssemblyName( ); assemName.Name = string.Format("MyControl{0}", DateTime.Now.Ticks); // Create the assembly builder object AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.RunAndSave); // Then create the module builder ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyAssembly.dll", "MyAssembly.dll"); // Get the base class for our new control Type baseClass = typeof(System.Windows.Forms.UserControl); Type controlClass = typeof(System.Windows.Forms.Control); Type labelClass = typeof(System.Windows.Forms.Label); // Construct the type TypeBuilder typeBuilder = moduleBuilder.DefineType("MyControls.MyControl", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.BeforeFieldInit, baseClass); // Create a private field for the label FieldBuilder labelField = typeBuilder.DefineField("_label", typeof(System.Windows.Forms.Label), FieldAttributes.Private); // Now generate the InitializeComponent method MethodBuilder initComponentBuilder = typeBuilder.DefineMethod("InitializeComponent", MethodAttributes.Private | MethodAttributes.HideBySig, CallingConventions.Standard, typeof(void), new System.Type[] { }); // Get an IL generator for the InitializeComponent method ILGenerator initIL = initComponentBuilder.GetILGenerator( ); // And write the method body initIL.BeginScope( ); // Construct the label initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Newobj, typeof(System.Windows.Forms.Label).GetConstructor(new Type[] { })); initIL.Emit(OpCodes.Stfld, labelField); // Then call Control.SuspendLayout initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Call, baseClass.GetMethod("SuspendLayout")); // Anchor the control to the top left right initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldc_I4_S, (int)(AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right)); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("Anchor", typeof(AnchorStyles)).GetSetMethod( )); // Set the border style of the control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldc_I4_2); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("BorderStyle", typeof(BorderStyle)).GetSetMethod()); // typeof(System.Windows.Forms.Label).GetProperty("BorderStyle",typeof(BorderStyle)).GetSetMethod ( ) ) ; // Set the top left of the label initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldc_I4_8); initIL.Emit(OpCodes.Ldc_I4_8); initIL.Emit(OpCodes.Newobj, typeof(System.Drawing.Point).GetConstructor(new Type[] { typeof(int), typeof(int) })); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("Location", typeof(System.Drawing.Point)).GetSetMethod( )); // Set the name of the control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldstr, "mainLabel"); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("Name", typeof(string)).GetSetMethod( )); // Set the size of the control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldc_I4, 312); initIL.Emit(OpCodes.Ldc_I4_S, 23); initIL.Emit(OpCodes.Newobj, typeof(Size).GetConstructor(new Type[] { typeof(int), typeof(int) })); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("Size", typeof(Size)).GetSetMethod( )); // Set the tab index of the label control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldc_I4_0); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("TabIndex", typeof(int)).GetSetMethod( )); // And set the text to that which the user typed in... initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Ldstr, messageText.Text); initIL.Emit(OpCodes.Callvirt, labelClass.GetProperty("Text", typeof(string)).GetSetMethod( )); // Now add the label to the controls on the user control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Call, controlClass.GetProperty("Controls").GetGetMethod( )); initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldfld, labelField); initIL.Emit(OpCodes.Callvirt, typeof(ControlCollection).GetMethod("Add")); // Now set the name of the main control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldstr, "MyControl"); initIL.Emit(OpCodes.Call, controlClass.GetProperty("Name").GetSetMethod( )); // Now emit the initial size of the control initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldc_I4, 328); initIL.Emit(OpCodes.Ldc_I4, 200); initIL.Emit(OpCodes.Newobj, typeof(Size).GetConstructor(new Type[] { typeof(int), typeof(int) })); initIL.Emit(OpCodes.Callvirt, controlClass.GetProperty("Size", typeof(Size)).GetSetMethod( )); // Call Control.ResumeLayout initIL.Emit(OpCodes.Ldarg_0); initIL.Emit(OpCodes.Ldc_I4_0); initIL.Emit(OpCodes.Call, baseClass.GetMethod("ResumeLayout", new Type[] { typeof(bool) })); // And emit the end of the function initIL.Emit(OpCodes.Ret); initIL.EndScope( ); MethodBuilder dummyBuilder = typeBuilder.DefineMethod("Dummy", MethodAttributes.Private | MethodAttributes.HideBySig, CallingConventions.Standard, typeof(void), new System.Type[] { }); // Get an IL generator ILGenerator dummyIL = dummyBuilder.GetILGenerator( ); dummyIL.BeginScope( ); LocalBuilder lb = dummyIL.DeclareLocal(typeof(Exception)); dummyIL.Emit(OpCodes.Ret); dummyIL.EndScope( ); // Then create the constructor which will call InitializeComponent ConstructorBuilder constructor = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.Standard, new System.Type[] { }); // Get an IL generator so I can write some code ILGenerator constructorIL = constructor.GetILGenerator( ); // Call the base class constructor and then InitializeComponent constructorIL.BeginScope( ); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Call, baseClass.GetConstructor(new Type[] { })); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Call, initComponentBuilder); constructorIL.Emit(OpCodes.Ret); constructorIL.EndScope( ); // Now write the type to the assembly Type newControl = typeBuilder.CreateType( ); assemblyBuilder.Save("MyAssembly.dll"); // And construct it and place it on screen! Control c = Activator.CreateInstance(newControl) as Control; c.Dock = DockStyle.Fill; controlPanel.SuspendLayout( ); controlPanel.Controls.Clear( ); controlPanel.Controls.Add(c); controlPanel.ResumeLayout( ); }
void EmitFunction(ILGenerator cil, Function f) { var document = ResolveDocument(f.Source.FullPath); if (!f.HasBody) { if (!f.IsAbstract && !_backend.IsPInvokable(_essentials, f)) { Log.Error(f.Source, ErrorCode.E0093, f.Quote() + " does not provide an implementation"); } return; } var bc = f.CreateBytecodeCompiler(); bc.Compile(); var bytecode = bc.Code; var locals = bc.Locals; var localBuilders = new LocalBuilder[locals.Count]; var labels = bc.Labels; var cilLabels = new Dictionary <API.Domain.Bytecode.Label, IKVM.Reflection.Emit.Label>(); foreach (var l in labels) { if (l.Offset != -1) { var x = cil.DefineLabel(); cilLabels.Add(l, x); } } // Create locals for (int i = 0; i < locals.Count; i++) { var t = _linker.GetType(locals[i].ValueType); var localBuilder = cil.DeclareLocal(t); localBuilder.SetLocalSymInfo(locals[i].Name); localBuilders[i] = localBuilder; } cil.BeginScope(); // Translate bytecode for (int i = 0; i < bytecode.Count; i++) { var b = bytecode[i]; switch (b.Opcode) { case Opcodes.Nop: break; case Opcodes.MarkSource: { var s = (Source)b.Argument; if (s.Line > 0) { var line = s.Line; var column = s.Column != 0 ? s.Column : 1; cil.MarkSequencePoint(document, line, column, s.EndLine != 0 ? s.EndLine : line, s.EndColumn != 0 ? s.EndColumn : column); AddLocation(cil.ILOffset, s.FullPath, s.Line, s.Column); } } break; case Opcodes.MarkLabel: { var label = b.Argument as API.Domain.Bytecode.Label; cil.MarkLabel(cilLabels[label]); } break; case Opcodes.Constrained: cil.Emit(OpCodes.Constrained, _linker.GetType((DataType)b.Argument)); break; case Opcodes.BeginExceptionBlock: cil.BeginExceptionBlock(); break; case Opcodes.EndExceptionBlock: cil.EndExceptionBlock(); break; case Opcodes.BeginCatchBlock: cil.BeginCatchBlock(_linker.GetType((DataType)b.Argument)); break; case Opcodes.BeginFinallyBlock: cil.BeginFinallyBlock(); break; case Opcodes.Null: cil.Emit(OpCodes.Ldnull); break; case Opcodes.NewObject: { var ctor = (Constructor)b.Argument; if (ctor.DeclaringType.IsGenericParameter) { cil.Emit(OpCodes.Call, _linker.System_Activator_CreateInstance.MakeGenericMethod(_linker.GetType(ctor.DeclaringType))); } else { cil.Emit(OpCodes.Newobj, _linker.GetConstructor((Constructor)b.Argument)); } } break; case Opcodes.NewArray: cil.Emit(OpCodes.Newarr, _linker.GetType((DataType)b.Argument)); break; case Opcodes.NewDelegate: cil.Emit(OpCodes.Newobj, _linker.GetDelegateConstructor((DelegateType)b.Argument)); break; case Opcodes.Box: cil.Emit(OpCodes.Box, _linker.GetType((DataType)b.Argument)); break; case Opcodes.Unbox: cil.Emit(OpCodes.Unbox, _linker.GetType((DataType)b.Argument)); break; case Opcodes.UnboxAny: cil.Emit(OpCodes.Unbox_Any, _linker.GetType((DataType)b.Argument)); break; case Opcodes.Constant: EmitConstant(cil, b.Argument); break; case Opcodes.DefaultInit: { var type = _linker.GetType((DataType)b.Argument); var temp = cil.DeclareLocal(type); EmitLoadLocal(cil, temp, true); cil.Emit(OpCodes.Initobj, type); EmitLoadLocal(cil, temp, false); } break; case Opcodes.TypeOf: { var type = _linker.GetType((DataType)b.Argument); cil.Emit(OpCodes.Ldtoken, type); cil.Emit(OpCodes.Call, _linker.System_Type_GetTypeFromHandle); } break; case Opcodes.This: cil.Emit(OpCodes.Ldarg_0); break; case Opcodes.Call: if (b.Argument is Constructor) { cil.Emit(OpCodes.Call, _linker.GetConstructor((Constructor)b.Argument)); } else { cil.Emit(OpCodes.Call, _linker.GetMethod((Function)b.Argument)); } break; case Opcodes.CallVirtual: cil.Emit(OpCodes.Callvirt, _linker.GetMethod((Function)b.Argument)); break; case Opcodes.CallDelegate: cil.Emit(OpCodes.Callvirt, _linker.GetDelegateInvokeMethod((DelegateType)b.Argument)); break; case Opcodes.Pop: cil.Emit(OpCodes.Pop); break; case Opcodes.Dup: cil.Emit(OpCodes.Dup); break; case Opcodes.LoadObj: cil.Emit(OpCodes.Ldobj, _linker.GetType((DataType)b.Argument)); break; case Opcodes.StoreObj: cil.Emit(OpCodes.Stobj, _linker.GetType((DataType)b.Argument)); break; case Opcodes.LoadFunction: cil.Emit(OpCodes.Ldftn, _linker.GetMethod((Function)b.Argument)); break; case Opcodes.LoadFunctionVirtual: cil.Emit(OpCodes.Ldvirtftn, _linker.GetMethod((Function)b.Argument)); break; case Opcodes.LoadArg: EmitLoadArgument(cil, f, (int)b.Argument, false); break; case Opcodes.LoadArgAddress: EmitLoadArgument(cil, f, (int)b.Argument, true); break; case Opcodes.StoreArg: { var argIndex = (int)b.Argument; if (!f.IsStatic) { argIndex++; } if (argIndex < 256) { cil.Emit(OpCodes.Starg_S, (byte)argIndex); } else { cil.Emit(OpCodes.Starg, (ushort)argIndex); } } break; case Opcodes.LoadLocal: EmitLoadLocal(cil, localBuilders[locals.IndexOf((Variable)b.Argument)], false); break; case Opcodes.LoadLocalAddress: EmitLoadLocal(cil, localBuilders[locals.IndexOf((Variable)b.Argument)], true); break; case Opcodes.StoreLocal: EmitStoreLocal(cil, localBuilders[locals.IndexOf((Variable)b.Argument)]); break; case Opcodes.LoadField: cil.Emit(OpCodes.Ldfld, _linker.GetField((Field)b.Argument)); break; case Opcodes.LoadFieldAddress: cil.Emit(OpCodes.Ldflda, _linker.GetField((Field)b.Argument)); break; case Opcodes.StoreField: cil.Emit(OpCodes.Stfld, _linker.GetField((Field)b.Argument)); break; case Opcodes.LoadStaticfield: cil.Emit(OpCodes.Ldsfld, _linker.GetField((Field)b.Argument)); break; case Opcodes.LoadStaticFieldAddress: cil.Emit(OpCodes.Ldsflda, _linker.GetField((Field)b.Argument)); break; case Opcodes.StoreStaticField: cil.Emit(OpCodes.Stsfld, _linker.GetField((Field)b.Argument)); break; case Opcodes.LoadArrayElement: case Opcodes.LoadArrayElementAddress: { bool addressMode = b.Opcode == Opcodes.LoadArrayElementAddress; var elmType = b.Argument as DataType; if (addressMode) { cil.Emit(OpCodes.Ldelema, _linker.GetType(elmType)); } else { switch (elmType.BuiltinType) { case BuiltinType.Long: cil.Emit(OpCodes.Ldelem_I8); break; case BuiltinType.ULong: cil.Emit(OpCodes.Ldelem_I8); break; // There is no U8 instruction case BuiltinType.Int: cil.Emit(OpCodes.Ldelem_I4); break; case BuiltinType.UInt: cil.Emit(OpCodes.Ldelem_U4); break; case BuiltinType.Short: cil.Emit(OpCodes.Ldelem_I2); break; case BuiltinType.UShort: cil.Emit(OpCodes.Ldelem_U2); break; case BuiltinType.Byte: cil.Emit(OpCodes.Ldelem_U1); break; case BuiltinType.SByte: cil.Emit(OpCodes.Ldelem_I1); break; case BuiltinType.Float: cil.Emit(OpCodes.Ldelem_R4); break; case BuiltinType.Double: cil.Emit(OpCodes.Ldelem_R8); break; default: if (!elmType.IsValueType && !elmType.IsGenericParameter) { cil.Emit(OpCodes.Ldelem_Ref); } else { cil.Emit(OpCodes.Ldelem, _linker.GetType(elmType)); } break; } } } break; case Opcodes.StoreArrayElement: { var elmType = b.Argument as DataType; switch (elmType.BuiltinType) { case BuiltinType.Long: case BuiltinType.ULong: cil.Emit(OpCodes.Stelem_I8); break; // There is no U8 instruction case BuiltinType.Int: case BuiltinType.UInt: cil.Emit(OpCodes.Stelem_I4); break; case BuiltinType.Short: case BuiltinType.UShort: cil.Emit(OpCodes.Stelem_I2); break; case BuiltinType.Byte: case BuiltinType.SByte: cil.Emit(OpCodes.Stelem_I1); break; case BuiltinType.Float: cil.Emit(OpCodes.Stelem_R4); break; case BuiltinType.Double: cil.Emit(OpCodes.Stelem_R8); break; default: if (elmType is ClassType || elmType is RefArrayType) { cil.Emit(OpCodes.Stelem_Ref); } else { cil.Emit(OpCodes.Stelem, _linker.GetType(elmType)); } break; } } break; case Opcodes.LoadArrayLength: cil.Emit(OpCodes.Ldlen); break; case Opcodes.ConvByte: cil.Emit(OpCodes.Conv_U1); break; case Opcodes.ConvSByte: cil.Emit(OpCodes.Conv_I1); break; case Opcodes.ConvChar: cil.Emit(OpCodes.Conv_U2); break; case Opcodes.ConvUShort: cil.Emit(OpCodes.Conv_U2); break; case Opcodes.ConvShort: cil.Emit(OpCodes.Conv_I2); break; case Opcodes.ConvUInt: cil.Emit(OpCodes.Conv_U4); break; case Opcodes.ConvInt: cil.Emit(OpCodes.Conv_I4); break; case Opcodes.ConvULong: cil.Emit(OpCodes.Conv_U8); break; case Opcodes.ConvLong: cil.Emit(OpCodes.Conv_I8); break; case Opcodes.ConvFloat: cil.Emit(OpCodes.Conv_R4); break; case Opcodes.ConvDouble: cil.Emit(OpCodes.Conv_R8); break; case Opcodes.AsClass: cil.Emit(OpCodes.Isinst, _linker.GetType(b.Argument as DataType)); break; case Opcodes.CastClass: cil.Emit(OpCodes.Castclass, _linker.GetType(b.Argument as DataType)); break; case Opcodes.Eq: cil.Emit(OpCodes.Ceq); break; case Opcodes.Neq: cil.Emit(OpCodes.Ceq); cil.Emit(OpCodes.Ldc_I4_0); cil.Emit(OpCodes.Ceq); break; case Opcodes.Lt: cil.Emit(OpCodes.Clt); break; case Opcodes.Lt_Unsigned: cil.Emit(OpCodes.Clt_Un); break; case Opcodes.Lte: cil.Emit(OpCodes.Cgt); cil.Emit(OpCodes.Ldc_I4_0); cil.Emit(OpCodes.Ceq); break; case Opcodes.Lte_Unsigned: cil.Emit(OpCodes.Cgt_Un); cil.Emit(OpCodes.Ldc_I4_0); cil.Emit(OpCodes.Ceq); break; case Opcodes.Gt: cil.Emit(OpCodes.Cgt); break; case Opcodes.Gt_Unsigned: cil.Emit(OpCodes.Cgt_Un); break; case Opcodes.Gte: cil.Emit(OpCodes.Clt); cil.Emit(OpCodes.Ldc_I4_0); cil.Emit(OpCodes.Ceq); break; case Opcodes.Gte_Unsigned: cil.Emit(OpCodes.Clt_Un); cil.Emit(OpCodes.Ldc_I4_0); cil.Emit(OpCodes.Ceq); break; case Opcodes.Add: cil.Emit(OpCodes.Add); break; case Opcodes.Sub: cil.Emit(OpCodes.Sub); break; case Opcodes.Mul: cil.Emit(OpCodes.Mul); break; case Opcodes.Div: cil.Emit(OpCodes.Div); break; case Opcodes.Div_Un: cil.Emit(OpCodes.Div_Un); break; case Opcodes.Rem: cil.Emit(OpCodes.Rem); break; case Opcodes.Rem_Un: cil.Emit(OpCodes.Rem_Un); break; case Opcodes.And: cil.Emit(OpCodes.And); break; case Opcodes.Or: cil.Emit(OpCodes.Or); break; case Opcodes.Xor: cil.Emit(OpCodes.Xor); break; case Opcodes.Shl: cil.Emit(OpCodes.Shl); break; case Opcodes.Shr: cil.Emit(OpCodes.Shr); break; case Opcodes.Shr_Un: cil.Emit(OpCodes.Shr_Un); break; case Opcodes.BitwiseNot: cil.Emit(OpCodes.Not); break; case Opcodes.Leave: cil.Emit(OpCodes.Leave, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.LogNot: cil.Emit(OpCodes.Ldc_I4_0); cil.Emit(OpCodes.Ceq); break; case Opcodes.Neg: cil.Emit(OpCodes.Neg); break; case Opcodes.Br: cil.Emit(OpCodes.Br, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrEq: cil.Emit(OpCodes.Beq, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrNeq: cil.Emit(OpCodes.Ceq); cil.Emit(OpCodes.Brfalse, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrTrue: cil.Emit(OpCodes.Brtrue, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrFalse: cil.Emit(OpCodes.Brfalse, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrLt: cil.Emit(OpCodes.Blt, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrLte: cil.Emit(OpCodes.Ble, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrGt: cil.Emit(OpCodes.Bgt, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrGte: cil.Emit(OpCodes.Bge, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrLt_Unsigned: cil.Emit(OpCodes.Blt_Un, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrLte_Unsigned: cil.Emit(OpCodes.Ble_Un, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrGt_Unsigned: cil.Emit(OpCodes.Bgt_Un, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrGte_Unsigned: cil.Emit(OpCodes.Bge_Un, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrNull: cil.Emit(OpCodes.Ldnull); cil.Emit(OpCodes.Beq, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.BrNotNull: cil.Emit(OpCodes.Ldnull); cil.Emit(OpCodes.Bne_Un, cilLabels[(API.Domain.Bytecode.Label)b.Argument]); break; case Opcodes.Ret: cil.Emit(OpCodes.Ret); break; case Opcodes.Throw: cil.Emit(OpCodes.Throw); break; default: throw new InvalidOperationException("Unhandled opcode in .NET backend: " + b.Opcode); } } cil.EndScope(); }
private void GenStmt(ParseTreeNode stmt, ILGenerator il, SymbolTable symbolTable, Label?exitScope = null) { if (stmt.Term.Name == "program") { if (stmt.ChildNodes.Count > 0) { this.GenStmt(stmt.ChildNodes[0].ChildNodes[0], il, symbolTable); this.GenStmt(stmt.ChildNodes[1], il, symbolTable); } } else if (stmt.Term.Name == "variableDeclaration") { Type localType; // declare a local if (stmt.ChildNodes[2].Term.Name == "typeSpecifier") { localType = this.TypeOfTypeDeclaration(stmt.ChildNodes[2].ChildNodes[0]); } else { localType = TypeOfExpr(stmt.ChildNodes[2].ChildNodes[1], symbolTable); } Action <string> generateAssign = null; ParseTreeNode assign = stmt.ChildNodes.Where(x => x.Term.Name == "setEqual").SingleOrDefault(); // set the initial value if (assign != null) { generateAssign = new Action <string>(name => { this.GenExpr(assign.ChildNodes[1], symbolTable.locals[name].LocalType, il, symbolTable); symbolTable.Store(name, TypeOfExpr(assign.ChildNodes[1], symbolTable), il); }); } var variableIden = stmt.ChildNodes[1]; while (true) { string name = variableIden.ChildNodes[0].Token.ValueString; symbolTable.AddLocal(name, il.DeclareLocal(localType)); if (generateAssign != null) { generateAssign(name); } if (variableIden.ChildNodes.Count < 2) { break; } variableIden = variableIden.ChildNodes[1]; } } else if (stmt.Term.Name == "io") { if (stmt.ChildNodes[0].Token.ValueString == "put") { //the first argument is always there, until we can build a proper AST this'll have to do ParseTreeNode argItem = stmt.ChildNodes[1]; this.GenExpr(argItem.ChildNodes[0], typeof(string), il, symbolTable); il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("Write", new System.Type[] { typeof(string) })); argItem = stmt.ChildNodes[2]; while (true) { if (argItem.ChildNodes.Count == 0) { break; } this.GenExpr(argItem.ChildNodes[0].ChildNodes[0], typeof(string), il, symbolTable); il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("Write", new System.Type[] { typeof(string) })); argItem = argItem.ChildNodes[1]; } if (stmt.ChildNodes[3].ChildNodes.Count == 0)//put a newline character if there is no ... { il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { })); } } else if (stmt.ChildNodes[0].Token.ValueString == "get") { foreach (var argument in stmt.ChildNodes[1].ChildNodes) { //switch(symbolTable.TypeOfVar( il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", new System.Type[] { })); symbolTable.Store(argument.Token.ValueString, typeof(string), il); } } } else if (stmt.Term.Name == "assignment") { if (stmt.ChildNodes[0].Term.Name == "functionCall")//if we see this as a function call, we know that's not true, and it's actually an array (which is kinda the same thing in turing) { string arrayName = stmt.ChildNodes[0].ChildNodes[0].Token.ValueString; if (symbolTable.TypeOfVar(arrayName).IsArray) { symbolTable.PushVar(arrayName, il); if (stmt.ChildNodes[0].ChildNodes[1].ChildNodes.Count > 1) { throw new NotImplementedException("Multi-Dimensional arrays are not yet supported"); } this.GenExpr(stmt.ChildNodes[0].ChildNodes[1].ChildNodes[0], typeof(int), il, symbolTable); this.GenExpr(stmt.ChildNodes[1].ChildNodes[1], TypeOfExpr(stmt.ChildNodes[1].ChildNodes[1], symbolTable), il, symbolTable); il.Emit(OpCodes.Stelem, symbolTable.TypeOfVar(arrayName).GetElementType()); } else { throw new NotSupportedException(String.Format("Non-array identifier used like an array: {0}", arrayName)); } } else { this.GenExpr(stmt.ChildNodes[1].ChildNodes[1], TypeOfExpr(stmt.ChildNodes[1].ChildNodes[1], symbolTable), il, symbolTable); string ident = stmt.ChildNodes[0].Token.ValueString; symbolTable.Store(ident, TypeOfExpr(stmt.ChildNodes[1].ChildNodes[1], symbolTable), il); } } else if (stmt.Term.Name == "functionDefinition") { string functionName = stmt.ChildNodes[0].ChildNodes[1].Token.ValueString; SymbolTable localSymbols = new SymbolTable(symbolTable); foreach (var parameter in symbolTable.functionTable[functionName].arguments) { localSymbols.AddParameter(parameter.argName, parameter.argType); } var ilMeth = symbolTable.functionTable[functionName].GetILGenerator(); GenStmt(stmt.ChildNodes[1], ilMeth, localSymbols); ilMeth.Emit(OpCodes.Ret); } else if (stmt.Term.Name == "result") { GenExpr(stmt.ChildNodes[1], TypeOfExpr(stmt.ChildNodes[1], symbolTable), il, symbolTable); var result = il.DeclareLocal(TypeOfExpr(stmt.ChildNodes[1], symbolTable)); il.Emit(OpCodes.Stloc, result); il.Emit(OpCodes.Ldloc, result); il.Emit(OpCodes.Ret, result); } else if (stmt.Term.Name == "functionCall" | stmt.Term.Name == "memberCall") { GenExpr(stmt, null, il, symbolTable); } else if (stmt.Term.Name == "ifBlock") { Label ifTrue = il.DefineLabel(); Label ifFalse = il.DefineLabel(); Label endLabel = il.DefineLabel(); GenExpr(stmt.ChildNodes[0], typeof(bool), il, symbolTable); //expression to check if true il.Emit(OpCodes.Brtrue, ifTrue); //if true then jump to true block il.Emit(OpCodes.Br, ifFalse); //otherwise jump to false block il.MarkLabel(ifTrue); //true block GenStmt(stmt.ChildNodes[1], il, symbolTable); il.Emit(OpCodes.Br, endLabel); //jump to after false block il.MarkLabel(ifFalse); //false block if (stmt.ChildNodes[2].ChildNodes.Count > 0) //then there's an else-if, this takes place in the else section { ParseTreeNode elseBlockStmt = stmt.ChildNodes[2]; //Turn the elsif to an inner if statement elseBlockStmt.ChildNodes.Add(stmt.ChildNodes[3]); //Move the optional else statement to the inner if statement elseBlockStmt.Term.Name = "ifBlock"; GenStmt(elseBlockStmt, il, symbolTable); } else if (stmt.ChildNodes[3].ChildNodes.Count > 0) { GenStmt(stmt.ChildNodes[3].ChildNodes[0], il, symbolTable); //generate expresson for false section, otherwise the label will be at the same spot as the end } il.MarkLabel(endLabel); //the end of the if statement } else if (stmt.Term.Name == "loop") { Label beginLoop = il.DefineLabel(); Label endLoop = il.DefineLabel(); il.MarkLabel(beginLoop); GenStmt(stmt.ChildNodes[0], il, symbolTable, endLoop); il.Emit(OpCodes.Br, beginLoop); il.MarkLabel(endLoop); } else if (stmt.Term.Name == "forLoop") { il.BeginScope(); Label beginLoop = il.DefineLabel(); Label endLoop = il.DefineLabel(); LocalBuilder i = il.DeclareLocal(typeof(int)); string identName = stmt.ChildNodes[1].Token.ValueString; symbolTable.AddLocal(identName, i); symbolTable.AddLocal("___endLoop", il.DeclareLocal(typeof(int))); if (stmt.ChildNodes[2].ChildNodes.Count == 1)//then an identifier is used as a range, or char. We just fail for now { throw new NotImplementedException(); } else { GenExpr(stmt.ChildNodes[2].ChildNodes[0], typeof(int), il, symbolTable); symbolTable.Store(identName, typeof(int), il); GenExpr(stmt.ChildNodes[2].ChildNodes[1], typeof(int), il, symbolTable); symbolTable.Store("___endLoop", typeof(int), il); } il.MarkLabel(beginLoop); GenStmt(stmt.ChildNodes[4], il, symbolTable, endLoop); symbolTable.PushVar(identName, il); il.Emit(OpCodes.Ldc_I4_1); if (stmt.ChildNodes[3].ChildNodes.Count > 0)//then there is a decreasing statement, so do decreasing { il.Emit(OpCodes.Sub); } else { il.Emit(OpCodes.Add); } il.Emit(OpCodes.Dup); symbolTable.Store(identName, typeof(int), il); symbolTable.PushVar("___endLoop", il); if (stmt.ChildNodes[3].ChildNodes.Count > 0)//then there is a decreasing statement, so do decreasing { il.Emit(OpCodes.Bge, beginLoop); } else { il.Emit(OpCodes.Ble, beginLoop); } il.MarkLabel(endLoop); symbolTable.RemoveLocal(identName); symbolTable.RemoveLocal("___endLoop"); il.EndScope(); } else { throw new System.Exception("don't know how to gen a " + stmt.Term.Name); } }
public void Build(IMethodBuilder builder) { //Dump(); ILGenerator il = builder.GetILGenerator(); Dictionary <BlockLabel, Label> labels = new Dictionary <BlockLabel, Label>(); Dictionary <BlockLocal, LocalBuilder> locals = new Dictionary <BlockLocal, LocalBuilder>(); foreach (IBlockLine line in (IEnumerable <IBlockLine>)lines) { BlockInstruction instruction = line as BlockInstruction; if ((instruction != null) && (instruction.Operation == BlockOperation.MarkLabel)) { labels[(BlockLabel)instruction.Parameter] = il.DefineLabel(); } } foreach (IBlockLine line in (IEnumerable <IBlockLine>)lines) { if (line is Instruction) { Instruction instruction = line as Instruction; if (instruction.Parameter == null) { il.Emit(instruction.Op); } else if (instruction.Parameter is int) { il.Emit(instruction.Op, (int)instruction.Parameter); } else if (instruction.Parameter is string) { il.Emit(instruction.Op, (string)instruction.Parameter); } else if (instruction.Parameter is Type) { il.Emit(instruction.Op, (Type)instruction.Parameter); } else if (instruction.Parameter is FieldInfo) { il.Emit(instruction.Op, (FieldInfo)instruction.Parameter); } else if (instruction.Parameter is MethodInfo) { il.Emit(instruction.Op, (MethodInfo)instruction.Parameter); } else if (instruction.Parameter is ConstructorInfo) { il.Emit(instruction.Op, (ConstructorInfo)instruction.Parameter); } else if (instruction.Parameter is BlockLabel) { BlockLabel blockLabel = (BlockLabel)instruction.Parameter; Label label; if (!labels.TryGetValue(blockLabel, out label)) { throw new Exception("Label " + blockLabel.Name + " not marked"); } il.Emit(instruction.Op, label); } else if (instruction.Parameter is BlockLocal) { il.Emit(instruction.Op, locals[(BlockLocal)instruction.Parameter]); } else { throw new NotImplementedException(instruction.Op.Value + " " + TypeNames.GetName(instruction.Parameter.GetType())); } } else if (line is BlockInstruction) { BlockInstruction instruction = line as BlockInstruction; if (instruction.Operation == BlockOperation.Comment) { } else if (instruction.Operation == BlockOperation.MarkLabel) { il.MarkLabel(labels[(BlockLabel)instruction.Parameter]); } else if (instruction.Operation == BlockOperation.DeclareLocal) { BlockLocal local = (BlockLocal)instruction.Parameter; locals[local] = il.DeclareLocal(local.Type); } else if (instruction.Operation == BlockOperation.BeginScope) { il.BeginScope(); } else if (instruction.Operation == BlockOperation.EndScope) { il.EndScope(); } else { throw new Exception(); } } else { throw new Exception(); } } }
public IFluentILGenerator BeginScope() { _logger?.LogMeta("{"); _generator.BeginScope(); return(this); }
internal override void TranslateToIL(ILGenerator il, Type rtype) { bool insideProtectedRegion = base.compilerGlobals.InsideProtectedRegion; base.compilerGlobals.InsideProtectedRegion = true; base.compilerGlobals.BreakLabelStack.Push(base.compilerGlobals.BreakLabelStack.Peek(0)); base.compilerGlobals.ContinueLabelStack.Push(base.compilerGlobals.ContinueLabelStack.Peek(0)); il.BeginExceptionBlock(); if (this.finally_block != null) { if (this.finallyHasControlFlowOutOfIt) { il.BeginExceptionBlock(); } if (this.handler != null) { il.BeginExceptionBlock(); } } this.body.TranslateToIL(il, Typeob.Void); if (this.tryEndContext != null) { this.tryEndContext.EmitLineInfo(il); } if (this.handler != null) { if (this.type == null) { il.BeginCatchBlock(Typeob.Exception); this.handler.context.EmitLineInfo(il); base.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptExceptionValueMethod); } else { Type c = this.type.ToType(); if (Typeob.Exception.IsAssignableFrom(c)) { il.BeginCatchBlock(c); this.handler.context.EmitLineInfo(il); } else { il.BeginExceptFilterBlock(); this.handler.context.EmitLineInfo(il); base.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptExceptionValueMethod); il.Emit(OpCodes.Isinst, c); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Cgt_Un); il.BeginCatchBlock(null); base.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptExceptionValueMethod); Microsoft.JScript.Convert.Emit(this, il, Typeob.Object, c); } } object obj2 = (this.field is JSVariableField) ? ((JSVariableField)this.field).GetMetaData() : this.field; if (obj2 is LocalBuilder) { il.Emit(OpCodes.Stloc, (LocalBuilder)obj2); } else if (obj2 is FieldInfo) { il.Emit(OpCodes.Stsfld, (FieldInfo)obj2); } else { Microsoft.JScript.Convert.EmitLdarg(il, (short)obj2); } if (this.handler_scope != null) { if (!this.handler_scope.isKnownAtCompileTime) { base.EmitILToLoadEngine(il); il.Emit(OpCodes.Ldstr, this.fieldName); ConstantWrapper.TranslateToILInt(il, this.handler_scope.scopeId); il.Emit(OpCodes.Call, Typeob.Try.GetMethod("PushHandlerScope")); base.Globals.ScopeStack.Push(this.handler_scope); il.BeginExceptionBlock(); } il.BeginScope(); if (base.context.document.debugOn) { this.handler_scope.EmitLocalInfoForFields(il); } } this.handler.TranslateToIL(il, Typeob.Void); if (this.handler_scope != null) { il.EndScope(); if (!this.handler_scope.isKnownAtCompileTime) { il.BeginFinallyBlock(); base.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.popScriptObjectMethod); il.Emit(OpCodes.Pop); base.Globals.ScopeStack.Pop(); il.EndExceptionBlock(); } } il.EndExceptionBlock(); } if (this.finally_block != null) { bool insideFinally = base.compilerGlobals.InsideFinally; int finallyStackTop = base.compilerGlobals.FinallyStackTop; base.compilerGlobals.InsideFinally = true; base.compilerGlobals.FinallyStackTop = base.compilerGlobals.BreakLabelStack.Size(); il.BeginFinallyBlock(); this.finally_block.TranslateToIL(il, Typeob.Void); il.EndExceptionBlock(); base.compilerGlobals.InsideFinally = insideFinally; base.compilerGlobals.FinallyStackTop = finallyStackTop; if (this.finallyHasControlFlowOutOfIt) { il.BeginCatchBlock(Typeob.BreakOutOfFinally); il.Emit(OpCodes.Ldfld, Typeob.BreakOutOfFinally.GetField("target")); int i = base.compilerGlobals.BreakLabelStack.Size() - 1; int num3 = i; while (i > 0) { il.Emit(OpCodes.Dup); ConstantWrapper.TranslateToILInt(il, i); Label label = il.DefineLabel(); il.Emit(OpCodes.Blt_S, label); il.Emit(OpCodes.Pop); if (insideFinally && (i < finallyStackTop)) { il.Emit(OpCodes.Rethrow); } else { il.Emit(OpCodes.Leave, (Label)base.compilerGlobals.BreakLabelStack.Peek(num3 - i)); } il.MarkLabel(label); i--; } il.Emit(OpCodes.Pop); il.BeginCatchBlock(Typeob.ContinueOutOfFinally); il.Emit(OpCodes.Ldfld, Typeob.ContinueOutOfFinally.GetField("target")); int num4 = base.compilerGlobals.ContinueLabelStack.Size() - 1; int num5 = num4; while (num4 > 0) { il.Emit(OpCodes.Dup); ConstantWrapper.TranslateToILInt(il, num4); Label label2 = il.DefineLabel(); il.Emit(OpCodes.Blt_S, label2); il.Emit(OpCodes.Pop); if (insideFinally && (num4 < finallyStackTop)) { il.Emit(OpCodes.Rethrow); } else { il.Emit(OpCodes.Leave, (Label)base.compilerGlobals.ContinueLabelStack.Peek(num5 - num4)); } il.MarkLabel(label2); num4--; } il.Emit(OpCodes.Pop); ScriptObject parent = base.Globals.ScopeStack.Peek(); while ((parent != null) && !(parent is FunctionScope)) { parent = parent.GetParent(); } if ((parent != null) && !insideFinally) { il.BeginCatchBlock(Typeob.ReturnOutOfFinally); il.Emit(OpCodes.Pop); il.Emit(OpCodes.Leave, ((FunctionScope)parent).owner.returnLabel); } il.EndExceptionBlock(); } } base.compilerGlobals.InsideProtectedRegion = insideProtectedRegion; base.compilerGlobals.BreakLabelStack.Pop(); base.compilerGlobals.ContinueLabelStack.Pop(); }
internal override void TranslateToIL(ILGenerator il, Type rtype) { //This assumes that rtype == Void.class. bool savedInsideProtectedRegion = compilerGlobals.InsideProtectedRegion; compilerGlobals.InsideProtectedRegion = true; compilerGlobals.BreakLabelStack.Push(compilerGlobals.BreakLabelStack.Peek(0)); compilerGlobals.ContinueLabelStack.Push(compilerGlobals.ContinueLabelStack.Peek(0)); il.BeginExceptionBlock(); if (this.finally_block != null) { if (this.finallyHasControlFlowOutOfIt) { il.BeginExceptionBlock(); } if (this.handler != null) { il.BeginExceptionBlock(); } } this.body.TranslateToIL(il, Typeob.Void); if (this.tryEndContext != null) { this.tryEndContext.EmitLineInfo(il); } if (this.handler != null) { if (this.type == null) { il.BeginCatchBlock(Typeob.Exception); this.handler.context.EmitLineInfo(il); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptExceptionValueMethod); } else { Type filterType = this.type.ToType(); if (Typeob.Exception.IsAssignableFrom(filterType)) { il.BeginCatchBlock(filterType); this.handler.context.EmitLineInfo(il); } else { il.BeginExceptFilterBlock(); this.handler.context.EmitLineInfo(il); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptExceptionValueMethod); il.Emit(OpCodes.Isinst, filterType); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Cgt_Un); il.BeginCatchBlock(null); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.jScriptExceptionValueMethod); Convert.Emit(this, il, Typeob.Object, filterType); } } Object tok = this.field is JSVariableField ? ((JSVariableField)this.field).GetMetaData() : this.field; if (tok is LocalBuilder) { il.Emit(OpCodes.Stloc, (LocalBuilder)tok); } else if (tok is FieldInfo) { il.Emit(OpCodes.Stsfld, (FieldInfo)tok); } else { Convert.EmitLdarg(il, (short)tok); } if (this.handler_scope != null) { if (!this.handler_scope.isKnownAtCompileTime) //I.e. eval or nested func { this.EmitILToLoadEngine(il); il.Emit(OpCodes.Ldstr, this.fieldName); ConstantWrapper.TranslateToILInt(il, this.handler_scope.scopeId); il.Emit(OpCodes.Call, Typeob.Try.GetMethod("PushHandlerScope")); Globals.ScopeStack.Push(this.handler_scope); il.BeginExceptionBlock(); } il.BeginScope(); // so that we can emit local scoped information for the handler variable if (this.context.document.debugOn) { this.handler_scope.EmitLocalInfoForFields(il); } } this.handler.TranslateToIL(il, Typeob.Void); if (this.handler_scope != null) { il.EndScope(); if (!this.handler_scope.isKnownAtCompileTime) //I.e. eval or nested func { il.BeginFinallyBlock(); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.popScriptObjectMethod); il.Emit(OpCodes.Pop); Globals.ScopeStack.Pop(); il.EndExceptionBlock(); } } il.EndExceptionBlock(); } if (this.finally_block != null) { bool savedInsideFinally = compilerGlobals.InsideFinally; int savedFinallyStackTop = compilerGlobals.FinallyStackTop; compilerGlobals.InsideFinally = true; compilerGlobals.FinallyStackTop = compilerGlobals.BreakLabelStack.Size(); il.BeginFinallyBlock(); this.finally_block.TranslateToIL(il, Typeob.Void); il.EndExceptionBlock(); compilerGlobals.InsideFinally = savedInsideFinally; compilerGlobals.FinallyStackTop = savedFinallyStackTop; if (this.finallyHasControlFlowOutOfIt) { il.BeginCatchBlock(Typeob.BreakOutOfFinally); il.Emit(OpCodes.Ldfld, Typeob.BreakOutOfFinally.GetField("target")); // don't need to go to 0 in the loop because 0 is the outmost block (i.e. function body) // and that would generate a JIT assert because the jump is sometimes outside the function for (int i = compilerGlobals.BreakLabelStack.Size() - 1, n = i; i > 0; i--) { il.Emit(OpCodes.Dup); ConstantWrapper.TranslateToILInt(il, i); Label lab = il.DefineLabel(); il.Emit(OpCodes.Blt_S, lab); il.Emit(OpCodes.Pop); if (savedInsideFinally && i < savedFinallyStackTop) { il.Emit(OpCodes.Rethrow); } else { il.Emit(OpCodes.Leave, (Label)compilerGlobals.BreakLabelStack.Peek(n - i)); } il.MarkLabel(lab); } il.Emit(OpCodes.Pop); il.BeginCatchBlock(Typeob.ContinueOutOfFinally); il.Emit(OpCodes.Ldfld, Typeob.ContinueOutOfFinally.GetField("target")); // don't need to go to 0 in the loop because 0 is the outmost block (i.e. function body) for (int i = compilerGlobals.ContinueLabelStack.Size() - 1, n = i; i > 0; i--) { il.Emit(OpCodes.Dup); ConstantWrapper.TranslateToILInt(il, i); Label lab = il.DefineLabel(); il.Emit(OpCodes.Blt_S, lab); il.Emit(OpCodes.Pop); if (savedInsideFinally && i < savedFinallyStackTop) { il.Emit(OpCodes.Rethrow); } else { il.Emit(OpCodes.Leave, (Label)compilerGlobals.ContinueLabelStack.Peek(n - i)); } il.MarkLabel(lab); } il.Emit(OpCodes.Pop); ScriptObject scope = Globals.ScopeStack.Peek(); while (scope != null && !(scope is FunctionScope)) { scope = scope.GetParent(); } if (scope != null && !savedInsideFinally) { il.BeginCatchBlock(Typeob.ReturnOutOfFinally); il.Emit(OpCodes.Pop); il.Emit(OpCodes.Leave, ((FunctionScope)scope).owner.returnLabel); } il.EndExceptionBlock(); } } compilerGlobals.InsideProtectedRegion = savedInsideProtectedRegion; compilerGlobals.BreakLabelStack.Pop(); compilerGlobals.ContinueLabelStack.Pop(); }
public virtual void BeginScope() { il.BeginScope(); }
public void BeginScope() { ilGenerator.BeginScope(); }
public void BeginScope() { il.BeginScope(); }
/// <summary> /// It's called when codegenerator enter to the code block. /// It create a new variable naming context /// </summary> public void BlockEnter() { currentContext = new Context(currentContext); il.BeginScope(); }
public void BeginScope() => generator.BeginScope();
public void BeginScope() { generator.BeginScope(); scopeCount++; }
public static void Main() { try { // <Snippet2> // <Snippet3> // Get the current AppDomain. AppDomain myAppDomain = AppDomain.CurrentDomain; AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "SampleAssembly"; // Create a dynamic assembly 'myAssembly' with access mode 'Run'. AssemblyBuilder myAssembly = myAppDomain.DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess.Run); // Create a dynamic module 'myModule' in 'myAssembly'. ModuleBuilder myModule = myAssembly.DefineDynamicModule("MyDynamicModule", true); // Define a public class 'MyDynamicClass'. TypeBuilder myTypeBuilder = myModule.DefineType("MyDynamicClass", TypeAttributes.Public); // Define a public string field. FieldBuilder myField = myTypeBuilder.DefineField("MyDynamicField", typeof(String), FieldAttributes.Public); // Create the constructor. Type[] myConstructorArgs = { typeof(String) }; ConstructorBuilder myConstructor = myTypeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, myConstructorArgs); // Generate IL for 'myConstructor'. ILGenerator myConstructorIL = myConstructor.GetILGenerator(); // Emit the necessary opcodes. myConstructorIL.Emit(OpCodes.Ldarg_0); ConstructorInfo mySuperConstructor = typeof(Object).GetConstructor(new Type[0]); myConstructorIL.Emit(OpCodes.Call, mySuperConstructor); myConstructorIL.Emit(OpCodes.Ldarg_0); myConstructorIL.Emit(OpCodes.Ldarg_1); myConstructorIL.Emit(OpCodes.Stfld, myField); myConstructorIL.Emit(OpCodes.Ret); // Define a dynamic method named 'MyDynamicMethod'. MethodBuilder myMethod = myTypeBuilder.DefineMethod("MyDynamicMethod", MethodAttributes.Public, typeof(String), null); // Generate IL for 'myMethod'. ILGenerator myMethodIL = myMethod.GetILGenerator(); // Begin the scope for a local variable. myMethodIL.BeginScope(); LocalBuilder myLocalBuilder = myMethodIL.DeclareLocal(typeof(int)); Console.WriteLine("\nTrying to access the local variable within the scope."); Console.WriteLine("'myLocalBuilder' type is: {0}", myLocalBuilder.LocalType); myMethodIL.Emit(OpCodes.Ldstr, "Local value"); myMethodIL.Emit(OpCodes.Stloc_0, myLocalBuilder); // End the scope of 'myLocalBuilder'. myMethodIL.EndScope(); // Access the local variable outside the scope. Console.WriteLine("\nTrying to access the local variable outside the scope:"); myMethodIL.Emit(OpCodes.Stloc_0, myLocalBuilder); myMethodIL.Emit(OpCodes.Ldloc_0); myMethodIL.Emit(OpCodes.Ret); // Create 'MyDynamicClass' class. Type myType1 = myTypeBuilder.CreateType(); // </Snippet3> // </Snippet2> // Create an instance of the 'MyDynamicClass'. Object myObject1 = Activator.CreateInstance(myType1, new Object[] { "HelloWorld" }); // Invoke 'MyDynamicMethod' method of 'MyDynamicClass'. Object myObject2 = myType1.InvokeMember("MyDynamicMethod", BindingFlags.InvokeMethod, null, myObject1, null); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.Message); } }
public void BeginScope() { _generator.BeginScope(); }
public void BeginScope() { ig.BeginScope(); SymbolWriter.OpenScope(ig); }
public void BeginScope() { sb.Append("\r\n\t\tBeginScope"); gen.BeginScope(); }