Syntax tree

suggest change

A Syntax Tree is an immutable data structure representing the program as a tree of names, commands and marks (as previously configured in the editor.)

For example, assume a Microsoft.CodeAnalysis.Compilation instance named compilation has been configured. There are multiple ways to list the names of every variable declared in the loaded code. To do so naively, take all pieces of syntax in every document (the DescendantNodes method) and use Linq to select nodes that describe variable declaration:

foreach (var syntaxTree in compilation.SyntaxTrees)
{
    var root = await syntaxTree.GetRootAsync();
    var declaredIdentifiers = root.DescendantNodes()
        .Where(an => an is VariableDeclaratorSyntax)
        .Cast<VariableDeclaratorSyntax>()
        .Select(vd => vd.Identifier);

    foreach (var di in declaredIdentifiers)
    {
        Console.WriteLine(di);
    }
}

Every type of C# construct with a corresponding type will exist in the syntax tree. To quickly find specific types, use the Syntax Visualizer window from Visual Studio. This will interpret the current opened document as a Roslyn syntax tree.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


.NET Compiler Platform Roslyn:
* Syntax tree

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script
150 .NET Compiler Platform Roslyn