Roslyn diagnostics reported through CompilationAnalysisContext.ReportDiagnostic do not show up in Visual Studio

44 Views Asked by At

I have created a Roslyn analyzer using the Analyzer with Code Fix template in Visual Studio 2022. Everything works in unit tests, but no diagnostics are shown up in Visual Studio.

A minimal example showing the problem:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DummyAnalyzer : DiagnosticAnalyzer
{
    private static readonly DiagnosticDescriptor Rule1 = new ("D001", "SymbolAction", "SymbolAction", "Test", DiagnosticSeverity.Warning, true);
    private static readonly DiagnosticDescriptor Rule2 = new ("D002", "CompilationAction", "CompilationAction", "Test", DiagnosticSeverity.Warning, true);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule1, Rule2];

    public override void Initialize(AnalysisContext context)
    {
        context.EnableConcurrentExecution();

        context.RegisterSymbolAction(c => c.ReportDiagnostic(Diagnostic.Create(Rule1, c.Symbol.Locations.FirstOrDefault())), SymbolKind.Method);

        context.RegisterCompilationAction(CompilationAction);
    }

    private void CompilationAction(CompilationAnalysisContext context)
    {
        foreach (var syntaxTree in context.Compilation.SyntaxTrees)
        {
            var compilationUnitSyntax = syntaxTree.GetRoot(context.CancellationToken) as CompilationUnitSyntax;
            var typeDeclarationSyntax = compilationUnitSyntax?.Members.OfType<BaseNamespaceDeclarationSyntax>().SelectMany(syntax => syntax.Members).OfType<TypeDeclarationSyntax>().FirstOrDefault();
            if (typeDeclarationSyntax != null)
                context.ReportDiagnostic(Diagnostic.Create(Rule2, typeDeclarationSyntax.GetLocation()));
        }
    }
}

In unit tests, both Rule1 and Rule2 produce diagnostics as expected. However, in Visual Studio only diagnostics from Rule1 are shown, despite debugger confirming that both context.ReportDiagnostic calls are being hit. It seems that no diagnostics reported through CompilationAnalysisContext.ReportDiagnostic are shown at all regardless to what I put there.

How can I solve the issue? Rewriting everything to use SymbolAnalysisContext.ReportDiagnostic would be too complex task as my analyzer needs to check relationships between several symbols.

I already made sure that no diagnostics are being suppressed through Visual Studio settings.

0

There are 0 best solutions below