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 instanceTSTree- A syntax treeTSNode- A node in a syntax tree (passed by value)TSQuery- A compiled queryTSLanguage- A language definition
ABI versioning
Tree-sitter uses ABI versioning to ensure compatibility between the library and language parsers:Memory management
The C API follows these memory management conventions:- Functions ending in
_newallocate memory that must be freed with the corresponding_deletefunction - Functions returning
const char *return pointers to memory owned by Tree-sitter (do not free) - Functions returning
char *return memory allocated withmallocthat 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:- Create a shallow copy with
ts_tree_copyfor each thread - Each thread can safely read from its own copy
- Delete each copy when done
Error handling
Most Tree-sitter functions indicate errors through return values:- Functions returning pointers return
NULLon error - Functions returning
boolreturnfalseon error - Query functions write error information to output parameters