Esempio n. 1
0
 private async Task<CompilationResult> CompileWith(ICompiler compiler, string contentId, IFile file)
 {
     CompilationResult result = await compiler.Compile(file);
     if (result.Success)
     {
         Cache[contentId] = new WeakReference<Type>(result.GetCompiledType());
     }
     return result;
 }
Esempio n. 2
0
        public void CanUseAssemblyFromSourceFile()
        {
            ICompiler c = Compiler.Create();

            c.AssemblyName = "Assem12";
            c.AddReferences(new string[] { "System.Int32", "System.Double", "System.IO.Path" });
            string tmpFile = Path.Combine(Path.GetTempPath(), "DynamicCSharpTest.cs");

            using (var outFile = new StreamWriter(tmpFile, false))
                outFile.Write(source);
            c.Source = null;
            using (c.SourceStream = new FileStream(tmpFile, FileMode.Open, FileAccess.Read))
                c.Compile();
            File.Delete(tmpFile);
            Type type = c.Assembly.ExportedTypes.Where(t => t.Name == "Joe").FirstOrDefault();
            var  joe  = Activator.CreateInstance(type);

            Assert.IsType(type, joe);
            var getNextInt = (Func <int>)Delegate
                             .CreateDelegate(typeof(Func <int>), joe, type.GetMethod("GetNextInt"));

            Assert.Equal(1, getNextInt());
            Assert.Equal(2, getNextInt());
        }
Esempio n. 3
0
        public void test(string src)
        {
            var domain = AppDomain.CreateDomain(new Random().Next(int.MaxValue).ToString());

            var writer = new StringWriterWithEvent();

            writer.Written += (str) => Console.WriteLine("=====" + str);

            var thisAssemblyName = Assembly.GetExecutingAssembly().FullName;
            var console          = domain.CreateInstanceAndUnwrap(thisAssemblyName, "lib.ConsoleWriterControl") as ConsoleWriterControl;

            console.SetOut(writer);
            console.SetError(writer);

            // 別スレッドでつくったコンパイラでもちゃんと動作する?
            ICompiler compiler = null;

            Task.Factory.StartNew(() =>
            {
                compiler = domain.CreateInstanceAndUnwrap("compiler", "compiler.Compiler") as ICompiler;
            }).Wait();

            if (compiler != null && compiler.Compile(src))
            {
                var instance = compiler.CreateInstance("Test");
                instance.InvokeMethod("Void", null);
            }

            Console.Error.WriteLine("hogehoge");

            console.Dispose();
            AppDomain.Unload(domain);

            // compiler.dll をちゃんと手放してるかどうかチェック
            //File.Delete("compiler.dll");
        }
Esempio n. 4
0
        Assembly CompileCommands(string path)
        {
            ICompiler compiler = GetCompiler(path);

            if (compiler == null)
            {
                Popup.Warning("Unsupported file '" + path + "'");
                return(null);
            }

            ConsoleHelpPlayer p      = new ConsoleHelpPlayer();
            CompilerResults   result = compiler.Compile(path, null);

            if (!result.Errors.HasErrors)
            {
                return(result.CompiledAssembly);
            }

            ICompiler.SummariseErrors(result, p);
            string body = "\r\n\r\n" + Colors.StripUsed(p.Messages);

            Popup.Error("Compilation error. See logs/errors/compiler.log for more details." + body);
            return(null);
        }
Esempio n. 5
0
 protected override void PrepareForRunning(string codeFileName)
 {
     _execFileName = _compiler.Compile(codeFileName);
 }
Esempio n. 6
0
 private void ExecuteScript()
 {
     compiler.Compile(syntaxBox.Document.Text);
 }
