Read insertion class registers in the output routine

This commit is contained in:
gloamxun committed 2026-10-23 12:28:09 +08:00
1 parent 72f5436318
commit c2ba59906c
3 files changed
+145 -3

No files matched your search

+39
View File
@@ -1873,6 +1873,15 @@ impl Engine {
let mut shipped = Vec::new();
for (index, page) in pages.into_iter().enumerate() {
let page_total: i64 = page.items.iter().map(item_height).sum();
let mut insertion_counts = [1000_i64; 256];
let mut insertion_dimens = [0_i64; 256];
let mut insertion_skips = [0_i64; 256];
for class in &document.insertion_classes {
let slot = class.number as usize;
insertion_counts[slot] = i64::from(class.multiplier);
insertion_dimens[slot] = class.max_height.unwrap_or(0);
insertion_skips[slot] = class.skip.unwrap_or(document.insertion_skip);
}
let context = output::OutputContext {
page_goal: page_goals.get(index).copied().unwrap_or(document.page_goal),
page_total,
@@ -1886,6 +1895,9 @@ impl Engine {
top_skip: document.top_skip,
max_depth: document.max_depth,
output_penalty: page_penalties.get(index).copied().unwrap_or(0),
insertion_counts,
insertion_dimens,
insertion_skips,
pageno: index as i64 + 1,
deadcycles: 0,
};
@@ -5389,6 +5401,33 @@ mod tests {
assert_eq!(engine.pages().len(), 1);
}
#[test]
fn output_routine_reads_insertion_registers() {
let mut document = Document::new(100, vec![Unit::rule(0, 10, 40)]);
document.insertion_classes = vec![InsertionClass {
number: 1,
fraction_percent: 100,
max_height: Some(7 * 65_536),
skip: Some(3 * 65_536),
multiplier: 2000,
}];
document.output_routine =
Some(r"\ifnum\count1=2000\shipout\box255\else\relax\fi".to_owned());
let engine = Engine::layout_paged(&document).expect("paged");
assert_eq!(engine.pages().len(), 1);
document.output_routine =
Some(r"\ifdim\dimen1>6pt\shipout\box255\else\relax\fi".to_owned());
let engine = Engine::layout_paged(&document).expect("paged");
assert_eq!(engine.pages().len(), 1);
document.output_routine =
Some(r"\ifnum\count1=1000\shipout\box255\else\relax\fi".to_owned());
let engine = Engine::layout_paged(&document).expect("paged");
assert_eq!(engine.pages().len(), 0);
}
#[test]
fn interpreted_output_can_ship_only_odd_pages() {
let mut document = Document::new(100, Vec::new());
+104 -1
View File
@@ -10,7 +10,7 @@
use std::fmt;
/// Page registers visible to the output routine.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutputContext {
/// TeX `\pagegoal`: the goal the current page was built for.
pub page_goal: i64,
@@ -40,6 +40,37 @@ pub struct OutputContext {
pub pageno: i64,
/// TeX `\deadcycles`: output routines since the last shipout.
pub deadcycles: i64,
/// TeX `\count<n>` for insertion class `n`: the insertion multiplier.
pub insertion_counts: [i64; 256],
/// TeX `\dimen<n>` for insertion class `n`: the class' maximum size.
pub insertion_dimens: [i64; 256],
/// TeX `\skip<n>` for insertion class `n`.
pub insertion_skips: [i64; 256],
}
impl Default for OutputContext {
fn default() -> Self {
Self {
page_goal: 0,
page_total: 0,
page_depth: 0,
page_stretch: 0,
page_fil_stretch: 0,
page_fill_stretch: 0,
page_filll_stretch: 0,
page_shrink: 0,
vsize: 0,
top_skip: 0,
max_depth: 0,
output_penalty: 0,
pageno: 0,
deadcycles: 0,
// TeX's default insertion multiplier is 1000.
insertion_counts: [1000; 256],
insertion_dimens: [0; 256],
insertion_skips: [0; 256],
}
}
}
/// A parsed `\output` program.
@@ -118,6 +149,8 @@ enum Register {
Vsize,
TopSkip,
MaxDepth,
InsertionDimen(u8),
InsertionSkip(u8),
}
impl Dimension {
@@ -136,6 +169,8 @@ impl Dimension {
Register::Vsize => context.vsize,
Register::TopSkip => context.top_skip,
Register::MaxDepth => context.max_depth,
Register::InsertionDimen(class) => context.insertion_dimens[class as usize],
Register::InsertionSkip(class) => context.insertion_skips[class as usize],
},
}
}
@@ -152,6 +187,7 @@ enum IntegerRegister {
PageNo,
DeadCycles,
OutputPenalty,
InsertionCount(u8),
}
impl Integer {
@@ -162,6 +198,7 @@ impl Integer {
IntegerRegister::PageNo => context.pageno,
IntegerRegister::DeadCycles => context.deadcycles,
IntegerRegister::OutputPenalty => context.output_penalty,
IntegerRegister::InsertionCount(class) => context.insertion_counts[class as usize],
},
}
}
@@ -468,6 +505,18 @@ fn parse_integer(tokens: &[Token], index: &mut usize) -> Result<Integer, String>
"pageno" => IntegerRegister::PageNo,
"deadcycles" => IntegerRegister::DeadCycles,
"outputpenalty" => IntegerRegister::OutputPenalty,
"count" => {
*index += 1;
if matches!(
tokens.get(*index),
Some(Token::Number { value, unit: None }) if value.round() as i64 == 0
) {
*index += 1;
return Ok(Integer::Register(IntegerRegister::PageNo));
}
let class = parse_insertion_class(tokens, index, "\\count", false)?;
return Ok(Integer::Register(IntegerRegister::InsertionCount(class)));
}
other => return Err(format!("unsupported integer register `\\{other}`")),
};
*index += 1;
@@ -507,6 +556,16 @@ fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result<Dimension, Str
"vsize" => Register::Vsize,
"topskip" => Register::TopSkip,
"maxdepth" => Register::MaxDepth,
"dimen" => {
*index += 1;
let class = parse_insertion_class(tokens, index, "\\dimen", true)?;
return Ok(Dimension::Register(Register::InsertionDimen(class)));
}
"skip" => {
*index += 1;
let class = parse_insertion_class(tokens, index, "\\skip", true)?;
return Ok(Dimension::Register(Register::InsertionSkip(class)));
}
other => return Err(format!("unsupported page register `\\{other}`")),
};
*index += 1;
@@ -517,6 +576,28 @@ fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result<Dimension, Str
Ok(dimension)
}
fn parse_insertion_class(
tokens: &[Token],
index: &mut usize,
command: &str,
allow_zero: bool,
) -> Result<u8, String> {
match tokens.get(*index) {
Some(Token::Number { value, unit: None }) => {
let class = value.round() as i64;
let lowest = if allow_zero { 0 } else { 1 };
if !(lowest..=255).contains(&class) {
return Err(format!(
"`{command}` needs an insertion class number between {lowest} and 255"
));
}
*index += 1;
Ok(class as u8)
}
_ => Err(format!("`{command}` needs an insertion class number")),
}
}
fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(), String> {
for op in ops {
match op {
@@ -603,6 +684,7 @@ mod tests {
output_penalty: 0,
pageno: 1,
deadcycles: 0,
..OutputContext::default()
}
}
@@ -655,6 +737,27 @@ mod tests {
assert_eq!(program.shipout_count(&context(0)).unwrap(), 0);
}
#[test]
fn insertion_registers_are_visible() {
let mut context = context(0);
context.insertion_counts[1] = 2000;
context.insertion_dimens[1] = 7 * 65_536;
context.insertion_skips[1] = 3 * 65_536;
let count = OutputProgram::parse(r"\ifnum\count1=2000\shipout\box255\fi").unwrap();
assert_eq!(count.shipout_count(&context).unwrap(), 1);
assert_eq!(count.shipout_count(&self::context(0)).unwrap(), 0);
let dimen = OutputProgram::parse(r"\ifdim\dimen1>6pt\shipout\box255\fi").unwrap();
assert_eq!(dimen.shipout_count(&context).unwrap(), 1);
let skip = OutputProgram::parse(r"\ifdim\skip1<4pt\shipout\box255\fi").unwrap();
assert_eq!(skip.shipout_count(&context).unwrap(), 1);
let pageno = OutputProgram::parse(r"\ifnum\count0=1\shipout\box255\fi").unwrap();
assert_eq!(pageno.shipout_count(&context).unwrap(), 1);
}
#[test]
fn conditional_ships_only_large_pages() {
let program = OutputProgram::parse(r"\ifdim\pagetotal>50pt\shipout\box255\fi").unwrap();
+2 -2
View File
@@ -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`, `\raggedright` (infinite `\rightskip`), `\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 (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` and a `\bottomfraction` cap) 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 registers, `PageFragment::penalty` carries the break penalty, 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` and a `\bottomfraction` cap) 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 registers, insertion class registers `\count<n>`/`\dimen<n>`/`\skip<n>` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`), `PageFragment::penalty` carries the break penalty, 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 |
@@ -346,7 +346,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 267 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 391 tests (267 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
The crate currently has 269 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 393 tests (269 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo