723 lines
43 KiB
Markdown
723 lines
43 KiB
Markdown
# Route D: complete implementation plan
|
||
|
||
Latest acceptance, 2026-11-03: [W3-S5b actual paragraph traces, canonical-zero
|
||
glue and owned ordinary side-script lists](NATIVE_PARAGRAPH_TRACE.md) passes
|
||
**1384 workspace tests /0**, CLI48, optimized 138 core +20 CLI and all retained/new
|
||
gates. Break traces observe the actual candidate/passive/selected path; real
|
||
glue specification identity and script h/v lists drive print and paint. The
|
||
8-job/32-page oracle has 24 exact reports /5436 pass-and-decision lines, zero
|
||
word/raster differences and identical native PDF bytes across trace controls.
|
||
All statistics/PK/PDF/device and 105-page object-stream gates remain accepted.
|
||
Original full entry and direct kernel now stop at latex.ltx:657:3 tracinggroups;
|
||
format_boot_passed=false. Full P2-M1 stays active/incomplete. Remaining real
|
||
tracing consumers/insertions, compound math fields, format/NFSS/native image/
|
||
article and sessions keep every original exit. No v1/source/template/font fallback.
|
||
Dated planning/pause notes below are historical; see [progress](P2_M1_PROGRESS.md).
|
||
|
||
Execution authorized, 2026-11-02: the user approved the complete
|
||
[P2-M1 stage](NATIVE_FORMAT_ARTICLE_STAGE.md), with **every original G1 exit
|
||
criterion mandatory in W1**. W0 implementation is under way; see
|
||
[live progress](P2_M1_PROGRESS.md). Earlier G1 pause/planning statements below
|
||
are historical. No stage completion or replacement of the 1204-test baseline
|
||
is claimed by this authorization or the current targeted work.
|
||
|
||
## Current product direction — 2026-11-02
|
||
|
||
The user reaffirmed the end product: a native LaTeX kernel with Typst-like
|
||
realtime incremental rendering and complete project portability. The Web app
|
||
is a frontend test surface. Primitive/diagnostic slices are subordinate to real
|
||
format, font, page and unmodified-project compatibility, together with correct
|
||
incremental execution. The governing roadmap and exit criteria are now in
|
||
[NATIVE_PRODUCT_GOAL.md](NATIVE_PRODUCT_GOAL.md). G1 remains paused at the user's
|
||
request. Its first-showbox component is now independently validated together
|
||
with P1-T1; its remaining input-context/diagnostic work is incomplete.
|
||
|
||
The next complete stage is [P2-M1: real format and unmodified article](NATIVE_FORMAT_ARTICLE_STAGE.md).
|
||
It plans actual pdflatex.ini/TEXMF/PDF initialization, execution/font/page
|
||
consumers, native format dump/load, five article corpus groups and full-job
|
||
session/revision/dependency/performance foundations. W0 fixes the reference
|
||
closure and general resource-resolution contract first. Fresh probes show
|
||
pdflatex.ini currently fails to find pdftexconfig.tex; the configuration itself
|
||
fails at pdfoutput, while direct latex.ltx still stops at errorcontextlines.
|
||
Actual reference TeX builds the format and a one-page minimal article. These
|
||
are planning/baseline results, not new native implementation acceptance.
|
||
G1 remains paused; incremental reuse and Web migration are separate exits.
|
||
|
||
Route-D is the sole future product engine and will completely replace v1.
|
||
The plan below this section is historical where it conflicts with these rules:
|
||
|
||
- Route-D owns input scanning, tokens, macro expansion, state, primitives,
|
||
modes, native horizontal/vertical/math lists, layout and export.
|
||
- Execute real LaTeX formats, `.cls` and `.sty` code. Replace string rewriting,
|
||
template detection and package simulation with native execution over time.
|
||
- Do not introduce v1 fallback or new template-specific placement rules.
|
||
Existing special cases are migration debt, not accepted general algorithms.
|
||
- Independent verified algorithms, metrics and font assets may be reused through
|
||
Route-D-owned interfaces; v1's semantic renderer and VM adapter are not the
|
||
new execution architecture. v1 is temporary comparison infrastructure only.
|
||
- pdfLaTeX and XeLaTeX compatibility are separate profiles on the same native
|
||
Route-D core. Pin format/package/font versions and test unmodified projects.
|
||
- Preview, PDF and source mapping consume the same measured page results.
|
||
Incremental reuse requires unchanged incoming engine state and dependencies.
|
||
|
||
Milestones and exit criteria:
|
||
|
||
1. Define native interfaces and strict capability/oracle accounting. Keep
|
||
original templates separate from patched layout-diagnostic fixtures.
|
||
2. Math C/D accepted for the current core atom slice (2026-10-31): retain styles and operator policies, store measured geometry,
|
||
paint it directly in display and inline math, embed raw CMEX slots and real
|
||
7pt/5pt optical masters. Validate actual PDF geometry against fresh TeX output.
|
||
3. First native bootstrap slice accepted (2026-10-31); continue native
|
||
primitive/profile and mode/list execution to replace textual expansion.
|
||
Keep token/state/list differential tests and safe dependency accounting.
|
||
4. Build the real font/page/output consumers required to boot the full native
|
||
LaTeX format and its input closure, implement native dump/load, and compile
|
||
an unmodified minimal article. Format startup depends on those consumers;
|
||
they cannot all be postponed until after initialization.
|
||
5. Grow complete native class/package/project portability through actual code
|
||
execution: fonts/NFSS/shaping, math, pagination/output, alignments/tables,
|
||
floats, graphics/PDF, references and multi-pass workflows. Validate original
|
||
source and resources, without font substitutions or package simulations.
|
||
6. Build stable state/dependency identities alongside core execution; validate
|
||
resumable checkpoints, correct invalidation/reuse, cancellation and page
|
||
patches against full compilation. Measure kernel cold/warm edit latency and
|
||
memory on pinned projects. Migrate all product endpoints and remove v1 and
|
||
its exclusive adapters/dependencies only after compatibility and realtime
|
||
replacement gates pass. Web changes are not a core-product milestone.
|
||
|
||
Accepted bounded P1-T1 (2026-11-02): [native sfcode and sentence spacing](NATIVE_SFCODE.md)
|
||
implements the scoped code table and actual factor/glue consumers. 256 default/
|
||
eight state, 132 exact list and nine raw-slot/timing cases, plus a real PDF gate,
|
||
pass. Full workspace: 1204 passed / 0 failed. G1 remains paused; full format
|
||
still stops at errorcontextlines (526:1), and realtime checkpoints remain open.
|
||
|
||
Short-term audit and next implementation goal (2026-11-02): see
|
||
[G1: native input contexts and basic diagnostics](NATIVE_SHORT_TERM_GOAL.md).
|
||
Forty paired INITEX probes retain three supported controls, 28 undefined-entry
|
||
findings, seven explicit unsupported-semantic findings, missing error context
|
||
and a new first-showbox blank-line mismatch. Six reference-only context probes
|
||
verify negative/zero/positive truncation rules. This audit changes no engine
|
||
implementation and does not increase the previous 1200-test acceptance count.
|
||
G1 closes real input frames/errorcontextlines, the first diagnostic channel
|
||
state, show and showthe, then re-probes untouched LaTeX beyond line 526. Other
|
||
short slices (macro scheduling/hooks, quantity expressions, OT1 punctuation/
|
||
sfcode, list primitives) and larger font/page goals have explicit dependencies
|
||
and separate acceptance. No unsupported feature is registered as a passed flag.
|
||
|
||
Current immediate work (2026-11-01): the native bootstrap and explicit partial
|
||
EtexBootstrap profile are accepted. In addition to owned lazy tokens, scoped
|
||
state, macros and typed output, the kernel implements protected definitions
|
||
with scanner-specific expansion, unexpanded/detokenize/expanded, numexpr,
|
||
extended count/toks registers, chardef, hash-brace macros and more conditional
|
||
evaluators. No source rewriting, v1 call or automatic fallback was added.
|
||
The job/I/O slice is accepted too: an actual host-local time snapshot, scoped
|
||
time/date parameters, real input/output streams, read/readline/ifeof, meaning,
|
||
live messages/logging and typed deferred output with an explicit shipout API.
|
||
The next quantity slice is accepted: typed mathchardef, real physical inputlineno,
|
||
dimen/skip/muskip registers, exact fixed-point units/glue orders/arithmetic,
|
||
printing and ifdim. Recursive scanners/expansion fail with bounded diagnostics.
|
||
|
||
Verification: **1204 tests / 0 failed**, **90 real pdfTeX INITEX token probes**,
|
||
**101 dimension/glue comparisons**, **119 paragraph INITEX comparisons**,
|
||
**205 box packing INITEX comparisons**, **117 math list/geometry and 88 math break comparisons**,
|
||
**12 filesystem byte comparisons**, a
|
||
selected/discarded shipout oracle, actual math pack-state oracle, **100 interline
|
||
vlist and 64 page-ownership cases**, **58 display vlist / 36 page / 24 quantity-mode-pack
|
||
cases**, **2816 font-slot predicates + four font-identifier queries**,
|
||
**61 diagnostic and 267 raw-slot/math/discretionary comparisons**, **438 accent
|
||
DVI geometry and 28 mutable-hyphen timing cases**, **452 delimiter DVI geometry
|
||
cases and 256 default-code/nine state/seven group readbacks**, and seventeen native CLI tests.
|
||
The paragraph slice now owns typed parameters, real glyph/glue/discretionary
|
||
nodes, integer line breaking, parameter timing and frozen line export. A real
|
||
CMR10 10pt PDF gate compares 89 words within 0.02bp; see
|
||
[native paragraph state and scope](NATIVE_PARAGRAPHS.md). The [native box slice](NATIVE_BOXES.md)
|
||
adds actual hpack/vpackage, modes, box registers and vertical append state, with
|
||
a 30-word nested-box PDF gate below 0.02bp. The [native inline math slice](NATIVE_MATH_EXECUTION.md)
|
||
now owns math tokens/noads, real family/font state, binary cancellation and actual
|
||
mu spacing/binop/rel penalties, including paragraph auto-breaking boundaries and
|
||
real internal hpack badness. Its 100-word PDF gate stays below 0.02bp. [Native interline penalties](NATIVE_INTERLINE_PENALTIES.md)
|
||
now sum actual interline/club/widow/broken state at par completion and feed the
|
||
strict native page consumer; a six-page/14-word gate verifies per-page ownership
|
||
and word boxes below 0.02bp. Saturated underfull page cost follows the actual
|
||
TeX deplorable rule. [Native display math](NATIVE_DISPLAY_MATH.md) now performs
|
||
real mode transitions, display-widow completion, pre/post penalties and normal/
|
||
short skips with actual pre-display size, shifted hpack, depth and continuation
|
||
state. A three-page/97-word PDF gate stays below 0.02bp. Native pages use actual
|
||
glue packaging; the generic builder fires at the first overfull legal/forced
|
||
point and chooses the best prior candidate. Math D remains passed: three pages,
|
||
y error +0.1035625bp and identical 144dpi formula ink bounds.
|
||
|
||
Real format startup remains open. The unchanged, SHA-pinned LaTeX2e 2025-11-01
|
||
entry passes its original e-TeX guard, writes actual time/date to texsys.aux,
|
||
reads it back and passes the source's own equality/directory test. It advances
|
||
from time at 168:8 through mathchardef/registers and paragraph parameters to
|
||
**526:1, missing errorcontextlines**. Version quantities identify
|
||
the explicit target interface; bootstrap coverage is not full conformance.
|
||
[Native font diagnostics](NATIVE_FONT_DIAGNOSTICS.md) now consumes tracinglostchars/
|
||
tracingonline in actual text, math fetch and discretionary construction, using
|
||
real TFM existence and Type1 slots/encodings. Actual iffontchar predicates,
|
||
transcript/terminal delivery, fatal PDF protection, all 128 CMR10 OT1 slot
|
||
rasters and a 25-word PDF gate pass. [Native font integer state and accents](NATIVE_FONT_STATE_ACCENTS.md)
|
||
now consume defaultskewchar on real first loads, mutable global skewchar in
|
||
actual mathaccent placement, and hyphenchar at real construction stages. Raw
|
||
font identity is independent of integers and repeated loads reuse state.
|
||
A 54-word PDF gate and full-accent ink gate pass. [Native delimiters](NATIVE_DELIMITERS.md)
|
||
now execute scoped delcodes, real delimiter/left/right fields and two-pass
|
||
delimiterfactor/delimitershortfall sizing, actual family searches, TFM variants
|
||
and extensible component assembly. A 61-word PDF gate and full-delimiter ink
|
||
gate pass; exact DVI cases also fix generic odd-sp fraction placement/reboxing.
|
||
[Native box/list diagnostics](NATIVE_BOX_DIAGNOSTICS.md) now retain original
|
||
horizontal nodes, selected paragraph material and named vertical glue, with
|
||
real breadth/depth traversal and log/terminal consumers. Four tests add 152
|
||
exact INITEX recursive-list cases, 24 paragraph lists and 24 byte-printer cases;
|
||
a CLI test verifies actual channels, show status 1 and continued PDF output.
|
||
The five-show fixture has one page / 19 words within the unchanged 0.02bp gate.
|
||
Compound math/glue diagnostic structure, showlists and full interaction/context
|
||
printing remain open; unsupported inspection errors explicitly.
|
||
Next preserve actual input/macro expansion context and consume
|
||
errorcontextlines in real error/context printing; no unused flag or fabricated
|
||
backtrace. Continue untouched format source after independent INITEX oracles.
|
||
Do not register unused parameters or substitute requested fonts. Ordinary interline penalties, inline
|
||
noads/binop-rel and unnumbered native display transitions are accepted slices;
|
||
equation numbers, alignments, display-style operator variants/limits and full
|
||
math/font/page conformance remain open. Parameter storage alone remains
|
||
insufficient for new coverage. Complete code tables, quantity expressions, font/magnification state,
|
||
remaining scanners, modes/lists with deferred shipout, and versioned dump/load.
|
||
Do not treat math character constants as painted text or supply demo em/ex/true
|
||
unit values. See [native quantity scope](NATIVE_QUANTITIES.md).
|
||
The demo CLI rejects pending output whatsits; it does not flush them at EOF.
|
||
See [job time and file-stream evidence](NATIVE_JOB_IO.md).
|
||
Only the entry file is pinned; the full input/config/font closure is still open.
|
||
|
||
Font/format fidelity is a separate required gate. The audited PDF text actually
|
||
uses Liberation Serif/Mono while the reference uses Nimbus Roman/SFTT1000;
|
||
strict native execution supports CMR10 10pt text and ten real CM mathematical
|
||
font masters/families. Latin math descriptor metrics use actual TFM masters.
|
||
Raw CMR10 OT1 slots now paint their real encoded glyphs; this does not
|
||
certify pdfTeX UTF-8 byte-input conformance. Arbitrary resources/sizes, full
|
||
encoding/map/VF closure and NFSS remain open. Implement
|
||
native font state, TFM/VF/encoding/map resolution and real format macros,
|
||
followed by the Unicode shaping profile. Do not extend font-name heuristics
|
||
or adjust template spacing to hide these differences. See
|
||
[the font/format gap audit](NATIVE_FONT_FORMAT_GAPS.md).
|
||
|
||
HTTP/project routes still use the transitional Route-D frontend; this slice
|
||
has not switched them. Do not stringify native output back into that frontend.
|
||
Native snapshots/read keys are not safe incremental reuse proofs by themselves;
|
||
input/mode checkpoints, dependency versions, cancellation and glyph source maps
|
||
remain required. See [NATIVE_EXECUTION_CORE.md](NATIVE_EXECUTION_CORE.md).
|
||
Math coverage and block/unit/display/float debts remain documented native
|
||
milestones in [MATH_ENGINE_TEX.md](MATH_ENGINE_TEX.md).
|
||
|
||
Status: active plan. Baseline commit `4414f27`, 2026-10-23.
|
||
|
||
Current status and verification evidence: `docs/ROUTE_D_STATUS.md`.
|
||
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 **sole target product engine** of the texrra web service; v1 is
|
||
retained only during migration for comparison and will be removed.
|
||
|
||
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`; flat `/preview` and project previews now
|
||
prefer route-D with a v1 fallback). 1094 workspace tests are green and no oracle
|
||
fixture is ignored. Preview JSON also carries a `warnings` array naming
|
||
environments route-D cannot lay out and control words that survived layout, so
|
||
unsupported source is reported instead of being silently typeset.
|
||
|
||
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
|
||
demerits and paragraph registers, the paged builder implements the page
|
||
builder (glue setting, inserts, marks, floats, paper size and page registers),
|
||
and the interpreted `\output` routine runs page by page with conditionals,
|
||
arithmetic, mark writes, register assignments and page retargeting. The audit
|
||
table in [`TEX_CORE.md`](TEX_CORE.md) lists the evidence per milestone.
|
||
|
||
Remaining gaps:
|
||
|
||
1. `\halign` handles spans/omit/templates, `p{width}` paragraph columns (wrapped cell text grows row heights and participates in row-level page splitting), explicit per-column `\tabskip` glue, page-sized row chunks that keep the table's column widths, and booktabs rule weights with partial `\cmidrule(lr){a-b}` spans, `@{}`/`@{\hspace{...}}` column expressions and `\noalign{\vskip ...}` row glue, longtable head/foot sections repeat the head rows on every page chunk and paint the foot block once, LaTeX `tabular` sources route through the same halign path, but not the full TeX column algorithm (`\valign` interleaving, nested tables);
|
||
2. math is a compact subset without the CM math fonts (`cmmi`, `cmsy`, `cmex`),
|
||
display-math line breaking or `\mathchoice`-level styling;
|
||
3. text fonts are Liberation, not Computer Modern; Type1 fonts are not embeddable
|
||
yet, so pixel comparison against pdfLaTeX is impossible;
|
||
4. class files (`article.cls`, `sn-jnl.cls`) are mapped semantically, never
|
||
executed;
|
||
5. the service integration is opt-in and maps only a small LaTeX subset;
|
||
6. the content of `\box255` is not inspectable, `\topmarks`/`\firstmarks`/
|
||
`\botmarks` are not readable by the routine, an assigned `\vsize` cannot
|
||
retarget a document that defers bottom floats, paged replay falls back to a
|
||
full rebuild with an interpreted `\output` or insertions, and a
|
||
narrow-measure `\tolerance=10000` break can differ from TeX's demerit
|
||
optimum.
|
||
|
||
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 an eleven-measure matrix (90-240pt) and all fixtures match
|
||
pdfLaTeX word for word within 0.05pt; the narrow measures exercise hyphenated
|
||
and overfull breaks, and a final line held at its declared shrink limit. 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.
|
||
|
||
`\spaceskip` and `\xspaceskip` replace the interword glue; pdfTeX dumps
|
||
`\xspaceskip` verbatim above factor 2000 while `\spaceskip` keeps its width
|
||
but scales stretch/shrink, and 150pt oracle fixtures pin both.
|
||
|
||
`\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; a 120pt fixture requires one extra
|
||
line and matches pdfLaTeX exactly. When the requested count is infeasible
|
||
TeX's own output picks an alternative optimum that route-D does not
|
||
reproduce; the infeasible case is covered by unit tests.
|
||
|
||
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. A paragraph that does
|
||
not fit is split at line boundaries: the next fragment continues on the next
|
||
page without a `\parskip`, and a single unsplittable line may overflow at the
|
||
top of a page (see `Paragraph::split_at`).
|
||
|
||
Still open: explicit
|
||
`\vskip` classes (`\smallskip` and friends). The breaker now rejects overfull
|
||
lines outside the emergency pass, exactly like TeX, so `\tolerance` cannot
|
||
smuggle in a single overfull line any more. Hyphenated breaks are checked at
|
||
80-120pt, and a 70/85pt fixture sets `\doublehyphendemerits` and
|
||
`\finalhyphendemerits` to 0 and 10000 so both demerits change the reference
|
||
breaks; at `\tolerance=10000` the wide-measure fixture matches pdfLaTeX at
|
||
100-240pt, and a 70/85pt fixture with `\pretolerance=10000 \tolerance=200`
|
||
matches the loose one-word lines TeX keeps before enabling hyphenation.
|
||
|
||
Bottom floats have two page fixtures: one where the float fits, and one
|
||
where it does not fit the remaining body space. In both cases the page
|
||
count and per-page text match pdfLaTeX: the page keeps filling, and a
|
||
float that cannot fit is carried to the next page's bottom, exactly as
|
||
TeX's page builder does. `PageBuilder::build_with_deferred_bottom_floats`
|
||
implements that behaviour, `Engine::layout_paged` and the route-D service
|
||
use it, and a float taller than a page still ends the page rather than
|
||
looping.
|
||
|
||
### P2 — Vertical list, page builder, `\output` (L2)
|
||
|
||
Scope:
|
||
|
||
- glue setting in vertical lists (ragged/flush bottom, `\vfil`/`\vfill`
|
||
orders), `\vsize`, `\voffset`,
|
||
`\topskip`, `\maxdepth`, `\splittopskip`, `\splitmaxdepth`;
|
||
- TeX page builder: candidate breakpoints, cost = badness + penalty, page goal
|
||
recomputation as insertions arrive, `\pagegoal` (`\vsize` less the insertion
|
||
space reserved on the page), `\pagetotal`, `\pagedepth`, `\pagestretch`,
|
||
`\pagefilstretch`, `\pagefillstretch`, `\pagefilllstretch` (per-order stretch
|
||
is recorded on every page fragment), `\pageshrink`;
|
||
- marks: `\mark`, `\botmark`, `\firstmark`, `\topmark`, `\marks` (marks are
|
||
collected per page; `Engine::top_mark`/`first_mark`/`bot_mark` now carry the
|
||
TeX register semantics, `\marks` remains open);
|
||
- insertions: `\insert` with `\count`, `\dimen`, `\skip` per class, split
|
||
insertions, held-over material with `\splittopskip` leading each
|
||
continuation and `\splitmaxdepth` clamping the first continued box's
|
||
depth (excess moves into its height), `\footins` defaults (the three registers are
|
||
now modelled by `InsertionClass::multiplier`, `max_height` and `skip`, and
|
||
the fitting head stays on the anchor page with the tail held over; TeX's
|
||
register arithmetic remains);
|
||
- output: `\output` as an interpreted token list (`\shipout\box255`, `\ifdim`,
|
||
`\ifnum`, `\outputpenalty`, `\pageno` and `\deadcycles` landed), page
|
||
display list assembly;
|
||
- floats: TeX-compatible policy module used by the default output routine
|
||
(top/bottom fractions and counts already exist).
|
||
|
||
The foundation is in `crates/texrra-tex-core/src/page.rs`: `PageBuilder` takes a
|
||
`VerticalNode` list (box height/depth, glue width/stretch/shrink, penalties,
|
||
marks) and chooses each page at the cheapest feasible breakpoint, scoring
|
||
badness from the page goal and accumulated glue, adding the break penalty, and
|
||
applying `\topskip` to the first box and `\maxdepth` to the page depth. Seven
|
||
unit tests cover overfull avoidance, exact glue filling, forced penalties,
|
||
penalty-driven earlier breaks, `\topskip`, `\maxdepth`, marks, insertion
|
||
limits, float placement, vertical glue setting and glue orders.
|
||
`Engine::layout_paged` now feeds it every document whose units are single
|
||
vertical items (`Document::max_depth` supplies `\maxdepth`) and materialises the
|
||
chosen fragments as hashed pages; ties go to the later breakpoint (TeX's `<=`
|
||
update), and a page that cannot fit any break within its glue shrink still takes
|
||
the least overfull break. Paragraph nodes carry their last-line descent as depth, so `\pagedepth` reports it and `\maxdepth` only caps the kept part while the excess moves into the page height; route-D applies LaTeX's 5pt `\maxdepth` default at the source layer, and the page fixtures pin it. `Document::h_offset` and
|
||
`v_offset` feed the PDF writer's `pdf::PageOrigin`, which translates the page
|
||
body without moving the sheet; a route-D integration fixture checks the shift
|
||
with `pdftotext -bbox`. `Document::paper_width`/`paper_height`
|
||
(`\paperwidth`/`\paperheight`, default US Letter) set the MediaBox and preview
|
||
page box, and the endpoints read leading
|
||
`\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension assignments from
|
||
the source. Insertion classes are placed by the
|
||
paged builder with their limits and held-over material, top floats are placed
|
||
at the head of a fragment with `\textfloatsep` reserved above the body, and
|
||
bottom floats sit at the page bottom with `\floatsep` between them and a
|
||
`\bottomfraction` cap; in-text floats flow inline with their `\intextsep` gaps counted as body height. Vertical glue is set when pages are materialised: `PageBuilder::ragged_bottom` defaults to `\raggedbottom`, while `\flushbottom` stretches `VerticalItem::StretchGlue` proportionally so the page body reaches the goal (`PageFragment::set` records the signed setting amount); glue orders follow TeX, so only the highest order with stretch (for example `\vfil`) takes the setting and short pages are free. Paged layouts also record the
|
||
node index starting each page, so `Engine::edit` reuses the sealed prefix and
|
||
rebuilds only the pages from the edited unit onward; insertions and interpreted
|
||
`\output` keep the full-rebuild fallback. Next: extend the `\output`
|
||
interpreter past the shipout/ifdim/ifnum/ifodd/ifcase subset.
|
||
|
||
Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks);
|
||
page counts identical and first/last baselines within 1pt of pdfLaTeX.
|
||
Progress: ten page fixtures are wired (single-line paragraphs, `\parskip=6pt`
|
||
spacing, multi-line paragraphs split across pages, a 300pt `\textheight`, a
|
||
30pt `\topskip`, `\newpage` forced breaks, stretchy `\vskip` glue between
|
||
paragraphs, `\footnotetext` insertions reserved at the page bottom, a
|
||
`[t]` float that reserves its height plus `\textfloatsep` on its own page,
|
||
and `[b]` floats that fit or defer to the next page); each
|
||
asserts the same page count and the same per-page body text as pdfLaTeX, with
|
||
footnote text excluded from the body comparison. Route-D's source mapping still
|
||
does not raise LaTeX floats, so the float fixture drives `Engine` directly.
|
||
Two more fixtures pin TeX's orphan and widow controls: `\clubpenalty=-10000`
|
||
forces a break after a paragraph's first line and `\widowpenalty=-10000` forces
|
||
one before its last, page for page against pdfLaTeX. The paged builder inserts
|
||
both penalties between line nodes (150 by default) and refuses any penalty of
|
||
10000 or more as a breakpoint. Display math units reserve `\abovedisplayskip`
|
||
above and `\belowdisplayskip` below (the 10/11/12pt class defaults, overridable
|
||
from the source in TeX's `7\p@ \@plus 2\p@` spelling too), and a page fixture
|
||
shows a display near the page goal moving to the next page with pdfLaTeX.
|
||
`\AtBeginDocument{...}` setup is lifted ahead of the body and `\newgeometry{...}`
|
||
is applied as preamble geometry, with an explicit `textheight`/`textwidth`
|
||
taking precedence over margins, so class files that set their page block in a
|
||
begin-document hook get the intended measure instead of a text warning.
|
||
|
||
### 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.
|
||
|
||
Progress: the arXiv template's class (`arxiv.sty`) previews with no warnings in
|
||
two pages. `\title`/`\author`/`\thanks` stay on the native title path, heading
|
||
commands are kept for the native section parser instead of expanding their class
|
||
redefinitions, `\keywords` becomes a plain paragraph, `\lipsum[n]` expands to
|
||
filler text, comments and external `\bibliography` commands are dropped, and a
|
||
`center`/`flushleft`/`flushright` environment that follows text starts its own
|
||
block, and `geometry`'s `top`/`bottom` margins offset the page body (the arXiv
|
||
first baseline is at 1in + 12pt) while an explicit `textheight` wins over the
|
||
margins. `\pagestyle{fancy}` and the fancyhdr head/foot fields paint L/C/R
|
||
running heads at `top margin - headsep` and feet at `text height + footskip`,
|
||
expand `\thepage` per page, draw `\headrulewidth`, and leave the title page
|
||
empty; the arXiv template shows `A Preprint` and its short title after page one.
|
||
Class files are still mapped semantically rather than executed by a VM.
|
||
|
||
### 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` (shipout/ifdim/ifnum/ifodd/ifcase subset landed) |
|
||
| 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.
|
||
|
||
## Handoff (round 150/150)
|
||
|
||
Route-D currently passes **928** workspace tests and is pushed at `b191f7d`.
|
||
The flat `/preview` and project preview/PDF endpoints now try route-D first
|
||
and fall back to v1 (pass `?engine=v1` or set `TEXRRA_ENGINE=v1` for the old
|
||
pipeline). To continue the programme:
|
||
|
||
1. Run `cargo fmt --all -- --check` and `cargo test --workspace --offline`
|
||
from `engine/` before every change; pdfLaTeX oracles skip automatically when
|
||
`pdflatex`/`pdftotext` are absent.
|
||
2. Work the gaps listed in `docs/TEX_CORE.md` under "Remaining gaps at round
|
||
148": token/catcode state, measured boxes, multirow centring, array column
|
||
modifiers, outer table margins, arbitrary NFSS families and Unicode.
|
||
3. Every increment: add tests (pdfLaTeX oracle where visual geometry matters),
|
||
update the counts in `TEX_CORE.md`, `ROUTE_D_PLAN.md` and `README.md`, then
|
||
commit and push to `texrra-engine` main.
|
||
|
||
The `warnings` array in preview JSON is the compatibility harness: any new
|
||
command or environment that reaches layout as text is reported there, so
|
||
fixtures can be promoted from failing to warning-free as support lands.
|