26
ROSLYN What it is and how to get started Oslo/NNUG Tomas Jansson 27/05/2014

Roslyn

Embed Size (px)

DESCRIPTION

Short presentation about Roslyn, which is the new compiler from Microsoft.

Citation preview

Page 1: Roslyn

ROSLYN

What it is and how to get started

Oslo/NNUG

Tomas Jansson

27/05/2014

Page 2: Roslyn

THIS IS ME

Tomas JanssonManager & Practice Lead .NETBEKK Oslo

@[email protected]/mastojblog.tomasjansson.com

Page 3: Roslyn

AGENDA

What is Roslyn

Summary

The compile pipeline

How to get started

Existing projects

Demo

Page 4: Roslyn

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/

Page 5: Roslyn

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/

Page 6: Roslyn

WHAT IS ROSLYN?

It’s a ”compiler-as-a-service (caas)”

Page 7: Roslyn

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

Page 8: Roslyn

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

Page 9: Roslyn

Now we know

exactly what we

gonna get!

Page 10: Roslyn

WHY?

Power to the developers

Easier to add features

(for Microsoft)

Page 11: Roslyn

THE COMPILE PIPELINE

http://roslyn.codeplex.com/wikipage?title=Overview&referringTitle=Home

Page 12: Roslyn

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

Page 13: Roslyn

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.vsixImportant to run the .exe

first and then the vsix files

Page 14: Roslyn

PROJECT TEMPLATES

Page 15: Roslyn

PROJECT TEMPLATES

Console applications

Create code refactoring

plugins

Diagnostic, build

extensions

Page 16: Roslyn

SYNTAX VISUALIZER

Page 17: Roslyn

DEMO

https://github.com/mastoj/RoslynSamples

Page 18: Roslyn

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)));

Page 19: Roslyn

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 assemblyassembly.EntryPoint.Invoke(null, new object[] { args });

Page 20: Roslyn

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.

Page 21: Roslyn

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;}

Page 22: Roslyn

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

Page 23: Roslyn

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

Page 24: Roslyn

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

Page 25: Roslyn

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

Page 26: Roslyn

Thank you!

@TomasJansson