Roslyn: getting character in parent or ancestor of SyntaxNode

I am writing a Roslyn analyzer to raise diagnostics when a specific library method is used in a specific method of a particular class, but I cannot get a character in the parent or ancestral syntax nodes.

For example,

class C
{
    void M()
    {
        MyLibrary.SomeMethod();
    }
}

And this is the code for analysis SyntaxNode 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 return SymbolInfofrom the ancestor SyntaxNode.

Is my approach right or should I try a different approach?

+4
source share
1 answer

Thanks Jeroen Vannevel ! I needed to usesemanticModel.GetDeclaredSymbol()

+3
source

Source: https://habr.com/ru/post/1628716/


All Articles