Reputation: 461
I'm writing a Roslyn analyzer to raise a diagnostic when a certain library method is used within a certain method in a certain kind of class, but I cannot retrieve the symbol in the parent or ancestor syntax nodes.
For example,
class C
{
void M()
{
MyLibrary.SomeMethod();
}
}
And this is the code for analyzing the SyntaxNode
of SyntaxKind.InvocationExpression
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var invocationExpression = context.Node as InvocationExpressionSyntax;
var methodSymbol = context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol as IMethodSymbol;
if (methodSymbol == null) { return; }
// check if it is the library method I am interested in. No problems here
if (!methodSymbol.Name.Equals("SomeMethod") ||
!methodSymbol.ContainingSymbol.ToString().Equals("MyNamespace.MyLibrary"))
{ return; }
// this retrieves outer method "M".
var outerMethodSyntax = invocationExpression.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (outerMethodSyntax == null) { return; }
// symbol.Symbol is always null here
var symbol = context.SemanticModel.GetSymbolInfo(outerMethodSyntax);
...
So my question is, is it possible to retrieve SymbolInfo
from an ancestor SyntaxNode
.
Is my approach correct or should I try another approach?
Upvotes: 8
Views: 2244
Reputation: 461
Thanks Jeroen Vannevel! I needed to use semanticModel.GetDeclaredSymbol()
Upvotes: 5