Tree-sitter Go Grammar for Python

0.25.0 · active · verified Thu Apr 09

tree-sitter-go provides Python bindings for the Go programming language grammar, enabling the tree-sitter parsing library to generate incremental syntax trees for Go code. This allows for robust code analysis, highlighting, and manipulation. The library is actively maintained, with releases generally coinciding with updates to the core tree-sitter project.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load the Go grammar, create a parser, and parse a simple Go code snippet. It then prints the root node's type and the types of its immediate children, showcasing the basic structure of the generated Abstract Syntax Tree (AST).

import tree_sitter_go as tsgo
from tree_sitter import Language, Parser

# Load the Go language grammar
GO_LANGUAGE = Language(tsgo.language())

# Create a parser and set its language
parser = Parser()
parser.set_language(GO_LANGUAGE)

# Example Go code (must be bytes for tree-sitter)
go_code = b"""
package main

import (
	"fmt"
	"os"
)

func main() {
	// A simple 'Hello World' in Go
	name := os.Getenv("USER_NAME")
	if name == "" {
		name = "Tree-sitter User"
	}
	fm.Println("Hello,", name + "!")
}
"""

# Parse the code
tree = parser.parse(go_code)

# Get the root node of the syntax tree
root_node = tree.root_node

# Print basic information about the root node
print(f"Root Node Type: {root_node.type}")
print(f"Root Node Text (first 50 chars): {root_node.text.decode('utf8')[:50]}...")

# Traverse and print types of top-level children
print("\nTop-level children types:")
for child in root_node.children:
    print(f"- {child.type}")

view raw JSON →