Skip to main content
The Tree-sitter C API provides a complete interface for parsing source code and working with syntax trees. This API is the foundation for all Tree-sitter language bindings and provides fine-grained control over parsing operations.

Core components

The C API is organized into several main components:
  • Parser - Create parsers, configure parsing options, and parse source code
  • Tree - Work with syntax trees, including copying, editing, and comparing trees
  • Node - Inspect and traverse syntax tree nodes
  • Query - Create and execute queries to search for patterns in syntax trees
  • Language - Access language-specific information and metadata

Key types

The API uses several opaque pointer types:
  • TSParser - A parser instance
  • TSTree - A syntax tree
  • TSNode - A node in a syntax tree (passed by value)
  • TSQuery - A compiled query
  • TSLanguage - A language definition

ABI versioning

Tree-sitter uses ABI versioning to ensure compatibility between the library and language parsers:
Languages generated by the Tree-sitter CLI are assigned an ABI version. The library is generally backwards-compatible with older versions but not forwards-compatible.

Memory management

The C API follows these memory management conventions:
  • Functions ending in _new allocate memory that must be freed with the corresponding _delete function
  • Functions returning const char * return pointers to memory owned by Tree-sitter (do not free)
  • Functions returning char * return memory allocated with malloc that the caller must free
  • Arrays returned with a length parameter are typically owned by the caller and must be freed

Basic usage example

Thread safety

Syntax trees are not thread-safe. To use a tree on multiple threads:
  1. Create a shallow copy with ts_tree_copy for each thread
  2. Each thread can safely read from its own copy
  3. Delete each copy when done
Parsers are also not thread-safe and should not be shared between threads.

Error handling

Most Tree-sitter functions indicate errors through return values:
  • Functions returning pointers return NULL on error
  • Functions returning bool return false on error
  • Query functions write error information to output parameters