SaTeX v0.2.7

The semantics SaTeX assumes

This document states what satex believes TeX, ε-TeX and LaTeX2e do. Every claim here is a claim about the engines, not about satex. Where satex deliberately departs from them, the departure is marked [abstraction] and justified. After why TeX is hard, this chapter says what TeX does. The abstract domains come next.

Sources: TeXbook (Knuth, The TeXbook, cited by chapter, since it has no numbered sections), tex.web (Knuth, TeX: The Program, cited by module number), TeX by Topic (Eijkhout), etex_man (the ε-TeX manual), clsguide and usrguide (LaTeX Project), expl3 (the interface documentation), texdimens (Burnol), and latex.ltx itself.


1. Processing model

TeX reads in three stages. The mouth turns characters into tokens, the gullet expands expandable tokens, and the stomach executes everything else. (TeXbook ch. 7, TeX by Topic ch. 1–2.)

satex implements the same three stages. It does not implement the fourth, typesetting: no boxes, glue setting or page builder. Everything that only affects typeset output is a no-operation.

A run starts in the interaction mode interaction: in satex.yaml names, as the engine's -interaction would set it (nonstopmode by default, as unattended builds run). In \batchmode and \nonstopmode a \read from the terminal is a fatal error that ends the job (tex.web § 484). LaTeX's prompt for a missing file (\@missingfileerror) is such a read.

SaTeX recovers the errors TeX itself raises the way tex.web does, never by widening: a \csname that meets an unexpandable token has its \endcsname inserted and the token read again (§ 373), an extra \endcsname, \else or \fi is ignored (§§ 510, 1135), a missing number is zero (§ 446), an argument that runs into a } gets \par inserted before the brace and the call ends in a runaway (§§ 395–396), and a runaway drops the call. Each is raised as the error TeX prints (raised-error, like \errmessage) and counted: the hundredth error in one paragraph ends the run, as it does in every TeX mode but errorstopmode (§ 82), and a paragraph's end clears the count (§ 1096).

\iftrue a\fi\fi   % the second \fi is ignored (§ 510)
\count1=a         % missing number: 0 is used, `a` is typeset (§ 446)

2. Category codes

Every character carries one of 16 category codes, and the code is fixed at the moment the character is tokenized, not when the token is used. (TeXbook ch. 7, tex.web § 232.)

3. The line reader

What one input character is depends on the engine. tex and pdftex are 8-bit. They read a file byte by byte, and a byte past 127 takes its category from the catcode table like any other character, 12 by default (tex.web § 232). A two-byte UTF-8 character is two character tokens there. xetex and luatex read UTF-8 characters instead. satex decides this once, from the settled engine, and every source its mouth reads is decoded that way. A column therefore counts bytes under an 8-bit engine and characters under a Unicode one.

A byte sequence that is no UTF-8 is read by xetex as one replacement character, U+FFFD, per sequence. luatex stops with "String contains an invalid utf-8 sequence". [abstraction] satex reads XeTeX's replacement character under both and records an invalid-utf8 gap for luatex.

TeX strips trailing spaces from each input line and appends the character \endlinechar (13 by default, category 5). If \endlinechar is outside 0–255 nothing is appended and the line yields no end-of-line token at all. The last line of a file is a line even without a final newline, and gets the \endlinechar like any other (tex.web § 31).

Reading then runs a three-state machine, new line N, skipping blanks S, middle of line M. With the appended character in category 5, state N yields \par, M a space, S nothing. In any other category it is read like any character of that category: in category 10 (after \catcode13=10, as \ProvidesFile does) it is a space token of character code 32 in state M and nothing in N or S. A comment character discards the rest of the line and moves to state N. State S is entered after any control word, including a one-letter one, and after a control symbol whose character has category 10 (the control space \ , or \~ under expl3), but after no other control symbol. (TeXbook ch. 8, tex.web § 303, §§ 343–354, § 240.)

\def\a{x}\a  y   % the blanks after \a are skipped (state S): xy
a
                  % a blank line is state N at its end: \par
b

A CRLF pair is one line ending, not two. [abstraction] TeX proper reads a file line by line and never sees the line terminator. satex reads a character stream and collapses CRLF so that files written on Windows tokenize as they would on any other platform.

4. Tokens and their equality

A token is either a control sequence or a (character, category code) pair. Two character tokens are equal when both components agree. Two control sequence tokens when their names agree. Source position is not part of a token. (TeXbook ch. 7.)

A category-10 character read from the input becomes a space token of character code 32 whatever the source character was. (tex.web § 348.)

5. Meanings

