Interpret the output routine shipout and ifdim subset
This commit is contained in:
1 parent
6cf8221ba7
commit
4bec90cf8c
5 files changed
+496
-20
No files matched your search
@@ -1,5 +1,6 @@
|
||||
pub mod cmr10;
|
||||
pub mod math;
|
||||
pub mod output;
|
||||
pub mod page;
|
||||
pub mod paragraph;
|
||||
pub mod pdf;
|
||||
@@ -623,6 +624,10 @@ pub struct Document {
|
||||
/// Extra vertical displacement of the page origin (`\voffset`).
|
||||
#[serde(default)]
|
||||
pub v_offset: i64,
|
||||
/// TeX `\output` token list, interpreted by [`output::OutputProgram`].
|
||||
/// `None` ships every page the builder produces.
|
||||
#[serde(default)]
|
||||
pub output_routine: Option<String>,
|
||||
}
|
||||
|
||||
fn default_text_fraction() -> u8 {
|
||||
@@ -683,6 +688,7 @@ impl Document {
|
||||
par_skip: 0,
|
||||
h_offset: 0,
|
||||
v_offset: 0,
|
||||
output_routine: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1722,6 +1728,24 @@ impl Engine {
|
||||
page.seal_in_place();
|
||||
pages.push(page);
|
||||
}
|
||||
if let Some(source) = &document.output_routine {
|
||||
let program = output::OutputProgram::parse(source).ok()?;
|
||||
let mut shipped = Vec::new();
|
||||
for page in pages {
|
||||
let page_total: i64 = page.items.iter().map(item_height).sum();
|
||||
let context = output::OutputContext {
|
||||
page_goal: document.page_goal,
|
||||
page_total,
|
||||
vsize: document.page_goal,
|
||||
top_skip: document.top_skip,
|
||||
max_depth: document.max_depth,
|
||||
};
|
||||
if program.shipout_count(&context).ok()? > 0 {
|
||||
shipped.push(page);
|
||||
}
|
||||
}
|
||||
pages = shipped;
|
||||
}
|
||||
let count = pages.len();
|
||||
Some(Self {
|
||||
layout: Layout {
|
||||
@@ -5039,6 +5063,48 @@ mod tests {
|
||||
assert!(layout.pages()[1].items.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreted_output_can_drop_pages() {
|
||||
let mut document = Document::new(
|
||||
100,
|
||||
vec![
|
||||
Unit::rule(1, 80, 40),
|
||||
Unit::penalty(2, -10_000),
|
||||
Unit::rule(3, 80, 80),
|
||||
],
|
||||
);
|
||||
document.output_routine = Some(r"\ifdim\pagetotal>50\shipout\box255\fi".to_owned());
|
||||
let layout = Engine::layout_paged(&document).expect("output routine is page-buildable");
|
||||
assert_eq!(layout.pages().len(), 1);
|
||||
assert_eq!(layout.pages()[0].items.len(), 1);
|
||||
match &layout.pages()[0].items[0] {
|
||||
VerticalItem::Rule { height, .. } => assert_eq!(*height, 80),
|
||||
other => panic!("unexpected item {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreted_output_ships_every_page_when_asked_to() {
|
||||
let mut document = Document::new(
|
||||
100,
|
||||
vec![
|
||||
Unit::rule(1, 80, 40),
|
||||
Unit::penalty(2, -10_000),
|
||||
Unit::rule(3, 80, 80),
|
||||
],
|
||||
);
|
||||
document.output_routine = Some(r"\shipout\box255".to_owned());
|
||||
let layout = Engine::layout_paged(&document).expect("output routine is page-buildable");
|
||||
assert_eq!(layout.pages().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_output_routines_fall_back_to_the_scrolling_builder() {
|
||||
let mut document = Document::new(100, vec![Unit::rule(1, 80, 40)]);
|
||||
document.output_routine = Some(r"\vbox{}".to_owned());
|
||||
assert!(Engine::layout_paged(&document).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paged_layout_edit_relayouts_and_reports_changes() {
|
||||
let style = ParagraphStyle {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user