Esempio n. 7
0
        static void Main(string[] args)
        {
            CompilerType compilerType = ReadCompilerType();
            ICompiler    compiler     = BaseCompiler.CreateCompiler(compilerType);

            Console.WriteLine("Enter file path.");
            string sourceFilePath = Console.ReadLine();
            string source         = File.ReadAllText(sourceFilePath);

            string fileName = Path.GetRandomFileName();

            if (compilerType == CompilerType.Java)
            {
                fileName = GetClassName(source);
            }
            string workingDirectory = Environment.CurrentDirectory + "\\" + Guid.NewGuid().ToString();

            Directory.CreateDirectory(workingDirectory);

            WriteSourceToFile(source, compilerType, workingDirectory, fileName);
            CompileResult compileResult = compiler.Compile(new CompilerArguments(fileName, workingDirectory, new List <string> {
                source
            }));

            if (!compileResult.IsSuccessfull)
            {
                Console.WriteLine($"Compile time error: {compileResult.Errors}");
                return;
            }

            IExecutor executor              = BaseExecutor.CreateExecutor(compilerType);
            string    compiledFileName      = Path.GetFileName(compileResult.CompiledFilePath);
            string    compiledFileDirectory = Path.GetDirectoryName(compileResult.CompiledFilePath);

            Console.WriteLine("Enter inputs to test the program. If you want to stop enter 'stop'!");
            string input = string.Empty;

            while ((input = Console.ReadLine()) != "stop")
            {
                ProcessExecutionResult processExecutionResult = executor.Execute(input, compiledFileName, compiledFileDirectory).GetAwaiter().GetResult();

                if (processExecutionResult.IsSuccesfull && processExecutionResult.Type == ProcessExecutionResultType.Success)
                {
                    Console.WriteLine("The application was run seccessfully!");
                    Console.WriteLine(processExecutionResult.ReceivedOutput);
                }
                else
                {
                    Console.WriteLine("Some errors occured!");
                    Console.WriteLine(processExecutionResult.ErrorOutput);
                }

                Console.WriteLine("Process statistics");
                Console.WriteLine($"Exit code: {processExecutionResult.ExitCode}");
                Console.WriteLine($"Memory Used: {processExecutionResult.MemoryUsed}");
                Console.WriteLine($"Processor time used: {processExecutionResult.TotalProcessorTime}");
                Console.WriteLine($"Working time: {processExecutionResult.TimeWorked}");
                Console.WriteLine($"Execution Type: {processExecutionResult.Type}");
                Console.WriteLine(new string('-', 50));
            }

            DeleteWorkingDirectory(workingDirectory);
        }
Esempio n. 8
0
        private CompilerResult ProcessConfig(string baseFolder, Config config)
        {
            ICompiler compiler = CompilerService.GetCompiler(config);

            var result = compiler.Compile(config);

            if (result.Errors.Any(e => !e.IsWarning))
            {
                return(result);
            }

            if (Path.GetExtension(config.OutputFile).Equals(".css", StringComparison.OrdinalIgnoreCase) && AdjustRelativePaths(config))
            {
                result.CompiledContent = CssRelativePath.Adjust(result.CompiledContent, config);
            }

            config.Output = result.CompiledContent;

            FileInfo outputFile      = config.GetAbsoluteOutputFile();
            bool     containsChanges = FileHelpers.HasFileContentChanged(outputFile.FullName, config.Output);

            OnBeforeProcess(config, baseFolder, containsChanges);

            if (containsChanges)
            {
                string dir = outputFile.DirectoryName;

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                File.WriteAllText(outputFile.FullName, config.Output, new UTF8Encoding(true));
            }

            OnAfterProcess(config, baseFolder, containsChanges);

            //if (!config.Minify.ContainsKey("enabled") || config.Minify["enabled"].ToString().Equals("true", StringComparison.OrdinalIgnoreCase))
            //{
            FileMinifier.MinifyFile(config);
            //}

            if (!string.IsNullOrEmpty(result.SourceMap))
            {
                string absolute  = config.GetAbsoluteOutputFile().FullName;
                string mapFile   = absolute + ".map";
                bool   smChanges = FileHelpers.HasFileContentChanged(mapFile, result.SourceMap);

                OnBeforeWritingSourceMap(absolute, mapFile, smChanges);

                if (smChanges)
                {
                    File.WriteAllText(mapFile, result.SourceMap, new UTF8Encoding(true));
                }

                OnAfterWritingSourceMap(absolute, mapFile, smChanges);
            }

            Telemetry.TrackCompile(config);

            return(result);
        }
