393 lines
19 KiB
Markdown
393 lines
19 KiB
Markdown
# Route D: complete implementation plan
|
||
|
||
Status: active plan. Baseline commit `4414f27`, 2026-10-23.
|
||
Owner: route-D core (`crates/texrra-tex-core`).
|
||
|
||
## 1. Objective
|
||
|
||
Build the typesetting engine the project actually needs:
|
||
|
||
- it **executes TeX/LaTeX the way TeX does** — macros, boxes, glue, penalties,
|
||
the page builder, the output routine — instead of mapping commands to an
|
||
approximated document model;
|
||
- its PDFs are **page-identical**, and with the matching fonts
|
||
**pixel-identical**, to pdfLaTeX/XeLaTeX over an explicit supported corpus;
|
||
- it stays **incremental in the Typst sense**: an edit replays from the nearest
|
||
page checkpoint and only the pages whose rendered content changed are
|
||
repainted;
|
||
- it is the **default engine** of the texrra web service, with the v1 semantic
|
||
pipeline kept as a fallback until the route-D corpus passes.
|
||
|
||
Explicit non-goals for the first complete release:
|
||
|
||
- LuaTeX callbacks, `\directlua`, OpenType feature selection, microtype font
|
||
expansion/protrusion;
|
||
- every CTAN package. The supported corpus is listed in section 9;
|
||
- byte-identical PDF object layout. Equality is measured on pages, text
|
||
positions and pixels, not on the PDF file bytes.
|
||
|
||
## 2. Baseline (what exists today)
|
||
|
||
`crates/texrra-tex-core` is about 9.1k lines across:
|
||
|
||
| module | responsibility |
|
||
| --- | --- |
|
||
| `lib.rs` | vertical items, page builder, checkpoints, edit replay, floats, insertions |
|
||
| `paragraph.rs` | horizontal items, Knuth–Plass break, hyphenation, justification |
|
||
| `math.rs` | math atom model, TeX-ish layout and spacing |
|
||
| `render.rs` | display list (text/rule/line/image/link/special), SVG |
|
||
| `pdf.rs` | multi-page PDF, Type0 CID fonts, XObjects, annotations |
|
||
| `tfm.rs`, `cmr10.rs` | TFM parsing, per-face Computer Modern metrics |
|
||
| `subset.rs` | per-document TrueType glyph subsetting |
|
||
|
||
Working and covered by tests: page hashes and checkpoint replay, CMR10 metrics
|
||
(width/height/depth/kern/ligature/italic correction), hyphenation, justification,
|
||
per-face TFMs, Type0 embedded faces, image XObjects, URI annotations, specials,
|
||
floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
|
||
`\bottomfraction`, `\textfraction`, `\floatpagefraction`, `\topnumber`,
|
||
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
|
||
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
|
||
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
|
||
PDF opt-in with `?engine=route-d`). 301 workspace tests are green and no oracle
|
||
fixture is ignored.
|
||
|
||
Known gaps, in dependency order:
|
||
|
||
1. paragraph breaking reproduces TeX's passes and demerits (including
|
||
`\adjdemerits`, `\doublehyphendemerits`, `\finalhyphendemerits`,
|
||
`\hyphenpenalty`, `\exhyphenpenalty`, `\hyphenation` exceptions,
|
||
`\hangindent`/`\hangafter`/`\parshape` line geometry, `\parfillskip`
|
||
with or without `fil`, default `\sfcode` sentence spacing,
|
||
`\looseness`, and `\baselineskip`/`\lineskip`/`\parskip` interline
|
||
glue), but not yet custom `\sfcode` overrides, generic `fil`/`fill` glue
|
||
orders or `\prevgraf`;
|
||
2. the page builder is a scrolling builder with fraction policies, not a TeX
|
||
page builder with badness and an interpreted `\output`;
|
||
3. `\insert` classes are data structures, not TeX registers and an output
|
||
routine;
|
||
4. `\halign` handles spans/omit/templates but not the full TeX column algorithm;
|
||
5. math is a compact subset without the CM math fonts (`cmmi`, `cmsy`, `cmex`),
|
||
display-math line breaking or `\mathchoice`-level styling;
|
||
6. text fonts are Liberation, not Computer Modern; Type1 fonts are not embeddable
|
||
yet, so pixel comparison against pdfLaTeX is impossible;
|
||
7. class files (`article.cls`, `sn-jnl.cls`) are mapped semantically, never
|
||
executed;
|
||
8. the service integration is opt-in and maps only a small LaTeX subset.
|
||
|
||
Host tooling available: `pdflatex`, `xelatex`, `lualatex`, `pdftoppm`,
|
||
`pdftotext`, `kpsewhich`, `fonttools`/`ttx`.
|
||
|
||
## 3. Target architecture
|
||
|
||
```
|
||
LaTeX source
|
||
-> tex-vm tokenizer + catcodes + macro expansion + save stack +
|
||
registers + conditionals + \output program
|
||
-> typeset horizontal / vertical / math lists
|
||
paragraph builder, page builder, insertion + float machinery
|
||
-> fonts TFM, Type1/TrueType embedding, NFSS state
|
||
-> layout display list (text, rules, images, links), page hashes,
|
||
checkpoints
|
||
-> service preview diff, PDF export, sessions, error mapping
|
||
```
|
||
|
||
Invariants:
|
||
|
||
1. **One layout truth.** Preview SVG and PDF are rendered from the same display
|
||
list, so they cannot diverge.
|
||
2. **Page hash = rendered content only.** Source metadata never changes a hash.
|
||
3. **No template special cases.** Every layout decision comes from TeX rules or
|
||
a documented engine policy; if a class needs new behavior, the engine gains a
|
||
general primitive.
|
||
4. **Incremental by construction.** Every top-level unit has a stable id and a
|
||
checkpoint before it; replay is the default path, full layout the fallback.
|
||
|
||
## 4. Fidelity ladder
|
||
|
||
| level | meaning |
|
||
| --- | --- |
|
||
| L0 | semantic mapping (today's v1 engine) |
|
||
| L1 | TeX list semantics: boxes/glue/penalties/output honored, break points may differ |
|
||
| L2 | TeX-identical measurements: same break points, same box metrics, same page count |
|
||
| L3 | pixel/byte identical: same outlines and sub-point positions |
|
||
|
||
Phase targets: P1–P3 reach **L2**; P4–P5 reach **L3** for text and math; P6
|
||
reaches **L2** for class files.
|
||
|
||
## 5. Phases
|
||
|
||
### P0 — TeX oracle harness (foundation)
|
||
|
||
Deliverables:
|
||
|
||
- `tests/oracle.rs` plus helpers: compile a fixture with `pdflatex`, extract
|
||
`pdftotext -bbox` word boxes, rasterize with `pdftoppm`, compare page count,
|
||
text lines, word boxes and ink bands against route-D output;
|
||
- fixture format: a `.tex` snippet plus a small JSON expectation (page size,
|
||
page count, per-line words, tolerance);
|
||
- skips cleanly when TeX tools are unavailable, and records why;
|
||
- a `--regen`-style path for refreshing goldens.
|
||
|
||
Status: the foundation landed in `crates/texrra-tex-core/tests/oracle.rs`. The
|
||
150pt CMR10 fixture matches pdfLaTeX word for word (x tolerance 0.05pt) and
|
||
exercises the overfull fallback; the 180pt fixture exercises the ordinary
|
||
pass-1 solution and matches as well. The ink-band test runs on the same
|
||
oracle-verified paragraph.
|
||
|
||
Acceptance: at least 20 paragraph fixtures and 5 page fixtures wired into
|
||
`cargo test`, harness green.
|
||
|
||
### P1 — Paragraphs exactly like TeX (L2)
|
||
|
||
Scope:
|
||
|
||
- demerits: line penalty, badness², penalty², flagged demerits (hyphenated,
|
||
adjacent fitness), `\doublehyphendemerits`, `\finalhyphendemerits`,
|
||
`\adjdemerits`, `\linepenalty`, `\tolerance`, `\pretolerance`,
|
||
`\emergencystretch`;
|
||
- breakpoints: glue, explicit penalty, discretionary with pre/post/replace;
|
||
- glue setting: normal/fil/fill/filll orders, `\parfillskip`, `\leftskip`,
|
||
`\rightskip`, `\spaceskip`, `\xspaceskip`, `\parindent`, `\hangindent`,
|
||
`\hangafter`, `\parshape`, `\looseness`;
|
||
- vertical list entry: `\baselineskip`, `\lineskip`, `\lineskiplimit`,
|
||
`\parskip`, `\prevgraf`;
|
||
- spaces: `\spacefactor`, `\sfcode`, `\frenchspacing`, `\nonfrenchspacing`,
|
||
`\@` sentence spacing;
|
||
- hyphenation: patterns, `\hyphenation` exceptions, `\lefthyphenmin`,
|
||
`\righthyphenmin`, `\hyphenpenalty`, `\exhyphenpenalty`.
|
||
|
||
Acceptance: 30 fixtures covering widths, indents, hyphenation, overfull and
|
||
underfull lines; line break positions and overfull boxes identical to
|
||
pdfLaTeX.
|
||
|
||
Status (P0 committed, P1 in progress): the oracle harness found and fixed
|
||
four real defects: the TFM lig/kern reader kept the last instruction for a
|
||
shared key (`k` + `a` picked up `w`'s kern), justification squeezed overfull
|
||
lines past their declared shrink while clamping legal stretch, the vendored
|
||
plain-TeX hyphenation patterns disagreed with pdfLaTeX (`kappa`, `lambda`),
|
||
and the final-pass fallback did not model TeX's artificial demerits. The
|
||
breaker now uses TeX Live's `hyph-en-us` patterns and exceptions with
|
||
`\lefthyphenmin=2`/`\righthyphenmin=3`, stretches normal glue past its
|
||
nominal stretch while clamping shrink at the declared limit, and falls back to
|
||
the longest prefix within `\tolerance` or the first overflowing prefix. The
|
||
oracle compares 100, 120, 150, 180, 200 and 240pt and all six match pdfLaTeX
|
||
word for word within 0.05pt; the narrow measures exercise hyphenated and
|
||
overfull breaks. Register fixtures pin `\pretolerance=10000` (pass 0 stops
|
||
before hyphenation) and `\hyphenpenalty=10000` (hyphenation illegal, first-fit
|
||
overfull lines).
|
||
|
||
Flagged demerits are now modelled too: the DP state records whether a line
|
||
ended in a discretionary break, so `\adjdemerits`, `\doublehyphendemerits`
|
||
and `\finalhyphendemerits` all affect the chosen solution, and
|
||
`\hyphenation` exceptions are inserted into the pattern trie (unit-tested by
|
||
counting the discretionary points they add).
|
||
|
||
`\hangindent`/`\hangafter` and `\parshape` now drive each line's measure
|
||
and left offset; the DP remembers a candidate's line number so the geometry can
|
||
vary per line, and a 120pt oracle fixture checks every line origin against
|
||
pdfLaTeX.
|
||
|
||
`\parfillskip` is modelled: with the default `0pt plus 1fil` the last line is
|
||
left short, and a finite/zero `\parfillskip` makes the final line justify like
|
||
any other; a 120pt `\parfillskip=0pt` oracle fixture confirms pdfLaTeX's
|
||
rebalancing of the preceding lines.
|
||
|
||
Sentence spacing is modelled with TeX's `\nonfrenchspacing` defaults:
|
||
stretch is multiplied and shrink divided by the space factor, `\fontdimen7`
|
||
is added from 2000, and `\frenchspacing` switches it off; a 150pt punctuated
|
||
oracle fixture matches pdfLaTeX's line breaks and word positions.
|
||
|
||
`\looseness` adjusts the final line count inside TeX's `[1,9]` window and is
|
||
reverted when no feasible layout exists; 120pt and 200pt fixtures require one
|
||
extra line and match pdfLaTeX exactly.
|
||
|
||
Interline spacing follows TeX: the first baseline sits at the paragraph's
|
||
ascent, each later baseline advances by `\baselineskip` when the resulting gap
|
||
clears `\lineskiplimit`, otherwise by `\lineskip`, and `\parskip` (default
|
||
`0pt`) separates paragraph units in the vertical list. Page-level `\topskip`
|
||
placement remains part of P2, and a paragraph still reserves a whole number of
|
||
line boxes for pagination.
|
||
|
||
Still open: generic `fil`/`fill` glue orders, custom `\sfcode` overrides,
|
||
`\prevgraf`, explicit `\vskip` classes (`\smallskip` and friends), page-level
|
||
`\topskip` placement, double/final hyphen demerit oracle fixtures, and more
|
||
width fixtures.
|
||
|
||
### P2 — Vertical list, page builder, `\output` (L2)
|
||
|
||
Scope:
|
||
|
||
- glue setting in vertical lists (ragged/flush bottom), `\vsize`, `\voffset`,
|
||
`\topskip`, `\maxdepth`, `\splittopskip`, `\splitmaxdepth`;
|
||
- TeX page builder: candidate breakpoints, cost = badness + penalty, page goal
|
||
recomputation as insertions arrive, `\pagegoal`, `\pagetotal`,
|
||
`\pagestretch`, `\pagefilstretch`, `\pagefillstretch`, `\pagefilllstretch`,
|
||
`\pageshrink`, `\pagedepth`;
|
||
- marks: `\mark`, `\botmark`, `\firstmark`, `\topmark`, `\marks`;
|
||
- insertions: `\insert` with `\count`, `\dimen`, `\skip` per class, split
|
||
insertions, held-over material, `\footins` defaults;
|
||
- output: `\output` as an interpreted token list, `\box255`, `\shipout`,
|
||
`\outputpenalty`, `\deadcycles`, page display list assembly;
|
||
- floats: TeX-compatible policy module used by the default output routine
|
||
(top/bottom fractions and counts already exist).
|
||
|
||
Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks);
|
||
page counts identical and first/last baselines within 1pt of pdfLaTeX.
|
||
|
||
### P3 — `\halign` / `\valign` (L2)
|
||
|
||
Scope: preamble templates and `#` parameters, `\tabskip`, `\omit`, `\span`,
|
||
`\multispan`, `\noalign` material, column widths from every row, multiline
|
||
cells, `\hfil`/`\hfill` in templates, rules.
|
||
|
||
Acceptance: 8 table fixtures; column x positions and rule extents within 0.2pt.
|
||
|
||
### P4 — Math engine (L3)
|
||
|
||
Scope:
|
||
|
||
- TeXbook Appendix G math list: styles D/T/S/SS and their size parameters,
|
||
atom classes with the full spacing table, `\mathchoice`, `\over`/`\atop`/
|
||
`\above`/`\choose`, fractions, radicals, `\left`/`\right`/`\middle` with
|
||
delimiter size variants, operators and limits, accents, `\mkern`/`\mskip`,
|
||
`\mathsurround`, `\mathord`-family wrappers;
|
||
- matrices and alignment: `matrix`, `pmatrix`, `cases`, `eqalign`, `aligned`;
|
||
- display math: `\displaywidth`, `\displayindent`, `\predisplaysize`,
|
||
equation numbers, display line breaking;
|
||
- math fonts: `cmmi10`, `cmsy10`, `cmex10`, `msam`/`msbm` subsets, including
|
||
extension glyphs for growing delimiters and radicals.
|
||
|
||
Acceptance: 25 formula fixtures; glyph boxes within 0.3pt of pdfLaTeX and
|
||
delimiter size classes identical.
|
||
|
||
### P5 — Fonts and NFSS (L3)
|
||
|
||
Scope:
|
||
|
||
- TFM loading for `cmr`, `cmbx`, `cmti`, `cmtt`, `cmss`, `cmmi`, `cmsy`,
|
||
`cmex` and the Latin Modern equivalents;
|
||
- Type1 embedding (`FontFile`) with encodings, then Type1 subsetting; keep the
|
||
TrueType path for Liberation/Mono;
|
||
- NFSS: family/series/shape/size, `\fontsize`, `\baselineskip`,
|
||
`\selectfont`, `\rmfamily`/`\sffamily`/`\ttfamily`/`\bfseries`/`\itshape`,
|
||
`\DeclareFontShape` resolved to the nearest available shape;
|
||
- metric parity: fontdimen, italic correction, kerning, ligatures, `\fontdimen`
|
||
parameters exposed to the paragraph builder.
|
||
|
||
Acceptance: embedded CM fonts reported by `pdffonts`; text extraction exact;
|
||
pixel difference against pdfLaTeX ≤0.5% at 150dpi for text-only fixtures.
|
||
|
||
### P6 — LaTeX class execution (L2)
|
||
|
||
Scope:
|
||
|
||
- `tex-vm`: catcodes, `\edef`, `\csname`, `\expandafter`, `\futurelet`,
|
||
`\afterassignment`, `\let`, `\chardef`, `\mathchardef`, grouping and save
|
||
stack, counters/lengths/boxes/toks, all `\if` forms;
|
||
- layout primitives: `\hbox`, `\vbox`, `\vtop`, `\vsplit`, `\halign`,
|
||
`\hskip`, `\kern`, `\penalty`, `\mark`, `\insert`, `\output`, `\shipout`,
|
||
`\special`, `\lastbox`, `\unhbox`, `\unvbox`, `\raise`, `\lower`,
|
||
`\moveleft`, `\moveright`;
|
||
- LaTeX list/environment layer: `\list`, `\trivlist`, `\@item`,
|
||
`\@startsection`, `\@makecaption`, `\@float`, `\caption`, `\footnote`,
|
||
`\thanks`, default `\maketitle`;
|
||
- run real class files from TeX Live: `article.cls` first, then a two-column
|
||
journal class (`sn-jnl.cls`).
|
||
|
||
Acceptance: `article.cls` at 10/11/12pt matches pdfLaTeX page count exactly;
|
||
the journal class matches page count within one page and column geometry within
|
||
1mm.
|
||
|
||
### P7 — Service and incrementality
|
||
|
||
Scope:
|
||
|
||
- route-D becomes the default engine for project preview and PDF, v1 stays
|
||
behind a flag;
|
||
- incremental snapshots include VM state at page boundaries (persistent maps),
|
||
dependency edges for `\label`/`\ref`/`\cite`/TOC, conservative invalidation
|
||
when floats or insertions move material backwards;
|
||
- performance targets: a one-paragraph edit of a 10-page document < 100ms;
|
||
full layout of 50 pages < 500ms; page diff payload proportional to changed
|
||
pages;
|
||
- error reporting with file:line and TeX-style messages.
|
||
|
||
Acceptance: e2e preview/edit/PDF tests, benchmark script, documented latency.
|
||
|
||
### P8 — Corpus, CI, documentation
|
||
|
||
Scope: corpus of 20 documents (article, amsmath, tables, floats, journal),
|
||
known-diff registry with reasons, CI script that runs fmt/test/build plus the
|
||
oracle suite, README/docs update.
|
||
|
||
Acceptance: corpus green or explicitly listed; CI documented.
|
||
|
||
## 6. Testing strategy
|
||
|
||
1. **Oracle comparisons** against pdfLaTeX at four levels: page count, extracted
|
||
text, word/line boxes, raster ink. Every phase adds fixtures.
|
||
2. **Golden display lists** for renderer/PDF regressions that TeX cannot express.
|
||
3. **Property tests**: random edits must produce the same pages as a full
|
||
layout; page hashes must be content-only.
|
||
4. **Benchmarks**: paragraph layout, page assembly, checkpoint replay, PDF
|
||
export. Stored as `cargo bench` or a small bench example with thresholds.
|
||
5. **Unit tests** for every new primitive, with TeXbook-derived expectations.
|
||
|
||
## 7. Incremental design
|
||
|
||
- Snapshot = immutable `Arc`-shared VM state + page builder state at a page
|
||
boundary. Macro tables and registers use persistent maps so snapshot cost is
|
||
O(1) and replay does not copy the world.
|
||
- Dependency graph: `\label`/`\ref`, counters, TOC entries and citations create
|
||
edges from the defining unit to the consuming pages; an edit invalidates from
|
||
the earliest affected checkpoint. Floats/insertions may pull material to
|
||
earlier pages, so their queues are part of the checkpoint and can force a
|
||
conservative replay from the page that owns the queue.
|
||
- Page identity is the content hash; unchanged prefixes are reused verbatim.
|
||
- Any change to the preamble, class files, global registers or fonts falls back
|
||
to a full layout.
|
||
|
||
## 8. Risks and mitigations
|
||
|
||
| risk | mitigation |
|
||
| --- | --- |
|
||
| class execution is effectively a TeX VM | stage it: lists/boxes/glue first, then macros, then classes; keep semantic fallback per class |
|
||
| math layout is the deepest subsystem | implement Appendix G incrementally, fixture by fixture, with CMEX fonts early |
|
||
| Type1 subsetting complexity | start with full Type1 embedding (valid PDF), subset later |
|
||
| incremental + TeX global state | persistent snapshot structures, conservative invalidation, property tests |
|
||
| oracle tests depend on host TeX | skip with a recorded reason; CI image pins TeX Live |
|
||
| scope creep from individual templates | corpus-driven: a template enters the corpus only with an oracle fixture and a general primitive |
|
||
|
||
## 9. Supported corpus (target)
|
||
|
||
| document | class | features |
|
||
| --- | --- | --- |
|
||
| article-10/11/12 | `article.cls` | sections, lists, footnotes, floats, tables |
|
||
| amsmath-paper | `article` + `amsmath` | display math, aligned, cases, matrices, equation numbers |
|
||
| arxiv-template | custom `arxiv.sty` | two-column title block, natbib, tables |
|
||
| sivp-paper | `sn-jnl.cls` | two-column journal, front matter, wide floats |
|
||
| thesis-chapters | `book.cls` | chapters, TOC, lists of figures/tables |
|
||
|
||
## 10. Sequencing into goals
|
||
|
||
| goal | phases | deliverable |
|
||
| --- | --- | --- |
|
||
| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` |
|
||
| G2 | P3, P4 | tables and math at L2/L3 |
|
||
| G3 | P5 | Computer Modern fonts, NFSS, pixel parity for text/math |
|
||
| G4 | P6 | class execution (article, journal) |
|
||
| G5 | P7, P8 | default engine, incrementality, corpus and CI |
|
||
|
||
Each goal keeps `cargo fmt`, `cargo test`, `cargo build --release` green, updates
|
||
`README.md` and `docs/TEX_CORE.md`, and pushes `texrra-engine`.
|
||
|
||
## 11. Definition of done (whole program)
|
||
|
||
- Route-D is the default engine for preview and PDF; v1 is a fallback flag.
|
||
- For the supported corpus, page counts match pdfLaTeX/XeLaTeX and text
|
||
positions match within 1pt; with CM fonts embedded, 150dpi pixel difference is
|
||
≤0.5%.
|
||
- A one-paragraph edit of a 10-page document repaints in < 100ms and only
|
||
changed pages are sent.
|
||
- The oracle harness runs in CI; known differences are listed with reasons.
|