Interpret the output routine shipout and ifdim subset

This commit is contained in:
gloamxun committed 2026-10-23 02:59:54 +08:00
1 parent 6cf8221ba7
commit 4bec90cf8c
5 files changed
+496 -20

No files matched your search

+406
View File
@@ -0,0 +1,406 @@
//! 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,
}
/// A parsed `\output` program.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OutputProgram {
ops: Vec<Op>,
}
impl OutputProgram {
pub fn parse(source: &str) -> Result<Self, String> {
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<usize, String> {
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<Op>,
else_ops: Vec<Op>,
},
}
#[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 Relation {
Less,
Greater,
Equal,
}
#[derive(Clone, Debug, PartialEq)]
enum Token {
Command(String),
Number { value: f64, unit: Option<String> },
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<Vec<Token>, String> {
let chars: Vec<char> = 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 == '.' => {
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 });
}
other => return Err(format!("unexpected character `{other}`")),
}
}
Ok(tokens)
}
fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<Vec<Op>, 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 = 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 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,
});
}
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_dimension(tokens: &[Token], index: &mut usize) -> Result<Dimension, String> {
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)?;
}
}
}
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,
}
}
#[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 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());
}
}