private static bool IsReportableCSharpError(Diagnostic compilerError) { return(!compilerError.ToString() .Contains(value: "netstandard", comparisonType: StringComparison.Ordinal) && !compilerError.ToString() .Contains(value: "static 'Main' method", comparisonType: StringComparison.Ordinal) && !compilerError.ToString() .Contains(value: "CS1002", comparisonType: StringComparison.Ordinal) && !compilerError .ToString() .Contains(value: "CS1702", comparisonType: StringComparison.Ordinal)); }
private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree) { var compilation = CSharpCompilation.Create( "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies new[] { syntaxTree }, BuildManager.GetReferencedAssemblies().OfType <Assembly>().Select(ResolveReference), new CSharpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default, optimizationLevel: host.DefaultDebugCompilation ? OptimizationLevel.Debug : OptimizationLevel.Release)); using (var dllStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { EmitResult emitResult = compilation.Emit(dllStream, pdbStream); if (!emitResult.Success) { Diagnostic diagnostic = emitResult.Diagnostics.First(x => x.Severity == DiagnosticSeverity.Error); string message = diagnostic.ToString(); LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition; throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1); } return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer())); } }
public static string GetMessageWithSource(this Diagnostic diagnostic, IOpenApiElementRegistry elementRegistry) { string?source = diagnostic.GetSource(elementRegistry); return(source == null ? diagnostic.ToString() : $"{source} {diagnostic}"); }
private void AddErrorsToStringBuilder(bool adderrorsonly, ref StringBuilder stringbuilder, Diagnostic diagnostic) { if (adderrorsonly == false || diagnostic.Severity == DiagnosticSeverity.Error) { stringbuilder.AppendLine(diagnostic.ToString()); } }
/// <summary> /// Adds compiler error or warning message with a link that opens the C# file and goes to that position. /// </summary> /// <param name="d">Error or warning.</param> /// <param name="fMain">Main file of the compilation. Used only for failures that are not C# errors, eg when fails to open a metadata reference file.</param> /// <remarks> /// This and other AddX functions add line like "[C:\path\file.cs(line,column)]: message" or "[C:\path\file.cs]: message". /// Then our print.Server.SetNotifications callback will convert the "[...]" part to a link. /// </remarks> public void AddErrorOrWarning(Diagnostic d, FileNode fMain) { _StartAdd(isWarning: d.Severity != DiagnosticSeverity.Error); var s = d.ToString(); int i = d.Location.IsInSource ? s.Find("): ") + 1 : 0; if (i > 0) { _b.AppendFormat("[{0}]{1}", s[..i], s[i..]);
/// <summary> /// Appends <paramref name="diagnostic" /> to the <paramref name="builder" />. /// </summary> /// <param name="builder">The builder the diagnostic should be appended to.</param> /// <param name="diagnostic">The diagnostic that should be appended.</param> public static void Write(StringBuilder builder, Diagnostic diagnostic) { var lineSpan = diagnostic.Location.GetLineSpan(); var message = diagnostic.ToString(); message = message.Substring(message.IndexOf(":", StringComparison.InvariantCulture) + 1); builder.AppendFormat("({1}-{2}) {0}\n\n", message, lineSpan.StartLinePosition, lineSpan.EndLinePosition); }
private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree, ICollection <ICompileModule> compilationModules) { var strArgs = new List <string>(); strArgs.Add("/target:library"); strArgs.Add(host.DefaultDebugCompilation ? "/o-" : "/o+"); strArgs.Add(host.DefaultDebugCompilation ? "/debug+" : "/debug-"); var cscArgs = CSharpCommandLineParser.Default.Parse(strArgs, null, null); var compilation = CSharpCompilation.Create( "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies new[] { syntaxTree }, BuildManager.GetReferencedAssemblies().OfType <Assembly>().Select(ResolveReference), cscArgs.CompilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); compilation = Hacks.MakeValueTuplesWorkWhenRunningOn47RuntimeAndTargetingNet45Plus(compilation); var diagnostics = new List <Diagnostic>(); var context = new CompileContext(compilationModules); context.Before(new BeforeCompileContext { Arguments = cscArgs, Compilation = compilation, Diagnostics = diagnostics, }); compilation = context.BeforeCompileContext.Compilation; using (var dllStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { EmitResult emitResult = compilation.Emit(dllStream, pdbStream); diagnostics.AddRange(emitResult.Diagnostics); if (!emitResult.Success) { Diagnostic diagnostic = diagnostics.First(x => x.Severity == DiagnosticSeverity.Error); string message = diagnostic.ToString(); LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition; throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1); } context.After(new AfterCompileContext { Arguments = context.BeforeCompileContext.Arguments, AssemblyStream = dllStream, Compilation = compilation, Diagnostics = diagnostics, SymbolStream = pdbStream, XmlDocStream = null, }); return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer())); } }
private FormatError ConvertError(Diagnostic diagnostic) { var lineSpan = diagnostic.Location.SourceTree.GetLineSpan( diagnostic.Location.SourceSpan ); return(new FormatError { LineSpan = lineSpan, Description = diagnostic.ToString(), }); }
public TypeScriptTask( FileName fileName, Diagnostic diagnostic, int column, int line) : base( fileName, diagnostic.ToString(), column, line, GetTaskType(diagnostic.category)) { }
private static void WriteErrorLine(string path, Diagnostic diagnostic) { Console.WriteLine( "{0}({1},{2},{3},{4}): {5} {6}: {7}", path, diagnostic.Location.GetLineSpan().StartLinePosition.Line + 1, diagnostic.Location.GetLineSpan().StartLinePosition.Character, diagnostic.Location.GetLineSpan().EndLinePosition.Line + 1, diagnostic.Location.GetLineSpan().EndLinePosition.Character, diagnostic.Severity, diagnostic.Id, diagnostic.ToString()); }
public static void Create() { var span = new TextSpan(3, 4); var message = "diagnostic"; var location = new TextLocation(SourceText.From("1"), span); var diagnostic = new Diagnostic(location, message); Assert.Multiple(() => { Assert.That(diagnostic.Location, Is.EqualTo(location), nameof(diagnostic.Location)); Assert.That(diagnostic.Message, Is.EqualTo(message), nameof(diagnostic.Message)); Assert.That(diagnostic.ToString(), Is.EqualTo(message), nameof(diagnostic.ToString)); }); }
/// <summary> /// Adds compiler error or warning message with a link that opens the C# file and goes to that position. /// </summary> /// <param name="d">Error or warning.</param> /// <param name="fMain">Main file of the compilation. Used only for failures that are not C# errors, eg when fails to open a metadata reference file.</param> /// <remarks> /// This and other AddX functions add line like "[C:\path\file.cs(line,column)]: message" or "[C:\path\file.cs]: message". /// Then our AOutputServer.SetNotifications callback will convert the "[...]" part to a link. /// </remarks> public void AddErrorOrWarning(Diagnostic d, FileNode fMain) { _StartAdd(isWarning: d.Severity != DiagnosticSeverity.Error); var s = d.ToString(); int i = d.Location.IsInSource ? s.Find("): ") + 1 : 0; if (i > 0) { _b.AppendFormat("[{0}]{1}", s.Remove(i), s.Substring(i)); } else { _b.AppendFormat("[{0}]: {1}", fMain.FilePath, s); } }
public void PrintDiagnostic(Diagnostic item) { switch (item.Severity) { case DiagnosticSeverity.Hidden: return; case DiagnosticSeverity.Error: Console.ForegroundColor = ConsoleColor.Red; break; case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; } PrintLine(item.ToString()); Console.ResetColor(); }
/// <summary> /// What we need to do is find a *repeatable* arbitrary way to choose between /// two errors; we can for example simply take the one that is lower in alphabetical /// order when converted to a string. As an optimization, we compare error codes /// first and skip string comparison if they differ. /// </summary> private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y) { ErrorCode xCode = (ErrorCode)x.Code; ErrorCode yCode = (ErrorCode)y.Code; int codeCompare = xCode.CompareTo(yCode); // ToString fails for a diagnostic with an error code that does not prevernt successful delegate conversion. // Also, the order doesn't matter, since all such diagnostics will be dropped. if (!ErrorFacts.PreventsSuccessfulDelegateConversion(xCode) || !ErrorFacts.PreventsSuccessfulDelegateConversion(yCode)) { return(codeCompare); } // Optimization: don't bother return(codeCompare == 0 ? string.CompareOrdinal(x.ToString(), y.ToString()) : codeCompare); }
private static string FormatDiagnostic(Diagnostic diagnostic) { var builder = new StringBuilder(); builder.AppendLine(diagnostic.ToString()); var location = diagnostic.Location; if (location == Location.None) { builder.Append($"Location unknown: ({diagnostic.Id})"); } else { True(location.IsInSource, $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostic}"); var linePosition = location.GetLineSpan().StartLinePosition; builder.Append($"({(linePosition.Line + 1)}, {(linePosition.Character + 1)}, {diagnostic.Id})"); } return(builder.ToString()); }
public static string GetAssertText(DiagnosticDescription[] expected, IEnumerable <Diagnostic> actual) { const int CSharp = 1; const int VisualBasic = 2; var language = actual.Any() && actual.First().Id.StartsWith("CS", StringComparison.Ordinal) ? CSharp : VisualBasic; var includeDiagnosticMessagesAsComments = (language == CSharp); int indentDepth = (language == CSharp) ? 4 : 1; var includeDefaultSeverity = expected.Any() && expected.All(d => d.DefaultSeverity != null); var includeEffectiveSeverity = expected.Any() && expected.All(d => d.EffectiveSeverity != null); if (IsSortedOrEmpty(expected)) { // If this is a new test (empty expectations) or a test that's already sorted, // we sort the actual diagnostics to minimize diff noise as diagnostics change. actual = Sort(actual); } var assertText = new StringBuilder(); assertText.AppendLine(); // write out the error baseline as method calls int i; assertText.AppendLine("Expected:"); var expectedText = ArrayBuilder <string> .GetInstance(); foreach (var d in expected) { expectedText.Add(GetDiagnosticDescription(d, indentDepth)); } GetCommaSeparatedLines(assertText, expectedText); // write out the actual results as method calls (copy/paste this to update baseline) assertText.AppendLine("Actual:"); var actualText = ArrayBuilder <string> .GetInstance(); var e = actual.GetEnumerator(); for (i = 0; e.MoveNext(); i++) { Diagnostic d = e.Current; string message = d.ToString(); if (Regex.Match(message, @"{\d+}").Success) { Assert.True(false, "Diagnostic messages should never contain unsubstituted placeholders.\n " + message); } if (i > 0) { assertText.AppendLine(","); } if (includeDiagnosticMessagesAsComments) { Indent(assertText, indentDepth); assertText.Append("// "); assertText.AppendLine(d.ToString()); var l = d.Location; if (l.IsInSource) { Indent(assertText, indentDepth); assertText.Append("// "); assertText.AppendLine(l.SourceTree.GetText().Lines.GetLineFromPosition(l.SourceSpan.Start).ToString()); } } var description = new DiagnosticDescription(d, errorCodeOnly: false, includeDefaultSeverity, includeEffectiveSeverity); var diffDescription = description; var idx = Array.IndexOf(expected, description); if (idx != -1) { diffDescription = expected[idx]; } assertText.Append(GetDiagnosticDescription(description, indentDepth)); actualText.Add(GetDiagnosticDescription(diffDescription, indentDepth)); } if (i > 0) { assertText.AppendLine(); } assertText.AppendLine("Diff:"); assertText.Append(DiffUtil.DiffReport(expectedText, actualText, separator: Environment.NewLine)); actualText.Free(); expectedText.Free(); return(assertText.ToString()); }
public MissingPredefinedMember(Diagnostic error) : base(error.ToString()) { this.Diagnostic = error; }
private static void OnDiagnosticProgress(Diagnostic diagnostic) { Console.WriteLine(diagnostic.ToString()); }
/// <summary> /// What we need to do is find a *repeatable* arbitrary way to choose between /// two errors; we can for example simply take the one that is lower in alphabetical /// order when converted to a string. As an optimization, we compare error codes /// first and skip string comparison if they differ. /// </summary> private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y) { ErrorCode xCode = (ErrorCode)x.Code; ErrorCode yCode = (ErrorCode)y.Code; int codeCompare = xCode.CompareTo(yCode); // ToString fails for a diagnostic with an error code that does not prevent successful delegate conversion. // Also, the order doesn't matter, since all such diagnostics will be dropped. if (!ErrorFacts.PreventsSuccessfulDelegateConversion(xCode) || !ErrorFacts.PreventsSuccessfulDelegateConversion(yCode)) { return codeCompare; } // Optimization: don't bother return codeCompare == 0 ? string.CompareOrdinal(x.ToString(), y.ToString()) : codeCompare; }
public DiagnosticItemViewModel(Diagnostic diagnostic) { Diagnostic = diagnostic; Content = diagnostic.ToString(); }
protected override Type GetTemplateCodeTypeByCode(string Code) { var tree = SyntaxTree.ParseCompilationUnit(Code); var compilation = Compilation.Create( "calc.dll", options: new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: new[] { new AssemblyFileReference(typeof(object).Assembly.Location), new AssemblyFileReference(System.Reflection.Assembly.GetAssembly(typeof(TemplateCodeGen)).Location) } ); var Errors = String.Join("\n", compilation.GetDiagnostics().Select(Diagnostic => Diagnostic.ToString())); if (Errors.Length > 0) { throw (new Exception(Errors)); } Assembly compiledAssembly; using (var stream = new MemoryStream()) { EmitResult compileResult = compilation.Emit(stream); compiledAssembly = Assembly.Load(stream.GetBuffer()); } return(compiledAssembly.GetType("CompiledTemplate_TempTemplate")); }
/// <summary> /// Writes the diagnostic and the offending code. /// </summary> /// <returns>A string for use in assert exception</returns> internal static async Task <string> ToStringAsync(this Diagnostic diagnostic, Solution solution) { var sources = await Task.WhenAll(solution.Projects.SelectMany(p => p.Documents).Select(d => CodeReader.GetStringFromDocumentAsync(d, Formatter.Annotation, CancellationToken.None))); return(diagnostic.ToString(sources)); }
public SerializableDiagnostic(Diagnostic diagnostic) { _string = diagnostic.ToString(); Severity = diagnostic.Severity; }
public DiagnosticListItem(Diagnostic diagnostic, TextBox codeTextBox) { _diagnostic = diagnostic; _codeTextBox = codeTextBox; Content = diagnostic.ToString(); }
public static string GetAssertText(DiagnosticDescription[] expected, IEnumerable <Diagnostic> actual) { var includeCompilerOutput = false; var includeDiagnosticMessagesAsComments = false; const int CSharp = 1; const int VisualBasic = 2; int language = actual.Any() && actual.First().Id.StartsWith("CS", StringComparison.Ordinal) ? CSharp : VisualBasic; if (language == CSharp) { includeDiagnosticMessagesAsComments = true; } StringBuilder assertText = new StringBuilder(); assertText.AppendLine(); // Write out the 'command line compiler output' including squiggles (easy to read debugging info in the case of a failure). // This will be useful for VB, because we can't do the inline comments. if (includeCompilerOutput) { assertText.AppendLine("Compiler output:"); foreach (Diagnostic d in actual) { Indent(assertText, 1); assertText.AppendLine(d.ToString()); Location location = d.Location; string lineText = location.SourceTree.GetText().Lines.GetLineFromPosition(location.SourceSpan.Start).ToString(); assertText.AppendLine(lineText); FileLinePositionSpan span = location.GetMappedLineSpan(); LinePosition startPosition = span.StartLinePosition; LinePosition endPosition = span.EndLinePosition; assertText.Append(' ', startPosition.Character); int endCharacter = (startPosition.Line == endPosition.Line) ? endPosition.Character : lineText.Length; assertText.Append('~', endCharacter - startPosition.Character); assertText.AppendLine(); } } // write out the error baseline as method calls int i; assertText.AppendLine("Expected:"); var expectedText = new StringBuilder(); for (i = 0; i < expected.Length; i++) { DiagnosticDescription d = expected[i]; AppendDiagnosticDescription(expectedText, d); if (i < expected.Length - 1) { expectedText.Append(","); } expectedText.AppendLine(); } assertText.Append(expectedText); // write out the actual results as method calls (copy/paste this to update baseline) assertText.AppendLine("Actual:"); var actualText = new StringBuilder(); IEnumerator <Diagnostic> e = actual.GetEnumerator(); for (i = 0; e.MoveNext(); i++) { Diagnostic d = e.Current; string message = d.ToString(); if (Regex.Match(message, @"{\d+}").Success) { Assert.True(false, "Diagnostic messages should never contain unsubstituted placeholders.\n " + message); } if (i > 0) { assertText.AppendLine(","); actualText.AppendLine(","); } if (includeDiagnosticMessagesAsComments) { Indent(assertText, 1); assertText.Append("// "); assertText.AppendLine(d.ToString()); Location l = d.Location; if (l.IsInSource) { Indent(assertText, 1); assertText.Append("// "); assertText.AppendLine(l.SourceTree.GetText().Lines.GetLineFromPosition(l.SourceSpan.Start).ToString()); } } var description = new DiagnosticDescription(d, errorCodeOnly: false, showPosition: true); AppendDiagnosticDescription(assertText, description); AppendDiagnosticDescription(actualText, description); } if (i > 0) { assertText.AppendLine(); actualText.AppendLine(); } assertText.AppendLine("Diff:"); assertText.Append(DiffUtil.DiffReport(expectedText.ToString(), actualText.ToString())); return(assertText.ToString()); }
private static string SkipDirectory(Diagnostic diagnostic) { var text = diagnostic.ToString(); return(text.Substring(text.LastIndexOf('\\') + 1)); }
public override string ToString() { return(_Diagnostic.ToString()); }