Skip to content

compiler: thread the loaded packages into math parsing; \colon takes amsmath's definition when amsmath is loaded - #198

Merged
GoKubar merged 3 commits into
mainfrom
agent/kabir-claude/math-package-context
Sep 14, 2026
Merged

GoKubar merged 3 commits into
mainfrom
agent/kabir-claude/math-package-context

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Compiler half of the package-context lane, found by the \colon lane (#180). Sibling pipeline PR is independent, also based on main, no stacking.

The problem

math::parse_tokens took no package context, so every construct a package redefines silently got the LaTeX kernel's definition — the wrong one whenever the document actually loaded the package. \colon is the case that forced the change:

definition spacing
kernel (fontmath.ltx 400) \DeclareMathSymbol{\colon}{\mathpunct}{operators}{"3A} 0mu / 3mu
amsmath (amsmath.sty 409-410) \nobreak\mskip2mu\mathpunct{}\nonscript\mkern-\thinmuskip{:}\mskip6mu plus1mu\relax 2mu / 6mu

amsmath's empty punctuation atom contributes 3mu that the negative kern behind it cancels exactly, so what is left is an ordinary : with 2mu of glue before and 6mu after. Most documents that write \colon load amsmath.

Measured with TeX Live 2025 pdflatex at 10pt, control \hbox{$ab$} = 9.57755pt:

box no amsmath with amsmath delta
\hbox{$\colon$} 2.77779pt 7.22212pt +8mu
\hbox{$a\colon b$} 14.02196pt 16.79967pt +5mu
\hbox{$a\colon=b$} 24.57747pt 30.13289pt +10mu
\hbox{$a\colon+b$} 21.79976pt 29.0218pt +13mu
\hbox{$f\colon A\to B$} 41.55893pt 44.33664pt +5mu

The 10mu and 13mu rows are the class in evidence, not just the glue: the kernel's punctuation atom turns a following + into an Ord (TeXbook Ch. 17's Bin-after-Punct rule) where amsmath's ordinary one leaves it a Bin.

The three-atom model implemented here — space(2/18), a : forced Ord, space(6/18) — was checked against amsmath's own expansion inside one document, so font metrics cancel. Identical to the scaled point in all nine probes: text, display, \scriptstyle, \scriptscriptstyle, inside a superscript, at a formula boundary, before a relation, before a binary, and doubled.

The mechanism, and why this one

MathPackages is a Copy value carried by MathParser and passed to parse_tokens / parse_tokens_reporting_unclosed as a required parameter, so a caller cannot forget it and silently fall back to the kernel — which is precisely the bug class being fixed. parser::P folds it from \documentclass and each \usepackage into a math_packages field.

I looked at what the compiler already does before inventing anything. There were four existing mechanisms:

  1. self.packages.iter().any(..) membership on the parser struct (parser/tabular.rs:322, array_package) — works, but cannot carry package options, which the parser reads and drops in the same place.
  2. A typed field on P set at \usepackage time — P::colors, P::font_encoding. This is the shape adopted: it captures options naturally when the next lane needs them (amsmath's intlimits/nosumlimits/nonamelimits all change math geometry — see the audit).
  3. A thread-local global — siunitx's Settings. Deliberately not repeated: one process compiles many documents.
  4. Post-parse re-scanning of the raw source in the render pipeline (adapter.rs:785). Too late to reach parsing.

siunitx::typeset/Context take it too: Context::math re-parses synthesized unit formulas and is the one path into the math parser with no document in scope.

Which packages and classes carry amsmath's definitions in was measured, not assumed. Each name was compiled with pdflatex and \hbox{$a a\colon b b$} compared against the kernel expansion (23.5995pt) and the amsmath expansion (26.37721pt) in the same document:

  • Load amsmath: mathtools, empheq, physics, nccmath, aligned-overset, cool, commath, mismath, mhchem, chemformula; classes amsart, amsbook, amsproc, acmart, beamer.
  • Do not (so deliberately absent): amsthm, amssymb, amsfonts, amsopn, amsbsy, amscd, amstext, bm, unicode-math, siunitx, esint, breqn, cases, mathdots, thmtools, braket, cancel, tikz-cd, diagbox; classes article, report, book, memoir, scrartcl, scrbook, scrreprt, revtex4-2, elsarticle, IEEEtran, letter, proc, slides, amsdtx.

\colon was previously diagnosed \colon is not supported in math mode and typeset literally, so both definitions are new behaviour. It joins the supported-LaTeX inventory; generated artefacts regenerated.

math::AtomClass and MathAtom::class_override become public. The render pipeline re-derives the forced class by reading the control word back out of the source at the atom's span (typeset::class_override_of), which cannot tell \colon's two definitions apart — they are the same five characters. The sibling PR reads the field instead.

Relationship to #180

#180 implements the kernel \colon deliberately and says so; this PR supersedes that arm with both definitions. They touch the same command_atom match, so whichever lands first, the other rebases. #180's other content (\mathbb as a real msbm alphabet, the largesymbols operators, \neg) is untouched here.

Gates

gate base this branch
crates/compiler cargo test --release 444 passed / 0 failed (9abbf330, control worktree) 447 passed, 0 failed (3 new tests)
amsmath corpus 59/59 59/59
amssymb corpus 38/39 38/39 (32-braces-narrow, 1.012 bp, fails at the base too)
real-world corpus, 10 fixtures × 2 producers — 20/20 pairs identical: status, page counts and exact diagnostic message sets
HW1 / HW2 (render) 3 / 3 pages 3 / 3 pages, 0 errors, 0 overfull

All render gates ran with zero font diagnostics, asserted per fixture.

apps/mac/scripts/sync-supported-latex.sh --check reports bundled copy is current: the bundled inventory and crates/compiler/supported/supported-latex.json were byte-identical at the base, so the Mac copy was regenerated with the script in its own commit.

crates/compiler's --test robustness case deeply_nested_input_does_not_blow_the_stack overflows the stack in a debug build on this machine — identically at the base, in a separate control worktree. Release passes on both.

The render gates cannot see this change

crates/render-pipeline depends on flashtex-compiler = { path = "vendor/compiler" }, a pinned mirror, so nothing in crates/compiler reaches flashtex-render until that pin moves. The corpus numbers above are therefore unchanged by construction — crates/render-pipeline, crates/math-layout and crates/font-engine are byte-identical to the base on this branch.

To measure the real thing I did an uncommitted vendor swap (the four changed files over vendor/compiler/src/, the practice #180 documents) together with the sibling pipeline change. Through that full stack, \hbox{$X a\colon b X$} rendered by flashtex-render against pdflatex, as the X-to-X span minus one X advance (9.03553 bp):

formula pdflatex before after
a\colon b 23.0052 bp 26.8794 (+7mu) 23.0051
a\colon b + amsmath 25.7725 bp 31.3072 (+10mu) 25.7726
f\colon A\to B 50.4392 bp — 50.4392
f\colon A\to B + amsmath 53.2066 bp — 53.2067

The audit: what else we get wrong for the same reason

I swept amsmath, amsopn, amssymb/amsfonts, mathtools, bm/amsbsy and the kernel against pdflatex. Full measurements in the issue #2 comment. Summary of what is a live bug in this compiler today:

Tier 1 — one match arm or table row, once MathPackages exists

construct wrong by note
\pmod inline −10mu kernel \mkern18mu, amsmath \mkern8mu via \pod. We hardcode 18mu. Display is identical on both sides (both 18mu), confirmed.
\bmod 1mu each side we force Bin (4mu); both kernel and amsmath emit explicit \mkern5mu. Wrong regardless of package.
\angle, \hbar, \rightleftharpoons metrics the only three kernel symbols amssymb actually replaces (of 238 declarations; 12 more collisions are \not@base error stubs). \angle 6.37344 → 7.22223pt wide; \hbar 5.76172 → 5.4028pt. amssymb changes no kernel symbol's atom class — verified.
\,/\! in text 20sp at 10pt, 24sp at 12pt kernel .16667em, amsmath .1667em. We use the kernel's. (\:/\; are identical, and — contrary to the usual claim — are not math-only in the TL2025 kernel: latex.ltx:15669 already defines \tmspace.)

Tier 2 — needs parser state or lookahead

  • \dots context sensitivity. amsmath makes \dots centered (\cdots) before any of + = < > - * : or a \mathbin/\mathrel/\DOTSB macro, and low (\ldots) otherwise. We always emit low. Widths are identical between the two dot forms, so only the glyph identity and ht/dp reveal it — confirmed with \showbox across 24 contexts.
  • \dots/\cdots trailing \,. amsmath appends exactly +3mu before a right delimiter, $, or (for \cdots) , ; . — measured in 12 cases. We never append it.
  • amsmath options intlimits / nosumlimits / nonamelimits. All display-only, all large: \displaystyle\int_0^1 f 22.12503 → 17.6389pt under intlimits; \displaystyle\sum_0^1 f 22.08336 → 26.56949pt under nosumlimits; nonamelimits moves limits to scripts for every amsopn operator (\lim 13.88893 → 19.33226pt, and 13 more), not just \varlimsup. The pipeline reads only leqno/fleqn; reqno, tbtags, centertags, cmex10 and all six limits options are ignored everywhere.
  • mathtools \underbrace/\overbrace: dp 7.19997 → 6.3666pt (−1.5mu), ht 14.14441 → 13.31104pt. A genuine kernel-construct redefinition we implement with kernel geometry only.
  • \boldsymbol: amsbsy destroys an operator's Op class (0mu), bm preserves it (+6mu) — \boldsymbol{\sum} in context 20.13313 vs 23.91078pt. We implement neither; it is a no-op group.

Tier 3 — pipeline/vendor work

  • \big/\Big/\bigg/\Bigg sizing. Identical at 10pt by coincidence (kernel's \vbox to 8.5pt and amsmath's \vcenter to 12pt both demand a 12pt delimiter). Every other size diverges: at 12pt \big( is 4.5694 → 5.50003pt wide, 9.0 → 10.20006pt tall; at \fontsize{20} the kernel's fixed 11.5pt vbox cannot outgrow the font, so kernel \Big( collapses onto \big( while amsmath scales. crates/math-layout implements amsmath's \bBigg@ exactly and crates/compiler implements a third rule; neither knows about packages.
  • \usepackage{amsmath} silently changes the large-symbol font at script sizes (\cmex@opt default 7). \scriptstyle\sum_0^1 14.45842 → 12.30563pt; x^{\sum_0^1} 20.67369 → 18.5209pt. [cmex10] restores byte-identical kernel output. Affects every superscripted large operator in every amsmath document. Not modelled anywhere.
  • \overrightarrow/\overleftarrow: ht 6.97429 → 7.97429pt under amsmath.

Resume notes

  • Branch agent/kabir-claude/math-package-context, head c22937c0 (703cc445, a clean merge of origin/main 9abbf330, then the Mac inventory re-sync).
  • Sibling: agent/kabir-claude/math-class-override-pipeline, head c72e33fc.
  • Font environment on NixOS: the corpus oracles override both FLASHTEX_FONT_DIRS and FLASHTEX_TFM_DIRS with whatever --fonts is, so --fonts must itself be the colon-joined list — the OTF directory first, then apps/mac/Fonts/texmf/fonts/tfm/{public/lm,jknappen/ec,public/amsfonts/symbols}. --fonts apps/mac/Fonts alone, and a flat symlink-free copy of every .otf + .tfm, both produce required_metrics_unavailable and score 0/59 while still exiting "recovered". Assert zero font diagnostics before trusting any number.
  • To see this through the pipeline: check out the sibling branch, copy crates/compiler/src/{math,parser,siunitx,supported}.rs from this branch over crates/render-pipeline/vendor/compiler/src/, and build --features math-class-override. Do not commit the vendor swap.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

GoKubar and others added 2 commits September 13, 2026 15:19
…amsmath's definition when amsmath is loaded

`math::parse_tokens` took no package context, so every construct a
package redefines silently got the LaTeX kernel's definition -- the
wrong one whenever the document actually loaded the package. `\colon`
is the case that forced this: the kernel declares it punctuation
(`fontmath.ltx` 400, `\DeclareMathSymbol{\colon}{\mathpunct}{operators}
{"3A}`, 0mu/3mu) and amsmath renews it (`amsmath.sty` 409-410) to
`\nobreak\mskip2mu\mathpunct{}\nonscript\mkern-\thinmuskip{:}\mskip6mu
plus1mu\relax`, whose empty punctuation atom's 3mu is cancelled by the
negative kern behind it -- leaving an *ordinary* `:` with 2mu before
and 6mu after. Most documents that write `\colon` load amsmath.

Measured with TeX Live 2025 pdflatex at 10pt, control `\hbox{$ab$}` =
9.57755pt:

| box | no amsmath | with amsmath | delta |
| --- | ---: | ---: | ---: |
| `\hbox{$\colon$}` | 2.77779pt | 7.22212pt | +8mu |
| `\hbox{$a\colon b$}` | 14.02196pt | 16.79967pt | +5mu |
| `\hbox{$a\colon=b$}` | 24.57747pt | 30.13289pt | +10mu |
| `\hbox{$a\colon+b$}` | 21.79976pt | 29.0218pt | +13mu |
| `\hbox{$f\colon A\to B$}` | 41.55893pt | 44.33664pt | +5mu |

The 10mu and 13mu rows are the class in evidence, not just the glue:
the kernel's punctuation atom turns a following `+` into an Ord
(TeXbook Chapter 17's Bin-after-Punct rule) where amsmath's ordinary
one leaves it a Bin. The three-atom model this emits -- `space(2/18)`,
a `:` forced Ord, `space(6/18)` -- was checked against amsmath's own
expansion inside one document and is identical to the scaled point in
text, display, script and scriptscript style, and for `\colon` at a
formula boundary, before a relation, before a binary, and doubled.

## The mechanism

`MathPackages` is a `Copy` value carried by `MathParser` and passed to
`parse_tokens` / `parse_tokens_reporting_unclosed` as a required
parameter, so a caller cannot forget it and silently fall back to the
kernel. `parser::P` folds it from `\documentclass` and each
`\usepackage` name into a `math_packages` field -- the shape
`P::colors` and `P::font_encoding` already use, and the one that can
capture package *options* later, since the parser reads and drops them
in the same place. It is deliberately not a global: siunitx's
thread-local `Settings` is the mistake this does not repeat, and one
process compiles many documents. `siunitx::typeset`/`Context` take it
too, because `Context::math` re-parses synthesized unit formulas and is
the one path into the math parser with no document in scope.

Which packages and classes carry amsmath's definitions in was measured,
not assumed: each name was compiled with pdflatex and
`\hbox{$a a\colon b b$}` compared against the kernel expansion
(23.5995pt) and the amsmath expansion (26.37721pt) in the same
document, so font metrics cancel. Loading amsmath: `mathtools`,
`empheq`, `physics`, `nccmath`, `aligned-overset`, `cool`, `commath`,
`mismath`, `mhchem`, `chemformula`, and the `amsart`/`amsbook`/
`amsproc`/`acmart`/`beamer` classes. Measured as leaving the kernel's
alone, and so deliberately absent: `amsthm`, `amssymb`, `amsfonts`,
`amsopn`, `amsbsy`, `amscd`, `amstext`, `bm`, `unicode-math`,
`siunitx`, `esint`, `breqn`, `cases`, `mathdots`, `thmtools`, `braket`,
`cancel`, `tikz-cd`, `diagbox`, and the `article`/`report`/`book`/
`memoir`/`scrartcl`/`scrbook`/`scrreprt`/`revtex4-2`/`elsarticle`/
`IEEEtran`/`letter`/`proc`/`slides`/`amsdtx` classes.

`\colon` was previously diagnosed `\colon is not supported in math
mode` and typeset literally, so both definitions are new behaviour; it
joins the supported-LaTeX inventory and the generated artefacts are
regenerated.

`math::AtomClass` and `MathAtom::class_override` become public. The
render pipeline re-derives the forced class today by reading the
control word back out of the source at the atom's span
(`typeset::class_override_of`), which cannot tell `\colon`'s two
definitions apart -- they are the same five characters of source. The
sibling pipeline PR reads the field instead, behind its own feature.

## Gates

`cargo test --release` in `crates/compiler`: 444 passed, 0 failed,
against 441 passed / 0 failed at the same base (590fd86) in a separate
control worktree -- the 3 new tests, no other change. (`--test
robustness`'s `deeply_nested_input_does_not_blow_the_stack` overflows
in a *debug* build on this machine identically on both sides; release
passes on both.)

Real-world corpus (`tools/real-world-corpus/run.py --no-oracle`, this
checkout's binaries): 20 fixture/producer pairs, status, page counts
and exact diagnostic message sets identical to the control. hw1 and hw2
render 3 pages each, 0 errors, 0 overfull.

`crates/render-pipeline` vendors its own pinned copy of this crate
(`flashtex-compiler = { path = "vendor/compiler" }`), so nothing here
reaches `flashtex-render` until that pin moves; the render gates were
therefore also run through an *uncommitted* vendor swap, together with
the sibling pipeline change. amsmath corpus 59/59, amssymb 38/39
(`32-braces-narrow`, 1.012 bp, fails at this base too), both with zero
font diagnostics. Through that full stack `\hbox{$X a\colon b X$}`
renders within 0.0001 bp of pdflatex with and without amsmath.

Implementation-Agent: Claude Code engine-engineer (linux-primary, NixOS)
Commit-Executor: git via Claude Code
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
`apps/mac/scripts/sync-supported-latex.sh --check` and
`CompletionTests.testBundledInventoryMatchesTheCompiler` compare
`apps/mac/Sources/FlashTeXMac/Resources/supported-latex.json` against
`crates/compiler/supported/supported-latex.json` by sha256, so the
editor's completion vocabulary never drifts from the compiler. The two
were byte-identical at this branch's base (21eed5701677) and the
previous commit regenerated the compiler-side copy, so the bundled one
had to follow. Regenerated with the script, not by hand; the check now
reports `bundled copy is current (23d25a1ff459)`.

Implementation-Agent: Claude Code engine-engineer (linux-primary, NixOS)
Commit-Executor: git via Claude Code
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant