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/
7. 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
8. 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
12. 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
13. 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
18. 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)));
19. 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 });
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 using the 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 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
24. 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
25. 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
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