From 61cef7d16c5199d70a55d0cec210cfc4c70d4754 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 03:10:55 +0800 Subject: [PATCH] Select output routine branches with ifcase --- crates/texrra-tex-core/src/output.rs | 61 ++++++++++++++++++++++++++++ docs/ROUTE_D_PLAN.md | 6 +-- docs/TEX_CORE.md | 10 ++--- 3 files changed, 69 insertions(+), 8 deletions(-) diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs index 6f38ddf..8ea2096 100644 --- a/crates/texrra-tex-core/src/output.rs +++ b/crates/texrra-tex-core/src/output.rs @@ -79,6 +79,11 @@ enum Op { then_ops: Vec, else_ops: Vec, }, + IfCase { + value: Integer, + branches: Vec>, + else_ops: Vec, + }, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -377,6 +382,33 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result< else_ops, }); } + "ifcase" => { + *index += 1; + let value = parse_integer(tokens, index)?; + let mut branches = vec![parse_sequence(tokens, index, &["or", "else", "fi"])?]; + while let Some(Token::Command(name)) = tokens.get(*index) + && name == "or" + { + *index += 1; + branches.push(parse_sequence(tokens, index, &["or", "else", "fi"])?); + } + let mut else_ops = Vec::new(); + if let Some(Token::Command(name)) = tokens.get(*index) + && name == "else" + { + *index += 1; + else_ops = parse_sequence(tokens, index, &["fi"])?; + } + match tokens.get(*index) { + Some(Token::Command(name)) if name == "fi" => *index += 1, + _ => return Err("\\ifcase is missing \\fi".to_owned()), + } + ops.push(Op::IfCase { + value, + branches, + else_ops, + }); + } other => return Err(format!("unsupported \\output command `\\{other}`")), }, token => return Err(format!("unexpected token {token:?}")), @@ -491,6 +523,22 @@ fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<( }; execute(if taken { then_ops } else { else_ops }, context, shipped)?; } + Op::IfCase { + value, + branches, + else_ops, + } => { + let value = value.resolve(context); + let branch: &[Op] = if value >= 0 { + branches + .get(value as usize) + .map(|branch| branch.as_slice()) + .unwrap_or(else_ops.as_slice()) + } else { + else_ops.as_slice() + }; + execute(branch, context, shipped)?; + } Op::IfOdd { value, then_ops, @@ -584,6 +632,19 @@ mod tests { assert_eq!(program.shipout_count(&context).unwrap(), 0); } + #[test] + fn ifcase_selects_a_branch_or_the_else_clause() { + let program = + OutputProgram::parse(r"\ifcase\pageno\relax\or\shipout\box255\else\relax\fi").unwrap(); + let mut context = context(0); + context.pageno = 1; + assert_eq!(program.shipout_count(&context).unwrap(), 1); + context.pageno = 0; + assert_eq!(program.shipout_count(&context).unwrap(), 0); + context.pageno = 5; + assert_eq!(program.shipout_count(&context).unwrap(), 0); + } + #[test] fn unsupported_commands_and_unbalanced_conditionals_are_errors() { assert!(OutputProgram::parse(r"\vbox{}").is_err()); diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 3f6100f..8d915cb 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -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`). 351 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 352 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -268,7 +268,7 @@ dimension assignments from the source. Insertion classes are placed by the paged builder with their limits and held-over material; floats and checkpoint replay still fall back to the scrolling builder, which stays the default until it has a paged equivalent. Next: port those paths and paper margins, then extend the `\output` -interpreter past the shipout/ifdim/ifnum/ifodd subset. +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. @@ -411,7 +411,7 @@ Acceptance: corpus green or explicitly listed; CI documented. | goal | phases | deliverable | | --- | --- | --- | -| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` (shipout/ifdim/ifnum/ifodd subset landed) | +| 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) | diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 3e4dcb0..2e07c16 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -116,7 +116,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`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` 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; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty | +| 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, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty | | 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 | @@ -324,7 +324,7 @@ M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments. -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 eight unit tests, and 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); `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. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies them. `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` and `\ifodd` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Floats and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent. +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 eight unit tests, and 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); `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. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies them. `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. Floats and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent. 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. @@ -332,7 +332,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 233 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 351 tests (233 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 234 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 352 tests (234 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -371,11 +371,11 @@ deliberately open rather than approximated: stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it for simple documents, but floats and incremental replay need a paged equivalent before it can become the default; paper margins remain open, and - the `\output` interpreter only covers the shipout/ifdim/ifnum/ifodd subset (explicit + the `\output` interpreter only covers the shipout/ifdim/ifnum/ifodd/ifcase subset (explicit `\hoffset`/`\voffset` offsets are applied by the PDF writer). - **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; `Document::output_routine` is interpreted per page by `output::OutputProgram` for the shipout/ifdim/ifnum/ifodd subset (with `\pageno`, `\outputpenalty`, `\deadcycles`), while `OutputRoutine` remains the Rust hook. + 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; `Document::output_routine` is interpreted per page by `output::OutputProgram` for the shipout/ifdim/ifnum/ifodd/ifcase subset (with `\pageno`, `\outputpenalty`, `\deadcycles`), while `OutputRoutine` remains the Rust hook. - Page hashes cover rendered items/insertions/marks/floats, not source-dependency metadata, so replaying an earlier page cannot change its hash merely by re-attaching source hashes.