Esempio n. 9
0
        CompileResult Compile(IAsset asset, StreamReader input)
        {
            var context = CreateCompileContext(asset);

            return(compiler.Compile(input.ReadToEnd(), context));
        }
Esempio n. 10
0
        /// <summary>
        /// 评测此任务
        /// </summary>
        /// <returns>评测结果</returns>
        public JudgeResult Judge()
        {
            //判题结果
            JudgeResult result = new JudgeResult
            {
                SubmitID    = JudgeTask.SubmitID,
                ProblemID   = JudgeTask.ProblemID,
                Author      = JudgeTask.Author,
                JudgeDetail = "",
                MemoryCost  = 0,
                TimeCost    = 0,
                PassRate    = 0,
                ResultCode  = JudgeResultCode.Accepted
            };

            //正则恶意代码检查
            if (!CodeChecker.Singleton.CheckCode(JudgeTask.SourceCode, JudgeTask.Language, out string unsafeCode, out int line))
            {
                result.ResultCode   = JudgeResultCode.CompileError;
                result.JudgeDetail  = "Include unsafe code, please remove them!";
                result.JudgeDetail += "\r\n";
                result.JudgeDetail += "line " + line + ": " + unsafeCode;
                return(result);
            }

            //创建临时目录
            if (!Directory.Exists(JudgeTask.TempJudgeDirectory))
            {
                Directory.CreateDirectory(JudgeTask.TempJudgeDirectory);
            }

            //写出源代码
            string sourceFileName = JudgeTask.TempJudgeDirectory + Path.DirectorySeparatorChar + JudgeTask.LangConfig.SourceCodeFileName;

            File.WriteAllText(sourceFileName, JudgeTask.SourceCode);

            //编译代码
            if (JudgeTask.LangConfig.NeedCompile)
            {
                ICompiler compiler = CompilerFactory.Create(JudgeTask);
                //使用分配的独立处理器核心
                compiler.ProcessorAffinity = _affinity.Affinity;

                string compileRes = compiler.Compile(JudgeTask.LangConfig.CompilerArgs);

                //检查是否有编译错误(compileRes不为空则代表有错误)
                if (!string.IsNullOrEmpty(compileRes))
                {
                    result.JudgeDetail = compileRes.Replace(JudgeTask.TempJudgeDirectory, "");//去除路径信息
                    result.ResultCode  = JudgeResultCode.CompileError;
                    return(result);
                }
            }


            //创建单例Judger
            ISingleJudger judger = SingleJudgerFactory.Create(JudgeTask);

            judger.ProcessorAffinity = _affinity.Affinity;

            //获取所有测试点文件名
            Tuple <string, string>[] dataFiles = TestDataManager.GetTestDataFilesName(JudgeTask.ProblemID);
            if (dataFiles.Length == 0)//无测试数据
            {
                result.ResultCode  = JudgeResultCode.JudgeFailed;
                result.JudgeDetail = "No test data.";
                return(result);
            }

            int acceptedCasesCount = 0;//通过的测试点数

            for (int i = 0; i < dataFiles.Length; i++)
            {
                try
                {
                    TestDataManager.GetTestData(JudgeTask.ProblemID, dataFiles[i].Item1, dataFiles[i].Item2, out string input, out string output); //读入测试数据

                    SingleJudgeResult singleRes = judger.Judge(input, output);                                                                     //测试此测试点

                    //计算有时间补偿的总时间
                    result.TimeCost   = Math.Max(result.TimeCost, (int)(singleRes.TimeCost * JudgeTask.LangConfig.TimeCompensation));
                    result.MemoryCost = Math.Max(result.MemoryCost, singleRes.MemoryCost);

                    if (singleRes.ResultCode == JudgeResultCode.Accepted)
                    {
                        acceptedCasesCount++;
                    }
                    else
                    {
                        result.ResultCode  = singleRes.ResultCode;
                        result.JudgeDetail = singleRes.JudgeDetail;
                        break;
                    }
                }
                catch (Exception e)
                {
                    result.ResultCode  = JudgeResultCode.JudgeFailed;
                    result.JudgeDetail = e.ToString();
                    break;
                }
            }

            //去除目录信息
            result.JudgeDetail = result.JudgeDetail.Replace(JudgeTask.TempJudgeDirectory, "");

            //通过率
            result.PassRate = (double)acceptedCasesCount / dataFiles.Length;

            return(result);
        }
    static void VerifyAssemblyVersion(ICompiler compiler, AssemblyVersioningScheme avs, string assemblyInformationalFormat = null)
    {
        var semanticVersion = new SemanticVersion
        {
            Major = 2,
            Minor = 3,
            Patch = 4,
            PreReleaseTag = "beta.5",
            BuildMetaData = new SemanticVersionBuildMetaData(6,
                "master", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")),
        };

        var config = new TestEffectiveConfiguration(assemblyVersioningScheme: avs, assemblyInformationalFormat: assemblyInformationalFormat);

        var versionVariables = VariableProvider.GetVariablesFor(semanticVersion, config, false);
        var assemblyInfoText = compiler.Builder.GetAssemblyInfoText(versionVariables, "Fake");
        assemblyInfoText.ShouldMatchApproved(c => c.UseCallerLocation().SubFolder(compiler.ApprovedSubFolder));

        var compilation = compiler.Compile(assemblyInfoText);

        var emitResult = compilation.Emit(new MemoryStream());
        Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Descriptor)));
    }
