Skip to content

Persistence grammars

A model is stored as real source text, not as a custom format. Which syntax that text uses is the language's persistence grammar. Python is the default; JavaScript and TypeScript are also built in; a plugin can register a new one, including one with no tree-sitter parser at all. This page covers choosing a grammar for a language, describing how your concepts print and parse in it, and adding a grammar.

Choosing a grammar for a language

Set persistenceGrammar on the language definition:

export default {
    name: "jsgrammar",
    namespace: "jsgrammar",
    displayName: "JS Grammar Demo",
    persistenceGrammar: "javascript",
    _importNames: ["core"],
    concepts: [],
};

The grammar decides the model file's extension (.model.py for Python, .model.js for JavaScript, a grammar's own fileExtension otherwise) and the # format: <grammar> header line written into any non-default file, so a file re-reads correctly without needing its Language in hand. A model file has exactly one grammar for all of its roots; secondary language imports compose concepts only and never contribute a grammar. Header metadata is limited to package, modelimports, format and langversion; a model's name is its file or folder name.

The built-in demos show the range:

Plugin What it proves
plugins/lang-jsgrammar/ persistenceGrammar: "javascript" with no concepts of its own: it imports Core and relies on the javascript: mappings Core concepts already declare.
plugins/lang-typescript/ The same for "typescript", sharing the JS-family mappings through aliasOf.
plugins/lang-json/, plugins/lang-xml/ headerless grammars: the model file is the bare format (no # key: value header), because JSON has no comments and XML must start with its declaration. See "Headerless grammars" below.
plugins/lang-sexpr/ A fully separate S-expression language with its own hand-rolled parser and its own concepts: grammar implementation, not just selection, is plugin-writable.

plugins/lang-python/ owns the Python, JavaScript and TypeScript tree-sitter grammars, their syntax-tree-to-AST mappers and printers; the engine under src/ knows none of them. Anything whose model files are Python-syntax imports plugins/lang-python/grammar/ts-parser.ts.

Describing a concept's syntax: surface

A concept's text syntax is a mapping per grammar. Unlike generate(), which is lossy one-way compilation to some output language, it must be lossless and round-trippable: parse(print(node)) has to reproduce node. It is written as the text the concept prints, with a hole for each slot:

surface = persist((self) => ({
    python:     print`${pad}while ${self.cond}:\n${suite(self.body)}`,
    javascript: print`${pad}while (${self.cond}) ${block(self.body)}`
        .parses("while_statement", { condition: self.cond, body: self.body }),
}));
surface = persist(() => infix("+"));                                   // Plus: text and node type per grammar
surface = persist((self) => ({ tsx: node("arguments")`(${self.args})` })); // TsArguments: a concept that IS the host syntax node

(From While, Plus and TsArguments.) persist (plugins/lang-python/grammar/surface-print.ts) is the only entry point: it returns a function the engine calls as a method, hands its callback the concept's slots as handles (a name that is not a slot is an error when the surface is harvested), and lowers what the callback returns to the declarations the engine has always run, so nothing downstream reads a different shape. The Language Editor's Text syntax tab reads this form and draws it (see the user guide).

Builder Writes
print`...` The text a grammar prints: literal text, and ${self.slot}, ${pad} (the statement's indentation), ${suite(self.body)} (Python's indented body), ${block(self.body)} (a braced body), ${text(self.name)}, ${children(", ")} or ${self.items.join(", ")} (a list), ${self.x.opt((r) => print ...${r})} (a part that is there only when the slot is; test: picks which kind of presence), ${whenCount(1, print...)}, and Python's named helpers (loopTarget, receiver, compCond, elseTail, annotation, ...).
.parses(type, { field: self.slot }) For a grammar that also reads text: the syntax-tree node it matches and which field fills which slot. How a field becomes the slot (expr, block) is derived from the slot's kind; .as("text"), .inner(), .omitIfAbsent() say it otherwise.
infix("+"), unary("~") An operator concept. One string is every grammar that has a default node type; { python: { operator: "==", type: "comparison_operator" }, javascript: "===" } spells out what differs.
node("if_statement")`...` A concept that is the host grammar's syntax node (the lang-ts family). One hole per slot, in the order the slots are stored: a text property is a gap (the text between located parts; text when it is alone, .field(name) for a field's text), a child slot is a field named like the slot (.field(name), .position(i), .ofType(t) otherwise), a list slot is a list (.delimit(open, close), .skipLocated(), .inside(name, open, close)), mark(n) stores nothing, and literal text is text the source always has there.

Defaults come from the grammar, not from the slot alone: Python's declarations reference a slot by its position and print an unfilled required slot as __Empty__ (sf), every other grammar references it by name (the accessor's property key: then_ for the slot then) and does not. An index and a name are not interchangeable on a plain node, so .byName() / .byIndex() and .sf(false) override one reference. optional of a node part is derived from the slot's cardinality; an empty list delimiter is not no delimiter (.delimit("", "")).

