Read output penalty and page number in the output routine

This commit is contained in:
gloamxun committed 2026-10-23 03:04:58 +08:00
1 parent 4bec90cf8c
commit a2a2eafab5
6 files changed
+243 -47

No files matched your search

+33 -1
View File
@@ -1649,6 +1649,7 @@ impl Engine {
.collect(),
};
let mut pages = Vec::new();
let mut page_penalties = Vec::new();
let mut held: BTreeMap<u8, Vec<VerticalItem>> = BTreeMap::new();
for fragment in builder.build(&nodes) {
let mut items = Vec::new();
@@ -1705,6 +1706,7 @@ impl Engine {
page.sources = sources;
page.seal_in_place();
pages.push(page);
page_penalties.push(fragment.penalty);
}
// Insertion material that did not fit its class limit on the page where
@@ -1727,11 +1729,12 @@ impl Engine {
page.insertions = insertions.into_values().collect();
page.seal_in_place();
pages.push(page);
page_penalties.push(0);
}
if let Some(source) = &document.output_routine {
let program = output::OutputProgram::parse(source).ok()?;
let mut shipped = Vec::new();
for page in pages {
for (index, page) in pages.into_iter().enumerate() {
let page_total: i64 = page.items.iter().map(item_height).sum();
let context = output::OutputContext {
page_goal: document.page_goal,
@@ -1739,6 +1742,9 @@ impl Engine {
vsize: document.page_goal,
top_skip: document.top_skip,
max_depth: document.max_depth,
output_penalty: page_penalties.get(index).copied().unwrap_or(0),
pageno: index as i64 + 1,
deadcycles: 0,
};
if program.shipout_count(&context).ok()? > 0 {
shipped.push(page);
@@ -4864,6 +4870,32 @@ mod tests {
assert!(engine.pages().iter().all(|page| page.hash != 0));
}
#[test]
fn interpreted_output_sees_the_break_penalty() {
let mut document = Document::new(100, Vec::new());
document.output_routine = Some(r"\ifnum\outputpenalty<-9999\shipout\box255\fi".to_owned());
document.units = vec![
Unit::rule(0, 10, 40),
Unit::penalty(1, -10_000),
Unit::rule(2, 10, 40),
];
let engine = Engine::layout_paged(&document).expect("paged layout");
assert_eq!(engine.pages().len(), 1);
}
#[test]
fn interpreted_output_reads_the_page_number() {
let mut document = Document::new(100, Vec::new());
document.output_routine = Some(r"\ifnum\pageno>1\shipout\box255\fi".to_owned());
document.units = vec![
Unit::rule(0, 10, 40),
Unit::penalty(1, -10_000),
Unit::rule(2, 10, 40),
];
let engine = Engine::layout_paged(&document).expect("paged layout");
assert_eq!(engine.pages().len(), 1);
}
#[test]
fn paged_layout_expands_vertical_units() {
let document = Document::new(
+173 -30
View File
@@ -21,6 +21,12 @@ pub struct OutputContext {
pub top_skip: i64,
/// TeX `\maxdepth`.
pub max_depth: i64,
/// TeX `\outputpenalty`: the penalty at which the page broke.
pub output_penalty: i64,
/// One-based number of the page being considered.
pub pageno: i64,
/// TeX `\deadcycles`: output routines since the last shipout.
pub deadcycles: i64,
}
/// A parsed `\output` program.
@@ -61,6 +67,13 @@ enum Op {
then_ops: Vec<Op>,
else_ops: Vec<Op>,
},
IfNum {
left: Integer,
relation: Relation,
right: Integer,
then_ops: Vec<Op>,
else_ops: Vec<Op>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -93,6 +106,32 @@ impl Dimension {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Integer {
Constant(i64),
Register(IntegerRegister),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum IntegerRegister {
PageNo,
DeadCycles,
OutputPenalty,
}
impl Integer {
fn resolve(self, context: &OutputContext) -> i64 {
match self {
Self::Constant(value) => value,
Self::Register(register) => match register {
IntegerRegister::PageNo => context.pageno,
IntegerRegister::DeadCycles => context.deadcycles,
IntegerRegister::OutputPenalty => context.output_penalty,
},
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Relation {
Less,
@@ -161,29 +200,14 @@ fn lex(source: &str) -> Result<Vec<Token>, String> {
index += 1;
}
_ if character.is_ascii_digit() || character == '.' => {
let start = index;
while index < chars.len() && chars[index].is_ascii_digit() {
index += 1;
}
if index < chars.len() && chars[index] == '.' {
index += 1;
while index < chars.len() && chars[index].is_ascii_digit() {
index += 1;
}
}
let number: String = chars[start..index].iter().collect();
let value: f64 = number
.parse()
.map_err(|_| format!("invalid number `{number}`"))?;
while index < chars.len() && chars[index].is_ascii_whitespace() {
index += 1;
}
let unit_start = index;
while index < chars.len() && chars[index].is_ascii_alphabetic() {
index += 1;
}
let unit = (unit_start < index).then(|| chars[unit_start..index].iter().collect());
tokens.push(Token::Number { value, unit });
tokens.push(lex_number(&chars, &mut index, false)?);
}
'-' if chars
.get(index + 1)
.is_some_and(|next| next.is_ascii_digit() || *next == '.') =>
{
index += 1;
tokens.push(lex_number(&chars, &mut index, true)?);
}
other => return Err(format!("unexpected character `{other}`")),
}
@@ -191,6 +215,35 @@ fn lex(source: &str) -> Result<Vec<Token>, String> {
Ok(tokens)
}
fn lex_number(chars: &[char], index: &mut usize, negative: bool) -> Result<Token, String> {
let start = *index;
while *index < chars.len() && chars[*index].is_ascii_digit() {
*index += 1;
}
if *index < chars.len() && chars[*index] == '.' {
*index += 1;
while *index < chars.len() && chars[*index].is_ascii_digit() {
*index += 1;
}
}
let number: String = chars[start..*index].iter().collect();
let value: f64 = number
.parse()
.map_err(|_| format!("invalid number `{number}`"))?;
while *index < chars.len() && chars[*index].is_ascii_whitespace() {
*index += 1;
}
let unit_start = *index;
while *index < chars.len() && chars[*index].is_ascii_alphabetic() {
*index += 1;
}
let unit = (unit_start < *index).then(|| chars[unit_start..*index].iter().collect());
Ok(Token::Number {
value: if negative { -value } else { value },
unit,
})
}
fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<Vec<Op>, String> {
let mut ops = Vec::new();
while *index < tokens.len() {
@@ -251,13 +304,7 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
"ifdim" => {
*index += 1;
let left = parse_dimension(tokens, index)?;
let relation = match tokens.get(*index) {
Some(Token::Relation('<')) => Relation::Less,
Some(Token::Relation('>')) => Relation::Greater,
Some(Token::Relation('=')) => Relation::Equal,
_ => return Err("\\ifdim expects <, > or =".to_owned()),
};
*index += 1;
let relation = parse_relation(tokens, index, "ifdim")?;
let right = parse_dimension(tokens, index)?;
let then_ops = parse_sequence(tokens, index, &["else", "fi"])?;
let mut else_ops = Vec::new();
@@ -279,6 +326,31 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
else_ops,
});
}
"ifnum" => {
*index += 1;
let left = parse_integer(tokens, index)?;
let relation = parse_relation(tokens, index, "ifnum")?;
let right = parse_integer(tokens, index)?;
let then_ops = parse_sequence(tokens, index, &["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("\\ifnum is missing \\fi".to_owned()),
}
ops.push(Op::IfNum {
left,
relation,
right,
then_ops,
else_ops,
});
}
other => return Err(format!("unsupported \\output command `\\{other}`")),
},
token => return Err(format!("unexpected token {token:?}")),
@@ -291,6 +363,38 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
}
}
fn parse_relation(tokens: &[Token], index: &mut usize, command: &str) -> Result<Relation, String> {
let relation = match tokens.get(*index) {
Some(Token::Relation('<')) => Relation::Less,
Some(Token::Relation('>')) => Relation::Greater,
Some(Token::Relation('=')) => Relation::Equal,
_ => return Err(format!("\\{command} expects <, > or =")),
};
*index += 1;
Ok(relation)
}
fn parse_integer(tokens: &[Token], index: &mut usize) -> Result<Integer, String> {
let integer = match tokens.get(*index) {
Some(Token::Number { value, unit: None }) => {
*index += 1;
Integer::Constant(value.round() as i64)
}
Some(Token::Command(name)) => {
let register = match name.as_str() {
"pageno" => IntegerRegister::PageNo,
"deadcycles" => IntegerRegister::DeadCycles,
"outputpenalty" => IntegerRegister::OutputPenalty,
other => return Err(format!("unsupported integer register `\\{other}`")),
};
*index += 1;
Integer::Register(register)
}
_ => return Err("expected an integer or integer register".to_owned()),
};
Ok(integer)
}
fn parse_dimension(tokens: &[Token], index: &mut usize) -> Result<Dimension, String> {
let dimension = match tokens.get(*index) {
Some(Token::Number { value, unit }) => {
@@ -345,6 +449,22 @@ fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(
};
execute(if taken { then_ops } else { else_ops }, context, shipped)?;
}
Op::IfNum {
left,
relation,
right,
then_ops,
else_ops,
} => {
let left = left.resolve(context);
let right = right.resolve(context);
let taken = match relation {
Relation::Less => left < right,
Relation::Greater => left > right,
Relation::Equal => left == right,
};
execute(if taken { then_ops } else { else_ops }, context, shipped)?;
}
}
}
Ok(())
@@ -361,6 +481,9 @@ mod tests {
vsize: 612 * 65_536,
top_skip: 10 * 65_536,
max_depth: 0,
output_penalty: 0,
pageno: 1,
deadcycles: 0,
}
}
@@ -397,6 +520,26 @@ mod tests {
assert_eq!(program.shipout_count(&small_page).unwrap(), 1);
}
#[test]
fn ifnum_reads_page_and_penalty_registers() {
let program = OutputProgram::parse(r"\ifnum\pageno>1\shipout\box255\fi").unwrap();
let mut context = context(0);
assert_eq!(program.shipout_count(&context).unwrap(), 0);
context.pageno = 2;
assert_eq!(program.shipout_count(&context).unwrap(), 1);
}
#[test]
fn ifnum_reads_negative_output_penalty() {
let program =
OutputProgram::parse(r"\ifnum\outputpenalty<-9999\shipout\box255\fi").unwrap();
let context = context(0);
assert_eq!(program.shipout_count(&context).unwrap(), 0);
let mut forced = context;
forced.output_penalty = -10_000;
assert_eq!(program.shipout_count(&forced).unwrap(), 1);
}
#[test]
fn unsupported_commands_and_unbalanced_conditionals_are_errors() {
assert!(OutputProgram::parse(r"\vbox{}").is_err());
+20 -1
View File
@@ -70,6 +70,9 @@ pub struct PageFragment {
pub end: usize,
/// TeX's page cost for the breakpoint: badness plus penalty.
pub cost: i64,
/// Penalty that produced this break: a forced penalty value, the chosen
/// candidate's penalty, or zero for the final page.
pub penalty: i64,
/// Badness of the page height against the page goal.
pub badness: i64,
/// Height of the page box after glue setting.
@@ -89,6 +92,7 @@ struct Candidate {
depth: i64,
shrink: i64,
reserved: i64,
penalty: i64,
end: usize,
next: usize,
}
@@ -198,7 +202,8 @@ impl PageBuilder {
height,
depth,
badness,
badness + penalty,
badness + *penalty,
*penalty,
self.insertion_space(nodes, start, end, held),
);
return Some((
@@ -239,6 +244,7 @@ impl PageBuilder {
best.depth,
best.badness,
best.cost,
best.penalty,
self.insertion_space(nodes, start, best.end, held),
);
Some((
@@ -311,6 +317,7 @@ impl PageBuilder {
let badness = self.badness(height, reserved, stretch, shrink);
Candidate {
cost: badness + penalty,
penalty,
badness,
height,
depth,
@@ -352,12 +359,14 @@ impl PageBuilder {
depth: i64,
badness: i64,
cost: i64,
penalty: i64,
insertions: Vec<InsertionSpace>,
) -> PageFragment {
PageFragment {
start,
end,
cost,
penalty,
badness,
height,
depth,
@@ -400,6 +409,16 @@ mod tests {
VerticalNode::Glue(VerticalGlue::new(width, stretch, shrink))
}
#[test]
fn forced_penalty_breaks_record_the_penalty() {
let builder = PageBuilder::new(100);
let nodes = vec![box_(20, 0), VerticalNode::Penalty(-10_000), box_(20, 0)];
let pages = builder.build(&nodes);
assert_eq!(pages.len(), 2);
assert_eq!(pages[0].penalty, -10_000);
assert_eq!(pages[1].penalty, 0);
}
#[test]
fn breaks_before_the_page_overflows() {
let builder = PageBuilder::new(100);