Getting the ProjectId from a Compilation and DocumentId from a SyntaxTree

Topics: APIs
Nov 22, 2014 at 10:03 AM
Hello,

I would need to relate an analysis (from inside an Analyzer) to the project in which it is used. For this I would need to be able to retrieve the project from a Compilation.

How can I achieve this?

Thank you.

-gael
Nov 26, 2014 at 7:26 AM
Edited Nov 26, 2014 at 7:31 AM
I had a similar problem, getting the Document from a SyntaxTree (because the formatter insists on getting the document/workspace and I wanted to write an Analyzer which checks whether the text is properly formatted). The only solution I found so far is going over SourceTextContainer to the Workspace, and from there you can get the Solution, Project and Document. Note that this only works on documents "opened" in the workspace (which is equivalent to opening the document in the IDE I believe). Does anyone have a better solution which works for any SyntaxTree and doesn't rely on having the document open?
private Document GetDocument(SyntaxTree tree)
{
    Workspace workspace;
    if (Workspace.TryGetWorkspace(tree.GetText().Container, out workspace))
        return workspace.CurrentSolution.GetDocument(tree);
    else
        return null;
}
Developer
Nov 26, 2014 at 11:39 PM
You can also get the project from the compilation, if you know the Solution.
var project = solution.GetProject(compilation.AssemblySymbol);
However, getting to this information is not generally encouraged since the analyzers are also supposed to run outside Visual Studio (during command line build) where there is no Workspace, Solution or Project defined.
Nov 27, 2014 at 11:50 AM
Edited Nov 27, 2014 at 11:52 AM
Why does the command line build not have a solution/project/document? That sounds odd to me, after all you'd go through these if you wanted to invoke the compiler from your code, right? I'm not aware of any way to compile source with Roslyn that sidesteps the solution/project/document levels.

And if they are required there should be a way to retrieve them from inside an Analyzer without having the document open in the IDE. At least the document/project/solution the Analyzer is analyzing! There are important things on the project level that an analyzer might need.