ROSLYN
What it is and how to get started
Oslo/NNUG
Tomas Jansson
27/05/2014
THIS IS ME
Tomas Jansson
Manager & Practice Lead .NET
BEKK Oslo
@TomasJansson
tomas.jansson@bekk.no
github.com/mastoj
blog.tomasjansson.com
AGENDA
What is Roslyn
Summary
The compile
pipeline
How to get
started
Existing projectsDemo
WHAT IS ROSLYN?
The .NET Compiler Platform ("Roslyn") provides open-source
C# and Visual Basic compilers with rich code analysis APIs.
You can build code analysis tools with the same APIs that
Microsoft is using to implement Visual Studio!
http://roslyn.codeplex.com/
WHAT IS ROSLYN?
The .NET Compiler Platform ("Roslyn") provides open-source
C# and Visual Basic compilers with rich code analysis APIs.
You can build code analysis tools with the same APIs that
Microsoft is using to implement Visual Studio!
http://roslyn.codeplex.com/
WHAT IS ROSLYN?
It’s a ”compiler-as-a-service (caas)”
WHAT IS A COMPILER-AS-A-SERVICE?
”C# compiler is like a box of chocolates,
you never know what you’re gonna get”
http://theawesomedaily.theawesomedaily.netdna-cdn.com/wp-content/uploads/2013/12/forrest-gump-original.jpeg
WHAT IS A COMPILER-AS-A-SERVICE?
”C# compiler is like a box of chocolates,
you never know what you’re gonna get”
This was life
before Roslyn
http://theawesomedaily.theawesomedaily.netdna-cdn.com/wp-content/uploads/2013/12/forrest-gump-original.jpeg
Now we know
exactly what
we gonna get!
WHY?
Power to the
developers
Easier to add
features (for
Microsoft)
THE COMPILE PIPELINE
http://roslyn.codeplex.com/wikipage?title=Overview&referringTitle=Home
HOW TO GET STARTED
Download and install the SDK: http://roslyn.codeplex.com/
Run ”Install Roslyn Preview into Roslyn Experimental Hive.exe”
Install all the Visual Studio Extensions
Roslyn End User Preview.vsix
Roslyn SDK Project Templates.vsix
Roslyn Syntax Visualizer.vsix
HOW TO GET STARTED
Download and install the SDK: http://roslyn.codeplex.com/
Run ”Install Roslyn Preview into Roslyn Experimental Hive.exe”
Install all the Visual Studio Extensions
Roslyn End User Preview.vsix
Roslyn SDK Project Templates.vsix
Roslyn Syntax Visualizer.vsix
Important to run
the .exe first and
then the vsix files
PROJECT TEMPLATES
PROJECT TEMPLATES
Console
applications
Create code
refactoring
plugins
Diagnostic,
build
extensions
SYNTAX VISUALIZER
DEMO
https://github.com/mastoj/RoslynSamples
KEY PARTS: CONSOLE APPLICATION
Install-package -pre Microsoft.CodeAnalysis.Csharp
// Create the syntax tree
var syntaxTree = CSharpSyntaxTree.ParseText(code);
// Compile the syntax tree
var compilation = CSharpCompilation.Create("Executable", new[] {syntaxTree},
_defaultReferences,
new CSharpCompilationOptions(OutputKind.ConsoleApplication));
private static IEnumerable<string> _defaultReferencesNames =
new [] { "mscorlib.dll", "System.dll", "System.Core.dll" };
private static string _assemblyPath =
Path.GetDirectoryName(typeof(object).Assembly.Location);
private static IEnumerable<MetadataFileReference> _defaultReferences =
_defaultReferencesNames.Select(
y => new MetadataFileReference(Path.Combine(_assemblyPath, y)));
KEY PARTS: CONSOLE APPLICATION
private Assembly CreateAssembly(CSharpCompilation compilation)
{
using(var outputStream = new MemoryStream())
using (var pdbStream = new MemoryStream())
{
// Emit assembly to streams
var result = compilation.Emit(outputStream, pdbStream: pdbStream);
if (!result.Success)
{
throw new CompilationException(result);
}
// Load the compiled assembly;
var assembly = Assembly.Load(outputStream.ToArray(), pdbStream.ToArray());
return assembly;
}
}
// Execute the assembly
assembly.EntryPoint.Invoke(null, new object[] { args });
KEY PARTS: DIAGNOSIS (DIAGNOSTIC ANALYZER)
Use project template: Diagnosis with Code Fix
public class DiagnosticAnalyzer : ISyntaxNodeAnalyzer<SyntaxKind>
public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest
{
get { return ImmutableArray.Create(SyntaxKind.IfStatement); }
}
public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel,
Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
What type analysis do
we want?
What kind of syntax
are we interested in?
Analyze and add
diagnostic.
KEY PARTS: DIAGNOSIS (CODE FIX PROVIDER)
public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document,
TextSpan span, IEnumerable<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
// Get the syntax root
var root = await document.GetSyntaxRootAsync(cancellationToken);
// Find the token that triggered the fix
var token = root.FindToken(span.Start);
if (token.IsKind(SyntaxKind.IfKeyword))
{
// Find the statement you want to change
var ifStatment = (IfStatementSyntax)token.Parent;
// Create replacement statement
var newIfStatement = ifStatment
.WithStatement(SyntaxFactory.Block(ifStatment.Statement))
.WithAdditionalAnnotations(Formatter.Annotation);
// New root based on the old one
var newRoot = root.ReplaceNode(ifStatment, newIfStatement);
return new[] {CodeAction.Create("Add braces",
document.WithSyntaxRoot(newRoot))};
}
return null;
}
EXISTING PROJECTS
ScriptCS
Build using the scripting engine in the CTP
Script engine is not available in the User Preview, but it will come back at some point
EXISTING PROJECTS
ScriptCS
Build using the scripting engine in the CTP
Script engine is not available in the User Preview, but it will come back at some point
Great for
exploration
SUMMARY
Roslyn is the new C# compiler from Microsoft
It’s open source
It’s a compiler-as-a-service
The have made easy to use project templates to extend Visual studio
RESOURCES
Good example blog post: http://tinyurl.com/RoslynExample
The Roslyn project: http://roslyn.codeplex.com/
Syntax Visualizer Overview: http://tinyurl.com/RoslynVisualizer
Source code to my demos: https://github.com/mastoj/RoslynSamples
Presentation from BUILD 2014: http://channel9.msdn.com/Events/Build/2014/2-577
My presentation on Slideshare: http://tinyurl.com/123Roslyn
Thank you!
@TomasJansson

