diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index df79090..3428c98 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -3067,6 +3067,32 @@ mod tests { assert_eq!(counts, vec![3, 2, 2], "pages: {counts:?}"); } + #[test] + fn output_routine_can_advance_vsize_for_later_pages() { + let mut units = Vec::new(); + for n in 0..7 { + units.push(Unit::rule(n * 2, 300, 300)); + if n < 6 { + units.push(Unit::penalty(n * 2 + 1, 0)); + } + } + let mut document = Document::new(1000, units); + document.top_skip = 0; + document.output_routine = Some(r"\advance\vsize by -300 \shipout\box255".to_owned()); + let engine = Engine::layout_paged(&document).expect("paged"); + let counts = engine + .pages() + .iter() + .map(|page| { + page.items + .iter() + .filter(|item| matches!(item, VerticalItem::Rule { .. })) + .count() + }) + .collect::>(); + assert_eq!(counts, vec![3, 2, 1, 1], "pages: {counts:?}"); + } + #[test] fn output_routine_sees_page_goal_after_insertion_reservation() { let scale = 65_536; diff --git a/crates/texrra-tex-core/src/output.rs b/crates/texrra-tex-core/src/output.rs index ebcfb77..884a49e 100644 --- a/crates/texrra-tex-core/src/output.rs +++ b/crates/texrra-tex-core/src/output.rs @@ -107,6 +107,10 @@ impl OutputProgram { register: Register::Vsize, .. } => true, + Op::Arithmetic { + target: ArithmeticTarget::Dimension(Register::Vsize), + .. + } => true, Op::IfDim { then_ops, else_ops, .. } @@ -171,6 +175,33 @@ enum Op { register: Register, value: Dimension, }, + Arithmetic { + target: ArithmeticTarget, + operation: ArithmeticOp, + operand: ArithmeticOperand, + }, +} + +/// The target of a TeX register arithmetic command in the output program. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ArithmeticTarget { + Integer(IntegerRegister), + Dimension(Register), +} + +/// TeX's arithmetic commands on registers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ArithmeticOp { + Advance, + Multiply, + Divide, +} + +/// Operand of an arithmetic command. +#[derive(Clone, Debug, PartialEq, Eq)] +enum ArithmeticOperand { + Integer(Integer), + Dimension(Dimension), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -179,6 +210,37 @@ enum Dimension { Register(Register), } +/// Parse the register named by `name` as an arithmetic target. +fn parse_arithmetic_target( + tokens: &[Token], + index: &mut usize, + name: &str, +) -> Result { + match name { + "pageno" => Ok(ArithmeticTarget::Integer(IntegerRegister::PageNo)), + "deadcycles" => Ok(ArithmeticTarget::Integer(IntegerRegister::DeadCycles)), + "maxdeadcycles" => Ok(ArithmeticTarget::Integer(IntegerRegister::MaxDeadCycles)), + "outputpenalty" => Ok(ArithmeticTarget::Integer(IntegerRegister::OutputPenalty)), + "prevgraf" => Ok(ArithmeticTarget::Integer(IntegerRegister::PrevGraf)), + "count" => { + let class = parse_insertion_class(tokens, index, "\\count", false)?; + Ok(ArithmeticTarget::Integer(IntegerRegister::InsertionCount( + class, + ))) + } + "dimen" => { + let class = parse_insertion_class(tokens, index, "\\dimen", true)?; + Ok(ArithmeticTarget::Dimension(Register::InsertionDimen(class))) + } + "skip" => { + let class = parse_insertion_class(tokens, index, "\\skip", true)?; + Ok(ArithmeticTarget::Dimension(Register::InsertionSkip(class))) + } + "vsize" => Ok(ArithmeticTarget::Dimension(Register::Vsize)), + other => Err(format!("unsupported arithmetic target \\{other}")), + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Register { PageGoal, @@ -267,7 +329,12 @@ enum Relation { #[derive(Clone, Debug, PartialEq)] enum Token { Command(String), - Number { value: f64, unit: Option }, + /// A bare alphabetic word, such as TeX's `by` keyword. + Word(String), + Number { + value: f64, + unit: Option, + }, Open, Close, Relation(char), @@ -277,6 +344,7 @@ impl fmt::Display for Token { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Command(name) => write!(formatter, "\\{name}"), + Self::Word(word) => write!(formatter, "{word}"), Self::Number { value, unit } => match unit { Some(unit) => write!(formatter, "{value}{unit}"), None => write!(formatter, "{value}"), @@ -324,6 +392,13 @@ fn lex(source: &str) -> Result, String> { tokens.push(Token::Relation(character)); index += 1; } + _ if character.is_ascii_alphabetic() => { + let start = index; + while index < chars.len() && chars[index].is_ascii_alphabetic() { + index += 1; + } + tokens.push(Token::Word(chars[start..index].iter().collect())); + } _ if character.is_ascii_digit() || character == '.' => { tokens.push(lex_number(&chars, &mut index, false)?); } @@ -355,6 +430,10 @@ fn lex_number(chars: &[char], index: &mut usize, negative: bool) -> Result Result bool { + matches!( + unit, + "pt" | "pc" | "in" | "bp" | "cm" | "mm" | "dd" | "cc" | "sp" | "em" | "ex" | "mu" + ) +} + fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result, String> { let mut ops = Vec::new(); while *index < tokens.len() { @@ -426,6 +518,39 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result< } ops.push(Op::Message(text)); } + "advance" | "multiply" | "divide" => { + *index += 1; + let register_name = match tokens.get(*index) { + Some(Token::Command(register)) => register.clone(), + _ => return Err(format!("\\{name} expects a register")), + }; + *index += 1; + let target = parse_arithmetic_target(tokens, index, ®ister_name)?; + if matches!(tokens.get(*index), Some(Token::Word(word)) if word == "by") { + *index += 1; + } + let operand = match target { + ArithmeticTarget::Integer(_) => { + ArithmeticOperand::Integer(parse_integer(tokens, index)?) + } + ArithmeticTarget::Dimension(_) if name.as_str() == "advance" => { + ArithmeticOperand::Dimension(parse_dimension(tokens, index)?) + } + ArithmeticTarget::Dimension(_) => { + ArithmeticOperand::Integer(parse_integer(tokens, index)?) + } + }; + let operation = match name.as_str() { + "advance" => ArithmeticOp::Advance, + "multiply" => ArithmeticOp::Multiply, + _ => ArithmeticOp::Divide, + }; + ops.push(Op::Arithmetic { + target, + operation, + operand, + }); + } "pageno" | "deadcycles" | "maxdeadcycles" | "outputpenalty" | "count" | "dimen" | "skip" | "vsize" => { *index += 1; @@ -776,39 +901,103 @@ fn execute(ops: &[Op], context: &mut OutputContext, shipped: &mut usize) -> Resu let odd = value.resolve(context).rem_euclid(2) == 1; execute(if odd { then_ops } else { else_ops }, context, shipped)?; } - Op::AssignInteger { register, value } => { - let value = value.resolve(context); - 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) => { - context.insertion_counts[*class as usize] = value; + Op::Arithmetic { + target, + operation, + operand, + } => { + let operand_value = match operand { + ArithmeticOperand::Integer(value) => value.resolve(context), + ArithmeticOperand::Dimension(value) => value.resolve(context), + }; + match target { + ArithmeticTarget::Integer(register) => { + let value = apply_arithmetic( + read_integer(context, *register), + operand_value, + *operation, + ); + write_integer(context, *register, value); + } + ArithmeticTarget::Dimension(register) => { + let value = apply_arithmetic( + Dimension::Register(*register).resolve(context), + operand_value, + *operation, + ); + write_dimension(context, *register, value)?; } } } + Op::AssignInteger { register, value } => { + let value = value.resolve(context); + write_integer(context, *register, value); + } Op::AssignDimension { register, value } => { let value = value.resolve(context); - match register { - Register::InsertionDimen(class) => { - context.insertion_dimens[*class as usize] = value; - } - Register::InsertionSkip(class) => { - context.insertion_skips[*class as usize] = value; - } - Register::Vsize => context.vsize = value, - other => { - return Err(format!("cannot assign to page register {other:?}")); - } - } + write_dimension(context, *register, value)?; } } } Ok(()) } +fn read_integer(context: &OutputContext, register: IntegerRegister) -> i64 { + 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], + } +} + +fn write_integer(context: &mut OutputContext, register: IntegerRegister, value: i64) { + 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) => { + context.insertion_counts[class as usize] = value; + } + } +} + +fn write_dimension( + context: &mut OutputContext, + register: Register, + value: i64, +) -> Result<(), String> { + match register { + Register::InsertionDimen(class) => { + context.insertion_dimens[class as usize] = value; + } + Register::InsertionSkip(class) => { + context.insertion_skips[class as usize] = value; + } + Register::Vsize => context.vsize = value, + other => return Err(format!("cannot assign to page register {other:?}")), + } + Ok(()) +} + +fn apply_arithmetic(current: i64, operand: i64, operation: ArithmeticOp) -> i64 { + match operation { + ArithmeticOp::Advance => current.saturating_add(operand), + ArithmeticOp::Multiply => current.saturating_mul(operand), + ArithmeticOp::Divide => { + if operand == 0 { + current + } else { + current / operand + } + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -989,6 +1178,22 @@ mod tests { assert_eq!(program.shipout_count(&mut context).unwrap(), 1); } + #[test] + fn arithmetic_commands_mutate_registers() { + let program = OutputProgram::parse( + r"\advance\pageno by 2 \multiply\pageno by 3 \divide\deadcycles by 2 \advance\dimen2 by 5pt \advance\pageno by \count3 \shipout\box255", + ) + .unwrap(); + let mut context = context(0); + context.deadcycles = 8; + context.insertion_counts[3] = 6; + let shipped = program.shipout_count(&mut context).unwrap(); + assert_eq!(shipped, 1); + assert_eq!(context.pageno, 15); + assert_eq!(context.deadcycles, 4); + assert_eq!(context.insertion_dimens[2], 5 * 65_536); + } + #[test] fn maxdeadcycles_is_readable_and_assignable() { let program = diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 90547fa..e6a1e1a 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`). 452 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 454 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 3c9092a..e13eb97 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -353,7 +353,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. A `[t]` float seen while a page is already being filled is installed at the top of that same page, exactly as TeX's `\@toplist` does: the page height gains the float plus one `\textfloatsep` (or `\floatsep` between stacked floats), so the body stops earlier instead of the float waiting for the next page; only a break before the float moves it forward. `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`, `\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; Route-D sources map a standalone `\newpage` or `\clearpage` onto `Document::page_breaks`, so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); 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: nine page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears) 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; `\advance`, `\multiply` and `\divide` adjust those registers in place (`\advance\pageno by 2`, `\divide\deadcycles by 2`, `\advance\dimen2 by 5pt`), and an arithmetic `\vsize` change retargets later pages exactly like an assignment; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; Route-D sources map a standalone `\newpage` or `\clearpage` onto `Document::page_breaks`, so the next paragraph starts on a fresh page (the paged builder turns each break into a `-10000` penalty node); 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: nine page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, a 30pt `\topskip`, a forced `\newpage`, stretchy `\vskip` glue between paragraphs, footnotes raised with `\footnotetext`, and a `[t]` float that reserves its height plus `\textfloatsep` on the page it appears) 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. @@ -361,7 +361,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 298 unit tests plus seven route-D integration tests and thirty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 452 tests (298 route-D unit, 7 route-D integration, 32 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. +The crate currently has 300 unit tests plus seven route-D integration tests and thirty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 454 tests (300 route-D unit, 7 route-D integration, 32 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo