Building Code Analyzers with Roslyn

Filip W

strathweb.com

@filip_woj

github.com/filipw

Roslyn

  • new .NET compiler platform
  • compiler as a service (access to compiler APIs)
  • code analysis (AST, semantic model)
  • facilitates building C# tooling
  • Apache 2.0

Code Analysis

C# Program

1: 
2: 
3: 
class Program
{
}

Syntax Trees

  • contain every bit of structural information about the code
  • know nothing of the outside world
  • round-trippable
  • immutable
  • built up of:
    • SyntaxNodes
    • SyntaxTokens
    • SyntaxTrivia

Syntax Tree

Rewrite a Syntax Tree

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
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

1: 
2: 
3: 
4: 
5: 
6: 
class Program
{
    static void Main()
    {
    }
}

Building stuff!

Roslyn-based code analysis tools

  • Analyzers
  • Code fixes
  • Refactorings

Analyzers

  • find problems in the code
  • can be installed as VSIX or Nuget
  • run in real time
  • integrate into the compiler
  • report Diagnostics

Analyzers

Code fixes

  • normally created for specific Diagnostics
  • can fix the problem identified by the analyzer
  • fix the problem in the scope of document/project/solution
  • typically ship together with analyzers
  • user has to invoke it (light bulb, Ctrl + .)

Code fixes

Refactorings

  • identifies and fixes the problem in one go
  • user has to explicitly ask for it (Ctrl+.)
  • use same engine behind the scenes as code fixes
  • only distributable via VSIX (thanks, MEF)

Refactorings

Show me the code!

Links

Tools

Projects