Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy for debugging C# analyzer

Tags:

c#

roslyn

I've created my own code analyzer

    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class PluginAnalyzer : Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer { ... }

During unit test pattern / error / I'm looking for is reported as it should. However when I plugin in the analyzer to real project the analysis its not getting executed - or at lest the error is not getting reported (I'm using file from this project in unit test).

E.G.:

realproject.csproj

 <PackageReference Include="MyAnalyzer" Version="1.0.0">
   <PrivateAssets>all</PrivateAssets>
   <IncludeAssets>analyzers</IncludeAssets>
 </PackageReference>

I can see the analyzer is getting executed (csc.exe /analyzer:..MyAnalyzer.dll) yet the error is not getting reported. Is there a way to debug the analyzer / analyze if it is getting triggered or why it is getting ignored ?

like image 280
Ondrej Svejdar Avatar asked Nov 04 '25 13:11

Ondrej Svejdar


1 Answers

It is actually pretty straightforward:

  1. Locate file where your analyzer package lives; usually its something like c:\Users\[your user name]\.nuget\packages\[your package name]\[your package version]\analyzers\dotnet\cs\
  2. In your analyzer project replace the initialize method with something like
public override void Initialize(AnalysisContext context) {
  if (!Debugger.IsAttached) {
    Debugger.Launch();
  }
}
  1. Build and replace the nuget package dll with modified one
  2. The moment code analysis is triggered it will ask you to attach debugger
like image 129
Ondrej Svejdar Avatar answered Nov 06 '25 03:11

Ondrej Svejdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!