2

While it's easy to get the syntax node you need in a DiagnosticAnalyzer (because it get passed to you), it's not clear how you can get hold of syntax nodes in Roslyn in other contexts. E.g., how does the Roslyn syntax visualizer (for which the source doesn't appear to be available) get hold of the syntax node under the cursor?

What I want to do is implement a command that can make use of the Roslyn syntax tree for the location of the cursor at the point at which the command was invoked. I've not been able to find using Roslyn in this sort of way.

Ian Griffiths
  • 14,302
  • 2
  • 64
  • 88
  • Perhaps Roslyn is just using the standard tags and classifiers system? https://msdn.microsoft.com/en-us/library/dd885240.aspx#tagsandclassifiers –  Jul 22 '15 at 07:06
  • @MickyDuncan it has its own representation for locations and ranges - https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/Diagnostic/Location.cs (It may well be possible to map between the two, but I'm hoping that there is a Right Way to do this...) – Ian Griffiths Jul 22 '15 at 09:05
  • Funny, I was investigating the same thing. Just out of curiosity, what does your extension do? – petr k. Jul 24 '15 at 10:46
  • @petrk. I'm implementing something very similar to what ReSharper does when you hit Alt-End - if the caret is on an interface member or a virtual member, it'll navigate to the implementation, or show a list of implementations if there are several. – Ian Griffiths Jul 28 '15 at 08:42
  • @IanGriffiths: Sounds great. I am in the midst of implementing something like ReSharper's Rearrange Code Elements feature (Move Up/Down & Move Left/Right) – petr k. Jul 28 '15 at 08:55

2 Answers2

1

First, you need to get the current text buffer. It is a bit involved, and I personally used code written by Mads Kristensen in his open-sourced WebEssentials. See GetCurentTextBuffer() in ProjectHelpers.cs.

Second, to retrieve an appropriate Roslyn structure (e.g. a Document), you can use one of the extension methods in Roslyn (see Microsoft.CodeAnalysis.Text.Extensions). This particular bit is inspired by a blog post by Josh Varty.

From there, it's quite straightforward to get hold of the Roslyn document's SyntaxTree and find the node at caret position.

Pang
  • 9,564
  • 146
  • 81
  • 122
petr k.
  • 8,040
  • 7
  • 41
  • 52
1

Here is the github Source code link for Sytax Visualizer

Venkatesh Muniyandi
  • 5,132
  • 2
  • 37
  • 40