johnny 5
johnny 5

Reputation: 21005

Roslyn SymbolFinder Convert Location to Syntax Node

I'm using a SymbolFinder to find all references to a variable. I would like to check if this Field is assigned to outside of its definition.

var references = await SymbolFinder.FindReferencesAsync(equivalentSymbol, 
                              context.GetSolution(), cancellationToken);
//Reference is grouped by variable name 
var reference = references.FirstOrDefault();

foreach (var location in reference.Locations)
{
   //How Do I check if the reference is an assignment?               
}

How can I Convert the location into a syntax node, and then check if the node is an assignment?

Upvotes: 4

Views: 1622

Answers (2)

JoshVarty
JoshVarty

Reputation: 9426

You can use FindNode() which accepts a TextSpan

So your example would look something like:

var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan);

Upvotes: 11

johnny 5
johnny 5

Reputation: 21005

I've created an extension Method to do so:

public static SyntaxNode GetNodeFromLocation(this SyntaxTree tree, ReferenceLocation location)
{ 
    var lineSpan = location.Location.GetLineSpan();
    return tree.GetRoot().DescendantNodes().FirstOrDefault(n => n.GetLocation().GetLineSpan().IsEqual(lineSpan));
}

Upvotes: 2

Related Questions