Esempio n. 12
0
        private void _GenerateCodeAndCompile_v2(IGenerateAndExecute generateAndExecute, string code, bool compileWithoutProject = false)
        {
            // use CompilerDefaultValues from runsource.runsource.config.xml runsource.runsource.config.local.xml

            if (code == "")
            {
                return;
            }

            CompilerProject compilerProject = null;

            if (!compileWithoutProject)
            {
                compilerProject = GetProjectCompilerProject();
            }
            if (compilerProject == null)
            {
                compilerProject = GetDefaultProject();
            }

            if (compilerProject != null)
            {
                generateAndExecute.NameSpace = compilerProject.GetNameSpace();
            }

            if (compilerProject != null)
            {
                generateAndExecute.AddUsings(compilerProject.GetUsings());
            }

            generateAndExecute.GenerateCSharpCode(code);

            SetCompilerValues(generateAndExecute, compilerProject);

            ICompiler compiler = generateAndExecute.Compiler;

            //Compiler compiler = new Compiler();
            //compiler.SetOutputAssembly(assemblyFilename);
            //compiler.AddSource(new CompilerFile(file));
            compiler.Compile();
            //Assembly assembly = _compiler.Results.CompiledAssembly;

            if (compiler.HasError())
            {
                //DataTable dtMessage = compiler.GetCompilerMessagesDataTable();
                //if (dtMessage != null)
                //{
                //    gdtResult = dtMessage;
                //    gdsResult = null;
                //    gsXmlResultFormat = null;
                //    if (ErrorResultSet != null)
                //        ErrorResultSet(gdtResult, null);
                //}
                SetResultCompilerMessages(compiler);
            }
            else
            {
                // trace warning
                compiler.TraceMessages();
            }
        }
