![]() |
Grammars and their tables | ![]() |
A grammar becomes parse tables once, in Scheme and C++; the tables are kept as a text in a cache, and the C runtime of tree-sitter loads that text at the first use of the language. Nothing is compiled per grammar.
The modules of
progs/treesit
follow the crate generate of tree-sitter 0.27.1, stage by stage, since the order of its operations shows in the tables (numbers of the states, choice among equal items):
ts-base.scm
Symbols (integers ordered as the symbols of tree-sitter), token sets, character sets as sorted lists of ranges, growable vectors, a reader of JSON.
ts-grammar.scm
Reading grammar.json into rules, and the steps of prepare_grammar: the tokens extracted into the lexical grammar, the repetitions as auxiliary rules, the productions, the default aliases, the inlined rules.
ts-nfa.scm
The patterns of the tokens, parsed with the simplifications of the crate regex_syntax (they decide the shape of the automaton), and the NFA of the tokens; the Unicode classes come from
ts-unicode.scm
, generated by
gen-unicode.py
.
ts-tables.scm
The LR(1) item sets and the parse table, with the conflict resolution of tree-sitter.
ts-build.scm
The token conflicts, the keywords, the error state, the merging of compatible states and the lex tables (DFAs).
ts-language.scm,
ts-export.scm
What render.rs writes into parser.c, as plain data (the symbols renumbered as the runtime numbers them, the alias and supertype maps of the queries), and the text of it which
ts_dynamic.c
reads (integers, and strings written LENGTH:BYTES, starting with tsdyn1).
In Scheme, the generation of a large grammar takes minutes and gigabytes. When the glue tree-sitter-tables-start exists,
ts-native.scm
sends the prepared syntax grammar to C++ as a text;
ts_tables.cpp
builds the LR(1) states and the token conflicts and sends back what the choice of the keywords needs, which stays in Scheme; tree-sitter-tables-finish then merges the states and builds the lex tables, and tree-sitter-tables-export writes the whole text, to which Scheme only adds what depends on the symbols (their names, fields and aliases). The entry point is ts-generate-tsdyn of
ts-export.scm
. The C++ port gives the same text byte for byte, the Scheme code being the reference: (ts-set-native-tables! #f) or the variable TS_SCHEME_TABLES select the Scheme path, and the suite compares both. With TS_PROFILE=1 each stage prints its time (and, for the C++ stages, the memory).
ts-registry.scm
knows the grammars by their names in
misc/tree-sitter
(which are not always the names of the program languages: the language shell has the grammar bash):
treesit-languages, the grammars of the list of the program languages, and treesit-supported?, true when the build has the glue and the grammar is there;
treesit-cache-url: the tables of a grammar are cached in $TEXMACS_HOME_PATH/system/cache/tree-sitter/<grammar>-<hash>.tsdyn, the hash being that of the text of grammar.json preceded by treesit-generator-version. A changed grammar, or a new version of the generator, thus gives another file, and the old one is no longer read. The version is to be changed with the generator or the exported data;
treesit-generate-cache generates the tables and writes them under a name ending in .part, then renames the file, so that a reader never sees half of it;
treesit-language gives the index of a grammar in the C runtime when its tables are ready, else #f, and then starts their generation; treesit-prepare calls a continuation when they are ready. The generation runs in a second TeXmacs without window (texmacs.bin -headless -x, through async-evaluate-system), with the message “Preparing the syntax of …”, while the usual highlighter colours the code.
The tables of all the grammars are shipped as well, compressed by xz, as misc/tree-sitter/<grammar>/<name of the cache file>.xz (1.6 MB for the 22 grammars): generating them all at the first start would take more than a minute, Lean alone about a minute and several gigabytes. treesit-cached? unpacks them into the cache when it lacks them (glue tree-sitter-unpack,
ts_xz.c
). Since the name holds the hash, shipped tables of an older grammar or generator are ignored and the grammar is generated as before.
ship-tables.sh
makes them again; the suite fails while they do not match.
tree-sitter-language-load reads the cached file in C++ (no Scheme string of a megabyte) and gives it to tsdyn_language_new: every state becomes a large state (one row of the parse table), the lex functions interpret the lex tables, and since the runtime calls them without the language, each loaded language takes one of TSDYN_MAX_LANGUAGES (32) pairs of functions. The result is an index into the languages of
tree_sitter_glue.cpp
, which Scheme passes to all the other glue routines. Queries are compiled by tree-sitter-query-new for a language; their regular expressions (#match?, and the Lua patterns of #lua-match?) are compiled once with std::regex.
A grammar with a scanner.c needs a port of it, ts-scanner-<grammar>.scm, listed in treesit-scanners of the registry. The protocol is described in
ts-scan.scm
: a scanner is a vector #(create scan deserialize serialize); (scan payload lexer valid), the payload being what create made, reads the text with lexer-lookahead, lexer-advance!, lexer-mark-end!, lexer-set-result!, lexer-column, lexer-eof?, valid being the vector of the external tokens which the parser accepts. (serialize payload) gives the state, a value compared by equal? and never modified afterwards (#f for the initial state), which (deserialize payload state) puts back; record-scanner makes these for a vector of fields. A scanner without state, as that of TOML, ends with:
(define-public (ts-toml-scanner) (stateless-scanner toml-scan)) |
The same functions serve both parsers: on the vector lexer of
ts-parse.scm
they act in Scheme, on anything else they call the glue tree-sitter-lexer-… on the current TSLexer. tree-sitter-set-scanner installs C++ trampolines (one create function per language, 32 slots, a language given its scanner again keeping its slot): the vectors of valid tokens are made once per row of the table of the external states, and the texts of the serialized states are mapped back to their values, so that the reader is rarely called. The loops over characters of
ts-scan.scm
(scan-advance-while!, scan-advance-until!, scan-skip-spaces!) run in C on the C lexer. The C code of a scanner is followed closely, quirks included, since the corpus of the grammar checks the trees.
A directory misc/tree-sitter/<grammar> with grammar.json, its LICENSE, a SOURCE which names the repository and its commit (and what is ours or patched), and the queries: highlights.scm (a first line ; inherits: c puts the query of another grammar before it), and when there are some injections.scm, tags.scm (the definitions), indents.scm (those of nvim-treesitter, Apache-2.0, the files they inherit put in front) and closers.scm (made by
gen-closers.py
). There is no query of folds: folds come from the nodes of several lines.
An entry of
tm-program-languages.scm
with (grammar "…"), and its comments (comment, block-comment) and other names (names, also used to resolve injections). This list also says what a new language needs outside of tree-sitter: the macros of its tags, its format and its -lang.scm.
The port of the scanner, if any, in treesit-scanners and in the modules used by the registry; without indents.scm, the rules of indentation of the language in syntax-indent-rules of
ts-edit.scm
(as for YAML, LaTeX, Lean and Haskell), else the lines are not indented by the tree. The runtime has 32 places for languages and 32 for scanners, shared by all (22 grammars and 17 scanners today).
The checks of
misc/tree-sitter
:
corpus.py
(the corpus of the grammar through the C runtime, compared as tree-sitter test does),
highlights.py
(the captures compared with those of tree-sitter query), then
ship-tables.sh
for its tables.
check-grammars.py
compares the grammars with clones of their repositories and updates one.