What has no derived spelling still has a name, never an object literal: the Text syntax tab draws a template's holes and read rows as concepts, and anything it cannot name would show up as JSON. tests/test-surfacerules-no-json-holes.mjs opens every bundled surface body and fails when a concept gains a raw({...}) hole or a .with({...}) tail.

Writes Spelled
Lists of children ${eachChild(print`\n${item.stmt()}`, { from: 1 })}, ${eachOf(self.handlers, print`...`)} with item / item.stmt().deeper() / item.empty("__Empty__") / itemBody for the current entry and whenItem([heads], then, otherwise) to chain a handler onto the line; members(self.body) is a JavaScript class body
Comment lines suppressComment("#"), docEntryComment, docComment, disabledComment("#", self.text) (the grammar's comment sign is the argument)
One-off print rules prefixedStatement(self.def.byIndex(), "async ", { whenStartsWith: "function" }), operands(" ?? ", { precedence: "nullishCoalescing", forceParen: ["or", "and"] }), whenIdentifier(slot, then, otherwise), whenPrintedStartsWith(slot, "{", then, otherwise), oneOf(slot, ["const", "var"], "let"), self.start.omitIfEmpty()
Where a field is read from on the slot: .child(0), .path("initializer", 0, ofType("name")), .wholeNode(), .orChild(1), .orPath(...), .rest() with .rewrite("spread_element", "starred") and .dropNullish(), .asByType(type, "stmt"), .dropEmpty(), .orElse("empty"), .stripPrefix("^:\\s*"), .raw(), plus the older .as(...), .inner(), .omitIfAbsent()
Parse helpers (a field that is more than one slot's worth) heritage(self.bases, "classBases"), objectPairs(self.pairs), catchAndFinally(self.handlers), parameterList(self.params, "params"), literalChild(""), emptyChild
The rest of an entry after .parses(...): .forType(type, { ... }) (a template that matches several types), .rejects(unlessToken("of"), ifFieldType("body", "statement_block"), unlessPath([...], type), unlessPathText, unlessSameText(textAt(...), textAt(...)), unlessCount), .reports([types], ...rules), .wrapsWhenToken("async", "async"), .headWhenToken("*", "yieldFrom"), .expressionStatement("ExpressionStatement", [bare types]), .dispatchOn("left", [whenType([types], build(head, read("expr").field("object"), ...))], otherwise)

Each lowers to exactly the atom or parse slot the engine already ran, so the surface atom golden is the check. A new helper belongs in surface-print.ts (list it in plugins/lang-surfacerules/helper-vocabulary.ts if it only reads: NOT_HOLES keeps it out of the print-hole completion). raw({ ... }) and .with({ ... }) still exist as escape hatches and the tab draws them as objects, but the census test makes a new use of them a failing test; read the type and its comment in surface-shape.ts before adding an atom. A concept whose syntax is genuinely code (the kernelf and json concepts print through hand-written functions) keeps a surface() method returning { <grammar>: { match?, parse?, print } }:

  • match is the syntax-tree node type this concept owns: a string, or { type, operator } when several concepts share one tree shape and are told apart by operator text.
  • parse(cstNode, helpers, lang) builds the node. helpers has expr, stmt and block, recursive mappers for child syntax nodes.
  • print(node, printChild, lang) renders the node back to text. printChild prints a child in the same grammar.

Python text lives in the concept (its surface entry for python). With no Language in scope (serializeSourceFile(meta, ast), FullForm paste) the engine prints with the language a plugin registered through registerDefaultSurfaceLanguage (Core registers one in plugins/lang-core/languages/core-default-print.js), so the text of a head has one definition. Parsing with no Language is deliberately different: it is language-agnostic and lenient (any text, another language's sample included, becomes generic call-syntax nodes), so it stays on the Python grammar's own CST mapper.

Verifying a conversion. A round trip of the text is not enough: the node's string split between slots matters too. Convert in a throwaway worktree of the previous commit, parse every plugins/*/languages source file (and a set of targeted snippets for shapes the corpus lacks) with the old and the new code from the same input files, and compare the id-stripped AST and the reprinted text. For print-only grammar entries, print seeded random trees with both and re-parse. tests/test-python-legacy-concept-parity.mjs and tests/test-concept-source-parse-snippets.mjs keep the cases that outlive the one-off comparison.

A print-only entry is enough when the concept is resolved contextually by another mapper. A concept that omits surface(), or a grammar within it, falls back first to the Python grammar's own mapper for "python" parsing, and then to a universal call-syntax mapping in every grammar: the node prints as head(child, child, ...) and a bare-identifier call parses back to the same head and children. That makes a concept lossless in any grammar, just not idiomatic. It also has a trap: a concept with a trailing variadic slot and no surface() persists through that positional form, so inserting a new fixed slot in front later changes what old files mean. npm run lint:concepts flags this shape.

A grammar is selected through the whole pipeline by parseSurface(text, ctx) in src/surface.ts (text to AST, the entry point for the editor and tests) and, for files on disk, parseSourceFile and parseMultiRootSourceFile in src/source-file-format.ts, which dispatch on the file's # format: header.

Notations and grammars

A notation or concept feature that has no valid form in the file's grammar should not be offered. A notation can carry grammars: ["javascript"] so it appears only under that grammar; Core's /* ... */ comment notation does this because it has no Python surface form.

Registering a new grammar

import { registerGrammar } from "../../../src/grammar-registry.ts";

registerGrammar({
    name: "sexpr",                         // the persistenceGrammar value
    loadParser: async () => ({ parse: (text: string) => ({ rootNode: text }) }),
    mapModule: (rootNode: any) => parseSexprProgram(rootNode),   // syntax tree -> struktJS AST
    fileExtension: ".sexpr",
    aiCodeFormatGuidance: "Generated code uses S-expression syntax: ...",
});

Only name, loadParser and mapModule are required. The registry is deliberately tree-sitter agnostic: loadParser is any async function resolving to an object with parse(text), and rootNode can be a real syntax tree or, as above, the raw text with a hand-rolled parser doing all the work in mapModule. Optional fields:

Field Role
setAliasContext Per-parse alias context (Python only today).
aliasOf Fall back to another grammar's mappings ("typescript" to "javascript").
kdlHeuristicKeywords Regular expression for the paste heuristic that decides whether text is KDL.
operatorExtractors Operator disambiguation when concepts share one tree node type.
fileExtension Model file extension; falls back to .py.
literalSpelling { null, true, false } spelling; falls back to Python's.
headerless The format has no room for the # key: value header; see "Headerless grammars" below.
parser An already-available parser, so the grammar counts as loaded from registration on (no async loadParser step).
monacoLanguageId Editor highlighting id; defaults to the grammar name.
aiCodeFormatGuidance The "Code Format" guidance given to the AI agent for this grammar.
printer The grammar's contribution to the default surface printer (statement formatting and legacy per-head printing). Python registers one; resolved through aliasOf when absent.
isDefault Marks the default grammar (Python does). The engine asks getDefaultGrammarName(); nothing else names it.

Call registerGrammar at module top level in the plugin's languages/index.ts. lang-library.ts imports every plugin at boot, so the registration has run before any model in that grammar can open. Samples need no src/ change: sample discovery globs *.model.*.

Then:

  1. Define concepts whose surface() has a print function for your grammar name. With a non-Python, non-JS style of syntax, give each concept its own explicit print: the engine's statement-formatting strategy is a binary fork between Python-style and JS-family and your print methods bypass it entirely.
  2. Set persistenceGrammar on the language.
  3. Add a demo model under models/; its file extension comes from fileExtension.

Pitfalls

  • A test that builds its own narrow module graph (and does not import lang-library.ts) must import the plugin and await ensureGrammarLoaded("<name>") before parsing. Forgetting it does not throw: for an unregistered name parseSurface silently parses the text as Python, which shows up as a sample parsing to the wrong root concept.
  • Likewise, an unknown # format: value in a file falls back to Python rather than failing.
  • BINARY_PREC in surface-precedence.ts is a fixed table; binaryOp() throws if a concept's head is not in it. A fully parenthesised grammar never needs it; an infix grammar built from scratch must add an entry or print by hand.

Reference: Grammar registry for the full design and its deliberately narrow corners, and tests/test-lang-sexpr.mjs, tests/test-lang-jsgrammar.mjs and tests/test-lang-typescript.mjs for end-to-end parse, edit, generate, evaluate, save and reload checks.

Headerless grammars

A model file normally starts with # package:/# modelimports:/# format:/# langversion: lines. A format that cannot carry them (JSON has no comments; XML must begin with <?xml) registers headerless: true. For such a grammar:

  • the persisted file is the bare body and nothing else, so it stays a valid document of its own format;
  • the grammar is never read from a # format: line. It is the caller's (ctx.grammar), else its Language's persistenceGrammar, and a file name is mapped to its grammar by grammarForModelFileName();
  • package, modelImports and the language langVersion are read from and written to the model's sibling model.json (ModelJsonData.package/modelImports/langVersion), applied by project.ts's applyHeaderlessMeta;
  • a headerless grammar has no comments to hold the # struktjs:suppress/documentation/disabled attribute markers, so those annotations are not available in its models;
  • the Theia opener claims any <name>.model.<ext> file, .json included; the metadata file is the fixed name model.json, whose basename does not end in .model.

Pass parser (a synchronous parser) as well as loadParser when parsing needs no async setup, so ensureGrammarReadyFor(text), which can only peek a # format: line, is never needed.