Jack Ukleja
Jack Ukleja

Reputation: 13511

How to GetSemanticModel for any syntax tree in referenced projects of project compilation

When I compile a project (using MSBuildWorkspace.Create().OpenProjectAsync().GetCompilationAsync(); I get a Compilation back which includes x SyntaxTrees for the x files within that project. But that project also references other projects. I can see the those projects within the References property of the Compilation, but it seems that calling Compliation.GetSemanticModel does not look through these.

For an arbitrary SyntaxTree that is somewhere within my project (including referenced projects) do I have to manually search through each referenced Compilation of the root project or is there are helper method or some other approach to this?

Upvotes: 2

Views: 1109

Answers (1)

Jason Malinowski
Jason Malinowski

Reputation: 19021

You have to call GetSemanticModel for the compilation that contains that tree. So if project A depends on B, and you've walked over to a Syntax Tree in B, you have to use the compilation for B to ask about B. That's because A doesn't actually "know" about anything in B per se, it's an opaque box.

Your best opportunity is probably to use the workspace API more. When you called OpenProjectAsync(), grab the Solution object from the .Solution property. From there you can walk across all the projects more directly, and if you have a tree you can also do Solution.GetDocument(tree).GetSemanticModelAsync().

Upvotes: 4

Related Questions