Ship pages conditionally on parity in the output routine

This commit is contained in:
gloamxun committed 2026-10-23 03:08:19 +08:00
1 parent a2a2eafab5
commit 7964765605
5 files changed
+66 -9

No files matched your search

+13
View File
@@ -4896,6 +4896,19 @@ mod tests {
assert_eq!(engine.pages().len(), 1);
}
#[test]
fn interpreted_output_can_ship_only_odd_pages() {
let mut document = Document::new(100, Vec::new());
document.output_routine = Some(r"\ifodd\pageno\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(
+44
View File
@@ -74,6 +74,11 @@ enum Op {
then_ops: Vec<Op>,
else_ops: Vec<Op>,
},
IfOdd {
value: Integer,
then_ops: Vec<Op>,
else_ops: Vec<Op>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -351,6 +356,27 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
else_ops,
});
}
"ifodd" => {
*index += 1;
let value = 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("\\ifodd is missing \\fi".to_owned()),
}
ops.push(Op::IfOdd {
value,
then_ops,
else_ops,
});
}
other => return Err(format!("unsupported \\output command `\\{other}`")),
},
token => return Err(format!("unexpected token {token:?}")),
@@ -465,6 +491,14 @@ fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(
};
execute(if taken { then_ops } else { else_ops }, context, shipped)?;
}
Op::IfOdd {
value,
then_ops,
else_ops,
} => {
let odd = value.resolve(context).rem_euclid(2) == 1;
execute(if odd { then_ops } else { else_ops }, context, shipped)?;
}
}
}
Ok(())
@@ -540,6 +574,16 @@ mod tests {
assert_eq!(program.shipout_count(&forced).unwrap(), 1);
}
#[test]
fn ifodd_ships_even_page_numbers_only() {
let program = OutputProgram::parse(r"\ifodd\pageno\shipout\box255\else\relax\fi").unwrap();
let mut context = context(0);
context.pageno = 1;
assert_eq!(program.shipout_count(&context).unwrap(), 1);
context.pageno = 2;
assert_eq!(program.shipout_count(&context).unwrap(), 0);
}
#[test]
fn unsupported_commands_and_unbalanced_conditionals_are_errors() {
assert!(OutputProgram::parse(r"\vbox{}").is_err());