Skip to content

Instantly share code, notes, and snippets.

@jelster
Created May 22, 2012 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jelster/2771993 to your computer and use it in GitHub Desktop.
Save jelster/2771993 to your computer and use it in GitHub Desktop.
sample implementation of a recursive (indirectly speaking) SymbolVisitor for Roslyn CTP. Returns flattened list of type symbols regardless of namespace nesting
public class Walk : SymbolVisitor<NamespaceSymbol, IEnumerable<NamedTypeSymbol>>
{
protected override IEnumerable<NamedTypeSymbol> VisitNamespace(NamespaceSymbol symbol, NamespaceSymbol argument)
{
var types = new List<NamedTypeSymbol>();
foreach (var ns in symbol.GetNamespaceMembers())
{
var closeTypes = types;
closeTypes.AddRange(Visit(ns));
closeTypes.AddRange(ns.GetTypeMembers());
}
return types;
}
}
/* and a quick self-standing unit test (xUnit) */
public class TypeSymbolWalkerFixture
{
Walk sut = new Walk();
[Fact]
public void when_walk_nested_namespaces_with_types_returns_all_unnested_classes()
{
var code = @"
namespace Bar {
public class FooA {}
public class BarB {}
namespace BarB {
public class FooB { public class NestedFoo {} }
public class FooC {}
}
}";
var tree = SyntaxTree.ParseCompilationUnit(code);
var comp = Compilation.Create("testA.dll").AddSyntaxTrees(tree);
var result = sut.Visit(comp.GlobalNamespace);
Assert.NotEmpty(result);
Assert.True(result.Count() == 4);
}
}
@jelster
Copy link
Author

jelster commented May 23, 2012

added tweaked code + a test to prove functionality

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment