@willbooster/tree-sitter-zig
v8.0.0
Published
Zig grammar for tree-sitter
Maintainers
Readme
@willbooster/tree-sitter-zig
Zig grammar for tree-sitter, forked from tree-sitter-grammars/tree-sitter-zig. We are grateful to its authors and contributors. This is not an official release of that project.
This fork builds on the grammar of upstream's version 1.1.2 and generates the parser with the
WillBooster/tree-sitter generator. The parser carries that fork's own ABI
number (0x5742000b) and loads only with that fork's runtime, version 15.0.0 or later in the 15.x series: upstream's tree-sitter runtime
rejects it. It parses as the parser in upstream's 1.1.2 packages does, with these exceptions:
In the ranges a
forloop iterates over, a range end whose first token can both start an expression and continue the one before.., for example(,[,.,*,&,-, or!(as infor (0..(n)) |i| {}orfor (0..&x) |i| {}), is the right operand of arange_expression. Upstream's packaged parser, generated by tree-sitter CLI 0.24, lets that token continue the expression instead, on a range without an end: a call, an index, a field access, a binary expression, and so on. tree-sitter CLI 0.27 generates this fork's reading from the same grammar. Every other range end reads the same in both, whether its first token can only start an expression (n,~x) or only continue one (+,orelse), and so do ranges outsideforloops.A NUL character inside a token such as a string or a comment is part of that token, where upstream's lexer reports an error.
Multiline strings expose each
\\line delimiter and nonemptystring_contentchildren. Line endings are outside the content nodes.///and//!producedoc_commentandcontainer_doc_commentnodes. Theirdoc_comment_contentchildren exclude the prefix and include the line ending when present. An empty comment at EOF has no content child. Ordinary comments, including////, remaincommentnodes. Code that handles every comment kind must match all three node types.Error sets are accepted directly as container field types, and pointer, slice and array element types may be conditional.
asyncandawaitare ordinary identifiers. Assembly clobbers use an expression, including an anonymous struct initializer, as in Zig 0.16.Zero-bit integers
u0andi0are builtin types.Quoted identifiers such as
@"hello world"expose their content directly insideidentifier, without a nestedstringnode.Boolean negation is a
unary_expression. Inferred error unions (!T) occur only in function return types; their payload includes suffixes such as calls and field access (!List(T)or!ns.Result). Explicit error unions (E!T) retain their error and payload types.Empty
struct,opaque,enum, anduniondeclarations have no fields, instead of synthesized zero-widthcontainer_fieldandidentifiernodes.Assignments occur in statement positions, loop continuations, and single-assignment switch prongs. Plain block assignments,
elsealternatives, andcomptimeassignments retainvariable_declarationnodes.assignment_expressionnodes exposeleft,operator, andrightfields. Struct field initializers producefield_initializernodes withnameandvaluefields.
Support Scope
This fork maintains only full parsing: valid input yields a correct tree, and invalid input yields ERROR or MISSING
nodes without crashing, hanging, or taking more than linear time. Incremental parsing works as in upstream tree-sitter
but is not tested here, and no queries (highlights, locals, injections, tags) are shipped. Node types, field names, and
the trees that error recovery produces may change; such changes are released as new major versions.
Usage
The npm package ships tree-sitter-zig.wasm for
@willbooster/web-tree-sitter version 15.0.0 or later in the 15.x series, which runs in Node.js, Bun, browsers, and Cloudflare Workers.
In Node.js and Bun, load the grammar from its path:
import { fileURLToPath } from 'node:url';
import { Language, Parser } from '@willbooster/web-tree-sitter';
await Parser.init();
const parser = new Parser();
const wasmPath = fileURLToPath(import.meta.resolve('@willbooster/tree-sitter-zig/tree-sitter-zig.wasm'));
parser.setLanguage(await Language.load(wasmPath));
const tree = parser.parse('pub fn main() void {}\n');In browsers, serve both .wasm files and load them by URL (the example uses Vite's ?url imports):
import zigUrl from '@willbooster/tree-sitter-zig/tree-sitter-zig.wasm?url';
import { Language, Parser } from '@willbooster/web-tree-sitter';
import runtimeUrl from '@willbooster/web-tree-sitter/web-tree-sitter.wasm?url';
await Parser.init({ locateFile: () => runtimeUrl });
const parser = new Parser();
parser.setLanguage(await Language.load(zigUrl));Cloudflare Workers do not allow compiling Wasm at run time, so import both .wasm files as modules, with or without
Node.js compatibility:
import zig from '@willbooster/tree-sitter-zig/tree-sitter-zig.wasm';
import { Language, Parser } from '@willbooster/web-tree-sitter';
import runtime from '@willbooster/web-tree-sitter/web-tree-sitter.wasm';
await Parser.init({ wasmModule: runtime });
const parser = new Parser();
parser.setLanguage(await Language.load(zig));The package also ships grammar.js and the node types in src/node-types.json.
It includes src/scanner.c, which must be compiled with a parser regenerated from this grammar.
In Rust, depend on the crate and on willbooster-tree-sitter, the runtime this package is tested and fuzzed with:
[dependencies]
tree-sitter = { package = "willbooster-tree-sitter", version = "15.0.0" }
tree-sitter-zig = { package = "willbooster-tree-sitter-zig", version = "6" }let mut parser = tree_sitter::Parser::new();
parser.set_language(&tree_sitter_zig::LANGUAGE.into())?;Development
mise install
bun install --frozen-lockfile
bun run test/ci-setup # installs Chromium for the browser test
bun run build/ci
bun run test
script/parse-examples
cargo testThe scripts and tests generate, build, test, and parse with script/tree-sitter, the tree-sitter CLI of the
WillBooster/tree-sitter runtime version locked in Cargo.lock, since the generator and the runtime of upstream's CLI are
not the ones this package ships with. Its first run downloads that CLI from the runtime's GitHub Release, or builds it
with cargo (whose build runs the CMake that mise.toml pins) when the download fails or the release has no binary that runs here. Run other CLI commands through it as
well (e.g. script/tree-sitter parse file.zig).
bun run generate records a fresh generation profile from the applicable test/corpus cases, then generates
compact parser tables. It would also profile files tracked in examples/, but this repository tracks none: upstream
ships neither examples nor a corpus, so the cases in test/corpus were written for this fork, with the trees upstream's
packaged parser gives them, except where the parsing differences listed above apply. Those cases pin this fork's
reading. The parser also embeds metadata from tree-sitter.json.
After changing a grammar, tree-sitter.json, or a corpus case, regenerate and commit src/.
Profiles in .tmp/generation-profiles/ are temporary and must not be committed. bun run build-wasm, bun run build/ci,
and the release build regenerate the parsers before compiling them.
bun run test runs:
- the corpus in
test/corpus, with the native build and with the Wasm build (the first run downloads the WASI SDK); - a check that the real-world Zig files in
examples/fail to parse exactly as listed inscript/known-failures.txt, while every library file from the pinned Zig 0.16 release must parse without errors. The older Zig corpus retains coverage of unsupported syntax. The first run fetches the repositories and the checksum-pinned Zig source archive. Their revisions are pinned inscript/parse-examples. After a grammar change or a moved pin alters that list,script/parse-examplesrewrites it; review its diff before committing; - a performance check (
test/unit/performance.test.ts) that recovering from an error on each line takes linear time, since consumers parse files while they are being edited. It loads the Wasm build through @willbooster/web-tree-sitter, whichbun run build/cirebuilds after regenerating the parser; - a check (
test/unit/runtimeVersion.test.ts) that@willbooster/web-tree-sitterinpackage.jsonandwillbooster-tree-sitterinCargo.lockare the same version, since the Wasm tests run on the former and the Rust tests, the fuzzer, and the CLI on the latter; - tests that load the Wasm build with @willbooster/web-tree-sitter in Chromium (
test/e2e/browser.test.ts) and in Cloudflare Workers with and without Node.js compatibility (test/e2e/workers.test.ts).
The tests and script/parse-examples compile the parser into .tmp/tree-sitter-lib rather than the CLI's cache shared
by every checkout.
CI also runs these tests on Linux arm64 and macOS, where the CLI compiles the parser natively, and fuzzes the parser
with libFuzzer and sanitizers (.github/workflows/robustness.yml).
