Tuesday, June 23, 2015

Running Roslyn Analyzers from console application

This post requires prior knowledge from my earlier post. In the last post, we saw how our C# program can compile other C# program via Roslyn compiler. Yes it's without Visual Studio. If we are compiling without Visual Studio how a custom Roslyn DiagnosticAnalyzer can be invoked to do analysis on the code fragment which is getting compiled?

Here we are going to see how we can connect with Roslyn custom analyzers when our program is compiling another program using .Net compiler platform.
First, we are defining our custom analyzer which is nothing but a check to make sure the type names are starting with a capital letter. See the code below. Now let us move on to how this analyzer can be integrated into our programmatic compilation using Roslyn.
  1. GetSimpleCompilation()
    This is same as what is there in previous post about simple compilation.
  2. GetAnalyzerAwareCompilation
  3. Here we connect our compilation unit with custom Roslyn diagnostic analyzer.
  4. GetAllDiagnosticsAsync()
  5. This is Roslyn API to execute our custom analyzers on top of source code input and get the results back. The important point here is the compiler platform returns same type ImmutableArray<Diagnostic> every time. ie Regardless of whether its simple compilation or compilation with analyzers.

    If the result from GetAllDiagnosticsAsync is empty list, proceed to actual compilation which produces the assembly file.
  6. ShowDiagnostics()
    This is too same as previous post.

Updates

2022-08-10 - Added full sample to https://github.com/dotnet-demos/roslyn-compile-with-analyzers 

2 comments:

tomthesofty said...

Hallo,

I found this very useful post.
I tried to put the posted snippets together and implemented a solution in my Visual Studio 2013.
But I just can't get this running.
Is your original project, on which you based this post, available by any change?

Thanks
Thomas from Germany

Joymon said...

Somehow this post came to my search and added the full sample

https://github.com/dotnet-demos/roslyn-compile-with-analyzers