GNU TeXmacsUser manualReferenceAboutEnglish
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.

1.The generator

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).

2.The registry and the cache

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):

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.

3.From the tables to the runtime

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.

4.External scanners in Scheme

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.

5.Adding a language

  1. 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.

  2. 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.

  3. 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).

  4. 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.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".