This project is read-only.

Getting the ProjectId from a Compilation and DocumentId from a SyntaxTree

Topics: APIs
Nov 22, 2014 at 11:03 AM

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.

Nov 26, 2014 at 8:26 AM
Edited Nov 26, 2014 at 8: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);
        return null;
Nov 27, 2014 at 12:39 AM
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 12:50 PM
Edited Nov 27, 2014 at 12:52 PM
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.