Project

EarthSciAST

The EarthSciML Abstract Syntax Tree format: schema, operators, coupling, and five language bindings.

Contents

This is the documentation for the older version v0.16.0. For the latest release, see v0.17.0.

The printer: expressions to tokens

Lean module Esm.Document.Math.Print, formal/Esm/Document/Math/Print.lean at ed59cfa2b070
Imports Esm.Document.Math.Surface, Esm.Document.Notation

pa c L e prints the expression e for a position that needs precedence level at least L, adding grouping parentheses when e’s own level is lower. The levels, loosest first (spec §4.1.1, Notation.precedence ):

levelconstruct
1or chain
2and chain
3a comparison
4+ chain, binary -
5* chain (juxtaposition, \cdot before a factor that starts with a digit or sign), unary -
6not; a derivative applied to a parenthesized operand; a \nabla form (its operand at level 9)
7Typst fraction a/b and Typst (dif N)/(dif t); a negative literal and a quantity (as the base of a power or an index they are parenthesized, and as a Typst fraction operand)
8power
9index (subscript or brackets)
10atoms: names, numbers, groups, function forms, LaTeX fractions, cases, calls, escapes

Operands of an n-ary chain are printed one level tighter, so a nested chain of the same operator keeps its parentheses and the JSON tree is kept exactly (the parser flattens a chain into one node). Binary - takes its left operand at its own level (a + b - c), its right operand one tighter.

Which notation a node gets is decided from its exact JSON shape; anything without a native or call notation prints in the generic escape form, which every node has.

Text pieces

def escSet (c : Char) : Bool

The characters escaped by a backslash inside \mathit{}, \operatorname{}, \esm{} and a name subscript’s \mathrm{}.

def escT : List Char → List Char

Escape the text of \mathit{} and the like.

def unescT : List Char → List Char

Undo escT .

def keySpecial (c : Char) : Bool

Characters of a field key written as {\char NNN} (three decimal digits) in LaTeX: they would end a Markdown math span ($), start a comment (%), be read as an alignment tab (&), a macro parameter (#), a space (~), a superscript (^) or a control sequence (\). With _, {, } written \_, \{, \}, a key is as safe inside \mathrm{} as a JSON string value is (Esm.Document.Math.Latex.quoteL).

def dig3 (n : Nat) : List Char

Three decimal digits.

def escK : List Char → List Char

Escape a field key for \mathrm{}.

def unescK : List Char → List Char

Undo escK .

def natChars (n : Nat) : List Char

The digits of a natural number.

The printing context

def grp (sf : Sf) (ts : List Tok) : List Tok

Grouping parentheses.

def rpG (sf : Sf) : Tok

The closing token of a grouping parenthesis.

def sepBy (sep : List Tok) : List (List Tok) → List Tok

Items joined by a separator.

Names

def baseTok (g : List Char) : Tok

A single letter or a Greek name as a token.

def subTxt (sf : Sf) (r : List Char) : List Tok

The subscript text of a name: upright.

def formulaRaw (g : List Char) : List Char

The raw \mathrm{} content of a formula: counts as _{n}.

def formTok (sf : Sf) (g : List Char) : Tok

A formula name.

def segToks (sf : Sf) (g : List Char) : List Tok

One segment of a name, by its shape.

def explicitName (S : Sym) (s : String) : Bool

A name never prints bare where the parser would read it otherwise: an undeclared e (bare e^{x} reads as exp) and an undeclared d (bare \frac{d N}{d t} reads as a derivative) print in the explicit form.

def plainLast (s : String) : Bool

The last segment of a name prints with no subscript, so an index subscript may follow it.

JSON inside escape nodes (LaTeX)

Operator tables

def fnKw : List (String × Kw)

Unary functions with a native spelling, and their keyword.

def cmpKw : List (String × Kw)

Comparisons and their token.

def callOps : List String

Core operators in the call form.

def fieldCallOps : List String

Core operators with no notation of their own that print in the call form, their fields as named arguments after ; (when no field annotates the node).

def reservedOpn : List String

Names \operatorname{…} never means a template or an open operator by.

def coreOps : List String

coreOpNames of Notation.

def opnOK (s : String) : Bool

A name \operatorname{…} can carry: identifier characters and dots.

abbrev annotKeys : List String

The fields that annotate a node.

def callFormOK (o : String) (fs : List (String × Json)) : Bool

An operator prints in the call form: an open operator, or a core operator of fieldCallOps none of whose fields annotates it.

def mathKeys : List String

The fields of a core operator in the call form that hold an expression; the others print as JSON, even a string that is a name.

def mathField (o : String) (kv : String × Json) : Bool

A field of a call-form node prints as math: its value is an expression and, for a core operator, the field holds one. An open operator’s fields are all read as math when they can be.

def keyOK (s : String) : Bool

A field key printed upright in a call: an identifier.

def insKV (kv : String × Json) : List (String × Json) → List (String × Json)

Sorted insertion by key.

def fieldsOf (kvs : List (String × Json)) : List (String × Json)

The fields of a node other than op and args.

def mkNode (o : String) (as : List Json) (fs : List (String × Json)) : Json

A node from its operator, operands and other fields (sorted keys).

def node (o : String) (as : List Json) : Json

The plain two-field node.

def simpleTok : Tok → Bool

Typst exponent and subscript tokens that need no parentheses: a nonnegative number in positional spelling, a letter, a Greek name.

def tparams (S : Sym) (n : String) : Option (List String)

The template parameter list, when the symbol table knows it.

def positional (S : Sym) (n : String) (bs : List (String × Json)) : Option (List String)

Positional template arguments: the table knows the parameters, they are distinct, and the bindings bind exactly them.

def rawB : Nat → List Char → Option (List Char × List Char)

Balanced text up to the } that closes depth 0; \x is one unit.

