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.
SemanticModel
? SemanticModel
? Without having to search for a specific symbol. SemanticModel
? 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().
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:
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.
The SemanticModel
is merely a bridge between the syntax and symbols, it allows you to query parts of the syntax for symbols. The symbols, however, are all available from the Compilation
. Compilation.GetTypeByMetadataName
is your friend in that regard.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.