Пример #1
0
        private static void DoCompilation(ConfigData cfg, ref bool showUsage)
        {
            var showUsage1 = showUsage;

            CompilerEngine.ExecuteInSeparateAppDomain(
                ce =>
            {
                ce.Configuration = cfg.Configuration;
                ce.CsProject     = cfg.CsProject;
                ce.OutDir        = cfg.OutDir;
                ce.Referenced.Clear();
                ce.TranlationHelpers.Clear();
                ce.ReferencedPyLibsLocations.Clear();

                // src and dest can be in different application domain
                // we need to add item by item
                ce.Set1(cfg.Referenced.ToArray(),
                        cfg.TranlationHelpers.ToArray(),
                        cfg.ReferencedPyLibsLocations.Select(a => a.Key + "\n" + a.Value).ToArray()
                        );
                ce.BinaryOutputDir = cfg.BinaryOutputDir;
                Debug.Assert(ce.Referenced.Count == cfg.Referenced.Count);
                Debug.Assert(ce.TranlationHelpers.Count == cfg.TranlationHelpers.Count);
                Debug.Assert(ce.ReferencedPyLibsLocations.Count == cfg.ReferencedPyLibsLocations.Count);
                //ce.CopyFrom(aa);
                ce.Check();
                showUsage1 = false;
                ce.Compile();
            });
            showUsage = showUsage1;
        }
Пример #2
0
        protected void btnCompileAndRun_Click(object sender, EventArgs e)
        {
            string code      = this.StripHTML(txtSourceLib.InnerText);
            string mainBlock = this.StripHTML(txtMain.InnerText);

            CompilerEngine compiler = new CompilerEngine(code, mainBlock);

            lblOutput.Text = compiler.EndToEndCompileAndRun();
        }
Пример #3
0
        /*
         * /// <summary>
         * /// The main.
         * /// </summary>
         * /// <param name="args">
         * /// The args.
         * /// </param>
         * private static void Main(string[] args)
         * {
         *  var host = new ScriptingHost();
         *  System.Diagnostics.Trace.Write("And it's started.");
         *  string codeLine;
         *  Console.Write(">");
         *  while ((codeLine = Console.ReadLine()) != "Exit();")
         *  {
         *      try
         *      {
         *          // Execute the code
         *          var res = host.Execute(codeLine);
         *
         *          // Write the result back to console
         *          if (res != null)
         *          {
         *              Console.WriteLine(" = " + res.ToString());
         *          }
         *      }
         *      catch (Exception e)
         *      {
         *          Console.WriteLine(" !! " + e.Message);
         *      }
         *
         *      Console.Write(">");
         *  }
         * } */

        static void Main(string[] args)
        {
            string code      = "public class Test{" + "public string SayHello() {" + "return \"Hi, WWW.\"; " + "}" + "}";
            string mainBlock = "Test test = new Test(); " + "Print(test.SayHello());";

            CompilerEngine compiler = new CompilerEngine(code, mainBlock);

            Console.WriteLine(compiler.EndToEndCompileAndRun());
            Console.Read();
        }
