Search code examples
roslynroslyn-code-analysis

Roslyn Analyzers do not run often enough


I am writing my first Roslyn analyzers. I have basically followed the tutorial https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/special-issue/csharp-and-visual-basic-use-roslyn-to-write-a-live-code-analyzer-for-your-api , and then proceeded by adding a second analyzer class which should be language-agnostics analysis, similar to what presented in https://www.meziantou.net/writing-a-language-agnostic-roslyn-analyzer-using-ioperation.htm .

So, I have one analyzer class which initializes itself with

context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);

and a second one which uses

context.RegisterOperationAction(AnalyzeConversionOperation, OperationKind.Conversion);
context.RegisterOperationAction(AnalyzeInvocationOperation, OperationKind.Invocation);

To test my analyzers, I have the generated .Vsix project set as startup project, and by pressing F5, it gets me to a separate instance of Visual Studio where I write some code and want to see whether my analyzers work as intended. And, I set breakpoints at the begininng of my analyzer actions - AnalyzeSymbol, AnalyzeConversionOperation and AnalyzeInvocationOperation, in the original VS instance.

The analyzer actions are not called as I would expect them too. In fact, they are not being called at all, as I write the code to be analyzed. Only if I place the cursor on some type name (which is related to the SymbolKind.NamedType action), and I click on the lightbulb that appears, I get the calls - and not only to the AnalyzeSymbol action, but also the AnalyzeConversionOperation and AnalyzeInvocationOperation are called as needed for various operations in the code.

So, the actions that get called are all fine - but they not called when I want them. I would expect them to be called as needed - basically, almost continuously as I edit the code. Or at least upon build, or some explicit "Analyze Now" command. But I am not aware of anything alike. The only way I found to trigger them is the way I described. That does not seem correct to me.

I tried Googling but could not find the solution; or possibly I have some misconception and it is supposed to work differently?


Solution

  • Analyzers are run out of process. So I think it's expected that you don't get the breakpoints hit, but in fact these lines get hit.

    You have three options:

    • Disable running analyzers out-of-process.

      image

    • Attach ServiceHub.RoslynCodeAnalysisService process to the debugger.

    • Debug through a unit test. This is my preferred approach.