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

+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());