Every control sequence has a meaning: a primitive, a macro, a character (\chardef, or \let to a character token), a register, or undefined. \let\a\b copies the current meaning of \b into \a: the two are \ifx-equal until either is redefined. (TeXbook ch. 20.) A copy of a primitive is that primitive: \let\e\escapechar makes \e=-1 set \escapechar, \meaning\e prints \escapechar, and \ifx tells copies of two different primitives apart. (tex.web § 1221, § 507.)

\futurelet\a\b\c assigns the meaning of \c to \a and leaves both \b and \c in the input. (TeXbook ch. 20.)

6. Macro definition

\def⟨control sequence⟩⟨parameter text⟩{⟨replacement text⟩}.

7. Argument matching

A macro's parameter text is a pattern, and reading the arguments matches it against the input with no expansion. A delimited argument is a cut of the input: what lies before the delimiter at brace level 0. Over unknown text satex lists every cut that may begin the delimiter (scanDelim in the formal model).

8. The gullet

Expandable: macros, conditionals, \csname, \expandafter, \noexpand, \the, \number, \romannumeral, \string, \meaning, \jobname, \fontname, \input, \endinput, and the mark primitives \topmark, \firstmark, \botmark, \splitfirstmark, \splitbotmark. ε-TeX adds \detokenize, \unexpanded, \scantokens, \unless and \eTeXrevision, ε-TeX's mark classes \topmarks … \splitbotmarks expand too. pdfTeX adds \expanded and its own convert commands (\pdfstrcmp, \pdfescapestring, \pdffilesize, \pdfmdfivesum, \pdfcreationdate, \pdftexrevision, …). Everything else is executed by the stomach. (TeX by Topic, "Ordinary expansion", etex_man § 3.)

9. Conditionals

\if…⟨test⟩⟨true text⟩\else⟨false text⟩\fi. Conditionals are expanded in the gullet. The branch that is not taken is skipped without expansion, so a \def inside it does not happen. \ifcase⟨number⟩ selects among \or-separated cases and falls back to \else. (TeXbook ch. 20.)

While skipping, TeX recognizes conditionals, \or, \else and \fi by their meaning, not their name, so \let\myif\iftrue affects the nesting count and a \csname if…\endcsname does not. Braces are not tracked while skipping: grouping and conditional nesting are independent. (TeX by Topic, "Incorrect matching".) A file that ends while TeX is skipping ends the skip with an inserted \fi ("Incomplete \if…"). (tex.web § 336.)

