Getting Started โ
What you'll learn โ
- How to add
tree-sitter.zigto a Zig 0.16.0 project. - How to create a parser, parse source, and read the resulting tree.
- Where to go next for editing, queries, and embedding.
When to use this โ
You are new to the library and want the shortest path to a working parse.
Prerequisites โ
- Zig 0.16.0 exactly (
zig versionmust print0.16.0). - A
Languagevalue describing the grammar to parse. The package ships a bundled expression grammar used by the examples and tests; real integrations plug in their own generated table data (see Language Definition).
Complete example โ
zig
const std = @import("std");
const treesitter = @import("treesitter");
const grammar = treesitter.expression_language;
pub fn main() !void {
var gpa_state = std.heap.DebugAllocator(.{}).init;
defer _ = gpa_state.deinit();
const allocator = gpa_state.allocator();
var parser = treesitter.Parser.init(allocator);
defer parser.deinit();
try parser.setLanguage(grammar);
var tree = try parser.parseString("1 + 2 * 3");
defer tree.deinit();
const root = tree.rootNode();
std.debug.print("root: {s} [{d}, {d}]\n", .{ root.nodeType(), root.startByte(), root.endByte() });
std.debug.print("has error: {}\n", .{tree.hasError()});
}Running the example โ
sh
zig build run-basic_parseExpected output โ
text
root: program [0, 9]
has error: false
text: 1 + 2 * 3How it works โ
Parser.init(allocator)โ the only place you hand over an allocator. Everything created from this parser inherits it.setLanguage(...)โ loads generic grammar tables and validates the ABI version.parseString(...)โ runs the LR engine and returns an owningTree. The source is copied into the tree, so the tree outlives your input slice.rootNode()โ returns a lightweightNodehandle. Reading its type, bytes, and points allocates nothing.- Each
defer ...deinit()releases exactly what its object owns.
API used โ
- Parser โ
init,setLanguage,parseString. - Tree โ
rootNode,hasError. - Node โ
nodeType,startByte,endByte,text.
Memory ownership โ
Client owns an allocator (e.g. std.heap.DebugAllocator)
Parser.init(allocator) borrows it for the parser lifetime
parseString copies source bytes into the new Tree
Tree owns its node pool, child index buffer, and source copy
tree.cursor() / parser.queryCursor() inherit the stored allocator
Every deinit releases exactly what its object owns
Performance considerations โ
parseString performs one source copy plus pooled tree construction. Reuse the same Parser for every parse to reuse its internal scratch buffers (see Parser Reuse).
Related guides โ
- Installation for all setup methods.
- Your First Parser for the line-by-line version.
- Understanding Trees for what the result means.
