tree-sitter-c C Grammar

0.24.1 · active · verified Thu Apr 09

tree-sitter-c is a Python package that provides the C language grammar for the Tree-sitter parsing library. It enables Python applications to parse C code into concrete syntax trees for advanced analysis, tooling, and transformation. The library is actively maintained, with frequent minor releases ensuring ongoing compatibility with the latest `tree-sitter` core and C language specifications.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import the `tree-sitter-c` grammar, initialize a `tree_sitter.Parser`, and parse a simple C code snippet. It then shows how to access the root node of the generated Abstract Syntax Tree (AST) and inspect its properties.

import tree_sitter_c as tsc
from tree_sitter import Language, Parser

# Load the C language grammar
C_LANGUAGE = Language(tsc.language())

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

# C code to parse
c_code = b"""
int main() {
    printf("Hello, Tree-sitter C!");
    return 0;
}
"""

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

# Get the root node and print its type
root_node = tree.root_node
print(f"Root node type: {root_node.type}")
print(f"Root node text: {root_node.text.decode('utf8')}")

# Example of traversing a child node
if root_node.children:
    first_child = root_node.children[0]
    print(f"First child type: {first_child.type}")

view raw JSON →