Пример #1
0
    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;
    }
Пример #2
0
        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);
        }
Пример #3
0
        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);
        }
Пример #4
0
        public CodeGen(ParseTreeNode stmt, string moduleName)
        {
            if (Path.GetFileName(moduleName) != moduleName)
            {
                throw new System.Exception("can only output into current directory!");
            }

            AssemblyName name = new AssemblyName(Path.GetFileNameWithoutExtension(moduleName));

            asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);

            ModuleBuilder modb = asmb.DefineDynamicModule(moduleName);

            //mainProgram = modb.DefineType("Program");

            //var mainArgs = new List<Tuple<string, Type>>();
            //var mainProgramDef = new FunctionDefinition
            //(
            //    mainProgram.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes),
            //    new List<FunctionDefinition.Argument>()
            //);

            SymbolTable symbolTable = new SymbolTable(modb.DefineType("__Program"));

            symbolTable.AddFunctionHeader("__Main", MethodAttributes.Static, null, new FunctionDefinition.Argument[]{});

            //symbolTable.functionTable.AddHeader("Main", mainProgramDef);

            stmt = PreGenerate(stmt, symbolTable);
            stmt = ImportList(stmt, symbolTable);

            // CodeGenerator
            var il = symbolTable.functionTable["__Main"].GetILGenerator();

            // Go Compile!
            this.GenStmt(stmt, il, symbolTable);

            //il.Emit(OpCodes.Ldstr, "Press any key to exit the program...");
            //il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
            //il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("ReadKey", new Type[] { }));

            il.Emit(OpCodes.Ret);
            //mainProgram.CreateType();
            modb.CreateGlobalFunctions();
            asmb.SetEntryPoint(symbolTable.functionTable["__Main"].methodDefinition);

            symbolTable.typeTable.types[0].typeBuilder.CreateType();

            asmb.Save(moduleName);
            foreach (var symbol in symbolTable.Locals)
            {
                Console.WriteLine("{0}: {1}", symbol.Key, symbol.Value);
            }
            symbolTable = null;
            il = null;
        }
Пример #5
0
        /**
         * Saves the constructed assembly to a file
         */
        public void SaveAssembly()
        {
            add_resources_to_assembly();

            // if there are some nemerle specific metadata encoded in attributes
            if (contains_nemerle_specifics)
            {
                var attr = Manager.AttributeCompiler.MakeEmittedAttribute(
                    SystemTypeCache.Reflection_AssemblyConfigurationAttribute, "ContainsNemerleTypes");
                this._assembly_builder.SetCustomAttribute(attr);
            }

            // set the entry point
            if (_need_entry_point)
            {
                if (Option.IsSome(_entry_point, out var entry_point_method_info))
                {
                    _assembly_builder.SetEntryPoint(entry_point_method_info,
                        (Manager.Options.TargetIsWinexe)
                            ? Emit.PEFileKinds.WindowApplication
                            : Emit.PEFileKinds.ConsoleApplication);
                }
                else
                {
                    Message.Error("no suitable entry point (Main function) found");
                }
            }

            // save the assembly
            try
            {
                var (portableExecutableKind, imageFileMachine) = make_platform_flags(Manager.Options.Platform);
                _assembly_builder.Save(Path.GetFileName(_OutputFileName), portableExecutableKind, imageFileMachine);
                //when (_debug_emit != null) _debug_emit.Close ();
            }
            catch (System.UnauthorizedAccessException e)
            {
                Message.Error($"could not write to output file `$(this._OutputFileName)' -- `$(e.Message)'");
            }
            catch (IOException e)
            {
                Message.Error($"could not write to output file `$(this._OutputFileName)' -- `$(e.Message)'");
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                Message.Error($"Problems saving assembly: $(e.Message)");
            }
            catch (System.ApplicationException e)
            {
                Message.Error(e.Message);
            }
        }
