TOML Grammar for Tree-sitter in Python

0.7.0 · active · verified Sun Apr 12

tree-sitter-toml provides a TOML grammar for the Tree-sitter parsing library, with Python bindings and pre-compiled wheels. It enables efficient, incremental parsing of TOML files, generating concrete syntax trees for various programming tools. The library is currently at version 0.7.0 and is actively maintained within the Tree-sitter grammars ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Tree-sitter parser with the `tree-sitter-toml` grammar and parse a simple TOML string. It then walks the resulting syntax tree to find and print the value associated with the 'name' key.

import tree_sitter_toml
from tree_sitter import Language, Parser

# Load the TOML grammar
TOML_LANGUAGE = Language(tree_sitter_toml.language())

# Create a parser instance
parser = Parser()
parser.set_language(TOML_LANGUAGE)

# Sample TOML source code
toml_code = b'''
[package]
name = "my-app"
version = "0.1.0"
authors = ["John Doe <john@example.com>"]
'''

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

# Get the root node and print its type
root_node = tree.root_node
print(f"Root Node Type: {root_node.type}")

# Example: Find a 'name' key-value pair
def find_name(node):
    for child in node.children:
        if child.type == 'key_value_pair':
            if child.child_by_field_name('key') and child.child_by_field_name('key').text == b'name':
                print(f"Found name: {child.child_by_field_name('value').text.decode()}")
        find_name(child)

find_name(root_node)

view raw JSON →