Search code examples
typescriptvscode-extensionsabstract-syntax-tree

VS code extension parse value of variable of typescript file


I'm working on a VS code extension to parse OpenAPI specs. The spec can be defined as a variable with a fixed name inside a typescript file.

Inside my vs extension I get the document as a string: const doc = vscode.window.activeTextEditor?.document;

How can I parse this string to extract the variable value? I was looking for something like an AST, but maybe there is a simpler solution.


Solution

  • VS Code does not provide an AST, or similar API, relative to the document you have opened. Which means, if you need something like an AST to parse a document, you will have to do it within your extension.

    On the other hand, VS Code provides you the Go to Symbol command, which rely on each language extension to expose the symbols within a document. Specifically the variables symbol is available for the TypeScript language so, if you need to know the variables within a document and its locations, you could use the vscode.executeDocumentSymbolProvider command.