Пример #6
0
        private void finalizar(string nombreEjecutable)
        {
            //Asigno una pausa para indicar que finalizo la ejecucion del codigo objetivo generado
            anadirPausa();
            //Creo el assembler .net y defino las ultimas opciones de configuracion
            il.Emit(Emit.OpCodes.Ret);
            Type pp = typeBuilder.CreateType();

            modb.CreateGlobalFunctions();
            asmb.SetEntryPoint(methb, Reflect.Emit.PEFileKinds.ConsoleApplication);
            asmb.Save(IO.Path.GetFileName(nombreEjecutable));
            //Ahora procedo a limpiar la tabla de direcciones para su proximo uso.
            TablaDireccionesSimbolos.Clear();
            this.il = null;
        }
Пример #7
0
        public AssemblyGen(TypeDeclaration methodDec, string moduleName, string dllProbeDirectory)
        {
            if (IO.Path.GetFileName(moduleName) != moduleName)
            {
                throw new System.Exception("can only output into current directory!");
            }

            this.dllProbeDirectory = dllProbeDirectory;

            typeList = new List <TypeGen>();

            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);
            GenerateType(methodDec, modb, dllProbeDirectory);
            modb.CreateGlobalFunctions();
            asmb.SetEntryPoint(GetEntryPoint());
            asmb.Save(moduleName);
        }
Пример #8
0
        public void BuildLi(List<CodeBlock> CodeBlocks, string asmname)
        {
            //setup
            asm = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName(asmname), AssemblyBuilderAccess.Save);
            ModuleBuilder mod = asm.DefineDynamicModule("TestOutput.exe",
               asmname +".exe");
            TypeBuilder type = mod.DefineType("Program", TypeAttributes.Class);
            MethodBuilder main = type.DefineMethod("Main",
               MethodAttributes.Public | MethodAttributes.Static);
            ILGenerator il = main.GetILGenerator();
            //actual il code

            foreach (var block in CodeBlocks)
            {
                if (block.name == "ClassCode")
                {
                    foreach (IAst node in block.Nodes)
                    {
                        if (node is ObjCallStmt)
                        {
                            ObjCallStmt nd = node as ObjCallStmt;
                            il.Emit(OpCodes.Ldstr, (nd.Paramaters[0] as EcString).Value as string);
                        }

                    }

                    break;
                }

            }

            /*  il.Emit(OpCodes.Ldstr, "Hello world!");
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
                BindingFlags.Public | BindingFlags.Static,
                null, new Type[] { typeof(String) }, null));*/
            il.Emit(OpCodes.Ret);

            //done
            type.CreateType();
            asm.SetEntryPoint(main);
        }
Пример #9
0
        public static TypeBuilder GetTypeBuilder(string fileName, ModuleBuilder mb, AssemblyBuilder ab)
        {
            StreamReader file = new StreamReader(fileName);
            TypeBuilder tb = mb.DefineType( fileName.Substring(0,fileName.Length-3).Replace(@"\", "."), TypeAttributes.Public);
            var code = file.ReadToEnd();
            var esprima = new Esprima.NET.Esprima();
            var node = esprima.parse(code, new Options());

            foreach (var fcuntionDef in node.body.Where(x => x.type == "FunctionDeclaration"))
            {
                var argumentNames = [email protected](x => typeof(Object)).ToArray();
                MethodBuilder metb = tb.DefineMethod(fcuntionDef.id.name, MethodAttributes.Public | MethodAttributes.Static, null, argumentNames);
                ab.SetEntryPoint(metb);
                ILGenerator il = metb.GetILGenerator();
                il.EmitWriteLine("Hello World");
                il.Emit(OpCodes.Ret);
                il.Emit(OpCodes.Ret);
            }
            tb.CreateType();
            return tb;
        }
Пример #10
0
        public BrainfuckApp(string name)
        {
            Name = name;
            _asBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName { Name = "Brainfuck app" }, AssemblyBuilderAccess.Save);
            _modBuilder = _asBuilder.DefineDynamicModule("bf", name + ".exe");
            _typeBuilder = _modBuilder.DefineType("Program", TypeAttributes.Public);
            _methBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);
            _asBuilder.SetEntryPoint(_methBuilder);
            _il = _methBuilder.GetILGenerator();

            _il.DeclareLocal(typeof(int));
            _il.DeclareLocal(typeof(int[]));

            // Initialize idx to 0
            _il.Emit(OpCodes.Ldc_I4_0);
            _il.Emit(OpCodes.Stloc_0);

            // Initialize cell with 30000 fields of int
            _il.Emit(OpCodes.Ldc_I4, 30000);
            _il.Emit(OpCodes.Newarr, typeof(int));
            _il.Emit(OpCodes.Stloc_1);
        }
