Building Code Analyzers with the new C# compiler platform (Roslyn)

Building Code Analyzers with Roslyn

Filip W

Open Source Guy

strathweb.com@filip_wojgithub.com/filipw

Code Analysis

C# Program

    
class Program
{
}
    

Syntax Tree

Rewrite a Syntax Tree

    
var tree = await document.GetSyntaxRootAsync();
var newTree = tree.DescendantNodesAndSelf().
  OfType<ClassDeclarationSyntax>().
  First().AddMembers(
    SyntaxFactory.MethodDeclaration(
        SyntaxFactory.PredefinedType(SyntaxFactory.Token(
          SyntaxKind.VoidKeyword)),
        SyntaxFactory.Identifier("Main"))
        .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(
          SyntaxKind.StaticKeyword)))
        .WithBody(SyntaxFactory.Block())
      )
    ).NormalizeWhitespace();
var newDocument = document.WithSyntaxRoot(newTree);
    

Modified program

    
class Program
{
    static void Main()
    {
    }
}
    

New Syntax Tree

Semantic Model

    
var tree = await document.GetSyntaxRootAsync();
var classDeclaration = tree.DescendantNodesAndSelf().
  OfType<ClassDeclarationSyntax>().First();

var semanticModel = await document.GetSemanticModelAsync();
var typeSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);

var references = await SymbolFinder.FindReferencesAsync(document.Project.Solution, typeSymbol);
// process references
    

Code analysis

Syntax Tree-based

- **structural** information about the code

- immutable

- round-trippable

Semantic Model-based

- **semantic** meaning of the syntax trees

- backed by compilation

- symbols, diagnostics, code flow..

Building stuff!

Analyzers

Code fixes

Refactorings

Roslyn Features API

   

Find issue Change code Diagnostic Distribution
Analyzer 🔍 🦄
Code fix 🔧 🦄
Refactoring 🔧

Show me the code!

Links

Tools & Demos

Projects