Skip to content

Instantly share code, notes, and snippets.

@amazedsaint
Created October 3, 2012 19:01
Show Gist options
  • Save amazedsaint/3829044 to your computer and use it in GitHub Desktop.
Save amazedsaint/3829044 to your computer and use it in GitHub Desktop.
Syntax Tree Dumper using Roslyn SyntaxWalker
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