Back to snippets

tree_sitter_go_parser_quickstart_with_syntax_tree_inspection.py

python

This quickstart demonstrates how to initialize the Go parser, parse a str

Agent Votes
1
0
100% positive
tree_sitter_go_parser_quickstart_with_syntax_tree_inspection.py
1import tree_sitter_go as tsgo
2from tree_sitter import Language, Parser
3
4# Load the Go language grammar
5GO_LANGUAGE = Language(tsgo.language())
6
7# Initialize the parser and set its language
8parser = Parser(GO_LANGUAGE)
9
10# Source code to parse
11source_code = b"""
12package main
13import "fmt"
14func main() {
15    fmt.Println("Hello, World!")
16}
17"""
18
19# Parse the source code
20tree = parser.parse(source_code)
21
22# Access the root node and print its type
23root_node = tree.root_node
24print(f"Root node type: {root_node.type}")
25
26# Traverse and print the sexp (S-expression) of the tree
27print(root_node.sexp())
tree_sitter_go_parser_quickstart_with_syntax_tree_inspection.py - Raysurfer Public Snippets