def balOK (raw : List Char) : Bool

Raw text that rawB reads back whole (the LaTeX lexer reads \mathrm{…} and \text{…} contents with rawB ).

def factorsOf (u : String) : List Esm.Units.Factor

The two-sided factor list of a units string ([] when it does not parse).

def unitsOK (sf : Sf) (u : String) : Bool

The units of a quantity print typeset when the string is the canonical spelling of a non-dimensionless unit whose typeset form reads back (Phase 1: every canonical unit does).

The printer

def wrap (sf : Sf) (L : Nat) (p : Nat × List Tok) : List Tok

Wrap a printed form for a position needing level L.

def mulToks : List (List Tok) → List Tok

A * chain: juxtaposition, \cdot before a factor that starts with a number.

theorem sizeOf_lt_arr proved source
theorem sizeOf_lt_arr {a : Json} {as : List Json} (h : a ∈ as) :
    sizeOf a < sizeOf (Json.arr as)

Size bookkeeping for the recursion.

inductive NabK source
inductive NabK where
  | grad | div | lap | curl
  deriving DecidableEq

The four defined operators with a \nabla form (spec §1.2): grad, div, laplacian, curl.

inductive OpK source
inductive OpK where
  | minus | div | pow | lnot | tru | fls | ite | ic | index
  | cmp (k : Kw) | un (k : Kw) | plus | times | land | lor | mm (k : Kw) | nab (n : NabK) | call | other
  deriving DecidableEq

How a plain node (op and args only) prints, by its operator.

def unKw : List (String × Kw)

Unary functions with a native spelling: their keyword (log10 is \log_{10}).

def kindTable : List (String × OpK)

The plain-node operators with their own notation.

structure Out source
structure Out where
  lvl : Nat
  toks : List Tok
  crow : List Tok

The printed form of an expression and its level. crow is the form as the last rows of a cases block: an ifelse chain contributes its rows, anything else is the otherwise row.

def escToks (sf : Sf) (o : String) (fs : List (String × Json)) (args : List (List Tok)) :
    List Tok