\if and \ifcat expand until two unexpandable tokens remain. A control sequence or active character whose meaning is a character token (\let\bgroup={) counts as that character's code and category, so \ifcat\bgroup\egroup is false. Any other unexpandable control sequence counts as character code 256 for \if and category 16 for \ifcat, and those compare equal to each other. A token behind \noexpand is not expanded, and an active character there counts as itself. (tex.web § 506, TeX by Topic.)

A conditional is on the condition stack while its test is read. A conditional that the test itself starts and leaves open (\if e\ifx AB x\else y\fi …) sits above it: the next \else or \fi belongs to the inner one, and when the outer one skips its false text, the inner \fi it passes ends the inner conditional and an inner \else is passed over. (tex.web § 498, § 500.) The same holds for the skip of an \ifcase to the arm its number selected. A number built by conditionals that close only after the \ifcase (\ifcase\ifnum … 1 \else\ifnum … 2 \else 3 \fi\fi 0 …) is the usual shape, so the \fi the skip meets first is theirs and not the \ifcase's, and an \or of theirs counts for no case.

Decidable when the operands are known: \iftrue, \iffalse, \ifx, \ifdefined, \ifcsname, \if, \ifcat, \ifnum, \ifdim, \ifodd. Mode-dependent: \ifvmode, \ifhmode, \ifmmode, \ifinner follow the mode (tex.web §§ 211, 1045–1200). A run starts in vertical mode. horizontal material (a letter or other character, \char, a \chardef character, \unhbox, \vrule, \hskip and the \hfil family, \accent, \discretionary, \-, control space, \noboundary, \valign, $) starts a paragraph in a vertical mode, inserting \everypar and reading the token again. \indent and \noindent start one too and are consumed (tex.web § 1088, § 1090). \par ends it. Vertical material (\vskip, \hrule, \unvbox, \halign) in a paragraph first reads a \par token. In restricted horizontal mode it is an error instead (tex.web § 1095). \hbox, \vbox, \vtop, \vcenter, \insert, \vadjust, \noalign, the parts of \discretionary and \mathchoice, $, $$, \eqno and a { in math begin a list of their own in the mode that list has (with \everyhbox, \everyvbox, \everymath, \everydisplay), and its end restores the modes around it. \currentgrouptype reports the group code. [abstraction] The run keeps the set of modes it may be in: paths that disagree join to their union, a command of unknown meaning may start or end a paragraph, and a test is decided only when every mode in the set answers alike. Where the set matters to what a token does (a paragraph start with a non-empty \everypar, vertical material under a redefined \par), the run splits into one path per mode. Alignment cells and rows share one mode set (restricted horizontal or internal vertical), \left may make a display inner, and the output routine never runs. Box registers are tracked by kind (tex.web §§ 1077–1110): a register is void until \setbox fills it when its box ends (so the box's own text still sees the old contents), locally or with \global globally. \box and \unhbox/\unvbox empty it in place without a save-stack entry, \copy and the copy forms do not. \lastbox and \vsplit give an unknown box. \ifvoid, \ifhbox, \ifvbox are decided when the kind is known. \wd, \ht, \dp are 0 for a void box, the to size (or 0 across it) for a box that received nothing, what \wd⟨n⟩= set on a non-void box, and unknown otherwise (a box with material is typesetting). \ifeof follows the streams. \currentiftype and \currentifbranch follow the condition stack. \lastnodetype is -1 until anything may have been put on a list. (etex_man for \ifdefined, \ifcsname, \unless.)

[abstraction] When the test is not decidable, satex analyzes every arm and merges the resulting environments: a name defined in one arm becomes uncertain and carries a control dependency on the conditional. This is what makes satex controls able to say what a package option governs.

10. Grouping and the save stack

A group makes assignments temporary: the first local write to a name in a group saves the old entry, and the group's end puts it back. Two numbers decide a save: the level the entry was set at and the current level. Where satex knows neither exactly (a loop left groups open, a loop was summarized), it records that the name may have been saved, and the name is unknown at the group's end (touched in the formal model).

A group is opened by a begin-group character ({, catcode 1) and closed by an end-group character (}, catcode 2), including a control sequence whose meaning is such a character, as \bgroup and \egroup are in plain TeX (\let\bgroup={), by \begingroup…\endgroup, by a math shift ($…$ and $$…$$), by \left…\right, by a box constructor (\hbox, \vbox, \vtop, \vcenter), by an alignment entry, and by the output routine and inserts. Each records its kind on the save stack, and a closer of the wrong kind is an error: } ends every group but a \begingroup, $ or \left one, \endgroup only a \begingroup one.

\bgroup x\egroup        % plain TeX: \let\bgroup={ and \let\egroup=}
\begingroup x\endgroup
\begingroup x}          % error: only \endgroup closes a \begingroup group

(tex.web § 269 (the group codes, cur_group § 271), § 1063, § 1069, § 1085, § 1100, § 1145, The TeXbook, ch. 24.)

Every non-global assignment is undone when the group closes. \aftergroup⟨token⟩ keeps the token back and inserts it just after the group ends, in the order the \aftergroups were given. (tex.web § 326.)

\def\x{a}
{\def\x{b}\aftergroup\x}   % \x is restored first, so the inserted \x gives a

\aftergroup and \afterassignment are two commands, so a \let copy waits for what the command it copied waits for and not for what the copy's name suggests. expl3 reaches \aftergroup only through copies, as \tex_aftergroup:D and \group_insert_after:N. (tex.web § 265.)

\global sets the value at the outermost level. The save-stack entries already pushed for that name are not removed, they are discarded instead of restored when the group ends, which is why alternating local and global assignments to one name make the save stack grow. (tex.web § 279, § 283, TeX by Topic, "Save size".)

\def\x{0}
{\def\x{1}\gdef\x{2}\def\x{3}}   % \x is 2: the entry saved before \gdef is discarded

Some assignments ignore grouping entirely: \globaldefs forces every assignment global when positive and makes \global a no-op when negative, and \fontdimen, \hyphenchar, \skewchar, \hyphenation, \patterns, the box dimensions \ht/\dp/\wd and the special quantities \spacefactor, \prevdepth, \prevgraf, \deadcycles, \insertpenalties, the \page… dimensions and \interactionmode are always global. \font\x=… defines \x locally. (tex.web §§ 1242–1253, TeX by Topic, "Local and global assignments".)

\usepackage and \input do not open a group: a package would be unable to define anything if they did. \makeatletter around a package file is a category code change, which LaTeX undoes explicitly. (clsguide § 2.)

11. Base types

TeX's internal quantities are ⟨number⟩, ⟨dimen⟩, ⟨glue⟩, ⟨muglue⟩ and ⟨token list⟩. (TeXbook ch. 10, tex.web § 410.)

Fonts

12. The LaTeX2e layer

satex reads the installation's own latex.ltx, class and package files, so the kernel is not assumed and, apart from the temporary stubs of § 16, nothing about it is stubbed: \newcommand, \newenvironment, \NewDocumentCommand, \newcounter, \newlength, \newif, \DeclareOption, \ProcessOptions, \define@key and the rest run for real, the way the engine would run them. Every one of them ends in an ordinary primitive, \def, \let, a register allocation, which satex records as one kind of Definition fact (by names whichever command the file actually called, a user's own wrapper included) rather than a separate record type per LaTeX concept.

A definition's semantic tag is read off what running it left behind, never off the defining command's spelling:

Argument signatures are found the same structural way, including for \NewDocumentCommand: every command's signature is probed (§ 13) rather than read off a spec table, because \def, ltcmd/xparse's own expansion, and a package's own \@ifnextchar-style hand code all look the same from outside.

Labels, citations and the other keys a document declares through its auxiliary files are observed the same way. Every line a \write hands an opened file, expanded as \immediate expands it, or as shipout does with \protect acting as \noexpand, is run in a copy of the kernel state at \begin{document}, @ a letter, where the next run reads the .aux back. A key is text the document gave the writing call: characters whose tokens stand in the document's own file, never text found by searching the source. A name the line defines that is made of such a key is a key the writing call declares (\newlabel{k} defines \r@k, \bibcite{k} \b@k). A key the same call declares as another's extension (cleveref's k@cref) is that key with the extension as suffix. A name of that shape a body call reads is a use of the key, declared or not. A line that defines nothing but whose argument its own call reads in such a name (\cite{k} writes \citation{k} and tests \b@k) names the key for the program that reads the file: a citation, and the declarations of that shape are bibliography entries. A line written in another line's argument (\@writefile{toc}{\contentsline…}) goes onward to a list file. An entry whose level has a running head (\⟨level⟩mark) is a sectioning unit. What else is written names files. A name that resolves to a .bib database, or ends in .bib (a .bcf datasource), is a bibliography. Keys that never pass through a read-back file are declared the same way during the run: a name a call in the document's own files defines whose spelling embeds the content of one of the call's braced arguments (\newglossaryentry{k} defines \glo@k@name, \DeclareAcronym{k} its properties) declares key k, unless the call loaded a file of that name or read the key itself as a name. The first call to define names of a key declares it. A later one, and a read of a name of its shape by a call given that key, uses it. The keys a line carries for another program (\indexentry, \glossaryentry) are entries. No table of .aux commands is consulted.

Copied-not-run text keeps the expansion behavior of the definition it comes from: one whose real definition is \protected (the expl3 definition functions \cs_new:Npn, \cs_set_eq:NN, \cs_generate_variant:Nn, \prg_new_conditional:Npnn, \keys_define:nn, the ltcmd declarations, the lthooks setters) is copied, not run, by an \edef body, \expanded, \message and \write (etex_man § 3.4).

13. expl3

An expl3 function is \⟨module⟩_⟨description⟩:⟨signature⟩, or \__⟨module⟩_… when private. A variable is \⟨scope⟩_⟨module⟩_⟨description⟩_⟨type⟩ and has no colon. The signature gives the number of arguments: one per letter of N n c V v o x e f T F, and an empty signature means none. A signature containing p (a parameter text), w (unspecified) or D gives no reliable arity. (expl3 § 3.2.6, § 4.)

satex uses this rule to step over any expl3 function correctly, including ones it does not model.

Command signatures

The signature explain reports is not read off the names of the kernel's dispatchers or off a spec table (§ 12): every command, \NewDocumentCommand included, is run instead. A copy of the machine at the end of the run, or at \begin{document} for the preamble, reads the command followed by probe input and stops when the main loop takes a probe character itself, which the command then did not consume. Nothing it does is recorded. The probe input is ⟨p⟩, what is known to be taken so far, followed by {X}{X}…. n is how much of that the command consumes. The run also notes:

At ⟨p⟩, in order: a star is taken when ⟨p⟩*… consumes exactly n + 1 and is wanted to the same effect after it (or, where nothing was wanted, the starred form then wants a delimited argument: \@ifstar\a\b). A character c looked for is an optional argument ([P], n + 3), a flag (c, as ltcmd's t), an embellishment (c{X}, e) or the opening of a delimited argument (cP followed by the closing the run then wants, d/r: required when the call without it raises an error). None of these is taken when it is the very text the plain call was refused for (\def\a[#1]), or when a macro took it as text of a delimited argument (\def\a#1#{…}). Then a keyword tried before any quantity began there, with the quantity it takes, keywords taking the same being alternatives (to|spread). Then a quantity. Then required text or a delimited argument wanted right here, and a mandatory argument when n > 0. The default of an optional argument is shown when the macro argument that held P holds text of its own when the bracket is left out, and text no call can write (ltcmd's -NoValue-) is none. The probe is bounded in tokens and time. Past what it could decide the signature is unknown (…). Where it cannot say at all, a delimited parameter text is what the command reads.

The signature is written in one notation, xparse's where it has a letter: s, m, o, O{…}, t…, d/D/r/R, e{…}, u{…} for text up to a delimiter, required text as itself, [kw ⟨quantity⟩] for a keyword and ⟨quantity⟩ for a quantity. effective writes a call. An expl3 name's signature is only compared with this (expl3-signature-mismatch).

Meanings and their context

A name can mean different things at different places in a run beyond the preamble/document split (§ "Several definitions" in the wiki): \item outside any list raises the kernel's error, inside enumerate or itemize (both built on \trivlist) it typesets one.

\item a                               % "Lonely \item": the kernel's error
\begin{itemize}\item a\end{itemize}   % a list item

Every recorded definition carries the environment stack in force where it was made, \@currenvir generalized to however deeply the run had nested. The stack is tracked the same way as the document's boundary (§ 9's document_depth), read from the \begin/\end the run executes, never from a table of environment names. explain groups a name's definitions by that context: two made in different places with the same replacement text are one meaning, shown under every context that holds it. Two with different text are two.

A name never redefined can still differ by context when what it calls does: the error a real use in the run raised there (found the same way raised-error finds one, § lint) stands in for the meaning. Without a real use in that context, the meaning falls back to what probing the command turns up instead.

14. Where satex is not exact

The semantics above are followed exactly. Where a real run's answer cannot be known, satex over-approximates: it takes every outcome that the engine could take, so that nothing real is missed. It never picks one outcome to move on, and it never invents a meaning.

Three limits are incompleteness rather than over-approximation, because a sound analysis of them would not terminate. Neither is ever silent: each reports an imprecision diagnostic naming the construct and the limit it hit, and any finding that depends on such a point says so.

Termination does not rest on any of these. One guard sees every step: each token read, each pass of the path driver, each replay. It charges the steps to the source line being read, paired with the data line \read took last, over all paths. A line past limits.line_steps has the expansion above it cut and widened, and the line reads on after an unknown token. A second overrun skips the rest of the line (stalled-line-skipped). A third stops the run. So a run takes at most 3 × limits.line_steps steps per line read, whatever the input: unknown text of unknown length, fully unknown values, or a loop TeX itself would never leave.

Paths are bounded the same way, long before the steps are. The undecided choices each place makes (a conditional, a name of several meanings) are counted while one source line is read, over all paths and replays. Past limits.site_forks of them the expansion above the line is cut as the guard cuts it (site-forks-widened): what it assigned is unknown, and the line reads on after an unknown token. A choice inside a value scan is not counted: its arms join where the scan ends, and they may hold what ends the number. Every count and limit is in steps or choices, never in seconds, so the result does not depend on the machine. A drive whose paths were all dropped before the input ended (none of them a run of the document as followed, so an approximation on the way went wrong) does not end the run either: it reads on from the last path, as after a cut, with what that path assigned since the paths parted widened (analysis-ended-early, an imprecision). Lowering the precision limits when a share of limits.steps is spent (limits.degrade_at_percent) is an optional fallback, off by default.

satex query diagnostics lists every such point in a run, and satex lint --filter 'code=analysis-imprecision' groups them by reason.

15. Caches

A cache never changes an answer: a run that starts from one reports exactly what the run that wrote it did.

16. Stubs

SaTeX needs no stubs. It runs the real macros of the kernel and the packages. A stub is still available for a macro you want to model on purpose. stubs: in satex.yaml replaces the expansion of a named macro by an effect summary. Its arguments are read and recorded. Then a result is left (a box of unknown size, unknown digits, unknown text or nothing) and the names in sets become unknown. The result is typed: an element of the lattice of unknown text, the narrowest one that is sound for the macro.

A stub is sound exactly when its summary is. sets must list every name the macro assigns, and result must cover what it leaves. There are no stubs by default. Each use is reported as an assumption (stubbed), once per name and run. A stub applies only to the package's own definition. A document that redefines the name gets its own meaning back.