Roslyn

  • 1.
    ROSLYN What it isand how to get started Oslo/NNUG Tomas Jansson 27/05/2014
  • 2.
    THIS IS ME TomasJansson Manager & Practice Lead .NET BEKK Oslo @TomasJansson tomas.jansson@bekk.no github.com/mastoj blog.tomasjansson.com
  • 3.
    AGENDA What is Roslyn Summary Thecompile pipeline How to get started Existing projectsDemo
  • 4.
    WHAT IS ROSLYN? The.NET Compiler Platform ("Roslyn") provides open-source C# and Visual Basic compilers with rich code analysis APIs. You can build code analysis tools with the same APIs that Microsoft is using to implement Visual Studio! http://roslyn.codeplex.com/
  • 5.
    WHAT IS ROSLYN? The.NET Compiler Platform ("Roslyn") provides open-source C# and Visual Basic compilers with rich code analysis APIs. You can build code analysis tools with the same APIs that Microsoft is using to implement Visual Studio! http://roslyn.codeplex.com/
  • 6.
    WHAT IS ROSLYN? It’sa ”compiler-as-a-service (caas)”
  • 7.
    WHAT IS ACOMPILER-AS-A-SERVICE? ”C# compiler is like a box of chocolates, you never know what you’re gonna get” http://theawesomedaily.theawesomedaily.netdna-cdn.com/wp-content/uploads/2013/12/forrest-gump-original.jpeg
  • 8.
    WHAT IS ACOMPILER-AS-A-SERVICE? ”C# compiler is like a box of chocolates, you never know what you’re gonna get” This was life before Roslyn http://theawesomedaily.theawesomedaily.netdna-cdn.com/wp-content/uploads/2013/12/forrest-gump-original.jpeg
  • 9.
    Now we know exactlywhat we gonna get!
  • 10.
    WHY? Power to the developers Easierto add features (for Microsoft)
  • 11.
  • 12.
    HOW TO GETSTARTED Download and install the SDK: http://roslyn.codeplex.com/ Run ”Install Roslyn Preview into Roslyn Experimental Hive.exe” Install all the Visual Studio Extensions Roslyn End User Preview.vsix Roslyn SDK Project Templates.vsix Roslyn Syntax Visualizer.vsix
  • 13.
    HOW TO GETSTARTED Download and install the SDK: http://roslyn.codeplex.com/ Run ”Install Roslyn Preview into Roslyn Experimental Hive.exe” Install all the Visual Studio Extensions Roslyn End User Preview.vsix Roslyn SDK Project Templates.vsix Roslyn Syntax Visualizer.vsix Important to run the .exe first and then the vsix files
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
    KEY PARTS: CONSOLEAPPLICATION Install-package -pre Microsoft.CodeAnalysis.Csharp // Create the syntax tree var syntaxTree = CSharpSyntaxTree.ParseText(code); // Compile the syntax tree var compilation = CSharpCompilation.Create("Executable", new[] {syntaxTree}, _defaultReferences, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); private static IEnumerable<string> _defaultReferencesNames = new [] { "mscorlib.dll", "System.dll", "System.Core.dll" }; private static string _assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); private static IEnumerable<MetadataFileReference> _defaultReferences = _defaultReferencesNames.Select( y => new MetadataFileReference(Path.Combine(_assemblyPath, y)));
  • 19.
    KEY PARTS: CONSOLEAPPLICATION private Assembly CreateAssembly(CSharpCompilation compilation) { using(var outputStream = new MemoryStream()) using (var pdbStream = new MemoryStream()) { // Emit assembly to streams var result = compilation.Emit(outputStream, pdbStream: pdbStream); if (!result.Success) { throw new CompilationException(result); } // Load the compiled assembly; var assembly = Assembly.Load(outputStream.ToArray(), pdbStream.ToArray()); return assembly; } } // Execute the assembly assembly.EntryPoint.Invoke(null, new object[] { args });
  • 20.
    KEY PARTS: DIAGNOSIS(DIAGNOSTIC ANALYZER) Use project template: Diagnosis with Code Fix public class DiagnosticAnalyzer : ISyntaxNodeAnalyzer<SyntaxKind> public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.IfStatement); } } public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) What type analysis do we want? What kind of syntax are we interested in? Analyze and add diagnostic.
  • 21.
    KEY PARTS: DIAGNOSIS(CODE FIX PROVIDER) public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { // Get the syntax root var root = await document.GetSyntaxRootAsync(cancellationToken); // Find the token that triggered the fix var token = root.FindToken(span.Start); if (token.IsKind(SyntaxKind.IfKeyword)) { // Find the statement you want to change var ifStatment = (IfStatementSyntax)token.Parent; // Create replacement statement var newIfStatement = ifStatment .WithStatement(SyntaxFactory.Block(ifStatment.Statement)) .WithAdditionalAnnotations(Formatter.Annotation); // New root based on the old one var newRoot = root.ReplaceNode(ifStatment, newIfStatement); return new[] {CodeAction.Create("Add braces", document.WithSyntaxRoot(newRoot))}; } return null; }
  • 22.
    EXISTING PROJECTS ScriptCS Build usingthe scripting engine in the CTP Script engine is not available in the User Preview, but it will come back at some point
  • 23.
    EXISTING PROJECTS ScriptCS Build usingthe scripting engine in the CTP Script engine is not available in the User Preview, but it will come back at some point Great for exploration
  • 24.
    SUMMARY Roslyn is thenew C# compiler from Microsoft It’s open source It’s a compiler-as-a-service The have made easy to use project templates to extend Visual studio
  • 25.
    RESOURCES Good example blogpost: http://tinyurl.com/RoslynExample The Roslyn project: http://roslyn.codeplex.com/ Syntax Visualizer Overview: http://tinyurl.com/RoslynVisualizer Source code to my demos: https://github.com/mastoj/RoslynSamples Presentation from BUILD 2014: http://channel9.msdn.com/Events/Build/2014/2-577 My presentation on Slideshare: http://tinyurl.com/123Roslyn
  • 26.

Editor's Notes

  • #2 Present the topic
  • #3 Keep it short
  • #12 Each phase is a separate component. * Parsing phase – tokenized and parsed (Syntax tree) * Declaration phase – forms the symbols (hierarchical symbol table) * Binding phase – match code against the symbols (model of the result from the compiler’s semantic analysis) * Emit phase – emitted as an assembly, IL code We don’t need to know all the details to get started, just do it