The escape form: LaTeX \esm{op}{fields}{args} with the fields as JSON, Typst esm.node("op", #(fields), args).

def lpC (_sf : Sf) : Tok

The call parenthesis ( (LaTeX (, Typst ( right after a name).

def callToks (sf : Sf) (head : List Tok) (args : List (List Tok)) : List Tok

A call: name(args) with call parentheses.

def unToks (sf : Sf) (k : Kw) (t : List Tok) : List Tok

A unary function applied to the printed operand t.

def caseRow (sf : Sf) (v cnd : List Tok) : List Tok

One cases row, value & \text{if } condition, then the row break.

def icTail (sf : Sf) : List Tok

t_{0} in an initial condition N(t_{0}).

def subList (sf : Sf) (simp : Option Tok) (args : List (List Tok)) : List Tok

A subscript list: LaTeX _{a, b}; Typst _a for one simple token, else _(a, b).

def simpleE (c : Ctx) : Json → Option Tok

The one token a Typst exponent or subscript may be written as without parentheses: a nonnegative number in positional spelling, or a one-letter or Greek name.

def subOK (S : Sym) (base : Json) (is : List Json) : Bool

The index prints with a subscript unless the base is not a plain name, or the subscript would collide with a name: one formula-shaped name (it would read as the upright subscript of a name), or one digit literal n when base_n is declared (k_{1} would look like the name k_1; decision 5).

def subPat4 (sf : Sf) : Tok → Tok → Tok → Tok → Bool

Four tokens of an upright name subscript.

def subPat (sf : Sf) : List Tok → Bool

An upright name subscript: a name before it would read it as part of the name.

def inlineD (o : Out) : Bool

Derivative operand printed inline (\frac{\mathrm{d} N}{\mathrm{d} t}) when it is postfix-level or tighter, and not a negative literal.

def keyToks (sf : Sf) (k : String) : List Tok

A field key, upright.

def jsonVal (sf : Sf) (v : Json) : List Tok

A field value that is not an expression, as JSON.

def openToks (sf : Sf) (o : String) (args fields : List (List Tok)) : List Tok

The open-operator call: positional operands, then ; and the fields.

def dTime (sf : Sf) (a : Out) : Out

The time derivative.

def dSpace (sf : Sf) (w : List Tok) (a : Out) : Out

The spatial derivative along the axis printed w.

def dCall (sf : Sf) (w : List Tok) (args : List (List Tok)) : List Tok

partial with trailing operands: \partial_{x}(u, a, b) / partial_(x)(u, a, b).

def nabName : NabK → String

The operator a \nabla form stands for.

def nabHead (sf : Sf) : NabK → List Tok

What a \nabla form writes before its operand: \nabla, \nabla \cdot, \nabla^{2}, \nabla \times (Typst nabla, nabla dot, nabla^2, nabla times).

def nabArg9 (sf : Sf) (n : NabK) (t : List Tok) : List Tok

An operand printed at the level of a power base, t; after the \times of a curl, one that starts with a number in parentheses.

def startsNabla : List Tok → Bool

The printed form starts with \nabla.

def nabArg (sf : Sf) (n : NabK) (o : Out) : List Tok

The operand of a \nabla form: another \nabla form as it is (\nabla \cdot \nabla u is div(grad(u))), anything else at the level of a power base. After \times an operand that starts with a number is parenthesized too, so that no \times 10^{…} follows a token (the lexers read a number’s scientific tail there).

def qtyToks (n : JNum) (l : List Esm.Units.Factor) : List Tok

The quantity 3\,\mathrm{m/s} / 3 thin upright("m") thin upright("s")^(-1): the number, then the unit as one token.

Constant arrays

def numsOf : List Json → Option (List JNum)

The entries of a list that are all well-formed numbers.

def rowsOf : List Json → Option (List (List JNum))

The rows of a list of number lists.

inductive AForm source
inductive AForm where
  | col (ns : List JNum)
  | mat (rs : List (List JNum))

The two array shapes with a native spelling.

def arrForm : Json → Option AForm

A constant array printed natively: a column for rank 1, or a matrix of at least two columns (a single-column matrix would print like a column), of any size, every entry a well-formed number.

def bmatCols : Nat

The most columns a LaTeX bmatrix takes (amsmath’s MaxMatrixCols).

def arrToks (sf : Sf) : AForm → List Tok

The array: LaTeX bmatrix, or for a matrix wider than bmatCols \left[\begin{array}{c…c} … \end{array}\right]; Typst vec(…) / mat(…).

def unitToks (l : List Esm.Units.Factor) : List Tok

The unit after a number or an array.

Reductions (faq)

def jbeq : Json → Json → Bool

Equality of JSON values as a check.

def idxBase (kvs : List (String × Json)) : Option String

The array an index node reads, when it names one.

def basesJ : Json → List String → List String

The arrays an expression indexes, in first-use order (appended to acc).

inductive RedK source
inductive RedK where
  | sum | prod | max | min
  deriving DecidableEq

The reductions with a native spelling.

structure FaqForm source
structure FaqForm where
  red : RedK
  marked : Bool
  out : List Json
  ranges : List (String × Json)
  expr : Json
  filter : Option Json
  set : List String

A faq node with a native spelling, by its parts. marked: args lists the arrays the body indexes; otherwise args is set (empty, or names printed as a superscript set).

def FaqForm.args (F : FaqForm) : List Json

The args of a native faq.

def FaqForm.sup (F : FaqForm) : List String

The names a superscript set shows: set when args is not the body’s arrays.

def strsOf : List Json → Option (List String)

The strings of a list of JSON values, when they are all strings.

def faqCand (kvs : List (String × Json)) : Option FaqForm

The parts a faq node would have.

def faqForm (kvs : List (String × Json)) : Option FaqForm

The parts of a faq node, when it is exactly the node they rebuild: no semiring, join, distinct or key, reduce absent or *, max, min, ranges absent or not empty, args empty, the arrays the body indexes, or other names.

def rangeOK : Json → Bool

A range a row can spell: [a, b], {"from": S} or {"from": S, "of": [i, …]}.

def outOK (j : Json) : Bool

An output entry: a name, or the singleton dimension 1.

def occursJ (k : String) : Json → Bool

A bare name occurs in an expression.

def faqOK (F : FaqForm) : Bool

The conditions under which the native spelling reads back.

def upSet (sf : Sf) (g : List Char) : Bool

A segment of an index set’s name that a Typst range row sets upright, k in upright("lev"): a set is named, as a function’s name is (upright("op")), not a quantity, and an italic lev reads as the product l·e·v (decided 2026-11-26). It is exactly a segment that would otherwise print italic("…"): an identifier that is neither a letter, a Greek name, the x_i shape nor a formula. Each segment of a scoped set name follows the rule on its own (upright("lev")"."upright("top"), a"."upright("bins")), so those other segments print as in any name, and LaTeX prints every set name as a name. The reader accepts an upright set segment only when this holds, so the upright spelling of a set is unique.

def setSegToks (sf : Sf) (g : List Char) : List Tok

One segment of an index set’s name.

def setToks (c : Ctx) (s : String) : List Tok

The tokens of an index set’s name in a range row: nameToks with setSegToks for each segment.

def rowToks (c : Ctx) (P : Json → Out) (kv : String × Json) : List Tok

A range row: a \le k \le b, k \in S, k \in S(i, j).

def redRanges (F : FaqForm) : List (String × Json)

The reduced ranges: those of indices that are not output indices.

def subRows (c : Ctx) (P : Json → Out) (F : FaqForm) : List (List Tok)

The rows of the subscript: the reduced ranges, then the filter.

def headToks (sf : Sf) (F : FaqForm) : List Tok

The operator, marked when args is listed.

def subToksL (c : Ctx) (P : Json → Out) (F : FaqForm) : List Tok

The LaTeX subscript: none, one row, a lone dense range _{k=a}^{b} (not when args is a superscript set), or \substack.

def subToksT (c : Ctx) (P : Json → Out) (F : FaqForm) : List Tok

The Typst subscript: rows in _( … ), stacked with \.

def supToks (c : Ctx) (ns : List String) : List Tok

The superscript set of names: LaTeX ^{\{f, g\}}, Typst ^({f, g}).

def supT (c : Ctx) (F : FaqForm) : List Tok

The args set of a faq, as a superscript, when it is one.

def redToks (c : Ctx) (P : Json → Out) (F : FaqForm) : List Tok

The reduction: operator, subscript, the superscript set (on the operator only when there are no output indices), body at level 5.

def entryToks (c : Ctx) (P : Json → Out) (F : FaqForm) (j : Json) : List Tok

An output entry: its range row when it has one.

def faqOut (c : Ctx) (P : Json → Out) (F : FaqForm) : Out

The native faq: the reduction, wrapped with its output indices when it has some. A superscript set goes on the bracket, before its subscript (it renders the same either way; written first, a reader meets it right after the bracket); the form is then a power’s level (a power of it, or an index into it, is parenthesized: no double superscript).

def faqSubs (F : FaqForm) : List Json

The sub-expressions a native faq prints.

def tableP (t : List (Json × Out)) (x : Json) : Out

A printer given by a table of printed sub-expressions.

Block assembly (makearray)

structure MkForm source
structure MkForm where
  out : List String
  regions : List (List (Json × Json))
  values : List Json

A makearray node with a native spelling, by its parts: the output indices (empty when the node has no output_idx), and the regions with their values.

def pairsOf : List Json → Option (List (Json × Json))

The bound pairs of a region.

def regionsOf : List Json → Option (List (List (Json × Json)))

The regions of a regions list.

def mkCand (kvs : List (String × Json)) : Option MkForm

The parts a makearray node would have.

def mkForm (kvs : List (String × Json)) : Option MkForm

The parts of a makearray node, when it is exactly the node they rebuild: args empty, regions and values, and an output_idx of names or none.

def mkOK (M : MkForm) : Bool

The conditions under which the native spelling reads back: one value per region, at least one region, each region a nonempty list of bound pairs, values and bounds expressions, output indices names.

def mkSubs (M : MkForm) : List Json

The sub-expressions a native makearray prints.

def cellSep : Sf → Kw

The cell separator, the row separator and the closing token of the table.

def pairToks (c : Ctx) (P : Json → Out) (p : Json × Json) : List Tok

A bound pair: a, b (its brackets are written around it).

def regToks (c : Ctx) (P : Json → Out) : List (Json × Json) → List Tok

A region: [a, b] \times [c, d], one bound pair per dimension.

def mkRow (c : Ctx) (P : Json → Out) (vr : Json × List (Json × Json)) : List Tok

A row of the table: the value, then the region it fills.

def matHead : List Tok

The Typst table head: mat(delim: "[", augment: #1,.

def mkSub (c : Ctx) (out : List String) : List Tok

The output indices as the bracket’s subscript.

def mkOutT (c : Ctx) (P : Json → Out) (M : MkForm) : Out

The native makearray: a bracketed two-column table, value then region, one row per region in order; LaTeX \left[\begin{array}{l|l} v & [a, b] \\ … \end{array}\right], Typst mat(delim: "[", augment: #1, v, [a, b]; …); the output indices as its subscript.

def tnameOK (n : String) : Bool

A template the call form can name: an identifier that is not a reserved operator name.

def bareOK (S : Sym) (n : String) : Bool

A bare \operatorname{n} is a template applied with no bindings, unless a template n with no parameters is in scope (that application prints \operatorname{n}()).

def nativeK (sf : Sf) (kvs : List (String × Json)) : Bool

The node has a native spelling the printer writes before the call form: a faq, a makearray, a constant array or a quantity.

def fieldsOK (fs : List (String × Json)) : Bool

Fields a node can carry: distinct keys, none of them op or args.

def callCond (c : Ctx) (o : String) (kvs : List (String × Json)) : Bool

The node with operator o prints in the call form (its field keys aside): the call form fits it (callFormOK ), o is a name \operatorname{…} holds, no template o is in scope, and it has no native spelling. The reader accepts the call form with fields only for such a node.

def pr (c : Ctx) (e : Json) : Out

The printer.

def pa (c : Ctx) (L : Nat) (e : Json) : List Tok

The tokens of an expression for a position needing level L.

The defining form of an equation

An equation whose right side is a faq with output indices, x = [body]_(s ∈ S), prints with the output indices on its left side and their ranges after its right side, x_s = body, s ∈ S (decided 2026-11-27): the usual way to write a family of equations. The right side is the reduction over the remaining ranges (∑_{k ∈ K} …, a faq with no output indices), or the body alone when the faq reduces nothing and carries nothing else. The reader takes a trailing , rows after a whole equation back to the faq (unlift ); the printer uses the form only when that gives back exactly the equation (liftOK ), and the bracket form otherwise.

def sortKVs : List (String × Json) → List (String × Json)

Sort bindings by key (insertion).

def isRedNode : Json → Bool

A faq node with no output indices.

def distinctNames : List String → Bool

No name occurs twice.

def defOutsOK (os : List Json) (rows : List (String × Json)) : Bool

The left side’s subscripts os and the ranges rows after the right side are those of a defining form: each subscript a name or 1 (outOK , as the bracket form’s entries, entryParts ), no name twice, and each row the range of one of the subscripts, at most once. A subscript with no row is an output index with no range, as in the bracket form.

def unlift (q : Json) (rows : List (String × Json)) : Option Json

The equation x_(os) = rhs with the ranges rows of its output indices, as the equation it writes: x = faq with the output indices os and the rows’ ranges, over rhs read as the reduction (a faq with no output indices that ranges over at least one index, none of them an output index) or as the body. Nothing else is a defining form: a reduction with no range of its own (sum v_j, limits(sum) v_j, sum_(j > 1) v_j) would read as reducing what it does not, and the printer writes the bracket form for it.

def liftParts (e : Json) : Option (Json × List (String × Json))

The parts of the defining form of an equation x = faq: the equation x_(os) = rhs and the ranges of the output indices, when the left side is a name that takes a subscript and the faq has output indices.

def liftOK (e q : Json) (rows : List (String × Json)) : Bool

The defining form is used: it reads back as exactly e.

def defRowsToks (c : Ctx) (rows : List (String × Json)) : List Tok

The range rows after a defining equation, separated by commas.

def print (sf : Sf) (S : Sym) (e : Json) : List Tok

The tokens of a whole expression: an equation x = faq with output indices in its defining form when that reads back, otherwise as any expression.

This module also proves 22 lemmas without doc comments; they are in the source.