2

I'm writing a Roslyn analyzer which detects certain patterns in the code that we don't like, and raising a Diagnostic (the specifics are irrelevant here). However, detecting said patterns is potentially an expensive operation.

If a user has disabled the diagnostic using a ruleset file, using NOWARN, or other global/assembly level setting, is there a way that I can pick up on that inside my analyzer and use it in an if statement to avoid the potentially expensive parts?

I'm aware that I can put the diagnostic in it's own class SomeNewAnalyzer : DiagnosticAnalyzer, and the compiler won't run that analyzer if all diagnostics it supports are disabled, but is there way to do this as part of another Analyzer that raises multiple diagnostics?

2 Answers 2

2

There's a method in the DiagnosticDescriptor class which you can use:

public ReportDiagnostic GetEffectiveSeverity(CompilationOptions compilationOptions);

It returns ReportDiagnostic.Suppress if the rule is suppressed.

You can get the compilation options from your analysis context like this:

context.SemanticModel.Compilation.Options
Sign up to request clarification or add additional context in comments.

1 Comment

I just used this for the first time now inside a CompliationStartAction, it works perfectly. Thank you!
1

For future travelers: I did a lot more googling, and looked more deeply through the Roslyn API's that you have access to from within an Analyzer, and I'm fairly confident that in 2023, the answer is No. All signs suggest that if you want a given diagnostic to be turned off, that diagnostic should be in it's own Analyzer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.