//! 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`, //! `\pagedepth`, `\pagestretch`, `\pageshrink`, `\vsize`, `\topskip`, //! `\maxdepth`, the insertion registers `\count`/`\dimen`/`\skip`, //! and assignments such as `\pageno=1` or `\count2=2000`. 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, Debug, 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 `\pagedepth`: the depth of the page box so far. pub page_depth: i64, /// TeX `\pagestretch`: stretch of the vertical glue so far. pub page_stretch: i64, /// TeX `\pagefilstretch`: stretch of `\vfil` glue on the page. pub page_fil_stretch: i64, /// TeX `\pagefillstretch`: stretch of `\vfill` glue on the page. pub page_fill_stretch: i64, /// TeX `\pagefilllstretch`: stretch of `\vfilll` glue on the page. pub page_filll_stretch: i64, /// TeX `\pageshrink`: shrink of the vertical glue so far. pub page_shrink: i64, /// TeX `\vbadness`: badness of the break that produced the page. pub vbadness: i64, /// TeX `\hsize`: width of the page box handed to the output routine. pub hsize: 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, /// TeX `\maxdeadcycles`: dead cycles allowed before TeX ships the /// page itself. pub max_deadcycles: i64, /// TeX `\prevgraf`: lines in the paragraph most recently broken. pub prev_graf: i64, /// TeX `\insertpenalties`: insertion items held over from the page. pub insert_penalties: i64, /// TeX `\count` for insertion class `n`: the insertion multiplier. pub insertion_counts: [i64; 256], /// TeX `\dimen` for insertion class `n`: the class' maximum size. pub insertion_dimens: [i64; 256], /// TeX `\skip` for insertion class `n`. pub insertion_skips: [i64; 256], /// `\mark{...}`/`\marks{...}` texts written by the routine; they /// reach later pages with their class. pub output_marks: Vec<(u8, String)>, } 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, hsize: 0, vbadness: 0, vsize: 0, top_skip: 0, max_depth: 0, output_penalty: 0, pageno: 0, deadcycles: 0, max_deadcycles: 25, prev_graf: 0, insert_penalties: 0, // TeX's default insertion multiplier is 1000. insertion_counts: [1000; 256], insertion_dimens: [0; 256], insertion_skips: [0; 256], output_marks: Vec::new(), } } } /// 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 }) } /// True when the routine assigns `\vsize`, so later page goals change. pub fn assigns_vsize(&self) -> bool { fn scan(ops: &[Op]) -> bool { ops.iter().any(|op| match op { Op::AssignDimension { register: Register::Vsize, .. } => true, Op::Arithmetic { target: ArithmeticTarget::Dimension(Register::Vsize), .. } => true, Op::IfDim { then_ops, else_ops, .. } | Op::IfNum { then_ops, else_ops, .. } | Op::IfOdd { then_ops, else_ops, .. } => scan(then_ops) || scan(else_ops), Op::IfCase { branches, else_ops, .. } => branches.iter().any(|branch| scan(branch)) || scan(else_ops), _ => false, }) } scan(&self.ops) } /// Execute the program for one page and return how many times it called /// `\shipout`. pub fn shipout_count(&self, context: &mut 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), Mark { class: u8, text: 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, }, IfCase { value: Integer, branches: Vec>, else_ops: Vec, }, AssignInteger { register: IntegerRegister, value: Integer, }, AssignDimension { register: Register, value: Dimension, }, Arithmetic { target: ArithmeticTarget, operation: ArithmeticOp, operand: ArithmeticOperand, }, } /// The target of a TeX register arithmetic command in the output program. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ArithmeticTarget { Integer(IntegerRegister), Dimension(Register), } /// TeX's arithmetic commands on registers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ArithmeticOp { Advance, Multiply, Divide, } /// Operand of an arithmetic command. #[derive(Clone, Debug, PartialEq, Eq)] enum ArithmeticOperand { Integer(Integer), Dimension(Dimension), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Dimension { Constant(i64), Register(Register), } /// Parse the register named by `name` as an arithmetic target. fn parse_arithmetic_target( tokens: &[Token], index: &mut usize, name: &str, ) -> Result { match name { "pageno" => Ok(ArithmeticTarget::Integer(IntegerRegister::PageNo)), "deadcycles" => Ok(ArithmeticTarget::Integer(IntegerRegister::DeadCycles)), "maxdeadcycles" => Ok(ArithmeticTarget::Integer(IntegerRegister::MaxDeadCycles)), "outputpenalty" => Ok(ArithmeticTarget::Integer(IntegerRegister::OutputPenalty)), "prevgraf" => Ok(ArithmeticTarget::Integer(IntegerRegister::PrevGraf)), "count" => { let class = parse_insertion_class(tokens, index, "\\count", false)?; Ok(ArithmeticTarget::Integer(IntegerRegister::InsertionCount( class, ))) } "dimen" => { let class = parse_insertion_class(tokens, index, "\\dimen", true)?; Ok(ArithmeticTarget::Dimension(Register::InsertionDimen(class))) } "skip" => { let class = parse_insertion_class(tokens, index, "\\skip", true)?; Ok(ArithmeticTarget::Dimension(Register::InsertionSkip(class))) } "hsize" => Ok(ArithmeticTarget::Dimension(Register::Hsize)), "vsize" => Ok(ArithmeticTarget::Dimension(Register::Vsize)), other => Err(format!("unsupported arithmetic target \\{other}")), } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Register { PageGoal, PageTotal, PageDepth, PageStretch, PageFilStretch, PageFillStretch, PageFilllStretch, PageShrink, /// TeX `\ht255`: height of the page box handed to the output routine. BoxHeight255, /// TeX `\dp255`: depth of the page box handed to the output routine. BoxDepth255, /// TeX `\wd255`: width of the page box handed to the output routine. BoxWidth255, Vsize, TopSkip, MaxDepth, Hsize, InsertionDimen(u8), InsertionSkip(u8), } 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::PageDepth => context.page_depth, Register::PageStretch => context.page_stretch, Register::PageFilStretch => context.page_fil_stretch, Register::PageFillStretch => context.page_fill_stretch, Register::PageFilllStretch => context.page_filll_stretch, Register::PageShrink => context.page_shrink, Register::BoxHeight255 => context.page_total, Register::BoxDepth255 => context.page_depth, Register::BoxWidth255 => context.hsize, Register::Vsize => context.vsize, Register::TopSkip => context.top_skip, Register::MaxDepth => context.max_depth, Register::Hsize => context.hsize, Register::InsertionDimen(class) => context.insertion_dimens[class as usize], Register::InsertionSkip(class) => context.insertion_skips[class as usize], }, } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Integer { Constant(i64), Register(IntegerRegister), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum IntegerRegister { PageNo, DeadCycles, MaxDeadCycles, VBadness, InsertPenalties, OutputPenalty, PrevGraf, InsertionCount(u8), } 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::MaxDeadCycles => context.max_deadcycles, IntegerRegister::OutputPenalty => context.output_penalty, IntegerRegister::PrevGraf => context.prev_graf, IntegerRegister::VBadness => context.vbadness, IntegerRegister::InsertPenalties => context.insert_penalties, IntegerRegister::InsertionCount(class) => context.insertion_counts[class as usize], }, } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Relation { Less, Greater, Equal, } #[derive(Clone, Debug, PartialEq)] enum Token { Command(String), /// A bare alphabetic word, such as TeX's `by` keyword. Word(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::Word(word) => write!(formatter, "{word}"), 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_alphabetic() => { let start = index; while index < chars.len() && chars[index].is_ascii_alphabetic() { index += 1; } tokens.push(Token::Word(chars[start..index].iter().collect())); } _ 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}`"))?; // Only a real TeX dimension unit belongs to the number. A following word // (such as `by` in `\advance\pageno by 2`) must stay a separate token, // even when TeX allows a space between the number and its unit. let after_number = *index; 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 candidate: String = chars[unit_start..*index].iter().collect(); let unit = if is_dimension_unit(&candidate) { Some(candidate) } else { *index = after_number; None }; Ok(Token::Number { value: if negative { -value } else { value }, unit, }) } fn is_dimension_unit(unit: &str) -> bool { matches!( unit, "pt" | "pc" | "in" | "bp" | "cm" | "mm" | "dd" | "cc" | "sp" | "em" | "ex" | "mu" ) } 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; let text = read_braced(tokens, index, "\\message")?; ops.push(Op::Message(text)); } "mark" | "marks" => { *index += 1; let class = if name == "mark" { 0_u8 } else { let class = match tokens.get(*index) { Some(Token::Number { value, unit: None }) => value.round() as i64, _ => return Err("\\marks expects a class number".to_owned()), }; *index += 1; if !(0..=255).contains(&class) { return Err("\\marks class must be between 0 and 255".to_owned()); } class as u8 }; let text = read_braced(tokens, index, "\\mark")?; ops.push(Op::Mark { class, text }); } "advance" | "multiply" | "divide" => { *index += 1; let register_name = match tokens.get(*index) { Some(Token::Command(register)) => register.clone(), _ => return Err(format!("\\{name} expects a register")), }; *index += 1; let target = parse_arithmetic_target(tokens, index, ®ister_name)?; if matches!(tokens.get(*index), Some(Token::Word(word)) if word == "by") { *index += 1; } let operand = match target { ArithmeticTarget::Integer(_) => { ArithmeticOperand::Integer(parse_integer(tokens, index)?) } ArithmeticTarget::Dimension(_) if name.as_str() == "advance" => { ArithmeticOperand::Dimension(parse_dimension(tokens, index)?) } ArithmeticTarget::Dimension(_) => { ArithmeticOperand::Integer(parse_integer(tokens, index)?) } }; let operation = match name.as_str() { "advance" => ArithmeticOp::Advance, "multiply" => ArithmeticOp::Multiply, _ => ArithmeticOp::Divide, }; ops.push(Op::Arithmetic { target, operation, operand, }); } "pageno" | "deadcycles" | "maxdeadcycles" | "outputpenalty" | "count" | "dimen" | "skip" | "vsize" => { *index += 1; let (integer_register, dimension_register) = match name.as_str() { "pageno" => (Some(IntegerRegister::PageNo), None), "deadcycles" => (Some(IntegerRegister::DeadCycles), None), "maxdeadcycles" => (Some(IntegerRegister::MaxDeadCycles), None), "outputpenalty" => (Some(IntegerRegister::OutputPenalty), None), "count" => { let class = parse_insertion_class(tokens, index, "\\count", false)?; (Some(IntegerRegister::InsertionCount(class)), None) } "dimen" => { let class = parse_insertion_class(tokens, index, "\\dimen", true)?; (None, Some(Register::InsertionDimen(class))) } "vsize" => (None, Some(Register::Vsize)), _ => { let class = parse_insertion_class(tokens, index, "\\skip", true)?; (None, Some(Register::InsertionSkip(class))) } }; expect_assignment(tokens, index, name)?; if let Some(register) = integer_register { let value = parse_integer(tokens, index)?; ops.push(Op::AssignInteger { register, value }); } else if let Some(register) = dimension_register { let value = parse_dimension(tokens, index)?; ops.push(Op::AssignDimension { register, value }); } } "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, }); } "ifcase" => { *index += 1; let value = parse_integer(tokens, index)?; let mut branches = vec![parse_sequence(tokens, index, &["or", "else", "fi"])?]; while let Some(Token::Command(name)) = tokens.get(*index) && name == "or" { *index += 1; branches.push(parse_sequence(tokens, index, &["or", "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("\\ifcase is missing \\fi".to_owned()), } ops.push(Op::IfCase { value, branches, 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 expect_assignment(tokens: &[Token], index: &mut usize, command: &str) -> Result<(), String> { match tokens.get(*index) { Some(Token::Relation('=')) => { *index += 1; Ok(()) } _ => Err(format!("\\{command} expects an assignment")), } } 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, "maxdeadcycles" => IntegerRegister::MaxDeadCycles, "outputpenalty" => IntegerRegister::OutputPenalty, "prevgraf" => IntegerRegister::PrevGraf, "vbadness" => IntegerRegister::VBadness, "insertpenalties" => IntegerRegister::InsertPenalties, "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; Integer::Register(register) } _ => return Err("expected an integer or integer register".to_owned()), }; Ok(integer) } /// Reads the box number after `\\ht`/`\\dp`; only box 255 is modelled. fn expect_box_255(tokens: &[Token], index: &mut usize, name: &str) -> Result<(), String> { match tokens.get(*index) { Some(Token::Number { value, unit }) if *value == 255.0 && unit.is_none() => { *index += 1; Ok(()) } _ => Err(format!("{name} only supports box 255")), } } 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, "pagedepth" => Register::PageDepth, "pagestretch" => Register::PageStretch, "pagefilstretch" => Register::PageFilStretch, "pagefillstretch" => Register::PageFillStretch, "pagefilllstretch" => Register::PageFilllStretch, "pageshrink" => Register::PageShrink, "ht" => { *index += 1; expect_box_255(tokens, index, "\\ht")?; return Ok(Dimension::Register(Register::BoxHeight255)); } "dp" => { *index += 1; expect_box_255(tokens, index, "\\dp")?; return Ok(Dimension::Register(Register::BoxDepth255)); } "wd" => { *index += 1; expect_box_255(tokens, index, "\\wd")?; return Ok(Dimension::Register(Register::BoxWidth255)); } "hsize" => Register::Hsize, "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; Dimension::Register(register) } _ => return Err("expected a dimension or page register".to_owned()), }; Ok(dimension) } fn parse_insertion_class( tokens: &[Token], index: &mut usize, command: &str, allow_zero: bool, ) -> Result { 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 read_braced(tokens: &[Token], index: &mut usize, name: &str) -> Result { if !matches!(tokens.get(*index), Some(Token::Open)) { return Err(format!("{name} expects a braced argument")); } *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; } } } Ok(text) } fn execute(ops: &[Op], context: &mut OutputContext, shipped: &mut usize) -> Result<(), String> { for op in ops { match op { Op::Shipout => *shipped += 1, Op::Relax | Op::Message(_) => {} Op::Mark { class, text } => { context.output_marks.push((*class, text.clone())); } 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::IfCase { value, branches, else_ops, } => { let value = value.resolve(context); let branch: &[Op] = if value >= 0 { branches .get(value as usize) .map(|branch| branch.as_slice()) .unwrap_or(else_ops.as_slice()) } else { else_ops.as_slice() }; execute(branch, 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)?; } Op::Arithmetic { target, operation, operand, } => { let operand_value = match operand { ArithmeticOperand::Integer(value) => value.resolve(context), ArithmeticOperand::Dimension(value) => value.resolve(context), }; match target { ArithmeticTarget::Integer(register) => { let value = apply_arithmetic( read_integer(context, *register), operand_value, *operation, ); write_integer(context, *register, value); } ArithmeticTarget::Dimension(register) => { let value = apply_arithmetic( Dimension::Register(*register).resolve(context), operand_value, *operation, ); write_dimension(context, *register, value)?; } } } Op::AssignInteger { register, value } => { let value = value.resolve(context); write_integer(context, *register, value); } Op::AssignDimension { register, value } => { let value = value.resolve(context); write_dimension(context, *register, value)?; } } } Ok(()) } fn read_integer(context: &OutputContext, register: IntegerRegister) -> i64 { match register { IntegerRegister::PageNo => context.pageno, IntegerRegister::DeadCycles => context.deadcycles, IntegerRegister::MaxDeadCycles => context.max_deadcycles, IntegerRegister::OutputPenalty => context.output_penalty, IntegerRegister::PrevGraf => context.prev_graf, IntegerRegister::VBadness => context.vbadness, IntegerRegister::InsertPenalties => context.insert_penalties, IntegerRegister::InsertionCount(class) => context.insertion_counts[class as usize], } } fn write_integer(context: &mut OutputContext, register: IntegerRegister, value: i64) { match register { IntegerRegister::PageNo => context.pageno = value, IntegerRegister::DeadCycles => context.deadcycles = value, IntegerRegister::MaxDeadCycles => context.max_deadcycles = value, IntegerRegister::OutputPenalty => context.output_penalty = value, IntegerRegister::PrevGraf => context.prev_graf = value, IntegerRegister::InsertionCount(class) => { context.insertion_counts[class as usize] = value; } // Read-only for the output routine: the parser never assigns them. IntegerRegister::VBadness | IntegerRegister::InsertPenalties => {} } } fn write_dimension( context: &mut OutputContext, register: Register, value: i64, ) -> Result<(), String> { match register { Register::InsertionDimen(class) => { context.insertion_dimens[class as usize] = value; } Register::InsertionSkip(class) => { context.insertion_skips[class as usize] = value; } Register::Vsize => context.vsize = value, Register::BoxWidth255 | Register::Hsize => context.hsize = value, other => return Err(format!("cannot assign to page register {other:?}")), } Ok(()) } fn apply_arithmetic(current: i64, operand: i64, operation: ArithmeticOp) -> i64 { match operation { ArithmeticOp::Advance => current.saturating_add(operand), ArithmeticOp::Multiply => current.saturating_mul(operand), ArithmeticOp::Divide => { if operand == 0 { current } else { current / operand } } } } #[cfg(test)] mod tests { use super::*; fn context(page_total: i64) -> OutputContext { OutputContext { page_goal: 612 * 65_536, page_total, page_depth: 0, page_stretch: 0, page_fil_stretch: 0, page_fill_stretch: 0, page_filll_stretch: 0, page_shrink: 0, vsize: 612 * 65_536, top_skip: 10 * 65_536, max_depth: 0, output_penalty: 0, pageno: 1, deadcycles: 0, max_deadcycles: 25, prev_graf: 0, ..OutputContext::default() } } #[test] fn ships_the_page_box() { let program = OutputProgram::parse(r"\shipout\box255").unwrap(); assert_eq!(program.shipout_count(&mut context(0)).unwrap(), 1); } #[test] fn page_stretch_and_shrink_are_visible() { let program = OutputProgram::parse(r"\ifdim\pagestretch>9pt\shipout\box255\fi").unwrap(); let mut stretched = context(0); stretched.page_stretch = 10 * 65_536; assert_eq!(program.shipout_count(&mut stretched).unwrap(), 1); assert_eq!(program.shipout_count(&mut context(0)).unwrap(), 0); let shrink = OutputProgram::parse(r"\ifdim\pageshrink>9pt\shipout\box255\fi").unwrap(); let mut shrunk = context(0); shrunk.page_shrink = 10 * 65_536; assert_eq!(shrink.shipout_count(&mut shrunk).unwrap(), 1); assert_eq!(shrink.shipout_count(&mut context(0)).unwrap(), 0); } #[test] fn fill_stretch_registers_are_visible() { let program = OutputProgram::parse(r"\ifdim\pagefilstretch>9pt\shipout\box255\fi").unwrap(); let mut context = context(0); context.page_fil_stretch = 10 * 65_536; assert_eq!(program.shipout_count(&mut context).unwrap(), 1); assert_eq!(program.shipout_count(&mut self::context(0)).unwrap(), 0); let fill = OutputProgram::parse(r"\ifdim\pagefillstretch>4pt\shipout\box255\fi").unwrap(); let mut context = self::context(0); context.page_fill_stretch = 5 * 65_536; assert_eq!(fill.shipout_count(&mut context).unwrap(), 1); let filll = OutputProgram::parse(r"\ifdim\pagefilllstretch>4pt\shipout\box255\fi").unwrap(); let mut context = self::context(0); context.page_filll_stretch = 5 * 65_536; assert_eq!(filll.shipout_count(&mut context).unwrap(), 1); } #[test] fn page_depth_register_is_visible() { let program = OutputProgram::parse(r"\ifdim\pagedepth>4pt\shipout\box255\fi").unwrap(); let mut deep = context(0); deep.page_depth = 5 * 65_536; assert_eq!(program.shipout_count(&mut deep).unwrap(), 1); assert_eq!(program.shipout_count(&mut context(0)).unwrap(), 0); } #[test] fn output_routine_can_assign_vsize() { let mut context = context(0); let program = OutputProgram::parse(r"\vsize=300pt\ifdim\vsize>200pt\shipout\box255\fi").unwrap(); assert!(program.assigns_vsize()); assert_eq!(program.shipout_count(&mut context).unwrap(), 1); assert_eq!(context.vsize, 300 * 65_536); let plain = OutputProgram::parse(r"\shipout\box255").unwrap(); assert!(!plain.assigns_vsize()); } #[test] fn output_routine_sees_prevgraf() { let mut context = context(0); context.prev_graf = 4; let program = OutputProgram::parse(r"\ifnum\prevgraf=4\pageno=9\fi").unwrap(); assert_eq!(program.shipout_count(&mut context).unwrap(), 0); assert_eq!(context.pageno, 9); let copy = OutputProgram::parse(r"\pageno=\prevgraf").unwrap(); let mut context = self::context(0); context.prev_graf = 6; copy.shipout_count(&mut context).unwrap(); assert_eq!(context.pageno, 6); } #[test] fn output_routine_reads_hsize_and_the_page_box_width() { let program = OutputProgram::parse( "\\ifdim\\hsize=480pt\\shipout\\box255\\fi\\ifdim\\wd255=480pt\\shipout\\box255\\fi", ) .unwrap(); let mut context = context(10 * 65_536); context.hsize = 480 * 65_536; assert_eq!(program.shipout_count(&mut context).unwrap(), 2); } #[test] fn output_routine_can_assign_registers() { let mut context = context(0); context.pageno = 7; let program = OutputProgram::parse(r"\pageno=3\ifnum\pageno=3\shipout\box255\fi").unwrap(); assert_eq!(program.shipout_count(&mut context).unwrap(), 1); assert_eq!(context.pageno, 3); let counts = OutputProgram::parse(r"\count2=1500\ifnum\count2=1000\shipout\box255\fi").unwrap(); let mut context = self::context(0); assert_eq!(counts.shipout_count(&mut context).unwrap(), 0); assert_eq!(context.insertion_counts[2], 1500); let skip = OutputProgram::parse(r"\skip2=5pt\ifdim\skip2>4pt\shipout\box255\fi").unwrap(); let mut context = self::context(0); assert_eq!(skip.shipout_count(&mut context).unwrap(), 1); assert_eq!(context.insertion_skips[2], 5 * 65_536); } #[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(&mut context).unwrap(), 1); assert_eq!(count.shipout_count(&mut self::context(0)).unwrap(), 0); let dimen = OutputProgram::parse(r"\ifdim\dimen1>6pt\shipout\box255\fi").unwrap(); assert_eq!(dimen.shipout_count(&mut context).unwrap(), 1); let skip = OutputProgram::parse(r"\ifdim\skip1<4pt\shipout\box255\fi").unwrap(); assert_eq!(skip.shipout_count(&mut context).unwrap(), 1); let pageno = OutputProgram::parse(r"\ifnum\count0=1\shipout\box255\fi").unwrap(); assert_eq!(pageno.shipout_count(&mut context).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(&mut context(40 * 65_536)).unwrap(), 0); assert_eq!(program.shipout_count(&mut 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(&mut small).unwrap(), 1); assert_eq!(program.shipout_count(&mut 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(&mut context(0)).unwrap(), 0); let mut small_page = context(0); small_page.page_goal = 500 * 65_536; assert_eq!(program.shipout_count(&mut 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(&mut context).unwrap(), 0); context.pageno = 2; assert_eq!(program.shipout_count(&mut context).unwrap(), 1); } #[test] fn arithmetic_commands_mutate_registers() { let program = OutputProgram::parse( r"\advance\pageno by 2 \multiply\pageno by 3 \divide\deadcycles by 2 \advance\dimen2 by 5pt \advance\pageno by \count3 \shipout\box255", ) .unwrap(); let mut context = context(0); context.deadcycles = 8; context.insertion_counts[3] = 6; let shipped = program.shipout_count(&mut context).unwrap(); assert_eq!(shipped, 1); assert_eq!(context.pageno, 15); assert_eq!(context.deadcycles, 4); assert_eq!(context.insertion_dimens[2], 5 * 65_536); } #[test] fn maxdeadcycles_is_readable_and_assignable() { let program = OutputProgram::parse(r"\ifnum\maxdeadcycles=25\shipout\box255\fi\maxdeadcycles=3") .unwrap(); let mut context = context(10); assert_eq!(program.shipout_count(&mut context).unwrap(), 1); assert_eq!(context.max_deadcycles, 3); } #[test] fn ifnum_reads_negative_output_penalty() { let program = OutputProgram::parse(r"\ifnum\outputpenalty<-9999\shipout\box255\fi").unwrap(); let mut context = context(0); assert_eq!(program.shipout_count(&mut context).unwrap(), 0); let mut forced = context; forced.output_penalty = -10_000; assert_eq!(program.shipout_count(&mut forced).unwrap(), 1); } #[test] fn ifnum_recognises_glue_break_penalties() { let program = OutputProgram::parse(r"\ifnum\outputpenalty=10000\shipout\box255\fi").unwrap(); let mut context = context(0); context.output_penalty = 10_000; assert_eq!(program.shipout_count(&mut context).unwrap(), 1); context.output_penalty = 150; assert_eq!(program.shipout_count(&mut context).unwrap(), 0); } #[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(&mut context).unwrap(), 1); context.pageno = 2; assert_eq!(program.shipout_count(&mut context).unwrap(), 0); } #[test] fn ifcase_selects_a_branch_or_the_else_clause() { let program = OutputProgram::parse(r"\ifcase\pageno\relax\or\shipout\box255\else\relax\fi").unwrap(); let mut context = context(0); context.pageno = 1; assert_eq!(program.shipout_count(&mut context).unwrap(), 1); context.pageno = 0; assert_eq!(program.shipout_count(&mut context).unwrap(), 0); context.pageno = 5; assert_eq!(program.shipout_count(&mut 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()); } }