//! A small interpreter for TeX's `\output` token list. //! //! Only the subset that decides *which* page box leaves the page builder is //! supported today: `\shipout\box255`, `\relax`, `\message{...}` and //! `\ifdim` comparisons over the page registers `\pagegoal`, `\pagetotal`, //! `\vsize`, `\topskip` and `\maxdepth`. Anything else is a parse error, which //! makes `Engine::layout_paged` fall back to the scrolling builder. use std::fmt; /// Page registers visible to the output routine. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct OutputContext { /// TeX `\pagegoal`: the goal the current page was built for. pub page_goal: i64, /// TeX `\pagetotal`: the height accumulated on the current page. pub page_total: i64, /// TeX `\vsize`: the configured page height. pub vsize: i64, /// TeX `\topskip`. 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. #[derive(Clone, Debug, PartialEq, Eq)] pub struct OutputProgram { ops: Vec, } impl OutputProgram { pub fn parse(source: &str) -> Result { let tokens = lex(source)?; let mut index = 0; let ops = parse_sequence(&tokens, &mut index, &[])?; if index != tokens.len() { return Err(format!("unexpected token {:?}", tokens[index])); } Ok(Self { ops }) } /// Execute the program for one page and return how many times it called /// `\shipout`. pub fn shipout_count(&self, context: &OutputContext) -> Result { let mut shipped = 0; execute(&self.ops, context, &mut shipped)?; Ok(shipped) } } #[derive(Clone, Debug, PartialEq, Eq)] enum Op { Shipout, Relax, Message(String), IfDim { left: Dimension, relation: Relation, right: Dimension, then_ops: Vec, else_ops: Vec, }, IfNum { left: Integer, relation: Relation, right: Integer, then_ops: Vec, else_ops: Vec, }, IfOdd { value: Integer, then_ops: Vec, else_ops: Vec, }, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Dimension { Constant(i64), Register(Register), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Register { PageGoal, PageTotal, Vsize, TopSkip, MaxDepth, } impl Dimension { fn resolve(self, context: &OutputContext) -> i64 { match self { Self::Constant(value) => value, Self::Register(register) => match register { Register::PageGoal => context.page_goal, Register::PageTotal => context.page_total, Register::Vsize => context.vsize, Register::TopSkip => context.top_skip, Register::MaxDepth => context.max_depth, }, } } } #[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, Greater, Equal, } #[derive(Clone, Debug, PartialEq)] enum Token { Command(String), Number { value: f64, unit: Option }, Open, Close, Relation(char), } impl fmt::Display for Token { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Command(name) => write!(formatter, "\\{name}"), Self::Number { value, unit } => match unit { Some(unit) => write!(formatter, "{value}{unit}"), None => write!(formatter, "{value}"), }, Self::Open => write!(formatter, "{{"), Self::Close => write!(formatter, "}}"), Self::Relation(relation) => write!(formatter, "{relation}"), } } } fn lex(source: &str) -> Result, String> { let chars: Vec = source.chars().collect(); let mut tokens = Vec::new(); let mut index = 0; while index < chars.len() { let character = chars[index]; match character { ' ' | '\t' | '\n' | '\r' => index += 1, '%' => { while index < chars.len() && chars[index] != '\n' { index += 1; } } '\\' => { index += 1; let start = index; while index < chars.len() && chars[index].is_ascii_alphabetic() { index += 1; } if start == index { return Err("expected a control sequence after `\\`".to_owned()); } tokens.push(Token::Command(chars[start..index].iter().collect())); } '{' => { tokens.push(Token::Open); index += 1; } '}' => { tokens.push(Token::Close); index += 1; } '<' | '>' | '=' => { tokens.push(Token::Relation(character)); index += 1; } _ if character.is_ascii_digit() || character == '.' => { 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}`")), } } Ok(tokens) } fn lex_number(chars: &[char], index: &mut usize, negative: bool) -> Result { 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, String> { let mut ops = Vec::new(); while *index < tokens.len() { if let Token::Command(name) = &tokens[*index] && stop.contains(&name.as_str()) { return Ok(ops); } match &tokens[*index] { Token::Command(name) => match name.as_str() { "shipout" => { *index += 1; let boxed = match tokens.get(*index) { Some(Token::Command(box_command)) if box_command == "box" => { *index += 1; match tokens.get(*index) { Some(Token::Number { value, unit: None }) if (*value - 255.0).abs() < f64::EPSILON => { *index += 1; true } _ => false, } } _ => false, }; if !boxed { return Err("\\shipout expects \\box255".to_owned()); } ops.push(Op::Shipout); } "relax" => { *index += 1; ops.push(Op::Relax); } "message" => { *index += 1; if !matches!(tokens.get(*index), Some(Token::Open)) { return Err("\\message expects a braced argument".to_owned()); } *index += 1; let mut text = String::new(); while *index < tokens.len() { match &tokens[*index] { Token::Close => { *index += 1; break; } token => { text.push_str(&token.to_string()); *index += 1; } } } ops.push(Op::Message(text)); } "ifdim" => { *index += 1; let left = parse_dimension(tokens, index)?; 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(); 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("\\ifdim is missing \\fi".to_owned()), } ops.push(Op::IfDim { left, relation, right, then_ops, 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, }); } "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:?}")), } } if stop.is_empty() { Ok(ops) } else { Err(format!("expected one of {stop:?}")) } } fn parse_relation(tokens: &[Token], index: &mut usize, command: &str) -> Result { 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 { 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 { let dimension = match tokens.get(*index) { Some(Token::Number { value, unit }) => { let factor = match unit.as_deref() { None | Some("sp") => 1.0, Some("pt") => 65_536.0, Some("bp") => 65_782.0, Some("in") => 4_736_286.0, Some("cm") => 1_864_680.0, Some("mm") => 186_468.0, Some("pc") => 786_432.0, Some(other) => return Err(format!("unsupported unit `{other}`")), }; *index += 1; Dimension::Constant((value * factor).round() as i64) } Some(Token::Command(name)) => { let register = match name.as_str() { "pagegoal" => Register::PageGoal, "pagetotal" => Register::PageTotal, "vsize" => Register::Vsize, "topskip" => Register::TopSkip, "maxdepth" => Register::MaxDepth, other => return Err(format!("unsupported page register `\\{other}`")), }; *index += 1; Dimension::Register(register) } _ => return Err("expected a dimension or page register".to_owned()), }; Ok(dimension) } fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(), String> { for op in ops { match op { Op::Shipout => *shipped += 1, Op::Relax | Op::Message(_) => {} Op::IfDim { 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)?; } 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)?; } 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(()) } #[cfg(test)] mod tests { use super::*; fn context(page_total: i64) -> OutputContext { OutputContext { page_goal: 612 * 65_536, page_total, vsize: 612 * 65_536, top_skip: 10 * 65_536, max_depth: 0, output_penalty: 0, pageno: 1, deadcycles: 0, } } #[test] fn ships_the_page_box() { let program = OutputProgram::parse(r"\shipout\box255").unwrap(); assert_eq!(program.shipout_count(&context(0)).unwrap(), 1); } #[test] fn conditional_ships_only_large_pages() { let program = OutputProgram::parse(r"\ifdim\pagetotal>50pt\shipout\box255\fi").unwrap(); assert_eq!(program.shipout_count(&context(40 * 65_536)).unwrap(), 0); assert_eq!(program.shipout_count(&context(60 * 65_536)).unwrap(), 1); } #[test] fn else_branch_ships_small_pages() { let program = OutputProgram::parse(r"\ifdim\pagetotal>50pt\shipout\box255\else\shipout\box255\fi") .unwrap(); let mut small = context(40 * 65_536); small.page_total = 40 * 65_536; assert_eq!(program.shipout_count(&small).unwrap(), 1); assert_eq!(program.shipout_count(&context(70 * 65_536)).unwrap(), 1); } #[test] fn page_goal_register_is_visible() { let program = OutputProgram::parse(r"\ifdim\pagegoal<600pt\shipout\box255\fi").unwrap(); assert_eq!(program.shipout_count(&context(0)).unwrap(), 0); let mut small_page = context(0); small_page.page_goal = 500 * 65_536; 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 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()); assert!(OutputProgram::parse(r"\ifdim\pagetotal>1pt\shipout\box255").is_err()); assert!(OutputProgram::parse(r"\shipout").is_err()); } }