Created
October 3, 2012 19:01
-
-
Save amazedsaint/3829044 to your computer and use it in GitHub Desktop.
Syntax Tree Dumper using Roslyn SyntaxWalker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using Roslyn.Compilers.CSharp; | |
namespace RoslynApp | |
{ | |
public static class SyntaxTreeExtensions | |
{ | |
public static void Dump(this SyntaxTree tree) | |
{ | |
var writer = new ConsoleDumpWalker(); | |
writer.Visit(tree.GetRoot()); | |
} | |
class ConsoleDumpWalker : SyntaxWalker | |
{ | |
public override void Visit(SyntaxNode node) | |
{ | |
int padding = node.Ancestors().Count(); | |
//To identify leaf nodes vs nodes with children | |
string prepend = node.ChildNodes().Any() ? "[-]" : "[.]"; | |
//Get the type of the node | |
string line = new String(' ', padding) + prepend + | |
" " + node.GetType().ToString(); | |
//Write the line | |
System.Console.WriteLine(line); | |
base.Visit(node); | |
} | |
} | |
} | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
const string code = @"class SimpleClass { | |
public void SimpleMethod() | |
{ | |
var list = new List<int>(); | |
list.Add(20); | |
list.Add(40); | |
var result = from item in list | |
where item > 20 | |
select item; | |
} | |
}"; | |
//Parsing the syntax tree | |
var tree = SyntaxTree.ParseText(code); | |
//Dumping the syntax tree | |
tree.Dump(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment