Reproduce TeX paragraph breaking with tolerance passes and demerits

- replace the single-tolerance DP with pass 0 (pretolerance, no hyphenation),
  pass 1 (tolerance, hyphenation) and an optional emergency pass
- add emergencystretch to ParagraphStyle; the emergency pass only runs when it
  is positive, otherwise TeX's overfull fallback applies and each line fills to
  the first break at or past the measure
- compute badness and fitness classes like TeX and fold them with penalties
  into demerits, ignoring the trailing forced penalty on the final line
- keep forward order in the greedy fallback
- enable the 180pt pdfLaTeX oracle fixture and add an emergencystretch test
- give route-D extraction tests scaled body styles so fixed-cell
  ParagraphStyle defaults no longer mix raw units with TFM advances
- document the passes, oracle results and remaining P1 gaps
This commit is contained in:
gloamxun committed 2026-10-23 00:50:57 +08:00
1 parent 03aa1c5110
commit ac134b3c4e
8 files changed
+331 -164

No files matched your search

+34 -43
View File
@@ -52,26 +52,30 @@ class execution are still ahead.
stretch/shrink;
- `Cmr10Metrics`, a CMR10 ASCII width table extracted from `cmr10.tfm` with
`tftopl`, plus the fontdimen space/stretch/shrink values;
- an item-stream Knuth-Plass-style dynamic program over character boxes, glue and penalty breakpoints that minimizes badness from
glue stretch/shrink, allows overfull lines with an explicit overfull penalty,
applies `par_indent` to the first line, and bakes the justification into the
glue widths of every non-final line;
- an item-stream dynamic program over character boxes, glue and penalty
breakpoints that minimizes TeX demerits (line penalty, badness, break
penalties and adjacent fitness changes), applies `par_indent` to the first
line, and bakes the justification into the glue widths of every non-final
line;
- `Paragraph { lines, height, width }` and a paragraph-backed `Unit`.
M1 reads real CMR10 TFM metrics (advances, height/depth, italic correction,
kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue parameters),
hyphenates with the plain-TeX en-US patterns, and is checked against pdfLaTeX
by `tests/oracle.rs`: the 150pt fixture matches the oracle word for word and
within 0.05pt horizontally. Justification now clamps the glue set ratio to the
declared stretch and shrink, so an overfull line stays overfull exactly as in
TeX instead of being squeezed into the measure.
M1 reads real CMR10 TFM metrics at runtime (advances, height/depth, italic
correction, kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue
parameters), hyphenates with the plain-TeX en-US patterns, and reproduces
TeX's paragraph breaker: pass 0 uses `\pretolerance` without hyphenation,
pass 1 uses `\tolerance`, and a third pass with `\tolerance=10000` runs only
when `\emergencystretch` is positive. With zero emergencystretch TeX gives up
and fills each line to the first break at or past the measure, which leaves
the familiar overfull boxes; the same fallback runs here. Justification clamps
the glue set ratio to the declared stretch and shrink, so an overfull line
stays overfull exactly as in TeX instead of being squeezed into the measure.
The demerits/tolerance model is still simplified: the final line keeps its
natural width and the last break can differ from TeX when the emergency pass
would accept a tighter split (the 180pt fixture is `#[ignore]`d until P1).
`route_d_multiline_bands_track_pdftex` rasterizes the same oracle-verified
150pt paragraph in both engines and compares ink bands, covering baseline
placement and justification.
`tests/oracle.rs` checks the 150pt and 180pt fixtures against pdfLaTeX: both
match the oracle word for word and within 0.05pt horizontally. The 150pt
fixture exercises the overfull fallback, the 180pt fixture the ordinary
pass-1 solution. `route_d_multiline_bands_track_pdftex` rasterizes the same
paragraph in both engines and compares ink bands, covering baseline placement
and justification.
## Target architecture
@@ -88,10 +92,10 @@ placement and justification.
| Milestone | Content | Acceptance |
| --- | --- | --- |
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, hyphenation, TeX glue clamps and a pdfLaTeX oracle at 150pt; demerits/tolerance next |
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, hyphenation, TeX demerits and tolerance passes, pdfLaTeX oracles at 150pt and 180pt; explicit tolerance registers and more fixtures next |
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; interpreted `\output`, float pages next |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: `Halign` model with natural column widths, spans and rule rows; no `\omit`/`\span` token parsing or PDF painting yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: `MathAtom` symbol/script/fraction boxes with CMR10 widths; no token conversion, radicals, accents or painter |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; no booktabs/longtable parity yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet |
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
| M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity |
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
@@ -99,28 +103,15 @@ placement and justification.
## Current limits
- The M1 paragraph builder parses CMR10 TFM metrics (widths, height/depth,
italic correction, kern pairs, ligatures) and applies plain-TeX hyphenation.
It does not yet reproduce TeX tolerance/demerits exactly or honor every
penalty class.
italic correction, kern pairs, ligatures), applies plain-TeX hyphenation and
runs TeX's tolerance passes with demerits. Remaining gaps are explicit
`\tolerance`/`\pretolerance` overrides, hyphenated-break penalties and
`\parfillskip` variants.
Multi-width pdfTeX comparison (same 24-word ASCII paragraph):
The pdfLaTeX oracle currently pins two measures (150pt and 180pt). The earlier
multi-width table was produced by the old single-cost breaker and is no longer
evidence of divergence; 120pt and 200pt should be added as fixtures next.
| `\hsize` | pdfTeX words per line | current DP |
| --- | --- | --- |
| 120pt | 5, 6, 7, 4 | 3, 4, 4, 4, 5 |
| 150pt | 6, 7, 6, 4 | 4, 5, 6, 6 |
| 180pt | 7, 7, 8 | 7, 7, 8 |
| 200pt | 8, 7, 7 | 6, 7, 9 |
The remaining difference is the TeX tolerance/demerit model, not CMR10
metrics: TeX accepts moderately overfull lines that our DP rejects.
Concrete 120pt first-line candidates: a 3-word line has natural 109.4pt,
stretch 4.6pt, badness 396; a 5-word line has natural 142.8pt, shrink 5.6pt,
overfull ratio 4.11, badness 6942. TeX rejects the underfull candidate under
its tolerance but still emits the moderately overfull 5-word line. Reproducing
this needs a two-pass tolerance algorithm with an emergency overfull pass, not
a single cost function.
- `\middle|` inside `\left...\right` is accepted as a delimiter symbol (not yet stretched).
- `\sqrt[n]{x}` carries an optional degree atom; `\left.` is an empty
delimiter with zero width.
@@ -246,7 +237,7 @@ for a later overlaid slash.
| Milestone | State | Notes |
| --- | --- | --- |
| M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay |
| M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, hyphenation, pdfTeX fixtures; tolerance/demerits still approximate |
| M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, hyphenation, TeX demerits and tolerance passes, pdfTeX 150pt/180pt oracles |
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; interpreted `\output` absent |
| M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter |
| M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping |
@@ -312,8 +303,8 @@ The staged program that closes these milestones is described in
Route D currently covers M0-M4/M6 as a working subset. The remaining milestones are
deliberately open rather than approximated:
- **M1**: TeX tolerance/demerits are still fitted to a few fixtures; multi-width
pdfTeX line breaks and full hyphenation demerits are not reproduced generally.
- **M1**: explicit `\tolerance`/`\pretolerance` registers, hyphenated-break
penalties and more width fixtures are still open.
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented.
- **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and
math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `\output` is still Rust code rather than interpreted tokens.