Architecture
How mathconv converts a formula: the math tree, the four-stage pipeline, the MathML reader, the rewrite rules and the writers.
This page and the others under internals are for contributors. They use the terms of Concepts.
Readers, writers and the math tree#
mathconv is built around a format-independent intermediate representation, the math tree, which describes the structure of a formula, such as "a fraction whose numerator is x".
- A reader takes one formula in its source format and produces a math tree.
- A writer takes a math tree and produces the formula in its target format.
A conversion pairs one reader with one writer. Because readers and writers communicate only through the math tree, any reader works with any writer.
The pipeline#
A conversion runs as a pipeline of four stages. Each stage consumes the output of the previous one and is independent of the others.
input string
│ 1. parse (reader)
▼
syntax tree
│ 2. lower (reader)
▼
math tree
│ 3. rewrite (shared by all conversions)
▼
math tree
│ 4. write (writer)
▼
output string
- Parse turns the input string into a syntax tree: the structure of the input in the terms of its own format, such as MathML elements and attributes.
- Lower turns the syntax tree into a math tree. It resolves every default of the format, so later stages never consult the source format.
- Rewrite normalises the math tree into a canonical form, so writers see one shape for each kind of formula.
- Write turns the math tree into the output in one fixed style, so equal trees give equal strings.
When the caller prefers carried TeX and the input has suitable carried TeX, the conversion returns it after parsing and skips the other stages.
Each stage records the fallbacks it makes. A reader also reports the display flag and any carried TeX it found. Its math tree is valid: every node has the children its kind requires, as listed below. A writer handles every kind of node.
Adding a source format means adding a reader, and adding a target format means adding a writer. Callers select formats by name, so no function signature changes. When a format needs something the math tree cannot express, the math tree itself changes: a node kind is reshaped or added, and every reader and writer is updated in the same change. Every writer always handles every node kind.
The math tree#
The math tree is a closed set of node kinds. A node has fields and an
ordered list of children; the meaning of each child comes from its
position. An empty row (a Row with no children) in a position
means "nothing here": a missing superscript, a missing root index.
| Kind | Fields | Children, by position |
|---|---|---|
Token | class, text, variant, operator properties | none |
Text | text, variant | none |
Row | any number of nodes | |
Fraction | line: normal or none | numerator, denominator |
Script | number of right pairs, number of left pairs | base, then each right pair (subscript, superscript), then each left pair |
UnderOver | accent below, accent above | base, below, above |
Root | radicand, index | |
Fence | stretchy | opening Token, content Row, closing Token |
Table | role, column alignments, lines, labelled | the rows in order: each its label, if labelled, then its cells |
Enclosure | set of notations | content |
Space | width | none |
Phantom | shown, kept dimensions | content |
Verbatim | notation, form, head, argument brackets | arguments, then the body of an environment |
Unknown | any number of nodes |
Tokenis one token. Its class is identifier (x), number (3.14), operator (+,(,∑) or function name. Its variant is the letter style. An operator carries its form and its operator properties.Textis ordinary text, such asif.Rowis a sequence of nodes placed left to right.Fractionhas line none when it is drawn without a line, as a binomial coefficient is.Scriptholds scripts in pairs of a subscript and a superscript; a missing script in a pair is an empty row.UnderOverholds what is set below and above its base. The accent flags say whether each is an accent.Roothas an empty index for a square root.Fenceis content between an opening and a closing delimiter, each aToken; a token with empty text means no delimiter on that side. Separators, such as commas, are tokens in the content.Tablehas the role matrix (a grid of entries) or equations (lines of a multi-line formula, aligned at their relations; the lowering of tables says when a table has the role). Its children are the cells in row-major order; the number of columns and each column's alignment and line come from the table's layout. Every row has one cell per column, so rows that are shorter in the source are padded with empty cells. Each cell is aRow, and an emptyRowis an empty cell. A labelled table has one more child before the cells of each row, the row's label, such as an equation number: aRow, empty for a row without one.Enclosureis content with MathMLmenclosenotations drawn around or across it, such as a box or a diagonal strike.Spacehas a width in eighteenths of an em, the unit in which LaTeX defines its spacing commands; an em is the font size. Negative widths are allowed.Phantomsets separately whether the content is shown and which of its width, height and depth take up space.Verbatimis reserved for readers of notations such as LaTeX. It keeps a command or environment as written: its head (the command or environment name) and the brackets around each argument, with the arguments themselves converted. No current reader produces it.Unknownis content that could not be converted. Its children are whatever could be lowered from inside it. Writers write it like a row; it keeps the fallback visible in the tree.
Storage#
The math tree is one array of 16-byte nodes in pre-order: each
node comes directly before its children, and its children before its
next sibling. Each node records the index just past its last
descendant, so the first child of node i is node i + 1, and the
next sibling of a child c is at the index recorded in c.
A node refers to its text by offset and length, into the input string or, for text that differs from the input (decoded entities, flattened text, added quotes), into one scratch buffer. Data too large for a node, such as the column alignments of a table, sits in a side array. All arrays and buffers belong to the workspace, which each conversion clears and reuses.
The layout is designed for throughput. The parser reads the input in one forward pass and recognises each element and attribute name once; text is never copied unless it changes; trees are walked by index; a reused workspace stops allocating once it has grown to fit the largest formula; every table is a static sorted array; and the writer appends to one output string.
The MathML reader#
Parse#
The MathML parser produces the MathML tree: the elements of the
first math element, with their names, attributes and text, stored
like the math tree. It is hand-written, works on the bytes of the
input, and finds the next < or & with a byte search. It reads XML
and HTML5 MathML and recovers from errors in real-world markup by these
rules:
- Names. A prefix such as
mml:is removed, names are compared case-insensitively, and namespace declarations are ignored. - Attributes. Values may be in double, single or no quotes. An attribute without a value has the empty value.
- Entities. Every HTML entity name and character reference is
replaced by its character. An undefined entity name is kept as
literal text, such as
&foo;, with the fallbackunknown-entity. - Closing tags. A closing tag closes the nearest open element with its name and every element opened inside it. A closing tag with no open element of its name is ignored. The end of the input closes every open element.
- Token elements. A token element holds only text. The opening tag
of any MathML element closes an open token element that already holds
text. A token element that holds nothing but whitespace when a MathML
element opens inside it is an
mrowinstead, so<mo><mover>…</mover></mo>and<mo><mspace/><mo>⟹</mo><mspace/></mo>, which some producers write around a layout element or around an operator with space, keep what is inside as children. Other markup inside a token element, such as an HTML<b>, adds its text to the token. - Everything else. Comments, processing instructions and
declarations are skipped. The text of a
CDATAsection is text. Anything before the firstmathelement or after its end is ignored.
Input with no math element ends the conversion here, with the
fallback no-math. Each further math element after the end of the
first is counted, and a count above zero is recorded as the fallback
extra-math once the conversion is done, with the count as its detail.
Carried TeX#
read/mathml/annotation.rs chooses the formula of a semantics
element and finds carried TeX, by the rules of
Semantics and annotations
and of prefer_carried_tex.
The parser looks for carried TeX only when the conversion prefers it,
and a conversion that takes carried TeX ends after parsing.
Lower#
Each MathML element maps to one math tree node, or is merged into its parent, according to this table:
| MathML | Math tree |
|---|---|
mi, mn, mo | Token |
mtext, ms | Text (an ms gets its quotes added) |
mspace | Space |
mrow, math, mstyle, mpadded, merror | Row |
mfrac | Fraction |
msqrt, mroot | Root |
msub, msup, msubsup, mmultiscripts | Script |
munder, mover, munderover | UnderOver |
mfenced | Fence around a Row with separator tokens |
menclose | Enclosure |
mtable, mtr, mtd | Table of Row cells |
mlabeledtr | like mtr, with its label cell as the label |
maligngroup, malignmark | nothing |
mphantom | Phantom, hidden, keeping all dimensions |
maction | the child it shows: the one selection counts from 1 for a toggle, else the first |
semantics | its formula, as Carried TeX describes |
mglyph | Unknown holding the alt text; code glyph |
| content markup | the nodes of its notation, as below |
| elementary math | Unknown; code elementary-math |
| any other element | Unknown; code unknown-element |
The reader converts every element of this table; elementary math,
mglyph, the content elements it does not convert and any other
element are the ones it keeps as an Unknown.
An Unknown node holds the children of its element, lowered by the
same table. Text directly inside the element, or directly inside a row
such as math or mrow, becomes one token per character: digits are
numbers, letters are identifiers, other characters are operators, and
whitespace is dropped. Only the outermost Unknown of a nested group
records a fallback.
Lowering also resolves what MathML leaves to defaults:
-
Variants. Each token gets an explicit variant. A one-letter identifier without
mathvariantis italic; a longer one is normal (upright). Amathvariantonmstyleapplies to the tokens inside that have none of their own. A styled Unicode letter in any token or in loose text becomes the plain letter with its variant: 𝐱 becomesxin bold. A token that mixes styled and other characters becomes a row of one node per run, so𝐱ybecomes a boldxand an italicy. -
Characters left out. Control characters other than tab, line feed and carriage return, and the invisible format characters, are left out of every token and of loose text, and each is recorded in the ledger. The invisible format characters are the format characters (Unicode general category Cf) that Unicode marks as default ignorable and that draw nothing, plus the combining grapheme joiner and the variation selectors: the soft hyphen U+00AD, the zero width space, non-joiner and joiner (U+200B to U+200D), the left-to-right and right-to-left marks and the other directional controls (U+200E, U+200F, U+061C, U+202A to U+202E, U+2066 to U+2069), the word joiner U+2060, the deprecated controls U+206A to U+206F, the byte order mark U+FEFF, the tag characters and a few more;
command-choices.txtlists them all. Producers such as LaTeXML write the zero width space where they mean an invisible product, so it is left out like the invisible times. A variation selector selects a form of the character before it, and the command of that character draws the form that authors type. The format characters that draw something stay: the Arabic number signs and the interlinear annotation anchors, for example. A token left with no text is an empty token: an empty operator is dropped like an invisible operator, so a sign that follows it is still prefix after a relation. Invisible operators are left out of the text of every token that holds other characters, and out ofmtextandms, where they mean nothing; a token that holds only invisible operators, such as anmowith function application, keeps them. Function application at the end of anmiormostays for the rule that recognises function names. -
Operators. Each operator token gets its form from its position or its
formattribute, and its properties from the operator dictionary, adjusted by thestretchy,largeop,movablelimits,fence,separatorandaccentattributes. When the dictionary lists the operator only in other forms, the entry of the first of infix, postfix and prefix that it lists applies. An operator the dictionary does not list gets the space of a relation, 5 eighteenths of an em on each side, in infix form and no space in prefix or postfix form. Anmocolon directly followed by anmoequals sign, or the equals sign by the colon, is one operator,:=or=:, which the dictionary lists as one relation; producers write the pair as two elements, which would be spaced as a colon and an equation.A sign is an operator that the dictionary lists in prefix and in infix form and not in postfix form:
+,-,±and∓. A sign between other items of a row is prefix when the item before it cannot end an operand, whatever the markup says about its position. Such an item is an operator that the dictionary lists in no postfix form: a relation, a binary operator, a comma, an opening bracket or another sign. An operator with limits or scripts, such as∑with its bounds, counts as the operator. Every other item can end an operand: identifiers, numbers, text, fences, closing brackets, an operator the dictionary lists in postfix form, such as!and′, and an operator it does not list, such as…. Invisible operators and spaces are skipped when looking for the item before the sign, because the rewrite stage drops the invisible operators. An explicitformattribute wins.The same holds for an operator that has no infix form to take, one that the dictionary does not list or lists only in prefix form, such as
Δ,∇or∂written in anmo: after an item that cannot end an operand it is prefix, soa = -∇bhas no relation spacing around∇.Row Form of the sign a = -bprefix, after a relation x → -∞,a × -bprefix, after a binary operator (a, -b),[-1, 1]prefix, after a comma or an opening bracket a - -bthe first infix, the second prefix ∑ᵢ -aᵢprefix, after a large operator with limits (a) - b,n! - 1,a - binfix, after an item that ends an operand a +last item of the row, as before One function of the math tree states the rule. Lowering applies it as each operator is read, and the rewrite stage applies it whenever the operators of a row are settled again, as when rows join or a fence is paired. Content markup writes its operators in infix form and settles them as each row closes, so
eq(a, minus(b))givesa = -b. -
Flat rows. Rows come out as the rule that flattens rows leaves them: a row that is an item of another row adds its items to that row, and a row in a fixed position that holds one node is that node. The operators of the joined rows take the forms their positions give them as that rule gives them, so a reader that lowers flat rows makes the rule change nothing.
-
Child counts. A layout element with too few children gets empty rows in the missing positions; extra children are placed in a row after the node. Both record
child-count. Whitespace and annotations between children are ignored, and any other text directly inside the element counts as one child, a row with one token per character. Anmsqrtaccepts any number of children, which form its radicand, so it never recordschild-count. -
Combining marks. A token ending in a combining accent, such as
xfollowed by U+0302, becomes anUnderOverwith the accent above. Up to four accents at the end of a token nest this way, the last one outermost; accents before those stay in the text of the base. -
Accents. An item set above a base is an accent when the
accentattribute ofmoverormunderoveristrue, or when it is an operator whose dictionary entry has the accent property, as^,¯and→have. The valuefalsedoes not remove the property: it tells a browser where to put the mark, and authors write it on marks that they mean as accents; the same holds for the attribute on themoitself.accentunderdecides the same for the item below. A one-charactermtextormiitem whose character has the accent property is read as that operator, so<mtext>→</mtext>and<mo>→</mo>over a base are the same accent. -
Space as an item. A space set below or above a base only widens it; it becomes an empty row. Space at either end of a base that is a row holding one operator, as in
<mrow><mspace/><mo>⟹</mo><mspace/></mrow>, only widens it too, so the base is the arrow; space around other content widens the mark over it and stays. Children beyond the base and its items that aremspaceor anmoof invisible operators only, as Temml writes afterargin\operatorname*{arg\,max}, are not operands and record nochild-count. This rule and the two above read the base and the items as flattening rows leaves them, so a row holding only an operator or a space counts as that operator or space. -
Scripts.
msub,msupandmsubsupbecome aScriptwith one right pair, and a missing script is an empty row. Inmmultiscripts, the pairs beforemprescriptsare right pairs and those after it left pairs, andnoneis an empty row. A script position with no child, such as the second script of an odd count, is an empty row, and anmmultiscriptswithout a base has an empty base; a secondmprescriptsis left out. Each recordschild-count. Anoneoutsidemmultiscriptsis an empty row, and anmprescriptsoutside it is unknown content. -
Fraction lines. A
linethicknessof zero, in any unit, gives a fraction without a line; any other value gives a normal line.bevelledis dropped: a bevelled fraction is a fraction. -
Space elements. An
mspacebecomes aSpaceof itswidth, 0 when it has none. A width is a number with a unit (em,ex,px,pt,pc,in,cm,mmorq) or a named width (thinmathspaceand the others up toveryverythickmathspace, each also with anegativeprefix). Units convert at 1 em = 16 px = 12 pt, 1 ex = 0.5 em and 1 in = 96 px, and a number without a unit is in em. The width is rounded to the nearest eighteenth of an em, with ties rounded toward zero. Any other length, such as a percentage, is 0. Alinebreakofnewlineorindentingnewlinemakes the space at least one quad wide, so that the parts it separates stay apart; every otherlinebreakvalue is dropped. -
Enclosures. An
menclosebecomes anEnclosureof the notations itsnotationattribute lists, defaulting tolongdiv. Unrecognised notation names are ignored. -
Quotes. An
msbecomesTextwithlquotebefore andrquoteafter its content, each defaulting to". -
Space characters. An
moormtextholding only space characters becomes aSpaceof their total width. The characters and their widths in eighteenths of an em are:Character Width Character Width U+0020 space, U+00A0 no-break space 6 U+2005 four-per-em space 4 U+2000 en quad, U+2002 en space, U+2007 figure space 9 U+2006 six-per-em space, U+2009 thin space, U+202F narrow no-break space 3 U+2001 em quad, U+2003 em space, U+3000 ideographic space 18 U+2008 punctuation space 5 U+2004 three-per-em space 6 U+200A hair space 1 U+205F medium mathematical space 4 The widths of the space and the no-break space are the interword space, a third of an em; the four-per-em space is the medium space that KaTeX writes for
\;. An invisible separator (U+2063) after the space characters makes the width negative, as KaTeX writes\!. Anmtextormskeeps one space at each end of its text and turns each run of whitespace inside it into one space; any other token drops the whitespace at its ends. ASpaceis at most 32 em wide in either direction; a wider one is cut to 32 em. -
Fences. An
mfencedbecomes aFenceof stretchy delimiters around a row of its children. Theopenandcloseattributes give the delimiters; whitespace around the value is removed, and an empty value means no delimiter on that side. When neither attribute is present the delimiters are(and). When one is present, the other side has no delimiter, because markup that gives one side only stands for\left\{…\right.and its mirror image, and a bracket the author never wrote would leave the formula unbalanced. The characters ofseparators, ignoring whitespace, separate successive children in turn, and the last one repeats for any remaining children; the default is,, and an empty value means no separators. A child that is an operator taking operands already separates them from its neighbours, so no separator is written beside it, whether the separator is the default or an explicit one. The operator dictionary decides. An operator listed in infix form, such as the+of<mfenced><mi>a</mi><mo>+</mo><mi>b</mi></mfenced>or the comma of<mfenced><mi>t</mi><mo>,</mo><mi>a</mi></mfenced>, takes the items on both sides, and so does a bracket or bar, and a name made of letters, such as<mo>sin</mo>. One listed in postfix but not infix form, like!, takes the item before it; one listed only in prefix form, like∀, the item after it. A child that the dictionary does not list and that holds no letter or digit, such as an ellipsis or∞, is an operand like an identifier and keeps its separators:<mfenced><mi>a</mi><mo>…</mo><mi>b</mi></mfenced>is(a, \dots, b). A separator character is used only where one is written, so the next gap takes the next character. A child that is a row beginning or ending with an operator is not an operator child and keeps its separators. Each delimiter and separator is a single token. -
Tables. The cells of a table are the
mtdelements of itsmtrandmlabeledtrrows. The first child of anmlabeledtris its label when another child follows it: the label is not a cell, and the table is labelled. With the optiondrop_labelsthe label is left out instead, and lowering records its characters astable-labels. A labelled row with one child shows that child. Malformed markup still produces a grid. Elements directly inside anmtablethat are not rows together form one row, in which eachmtdor other element is a cell. Likewise, an element other thanmtddirectly inside anmtrbecomes the content of one cell. A row outside a table becomes a table of that row, and anmtdoutside a table becomes a row. The column count is the length of the longest row, and shorter rows are padded with empty cells. A table with no cells is an empty row.A cell shows something when it holds text, or any element but the containers (
mrow,mstyle,mpadded,mphantom,mtd), the alignment elements and annotations, which show only what is inside them; a token without text, an operator that is invisible and whitespace show nothing. A column is blank when no cell of it shows anything.The alignment of a cell comes from the first of these that gives one: the
columnalignof themtd(its first word), a class of themtd(below), thecolumnalignof itsmtr(a list indexed by column), a class of themtr, and thecolumnalignof themtable(a list indexed by column). A list repeats its last entry for further columns, and an alignment other thanleftorrightis centred. A class gives an alignment when its name, split at-and_, ends inleft,rightorcenter(centre), or inl,rorcafteralignorcolumnalign; the wordborderbeforeleftorrightnames a border instead. The alignment of a column is the one that most of its cells that show something have, and centre when the leading alignments tie; the cells of a blank column count together.A blank column is padding and the table does not have it, unless it is an empty side of the lines. The columns of lines come in pairs of a left-hand side, aligned right, and a right-hand side, aligned left. A blank column in the place of a left-hand side is one when the column after it shows cells that all start with a relation, or is the only column that shows anything and is left-aligned. A blank column in the place of a right-hand side is one when the column after it shows something that does not start with a relation, the next left-hand side. Only a table of equations drops padding; in a matrix every column stays, as an empty column of a matrix may be deliberate. The
columnalignlist of the table, where a cell has no alignment of its own, applies to the columns that remain.A column whose cells that show something are each one relation and nothing else, between a column before it and one after it, is part of the cell after it. Lines written with the relation in a cell of their own, as
a | = | b, are the linesa & = b; the two cells are lowered as one row, and the table is then judged by the columns that remain. In a matrix every column stays as it is.In a table of equations without labelled rows, a last column whose cells that show something are each a number in parentheses, as
(1)and(2.3), holds the numbers of the lines. It leaves the columns, and each of its cells is the label of its row, as the label of anmlabeledtris. A labelled table whose columns are all padding keeps its first column, empty, beside the labels. A labelled table of equations with one row has one cell, holding the items of all the cells of the row, as the rewrite stage makes the cells of an unlabelled one the items of a row.A table has the role equations when it has
displaystyle="true"or labelled rows; or when it has at least two columns and its columns alternate right and left, the first, third and every odd column aligned right and the others left, whether the columns are counted as they stand or without their padding; or when its rows are lines of equations. Lines of equations are at least two rows that show something, such that- with one column, every row but the first has a relation at the top level of its cell, a relation being an operator whose dictionary entry spaces it as a relation on both sides;
- with an even number of columns, counted without padding, every cell that shows something in an even-numbered column starts with a relation, and some do.
Any other table is a matrix. The columns of lines of equations that alternate in no other way align right and left in turn where the markup centres them, which is what lines split at their relations are; a column the markup aligns keeps its alignment.
columnlinesgives the line after each column androwlinesthe line after each row, each as a list whose last entry repeats for any further columns or rows; any line other thansolidordashedis none. -
Dropped settings. Colours, sizes,
lspaceandrspace,mpaddeddimensions,scriptlevelanddisplaystyleof anything but a table are dropped; the line breaks that matter are themspaceones above. Of a table the settingsrowalign,align,frame,groupalign,side, spacing, widths and spans are dropped as well. -
Errors. An
merrorkeeps its content and recordserror-element. -
Depth. The arguments of content markup count three levels below their element, because lowering may set an argument in a fence inside a script of its operator's node. Elements nested deeper than 256 levels become one
Unknownholding their flattened text as one token per character, withdepth-limit. An element adds at most two levels to the math tree, so the tree stays below its own limit of 1,024 levels, which bounds the stack depth of every later stage. The parser keeps no element below that depth: the text of deeper markup joins the deepest element it keeps, and each closing tag of deeper markup is absorbed, so deep markup takes time in proportion to its length.
Content markup#
Content markup arrives in the same math element as presentation
markup, mixed with it in both directions: content inside a presentation
row or semantics, presentation tokens inside ci and cn. It
therefore belongs to the MathML reader, which parses both alike, as a
second lowering path chosen per element; the mathml source covers
both. Lowering writes content markup in the notation of hand-written
mathematics, out of the same node kinds as presentation markup:
Token, Row, Fraction, Script, UnderOver, Root, Fence,
Table, Space and Text. The rewrite rules and the writers see no
difference, and the rules of
LaTeX output style say which
notation each construct takes. The notation follows the default
renderings of the MathML 3 specification, chapter 4.
The operator table. Each operator and constant of content markup is
one row of the operator table in read/mathml/operators.rs, found by
the name of its empty element, such as <plus/>, or by the name of a
csymbol: the last part of its definitionURL, or else its text, such
as <csymbol cd="arith1">plus</csymbol>. A row gives the operator's
notation, its arity (the number of arguments it takes) and,
through the notation, its binding: how tightly the written
expression holds together. The notations are:
| Notation | Writes | Rows |
|---|---|---|
| constant | an identifier | pi, infinity, true, the number sets, the time of a model |
| infix | the symbol between the arguments, associative or strict, with a large form under bound variables | relations, plus, and, or, union, compose, rem |
| product | the factors side by side or between ⋅ | times |
| minus | a sign before one argument, a difference of more | minus |
| prefix, postfix | the symbol before or after the argument | not, factorial |
| function | a function name before its arguments, with limits below it | sin and the other elementary functions, ln, gcd, max, limit |
| fraction, power, root, exp, log | a Fraction, Script or Root | divide, power, root, exp, log |
| fenced | the arguments between delimiters | abs, floor, ceiling, card |
| mark, overline, selector | a fixed superscript, a line above, a subscript of indices | transpose, inverse, conjugate, selector |
| large operator | the symbol with its limits, then the body | sum, product, int |
| derivative | a fraction of differentials, or a prime | diff, partialdiff |
| quantifier | the symbol, the bound variables, a colon and the body | forall, exists |
| script, sequence, others | a subscript or superscript, arguments in turn | the subscripts and sequences of csymbol |
Adding an operator is adding a row. The constructors interval, set,
list, vector, matrix, piecewise and lambda, the tokens ci,
cn, csymbol and cs, and apply itself are content elements of
their own.
Bindings and parentheses. The bindings are ordered from the loosest
to the tightest: lambda, quantifier and sequence; implication;
disjunction; conjunction; relation; negation; set operation; sum; sign;
product; an operator that extends to the right, such as \sin x or a
large operator with its body; fraction and root; power and script;
atom. Each argument has a place: the loosest binding that stands
there without parentheses, whether it may begin with a sign, and what
follows it in a product. Lowering puts an argument in parentheses
exactly when its binding is looser than its place, so parentheses
appear where the reading requires them and nowhere else. A strict infix
operator, such as a relation, places its own binding in parentheses; an
associative one does not. A sign is allowed only where a term starts,
as first in a sum or a product, or after a relation.
Products. Before writing a product, lowering finds what each factor
starts and ends with: a letter, a name of several characters, a number,
a sign, a delimiter, a fraction, a command or a script. When any two
neighbours would run together side by side, every factor is separated
by ⋅; otherwise they stand side by side. Products inside a product are
its factors.
Applications. apply writes its head by the head's notation. An
operator character in a ci, such as →, is written as an accent over
one argument, before one argument, or between several; any other head
is a function applied to its arguments in parentheses, and a head that
is a large operator or a function name with scripts, such as
\int_0^1 or \sin^2, takes its arguments as a body. An and whose
later arguments each begin with share is a chain of relations that
share their middle terms, a = b = c.
Tokens. A ci is lowered as an mi, and a cn as an mn, so
they get the same variants, characters and accents; presentation markup
inside them is lowered as it stands. A cn with sep is a number in
e-notation, a rational number or a complex number by its type. A
csymbol that names a row is written as that row, and its own text is
left out; any other csymbol is written by its text.
Unconverted content. Nothing is dropped. A qualifier that its
operator does not take, a qualifier outside an apply, declare,
share, sep and cbytes out of place become Unknown with the code
content-markup; an operator with the wrong number of arguments writes
what it has and records child-count; cerror records
error-element and writes its arguments.
Rewrite#
The rewrite stage applies an ordered list of rules. A rule is a hook that a shared walker calls for nodes: it keeps the node, drops it, replaces its kind, unwraps it so that its children take its place, or makes it the opening delimiter of a new node that encloses the siblings up to a later one. The walker copies the tree into a second array of the workspace as the hooks decide, offering each node to the rules of a pass in their order, each rule seeing the kind the rules before it gave the node; the two arrays then swap roles. A dropped node leaves what its position requires: nothing in a row, a delimiter with empty text in a fence, an empty row anywhere else.
Consecutive rules that look only at the node they visit share one pass. A rule that reads the other items of a row, such as the siblings of the node it visits, runs in a pass of its own, so that it reads the items as the rules before it left them. Before the passes, one scan over the tree asks each rule whether it may change any node; a pass runs only when one of its rules may, and a tree that no rule changes is not copied. After a pass, the scan asks the rules after it again.
Most formulas need no rule, so the scan asks only the rules that could apply. The tree records its features as nodes are stored: a table, a phantom, a row below the root, an upright one-letter identifier, a token that may spell a function name, function application, an invisible operator, and an operator that is a bracket or a bar. Each rule names the features without which it changes nothing, and the scan asks a rule only when the tree has one of them; a tree with none is not scanned at all. The tree records the features itself, so every reader supplies them, and a token stored without its text counts as having every feature that a text can give. Builds with debug assertions, which the tests and the fuzz targets use, also ask every rule and check that no rule left out would have changed the tree.
A rule:
- is stated in terms of the math tree only;
- does one job, relying only on the rules before it;
- is idempotent: applied to its own output, it gives the same tree;
- produces a valid tree no deeper than 1,024 levels: the walker leaves siblings as they are where enclosing them would go deeper;
- records every token character it removes, so that tests can account for all input characters; the walker records the characters of every node a rule drops.
The rules run in this order:
-
Unwrap single-line tables. A table of one cell is replaced by its cell. A table of equations with one row is replaced by a row of its cells. Such tables only wrap a single equation or split one at its relation. Flattening then joins the cells, so the cells
a = band+ creada = b + c. A row of equations that is alone between two brackets, or inside a fence, is a row of a matrix and stays a table, and a labelled table stays a table, which keeps its labels. -
Drop empty phantoms. A phantom whose content is empty, as the hidden left-hand side that an equation line continues from, takes no space and is left out. The items after it take the forms their new positions give them. A phantom with content stays.
-
Flatten rows. A row inside a row is replaced by its children. A row with one child, in a place where any node may stand, is replaced by that child; the rows inside it are flattened first, so
<mrow><mrow/><mi>s</mi></mrow>as a subscript iss. The root, the content of a fence and the cells of a table stay rows, and a row of several items in a fixed position, such as the argument of a script or a fraction, stays a single child. Operators among the moved children get the form implied by their new position, as in lowering, unless aformattribute set it explicitly:<mi>a</mi><mrow><mo>-</mo><mi>b</mi></mrow>isa - b, as in the flat markup. -
Recognise function names. An upright identifier that spells a known function name, such as
sin, becomes a function name, except that a name that is also a unit, such asminin5 min, needs a sign of use: function application follows it, it is the base of a script or of an under and over construct, or an opening bracket or fence follows it, a script on an empty base follows it, or the identifierargprecedes it. Words of letters that space characters separate, as inarg max, are the known name that they spell without the spaces, if there is one; otherwise they are a function name when function application follows or they are the base of an under and over construct, and keep their spaces. Any other upright identifier of ASCII letters that function application (U+2061) follows, such assgnorE, becomes a function name too. A run of one-letter identifiers becomes one function name when the whole run spells a known function name and function application follows it, or, for upright letters, an opening bracket or fence follows it or the last letter is the base of a script, sos,i,nand U+2061 givesin, whilex,s,i,nand U+2061 stay four identifiers. Function application at the end of a token's own text, as in<mi>log</mi>, counts as following it and is removed there; a separate function application is left for the next rule. Anmotoken that holds only letters, as in<mo>max</mo>, is treated as an identifier. An identifier that is not upright, such as one in the italic or bold variant, is never a function name. -
Drop invisible operators. Tokens holding only invisible operators, and operators without text, are removed. This runs after function names are recognised, because recognition reads function application.
-
Pair fences. In a row, an opening bracket operator and the closing one after it become a
Fencearound the nodes between them. The brackets are(),[],{},⟨⟩,⌈⌉and⌊⌋. A closing bracket pairs with the nearest open one that it can close: the same kind, or, for round and square brackets, either of the two, so that the half-open intervals[a, b)and(a, b]pair. A closing bracket that cannot close the nearest open one, and an opening bracket that is never closed, stay as written, as does the reversed interval]a, b[. The fence stretches when both brackets do. The content of a fence is a row of its own, so its operators take the forms their positions in it give them, as in lowering, and the operators around the fence are settled again, since the fence is now one item of their row: ina + (-x)the-is a sign.An opening bracket that is never closed, and directly followed by a table, opens a fence around that table alone, with an empty closing side; a closing bracket that does not close anything and directly follows a table closes a fence around it with an empty opening side. Between an unpaired opening bracket and an unpaired closing one, the table is the content of one fence. A table of equations that is the whole content of a fence and holds one column of left-aligned lines becomes a matrix, which is written as an
arrayof one left-aligned column: the lines are set in the brackets as they are, with no empty left-hand side.The vertical bars
|and‖open and close with the same character, and the divides sign∣(U+2223), which several producers use for the bar of a ket, a bra or an absolute value, counts as|, so the bars of one kind in a row are first paired by counting. When the row holds an even number of them and pairing them in order, the first with the second, the third with the fourth, leaves every pair with content that is not empty, whose brackets pair among themselves, and that neither starts nor ends with an infix operator, the bars are paired that way, even where an opening bar follows an operand, as ina|x| + |y|. An infix operator here is one that the operator dictionary lists in no form that can start, or end, an item:-can start one as a sign,=cannot, and!can end one.Bars that do not pair by counting follow their place. A bar opens at the start of a row or after an operator other than a closing bracket. After anything else it closes the open bar of its own kind, when the nearest open delimiter is one, and otherwise stays a lone bar; a bar that opens and is never closed stays a lone bar too.
A lone bar between two items inside the braces of a fence, as in the set
{x | x > 0}, is in infix form, which the writers set apart as a bar between items. Any other lone bar is in postfix form after an item and in prefix form elsewhere, and the writers write it as a plain bar. A lone divides sign between two items is in infix form wherever it stands, since it is the relation there, as inP(A ∣ B); before an item with nothing to its left, or after one with nothing to its right, it is a bar like any other.
The writers#
The LaTeX writer walks the math tree once, appending to the output string, and looks up the command for each character in the symbol table. Its rules are in LaTeX output style.
The text writer writes readable plain Unicode text on one line,
such as x^2 + 1. Its rules are in Text output.
The engine interface#
The engine is the mathconv crate in crates/mathconv. It is not
published on crates.io; the Python binding, the WebAssembly binding of
the website and the project's own tools use it from the workspace.
A Converter is created from a Source and a Target, enums whose
variants carry each format's options, or by Converter::from_names
from format and option names, which both bindings and the test case
runner use. Its convert method takes the input &str and a
Workspace and returns a Conversion: the output, the display flag,
where the output was taken from, and the fallbacks.
A workspace owns the buffers a conversion uses, so reusing one workspace across conversions avoids repeated allocation. The conversion borrows its output from the workspace and is valid until the next conversion with that workspace.
The engine spawns no threads and has no mutable global state. Conversions can run on any thread, each with its own workspace. The Python binding keeps one workspace per thread.