Пример #4
0
        //private const string KernelFile = CosmosRoot + @"\Users\Emile\TestBed\TestBed\bin\Debug\TestBed.dll";
        //private const string OutputFile = CosmosRoot + @"\Users\Emile\TestBed\TestBed\bin\Debug\TestBedBoot.asm";

        private static void Main(string[] args)
        {
            //Console.SetOut(new StreamWriter("out", false));

            var xSW = Stopwatch.StartNew();

            try
            {
                CosmosPaths.DebugStubSrc = Path.Combine(CosmosRoot, "source", "Cosmos.Debug.DebugStub");
                var xTask = new CompilerEngine();
                xTask.DebugEnabled = true;
                xTask.StackCorruptionDetectionEnabled = true;
                xTask.StackCorruptionDetectionLevel   = "AllInstructions";
                xTask.DebugMode                = "Source";
                xTask.TraceAssemblies          = "All";
                xTask.DebugCom                 = 1;
                xTask.UseNAsm                  = true;
                xTask.OutputFilename           = OutputFile;
                xTask.EnableLogging            = true;
                xTask.EmitDebugSymbols         = true;
                xTask.IgnoreDebugStubAttribute = false;
                xTask.References               = GetReferences();
                xTask.OnLogError               = (m) => Console.WriteLine("Error: {0}", m);
                xTask.OnLogWarning             = (m) => Console.WriteLine("Warning: {0}", m);
                xTask.OnLogMessage             = (m) =>
                {
                    Console.WriteLine("Message: {0}", m);
                };
                xTask.OnLogException = (m) => Console.WriteLine("Exception: {0}", m.ToString());

                if (xTask.Execute())
                {
                    Console.WriteLine("Executed OK");
                }
                else
                {
                    Console.WriteLine("Errorred");
                }
                xSW.Stop();
            }
            catch (Exception E)
            {
                Console.Out.Flush();
                Console.WriteLine(E.ToString());
                //Console.ReadLine();
                return;
            }
            Console.WriteLine("Run took {0}", xSW.Elapsed);
            Console.WriteLine("Generated {0} Guids", DebugInfo.GeneratedIdsCount());
            Console.Out.Flush();
            Console.ReadKey();
        }
Пример #5
0
        public void Execute()
        {
            if (String.IsNullOrWhiteSpace(OutputFile))
            {
                throw new InvalidOperationException("No OutputFile specified!");
            }
            if (References.Count == 0)
            {
                throw new InvalidOperationException("No References specified!");
            }

            DebugInfo.SetRange(DebugInfo.AssemblerDebugSymbolsRange);
            Console.WriteLine("Compiling to '{0}'", OutputFile);
            var xTask = new CompilerEngine();

            xTask.DebugEnabled = false;
            xTask.StackCorruptionDetectionEnabled = false;
            xTask.StackCorruptionDetectionLevel   = "MethodFooters";
            xTask.DebugMode                = "Source";
            xTask.TraceAssemblies          = "User";
            xTask.DebugCom                 = 1;
            xTask.UseNAsm                  = true;
            xTask.OutputFilename           = OutputFile;
            xTask.EnableLogging            = true;
            xTask.EmitDebugSymbols         = true;
            xTask.IgnoreDebugStubAttribute = false;
            xTask.References               = GetReferences();
            xTask.AssemblerLog             = AssemblerLogFile;
            xTask.OnLogError               = m =>
            {
                throw new Exception("Error during compilation: " + m);
            };
            xTask.OnLogWarning = (m) => Console.WriteLine("Warning: {0}", m);
            xTask.OnLogMessage = (m) =>
            {
                Console.WriteLine("Message: {0}", m);
            };
            xTask.OnLogException = (m) => Console.WriteLine("Exception: {0}", m.ToString());

            if (!xTask.Execute())
            {
                throw new Exception("Error occurred while running compiler!");
            }
        }
Пример #6
0
        /// <summary>
        /// The compile operation to compile the requested code unit.
        /// </summary>
        /// <param name="compileRequest">
        /// The compile request.
        /// </param>
        /// <returns>
        /// The <see cref="CompileResponse"/>.
        /// </returns>
        public CompileResponse Compile(CompileRequest compileRequest)
        {
            // TODO: Future version execution

            /*
             * FlowRequirement requirement = new FlowRequirement(compileRequest.SourceCode);
             * ExecutionFlowBuilder.Build().Execute(ContextProvider.Context, requirement);
             * */

            ICompiler   csharpCompiler = new CompilerEngine();
            CompileArgs arguments      = new CompileArgs {
                SourceCode = compileRequest.SourceCode
            };

            var result = csharpCompiler.Compile(arguments);

            return(new CompileResponse {
                CompileResult = result
            });
        }
