Telerik blogs
roslyn_header

Roslyn is made up of the open-source C# and Visual Basic compilers and code analysis APIs for Microsoft's development stack. Very few people realize that Roslyn came out in October 2011 as a preview that worked with Visual Studio 2010 SP1. While there has been several changes since 2011, it really took the spotlight at the //Build conference held in 2014 when Microsoft open-sourced it and made it available for Visual Studio 2013.

Fast forward to today, we can see on the landing page that Visual Studio 2015 is front and center for Roslyn. In this post, I'll walk you through a few samples that I found helpful to wrap my head around Roslyn.

Getting Started

One of the easiest ways to get started with Roslyn is by downloading the Visual Studio 2015 Preview and installing it. I'd recommend using a Virtual Machine in order to do so. After that, navigate to the Roslyn Project and download the source code. You should have a folder with several files and folders in it. We are only concerned with the one named Src, so go ahead and navigate to it as shown below.

Roslyn Source Code

Double click on the Roslyn.sln file and the project will load. Upon first launch, go ahead and build the solution. Navigate one directory back and you will see Binaries, then navigate inside Debug as shown below.

A Compiler is Found

I See a Compiler!

Anyone used to C# will be familiar with csc.exe. If you check the date created, you will see that we just compiled our own version of it. Cool, but how does that help?

Go ahead and run csc from the command prompt and you will see the following:

C:\Users\Michael\Documents\Visual Studio 2015\Projects\roslyn\Binaries\Debug>csc

Microsoft (R) Visual C# Compiler version 1.0.0.0
Copyright (C) Microsoft Corporation. All rights reserved.

warning CS2008: No source files specified.
error CS1562: Outputs without source must have the /out option specified

C:\Users\Michael\Documents\Visual Studio 2015\Projects\roslyn\Binaries\Debug>
Nothing should be a surprise here as you did not specify a source file to be compiled, but what is really interesting is the ability to look into the source code and understand the warning and error messages being generated.

If we search for the text, Outputs without source must have the /out option specified, we could find in the source code where it pulls that error message from. In this case, it is coming from the ResourceManager class.

Visual Studio Output

If you want to actually change the way the compiler behaves as it reads through a C# program than check out this blog post. This demonstrates how Anders Hejlsberg added support for French quotes in the C# compiler with just a few lines of code.

Taking a Look Under the Hood

Go ahead and download the following files:

Once those are installed, open Visual Studio 2015 Preview and navigate to the "Compiler Platform Console Application" template as shown below.

Visual Studio Output

Once the project spins up, you will notice several references have been added, but you will primarily be working with the Microsoft.CodeAnalysis namespaces.

Add the following code to your Main method:

public static void Main(string[] args)
 {
     SyntaxTree tree = CSharpSyntaxTree.ParseText(
     @"using System;
     using System.Collections.Generic;
     using System.Text;

     namespace HelloWorld
     {
         class Program
         {
             static void Main(string[] args)
             {
                 Console.WriteLine(""Hello, TDN!"");
             }
         }
     }");

     var root = (CompilationUnitSyntax)tree.GetRoot();
     var compilation = CSharpCompilation.Create("HelloTDN")
            .AddReferences(references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) })
            .AddSyntaxTrees(tree);
 }
Set a breakpoint on the last curly brace and turn on the Roslyn Syntax Visualizer by going to View -> Other Windows -> Roslyn Syntax Visualizer and you will see the following (which should be blank at the moment):

Visual Studio Output

Run the application and scroll to the top of the document. Click on SyntaxTree as declared in the code and it will take you to the proper node. From there, you can view a vast variety of information. In my example, I am taking a look at the Leading and Trailing WhiteSpace. Of course, you can dig deeper and learn exactly what is going on behind the scenes of your app.

In Action

You have just seen an example of compilation. A Compilation is an abstract class with language-specific derivatives.

SemanticModels

Now that we have seen a Compilation, we can ask it for a SemanticModel for any SyntaxTree contained in that Compilation.

Microsoft describes SemanticModels as something that can be queried to answer questions like:

  • "What names are in scope at this location?"
  • "What members are accessible from this method?"
  • "What variables are used in this block of text?"
  • "What does this name/expression refer to?"

A simple example of this could be achieved with the following code:

var model = compilation.GetSemanticModel(tree);
var nameInfo = model.GetSymbolInfo(root.Usings[0].Name);
var systemSymbol = (INamespaceSymbol)nameInfo.Symbol;
foreach (var ns in systemSymbol.GetNamespaceMembers())
{
   Console.WriteLine(ns.Name);
}
In this sample, we create a model using the GetSemanticModel method passing in our tree that we defined earlier. We declare another variable called nameInfo that will bind to the "using System;" namespace and pull all the systems for the member into a console window.

Congrats, you just successfully bound a name to find a symbol.

Next Steps for Exploring Roslyn

I hope this gives you a quick look at how powerful Roslyn actually is. While I was writing this article, I came across a lot of documentation that was outdated, but it looks like the community is quickly fixing it and adding more features. We haven't dug into binding expressions, syntax transformation and diagnostics, but thankfully this has been documented.

At Telerik, we've already been working with Roslyn and we will be releasing a new version of JustCode for Visual Studio 2015 that will take advantage of it for enhancing developer productivity. We still have the same great controls for web, desktop and mobile applications that will be ready to go when Visual Studio 2015 is released. Thanks for taking the time to read this and if you have any comments or links to share, feel free to leave them below.

Header image courtesy of Stephen Nakatani


MichaelCrump
About the Author

Michael Crump

is a Microsoft MVP, Pluralsight and MSDN author as well as an international speaker. He works at Telerik with a focus on everything mobile.  You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

Comments

Comments are disabled in preview mode.