Tuesday, June 23, 2015

Running Roslyn Analyzers from console application

This post require prior knowledge from my earlier post. In last post we saw how our C# program can compile other C# program via Roslyn compiler. Yes its 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 capital letter. See the code below. Now lets move on how this analyzer can be integrated to 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.

1 comment:

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