What is Roslyn and how can we use it? Telerik Academy Plus C# 6.0 and Roslyn Seminar
What is "Roslyn"? Exposing the compiler Pipeline API layer Working with syntax Trees, Nodes, Tokens, Trivia Semantics Compilation Semantic model 2
.NET Compiler Platform
Normal compiler – traditionally black box Source code in Magic in between Assemblies out Nowadays we use Intellisense Refactoring Code productivity tools 4
Traditional compiler pipeline Parser – parses text to syntax objects Symbols/Metadata – declarations are collected Binder – identifiers, code flow bind to symbols IL Emitter – IL assembly creation 5
Each phase now has corresponding API 6
The Grammar Nazi of Programming
Why – without text processing tools can: See the structure of the source code Create and rearrange source code Contains Syntax Trees Syntax Nodes Syntax Tokens Syntax Trivia Spans and Kinds 8
Syntax Trees Primary structure for compilation Hold all the source information Constructs Tokens Everything! Two-way communication with the source text Immutable and thread-safe Contains Nodes, Tokens, Trivia 9
Syntax Trees Useful members GetRoot() GetText() GetChanges() Options 10 var code = File.ReadAllText("Code.cs"); var tree = SyntaxFactory.ParseSyntaxTree(code);
Syntax Nodes Primary element of Syntax Tree Represents Declarations Statements Clauses Expressions Each node has children – other nodes and tokens 11
Syntax Nodes Useful members Modifiers Type Parent DescendantNodes() 12 var localDeclarationNodes = tree.GetRoot().DescendantNodes().DescendantNodes().OfType ();.OfType ();
Syntax Tokens Smallest syntactic fragment – no children Represents Keywords Identifiers Literals Punctuation 13 var tokens = node.ChildTokens(); var token = tokens.First(); token.Value;
Syntax Trivia Whitespace, comments, etc. Spans Position and number of characters within the source code Kinds Identifies the exact syntax element represented Errors Missing tokens or skipped tokens 14
Let's build something
Compilation needs Syntax Tree Compilation Options File Reference 16 var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var reference = new MetadataFileReference(typeof(object).Assembly.Location); var compilation = CSharpCompilation.Create("Test").WithOptions(options).WithOptions(options).AddSyntaxTrees(tree).AddSyntaxTrees(tree).AddReferences(reference);.AddReferences(reference);
Additional semantic information for source code Symbols at specific location Resultant type of any expression Errors and warnings Variable flow in and out of source parts Answer to everything – 42? 17
Semantic Model 18 var comp = CreateCompilation(tree, options, reference); var model = comp.GetSemanticModel(tree); var localDeclarationNodes = tree.GetRoot().DescendantNodes().DescendantNodes().OfType ();.OfType (); foreach (var node in localDeclarationNodes) { var info = model.GetTypeInfo(node.Declaration.Type); var info = model.GetTypeInfo(node.Declaration.Type); Console.WriteLine("{0} {1}", info.Type, node.Declaration); Console.WriteLine("{0} {1}", info.Type, node.Declaration);}
Actually use the code
Using the dynamically compiled result Emit to memory stream Load assembly from byte array Use with normal reflection 20 using (var memory = new MemoryStream()) { compilation.Emit(memory); compilation.Emit(memory); var assembly = Assembly.Load(memory.GetBuffer()); var assembly = Assembly.Load(memory.GetBuffer()); var type = assembly.GetType("NameOfType"); var type = assembly.GetType("NameOfType"); var instance = Activator.CreateInstance(type); var instance = Activator.CreateInstance(type);}
Live Demo
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране