Question

I am trying to find all references in solution for a type. My starting point is a span inside a file (current cursor position) like 110:116. Looking at the samples coming with Roslyn I found that I need SymbolFinder.FindReferencesAsync(theType, solution). I created File->NewProject for test solution and then tried:

  1. Create syntax tree
  2. Load solution
  3. Find the Document using the tree // I fail here, returns null
  4. Extract the ISymbol (theType) // How?

I was not able to format the code belo so a screenshot for easier reading is here:

enter image description here

string fileContent = 
    @"using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace APISampleUnitTestsCS
    {
        class Class1
        {
        }
    }";

// it doesn;t matter if I supply or not the 2 and 3 parameters
var tree = SyntaxFactory.ParseSyntaxTree(fileContent, "thePathTo_fileContent", new CSharpParseOptions());

MSBuildWorkspace workspace = MSBuildWorkspace.Create();
// Open the solution within the workspace.
Microsoft.CodeAnalysis.Solution originalSolution = workspace.OpenSolutionAsync(dte.Solution.FileName).Result;

// document is null
var document = originalSolution.GetDocument(tree);

//var textSpan = new Microsoft.CodeAnalysis.Text.TextSpan(textExtent.Span.Span.Start, asd.Span.Span.Length);
var textSpan = new Microsoft.CodeAnalysis.Text.TextSpan(110, 116); //these values are for stackoverlow question

// at least I can get TypeDeclarationSyntax. But how to extraxt the ISymbol???
var tt = tree.GetRoot().FindNode(textSpan) as Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax;
Was it helpful?

Solution

solution.GetDocument(syntaxTree) gives you the document that gave you that syntax tree when you called GetSyntaxTreeAsync. You can't pass it an arbitrary syntax tree -- only one you got from a document somewhere. It's just a convenient helper to "go back" to the document from whence it came.

I'm not exactly sure what you're trying to do from the snippet, so I'm going to make three guesses:

  1. if you're trying to analyze a file that's already in that solution, you should be taking the Solution object you got in originalSolution and find the file document there.

  2. if you want to do analysis as if that additional tree was also added to your document, you can call Solution.AddDocument() to add that as a document, and then you can analyze it from there. Remember Roslyn is immutable, when you call Solution.AddDocument, you get a new solution to analyze, so hold onto what it gives you!

  3. If all you're trying to do is find a symbol which you already know by name, consider finding the Project in your solution that contains that type, calling GetCompilationAsync, and then either calling GetTypeByMetadataName or walking the namespaces to get your type symbol.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top