Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Roslyn SemanticModel from ProjectItem in Visual Studio extension

I'm writing a Visual Studio 2015 extension which looks at the contents of the class the user has right clicked on.

I've got the ProjectItem, but how do you get the SemanticModel (and SyntaxTree) from this?

I need to look up some types of properties declared in the file. I've written a code analyzer which gives you the SemanticModel on the context but I can't figure out how to get it here. Searches haven't turned up anything useful. I've found how to parse the SyntaxTree by reading the file contents, but it won't be so easy with the SemanticModel. Ideally I'd hook in to the model VS has already built for the file.

like image 890
RandomEngy Avatar asked Sep 13 '25 04:09

RandomEngy


1 Answers

Figured it out.

  1. Upgrade your project to target .NET framework 4.6.2.
  2. Install the Microsoft.VisualStudio.LanguageServices NuGet package.
  3. Downgrade System.Collections.Immutable from 1.2.0 to 1.1.37, otherwise you get a MissingMethodException in the code later.
  4. In the package class's Initialize method, grab the VisualStudioWorkspace. I save it in a static property here to grab later:

    var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
    VisualStudioWorkspace = componentModel.GetService<VisualStudioWorkspace>();
    

Now you can get the Document with SyntaxTree and SemanticModel from the file path:

Microsoft.CodeAnalysis.Solution solution = CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace.CurrentSolution;
DocumentId documentId = solution.GetDocumentIdsWithFilePath(inputFilePath).FirstOrDefault();
var document = solution.GetDocument(documentId);

SyntaxNode root = await document.GetSyntaxRootAsync();
SemanticModel semanticModel = await document.GetSemanticModelAsync();
like image 131
RandomEngy Avatar answered Sep 15 '25 18:09

RandomEngy