简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM