Chapter 27. The Roslyn Compiler
The C# compiler is itself written in C# and available as a set of modular libraries known as Roslyn. By referencing these libraries, you can utilize the compiler’s functionality in many ways besides compiling source code to an assembly. For example, you can write static code analysis and refactoring tools, editors with syntax highlighting and code completion, and Visual Studio plug-ins that understand C# code.
You can download the Roslyn libraries from NuGet, and there are packages for both C# and Visual Basic. Because both languages share some architecture, there are common dependencies. The NuGet package ID for the C# compiler libraries is Microsoft.CodeAnalysis.CSharp.
Roslyn’s GitHub site also includes documentation, examples, and walkthroughs that demonstrate code analysis and refactoring.
Roslyn Architecture
The Roslyn architecture separates compilation into three phases:
Parsing code into syntax trees (the syntactic layer)
Binding identifiers to symbols (the semantic layer)
Emitting Intermediate Language (IL)
In the first phase, a parser reads C# code and outputs syntax trees. A syntax tree is a Document Object Model (DOM) that describes source code in tree structure.
The second phase is the one in which C#’s static binding takes place. Assembly references are read, and the compiler determines, for instance, that “Console” refers to System.Console
in System.Console.dll. Overload resolution and type inference are a part of this, too.
Get C# 8.0 in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.