user1234554321
user1234554321

Reputation: 83

Roslyn: How to get candidate namespaces for unresolved types

Using Roslyn, is there a way I can get the list of candidate namespaces for each unresolved symbols in a list? If so, is there a way I can do a 'best match' for symbols with ambiguity, which belong to multiple possible namespaces?

I would like to generate a list of using statements for the unresolved symbols in a file. I am able to get the unresolved symbols from the semantic information using an approach like Roslyn : How to get unresolved types, but could not find a way to arrive at the namespaces for these symbols from the referenced assemblies in the project.

Upvotes: 1

Views: 980

Answers (1)

JoshVarty
JoshVarty

Reputation: 9426

I skimmed the Roslyn Repo and it looks like they use the SymbolFinder to retrieve information when they believe the user is missing a using: See here.

As for finding the "best" match, I believe that's something you'll have to implement according to what you consider to be the "best" match. Visual Studio simply shows you all candidate using statements.

Here's a sample I threw together quickly to demonstrate SymbolFinder:

var ws = new AdhocWorkspace();
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId();, VersionStamp.Create());
var solution = ws.AddSolution(solutionInfo);
var project = ws.AddProject("Sample", "C#");

//Add reference to mscorlib
var mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
project = project.AddMetadataReference(mscorlib);
ws.TryApplyChanges(project.Solution);

string text = @"
class C
{
    void M()
    {
        //Missing a using System;
        Console.Write();
    }
}";
var sourceText = SourceText.From(text);

//Add document to project
var doc = ws.AddDocument(project.Id, "NewDoc", sourceText);
var model = doc.GetSemanticModelAsync().Result;
var unresolved = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<IdentifierNameSyntax>()
   .Where(x => model.GetSymbolInfo(x).Symbol == null);

foreach (var identifier in unresolved)
{
    var candidateUsings = SymbolFinder.FindDeclarationsAsync(doc.Project, identifier.Identifier.ValueText, ignoreCase: false).Result;

    //Process candidate usings...
}

Upvotes: 4

Related Questions