Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn SymbolFinder Convert Location to Syntax Node

Tags:

c#

roslyn

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?

like image 777
johnny 5 Avatar asked Dec 10 '22 11:12

johnny 5


2 Answers

You can use FindNode() which accepts a TextSpan

So your example would look something like:

var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan);
like image 179
JoshVarty Avatar answered Dec 21 '22 09:12

JoshVarty


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));
}
like image 34
johnny 5 Avatar answered Dec 21 '22 09:12

johnny 5