Ship the page after maxdeadcycles

This commit is contained in:
gloamxun committed 2026-10-23 14:26:58 +08:00
1 parent 8007fd1b6c
commit 4111080422
4 files changed
+84 -8

No files matched your search

+58 -2
View File
@@ -673,6 +673,10 @@ pub struct Document {
/// Extra vertical displacement of the page origin (`\voffset`).
#[serde(default)]
pub v_offset: i64,
/// TeX `\maxdeadcycles`: how many pages the output routine may decline to
/// ship before TeX ships the page itself. Defaults to 25.
#[serde(default = "default_max_deadcycles")]
pub max_deadcycles: i64,
/// TeX `\output` token list, interpreted by [`output::OutputProgram`].
/// `None` ships every page the builder produces.
#[serde(default)]
@@ -731,6 +735,10 @@ fn default_total_number() -> u8 {
12
}
fn default_max_deadcycles() -> i64 {
25
}
impl Document {
pub fn new(page_goal: i64, units: Vec<Unit>) -> Self {
Self {
@@ -757,6 +765,7 @@ impl Document {
par_skip: 0,
h_offset: 0,
v_offset: 0,
max_deadcycles: default_max_deadcycles(),
output_routine: None,
}
}
@@ -1972,6 +1981,7 @@ impl Engine {
top_skip: document.top_skip,
max_depth: document.max_depth,
output_penalty: page_penalties.get(index).copied().unwrap_or(10_000),
max_deadcycles: document.max_deadcycles,
insertion_counts,
insertion_dimens,
insertion_skips,
@@ -1979,7 +1989,15 @@ impl Engine {
deadcycles,
prev_graf: page_prev_graf(&page),
};
let shipped_now = program.shipout_count(&mut context).ok()?;
let forced = deadcycles >= document.max_deadcycles.max(0);
if forced {
context.deadcycles = 0;
}
let shipped_now = if forced {
1
} else {
program.shipout_count(&mut context).ok()?
};
insertion_counts = context.insertion_counts;
insertion_dimens = context.insertion_dimens;
insertion_skips = context.insertion_skips;
@@ -2162,6 +2180,7 @@ impl Engine {
top_skip: document.top_skip,
max_depth: document.max_depth,
output_penalty: fragment.penalty,
max_deadcycles: document.max_deadcycles,
insertion_counts,
insertion_dimens,
insertion_skips,
@@ -2169,7 +2188,15 @@ impl Engine {
pageno,
deadcycles,
};
let shipped = program.shipout_count(&mut context).ok()?;
let forced = deadcycles >= document.max_deadcycles.max(0);
if forced {
context.deadcycles = 0;
}
let shipped = if forced {
1
} else {
program.shipout_count(&mut context).ok()?
};
insertion_counts = context.insertion_counts;
insertion_dimens = context.insertion_dimens;
insertion_skips = context.insertion_skips;
@@ -6015,6 +6042,35 @@ mod tests {
assert_eq!(item_height(&engine.pages()[0].items[0]), 70 * pt);
}
#[test]
fn max_deadcycles_forces_a_page_out() {
let document_with = |limit: i64| {
let mut document = Document::new(
100,
vec![
Unit::rule(1, 10, 90),
Unit::penalty(2, -10_000),
Unit::rule(3, 10, 90),
Unit::penalty(4, -10_000),
Unit::rule(5, 10, 90),
Unit::penalty(6, -10_000),
Unit::rule(7, 10, 90),
],
);
document.output_routine = Some(r"\relax".into());
document.max_deadcycles = limit;
document
};
// With the default limit no page is ever shipped.
let idle = Engine::layout_paged(&document_with(25)).expect("paged layout");
assert_eq!(idle.pages().len(), 0);
// After two dead cycles TeX ships the third page itself, then the
// fourth page starts a fresh dead cycle and is dropped too.
let forced = Engine::layout_paged(&document_with(2)).expect("paged layout");
assert_eq!(forced.pages().len(), 1);
assert_eq!(item_height(&forced.pages()[0].items[0]), 90);
}
#[test]
fn output_register_assignments_persist_across_pages() {
let mut document = Document::new(
+22 -2
View File
@@ -42,6 +42,9 @@ pub struct OutputContext {
pub pageno: i64,
/// TeX `\deadcycles`: output routines since the last shipout.
pub deadcycles: i64,
/// TeX `\maxdeadcycles`: dead cycles allowed before TeX ships the
/// page itself.
pub max_deadcycles: i64,
/// TeX `\prevgraf`: lines in the paragraph most recently broken.
pub prev_graf: i64,
/// TeX `\count<n>` for insertion class `n`: the insertion multiplier.
@@ -69,6 +72,7 @@ impl Default for OutputContext {
output_penalty: 0,
pageno: 0,
deadcycles: 0,
max_deadcycles: 25,
prev_graf: 0,
// TeX's default insertion multiplier is 1000.
insertion_counts: [1000; 256],
@@ -231,6 +235,7 @@ enum Integer {
enum IntegerRegister {
PageNo,
DeadCycles,
MaxDeadCycles,
OutputPenalty,
PrevGraf,
InsertionCount(u8),
@@ -243,6 +248,7 @@ impl Integer {
Self::Register(register) => match register {
IntegerRegister::PageNo => context.pageno,
IntegerRegister::DeadCycles => context.deadcycles,
IntegerRegister::MaxDeadCycles => context.max_deadcycles,
IntegerRegister::OutputPenalty => context.output_penalty,
IntegerRegister::PrevGraf => context.prev_graf,
IntegerRegister::InsertionCount(class) => context.insertion_counts[class as usize],
@@ -420,12 +426,13 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
}
ops.push(Op::Message(text));
}
"pageno" | "deadcycles" | "outputpenalty" | "count" | "dimen" | "skip"
| "vsize" => {
"pageno" | "deadcycles" | "maxdeadcycles" | "outputpenalty" | "count" | "dimen"
| "skip" | "vsize" => {
*index += 1;
let (integer_register, dimension_register) = match name.as_str() {
"pageno" => (Some(IntegerRegister::PageNo), None),
"deadcycles" => (Some(IntegerRegister::DeadCycles), None),
"maxdeadcycles" => (Some(IntegerRegister::MaxDeadCycles), None),
"outputpenalty" => (Some(IntegerRegister::OutputPenalty), None),
"count" => {
let class = parse_insertion_class(tokens, index, "\\count", false)?;
@@ -591,6 +598,7 @@ fn parse_integer(tokens: &[Token], index: &mut usize) -> Result<Integer, String>
let register = match name.as_str() {
"pageno" => IntegerRegister::PageNo,
"deadcycles" => IntegerRegister::DeadCycles,
"maxdeadcycles" => IntegerRegister::MaxDeadCycles,
"outputpenalty" => IntegerRegister::OutputPenalty,
"prevgraf" => IntegerRegister::PrevGraf,
"count" => {
@@ -773,6 +781,7 @@ fn execute(ops: &[Op], context: &mut OutputContext, shipped: &mut usize) -> Resu
match register {
IntegerRegister::PageNo => context.pageno = value,
IntegerRegister::DeadCycles => context.deadcycles = value,
IntegerRegister::MaxDeadCycles => context.max_deadcycles = value,
IntegerRegister::OutputPenalty => context.output_penalty = value,
IntegerRegister::PrevGraf => context.prev_graf = value,
IntegerRegister::InsertionCount(class) => {
@@ -820,6 +829,7 @@ mod tests {
output_penalty: 0,
pageno: 1,
deadcycles: 0,
max_deadcycles: 25,
prev_graf: 0,
..OutputContext::default()
}
@@ -979,6 +989,16 @@ mod tests {
assert_eq!(program.shipout_count(&mut context).unwrap(), 1);
}
#[test]
fn maxdeadcycles_is_readable_and_assignable() {
let program =
OutputProgram::parse(r"\ifnum\maxdeadcycles=25\shipout\box255\fi\maxdeadcycles=3")
.unwrap();
let mut context = context(10);
assert_eq!(program.shipout_count(&mut context).unwrap(), 1);
assert_eq!(context.max_deadcycles, 3);
}
#[test]
fn ifnum_reads_negative_output_penalty() {
let program =
+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\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`). 440 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 442 workspace tests are green and no oracle
fixture is ignored.
Known gaps, in dependency order:
+3 -3
View File
@@ -125,7 +125,7 @@ and justification.
| --- | --- | --- |
| 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, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures |
| 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; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets later pages when the document has no insertions or floats), `\ht255` and `\dp255` expose the page box height and depth to the routine, insertion class registers `\count<n>`/`\dimen<n>`/`\skip<n>` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments for the duration of the routine, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine |
| 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; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets later pages when the document has no insertions or floats), `\ht255` and `\dp255` expose the page box height and depth to the routine, insertion class registers `\count<n>`/`\dimen<n>`/`\skip<n>` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments for the duration of the routine, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine |
| 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 |
@@ -347,7 +347,7 @@ M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` be
M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. A standalone `\smallskip`, `\medskip`, `\bigskip` or `\vskip` line between paragraphs becomes the following unit's `space_before` glue, carrying TeX's width plus its `plus`/`minus` parts (`\smallskip` is 3pt plus 1pt minus 1pt, and so on). Both page builders reserve it, the paged builder gets a real breakpoint with the glue's stretch and shrink, and edits preserve all three components; the command no longer leaks into the paragraph text. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and
preview pages apply the same offsets to their display list so the editor and
PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: five page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, and a 30pt `\topskip`) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`.
PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance`, `\pretolerance`, `\hangindent`/`\hangafter`, `\spaceskip`/`\xspaceskip` and `\frenchspacing` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty`, `\deadcycles` and `\maxdeadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: five page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, and a 30pt `\topskip`) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`.
M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved.
@@ -355,7 +355,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 289 unit tests plus seven route-D integration tests and twenty-seven oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 440 tests (294 route-D unit, 7 route-D integration, 27 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 11 binary units), with none ignored. v1 remains the live server path.
The crate currently has 296 unit tests plus seven route-D integration tests and twenty-seven oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 442 tests (296 route-D unit, 7 route-D integration, 27 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 11 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo