Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Identifier in Semantic Model

Tags:

c#

roslyn

Supposing I have a source file that looks like this:

public class FieldReference
{
    int field;

    public FieldReference()
    {
        field = 1;
    }
}

I am using a SyntaxRewriter to visit all of the identifiers in this file. In the VisitIdentifierName method, I want to look up the identifier in the semantic model, in order to discover if an identifier refers to a member of the current class.

This is what I have so far:

public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
{
    SemanticModel model = this.compilation.GetSemanticModel(this.src);
    // ?? look up identifier in compilation here ??
    return base.VisitIdentifierName(node);
}

However I can't find away to look up the identifier in the symantic model - there is no overload of the SemanticModel.GetDeclaredSymbol method that accepts an IdentifierNameSyntax.

Any idea how I should do this?

like image 988
Grokys Avatar asked Aug 30 '12 09:08

Grokys


1 Answers

You should use SemanticModel.GetSymbolInfo on the expression (in this particular case the IdentifierNameSyntax).

GetDeclaredSymbol is for going from the declaration point (int field; above) to a symbol. To perform the compiler's binding logic and see what symbol a particular expression binds to, use GetSymbolInfo.

like image 149
Kevin Pilch Avatar answered Sep 21 '22 16:09

Kevin Pilch