Пример #11
0
    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);
    }
Пример #12
0
        private AssemblyBuilder CreateExecutable(string name)
        {
            ILGenerator il;

            name = name.Replace('\\', '/');
            string exename  = name.Contains('/') ? name.Substring(name.LastIndexOf('/') + 1) : name;
            string pathname = name.Contains('/') ? name.Remove(name.LastIndexOf('/')) : null;
            string asmname  = exename.Contains('.') ? exename.Remove(exename.LastIndexOf('.')) : exename;
            //
            // We are generating a dynamic assembly here.
            //
            // Get type information from the runtime assembly
            var  asm_runtime = Assembly.Load("GameCreator.Runtime");
            var  asm_gamei   = Assembly.Load("GameCreator.Runtime.Game.Interpreted");
            var  asm_game    = Assembly.Load("GameCreator.Runtime.Game");
            Type t_gamei     = asm_gamei.GetType("GameCreator.Runtime.Game.Interpreted.InterpretedGame");
            Type t_game      = asm_game.GetType("GameCreator.Runtime.Game.Game");
            Type t_ext       = typeof(ResourceExtensions);
            Type t_obj       = typeof(Framework.Object);
            Type t_room      = typeof(Room);
            Type t_event     = typeof(Event);
            Type t_lib       = typeof(Framework.ActionLibrary);
            Type t_context   = typeof(LibraryContext);
            Type t_rcontext  = typeof(ResourceContext);

            // Define our dynamic assembly
            System.Reflection.Emit.AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(asmname), AssemblyBuilderAccess.RunAndSave, pathname);
            ModuleBuilder mod = asm.DefineDynamicModule(exename, exename);
            // Define our Program type
            TypeBuilder program = mod.DefineType(string.Format("{0}.Program", asmname));

            System.Resources.IResourceWriter resw = mod.DefineResource(string.Format("{0}.Program.resources", asmname), string.Empty);
            FieldBuilder  resourceManager         = program.DefineField("resourceManager", typeof(System.Resources.ResourceManager), FieldAttributes.Static);
            MethodBuilder GetResourceManager      = program.DefineMethod("GetResourceManager", MethodAttributes.Static, typeof(System.Resources.ResourceManager), Type.EmptyTypes);

            il = GetResourceManager.GetILGenerator();
            System.Reflection.Emit.Label grm_l_1 = il.DefineLabel();
            il.Emit(OpCodes.Ldsfld, resourceManager);
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Brtrue_S, grm_l_1);
            il.Emit(OpCodes.Pop);
            il.Emit(OpCodes.Ldstr, string.Format("{0}.Program", asmname));
            il.Emit(OpCodes.Ldtoken, program);
            il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public));
            il.Emit(OpCodes.Callvirt, typeof(Type).GetProperty("Assembly").GetGetMethod());
            il.Emit(OpCodes.Newobj, typeof(System.Resources.ResourceManager).GetConstructor(new Type[] { typeof(string), typeof(Assembly) }));
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Stsfld, resourceManager);
            il.MarkLabel(grm_l_1);
            il.Emit(OpCodes.Ret);
            //program.SetCustomAttribute(new CustomAttributeBuilder(typeof(STAThreadAttribute).GetConstructor(new Type[] { }), new object[] { }));
            // our static Main() function
            // {
            //   GameCreator.Runtime.Object obj;
            //   GameCreator.Runtime.Event ev;
            //   GameCreator.Runtime.ActionLibrary lib;
            //   GameCreator.Runtime.Game.Init();
            //   ...
            //   lib = GameCreator.ActionLibrary.Define(id);
            //   lib.DefineAction(actionid, kind, execution, question, func, code, args);
            //   ...
            //   GameCreator.Runtime.Script.Define("name", index, "code");
            //   ...
            //   obj = GameCreator.Runtime.Object.Define("name", index);
            //   ev = obj.DefineEvent(event, num);
            //   ev.DefineAction(libid, actionid, args, appliesto, relative, not);
            //   ...
            //   GameCreator.Runtime.Room.Define("name", index).CreationCode = "code";
            //   ...
            //   GameCreator.Runtime.Game.Name = "name";
            //   GameCreator.Runtime.Game.Run();
            //   (return)
            // }
            // GameCreator.Runtime.Object obj;
            // GameCreator.Runtime.Event ev;
            // GameCreator.Runtime.ActionLibrary lib;
            MethodBuilder initLibraries = program.DefineMethod("InitLibraries", MethodAttributes.Static);

            il = initLibraries.GetILGenerator();
            foreach (ActionLibrary lib in Program.Library)
            {
                // lib = GameCreator.ActionLibrary.Define(id);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.Emit(OpCodes.Ldc_I4, lib.LibraryID);
                il.EmitCall(OpCodes.Call, t_context.GetMethod("GetActionLibrary", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int) }, null), null);
                foreach (ActionDefinition ad in lib.Actions)
                {
                    // lib.DefineAction(actionid, kind, execution, question, func, code, args);
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, ad.ActionID);
                    il.Emit(OpCodes.Ldc_I4, (int)ad.Kind);
                    il.Emit(OpCodes.Ldc_I4, (int)ad.ExecutionType);
                    il.Emit(ad.IsQuestion ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                    il.Emit(OpCodes.Ldstr, ad.FunctionName);
                    il.Emit(OpCodes.Ldstr, ad.Code);
                    // ... , new ActionArgumentType[] { x, y, z },
                    il.Emit(OpCodes.Ldc_I4, ad.ArgumentCount);
                    il.Emit(OpCodes.Newarr, typeof(ActionArgumentType));
                    for (int i = 0; i < ad.ArgumentCount; i++)
                    {
                        il.Emit(OpCodes.Dup);
                        il.Emit(OpCodes.Ldc_I4, i);
                        il.Emit(OpCodes.Ldc_I4, (int)ad.Arguments[i].Type);
                        il.Emit(OpCodes.Stelem_I4);
                    }
                    //
                    il.EmitCall(OpCodes.Call, t_lib.GetMethod("DefineAction", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(ActionKind), typeof(ActionExecutionType), typeof(bool), typeof(string), typeof(string), typeof(ActionArgumentType[]) }, null), null);
                }
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineSprites = program.DefineMethod("DefineSprites", MethodAttributes.Static);

            il = defineSprites.GetILGenerator();
            foreach (SpriteResourceView res in Program.Sprites.Values)
            {
                // Define the resource
                int i = 0;
                foreach (Bitmap b in res.Animation.Frames)
                {
                    resw.AddResource(string.Format("spr_{0}_{1}", res.ResourceID, i++), b);
                }
                // GameCreator.Runtime.Sprite.Define("name", index, subimages);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Sprites", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.Emit(OpCodes.Ldstr, res.Name);
                il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                il.Emit(OpCodes.Ldc_I4, res.Animation.FrameCount);
                il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Sprite>), typeof(string), typeof(int), typeof(int) }, null), null);
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineScripts = program.DefineMethod("DefineScripts", MethodAttributes.Static);

            il = defineScripts.GetILGenerator();
            foreach (ScriptResourceView res in Program.Scripts.Values)
            {
                // GameCreator.Runtime.Script.Define("name", index, "code");
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Sprites", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.Emit(OpCodes.Ldstr, res.Name);
                il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                il.Emit(OpCodes.Ldstr, res.Code);
                il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Script>), typeof(string), typeof(int), typeof(string) }, null), null);
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineObjects = program.DefineMethod("DefineObjects", MethodAttributes.Static);

            il = defineObjects.GetILGenerator();
            foreach (ObjectResourceView res in Program.Objects.Values)
            {
                // obj = GameCreator.Runtime.Object.Define("name", index);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Objects", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.Emit(OpCodes.Ldstr, res.Name);
                il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Framework.Object>), typeof(string), typeof(int) }, null), null);
                foreach (ObjectEvent ev in res.Events)
                {
                    // ev = obj.DefineEvent(event, num);
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, (int)ev.EventType);
                    il.Emit(OpCodes.Ldc_I4, (int)ev.EventNumber);
                    il.EmitCall(OpCodes.Call, t_obj.GetMethod("DefineEvent", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int) }, null), null);
                    foreach (ActionDeclaration ad in ev.Actions)
                    {
                        // ev.DefineAction(libid, actionid, args, appliesto, relative, not);
                        il.Emit(OpCodes.Dup);
                        il.Emit(OpCodes.Ldc_I4, ad.Kind.Library.LibraryID);
                        il.Emit(OpCodes.Ldc_I4, ad.Kind.ActionID);
                        // ... , new string[] { "arg", "arg", "arg" },
                        il.Emit(OpCodes.Ldc_I4, ad.Kind.ArgumentCount);
                        il.Emit(OpCodes.Newarr, typeof(string));
                        for (int i = 0; i < ad.Kind.ArgumentCount; i++)
                        {
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Ldc_I4, i);
                            il.Emit(OpCodes.Ldstr, ad.Arguments[i]);
                            il.Emit(OpCodes.Stelem_Ref);
                        }
                        //
                        il.Emit(OpCodes.Ldc_I4, ad.AppliesTo);
                        il.Emit(ad.Relative ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                        il.Emit(ad.Not ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                        il.EmitCall(OpCodes.Call, t_event.GetMethod("DefineAction", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int), typeof(string[]), typeof(int), typeof(bool), typeof(bool) }, null), null);
                    }
                    il.Emit(OpCodes.Pop);
                }
                il.Emit(OpCodes.Dup);
                // obj.SpriteIndex = ind;
                il.Emit(OpCodes.Ldc_I4, res.Sprite);
                il.EmitCall(OpCodes.Call, t_obj.GetProperty("SpriteIndex").GetSetMethod(), null);
                //obj.Depth = d;
                il.Emit(OpCodes.Ldc_R8, res.Depth);
                il.EmitCall(OpCodes.Call, t_obj.GetProperty("Depth").GetSetMethod(), null);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineRooms = program.DefineMethod("DefineRooms", MethodAttributes.Static);

            il = defineRooms.GetILGenerator();
            // Start defining rooms.
            // We perform a 'preorder iterative traversal' of the 'Rooms' TreeNode to ensure the rooms are defined in the correct order.
            // We can probably eliminate the stack by using the 'Parent' property of the nodes instead.
            Stack <TreeNode> nodes = new Stack <TreeNode>();

            nodes.Push(Rooms.Node);
            while (nodes.Count != 0)
            {
                TreeNode tn = nodes.Pop();
                if (tn.Tag.GetType() == typeof(RoomResourceView))
                {
                    RoomResourceView res = (RoomResourceView)(tn.Tag);
                    // GameCreator.Runtime.Room.Define("name", index).CreationCode = "code";
                    il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                    il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                    il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Rooms", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                    il.Emit(OpCodes.Ldstr, res.Name);
                    il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                    il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Room>), typeof(string), typeof(int) }, null), null);
                    il.Emit(OpCodes.Ldstr, res.CreationCode);
                    il.EmitCall(OpCodes.Call, t_room.GetProperty("CreationCode").GetSetMethod(), null);
                }
                tn = tn.LastNode;
                while (tn != null)
                {
                    nodes.Push(tn);
                    tn = tn.PrevNode;
                }
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder main = program.DefineMethod("Main", MethodAttributes.Static);

            main.SetCustomAttribute(new CustomAttributeBuilder(typeof(STAThreadAttribute).GetConstructor(System.Type.EmptyTypes), new object[] { }));
            il = main.GetILGenerator();
            // GameCreator.Runtime.Game.Interpreted.InterpretedGame.Initialize();
            il.EmitCall(OpCodes.Call, t_gamei.GetMethod("Initialize"), null);
            // InitLibraries();
            il.EmitCall(OpCodes.Call, initLibraries, null);
            // DefineScripts();
            il.EmitCall(OpCodes.Call, defineScripts, null);
            // DefineSprites();
            il.EmitCall(OpCodes.Call, defineSprites, null);
            // DefineObjects();
            il.EmitCall(OpCodes.Call, defineObjects, null);
            // DefineRooms();
            il.EmitCall(OpCodes.Call, defineRooms, null);
            // GameCreator.Runtime.Game.Name = "name";
            //il.Emit(OpCodes.Ldstr, asmname);
            //il.EmitCall(OpCodes.Call, t_game.GetProperty("Name").GetSetMethod(), null);
            // GameCreator.Runtime.Game.ResourceManager = GetResourceManager();
            il.EmitCall(OpCodes.Call, GetResourceManager, null);
            il.EmitCall(OpCodes.Call, t_game.GetProperty("ResourceManager").GetSetMethod(), null);
            // GameCreator.Runtime.Game.Interpreted.InterpretedGame.Run();
            il.EmitCall(OpCodes.Call, t_gamei.GetMethod("Run"), null);
            // return statement, required
            il.Emit(OpCodes.Ret);
            program.CreateType();
            asm.SetEntryPoint(main, PEFileKinds.WindowApplication);
            // Use 32 bit (i386) since GTK# requires it and we plan on using it later
            asm.Save(exename, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
            return(asm);
        }
 public static void SetEntryPointForConsoleApplicationPortable(AssemblyBuilder assemblyBuilder, MethodInfo entryMethod)
 {
     assemblyBuilder.SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
 }
        private static void AddEntryPoint(AssemblyBuilder assemblyBuilder, ModuleBuilder moduleBuilder)
        {
            var typeBuilder = moduleBuilder.DefineType(
                 Guid.NewGuid().ToString("N"), TypeAttributes.Class | TypeAttributes.Public,
                 typeof(object));

            var methodBuilder = typeBuilder.DefineMethod("Main",
                MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public,
                typeof(void), new Type[] { typeof(string[]) });

            var methodGenerator = methodBuilder.GetILGenerator();
            methodGenerator.EmitWriteLine("go!");
            methodGenerator.Emit(OpCodes.Ret);

            typeBuilder.CreateType();

            assemblyBuilder.SetEntryPoint(methodBuilder);
        }
