public void SimpleExpression1_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"simple expression1.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH; G.Directives["TinyPG"]["OutputPath"] = OUTPUTPATH; // basic checks string temp = G.PrintFirsts(); Assert.IsTrue(!String.IsNullOrEmpty(temp)); temp = G.GetOutputPath(); Assert.IsTrue(!String.IsNullOrEmpty(temp)); temp = G.PrintGrammar(); Assert.IsTrue(!String.IsNullOrEmpty(temp)); Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("5+7/3*2+(4*2)"); Assert.IsTrue(result.Output.StartsWith("Parse was successful.")); }
public async Task CompilingCode_ThatDoesCompile_CompilesLoadableCode() { var playground = PlaygroundWorkspace.FromSource(SourceCodeKind.Regular, SampleCode.CompilerTest); CompilerResult result = await playground.CompileAsync(); Assert.IsTrue(result.Success); CollectionAssert.IsEmpty(result.Diagnostics); if (result.Success) { Assembly assembly = AppDomain.CurrentDomain.Load(result.Assembly); Type[] sourceTypes = assembly.GetTypes(); Type sourceType = sourceTypes.Single(); MethodInfo main = sourceType.GetMethod("Sample"); var invokeResult = main.Invoke(null, new object[] { new List <string> { "asdf1", "asdf" } }); Assert.IsAssignableFrom <string>(invokeResult); Assert.AreEqual("asdf1, asdf, From Source", invokeResult); } }
protected override void UpdateMargin(CompilerResult result) { if (_browser == null) { return; } // The Markdown compiler cannot return errors string html = String.Format(CultureInfo.InvariantCulture, @"<!DOCTYPE html> <html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml""> <head> <meta charset=""utf-8"" /> <base href=""file:///{0}/""> <title>Markdown Preview</title> {1} </head> <body>{2}</body> </html>", Path.GetDirectoryName(Document.FilePath).Replace("\\", "/"), GetStylesheet(), result.Result); if (_document == null) { _browser.NavigateToString(html); return; } _cachedPosition = _document.documentElement.getAttribute("scrollTop"); _cachedHeight = Math.Max(1.0, _document.body.offsetHeight); _positionPercentage = _cachedPosition * 100 / _cachedHeight; _browser.NavigateToString(html); }
public async Task UndefinedVariable() { CompilerResult result = await Execute("undefined-variable.less"); Assert.IsTrue(result.HasError); Assert.IsFalse(File.Exists(result.OutputFile)); }
public CompileMultipleTestsSourceResponse(Guid id, CompilerResult result, SandboxResponseStatus status, IReadOnlyList <CompileTestSourceResponse> results) : base(id, CompileRequestType.MultipleTests, result) { this.Results = results; this.Status = status; }
public override async Task <CompilerResult> CompileAsync(string code) { var assemblyPath = Path.Combine(Options.TemporaryCompilationLocation, $"{Options.AssemblyName}.data"); CompilerResult result; if (File.Exists(assemblyPath)) { File.Delete(assemblyPath); } var compilerParameters = new CompilerParameters { GenerateExecutable = Options.OutputType != OutputType.DynamicLinkLibrary, GenerateInMemory = false, TreatWarningsAsErrors = true, IncludeDebugInformation = false, OutputAssembly = assemblyPath }; if (Options.ReferencesAssemblyLocations != null) { compilerParameters.ReferencedAssemblies.AddRange(Options.ReferencesAssemblyLocations); } try { var compilationResult = _compiler.CompileAssemblyFromSource(compilerParameters, code); result = new CompilerResult(); if (compilationResult.Errors.Count > 0) { foreach (var compilationError in compilationResult.Errors) { result.Errors.Add(compilationError.ToString()); } } else { using (var fileStream = File.OpenRead(assemblyPath)) { using (var ms = new MemoryStream()) { await fileStream.CopyToAsync(ms); result.Assembly = ms.ToArray(); }; } } } catch (Exception ex) { throw new CompilerException(ex.Message, ex); } if (File.Exists(assemblyPath)) { File.Delete(assemblyPath); } return(result); }
public async Task AutoPrefix() { CompilerResult result = await Execute("autoprefix.less"); Assert.IsFalse(result.HasError); Assert.AreEqual("body {\n transition: ease;\n}\n", File.ReadAllText(result.OutputFile)); }
protected override void UpdateMargin(CompilerResult result) { if (_browser == null) return; // The Markdown compiler cannot return errors string html = String.Format(CultureInfo.InvariantCulture, @"<!DOCTYPE html> <html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml""> <head> <meta charset=""utf-8"" /> <base href=""file:///{0}/""> <title>Markdown Preview</title> {1} </head> <body>{2}</body> </html>", Path.GetDirectoryName(Document.FilePath).Replace("\\", "/"), GetStylesheet(), result.Result); if (_document == null) { _browser.NavigateToString(html); return; } _cachedPosition = _document.documentElement.getAttribute("scrollTop"); _cachedHeight = Math.Max(1.0, _document.body.offsetHeight); _positionPercentage = _cachedPosition * 100 / _cachedHeight; _browser.NavigateToString(html); }
/// <inheritdoc cref="CompileResponseBase"/> /// <summary> /// Creates a new instance of the compile source response. /// </summary> /// <param name="id"></param> /// <param name="result"></param> /// <param name="standardOutput">The output of the compile.</param> /// <param name="standardErrorOutput">The error out of the compile.</param> /// <param name="status">The status of the sandbox after finishing.</param> public CompileSourceResponse(Guid id, IReadOnlyList <string> standardOutput, IReadOnlyList <string> standardErrorOutput, CompilerResult result, SandboxResponseStatus status) : base(id, CompileRequestType.Compile, result) { this.StandardOutput = standardOutput; this.StandardErrorOutput = standardErrorOutput; this.Status = status; }
/// <summary> /// Takes in a tsql string, analyzes it and return all found data queries and data manipulations /// </summary> /// <param name="tsqlContent">A string containing tsql</param> /// <param name="serverName">The name of the server on which the tsql is executed on</param> /// <param name="databaseName">The initial database this tsql is targeting</param> /// <param name="causer">The name of the entity that executes this sql e.g. the name of a script</param> /// <param name="options">Options for how the compiler should perform the analysis</param> /// <returns>The compiler result containing all queries and manipulations</returns> public CompilerResult Compile(string tsqlContent, string serverName, string databaseName, string causer, CompilerOptions options) { context = new CompilerContext(causer, serverName, databaseName, options.ConsiderQueries); result = new CompilerResult(); AnalyzeTSQLContentString(tsqlContent, context); return(result); }
public CompilerResult CompileFromPlainText(Participant participant, string code) { CompilerResult compResultTest = new CompilerResult { CompilationTime = 100, StandardError = "", StandardOutput = "Hello World!" }; return(compResultTest); }
public static string CompilePlcSoftware(PlcSoftware plcSoftware) { string message = null; ICompilable compilePLC = plcSoftware.GetService <ICompilable>(); CompilerResult result = compilePLC.Compile(); message = WriteCompilerResults(result); return(message); }
public static string CompileHmiTarget(HmiTarget hmiTarget) { string message = null; ICompilable compileHMI = hmiTarget.GetService <ICompilable>(); CompilerResult result = compileHMI.Compile(); message = WriteCompilerResults(result); return(message); }
public async Task SourceMap() { CompilerResult result = await Execute("sourcemap.less"); string mapFile = Path.ChangeExtension(result.OutputFile, ".css.map"); Assert.IsFalse(result.HasError); Assert.IsTrue(File.Exists(result.OutputFile)); Assert.IsTrue(File.Exists(mapFile)); }
public void Build_ResultContainsTemplateCollectionWrappedInFunction() { IList <string> templateCollection = new List <string> { "a", "b" }; var sut = new RazorJSTemplateBuilder(templateCollection, this._helperCollection.Object); CompilerResult result = sut.Build(); Assert.AreEqual("function (Model) {\r\nvar _tmpl = [];\r\na\r\nb\r\nreturn _tmpl.join('');\r\n}", result.RazorJSTemplate); }
public void Compile_Success_ReturnsCompilerResultFromTemplateBuilder() { CompilerResult expected = new CompilerResult("a"); this._templateBuilder.Setup(t => t.Build()).Returns(expected); var sut = this.CreateCompiler(); var result = sut.Compile("a"); Assert.AreEqual(expected, result); }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { SetText(result.Result); } else { SetText("/*\r\n\r\nCompilation Error occurred (see error list to navigate to the error location):\r\n" + string.Join("\r\n", result.Errors.Select(e => "Error found" + (e.Line > 0 ? " at line " + e.Line + (e.Column > 0 ? ", column " + e.Column : "") : "") + ":\r\n" + e.FullMessage)) + "\r\n\r\n*/"); } }
public static string CompileCodeBlock(PlcSoftware plcSoftware) { string message = null; CodeBlock block = plcSoftware.BlockGroup.Blocks.Find("MyCodeBlock") as CodeBlock; if (block != null) { ICompilable compileService = block.GetService <ICompilable>(); CompilerResult result = compileService.Compile(); message = WriteCompilerResults(result); } return(message); }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { SetText(result.Result); } else { SetText("/*\r\n\r\nCompilation Error. \r\nSee error list for details\r\n" + string.Join("\r\n", result.Errors.Select(e => e.Message)) + "\r\n\r\n*/"); } }
private void Compile(object sender, EventArgs e) { btn_CompileHW.Enabled = false; string devname = txt_Device.Text; bool found = false; foreach (Device device in MyProject.Devices) { DeviceItemComposition deviceItemAggregation = device.DeviceItems; foreach (DeviceItem deviceItem in deviceItemAggregation) { if (deviceItem.Name == devname || device.Name == devname) { SoftwareContainer softwareContainer = deviceItem.GetService <SoftwareContainer>(); if (softwareContainer != null) { if (softwareContainer.Software is PlcSoftware) { PlcSoftware controllerTarget = softwareContainer.Software as PlcSoftware; if (controllerTarget != null) { found = true; ICompilable compiler = controllerTarget.GetService <ICompilable>(); CompilerResult result = compiler.Compile(); txt_Status.Text = "Compiling of " + controllerTarget.Name + ": State: " + result.State + " / Warning Count: " + result.WarningCount + " / Error Count: " + result.ErrorCount; } } if (softwareContainer.Software is HmiTarget) { HmiTarget hmitarget = softwareContainer.Software as HmiTarget; if (hmitarget != null) { found = true; ICompilable compiler = hmitarget.GetService <ICompilable>(); CompilerResult result = compiler.Compile(); txt_Status.Text = "Compiling of " + hmitarget.Name + ": State: " + result.State + " / Warning Count: " + result.WarningCount + " / Error Count: " + result.ErrorCount; } } } } } } if (found == false) { txt_Status.Text = "Found no device with name " + txt_Device.Text; } btn_CompileHW.Enabled = true; }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { _compilerResult = result as CssCompilerResult; UpdateResults().DoNotWait("updating TextView property"); SetText(result.Result); } else SetText("/*\r\n\r\nCompilation Error. \r\nSee error list for details\r\n" + string.Join("\r\n", result.Errors.Select(e => e.Message)) + "\r\n\r\n*/"); }
public void Can_compress_image_with_pingo(PingoOptions options) { // Act CompilerResult result = Pingo.Compress(options); // Assert result.Success.ShouldBeTrue(result.Message); result.Elapse.Ticks.ShouldBeGreaterThan(0); result.NewSize.ShouldBeLessThanOrEqualTo(result.OriginalSize); File.Exists(result.SourceFile).ShouldBeTrue(result.Message); File.Exists(result.OuputFile).ShouldBeTrue(result.Message); Diff.ApproveFile(result.OuputFile, Path.GetFileNameWithoutExtension(result.OuputFile)); }
/// <summary> /// Checks if all columns of a result generated by the compiler have full notation /// (database.schema.dbo.column) /// </summary> private static void CheckAllColumnNotations(CompilerResult result) { foreach (var mani in result.DataManipulations) { foreach (var exp in mani.Expressions) { CheckColumnNotation(exp); } } foreach (var exp in result.DataQueries) { CheckColumnNotation(exp); } }
public bool Execute() { if (string.IsNullOrEmpty(ProjectDirectory)) { ProjectDirectory = Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode); } if (!Directory.Exists(ProjectDirectory)) { throw new DirectoryNotFoundException($"Could not find directory at '{ProjectDirectory}'."); } NodeJS.Install((message, _, __) => { Message($"{nameof(CompileSassFiles)}: {message}", MessageImportance.High); }); var options = new CompilerOptions { Minify = Minify, OutputDirectory = OutputDirectory, AddSourceComments = AddSourceComments, GenerateSourceMaps = GenerateSourceMaps, SourceMapDirectory = SourceMapDirectory, ConfigurationFile = (File.Exists(OptionsFile) ? OptionsFile : null) }; int failures = 0; foreach (string sassFile in SassCompiler.GetSassFiles(ProjectDirectory)) { CompilerResult result = SassCompiler.Compile(sassFile, options); foreach (CompilerError err in result.Errors) { LogError(err); } if (result.Success) { LogResult(result); } else { failures++; } } return(failures == 0); }
private void LogResult(CompilerResult result) { string rel(string x) => (x == null ? "null" : string.Format("{0}\\{1}", Path.GetDirectoryName(x).Replace(ProjectDirectory, string.Empty), Path.GetFileName(x))); BuildEngine.LogMessageEvent(new BuildMessageEventArgs( string.Format( "sass -> in:{0} out:{1} elapse:{2}", rel(result.SourceFile), (result.GeneratedFiles.Length > 1 ? string.Format("[{0}]", string.Join(" ", result.GeneratedFiles.Select(x => rel(x)))) : rel(result.OutputFile)), result.Elapse.ToString("hh\\:mm\\:ss\\.fff")), null, nameof(CompileSassFiles), MessageImportance.Normal )); }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { _compilerResult = result as CssCompilerResult; UpdateResults().DoNotWait("updating TextView property"); SetText(result.Result); } else { SetText("/*\r\n\r\nCompilation Error. \r\nSee error list for details\r\n" + string.Join("\r\n", result.Errors.Select(e => e.Message)) + "\r\n\r\n*/"); } }
public void SimpleExpression1_VB_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"simple expression1_vb.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH_VB; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("5+7/3*2+(4*2)"); Assert.IsTrue(result.Output.StartsWith("Parse was successful.")); }
protected override void UpdateMargin(CompilerResult result) { if (_browser == null) return; // The Markdown compiler cannot return errors string html = String.Format(CultureInfo.InvariantCulture, @"<!DOCTYPE html> <html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml""> <head> <meta charset=""utf-8"" /> <title>Markdown Preview</title> {0} </head> <body>{1}</body></html>", GetStylesheet(), result.Result); _browser.NavigateToString(html); }
public void SimpleExpression4_VB_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"GrammarHighlighter_vb.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives.Add(new Directive("TinyPG")); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH_VB; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("using System.IO;\r\n"); Assert.IsTrue(result.Output.StartsWith("Parse was successful.")); }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { _compilerResult = result as CssCompilerResult; if (SourceTextView.Properties.ContainsProperty("CssCompilerResult")) SourceTextView.Properties.RemoveProperty("CssCompilerResult"); SourceTextView.Properties.AddProperty("CssCompilerResult", _compilerResult); SetText(result.Result); } else SetText("/*\r\n\r\nCompilation Error. \r\nSee error list for details\r\n" + string.Join("\r\n", result.Errors.Select(e => e.Message)) + "\r\n\r\n*/"); }
public void SimpleExpression2_VB_Test() { GrammarTree GT = LoadGrammar(TESTFILESPATH + @"simple expression2_vb.tpg"); Grammar G = (Grammar)GT.Eval(); G.Directives.Add(new Directive("TinyPG")); G.Directives["TinyPG"]["TemplatePath"] = TEMPLATEPATH_VB; Compiler.Compiler compiler = new Compiler.Compiler(); compiler.Compile(G); Assert.IsTrue(compiler.Errors.Count == 0, "compilation contains errors"); CompilerResult result = compiler.Run("5+8/4*2+(4*2)"); Assert.IsTrue(Convert.ToInt32(result.Value) == 17); }
/// <summary> /// Retrieve the string that rapresent the html to display in /// the preview. /// If an html template is found in the project folder or in the solution folder, it /// is returned after the place holders have been substituted. /// If no html template is found, the old behavior that was in place before /// the html template was introduced is used (a minimal html is returned with a /// reference to a custom stylesheet). The only change is that a custom stylesheet /// found in the project folder will take precedence over the one in the solution /// folder. /// </summary> /// <remarks> /// The supported placeholders are: /// /// {##SOLUTION_PATH_PLACEHOLDER##} /// {##PROJECT_PATH_PLACEHOLDER##} /// {##DOCUMENT_PATH_PLACEHOLDER##} /// {##MARKDOWN_HTML_PLACEHOLDER##} /// /// Note that to keep things simple, a placeholder must appear in the html template /// literally. there is no parsing involved. /// </remarks> /// <param name="compilerResult">The result of the markdown compilation</param> /// <returns>The html string</returns> public static string CompileHtmlDocumentString(string currentDocumentPath, CompilerResult compilerResult) { // The Markdown compiler cannot return errors var solutionPath = ProjectHelpers.GetSolutionFolderPath(); var projectPath = ProjectHelpers.GetProjectFolder(currentDocumentPath); var htmlTemplateFilePath = GetExistingFilesInFolders(_htmlTemplate, projectPath, solutionPath).FirstOrDefault(); var currentDocumentPathUrl = ConvertLocalDirectoryPathToUrl(Path.GetDirectoryName(currentDocumentPath)); if (htmlTemplateFilePath != null) { var solutionPathUrl = solutionPath == null ? currentDocumentPathUrl : ConvertLocalDirectoryPathToUrl(solutionPath); var projectPathUrl = projectPath == null ? currentDocumentPathUrl : ConvertLocalDirectoryPathToUrl(projectPath); //Load the template and replace the placeholder with the generated html var htmlTemplate = File.ReadAllText(htmlTemplateFilePath); // TODO: Find a better way to do this(Handlerbar, HTML parsing, etc...) return(htmlTemplate .Replace("{##SOLUTION_PATH_PLACEHOLDER##}", solutionPathUrl) .Replace("{##PROJECT_PATH_PLACEHOLDER##}", projectPathUrl) .Replace("{##DOCUMENT_PATH_PLACEHOLDER##}", currentDocumentPathUrl) .Replace("{##MARKDOWN_HTML_PLACEHOLDER##}", compilerResult.Result)); } // Keep the legacy behavior return(string.Format( CultureInfo.InvariantCulture, @"<!DOCTYPE html> <html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml""> <head> <meta charset=""utf-8"" /> <base href=""{0}""> <title>Markdown Preview</title> {1} </head> <body> {2} </body> </html>", currentDocumentPathUrl, GetStylesheet(projectPath, solutionPath), compilerResult.Result )); }
protected override void UpdateMargin(CompilerResult result) { if (_browser == null) { return; } var htmlString = CompileHtmlDocumentString(Document.FilePath, _globalStylesheetPath, result); if (_browser.Document == null) { _browser.NavigateToString(htmlString); return; } SaveDocumentVerticalPosition(_browser); _browser.NavigateToString(htmlString); }
public override async Task <CompilerResult> CompileAsync(string sourceFileName, string targetFileName) { //dont compile files that start with _ //http://sass-lang.com/documentation/file.SASS_REFERENCE.html#partials if (Path.GetFileName(sourceFileName).StartsWith("_")) { Logger.Log(string.Format("Ignoring {0}, see http://sass-lang.com/documentation/file.SASS_REFERENCE.html#partials", sourceFileName)); return(CompilerResult.GenerateResult(sourceFileName, targetFileName, "", true, "", "", null, true)); } if (WESettings.Instance.Scss.UseRubyRuntime) { await RubyScssServer.Up(); } return(await base.CompileAsync(sourceFileName, targetFileName)); }
protected override string PostProcessResult(CompilerResult result) { return result.Result; }
protected override void UpdateMargin(CompilerResult result) { if (_browser == null) return; var htmlFormatString = GetHtmlTemplate(); var baseHref = Path.GetDirectoryName(Document.FilePath).Replace("\\", "/"); var styleSheet = GetStylesheet(); string html; try { // The Markdown compiler cannot return errors html = string.Format(CultureInfo.InvariantCulture, htmlFormatString, baseHref, styleSheet, result.Result); } catch (Exception exp) { html = string.Format(CultureInfo.InvariantCulture, _defaultHtmlTemplate, baseHref, styleSheet, result.Result + CreateExceptionBox(exp)); } if (_document == null) { _browser.NavigateToString(html); return; } _cachedPosition = _document.documentElement.getAttribute("scrollTop"); _cachedHeight = Math.Max(1.0, _document.body.offsetHeight); _positionPercentage = _cachedPosition * 100 / _cachedHeight; _browser.NavigateToString(html); }
/// <summary> /// Compile a script (or set of scripts), and return information about /// the compilation request. /// </summary> /// <param name="Filespec">Supplies a filespec of files to compile, /// such as *.nss.</param> /// <param name="Options">Optionally supplies additional compiler /// options (e.g. -e -v1.70).</param> /// <param name="ParseLine">Optionally supplies a function to parse /// each line printed by the compiler.</param> /// <returns>A compiler result descriptor is returned.</returns> public static CompilerResult CompileScript(string Filespec, string Options, CompilerParseLineDelegate ParseLine = null) { CompilerResult Result = new CompilerResult(); Result.Compiled = false; Result.Warnings = new List<string>(); Result.Errors = new List<string>(); try { // // Construct the command line for the compiler instance. // string CmdLine = CreateCompilerCommandLine(Filespec, Options); Process CompilerProcess; ProcessStartInfo StartInfo = new ProcessStartInfo(GetCompilerExe(), CmdLine); string Line; // // Start the compiler process and begin reading stdout until // end of file is reached. In the absence of any error // messages observed, the operation is assumed to have // completed successfully. // StartInfo.CreateNoWindow = true; StartInfo.UseShellExecute = false; StartInfo.WindowStyle = ProcessWindowStyle.Hidden; StartInfo.RedirectStandardOutput = true; StartInfo.WorkingDirectory = ALFA.SystemInfo.GetModuleDirectory(); CompilerProcess = Process.Start(StartInfo); Result.Compiled = true; while ((Line = CompilerProcess.StandardOutput.ReadLine()) != null) { // // Parse each line, examining it for a compiler diagnostic // indicator. Accumulate errors and warnings into their // respective diagnostic message lists for the caller to // examine. // if (ParseLine != null && ParseLine(Line)) continue; if (Line.StartsWith("Error:")) { Result.Errors.Add(Line); Result.Compiled = false; } else if (Line.Contains("): Error: NSC")) { Result.Errors.Add(Line); Result.Compiled = false; } else if (Line.StartsWith("Warning:")) { Result.Warnings.Add(Line); } else if (Line.Contains("): Warning: NSC")) { Result.Warnings.Add(Line); } } CompilerProcess.WaitForExit(); } catch (Exception e) { Result.Errors.Add(String.Format( "ALFA.ScriptCompiler.CompileScript({0}, {1}): Exception: '{2}'.", Filespec, Options, e)); Result.Compiled = false; } return Result; }
public ScriptCompilerResult(CompilerResult compilerResult, Assembly compiledAssembly = null) { _compiledAssembly = compiledAssembly; CompilerResult = compilerResult; }
///<summary>Creates a new CompilerResultEventArgs instance.</summary> public CompilerResultEventArgs(CompilerResult result) { CompilerResult = result; }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { SetText(result.Result); } else SetText("/*\r\n\r\nCompilation Error. \r\nSee error list for details\r\n" + string.Join("\r\n", result.Errors.Select(e => e.Message)) + "\r\n\r\n*/"); }
public CompilerResult Run(string input, RichTextBox textHighlight) { CompilerResult compilerresult = new CompilerResult(); string output = null; if (assembly == null) return null; object scannerinstance = assembly.CreateInstance("TinyPG.Debug.Scanner"); Type scanner = scannerinstance.GetType(); object parserinstance = (IParser)assembly.CreateInstance("TinyPG.Debug.Parser", true, BindingFlags.CreateInstance, null, new object[] { scannerinstance }, null, null); Type parsertype = parserinstance.GetType(); object treeinstance = parsertype.InvokeMember("Parse", BindingFlags.InvokeMethod, null, parserinstance, new object[] { input, string.Empty }); IParseTree itree = treeinstance as IParseTree; compilerresult.ParseTree = itree; Type treetype = treeinstance.GetType(); List<IParseError> errors = (List<IParseError>)treetype.InvokeMember("Errors", BindingFlags.GetField, null, treeinstance, null); if (textHighlight != null && errors.Count == 0) { // try highlight the input text object highlighterinstance = assembly.CreateInstance("TinyPG.Debug.TextHighlighter", true, BindingFlags.CreateInstance, null, new object[] { textHighlight, scannerinstance, parserinstance }, null, null); if (highlighterinstance != null) { output += "Highlighting input..." + "\r\n"; Type highlightertype = highlighterinstance.GetType(); // highlight the input text only once highlightertype.InvokeMember("HighlightText", BindingFlags.InvokeMethod, null, highlighterinstance, null); // let this thread sleep so background thread can highlight the text System.Threading.Thread.Sleep(20); // dispose of the highlighter object highlightertype.InvokeMember("Dispose", BindingFlags.InvokeMethod, null, highlighterinstance, null); } } if (errors.Count > 0) { foreach (IParseError err in errors) output += string.Format("({0},{1}): {2}\r\n", err.Line, err.Column, err.Message); } else { output += "Parse was successful." + "\r\n"; output += "Evaluating..."; // parsing was successful, now try to evaluate... this should really be done on a seperate thread. // e.g. if the thread hangs, it will hang the entire application (!) try { compilerresult.Value = itree.Eval(null); output += "\r\nResult: " + (compilerresult.Value == null ? "null" : compilerresult.Value.ToString()); } catch (Exception exc) { output += "\r\nException occurred: " + exc.Message; output += "\r\nStacktrace: " + exc.StackTrace; } } compilerresult.Output = output.ToString(); return compilerresult; }
protected override void UpdateMargin(CompilerResult result) { if (result.IsSuccess) { SetText(result.Result); } else SetText("/*\r\n\r\nCompilation Error occurred (see error list to navigate to the error location):\r\n" + string.Join("\r\n", result.Errors.Select(e => "Error found" + (e.Line > 0 ? " at line " + e.Line + (e.Column > 0 ? ", column " + e.Column : "") : "") + ":\r\n" + e.FullMessage)) + "\r\n\r\n*/"); }
private void EvaluateExpression() { textOutput.Text = "Parsing expression...\r\n"; try { if (IsDirty || compiler == null || !compiler.IsCompiled) CompileGrammar(); if (string.IsNullOrEmpty(GrammarFile)) return; // save the grammar when compilation was successful if (compiler != null && compiler.Errors.Count == 0) SaveGrammar(GrammarFile); CompilerResult result = new CompilerResult(); if (compiler.IsCompiled) { result = compiler.Run(textInput.Text, textInput); //textOutput.Text = result.ParseTree.PrintTree(); textOutput.Text += result.Output; ParseTreeViewer.Populate(tvParsetree, result.ParseTree); } } catch (Exception exc) { textOutput.Text += "An exception occured compiling the assembly: \r\n" + exc.Message + "\r\n" + exc.StackTrace; } }