Search code examples
typescriptvisual-studio-2015roslynvisual-studio-extensionsroslyn-code-analysis

How to get Typescript as either FileCodeModel or (Roslyn) Document with working GetSyntaxRoot in VSIX


Title is pretty much it. I need to be able to parse the syntax of a document to figure out what a user right clicked on to take my action. I am not manipulating the document so I really only need something that can get me the syntax node or equivalent. I have this working with C# and VB already but cannot figure out any part of the VSSDK or Roslyn SDK that can get me any kind of syntax tree for typescript.

Example of how I do it with the other languages with Roslyn, I have other code that works with the FileCodeModels so if I could get that it would also be fine for me to work with.

I'm actually thinking that I need to tap into the TypeScript Extension installed into VS (create extension dependency) but am not really sure.

Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
if (textView != null)
{
                SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
                Document document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
                if (document != null)
                {
                    SyntaxToken? token = document.GetSyntaxRootAsync().Result?.FindToken(caretPosition);                        
    }
}

Solution

  • There is neither a Roslyn SyntaxTree nor a FileCodeModel for TypeScript code, partly because the TypeScript engine is written itself in TypeScript, so there aren't managed representations to speak of. TypeScript's IDE experience internally uses a bit of Roslyn, which is why you see there's a Document available for you to grab, but there's no syntax tree from there to use.