Пример #15
0
        public void GenerateExe()
        {
            string AssemblyName = "TestAssembly";
            string ClassName = "TestClass";
            string ExeName = ClassName + ".exe";

            // 获得应用程序域,用于创建程序集。
            domain = Thread.GetDomain();

            // 创建程序集名称。
            name = new AssemblyName();
            name.Name = AssemblyName;

            // 创建程序集。
            asmbuilder = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);

            // 创建模块。
            modbuilder = asmbuilder.DefineDynamicModule(ExeName);

            // 创建类型。
            typbuilder = modbuilder.DefineType(ClassName);

            // 创建全局变量(类的静态变量)
            fld = typbuilder.DefineField("haha", typeof(int), FieldAttributes.Static);

            // 创建静态方法Add:public static int Add(int,int)
            addBuilder = typbuilder.DefineMethod("Add", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });

            // 创建静态方法Add:public static int Fact(int)
            factBuilder = typbuilder.DefineMethod("Fact", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int) });

            // 创建静态方法Main:public static void Main(string[])
            mainBuilder = typbuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { typeof(string[]) });

            // Add方法的代码生成器
            iladd = addBuilder.GetILGenerator();

            // 产生Add方法的代码
            GenerateCodeForAdd();

            // Fact方法的代码生成器
            ilfact = factBuilder.GetILGenerator();

            // 产生Fact方法的代码
            GenerateCodeForFact();

            // Main方法的代码生成器
            ilmain = mainBuilder.GetILGenerator();

            // 产生Main方法的代码。
            GenerateCodeForMain();

            // 类里所有东西都已经定义好了,现在要创建这个类。
            typbuilder.CreateType();

            // 设置入口点。
            asmbuilder.SetEntryPoint((modbuilder.GetType(ClassName)).GetMethod("Main"));

            // 保存到EXE文件。
            asmbuilder.Save(ExeName);
        }
Пример #16
0
        private void SaveAssembly(
      string fullyQualifiedModuleName,
      AssemblyBuilder assemblyBuilder,
      TypeBuilder typeBuilder)
        {
            Type NireType = typeBuilder.CreateType();

              NireType.GetMethod("Main").Invoke(null, new string[] {null});

              // set the entry point for the application and save it
              assemblyBuilder.SetEntryPoint(this.methodbuilder, PEFileKinds.ConsoleApplication);
              assemblyBuilder.Save(fullyQualifiedModuleName);
        }