silkfire
silkfire

Reputation: 25945

Disable other rules by use of a custom Roslyn Analyzer

I'm implementing a custom Roslyn Analyzer whose ruleset would override a currently existing rule shipped by default with Visual Studio. Is there some way to make my rule silence this other rule in specific scenarios?

I haven't so far been able to find any documentation on whether this is possible.

Upvotes: 5

Views: 690

Answers (1)

FlashOver
FlashOver

Reputation: 2073

Yes! This is possible via implementing a DiagnosticSuppressor, available since Roslyn 3.3.1, that you could add alongside your DiagnosticAnalyzer. Actually, DiagnosticSuppressor derives from DiagnosticAnalyzer, and could look something like this:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class MyDiagnosticSuppressor : DiagnosticSuppressor
{
    private static readonly SuppressionDescriptor Rule = new(
        "My-Diagnostic-Suppressor-Id",
        "Suppressed-Diagnostic-Id",
        "Justification / Description."
    );

    public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions
        => ImmutableArray.Create(Rule);

    public override void ReportSuppressions(SuppressionAnalysisContext context)
    {
        foreach (var diagnostic in context.ReportedDiagnostics)
        {
            Location location = diagnostic.Location;
            SyntaxTree? syntaxTree = location.SourceTree;
            SyntaxNode root = syntaxTree.GetRoot(context.CancellationToken);
            TextSpan textSpan = location.SourceSpan;
            SyntaxNode node = root.FindNode(textSpan);
            SemanticModel semanticModel = context.GetSemanticModel(syntaxTree);

            if (ShouldSuppress(context.Compilation, semanticModel, node, context.CancellationToken))
            {
                Suppression suppression = Suppression.Create(Rule, diagnostic);
                context.ReportSuppression(suppression);
            }
        }
    }

    private static bool ShouldSuppress(Compilation compilation, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
}

Also, I've recently built a DiagnosticSuppressor, which suppresses CA1707 (Identifiers should not contain underscores) on MSTest, NUnit and xUnit.net test methods. Here's that Pull Request, including unit tests and benchmarks. Perhaps it proves useful to you.

Upvotes: 3

Related Questions