Пример #7
0
        public static ABIExitCode Compile(ABIFileSystemOptions options, LogFactory factory)
        {
            #region Argument exceptions

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            #endregion

            _logger = factory.GetCurrentClassLogger();
            _logger.Debug(options);
            try
            {
                if (!Validate(options))
                {
                    return(ABIExitCode.ErrorDuringValidation);
                }

                var engine = new CompilerEngine(options, factory);
                var result = engine.Compile();

                Debug.Assert(result != ABIExitCode.ErrorExitCodeUnassigned);

                return(result);
            }
            catch (Exception ex) // avoid external unhandled exceptions
            {
                _logger.Error(ex);
            }

            return(ABIExitCode.ErrorUnhandledException);
        }
Пример #8
0
        public void Run()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("using CodeRank.CSharpProblems.Ruleset.Base;");
            sb.Append("namespace CodeRank.CSharpProblems.Ruleset.Solution");
            sb.Append("{");
            sb.Append("public class SampleTestRuleSolution : ISampleTest");
            sb.Append("{");
            sb.Append("public int Sum(int a, int b)");
            sb.Append("{");
            sb.Append("return a + b;");
            sb.Append("}");
            sb.Append("}");
            sb.Append("}");

            CompilerEngine engine   = new CompilerEngine();
            var            response = engine.Compile(new CompileArgs {
                SourceCode = sb.ToString()
            });

            string pathToDlls       = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            var    assemblyFilePath = Path.Combine(pathToDlls, response.AssemblyFileName);

            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
            AppDomain.CurrentDomain.Load(response.LoadedStream.ToArray());

            CoreExtensions.Host.InstallBuiltins();

            var runner = new InMemoryNunitTestRunner().RunTests(new TestRunRequest {
                TestAssembly = Assembly.Load("CodeRank.CSharpProblems.Ruleset"), SourceAssemblyStream = response.LoadedStream
            });

            Console.WriteLine(runner);
            Console.Read();
        }
