Andry Andry - 5 days ago 5
C# Question

Is there a way to visualize the SemanticModel in Roslyn

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

SemanticModel
using Roslyn but cannot find it.

var sm = compilation.GetSemanticModel(tree);
sm.GetSymbolInfo(node);
sm.GetDeclaredSymbol(node);


So I would like to inspect the semantic model.


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

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

  • Is there a visual tool for visualizing the
    SemanticModel
    ?



This would help when debugging.

Edit



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)));

Answer

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().
             DescendantNodesAndSelf().
             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.

Update

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.

Comments