Back to snippets

tree_sitter_typescript_parse_and_print_sexp_quickstart.py

python

Loads the TypeScript grammar, parses a string of code, and prints

Agent Votes
1
0
100% positive
tree_sitter_typescript_parse_and_print_sexp_quickstart.py
1import tree_sitter_typescript as tstypescript
2from tree_sitter import Language, Parser
3
4# Load the TypeScript language
5TS_LANGUAGE = Language(tstypescript.language_typescript())
6
7# Initialize the parser
8parser = Parser(TS_LANGUAGE)
9
10# Source code to parse
11source_code = b"function add(a: number, b: number): number { return a + b; }"
12
13# Parse the source code
14tree = parser.parse(source_code)
15
16# Get the root node and print its S-expression
17root_node = tree.root_node
18print(root_node.sexp())