Andry Andry - 2 months ago 20
C# Question

Is there a way to visualize the SemanticModel in Roslyn

In many different cases, I search for a symbol in the

using Roslyn but cannot find it.

var sm = compilation.GetSemanticModel(tree);

So I would like to inspect the semantic model.

  • Is it possible to get the full list of types loaded in the

  • Is it possible to see everything that is available in the
    ? Without having to search for a specific symbol.

  • Is there a visual tool for visualizing the

This would help when debugging.


Following Dudi Keleti's approach, this snippet is being very effective:

return tree.GetRoot().DescendantNodesAndSelf()
.Where(node => node as ClassDeclarationSyntax != null || node as InterfaceDeclarationSyntax != null)
.Select(node => new KeyValuePair<SyntaxNode, ISymbol>(node, model.GetSymbolInfo(node).Symbol ?? model.GetDeclaredSymbol(node)));


I don't know about a visualizer tool, but you can do something like this:

static IEnumerable<ISymbol> GetTeeSymbols(SyntaxTree tree, SemanticModel model)
    return tree.GetRoot().
             Select(node => model.GetSymbolInfo(node).Symbol ?? model.GetDeclaredSymbol(node)).Where(info => info != null);

You can do it as extension method on tree and send a semantic model or extension on semantic model and send an IEnumerable<SyntaxTree> than go over each of them and do the LINQ

I don't know if it's perfect but it give you an idea of what going on. On my compilation its looks like this:

Syntax nodes and their symbols

With this you can build your own visualizer or maybe create a VISX to display it inside Visual Studio.


After I wrote this, I find a sample code in Roslyn that enumerate symbols in compilation.

Check also GetAllFieldAndMethodSymbolsInACompilation and TraverseAllExpressionsInASyntaxTreeUsingAWalker. Keep in mind that for complete solution you need to track also referenced assemblies.