# treesitter-lang — API Reference
> Complete reference for every public item in `treesitter-lang`, with examples.
> **Status: stable (1.0).** The surface below is the `1.0` contract; it follows
> [Semantic Versioning](#stability) and will not change in a breaking way before
> `2.0`. See [`../dev/ROADMAP.md`](../dev/ROADMAP.md).
<sub>Copyright © 2026 <strong>James Gober</strong>.</sub>
## Table of contents
- [Overview](#overview)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Concepts](#concepts)
- [From Rust to tree-sitter](#from-rust-to-tree-sitter)
- [Rules, names, and the start rule](#rules-names-and-the-start-rule)
- [Tokens and extras](#tokens-and-extras)
- [What validation checks](#what-validation-checks)
- [Corpus tests from your own parser](#corpus-tests-from-your-own-parser)
- [`Rule`](#rule)
- [`Rule::symbol`](#rulesymbol)
- [`Rule::string`](#rulestring)
- [`Rule::pattern`](#rulepattern)
- [`Rule::blank`](#ruleblank)
- [`Rule::seq`](#ruleseq)
- [`Rule::choice`](#rulechoice)
- [`Rule::optional`](#ruleoptional)
- [`Rule::repeat`](#rulerepeat)
- [`Rule::repeat1`](#rulerepeat1)
- [`Rule::field`](#rulefield)
- [`Rule::alias`](#rulealias)
- [`Rule::token`](#ruletoken)
- [`Rule::immediate`](#ruleimmediate)
- [`Rule::prec`](#ruleprec)
- [`Rule::prec_left`](#ruleprec_left)
- [`Rule::prec_right`](#ruleprec_right)
- [`Rule::prec_dynamic`](#ruleprec_dynamic)
- [`Grammar`](#grammar)
- [`Grammar::new`](#grammarnew)
- [`Grammar::rule`](#grammarrule)
- [`Grammar::extra`](#grammarextra)
- [`Grammar::external`](#grammarexternal)
- [`Grammar::supertype`](#grammarsupertype)
- [`Grammar::inline`](#grammarinline)
- [`Grammar::conflict`](#grammarconflict)
- [`Grammar::word`](#grammarword)
- [`Grammar::to_js`](#grammarto_js)
- [`Grammar::write_js`](#grammarwrite_js)
- [`Grammar::to_json`](#grammarto_json)
- [`Grammar::write_json`](#grammarwrite_json)
- [`Grammar::sexp`](#grammarsexp)
- [`Grammar::write_sexp`](#grammarwrite_sexp)
- [`Error`](#error)
- [Re-export: `syntax_lang`](#re-export-syntax_lang)
- [Feature flags](#feature-flags)
- [Guide: generating a grammar package](#guide-generating-a-grammar-package)
- [Guide: corpus tests from a hand-written parser](#guide-corpus-tests-from-a-hand-written-parser)
- [Stability](#stability)
---
## Overview
treesitter-lang builds [tree-sitter](https://tree-sitter.github.io/) grammars
in Rust. A [`Grammar`](#grammar) is a list of named [`Rule`](#rule)s plus
tree-sitter's grammar-level settings; it validates itself and emits
`grammar.js` or `grammar.json`, the input `tree-sitter generate` turns into a
parser. [`Grammar::sexp`](#grammarsexp) goes the other way: it renders a
[`syntax_lang::Node`](https://docs.rs/syntax-lang) tree the way tree-sitter
prints its own trees, so the trees a hand-written parser builds become
tree-sitter corpus tests.
| Item | Role |
|---|---|
| [`Rule`](#rule) | One rule expression: tree-sitter's rule language, one constructor per DSL function. |
| [`Grammar`](#grammar) | The named rules and grammar settings; validates and emits, and renders trees. |
| [`Error`](#error) | What validation found, or why a tree could not be rendered. |
| [`syntax_lang`](#re-export-syntax_lang) | The concrete-syntax-tree crate `sexp` reads, re-exported. |
The crate has one dependency, [`syntax-lang`](https://crates.io/crates/syntax-lang),
is `no_std`-compatible (it needs only `alloc`), and contains no `unsafe` code.
---
## Installation
```toml
[dependencies]
treesitter-lang = "1"
```
Or from the terminal:
```bash
cargo add treesitter-lang
```
A grammar is usually generated by a build step or a small program — an
example, an `xtask`, or a test that writes the files — so the crate can just
as well be a dev-dependency:
```toml
[dev-dependencies]
treesitter-lang = "1"
```
MSRV: Rust 1.85 (Rust 2024 edition).
---
## Quick start
Describe the language, emit `grammar.js`, and hand it to tree-sitter:
```rust
use treesitter_lang::{Grammar, Rule};
let e = || Rule::symbol("_expression");
let grammar = Grammar::new("calc")
.rule("source_file", Rule::repeat(e()))
.rule("_expression", Rule::choice([
Rule::symbol("number"),
Rule::symbol("sum"),
Rule::symbol("product"),
]))
.rule("sum", Rule::prec_left(1, Rule::seq([
Rule::field("left", e()),
Rule::string("+"),
Rule::field("right", e()),
])))
.rule("product", Rule::prec_left(2, Rule::seq([
Rule::field("left", e()),
Rule::string("*"),
Rule::field("right", e()),
])))
.rule("number", Rule::pattern(r"\d+"));
let js = grammar.to_js()?;
assert!(js.contains(" sum: $ => prec.left(1, seq(\n"));
// std::fs::write("tree-sitter-calc/grammar.js", js)?;
// then, in tree-sitter-calc/: tree-sitter generate
# Ok::<(), treesitter_lang::Error>(())
```
`to_js` produces the file a grammar author would have written by hand:
```js
/// <reference types="tree-sitter-cli/dsl" />
// @ts-check
module.exports = grammar({
name: 'calc',
rules: {
source_file: $ => repeat($._expression),
_expression: $ => choice($.number, $.sum, $.product),
sum: $ => prec.left(1, seq(
field('left', $._expression),
'+',
field('right', $._expression),
)),
product: $ => prec.left(2, seq(
field('left', $._expression),
'*',
field('right', $._expression),
)),
number: $ => /\d+/,
},
});
```
---
## Concepts
### From Rust to tree-sitter
Tree-sitter grammars are written in a small JavaScript DSL, `grammar.js`.
`tree-sitter generate` evaluates it into `src/grammar.json`, then compiles
that into a C parser. treesitter-lang produces either file:
| Output | Use it when |
|---|---|
| [`to_js`](#grammarto_js) — `grammar.js` | The grammar lives in a repository and is read, reviewed, and published like any tree-sitter grammar. |
| [`to_json`](#grammarto_json) — `grammar.json` | A build generates the parser directly, with no JavaScript runtime: `tree-sitter generate grammar.json`. |
The two agree exactly: both produce the same `parser.c`, and with
tree-sitter 0.25 or later the `grammar.json` this crate emits is
byte-identical to the `src/grammar.json` tree-sitter writes when it generates
from the emitted `grammar.js`. The CI suite checks this against the real
tree-sitter CLI on every change.
| tree-sitter | `grammar.json` loads | Same parser from both formats | `grammar.json` byte-identical |
|---|:---:|:---:|:---:|
| 0.25 – 0.27 | yes | yes | yes |
| 0.24 | yes | yes | all but the final, empty `reserved` field |
| 0.20, 0.22 | yes | not checked | — |
0.27 is checked in CI; the older versions were checked when the 0.2 release
was prepared.
Writing the grammar in Rust buys three things over writing `grammar.js` by
hand: rules can be generated from the same tables the language's own parser
uses (operator precedence, keyword lists); mistakes are reported by
[validation](#what-validation-checks) before tree-sitter runs; and the
grammar can be checked against the language's real parser through
[corpus tests](#corpus-tests-from-your-own-parser).
### Rules, names, and the start rule
A grammar is an ordered list of named rules. The **first rule is the start
rule**: every tree has it at the root. Names are identifiers — an ASCII letter
or `_`, then letters, digits, and `_` — and by tree-sitter convention
`snake_case`.
A name's first character decides how the rule's nodes appear in the tree:
| Name | Node in the tree |
|---|---|
| `expression` | Visible: a named node, `(expression ...)`. |
| `_expression` | Hidden: the rule matches as usual, but its node is left out and its children take its place. |
Hidden rules hold structure that is useful for writing the grammar but noise
in the tree — a choice between expression kinds, a list's separators. The
start rule must be visible.
Strings inside a rule (`Rule::string("+")`) become *anonymous* nodes: they
are in the tree, but tree-sitter's S-expressions leave them out. A rule whose
whole body is a string, pattern, or token is a *named token* and shows up as
`(name)`.
### Tokens and extras
Tree-sitter lexes text into tokens and parses tokens into trees. Every string
and pattern is a token. Between tokens, tree-sitter skips **extras** —
whitespace by default. [`Grammar::extra`](#grammarextra) sets them: usually
whitespace and a `comment` rule, which then appears in the tree wherever it
occurs.
Because extras may appear between any two tokens, `Rule::seq([a, b])` also
matches `a b` and `a /* comment */ b`. To match text with nothing in between,
make it one token: [`Rule::token`](#ruletoken) lexes its whole content as a
single token, and [`Rule::immediate`](#ruleimmediate) makes a token that
must follow the previous one directly.
### What validation checks
[`to_js`](#grammarto_js), [`to_json`](#grammarto_json), and their `write_`
forms validate the grammar first and refuse to emit one tree-sitter would
refuse — or, in a few cases, crash or hang on — returning the first problem
found as an [`Error`](#error):
| Check | Error |
|---|---|
| The grammar, rules, externals, fields, and aliases have identifier names; no rule or external is called `__proto__`. | [`InvalidName`](#error) |
| The grammar has at least one rule. | [`NoRules`](#error) |
| The start rule is visible. | [`HiddenStart`](#error) |
| No two rules share a name. | [`DuplicateRule`](#error) |
| Every symbol names a rule or an external — in rules, extras, `word`, `conflicts`, `inline`, and `supertypes`. | [`UndefinedSymbol`](#error) |
| No pattern is empty, and no string in a reachable rule. Every pattern is a regular expression JavaScript accepts, and — in reachable rules and the extras — one tree-sitter's own regular expression parser accepts (see [accepted patterns](#accepted-patterns)). | [`EmptyString`](#error) |
| No choice is empty. | [`EmptyChoice`](#error) |
| No symbol appears inside a token, or inside an extra that is not a lone symbol. | [`SymbolInToken`](#error) |
| No reachable rule that another rule (or an extra) refers to, and nothing a reachable `repeat` repeats, can match the empty string. | [`MatchesEmpty`](#error) |
| No reachable rules form a cycle in which each can be just the next, and no hidden rule is itself under a non-zero precedence (tree-sitter loops forever on it). | [`IndirectRecursion`](#error) |
| The word rule is a token. | [`WordNotToken`](#error) |
| A rule sharing an external's name is a token. | [`InvalidExternal`](#error) |
| An inlined rule is not the start rule, a token, or recursive through inlined rules alone. | [`InvalidInline`](#error) |
| A reachable supertype is not a token, is never itself, and produces a single node in each alternative. | [`InvalidSupertype`](#error) |
Two ideas from tree-sitter run through the table:
- **Reachability.** Tree-sitter drops rules that cannot be reached from the
start rule or the extras before it builds the parser, so the checks that
depend on how rules are used — empty strings, empty matches, cycles,
supertype shapes, and tree-sitter's parse of each pattern — apply only to
reachable rules. The checks `grammar.js` itself would trip on (names,
symbols, tokens, JavaScript's parse of each pattern) apply to every rule.
- **Token rules.** A rule whose whole body is a string, a pattern, a
[`token`](#ruletoken), or an [`immediate`](#ruleimmediate) token becomes a
token of its own — unless it is the start rule, or another reachable rule
uses the identical token (tree-sitter merges the two, and `token('x')` is
the same token as `'x'`), or it is hidden (or a supertype) and its token is
a bare string literal, which tree-sitter treats as that anonymous string.
The word rule and a rule sharing an external's name must be token rules;
an inlined rule and a reachable supertype must not.
Each check mirrors tree-sitter's behaviour, probed against its CLI, and the
whole was cross-checked by generating thousands of random grammars and
running each through both validation and `tree-sitter generate`. Some checks
are stricter than tree-sitter, because what they catch is always a mistake:
an empty choice (tree-sitter accepts it silently), an `inline` entry naming
no rule (tree-sitter only warns), and empty patterns and empty strings inside
tokens (tree-sitter accepts some, but they can only match nothing).
Validation does not build parse tables. What tree-sitter finds while building
them is reported by `tree-sitter generate`: ambiguities, which it explains by
naming the rules involved — resolve them with [precedence](#ruleprec) or
declare them with [`Grammar::conflict`](#grammarconflict) — and extras built
from rules whose end it cannot tell.
### Corpus tests from your own parser
Tree-sitter tests a grammar with *corpus files*: samples of source text, each
followed by the tree the parser should build, written as an S-expression.
```text
==================
Sum
==================
1 + 2
---
(source_file
(sum
(number)
(number)))
```
A language built with the `-lang` family already has a parser that builds
[`syntax_lang::Node`](https://docs.rs/syntax-lang) trees. Name its node and
token kinds after the grammar's rules, and [`Grammar::sexp`](#grammarsexp)
renders its trees as the S-expressions above. Feed it the language's test
samples and write the results as corpus files: `tree-sitter test` then checks
the generated parser against the hand-written one, and a change to either
that makes them disagree fails the test. The
[guide below](#guide-corpus-tests-from-a-hand-written-parser) walks through
it.
---
## `Rule`
```rust,ignore
#[derive(Clone, Debug)]
pub struct Rule(/* private */);
```
A rule expression: what one rule of a grammar matches. Each constructor
corresponds to one function of tree-sitter's `grammar.js` DSL:
| Constructor | `grammar.js` | Matches |
|---|---|---|
| [`symbol`](#rulesymbol) | `$.name` | The rule (or external token) called `name`. |
| [`string`](#rulestring) | `'text'` | The exact text. |
| [`pattern`](#rulepattern) | `/regex/` | Text matching a regular expression. |
| [`blank`](#ruleblank) | `blank()` | Nothing. |
| [`seq`](#ruleseq) | `seq(a, b)` | Each rule in order. |
| [`choice`](#rulechoice) | `choice(a, b)` | Any one of the rules. |
| [`optional`](#ruleoptional) | `optional(a)` | The rule, or nothing. |
| [`repeat`](#rulerepeat) | `repeat(a)` | The rule zero or more times. |
| [`repeat1`](#rulerepeat1) | `repeat1(a)` | The rule one or more times. |
| [`field`](#rulefield) | `field('name', a)` | The rule, labelled as a field of its parent. |
| [`alias`](#rulealias) | `alias(a, $.name)` | The rule, appearing in the tree as `name`. |
| [`token`](#ruletoken) | `token(a)` | The rule, lexed as one token. |
| [`immediate`](#ruleimmediate) | `token.immediate(a)` | One token, with nothing before it. |
| [`prec`](#ruleprec), [`prec_left`](#ruleprec_left), [`prec_right`](#ruleprec_right), [`prec_dynamic`](#ruleprec_dynamic) | `prec(n, a)`, `prec.left`, `prec.right`, `prec.dynamic` | The rule, with a precedence. |
Rules are plain values. Build them, keep them in variables, and clone a piece
to use it in several places. Nothing is checked until the grammar is emitted,
so a rule may name a symbol defined later. Text arguments take
`impl Into<Cow<'static, str>>`: a string literal is stored without copying,
and a `String` built at run time is taken as is.
`Clone` and `Debug` recurse into nested rules, so a rule nested tens of
thousands of levels deep can exhaust the stack in them. Dropping, validating,
and emitting a rule are iterative and safe at any depth.
```rust
use treesitter_lang::{Grammar, Rule};
// A helper that builds a reusable rule shape.
fn comma_separated(item: Rule) -> Rule {
Rule::seq([
item.clone(),
Rule::repeat(Rule::seq([Rule::string(","), item])),
])
}
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("list")))
.rule("list", Rule::seq([
Rule::string("["),
Rule::optional(comma_separated(Rule::symbol("number"))),
Rule::string("]"),
]))
.rule("number", Rule::pattern(r"\d+"))
.to_js()?;
assert!(js.contains("optional(seq(\n $.number,\n repeat(seq(',', $.number)),\n )),"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::symbol`
```rust,ignore
pub fn symbol(name: impl Into<Cow<'static, str>>) -> Rule
```
A reference to another rule, or to an external token, by name. Emitted as
`$.name`. Names are resolved when the grammar is emitted, so rules may refer
to each other in any order, including recursively. A name starting with `_`
refers to a hidden rule.
| Parameter | Meaning |
|---|---|
| `name` | The rule's name. A string literal is not copied; a `String` is moved in. |
An undefined name is reported as [`Error::UndefinedSymbol`](#error) when the
grammar is emitted.
```rust
use treesitter_lang::{Grammar, Rule};
// Recursion through a symbol: nested parentheses.
let js = Grammar::new("parens")
.rule("source_file", Rule::repeat(Rule::symbol("group")))
.rule("group", Rule::seq([
Rule::string("("),
Rule::repeat(Rule::symbol("group")),
Rule::string(")"),
]))
.to_js()?;
assert!(js.contains("group: $ => seq('(', repeat($.group), ')'),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
// A typo is caught before tree-sitter runs.
let result = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("statment")))
.rule("statement", Rule::string(";"))
.to_js();
assert_eq!(
result,
Err(Error::UndefinedSymbol { symbol: "statment".into(), rule: "source_file".into() }),
);
```
### `Rule::string`
```rust,ignore
pub fn string(text: impl Into<Cow<'static, str>>) -> Rule
```
Exactly this text. Emitted as a single-quoted JavaScript string; quotes,
backslashes, control characters, and the JavaScript line separators U+2028
and U+2029 are escaped, so any text survives into `grammar.js` and back.
| Parameter | Meaning |
|---|---|
| `text` | The literal text. Any characters; must not be empty. |
Inside a larger rule a string is an anonymous token: present in the tree but
left out of S-expressions. As a rule's whole body it makes a named token. An
empty string is [`Error::EmptyString`](#error).
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::choice([
Rule::symbol("keyword"),
Rule::string("it's"),
Rule::string(r"C:\path"),
])))
.rule("keyword", Rule::string("return"))
.to_js()?;
assert!(js.contains(r"choice($.keyword, 'it\'s', 'C:\\path')"));
assert!(js.contains("keyword: $ => 'return',"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Text built at run time.
let operators: Vec<String> = ["+", "-", "*"].iter().map(|s| s.to_string()).collect();
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::choice(operators.into_iter().map(Rule::string))))
.to_js()?;
assert!(js.contains("choice('+', '-', '*')"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::pattern`
```rust,ignore
pub fn pattern(regex: impl Into<Cow<'static, str>>) -> Rule
```
Text matching a regular expression, written as the source of a JavaScript
regular expression — what goes between the slashes of `/.../`. Use a raw
string (`r"\d+"`) so backslashes need no doubling. A `/` is written as `\/`
and a control character as `\n`, `\r`, `\t`, or `\xHH`, so the pattern fits
in a `/.../` literal; the regular expression is unchanged. `grammar.json`
records the pattern the same way, as tree-sitter would.
| Parameter | Meaning |
|---|---|
| `regex` | The pattern source; must not be empty, and must be one of the [accepted patterns](#accepted-patterns). |
An empty or invalid pattern is [`Error::EmptyString`](#error); for an invalid
one the error names the rule, says what is wrong, and gives the byte offset
in the pattern.
#### Accepted patterns
A pattern passes through two parsers on its way into a lexer, and validation
holds it to both:
1. **JavaScript.** `grammar.js` holds the pattern as a `/.../` literal with
no flags, which the runtime that loads the file — Node.js, or
tree-sitter's built-in QuickJS with `--js-runtime native` — parses under
the web-compatible grammar of ECMAScript Annex B (B.1.2). This applies to
every pattern, in every rule and extra: `grammar.js` evaluates them all.
2. **tree-sitter.** Tree-sitter reads the literal's source back, rewrites
`\w`, `\s`, `\d`, `\W`, `\S`, and `\D` into bracketed classes — textually,
so `\\D` becomes `\[^0-9]` — parses the result with the Rust
`regex-syntax` crate (0.8), and refuses any assertion left in it. This
applies to the patterns of rules reachable from the start rule and of the
extras; tree-sitter never reads the others.
The two grammars differ, so the accepted patterns are those both accept. The
pattern then *means* what regex-syntax makes of it: JavaScript's reading only
decides whether `grammar.js` loads.
| Construct | Accepted | Refused |
|---|---|---|
| Characters | Any character. `/`, control characters, and line separators are escaped for you. | — |
| Escapes | `\` before any ASCII punctuation or space; `\t` `\n` `\r` `\f` `\v` `\a`; `\xHH`, `\uHHHH`, `\UHHHHHHHH`, `\x{H…}`, `\u{H…}` naming a Unicode scalar value; `\d` `\w` `\s` `\D` `\W` `\S`; `\p{…}`, `\pL`, `\P{…}`. | `\0`–`\9` (backreferences and octal escapes), `\c`, `\k`, `\e`, and other letters regex-syntax does not define; `\` before a non-ASCII character; surrogate escapes (`\uD83D`); `\p{}`. |
| Classes | `[…]` and `[^…]`; ranges in order; a leading `]` (`[]a]`) or `-`; nested classes, `&&`, `--`, and `~~` (regex-syntax set operations, which JavaScript reads as plain characters); `[:alpha:]` and the other ASCII classes inside a class. | A class unclosed in either reading (`[[a]` is closed for JavaScript but not for regex-syntax); a range out of order, by code point for regex-syntax and by UTF-16 code unit for JavaScript (`[😀-😁]`); a range ending in a class (`[a-\pL]`) or an assertion; `[]` and `[^]`. |
| Groups | `(…)`, `(?:…)`, `(?<name>…)` with a name of ASCII letters, digits, and `_`, not starting with a digit; modifier groups `(?i:…)`, `(?m:…)`, `(?s:…)`, `(?i-s:…)`. | Look-ahead and look-behind; `(?P<name>…)`; flags without a group, `(?i)`; repeated or empty names; unclosed or unmatched parentheses. |
| Repetition | `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}` with `n ≤ m < 2³²`, spaces allowed around the numbers, each optionally lazy (`?`). | A quantifier with nothing to repeat — at the start, after `(` or `\|`, after an assertion, or after another quantifier (`a**`, `\x{41}{2}`, which JavaScript reads as `x` repeated 41 times, then repeated again); a `{` that is not a whole quantifier (`{`, `a{`, `a{,3}`). |
| Assertions | Only inside a repetition of exactly zero, `(?:^){0}`, which compiles to nothing. | `^`, `$`, `\b`, `\B`, `\A`, `\z`, `\<`, `\>`, `\b{start}` and the other word boundaries. |
| Nesting | Up to 250 levels, as regex-syntax counts them: groups, repetitions, alternations, concatenations of two or more, classes and class operations. | Deeper. |
What validation does not check, all reported by `tree-sitter generate` or
the JavaScript runtime as before:
- The property names in `\p{…}` and `\P{…}`; regex-syntax knows them from
Unicode tables this crate does not carry.
- Whether a non-ASCII character in a group name is a JavaScript identifier
character (`ID_Start`, `ID_Continue`).
- Repeated group names in rules tree-sitter drops, where only JavaScript
reads them: ES2025 allows repeats in different alternatives, and engines
differ on exactly where.
- How long tree-sitter takes to expand a large counted repetition into its
lexer: `a{100000}` is accepted, and takes tree-sitter a long time.
- Runtime differences in the JavaScript checked against: modifier groups
(`(?i:…)`) are ES2025, verified with Node.js 24 — tree-sitter 0.27's
QuickJS runtime refuses them, as may older Node.js releases.
Whatever a pattern holds, the literal `grammar.js` writes for it ends at its
own closing slash: a `[` that would open a character class running past the
end of the pattern is written `\[`, and an empty pattern or one starting
with `*` as `new RegExp('…')`. Validation refuses all of these first, so
valid patterns are written unchanged; this is a second line of defence.
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::choice([
Rule::symbol("float"),
Rule::symbol("path"),
])))
.rule("float", Rule::pattern(r"\d+\.\d+([eE][+-]?\d+)?"))
.rule("path", Rule::pattern("[a-z]+(/[a-z]+)*"))
.to_js()?;
assert!(js.contains(r"float: $ => /\d+\.\d+([eE][+-]?\d+)?/,"));
assert!(js.contains(r"path: $ => /[a-z]+(\/[a-z]+)*/,"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// grammar.json records what grammar.js holds between the slashes.
let json = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::pattern("a/b")))
.to_json()?;
assert!(json.contains(r#""value": "a\\/b""#));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::blank`
```rust,ignore
pub const fn blank() -> Rule
```
Matches nothing. Emitted as `blank()`. [`optional`](#ruleoptional) is
`choice(rule, blank())`; use `blank` directly for an explicit empty
alternative.
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::seq([
Rule::choice([Rule::string("+"), Rule::string("-"), Rule::blank()]),
Rule::pattern(r"\d+"),
]))
.to_js()?;
assert!(js.contains("choice('+', '-', blank())"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::Rule;
// `blank` is `const`, so it can initialize a constant.
const NOTHING: Rule = Rule::blank();
let _maybe_sign = Rule::choice([Rule::string("-"), NOTHING]);
```
### `Rule::seq`
```rust,ignore
pub fn seq(rules: impl IntoIterator<Item = Rule>) -> Rule
```
Each rule in order. [Extras](#tokens-and-extras) may appear between the
parts; to forbid that, wrap the sequence in [`token`](#ruletoken). An empty
sequence matches nothing: it is [`blank`](#ruleblank), and is emitted as
`blank()` (tree-sitter refuses an empty `seq()` inside a token, but not
`blank()`).
| Parameter | Meaning |
|---|---|
| `rules` | The parts, in order: an array, a `Vec`, or any iterator of rules. |
Short sequences of simple parts are emitted on one line; longer ones put each
part on its own line.
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("assignment")))
.rule("assignment", Rule::seq([
Rule::field("name", Rule::symbol("identifier")),
Rule::string("="),
Rule::field("value", Rule::symbol("identifier")),
Rule::string(";"),
]))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains(" assignment: $ => seq(\n field('name', $.identifier),\n"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Parts built from data: a fixed keyword sequence.
let words = ["end", "of", "file"];
let js = Grammar::new("demo")
.rule("source_file", Rule::seq(words.map(Rule::string)))
.to_js()?;
assert!(js.contains("source_file: $ => seq('end', 'of', 'file'),"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::choice`
```rust,ignore
pub fn choice(rules: impl IntoIterator<Item = Rule>) -> Rule
```
Any one of the rules. Ambiguity between alternatives is settled with
[precedence](#ruleprec) or [declared as a conflict](#grammarconflict). A
choice with no alternatives can never match and is
[`Error::EmptyChoice`](#error).
| Parameter | Meaning |
|---|---|
| `rules` | The alternatives: an array, a `Vec`, or any iterator of rules. At least one. |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("_literal")))
.rule("_literal", Rule::choice([
Rule::symbol("number"),
Rule::symbol("boolean"),
]))
.rule("number", Rule::pattern(r"\d+"))
.rule("boolean", Rule::choice([Rule::string("true"), Rule::string("false")]))
.to_js()?;
assert!(js.contains("_literal: $ => choice($.number, $.boolean),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
// Alternatives filtered from a table; an empty result is caught.
let enabled: [&'static str; 0] = [];
let result = Grammar::new("demo")
.rule("source_file", Rule::choice(enabled.map(Rule::string)))
.to_js();
assert_eq!(result, Err(Error::EmptyChoice { rule: "source_file".into() }));
```
### `Rule::optional`
```rust,ignore
pub fn optional(rule: Rule) -> Rule
```
The rule, or nothing. The same as `choice([rule, blank()])`, which is how
tree-sitter records it in `grammar.json`; `grammar.js` shows it as
`optional(...)`.
| Parameter | Meaning |
|---|---|
| `rule` | What may be left out. |
A rule that other rules refer to must not be able to match nothing, so an
`optional` that covers a whole rule body belongs at the places that use the
rule instead (see [`Error::MatchesEmpty`](#error)).
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("call")))
.rule("call", Rule::seq([
Rule::pattern("[a-z]+"),
Rule::string("("),
Rule::optional(Rule::symbol("arguments")),
Rule::string(")"),
]))
.rule("arguments", Rule::repeat1(Rule::pattern(r"\d+")))
.to_js()?;
assert!(js.contains("optional($.arguments)"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
let json = Grammar::new("demo")
.rule("source_file", Rule::optional(Rule::string("x")))
.to_json()?;
assert!(json.contains("\"type\": \"CHOICE\""));
assert!(json.contains("\"type\": \"BLANK\""));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::repeat`
```rust,ignore
pub fn repeat(rule: Rule) -> Rule
```
The rule zero or more times. Because it can match nothing, it makes the rule
it is in able to match the empty string: right for the start rule, an
[`Error::MatchesEmpty`](#error) in a rule others refer to. Use
[`repeat1`](#rulerepeat1) there.
| Parameter | Meaning |
|---|---|
| `rule` | What repeats. |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("line")))
.rule("line", Rule::seq([Rule::pattern("[^\n]+"), Rule::string("\n")]))
.to_js()?;
assert!(js.contains("source_file: $ => repeat($.line),"));
assert!(js.contains(r"line: $ => seq(/[^\n]+/, '\n'),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
// A block may be empty, so its body cannot be a bare `repeat`.
let result = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("block")))
.rule("block", Rule::seq([Rule::string("{"), Rule::symbol("body"), Rule::string("}")]))
.rule("body", Rule::repeat(Rule::pattern("[a-z]+")))
.to_js();
assert_eq!(result, Err(Error::MatchesEmpty { rule: "body".into() }));
```
### `Rule::repeat1`
```rust,ignore
pub fn repeat1(rule: Rule) -> Rule
```
The rule one or more times.
| Parameter | Meaning |
|---|---|
| `rule` | What repeats. |
```rust
use treesitter_lang::{Grammar, Rule};
// The fix for the empty block above: `body` matches at least one word, and
// the block makes it optional.
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("block")))
.rule("block", Rule::seq([
Rule::string("{"),
Rule::optional(Rule::symbol("body")),
Rule::string("}"),
]))
.rule("body", Rule::repeat1(Rule::pattern("[a-z]+")))
.to_js()?;
assert!(js.contains("body: $ => repeat1(/[a-z]+/),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// A non-empty, comma-separated list.
let js = Grammar::new("demo")
.rule("source_file", Rule::seq([
Rule::pattern("[a-z]+"),
Rule::repeat1(Rule::seq([Rule::string(","), Rule::pattern("[a-z]+")])),
]))
.to_js()?;
assert!(js.contains("repeat1(seq(',', /[a-z]+/))"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::field`
```rust,ignore
pub fn field(name: impl Into<Cow<'static, str>>, rule: Rule) -> Rule
```
The rule, labelled as a field of the node it appears in. Fields let a tree
consumer ask for a child by role — "the condition", "the body" — rather than
by position. They do not change what is matched.
| Parameter | Meaning |
|---|---|
| `name` | The field name; an identifier, conventionally `snake_case`. |
| `rule` | The labelled part. |
An invalid name is [`Error::InvalidName`](#error).
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("if_statement")))
.rule("if_statement", Rule::seq([
Rule::string("if"),
Rule::field("condition", Rule::symbol("identifier")),
Rule::field("consequence", Rule::symbol("block")),
]))
.rule("block", Rule::seq([Rule::string("{"), Rule::string("}")]))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains("field('condition', $.identifier)"));
assert!(js.contains("field('consequence', $.block)"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// A field around several children: every child it matches carries the label.
let json = Grammar::new("demo")
.rule("source_file", Rule::field("items", Rule::repeat(Rule::pattern("[a-z]+"))))
.to_json()?;
assert!(json.contains("\"type\": \"FIELD\",\n \"name\": \"items\","));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::alias`
```rust,ignore
pub fn alias(rule: Rule, name: impl Into<Cow<'static, str>>) -> Rule
```
The rule, appearing in the tree as a named node called `name`. Use it to give
anonymous syntax a node of its own, or to show a rule under a different name
in one context. The name need not be a rule of the grammar.
| Parameter | Meaning |
|---|---|
| `rule` | What matches. |
| `name` | The node name it appears as; an identifier. |
```rust
use treesitter_lang::{Grammar, Rule};
// `...` gets a named node, `(spread)`.
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::choice([
Rule::alias(Rule::string("..."), "spread"),
Rule::pattern("[a-z]+"),
])))
.to_js()?;
assert!(js.contains("alias('...', $.spread)"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// An identifier that appears as `type_identifier` after a colon.
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("declaration")))
.rule("declaration", Rule::seq([
Rule::symbol("identifier"),
Rule::string(":"),
Rule::alias(Rule::symbol("identifier"), "type_identifier"),
]))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains("alias($.identifier, $.type_identifier)"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::token`
```rust,ignore
pub fn token(rule: Rule) -> Rule
```
The rule, lexed as a single token: no extras inside it, and one leaf in the
tree for the whole match. The contents may only be strings, patterns, and
combinators over them — a [`symbol`](#rulesymbol) inside a token is
[`Error::SymbolInToken`](#error).
| Parameter | Meaning |
|---|---|
| `rule` | The token's lexical structure. |
```rust
use treesitter_lang::{Grammar, Rule};
// A comment runs to the end of the line, whatever it contains.
let js = Grammar::new("demo")
.extra(Rule::pattern(r"\s"))
.extra(Rule::symbol("comment"))
.rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
.rule("comment", Rule::token(Rule::seq([Rule::string("//"), Rule::pattern(".*")])))
.to_js()?;
assert!(js.contains("comment: $ => token(seq('//', /.*/)),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
let result = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("version")))
.rule("version", Rule::token(Rule::seq([Rule::symbol("digits"), Rule::string(".")])))
.rule("digits", Rule::pattern(r"\d+"))
.to_js();
assert_eq!(
result,
Err(Error::SymbolInToken { symbol: "digits".into(), rule: "version".into() }),
);
```
### `Rule::immediate`
```rust,ignore
pub fn immediate(rule: Rule) -> Rule
```
A token that must follow the previous token with nothing — not even an
extra — in between. Emitted as `token.immediate(...)`. The same content
restrictions as [`token`](#ruletoken) apply.
| Parameter | Meaning |
|---|---|
| `rule` | The token's lexical structure. |
```rust
use treesitter_lang::{Grammar, Rule};
// `x.y` is a member access; `x . y` is not.
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("member")))
.rule("member", Rule::seq([
Rule::symbol("identifier"),
Rule::immediate(Rule::string(".")),
Rule::immediate(Rule::pattern("[a-z]+")),
]))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains("token.immediate('.')"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// String contents glued to the opening quote.
let json = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("string")))
.rule("string", Rule::seq([
Rule::string("\""),
Rule::immediate(Rule::pattern("[^\"]*")),
Rule::string("\""),
]))
.to_json()?;
assert!(json.contains("\"type\": \"IMMEDIATE_TOKEN\""));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::prec`
```rust,ignore
pub fn prec(level: i32, rule: Rule) -> Rule
```
The rule with a numeric precedence, emitted as `prec(level, ...)`. When the
parser generator finds two ways to proceed, the one with the higher
precedence wins. Inside a [`token`](#ruletoken), precedence chooses between
tokens that match the same text.
| Parameter | Meaning |
|---|---|
| `level` | The precedence. Higher binds tighter; the default is `0`; negative values are allowed. |
| `rule` | The rule it applies to. |
```rust
use treesitter_lang::{Grammar, Rule};
// Unary minus binds tighter than any binary operator.
let e = || Rule::symbol("_expression");
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(e()))
.rule("_expression", Rule::choice([
Rule::symbol("number"),
Rule::symbol("negation"),
Rule::symbol("difference"),
]))
.rule("negation", Rule::prec(3, Rule::seq([Rule::string("-"), e()])))
.rule("difference", Rule::prec_left(1, Rule::seq([e(), Rule::string("-"), e()])))
.rule("number", Rule::pattern(r"\d+"))
.to_js()?;
assert!(js.contains("negation: $ => prec(3, seq('-', $._expression)),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Lexical precedence: `true` is a keyword even though it matches the
// identifier pattern too.
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::choice([
Rule::symbol("boolean"),
Rule::symbol("identifier"),
])))
.rule("boolean", Rule::token(Rule::prec(1, Rule::string("true"))))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains("boolean: $ => token(prec(1, 'true')),"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::prec_left`
```rust,ignore
pub fn prec_left(level: i32, rule: Rule) -> Rule
```
The rule with a precedence and left associativity, emitted as
`prec.left(level, ...)`: `a - b - c` groups as `(a - b) - c`.
| Parameter | Meaning |
|---|---|
| `level` | The precedence. |
| `rule` | The rule it applies to, usually a binary-operator sequence. |
```rust
use treesitter_lang::{Grammar, Rule};
// One alternative per operator, from an operator table.
let table = [("+", 1), ("-", 1), ("*", 2), ("/", 2)];
let e = || Rule::symbol("_expression");
let binary = Rule::choice(table.map(|(op, level)| {
Rule::prec_left(level, Rule::seq([e(), Rule::string(op), e()]))
}));
let js = Grammar::new("calc")
.rule("source_file", Rule::repeat(e()))
.rule("_expression", Rule::choice([Rule::symbol("number"), Rule::symbol("binary")]))
.rule("binary", binary)
.rule("number", Rule::pattern(r"\d+"))
.to_js()?;
assert!(js.contains("prec.left(2, seq($._expression, '/', $._expression)),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
let json = Grammar::new("demo")
.rule("source_file", Rule::prec_left(-1, Rule::string("x")))
.to_json()?;
assert!(json.contains("\"type\": \"PREC_LEFT\",\n \"value\": -1,"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::prec_right`
```rust,ignore
pub fn prec_right(level: i32, rule: Rule) -> Rule
```
The rule with a precedence and right associativity, emitted as
`prec.right(level, ...)`: `a = b = c` groups as `a = (b = c)`.
| Parameter | Meaning |
|---|---|
| `level` | The precedence. |
| `rule` | The rule it applies to. |
```rust
use treesitter_lang::{Grammar, Rule};
let e = || Rule::symbol("_expression");
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(e()))
.rule("_expression", Rule::choice([
Rule::symbol("identifier"),
Rule::symbol("assignment"),
]))
.rule("assignment", Rule::prec_right(0, Rule::seq([
Rule::field("left", Rule::symbol("identifier")),
Rule::string("="),
Rule::field("right", e()),
])))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains("assignment: $ => prec.right(0, seq(\n"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Exponentiation is right-associative and binds tightest.
let e = || Rule::symbol("_expression");
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(e()))
.rule("_expression", Rule::choice([Rule::symbol("number"), Rule::symbol("power")]))
.rule("power", Rule::prec_right(4, Rule::seq([e(), Rule::string("**"), e()])))
.rule("number", Rule::pattern(r"\d+"))
.to_js()?;
assert!(js.contains("prec.right(4, seq($._expression, '**', $._expression))"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Rule::prec_dynamic`
```rust,ignore
pub fn prec_dynamic(level: i32, rule: Rule) -> Rule
```
The rule with a dynamic precedence, emitted as `prec.dynamic(level, ...)`.
Dynamic precedence is applied while parsing, between the alternatives of a
[declared conflict](#grammarconflict) that are still alive at the end: the
parse with the higher total wins.
| Parameter | Meaning |
|---|---|
| `level` | The dynamic precedence. |
| `rule` | The rule it applies to. |
```rust
use treesitter_lang::{Grammar, Rule};
// `<a b>` reads both as a group of names and as a tuple of values; the
// conflict is declared and the group preferred at run time.
let js = Grammar::new("demo")
.conflict(["_value", "group"])
.rule("source_file", Rule::repeat(Rule::symbol("_value")))
.rule("_value", Rule::choice([
Rule::symbol("identifier"),
Rule::symbol("group"),
Rule::symbol("tuple"),
]))
.rule("group", Rule::prec_dynamic(1, Rule::seq([
Rule::string("<"),
Rule::repeat1(Rule::symbol("identifier")),
Rule::string(">"),
])))
.rule("tuple", Rule::seq([
Rule::string("<"),
Rule::repeat1(Rule::symbol("_value")),
Rule::string(">"),
]))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains("group: $ => prec.dynamic(1, seq('<', repeat1($.identifier), '>')),"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
let json = Grammar::new("demo")
.rule("source_file", Rule::prec_dynamic(2, Rule::string("x")))
.to_json()?;
assert!(json.contains("\"type\": \"PREC_DYNAMIC\""));
# Ok::<(), treesitter_lang::Error>(())
```
---
## `Grammar`
```rust,ignore
#[derive(Clone, Debug)]
pub struct Grammar { /* private */ }
```
A tree-sitter grammar: a name, an ordered list of rules (the first is the
start rule), and the grammar-level settings — extras, externals, supertypes,
inlined rules, conflicts, and the word token. Build one by chaining: every
builder method takes the grammar by value and returns it. Nothing is checked
until it is emitted.
| Method | Purpose |
|---|---|
| [`new`](#grammarnew) | Start an empty grammar. |
| [`rule`](#grammarrule) | Add a named rule. |
| [`extra`](#grammarextra), [`external`](#grammarexternal), [`supertype`](#grammarsupertype), [`inline`](#grammarinline), [`conflict`](#grammarconflict), [`word`](#grammarword) | Grammar-level settings. |
| [`to_js`](#grammarto_js), [`write_js`](#grammarwrite_js) | Validate and emit `grammar.js`. |
| [`to_json`](#grammarto_json), [`write_json`](#grammarwrite_json) | Validate and emit `grammar.json`. |
| [`sexp`](#grammarsexp), [`write_sexp`](#grammarwrite_sexp) | Render a `syntax_lang` tree as tree-sitter's S-expression. |
`Grammar` is `Send + Sync`: build it once and share it between threads
rendering trees.
### `Grammar::new`
```rust,ignore
pub fn new(name: impl Into<Cow<'static, str>>) -> Grammar
```
Starts an empty grammar called `name`. The name is the language's name in
tree-sitter: the generated parser exports `tree_sitter_<name>()`, and the
package is conventionally `tree-sitter-<name>`.
| Parameter | Meaning |
|---|---|
| `name` | The language name, an identifier, conventionally lowercase. |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("ini").rule("document", Rule::blank()).to_js()?;
assert!(js.contains(" name: 'ini',"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
// Hyphens belong in the package name, not the grammar name.
let result = Grammar::new("my-lang").rule("document", Rule::blank()).to_js();
assert_eq!(result, Err(Error::InvalidName { name: "my-lang".into() }));
```
### `Grammar::rule`
```rust,ignore
pub fn rule(self, name: impl Into<Cow<'static, str>>, rule: Rule) -> Grammar
```
Adds a rule called `name` matching `rule`. Rules are emitted in the order
they are added; the **first is the start rule** and must be visible
([`Error::HiddenStart`](#error)). Names must be identifiers and unique
([`Error::DuplicateRule`](#error)).
| Parameter | Meaning |
|---|---|
| `name` | The rule's name, which is also the name of its nodes. `_` first hides them. |
| `rule` | What the rule matches. |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("_item")))
.rule("_item", Rule::choice([Rule::symbol("word"), Rule::symbol("number")]))
.rule("word", Rule::pattern("[a-z]+"))
.rule("number", Rule::pattern(r"\d+"))
.to_js()?;
let order: Vec<usize> = ["source_file:", "_item:", "word:", "number:"]
.iter()
.map(|name| js.find(name).unwrap())
.collect();
assert!(order.windows(2).all(|w| w[0] < w[1]));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Keyword rules generated from a list.
let keywords = ["if", "else", "while", "return"];
let mut grammar = Grammar::new("demo").rule(
"source_file",
Rule::repeat(Rule::choice(keywords.map(|k| Rule::symbol(format!("{k}_keyword"))))),
);
for k in keywords {
grammar = grammar.rule(format!("{k}_keyword"), Rule::string(k));
}
assert!(grammar.to_js()?.contains("return_keyword: $ => 'return',"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
let hidden_start = Grammar::new("demo").rule("_root", Rule::blank());
assert_eq!(hidden_start.to_js(), Err(Error::HiddenStart { name: "_root".into() }));
let duplicate = Grammar::new("demo")
.rule("source_file", Rule::blank())
.rule("source_file", Rule::string("x"));
assert_eq!(duplicate.to_js(), Err(Error::DuplicateRule { name: "source_file".into() }));
```
### `Grammar::extra`
```rust,ignore
pub fn extra(self, rule: Rule) -> Grammar
```
Adds an extra: something that may appear between any two tokens. Until this
is first called, tree-sitter's default applies — whitespace (`/\s/`) is the
only extra. **The first call replaces the default**, so add whitespace
yourself alongside a comment extra.
| Parameter | Meaning |
|---|---|
| `rule` | The extra: usually a pattern, or a symbol naming a rule. |
`grammar.js` leaves `extras` out while the default applies; `grammar.json`
always lists the extras, since that format has no implicit default.
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.extra(Rule::pattern(r"\s"))
.extra(Rule::symbol("comment"))
.rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
.rule("comment", Rule::token(Rule::seq([Rule::string(";"), Rule::pattern(".*")])))
.to_js()?;
assert!(js.contains(" extras: $ => [\n /\\s/,\n $.comment,\n ],\n"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Line continuations count as whitespace too.
let js = Grammar::new("demo")
.extra(Rule::pattern(r"\s"))
.extra(Rule::pattern(r"\\\r?\n"))
.rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
.to_js()?;
assert!(js.contains(r" /\\\r?\n/,"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Grammar::external`
```rust,ignore
pub fn external(self, name: impl Into<Cow<'static, str>>) -> Grammar
```
Declares an external token, lexed by a hand-written scanner in
`src/scanner.c` rather than by the generated lexer — for indentation,
heredocs, nested comments, anything a regular expression cannot match.
Rules refer to it with [`Rule::symbol`](#rulesymbol). Tree-sitter hands the
scanner the externals in declaration order, so keep the order in step with
the scanner's token enum.
| Parameter | Meaning |
|---|---|
| `name` | The token's name; an identifier. It may also name a rule that is a [token rule](#what-validation-checks), which then serves as the fallback when the scanner declines ([`InvalidExternal`](#error) otherwise). |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("outline")
.external("indent")
.external("dedent")
.external("newline")
.rule("source_file", Rule::repeat(Rule::symbol("item")))
.rule("item", Rule::seq([
Rule::pattern("[a-z]+"),
Rule::symbol("newline"),
Rule::optional(Rule::seq([
Rule::symbol("indent"),
Rule::repeat1(Rule::symbol("item")),
Rule::symbol("dedent"),
])),
]))
.to_js()?;
assert!(js.contains(" externals: $ => [\n $.indent,\n $.dedent,\n $.newline,\n ],"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// A hidden external is lexed but never appears in the tree.
let json = Grammar::new("demo")
.external("_line_break")
.rule("source_file", Rule::repeat(Rule::seq([
Rule::pattern("[a-z]+"),
Rule::symbol("_line_break"),
])))
.to_json()?;
assert!(json.contains("\"externals\": [\n {\n \"type\": \"SYMBOL\",\n \"name\": \"_line_break\"\n }\n ]"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Grammar::supertype`
```rust,ignore
pub fn supertype(self, name: impl Into<Cow<'static, str>>) -> Grammar
```
Marks a hidden rule as a supertype: a choice between other rules, like
`_expression` or `_statement`. It still does not appear in trees, but
tree-sitter records it in `node-types.json`, and queries can match on it —
`(_expression)` matches any expression.
| Parameter | Meaning |
|---|---|
| `name` | A rule's name, usually hidden; tree-sitter treats a supertype as hidden either way. When reachable, it must not be a token, never be itself, and produce a single node in each alternative ([`Error::InvalidSupertype`](#error)). |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.supertype("_statement")
.rule("source_file", Rule::repeat(Rule::symbol("_statement")))
.rule("_statement", Rule::choice([Rule::symbol("break"), Rule::symbol("continue")]))
.rule("break", Rule::string("break;"))
.rule("continue", Rule::string("continue;"))
.to_js()?;
assert!(js.contains(" supertypes: $ => [\n $._statement,\n ],"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
let result = Grammar::new("demo")
.supertype("_expresion")
.rule("source_file", Rule::blank())
.to_js();
assert_eq!(
result,
Err(Error::UndefinedSymbol { symbol: "_expresion".into(), rule: "supertypes".into() }),
);
```
### `Grammar::inline`
```rust,ignore
pub fn inline(self, name: impl Into<Cow<'static, str>>) -> Grammar
```
Asks tree-sitter to inline a rule: substitute its body wherever it is used,
instead of giving it parse states of its own. Suits small hidden helpers used
in many places, and can resolve conflicts that exist only because the helper
is a separate rule. An inlined rule never appears in the tree.
| Parameter | Meaning |
|---|---|
| `name` | A rule's name ([`Error::UndefinedSymbol`](#error) otherwise; tree-sitter only warns, but a name that matches nothing is always a typo). Not the start rule, a token, or a rule that refers to itself through inlined rules alone ([`Error::InvalidInline`](#error)). Repeated entries are written once, as tree-sitter keeps them. |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.inline("_name")
.rule("source_file", Rule::repeat(Rule::symbol("_name")))
.rule("_name", Rule::choice([Rule::symbol("identifier"), Rule::symbol("self")]))
.rule("identifier", Rule::pattern("[a-z]+"))
.rule("self", Rule::string("self"))
.to_js()?;
assert!(js.contains(" inline: $ => [\n $._name,\n ],"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
let json = Grammar::new("demo")
.inline("_a")
.inline("_b")
.rule("source_file", Rule::repeat(Rule::choice([Rule::symbol("_a"), Rule::symbol("_b")])))
.rule("_a", Rule::string("a"))
.rule("_b", Rule::string("b"))
.to_json()?;
assert!(json.contains("\"inline\": [\n \"_a\",\n \"_b\"\n ]"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Grammar::conflict`
```rust,ignore
pub fn conflict<N>(self, names: impl IntoIterator<Item = N>) -> Grammar
where
N: Into<Cow<'static, str>>,
```
Declares an expected conflict between rules. When `tree-sitter generate`
finds an ambiguity that precedence does not settle, it stops and lists the
rules involved. Declaring the conflict tells it the ambiguity is intended: the
generated parser then explores the alternatives at run time and keeps the one
that succeeds (or, among several, the one with the higher
[dynamic precedence](#ruleprec_dynamic)).
| Parameter | Meaning |
|---|---|
| `names` | The conflicting rules, as tree-sitter named them. Each must be a rule or external ([`Error::UndefinedSymbol`](#error)). |
```rust
use treesitter_lang::{Grammar, Rule};
// `<a b>` is a group of names or a tuple of values.
let js = Grammar::new("demo")
.conflict(["_value", "group"])
.rule("source_file", Rule::repeat(Rule::symbol("_value")))
.rule("_value", Rule::choice([
Rule::symbol("identifier"),
Rule::symbol("group"),
Rule::symbol("tuple"),
]))
.rule("group", Rule::seq([
Rule::string("<"),
Rule::repeat1(Rule::symbol("identifier")),
Rule::string(">"),
]))
.rule("tuple", Rule::seq([
Rule::string("<"),
Rule::repeat1(Rule::symbol("_value")),
Rule::string(">"),
]))
.rule("identifier", Rule::pattern("[a-z]+"))
.to_js()?;
assert!(js.contains(" conflicts: $ => [\n [$._value, $.group],\n ],"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::Grammar;
// Several conflicts, with names known only at run time.
let pairs: Vec<[String; 2]> = vec![
["type".into(), "expression".into()],
["pattern".into(), "expression".into()],
];
let mut grammar = Grammar::new("demo");
for pair in pairs {
grammar = grammar.conflict(pair);
}
# let _ = grammar;
```
### `Grammar::word`
```rust,ignore
pub fn word(self, name: impl Into<Cow<'static, str>>) -> Grammar
```
Names the word token: the identifier-like token keywords are carved out of.
With a word token, tree-sitter lexes a keyword by matching the word token and
then comparing the text with the keyword strings. The lexer gets smaller, and
keywords are no longer recognized inside longer identifiers (`if` in
`iffy`). Calling `word` again replaces the earlier choice.
| Parameter | Meaning |
|---|---|
| `name` | The identifier rule's name. Its body must be a string, a pattern, a [`token`](#ruletoken), or an [`immediate`](#ruleimmediate) token, with nothing wrapped around it — or the name must be an external. |
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("demo")
.word("identifier")
.rule("source_file", Rule::repeat(Rule::choice([
Rule::seq([Rule::string("let"), Rule::symbol("identifier")]),
Rule::symbol("identifier"),
])))
.rule("identifier", Rule::pattern("[a-zA-Z_][a-zA-Z0-9_]*"))
.to_js()?;
assert!(js.contains(" word: $ => $.identifier,\n"));
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
// Precedence around the pattern makes it a non-terminal in tree-sitter's eyes.
let result = Grammar::new("demo")
.word("identifier")
.rule("source_file", Rule::repeat(Rule::symbol("identifier")))
.rule("identifier", Rule::prec(1, Rule::pattern("[a-z]+")))
.to_js();
assert_eq!(result, Err(Error::WordNotToken { name: "identifier".into() }));
```
### `Grammar::to_js`
```rust,ignore
pub fn to_js(&self) -> Result<String, Error>
```
Validates the grammar and emits it as `grammar.js`. The output is formatted
as tree-sitter grammars are written by hand — two-space indentation, short
sequences on one line, trailing commas — and starts with the
`tree-sitter-cli/dsl` type reference, so it reads naturally and diffs
cleanly when committed. Settings appear in a fixed order: `name`, `extras`,
`externals`, `supertypes`, `inline`, `conflicts`, `word`, `rules`; empty
settings are left out.
**Errors.** The first problem [validation](#what-validation-checks) finds.
```rust
use treesitter_lang::{Grammar, Rule};
let js = Grammar::new("pairs")
.rule("source_file", Rule::repeat(Rule::symbol("pair")))
.rule("pair", Rule::seq([
Rule::field("key", Rule::symbol("identifier")),
Rule::string("="),
Rule::field("value", Rule::choice([
Rule::symbol("identifier"),
Rule::symbol("number"),
])),
]))
.rule("identifier", Rule::pattern("[a-z]+"))
.rule("number", Rule::pattern(r"\d+"))
.to_js()?;
assert_eq!(js, r#"/// <reference types="tree-sitter-cli/dsl" />
// @ts-check
module.exports = grammar({
name: 'pairs',
rules: {
source_file: $ => repeat($.pair),
pair: $ => seq(
field('key', $.identifier),
'=',
field('value', choice($.identifier, $.number)),
),
identifier: $ => /[a-z]+/,
number: $ => /\d+/,
},
});
"#);
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Writing the file, as a build step would.
let dir = std::env::temp_dir().join("tree-sitter-pairs-doc");
std::fs::create_dir_all(&dir)?;
let grammar = Grammar::new("pairs").rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")));
std::fs::write(dir.join("grammar.js"), grammar.to_js()?)?;
assert!(std::fs::read_to_string(dir.join("grammar.js"))?.contains("name: 'pairs'"));
# std::fs::remove_dir_all(&dir)?;
# Ok::<(), Box<dyn std::error::Error>>(())
```
### `Grammar::write_js`
```rust,ignore
pub fn write_js(&self, out: &mut String) -> Result<(), Error>
```
The same output as [`to_js`](#grammarto_js), appended to a buffer the
caller owns. Reuse one buffer to emit many grammars without reallocating.
| Parameter | Meaning |
|---|---|
| `out` | The buffer to append to. Existing contents are kept. |
**Errors.** As [`to_js`](#grammarto_js). On error nothing is appended.
```rust
use treesitter_lang::{Grammar, Rule};
// One buffer for several dialects.
let mut buffer = String::new();
for dialect in ["strict", "loose"] {
buffer.clear();
Grammar::new(dialect)
.rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
.write_js(&mut buffer)?;
assert!(buffer.contains(&format!("name: '{dialect}'")));
}
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Appending after a license header.
let mut out = String::from("// SPDX-License-Identifier: MIT\n");
Grammar::new("demo")
.rule("source_file", Rule::blank())
.write_js(&mut out)?;
assert!(out.starts_with("// SPDX-License-Identifier: MIT\n/// <reference"));
# Ok::<(), treesitter_lang::Error>(())
```
### `Grammar::to_json`
```rust,ignore
pub fn to_json(&self) -> Result<String, Error>
```
Validates the grammar and emits it as `grammar.json`, the format
`tree-sitter generate` writes to `src/grammar.json` and accepts in place of
`grammar.js`. Both inputs produce the same parser, and with tree-sitter 0.25
or later the output is byte-identical to the file tree-sitter writes when it
generates from this grammar's [`to_js`](#grammarto_js) output — same
`$schema` line, field order, and layout, no trailing newline (see
[the compatibility table](#from-rust-to-tree-sitter)). Without any
[`extra`](#grammarextra), the default whitespace extra is written out.
**Errors.** The first problem [validation](#what-validation-checks) finds.
```rust
use treesitter_lang::{Grammar, Rule};
let json = Grammar::new("tiny")
.rule("source_file", Rule::repeat(Rule::symbol("word")))
.rule("word", Rule::pattern("[a-z]+"))
.to_json()?;
assert_eq!(json, r#"{
"$schema": "https://tree-sitter.github.io/tree-sitter/assets/schemas/grammar.schema.json",
"name": "tiny",
"rules": {
"source_file": {
"type": "REPEAT",
"content": {
"type": "SYMBOL",
"name": "word"
}
},
"word": {
"type": "PATTERN",
"value": "[a-z]+"
}
},
"extras": [
{
"type": "PATTERN",
"value": "\\s"
}
],
"conflicts": [],
"precedences": [],
"externals": [],
"inline": [],
"supertypes": [],
"reserved": {}
}"#);
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
// Strings are JSON-escaped; non-ASCII text is kept as is.
let json = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::choice([
Rule::string("say \"hi\""),
Rule::string("café"),
])))
.to_json()?;
assert!(json.contains(r#""value": "say \"hi\"""#));
assert!(json.contains("\"value\": \"café\""));
# Ok::<(), treesitter_lang::Error>(())
```
### `Grammar::write_json`
```rust,ignore
pub fn write_json(&self, out: &mut String) -> Result<(), Error>
```
The same output as [`to_json`](#grammarto_json), appended to a buffer the
caller owns.
| Parameter | Meaning |
|---|---|
| `out` | The buffer to append to. Existing contents are kept. |
**Errors.** As [`to_json`](#grammarto_json). On error nothing is appended.
```rust
use treesitter_lang::{Grammar, Rule};
let grammar = Grammar::new("demo").rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")));
let mut js = String::new();
let mut json = String::new();
grammar.write_js(&mut js)?;
grammar.write_json(&mut json)?;
assert!(js.len() < json.len());
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
let mut out = String::from("kept");
let broken = Grammar::new("demo").rule("source_file", Rule::string(""));
assert_eq!(
broken.write_json(&mut out),
Err(Error::EmptyString { rule: "source_file".into() }),
);
assert_eq!(out, "kept");
```
### `Grammar::sexp`
```rust,ignore
pub fn sexp<'n, K>(&self, tree: &Node<K>, name: impl Fn(&K) -> &'n str) -> Result<String, Error>
```
Renders a [`syntax_lang::Node`](https://docs.rs/syntax-lang) tree as the
S-expression tree-sitter prints for the same input, for writing corpus tests.
Each node and token is named by `name`, then shown the way tree-sitter shows
it:
| The name is… | Shown as |
|---|---|
| A visible rule that lexes a single token (a string, pattern, or `token`, possibly under `prec` or `field`) | A leaf, `(name)`; anything beneath it is part of the token. |
| A visible rule that names no other node (no symbol or alias in it) | `(name ...)` around only the extras, such as comments, beneath it. |
| Any other visible rule, or a name given by [`alias`](#rulealias) | `(name ...)` around its children; on a token, `(name)`. |
| A hidden rule (`_name`), an [inlined](#grammarinline) rule, or a [supertype](#grammarsupertype) | Not shown; its children take its place. |
| An [external](#grammarexternal) token | `(name)`, unless hidden. |
| Not in the grammar, on a token | Not shown: an anonymous token — punctuation, keywords written as strings, whitespace. |
| Not in the grammar, on a node | [`Error::UnknownNode`](#error). |
Children are indented two spaces per level, as `tree-sitter test` formats
them. Fields are not reconstructed — the tree does not record them, and
`tree-sitter test` ignores fields when the expected tree has none — and an
alias shows up only where the tree itself uses the aliased name.
Extras such as comments appear wherever the tree has them; tree-sitter puts
an extra inside the innermost node whose first and last tokens surround it,
so a parser whose trees are compared this way should place trivia the same
way. `sexp` does not validate the grammar.
| Parameter | Meaning |
|---|---|
| `tree` | The tree; its root is rendered like any other node. |
| `name` | Names a node or token kind, matching the grammar's rule names. Usually a method on the kind type. |
**Errors.** [`Error::UnknownNode`](#error) if a node's name is not a rule,
external, or alias name.
```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Builder, Span, Token};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind { File, Sum, Number, Plus, Space }
impl Kind {
fn name(&self) -> &'static str {
match self {
Kind::File => "source_file",
Kind::Sum => "sum",
Kind::Number => "number",
Kind::Plus => "+",
Kind::Space => " ",
}
}
}
let grammar = Grammar::new("calc")
.rule("source_file", Rule::repeat(Rule::symbol("_expression")))
.rule("_expression", Rule::choice([Rule::symbol("number"), Rule::symbol("sum")]))
.rule("sum", Rule::prec_left(1, Rule::seq([
Rule::symbol("_expression"),
Rule::string("+"),
Rule::symbol("_expression"),
])))
.rule("number", Rule::pattern(r"\d+"));
// `1 + 2`, as a parser builds it.
let mut b = Builder::new();
b.start_node(Kind::File);
b.start_node(Kind::Sum);
b.token(Token::new(Kind::Number, Span::new(0, 1)));
b.token(Token::new(Kind::Space, Span::new(1, 2)));
b.token(Token::new(Kind::Plus, Span::new(2, 3)));
b.token(Token::new(Kind::Space, Span::new(3, 4)));
b.token(Token::new(Kind::Number, Span::new(4, 5)));
b.finish_node();
b.finish_node();
let tree = b.finish()?;
assert_eq!(grammar.sexp(&tree, Kind::name)?, "(source_file\n (sum\n (number)\n (number)))");
# Ok::<(), Box<dyn std::error::Error>>(())
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};
let grammar = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("_group")))
.rule("_group", Rule::seq([Rule::string("("), Rule::symbol("word"), Rule::string(")")]))
.rule("word", Rule::pattern("[a-z]+"));
// A hidden rule's node is replaced by its children.
let tree = Node::new("source_file", vec![Element::Node(Node::new("_group", vec![
Element::Token(Token::new("(", Span::new(0, 1))),
Element::Token(Token::new("word", Span::new(1, 3))),
Element::Token(Token::new(")", Span::new(3, 4))),
]))]);
assert_eq!(grammar.sexp(&tree, |k| *k)?, "(source_file\n (word))");
// A node the grammar does not know is an error.
let stray = Node::new("source_file", vec![Element::Node(Node::new("block", vec![]))]);
assert_eq!(grammar.sexp(&stray, |k| *k), Err(Error::UnknownNode { name: "block".into() }));
# Ok::<(), Error>(())
```
### `Grammar::write_sexp`
```rust,ignore
pub fn write_sexp<'n, K>(
&self,
tree: &Node<K>,
name: impl Fn(&K) -> &'n str,
out: &mut String,
) -> Result<(), Error>
```
The same output as [`sexp`](#grammarsexp), appended to a buffer the caller
owns — reuse one buffer across a whole corpus.
| Parameter | Meaning |
|---|---|
| `tree` | The tree to render. |
| `name` | Names a node or token kind. |
| `out` | The buffer to append to. Existing contents are kept. |
**Errors.** As [`sexp`](#grammarsexp). On error nothing is appended.
```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};
let grammar = Grammar::new("words")
.rule("source_file", Rule::repeat(Rule::symbol("word")))
.rule("word", Rule::pattern("[a-z]+"));
let source = "hi there";
let tree = Node::new("source_file", vec![
Element::Token(Token::new("word", Span::new(0, 2))),
Element::Token(Token::new("space", Span::new(2, 3))),
Element::Token(Token::new("word", Span::new(3, 8))),
]);
// A complete corpus entry.
let mut corpus = String::new();
corpus.push_str("==================\nTwo words\n==================\n\n");
corpus.push_str(source);
corpus.push_str("\n\n---\n\n");
grammar.write_sexp(&tree, |k| *k, &mut corpus)?;
corpus.push('\n');
assert_eq!(corpus, "==================\nTwo words\n==================\n\nhi there\n\n---\n\n\
(source_file\n (word)\n (word))\n");
# Ok::<(), treesitter_lang::Error>(())
```
```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};
// Names from a table, borrowed by the naming closure.
let names: Vec<String> = vec!["source_file".into(), "word".into()];
let grammar = Grammar::new("words")
.rule("source_file", Rule::repeat(Rule::symbol("word")))
.rule("word", Rule::pattern("[a-z]+"));
let tree = Node::new(0usize, vec![Element::Token(Token::new(1usize, Span::new(0, 2)))]);
let mut out = String::new();
grammar.write_sexp(&tree, |k| names[*k].as_str(), &mut out)?;
assert_eq!(out, "(source_file\n (word))");
# Ok::<(), treesitter_lang::Error>(())
```
---
## `Error`
```rust,ignore
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
InvalidName { name: String },
NoRules,
DuplicateRule { name: String },
HiddenStart { name: String },
UndefinedSymbol { symbol: String, rule: String },
EmptyString { rule: String },
EmptyChoice { rule: String },
SymbolInToken { symbol: String, rule: String },
MatchesEmpty { rule: String },
IndirectRecursion { rule: String },
WordNotToken { name: String },
InvalidExternal { name: String },
InvalidInline { name: String },
InvalidSupertype { name: String },
UnknownNode { name: String },
}
```
Why a grammar could not be emitted, or a tree could not be rendered.
Validation reports the first problem, checking in this order:
1. names (the grammar's, then each rule's, then each external's), the start
rule, and duplicate rules;
2. every rule body in definition order, then the extras: symbols resolve and
are not inside tokens, patterns and choices are not empty, patterns are
regular expressions JavaScript accepts, field and alias names are
identifiers;
3. the names in `word`, `conflicts`, `inline`, and `supertypes` resolve;
4. the rules reachable from the start rule and the extras: no cycle of rules
that can each be just the next; then, in definition order, no empty
strings, only patterns tree-sitter's regular expression parser accepts,
and nothing that can match the empty string where tree-sitter needs a
token; then the patterns in the extras;
5. the word token, externals sharing a rule's name, inlined rules, and
supertypes.
Where a variant has a `rule` field, it names the rule the problem is in — or,
for a problem outside any rule, the grammar setting it is in: `extras`,
`word`, `conflicts`, `inline`, or `supertypes`. `Error` implements `Display`
and `core::error::Error`.
| Variant | Meaning | What to do |
|---|---|---|
| `InvalidName { name }` | A grammar, rule, external, field, or alias name is not an identifier, or a rule or external is called `__proto__`. | Rename: ASCII letter or `_`, then letters, digits, `_`. |
| `NoRules` | The grammar has no rules. | Add at least the start rule. |
| `DuplicateRule { name }` | Two rules share a name. | Rename one, or merge them with a `choice`. |
| `HiddenStart { name }` | The first rule's name starts with `_`. | Make the start rule visible. |
| `UndefinedSymbol { symbol, rule }` | A symbol names neither a rule nor an external. | Fix the typo, or define the rule or external. |
| `EmptyString { rule }` | A pattern is empty or is not one of the [accepted patterns](#accepted-patterns), or a string in a reachable rule is empty. For an invalid pattern, `rule` is the rule's name, `: `, then what is wrong and where: `` "number: unterminated character class at byte 0 of `[0-9`" ``. | Express "nothing" with `blank` or `optional`; fix an invalid pattern as the report says. |
| `EmptyChoice { rule }` | A choice has no alternatives. | Give it at least one. |
| `SymbolInToken { symbol, rule }` | A symbol appears inside `token`, `immediate`, or an extra that is not a lone symbol. | Inline the referenced rule's strings and patterns, or make the extra a symbol. |
| `MatchesEmpty { rule }` | A reachable rule another rule (or an extra) refers to can match the empty string, or something a `repeat` repeats can. | Make it match at least one token; put the `optional` at its uses, or use `repeat1`. |
| `IndirectRecursion { rule }` | Reachable rules form a cycle in which each can be just the next (`a` can be `b` alone, `b` can be `a` alone), or a hidden rule can be itself under a non-zero precedence. | Make one rule require more than the other, or merge them. |
| `WordNotToken { name }` | The `word` rule is not a token rule. | Make its body a bare string, pattern, or token used nowhere else. |
| `InvalidExternal { name }` | An external shares its name with a rule that is not a token rule. | Rename one of them, or make the rule a token. |
| `InvalidInline { name }` | An inlined rule is the start rule, an external, a token rule, or recursive through inlined rules alone. | Remove it from the inline list, or break the cycle. |
| `InvalidSupertype { name }` | A supertype is an external, or a reachable rule that is a token rule, is itself in an alternative, or produces several nodes in one. | Make it a choice of single symbols. |
| `UnknownNode { name }` | `sexp` met a node whose name is not a rule, external, or alias name. | Add the rule, or fix the naming function. |
```rust
use treesitter_lang::{Error, Grammar, Rule};
let result = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("block")))
.rule("block", Rule::seq([Rule::string("{"), Rule::symbol("body"), Rule::string("}")]))
.rule("body", Rule::optional(Rule::pattern("[a-z]+")))
.to_js();
match result {
Err(Error::MatchesEmpty { rule }) => assert_eq!(rule, "body"),
other => panic!("unexpected {other:?}"),
}
```
```rust
use treesitter_lang::{Error, Grammar, Rule};
let result = Grammar::new("demo")
.rule("source_file", Rule::repeat(Rule::symbol("number")))
.rule("number", Rule::pattern("[0-9"))
.to_js();
match result {
Err(Error::EmptyString { rule }) => {
assert_eq!(rule, "number: unterminated character class at byte 0 of `[0-9`");
// The rule's name is everything before the first `: `.
assert_eq!(rule.split_once(": ").map(|(name, _)| name), Some("number"));
}
other => panic!("unexpected {other:?}"),
}
```
```rust
use treesitter_lang::Error;
let e = Error::UndefinedSymbol { symbol: "item".into(), rule: "extras".into() };
assert_eq!(e.to_string(), "`extras` refers to undefined symbol `item`");
// A standard error: it boxes and propagates with `?`.
let boxed: Box<dyn std::error::Error> = Box::new(Error::NoRules);
assert!(boxed.to_string().contains("no rules"));
```
---
## Re-export: `syntax_lang`
```rust,ignore
pub use syntax_lang;
```
The [`syntax-lang`](https://docs.rs/syntax-lang) crate, re-exported whole.
[`Grammar::sexp`](#grammarsexp) reads its `Node`; building trees through the
re-export guarantees the same version this crate was compiled against, with
no separate dependency to keep in step.
```rust
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};
let tree = Node::new("source_file", vec![Element::Token(Token::new("word", Span::new(0, 4)))]);
assert_eq!(tree.span(), Span::new(0, 4));
```
---
## Feature flags
| Feature | Default | Effect |
|---|---|---|
| `std` | yes | The standard library. Without it the crate is `no_std` and needs only `alloc`. Forwards to `syntax-lang/std`. |
---
## Guide: generating a grammar package
A tree-sitter grammar package is a directory holding `grammar.js`, the
generated parser under `src/`, and corpus tests under `test/corpus/`. The
grammar is best generated by a small program next to the language's own
code — an example or an `xtask` — so it is rebuilt whenever the language
changes:
```rust,no_run
use std::{fs, path::Path};
use treesitter_lang::{Grammar, Rule};
fn grammar() -> Grammar {
Grammar::new("mini")
.extra(Rule::pattern(r"\s"))
.word("identifier")
.rule("source_file", Rule::repeat(Rule::symbol("statement")))
.rule("statement", Rule::seq([Rule::symbol("identifier"), Rule::string(";")]))
.rule("identifier", Rule::pattern("[a-z_]+"))
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir = Path::new("tree-sitter-mini");
fs::create_dir_all(dir)?;
let mut buffer = String::new();
grammar().write_js(&mut buffer)?;
fs::write(dir.join("grammar.js"), &buffer)?;
Ok(())
}
```
Then, in the package directory:
```bash
tree-sitter generate # grammar.js -> src/parser.c, src/grammar.json, src/node-types.json
tree-sitter test # run the corpus
```
`tree-sitter generate` evaluates `grammar.js` with Node.js by default, or
with its built-in JavaScript runtime given `--js-runtime native`. To skip
JavaScript altogether, emit [`grammar.json`](#grammarto_json) instead and run
`tree-sitter generate grammar.json`: it produces the same parser.
If generation stops on a conflict, it prints the ambiguous token sequence and
the rules involved. Settle it with [`prec`](#ruleprec),
[`prec_left`](#ruleprec_left), or [`prec_right`](#ruleprec_right) when one
reading is always right, or declare it with
[`Grammar::conflict`](#grammarconflict) when the parser must decide at run
time.
---
## Guide: corpus tests from a hand-written parser
The point of keeping the grammar in Rust is that it can be held to the
language's real parser. The steps:
1. **Name kinds after rules.** Give the kind type a method returning each
kind's rule name. Node kinds and named tokens (identifiers, numbers,
comments) use their rule names; punctuation and keywords that the grammar
writes as strings use any name that is not a rule, such as their text.
2. **Place trivia as tree-sitter does.** Tree-sitter puts an extra (a
comment, whitespace) inside the innermost node whose first and last
tokens surround it, and outside any node that starts or ends there. A
parser that holds trivia back until the next token is consumed, then
attaches it to whichever node that token belongs to, matches.
3. **Render each sample.** Parse it, call [`write_sexp`](#grammarwrite_sexp),
and write the entry: a `===` header with a title, the source, a `---`
divider, and the S-expression.
4. **Run `tree-sitter test`.** It parses every sample with the generated
parser and compares the trees.
```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};
let grammar = Grammar::new("lists")
.extra(Rule::pattern(r"\s"))
.rule("source_file", Rule::repeat(Rule::symbol("list")))
.rule("list", Rule::seq([
Rule::string("("),
Rule::repeat(Rule::choice([Rule::symbol("atom"), Rule::symbol("list")])),
Rule::string(")"),
]))
.rule("atom", Rule::pattern("[a-z]+"));
// What a hand-written parser built for `(a (b))`.
let t = |kind, start, end| Element::Token(Token::new(kind, Span::new(start, end)));
let inner = Node::new("list", vec![t("(", 3, 4), t("atom", 4, 5), t(")", 5, 6)]);
let outer = Node::new("list", vec![
t("(", 0, 1), t("atom", 1, 2), t(" ", 2, 3), Element::Node(inner), t(")", 6, 7),
]);
let tree = Node::new("source_file", vec![Element::Node(outer)]);
let mut entry = String::from("=====\nNested lists\n=====\n\n(a (b))\n\n---\n\n");
grammar.write_sexp(&tree, |k| *k, &mut entry)?;
assert!(entry.ends_with("---\n\n(source_file\n (list\n (atom)\n (list\n (atom))))"));
// std::fs::write("tree-sitter-lists/test/corpus/lists.txt", entry)?;
# Ok::<(), treesitter_lang::Error>(())
```
The [`corpus` example](../examples/corpus.rs) does this for a small
expression language with comments, using a complete hand-written lexer and
Pratt parser; the CI suite runs its corpus through `tree-sitter test` on
every change.
---
## Stability
As of `1.0.0` the public API is frozen. treesitter-lang follows
[Semantic Versioning](https://semver.org/); within the `1.x` series:
- The **surface** will not change in a breaking way: [`Rule`](#rule) and its
seventeen constructors (`symbol`, `string`, `pattern`, `blank`, `seq`,
`choice`, `optional`, `repeat`, `repeat1`, `field`, `alias`, `token`,
`immediate`, `prec`, `prec_left`, `prec_right`, `prec_dynamic`) with
`Clone` and `Debug`; [`Grammar`](#grammar) (`new`, `rule`, `extra`,
`external`, `supertype`, `inline`, `conflict`, `word`, `to_js`, `write_js`,
`to_json`, `write_json`, `sexp`, `write_sexp`) with `Clone`, `Debug`, `Send`,
and `Sync`; [`Error`](#error), its variants and their fields, with `Clone`,
`Debug`, `PartialEq`, `Eq`, `Display`, and `core::error::Error`; and the
[`syntax_lang`](#re-export-syntax_lang) re-export. New constructors, builder
methods, and error variants are minor additions.
- `Error` is `#[non_exhaustive]`, so failure modes can be added in a minor
release: match it with a wildcard arm. The meaning of every existing
variant is fixed.
- The **validation contract** holds: a grammar that validates is one
`tree-sitter generate` loads, up to what only its parse tables reveal
(conflicts, and extras whose end it cannot tell); and a grammar validation
refuses is one tree-sitter refuses, crashes on, or hangs on — apart from the
documented stricter checks. Checks may be refined in a minor release only
to follow tree-sitter more closely; the stricter checks stay. (1.0.1
brought patterns under this contract as a security fix: see below.)
- The **output contract** holds: `to_js` writes a `grammar.js` that describes
exactly the grammar built, and `to_json` writes tree-sitter's
`grammar.json` for it, generating the same parser. The `grammar.json`
matches, byte for byte, the file the tree-sitter versions in the
[compatibility table](#from-rust-to-tree-sitter) write; when tree-sitter
changes its own format, a minor release may follow it.
- The **rendering rules** of [`sexp`](#grammarsexp) — which names are shown,
spliced, or left out, and the two-space indentation — are fixed.
- `syntax-lang` is a **public dependency**: the re-exported crate and the
tree type `sexp` takes come from `syntax-lang` 1. Moving to a new major
version of it would be a major release here.
- MSRV (Rust 1.85) is a compatibility surface: raising it is a documented
minor change, never a patch.
What is **not** promised: the exact layout of `grammar.js` (line breaks and
spacing may improve; what it describes may not change), which problem
validation reports first when a grammar has several, the `Display` wording of
`Error`, the `Debug` output of any type, and performance figures — the
benchmarks are tracked, but they are measurements, not guarantees.
**1.0.1 and patterns.** Until 1.0.1 a pattern was emitted unchecked, its
validity left to tree-sitter, and a pattern with an unclosed character class
could make the emitted `grammar.js` run text from the grammar's own strings
as code when tree-sitter evaluated it (ISSUES H06). 1.0.1 checks every
pattern against both parsers that read it (see
[accepted patterns](#accepted-patterns)) and writes every literal so that it
ends at its own closing slash. The patterns newly refused are ones the
JavaScript runtime or tree-sitter already refused, so no `grammar.js` that
loaded and generated stops validating. One workflow is affected: a grammar
emitted only as `grammar.json`, with a pattern JavaScript refuses but
tree-sitter's parser accepts (`a**`, `[😀-😁]`), validated before and is
refused now — both formats describe one grammar, and its `grammar.js` could
never load. The public surface is unchanged: the report travels in
[`Error::EmptyString`](#error).
Features planned for 1.1.0, all additive: named precedences (tree-sitter's
`precedences` field), reserved-word sets, anonymous aliases, and a
`Grammar::check` that validates without emitting. Pattern flags remain a
candidate.
See [`../dev/ROADMAP.md`](../dev/ROADMAP.md) and
[`../CHANGELOG.md`](../CHANGELOG.md).