Search code examples
roslyncode-analysis

Programmatically access Code analysis results in Roslyn


I'm building a tool that analyses C# snippets and provides some feedback on them. I use

tree = CSharpSyntaxTree.ParseText(codeSample);

to get a SyntaxTree and then

semanticModel = compilation.GetSemanticModel(tree);

to get a SemanticModel.

I can find syntactic errors in the code with semanticModel.Compilation.GetDiagnostics(); but I know that there are also a bunch of code quality rules that Roslyn can perform as well (here and here) using the Roslyn Analyzers.

My question is: how can I obtain those code-style issues in code programmatically, like I can get the syntactic errors?


Solution

  • Solution:

    Firstly you have to load the CodeAnalysis .dll, and get the analyzers from it:

    var assembly = Assembly.LoadFrom(@"Microsoft.CodeAnalysis.NetAnalyzers.dll");
    var analyzers = assembly.GetTypes()
                            .Where(t => t.GetCustomAttribute<DiagnosticAnalyzerAttribute>() is object)
                            .Select(t => (DiagnosticAnalyzer)Activator.CreateInstance(t))
                            .ToArray();
    

    Then, when generating the Compilation, add the analyzers with WithAnalyzers(...):

    var compilationWithAnalyzers = CSharpCompilation.Create("query")
                    .AddReferences(
                        MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
                    ).AddSyntaxTrees(tree).WithAnalyzers(ImmutableArray.Create(analyzers));
    

    After that you can get the CodeAnalysis results with:

    var analyzerDiagnostics = (await compilationWithAnalyzers.GetAllDiagnosticsAsync()).ToList();