Пример #9
0
        public void Compile()
        {
            using (new AppConfigManipulator())
            {
                CompilerEngine.ExecuteInSeparateAppDomain(
                    ce =>
                {
#if DEBUG
                    ce.Configuration = "DEBUG";
#else
                    ce.Configuration = "RELEASE";
#endif
                    ce.CsProject = LangPhpTestCsProj;
                    ce.OutDir    = ce.BinaryOutputDir = Path.GetTempPath();
                    ce.Referenced.Clear();

                    var types = new[]
                    {
                        typeof(Func <,>),
                        typeof(EmitContext),
                        typeof(ThisExpression),
                        typeof(CompilerEngine)
                    };
                    {
                        var tmp =
                            Assembly.Load(
                                "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        ce.Referenced.Add(tmp.GetCodeLocation().FullName);
                    }
                    ce.Referenced.AddRange(types.Select(type => type.Assembly.GetCodeLocation().FullName));


                    ce.TranlationHelpers.Clear();
                    ce.ReferencedPhpLibsLocations.Clear();
                    ce.Check();

                    using (var comp = ce.PreparePhpCompiler())
                    {
                        Console.WriteLine("Compilation");
                        var emitResult = comp.CompileCSharpProject(comp.Sandbox, ce.DllFilename);
                        if (!emitResult.Success)
                        {
                            foreach (var i in emitResult.Diagnostics.Where(a => a.Severity == DiagnosticSeverity.Error))
                            {
                                throw new Exception("Compilation error: " + i.GetMessage());
                            }
                        }


                        var translationInfo = comp.ParseCsSource();


                        translationInfo.CurrentAssembly = comp.CompiledAssembly;
                        var assemblyTi = translationInfo.GetOrMakeTranslationInfo(comp.CompiledAssembly);
                        var ecBaseDir  = Path.Combine(Directory.GetCurrentDirectory(),
                                                      assemblyTi.RootPath.Replace("/", "\\"));
                        Console.WriteLine("Output root {0}", ecBaseDir);

                        var translationState = new TranslationState(translationInfo);
                        var translator       = new Translator(translationState);

                        translator.Translate(comp.Sandbox);

                        // =============
                        var m =
                            string.Join(", ", translator.Modules.Select(i => i.Name.Name).OrderBy(i => i)).ToArray();

                        //Assert.True(m == "Lang_Php_Test_Code_MyCode, Lang_Php_Test_Code_SampleEmptyClass", m);

                        MethodTranslation(ModuleMycode, ClassMycode, "BasicMath1", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "Collections", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "CostantsAndVariables", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "Filters", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "StringConcats", translator);
                        MethodTranslation(ModuleMycode, ClassMycode, "PregTest", translator);

//                            ModuleTranslation("Lang_Php_Test_Code_SampleEmptyClass", translator);
//                            ModuleTranslation("Lang_Php_Test_Code_BusinessClass", translator);
//                            ModuleTranslation("Lang_Php_Test_Code_BusinessClassDefinedConst", translator);

                        foreach (var moduleName in translator.Modules.Select(i => i.Name.Name))
                        {
                            ModuleTranslation(moduleName, translator);
                        }
                    }
                    ;
                }, AppDomain.CurrentDomain);
            }
        }
Пример #10
0
        private static int Main(string[] args)
        {
            try {
                var tmp = "";
                foreach (var s in args)
                {
                    tmp += s;
                    string[] s1    = s.Split(':');
                    string   argID = s1[0].ToLower();
                    if (argID != "References".ToLower())
                    {
                        CmdOptions.Add(argID, s.Replace(s1[0] + ":", ""));
                    }
                    else
                    {
                        References.Add(s.Replace(s1[0] + ":", ""));
                    }
                }
                //File.WriteAllText("C:\\Users\\Emile\\Desktop\\dump.txt",tmp);

                var xTask = new CompilerEngine();
                xTask.DebugEnabled = Convert.ToBoolean(CmdOptions["DebugEnabled".ToLower()]);
                Console.WriteLine("Loaded : DebugEnabled");
                xTask.StackCorruptionDetectionEnabled = Convert.ToBoolean(CmdOptions["StackCorruptionDetectionEnabled".ToLower()]);
                Console.WriteLine("Loaded : StackCorruptionDetectionEnabled");
                xTask.DebugMode = CmdOptions["DebugMode".ToLower()];
                Console.WriteLine("Loaded : DebugMode");
                xTask.TraceAssemblies = null;
                Console.WriteLine("Loaded : TraceAssemblies");
                xTask.DebugCom = Convert.ToByte(CmdOptions["DebugCom".ToLower()]);
                Console.WriteLine("Loaded : DebugCom");
                xTask.UseNAsm = Convert.ToBoolean(CmdOptions["UseNAsm".ToLower()]);
                Console.WriteLine("Loaded : UseNAsm");
                xTask.OutputFilename = CmdOptions["OutputFilename".ToLower()];;
                Console.WriteLine("Loaded : OutputFilename");
                xTask.EnableLogging = Convert.ToBoolean(CmdOptions["EnableLogging".ToLower()]);;
                Console.WriteLine("Loaded : EnableLogging");
                xTask.EmitDebugSymbols = Convert.ToBoolean(CmdOptions["EmitDebugSymbols".ToLower()]);;
                Console.WriteLine("Loaded : EmitDebugSymbols");
                xTask.IgnoreDebugStubAttribute = Convert.ToBoolean(CmdOptions["IgnoreDebugStubAttribute".ToLower()]);
                Console.WriteLine("Loaded : IgnoreDebugStubAttribute");
                xTask.References = References.ToArray();
                Console.WriteLine("Loaded : References");

                xTask.OnLogError   = (m) => Console.Error.WriteLine("Error: {0}", m);
                xTask.OnLogWarning = (m) => Console.WriteLine("Warning: {0}", m);
                xTask.OnLogMessage = (m) =>
                {
                    Console.WriteLine("Message: {0}", m);
                };
                xTask.OnLogException = (m) => Console.Error.WriteLine("Exception: {0}", m.ToString());
                xTask.AssemblerLog   = "Cosmos.Assembler.log";
                if (xTask.Execute())
                {
                    Console.WriteLine("Executed OK");
//          File.WriteAllText(@"e:\compiler.log", "OK");
                    return(0);
                }
                else
                {
                    Console.WriteLine("Errorred");
//          File.WriteAllText(@"e:\compiler.log", "Errored");
                    return(2);
                }
            }
            catch (Exception E)
            {
                // Console.Out.Flush();
                // File.WriteAllText("./ErrorDump.txt",E.ToString()  + " " + E.Source);
                Console.WriteLine("Error occurred: " + E.ToString());
//        File.WriteAllText(@"e:\compiler.log", "Exception: " + E.ToString());
                return(1);
            }
        }
Пример #11
0
        public static int Run(string[] args, Action <string> logMessage, Action <string> logError)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (logMessage == null)
            {
                throw new ArgumentNullException("logMessage");
            }
            if (logError == null)
            {
                throw new ArgumentNullException("logError");
            }

            try
            {
                var tmp = "";
                foreach (var s in args)
                {
                    tmp += s;
                    string[] s1    = s.Split(':');
                    string   argID = s1[0].ToLower();
                    if (argID != "References".ToLower())
                    {
                        CmdOptions.Add(argID, s.Replace(s1[0] + ":", ""));
                    }
                    else
                    {
                        References.Add(s.Replace(s1[0] + ":", ""));
                    }
                }

                var xTask = new CompilerEngine();
                xTask.DebugEnabled = Convert.ToBoolean(CmdOptions["DebugEnabled".ToLower()]);
                logMessage("Loaded : DebugEnabled");
                xTask.StackCorruptionDetectionEnabled = Convert.ToBoolean(CmdOptions["StackCorruptionDetectionEnabled".ToLower()]);
                logMessage("Loaded : StackCorruptionDetectionEnabled");
                xTask.DebugMode = CmdOptions["DebugMode".ToLower()];
                logMessage("Loaded : DebugMode");
                xTask.TraceAssemblies = null;
                logMessage("Loaded : TraceAssemblies");
                xTask.DebugCom = Convert.ToByte(CmdOptions["DebugCom".ToLower()]);
                logMessage("Loaded : DebugCom");
                xTask.UseNAsm = Convert.ToBoolean(CmdOptions["UseNAsm".ToLower()]);
                logMessage("Loaded : UseNAsm");
                xTask.OutputFilename = CmdOptions["OutputFilename".ToLower()];;
                logMessage("Loaded : OutputFilename");
                xTask.EnableLogging = Convert.ToBoolean(CmdOptions["EnableLogging".ToLower()]);;
                logMessage("Loaded : EnableLogging");
                xTask.EmitDebugSymbols = Convert.ToBoolean(CmdOptions["EmitDebugSymbols".ToLower()]);;
                logMessage("Loaded : EmitDebugSymbols");
                xTask.IgnoreDebugStubAttribute = Convert.ToBoolean(CmdOptions["IgnoreDebugStubAttribute".ToLower()]);
                logMessage("Loaded : IgnoreDebugStubAttribute");
                xTask.References = References.ToArray();
                logMessage("Loaded : References");

                xTask.OnLogError     = logError;
                xTask.OnLogWarning   = m => logMessage(String.Format("Warning: {0}", m));
                xTask.OnLogMessage   = logMessage;
                xTask.OnLogException = (m) => logError(String.Format("Exception: {0}", m.ToString()));
                xTask.AssemblerLog   = "Cosmos.Assembler.log";
                if (xTask.Execute())
                {
                    logMessage("Executed OK");
                    //          File.WriteAllText(@"e:\compiler.log", "OK");
                    return(0);
                }
                else
                {
                    logMessage("Errorred");
                    //          File.WriteAllText(@"e:\compiler.log", "Errored");
                    return(2);
                }
            }
            catch (Exception E)
            {
                logError(String.Format("Error occurred: " + E.ToString()));
                return(1);
            }
        }