Esempio n. 13
0
        public IDataProcessor Build()
        {
            if (_state != 0)
            {
                throw new InvalidOperationException();
            }
            _state = 1;

            using (Timer.Step("DataProcessorBuilder.Build"))
            {
                // flatten tree into list where dependants come later
                var queue = ProcessorInfo.SortDependenciesFirst(_nodes);

                // loop through processors, adding them to their source writers
                for (var ix = 0; ix < queue.Count; ix++)
                {
                    var o = queue[ix];

                    var needsSplit = o.GetSourceWriters().Count() > 1;

                    // if the processor needs data from multiple writers,
                    // then insert an intermediate node to store the state
                    if (needsSplit)
                    {
                        var newNodes = o.Split(out WriterInfo newWriter);
                        _writers.Add(newWriter);

                        // update the queue
                        queue.RemoveAt(ix);
                        queue.InsertRange(ix, newNodes);

                        // reprime the current node
                        o = queue[ix];
                    }

                    var w = o.GetSourceWriters().SingleOrDefault();

                    // no source writer, then nothing to do
                    if (w == null)
                    {
                        Log.Warn($"No source writer for: {o.Name}");
                        continue;
                    }

                    // add it to the writer
                    w.Append(o);
                }

                // loop through the writers, compiling each one
                foreach (var w in _writers)
                {
                    var expr = w.GetFinalLambda();

                    if (Log.IsVerbose)
                    {
                        Log.Verbose($"Compiling writer: {w.Name}", expr);
                    }

                    var action = _compiler.Compile(w.Name, expr);
                    w.Writer.SetAction(action);
                }

                // return the data processor
                var cs = _writers.Select(w => w.Writer)
                         .OfType <IClosable>()
                         .ToArray();
                return(new DataProcessor(cs));
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Verifies the solution compiles.
 /// </summary>
 /// <param name="solutionContext">The solution context.</param>
 /// <returns></returns>
 private Result <SolutionContext> VerifySolutionCompiles(SolutionContext solutionContext)
 => _compiler
 .Compile(solutionContext.ProjectContext, _log)
 .ToTypedResult(solutionContext);
        public void Setup()
        {
            _compilerMock = Substitute.For<ICompiler>();
            _solutionExplorerMock = Substitute.For<ISolutionExplorer>();
            _testRunnerMock = Substitute.For<ITestRunner>();
            _compiledAllItems = new List<ICompiledItem>();
            _compiledSingleProjectItems=new List<ICompiledItem>();
            _testExplorerMock = Substitute.For<ITestExplorer>();

            _testExplorerMock.SolutionExplorer.Returns(_solutionExplorerMock);

            _sut = new LineCoverageCalc(_testExplorerMock,
                _compilerMock,
                _testRunnerMock);

            _compilerMock.Compile(Arg.Any<CompilationItem>(), Arg.Any<IEnumerable<string>>())
                .Returns((x) => _compiledSingleProjectItems.ToArray());

            _compilerMock.Compile(Arg.Any<IEnumerable<CompilationItem>>())
                .Returns((x) => _compiledAllItems.ToArray());
        }
Esempio n. 16
0
        /// <summary>
        /// Attempts to compile the specified C# source content.
        /// </summary>
        /// <param name="sourceContent">The string source content array containing the C# source code</param>
        /// <param name="extraReferences">Any additional assembly reference names</param>
        /// <returns>True if the compile was successful or false if there were one or more errors</returns>
        public bool CompileSources(string[] sourceContent, params string[] extraReferences)
        {
            // Set the compiling flag
            isCompiling = true;
            // Reset result
            assemblyData = null;

            // Reset errors
            errors       = new string[0];
            warnings     = new string[0];
            assemblyData = null;

            byte[] assemblyResult = null;
            ScriptCompilerError[] compileResult = null;

            lock (compilerLock)
            {
                // Register references
                compiler.AddReferences(extraReferences);

                // Invoke the compiler
                compileResult = compiler.Compile(sourceContent);

                // Get assembly data
                assemblyResult = compiler.AssemblyData;
            }

            // Success flag
            bool successful = true;

            foreach (ScriptCompilerError err in compileResult)
            {
                if (err.isWarning == true)
                {
                    // Generate a warning
                    AddWarning(err.errorCode, err.errorText, err.fileName, err.line, err.column);
                }
                else
                {
                    // Set flag
                    successful     = false;
                    errorLineValue = err.line;


                    if (err.line != 0)
                    {
                        UnityEngine.Debug.Log("eeeeeeee" + err.line);
                        UnityEngine.GameObject.Find("ErrorShowLine").GetComponent <UnityEngine.RectTransform>().localPosition = new UnityEngine.Vector3(0, 481f - (16f * (err.line - 2)), 0);
                    }
                    // Generate an error
                    AddError(err.errorCode, err.errorText, err.fileName, err.line, err.column);
                }
            }

            // Check for success
            if (successful == true)
            {
                assemblyData = assemblyResult;
            }

            // Set the compiling flag
            isCompiling = false;

            // Check for success
            return(successful);
        }
Esempio n. 17
0
        private async Task <bool> CompileSingleFile(ICompiler compiler, string filePath)
        {
            //dependencies
            var shell     = IoC.Get <IShell>();
            var output    = IoC.Get <IOutput>();
            var errorList = IoC.Get <IErrorList>();
            var statusBar = IoC.Get <IStatusBar>();

            //semaphore and mutex for multi-processing
            var semaphore = 1;
            var completed = false;

            //final result
            var result = false;

            //show output
            shell.ShowTool(output);

            //reset output
            output.Clear();
            output.AppendLine($"----- {Resources.CompileSingleFileStartOutput}");

            // reset error list
            errorList.Clear();

            // reset status bar first item
            if (statusBar.Items.Count == 0)
            {
                statusBar.AddItem(Resources.CompileSingleFileStartOutput,
                                  new System.Windows.GridLength(1, System.Windows.GridUnitType.Auto));
            }
            else
            {
                statusBar.Items[0].Message = Resources.CompileSingleFileStartOutput;
            }

            //handle compile events
            EventHandler <string> outputReceivedHandler = delegate(object s, string data)
            {
                while (semaphore <= 0)
                {
                }

                semaphore--;
                if (!string.IsNullOrWhiteSpace(data))
                {
                    output.AppendLine($"> {data}");
                }
                semaphore++;
            };

            CompilerExitedEventHandler compileExitedHandler = null;

            compileExitedHandler = delegate(IEnumerable <CompileError> errors, IEnumerable <CompileError> warnings)
            {
                //check for errors
                var compileErrors   = errors as IList <CompileError> ?? errors.ToList();
                var compileWarnings = warnings as IList <CompileError> ?? warnings.ToList();

                //show error(s)
                foreach (var error in compileErrors)
                {
                    errorList.AddItem(ErrorListItemType.Error, error.Code, error.Description, error.Path, error.Line,
                                      error.Column);
                }
                //show warning(s)
                foreach (var warning in compileWarnings)
                {
                    errorList.AddItem(ErrorListItemType.Warning, warning.Code, warning.Description, warning.Path,
                                      warning.Line,
                                      warning.Column);
                }
                if (compileErrors.Any() || compileWarnings.Any())
                {
                    shell.ShowTool(errorList);
                }

                //result
                if (!compileErrors.Any())
                {
                    //no error
                    result = true;
                    output.AppendLine($"----- {Resources.CompileSingleFileFinishSuccessfullyOutput}");
                    statusBar.Items[0].Message = Resources.CompileSingleFileFinishSuccessfullyOutput;
                }
                else
                {
                    //has error(s)
                    result = false;
                    output.AppendLine($"----- {Resources.CompileSingleFileFailedOutput}");
                    statusBar.Items[0].Message = Resources.CompileSingleFileFailedOutput;
                }

                // release subcribed delegate
                compiler.OutputDataReceived -= outputReceivedHandler;
                compiler.OnExited           -= compileExitedHandler;
                completed = true;
            };
            compiler.OutputDataReceived += outputReceivedHandler;
            compiler.OnExited           += compileExitedHandler;

            // compile
            compiler.Compile(filePath, Path.GetDirectoryName(FilePath));

            // wait for compilation finish
            while (!completed)
            {
                await Task.Delay(25);
            }
            return(result);
        }
Esempio n. 18
0
        public PostfixNotation CompileToPostfix(string expression)
        {
            var rawNotation = grammarCompiler.Compile(expression);

            return(shuntingYard.ConvertToPostfix(rawNotation));
        }