Files
texrra-engine/crates/texrra-tex-core/tests/execution_fractions.rs
T

681 lines
24 KiB
Rust

//! Native generalized fractions, with actual TeX lists and shipped effects.
#[path = "support/font_world.rs"]
mod font_world;
use std::{
fs,
process::Command,
sync::atomic::{AtomicU64, Ordering},
};
use texrra_tex_core::execution::*;
const FONTS: &str = include_str!("../../../examples/native-bootstrap/math-fonts.tex");
const SETUP: &str = r#"\catcode38=4\delcode`\(="028300\delcode`\)="029301\delcode`\.=0\newlinechar=-1\showboxbreadth=1000\showboxdepth=40 "#;
struct Host;
impl SourceProvider for Host {
font_world::font_resources!();
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
Err(format!("unexpected input {name}"))
}
}
fn directory() -> std::path::PathBuf {
static ID: AtomicU64 = AtomicU64::new(0);
let p = std::env::temp_dir().join(format!(
"texrra-fractions-{}-{}",
std::process::id(),
ID.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&p).unwrap();
p
}
fn markers(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = text;
while let Some(i) = rest.find("FRAC[") {
rest = &rest[i..];
let end = rest.find(';').unwrap() + 1;
out.push(rest[..end].into());
rest = &rest[end..];
}
out
}
fn compare(body: &str) -> Execution {
let p = directory();
let source = format!(
"{FONTS}{SETUP}{body}\\message{{FRAC[PACK]=\\number\\wd0,\\number\\ht0,\\number\\dp0,\\the\\badness;}}\\showbox0\\end\n"
);
fs::write(p.join("probe.tex"), &source).unwrap();
let reference = Command::new("pdftex")
.args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"])
.current_dir(&p)
.output()
.unwrap();
let log = fs::read_to_string(p.join("probe.log")).unwrap();
assert_eq!(reference.status.code(), Some(1), "{p:?}: {log}");
for line in log.lines().filter(|line| line.starts_with("! ")) {
assert_eq!(line, "! OK.", "{p:?}: {body}\n{log}");
}
let e = Executor::new(
State::initex().with_etex(),
Limits {
steps: 1_000_000,
..Limits::default()
},
)
.run(
SourceFile {
name: "probe.tex".into(),
data: source.into_bytes(),
},
&mut Host,
)
.unwrap_or_else(|error| panic!("{p:?}: {body}: {error}"));
fs::write(p.join("native.json"), serde_json::to_vec(&e).unwrap()).unwrap();
let actual: Vec<_> = e
.events
.iter()
.filter_map(|v| match v {
Event::Message { text, .. } => Some(markers(text)),
_ => None,
})
.flatten()
.collect();
assert_eq!(actual, markers(&log), "{p:?}: {body}");
let reports: Vec<_> = e
.events
.iter()
.filter_map(|v| match v {
Event::ShowBox(r) => Some(r),
_ => None,
})
.collect();
assert_eq!(reports.len(), 1);
assert!(
log.contains(&reports[0].text),
"{p:?}: {body}\nnative:\n{}\nreference:\n{log}",
reports[0].text
);
e
}
#[test]
fn generalized_fraction_styles_thickness_and_delimiters_match_real_pdftex_lists() {
for style in [
"displaystyle",
"textstyle",
"scriptstyle",
"scriptscriptstyle",
] {
for operation in [
r"\over",
r"\atop",
r"\above1pt",
r"\overwithdelims()",
r"\atopwithdelims()",
r"\abovewithdelims()3sp",
] {
for (upper, lower) in [("a", "b"), ("f", "gj"), ("", ""), ("x^{y}", "z_{g}")] {
compare(&format!(
r"\setbox0=\hbox{{$\{style}{{{upper}{operation} {lower}}}$}}"
));
}
}
}
}
#[test]
fn explicit_fraction_dimensions_live_parameters_and_nested_fields_match_pdftex() {
for thickness in ["0sp", "1sp", "2sp", "3sp", "-1sp", "-3sp", "-2pt", "7pt"] {
for style in [
"displaystyle",
"textstyle",
"scriptstyle",
"scriptscriptstyle",
] {
compare(&format!(
r"\setbox0=\hbox{{$\{style}{{f\abovewithdelims() {thickness} gj}}$}}"
));
}
}
for body in [
r"\setbox0=\hbox{$a+{b\over c}=d$}",
r"\setbox0=\hbox{$\left(a\over b\right)$}",
r"\setbox0=\hbox{$\left. a\abovewithdelims()1pt b\right)$}",
r"\setbox0=\hbox{${{a\over b}\over{c\atop d}}$}",
r"\setbox0=\hbox{${a\above1sp b}^{g}_{j}$}",
r"\setbox0=\hbox{${a\over{b\above3sp{c\over d}}}$}",
r"\setbox0=\hbox{${\hbox to20pt{A\hfil}\atop\vbox{\hbox{B}\hbox{C}}}$}",
r"\setbox0=\hbox{${\lower2pt\hbox{A}\above1pt\raise3pt\hbox{g}}$}",
r"\nulldelimiterspace=5pt\setbox0=\hbox{${a\over b}$}",
r"\fontdimen8\tenex=3sp\setbox0=\hbox{${a\over b}$}",
r"\fontdimen22\tensy=-3sp\fontdimen20\tensy=30pt\setbox0=\hbox{${a\overwithdelims() b}$}",
r"\let\fraction=\above\dimen0=3sp\def\thickness{\dimen0}\setbox0=\hbox{${a\fraction\thickness b}$}",
r"\def\leftdelim{\delimiter'0502400}\def\rightdelim{\delimiter'0512401}\setbox0=\hbox{${a\overwithdelims\leftdelim\rightdelim b}$}",
r"\setbox0=\hbox{${a\atopwithdelims.. b}$}",
r"\setbox0=\hbox{${a\over\fontdimen8\tenex=7sp b}$}",
r"\setbox0=\hbox{${a\above1sp\fontdimen8\tenex=7sp b}$}",
r"\setbox0=\hbox{$\scriptstyle{a\atop\fontdimen8\tenex=5sp b}$}",
r"\setbox0=\hbox{${\hbox to0pt{A\hss}\above1sp\hbox to-3pt{B\hss}}$}",
] {
compare(body);
}
}
#[test]
fn fraction_specification_and_owned_lists_serialize_without_geometry_reconstruction() {
let e = compare(r"\setbox0=\hbox{${f\abovewithdelims()3sp gj}$}");
let math = e
.events
.iter()
.find_map(|e| match e {
Event::BuiltMath(m) => Some(m),
_ => None,
})
.unwrap();
let MathNode::Noad(noad) = &math.noads[0] else {
panic!("group noad")
};
let MathField::List(list) = &noad.nucleus else {
panic!("retained sub-mlist")
};
let MathNode::Fraction {
numerator,
denominator,
specification,
source,
..
} = &list[0]
else {
panic!("actual fraction node")
};
assert!(!numerator.is_empty() && !denominator.is_empty());
assert_eq!(specification.thickness, Some(3));
assert_ne!(specification.left, specification.right);
assert!(!specification.left_source.tokens.is_empty());
assert!(!specification.right_source.tokens.is_empty());
assert!(!source.tokens.is_empty());
let box_ = e.state.box_register(0).unwrap();
fn vertical_count(b: &NativeBox) -> usize {
let mut count = usize::from(b.kind == BoxKind::Vertical);
match &b.content {
BoxContent::Horizontal(v) => {
for n in v {
if let TextNode::Box(b) = n {
if let Some(b) = &b.native_box {
count += vertical_count(b);
}
}
}
}
BoxContent::Vertical(v) => {
for n in v {
if let NativeVerticalNode::Box(b) = n {
count += vertical_count(b);
}
}
}
}
count
}
assert!(vertical_count(box_) >= 1);
let decoded: Execution = serde_json::from_slice(&serde_json::to_vec(&e).unwrap()).unwrap();
assert!(
decoded == e,
"owned nodes and provenance changed in roundtrip"
);
}
#[test]
fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
let seed = format!(
r"{FONTS}{SETUP}\let\savedabove=\above\def\FRAC#1#2{{#1\abovewithdelims()3sp#2}}\setbox2=\hbox{{$\FRAC{{f}}{{gj}}$}}\dump"
);
let bootstrap = || {
Executor::new(State::initex().with_etex(), Limits::default())
.run(
SourceFile {
name: "seed.tex".into(),
data: seed.as_bytes().to_vec(),
},
&mut Host,
)
.unwrap()
};
let bytes = FormatImage::from_dump(bootstrap(), Vec::new(), Vec::new())
.unwrap()
.encode()
.unwrap();
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 39);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
.new_job(
state.profile(),
state.input_profile(),
JobTime::new(2026, 11, 17, 0).unwrap(),
Limits::default(),
|_| Ok(seed.as_bytes().to_vec()),
)
.unwrap();
let document = || SourceFile {
name: "main.tex".into(),
data:
br"\setbox0=\hbox{$\scriptstyle\FRAC{a}{b}$}\setbox1=\hbox{${a\savedabove1sp b}$}\end"
.to_vec(),
};
let a = loaded.run(document(), &mut Host).unwrap();
let b = Executor::from_execution(bootstrap(), Limits::default())
.run(document(), &mut Host)
.unwrap();
assert_eq!(
a.state.meaning(&CommandName::Control("savedabove".into())),
Meaning::Primitive(Primitive::Above)
);
for index in [0, 1, 2] {
assert!(
a.state.box_register(index) == b.state.box_register(index),
"box {index} lost content or origins"
);
}
let dir = directory();
fs::write(dir.join("seed.tex"), seed).unwrap();
fs::write(dir.join("format.tfx"), bytes).unwrap();
fs::write(dir.join("loaded.json"), serde_json::to_vec(&a).unwrap()).unwrap();
fs::write(dir.join("fresh.json"), serde_json::to_vec(&b).unwrap()).unwrap();
}
#[test]
fn illegal_generalized_fraction_modes_and_ambiguous_scans_fail_in_both_engines() {
for body in [
r"\above1pt",
r"\hbox{\overwithdelims()}",
r"\hbox{$a\over b\above1pt c$}",
r"\hbox{$a\atop b\abovewithdelims()2pt c$}",
r"\hbox{$a^\above1pt b$}",
r"\hbox{$a\overwithdelims Q) b$}",
r"\hbox{$a\abovewithdelims()Q b$}",
] {
let dir = directory();
let source = format!(r"{FONTS}{SETUP}{body}\end");
fs::write(dir.join("probe.tex"), &source).unwrap();
let reference = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&dir)
.output()
.unwrap();
fs::write(dir.join("reference.stdout"), &reference.stdout).unwrap();
assert_eq!(reference.status.code(), Some(1), "{dir:?}: {body}");
assert!(!dir.join("probe.pdf").exists());
let failure = Executor::new(State::initex().with_etex(), Limits::default())
.run_detailed(
SourceFile {
name: "probe.tex".into(),
data: source.into_bytes(),
},
&mut Host,
)
.unwrap_err();
fs::write(
dir.join("native-failure.json"),
serde_json::to_vec(&failure).unwrap(),
)
.unwrap();
}
}
#[test]
fn suspended_fraction_numerator_is_owned_during_actual_scanner_errors_and_cancellation() {
struct Stop {
cancellation: Cancellation,
cancel: bool,
}
impl SourceProvider for Stop {
font_world::font_resources!();
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
assert_eq!(name, "stop");
if !self.cancel {
return Err("fraction input failed".into());
}
self.cancellation.cancel();
Ok(SourceFile {
name: "stop.tex".into(),
data: br"\message{FORBIDDEN}".to_vec(),
})
}
}
for cancel in [false, true] {
let mut counts = Vec::new();
for number in 0..3 {
let cancellation = Cancellation::default();
let source = format!(
r"{FONTS}{SETUP}\tracingstats1\setbox0=\hbox{{${}\abovewithdelims()\input stop }}",
r"\hbox{N}".repeat(number)
);
let failure = Executor::new(State::initex().with_etex(), Limits::default())
.with_cancellation(cancellation.clone())
.run_detailed(
SourceFile {
name: "pending.tex".into(),
data: source.into_bytes(),
},
&mut Stop {
cancellation,
cancel,
},
)
.unwrap_err();
assert!(
failure.error.message.contains(if cancel {
"compilation cancelled"
} else {
"fraction input failed"
}),
"{}",
failure.error
);
assert_eq!(failure.evidence.paragraph_mode, ParagraphMode::Math);
assert!(
!failure
.evidence
.events
.iter()
.any(|e| matches!(e, Event::Message { text, .. } if text == "FORBIDDEN"))
);
let usage = failure
.evidence
.events
.iter()
.find_map(|e| match e {
Event::Statistics(s) => match &s.phase {
StatisticsPhase::End {
success: false,
usage,
} => Some(usage),
_ => None,
},
_ => None,
})
.unwrap();
assert_eq!(usage.stacks.math_frames, 1);
counts.push(usage.active_material.math_nodes);
let dir = directory();
fs::write(
dir.join("native-pending-failure.json"),
serde_json::to_vec(&failure).unwrap(),
)
.unwrap();
}
assert_eq!(counts[1] - counts[0], 1);
assert_eq!(counts[2] - counts[0], 2);
}
}
#[test]
fn generalized_fractions_defer_actual_files_until_shipout() {
use std::{collections::BTreeMap, io::Write, path::PathBuf};
struct Files {
root: PathBuf,
files: BTreeMap<u8, fs::File>,
observed: Vec<(String, Vec<u8>)>,
}
impl SourceProvider for Files {
font_world::font_resources!();
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
Err(format!("unexpected input {name}"))
}
fn open_out(&mut self, stream: u8, name: &str, _: &str) -> Result<String, String> {
let p = self.root.join(name);
self.files
.insert(stream, fs::File::create(&p).map_err(|e| e.to_string())?);
Ok(p.display().to_string())
}
fn write_out(&mut self, stream: u8, text: &str) -> Result<(), String> {
self.files
.get_mut(&stream)
.ok_or("stream not open")?
.write_all(text.as_bytes())
.map_err(|e| e.to_string())
}
fn close_out(&mut self, stream: u8) -> Result<(), String> {
if let Some(mut f) = self.files.remove(&stream) {
f.flush().map_err(|e| e.to_string())?;
}
Ok(())
}
fn observe_message(&mut self, text: &str) -> Result<(), String> {
if matches!(text, "BEFORE" | "AFTER") {
self.observed.push((
text.into(),
fs::read(self.root.join("proof.dat")).map_err(|e| e.to_string())?,
));
}
Ok(())
}
}
for math in [
r"\hbox{\write1{NUM-\the\count0}N}\over\hbox{\write1{DEN-\the\count0}D}",
r"\displaystyle\hbox{\write1{NUM-\the\count0}N}\abovewithdelims()3sp\hbox{\write1{DEN-\the\count0}D}",
r"\hbox{\write1{NUM-\the\count0}N}\atop{\hbox{\write1{DEN-\the\count0}D}\over x}",
] {
let p = directory();
let native = p.join("native");
let reference = p.join("pdftex");
fs::create_dir(&native).unwrap();
fs::create_dir(&reference).unwrap();
let source = format!(
r"{FONTS}{SETUP}\immediate\openout1=proof.dat\count0=7\setbox2=\hbox{{$\hbox{{\write1{{UNSHIPPED}}N}}\over x$}}\setbox0=\hbox{{${math}$}}\count0=9\message{{BEFORE}}\shipout\copy0\message{{AFTER}}\immediate\closeout1\end"
);
fs::write(reference.join("probe.tex"), &source).unwrap();
fs::write(native.join("probe.tex"), &source).unwrap();
let output = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&reference)
.output()
.unwrap();
assert!(
output.status.success(),
"{p:?}: {}",
String::from_utf8_lossy(&output.stdout)
);
let mut host = Files {
root: native.clone(),
files: BTreeMap::new(),
observed: Vec::new(),
};
let e = Executor::new(State::initex().with_etex(), Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: source.into_bytes(),
},
&mut host,
)
.unwrap_or_else(|error| panic!("{p:?}: {error}"));
fs::write(
native.join("execution.json"),
serde_json::to_vec(&e).unwrap(),
)
.unwrap();
let expected = b"NUM-9\nDEN-9\n";
assert_eq!(fs::read(native.join("proof.dat")).unwrap(), expected);
assert_eq!(fs::read(reference.join("proof.dat")).unwrap(), expected);
assert_eq!(
host.observed,
[
("BEFORE".into(), Vec::new()),
("AFTER".into(), expected.to_vec())
]
);
assert_eq!(
e.events
.iter()
.filter(|e| matches!(e, Event::Shipout(_)))
.count(),
1
);
}
}
#[test]
fn generalized_fractions_shipouts_match_independent_dvi_glyphs_and_rules() {
use texrra_tex_core::math_engine_tex::MathItem;
for (case, body) in [
r"\hbox{${a\over b}$}",
r"\hbox{$\displaystyle{f\overwithdelims() gj}$}",
r"\hbox{${a\abovewithdelims()1sp b}$}",
r"\hbox{$\scriptstyle{a\abovewithdelims()3sp b}$}",
r"\hbox{$\scriptscriptstyle{f\atopwithdelims() gj}$}",
r"\hbox{$\displaystyle{a\above-3sp b}$}",
r"\hbox{$\left({a\over {b\above3sp c}}\right)$}",
r"\hbox{${\vbox{\hbox{Ag}\hbox{B}}\above1pt\hbox to20pt{C\hfil}}$}",
r"\hbox{${a\over b}^{xy}_{gj}$}",
]
.iter()
.enumerate()
{
let dir = std::env::temp_dir().join(format!(
"texrra-fractions-dvi-{}-{case}",
std::process::id()
));
fs::create_dir_all(&dir).unwrap();
let source = format!(
"{FONTS}{SETUP}\\pdfoutput=0\\setbox0={body}\\setbox1=\\hbox{{X\\box0}}\\shipout\\copy1\\end\n"
);
fs::write(dir.join("probe.tex"), &source).unwrap();
let output = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&dir)
.output()
.unwrap();
assert!(
output.status.success(),
"{dir:?}: {}",
String::from_utf8_lossy(&output.stdout)
);
let output = Command::new("python3")
.arg(
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../scripts/native-math-dvi-oracle.py"),
)
.arg(dir.join("probe.dvi"))
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
fs::write(dir.join("reference.json"), &output.stdout).unwrap();
let reference: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
let execution = Executor::new(State::initex().with_etex(), Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: source.into_bytes(),
},
&mut Host,
)
.unwrap();
fs::write(
dir.join("native.json"),
serde_json::to_vec(&execution).unwrap(),
)
.unwrap();
let ships: Vec<_> = execution
.events
.iter()
.filter_map(|e| match e {
Event::Shipout(s) => Some(s),
_ => None,
})
.collect();
assert_eq!(ships.len(), 1);
let page = &reference[0];
let anchor = &page["glyphs"][0];
assert_eq!(anchor["slot"], 88);
let (ox, oy) = (anchor["x"].as_i64().unwrap(), anchor["y"].as_i64().unwrap());
let mut expected: Vec<_> = page["glyphs"]
.as_array()
.unwrap()
.iter()
.map(|v| {
(
v["font"].as_str().unwrap().to_owned(),
v["size"].as_i64().unwrap(),
v["slot"].as_u64().unwrap() as u8,
v["x"].as_i64().unwrap() - ox,
v["y"].as_i64().unwrap() - oy,
)
})
.collect();
let mut rules: Vec<_> = page["rules"]
.as_array()
.unwrap()
.iter()
.map(|v| {
(
v["x"].as_i64().unwrap() - ox,
v["y"].as_i64().unwrap() - oy,
v["width"].as_i64().unwrap(),
v["height"].as_i64().unwrap(),
)
})
.collect();
let (mut actual, mut actual_rules) = (Vec::new(), Vec::new());
for item in ships[0].box_node.geometry().unwrap().items {
match item.item {
MathItem::NativeGlyph {
font, slot, size, ..
} => actual.push((font.name.clone(), size, slot, item.x, item.y)),
MathItem::Rule { width, height } => {
actual_rules.push((item.x, item.y, width, height))
}
_ => panic!("non-native material"),
}
}
actual.sort();
expected.sort();
rules.sort();
actual_rules.sort();
assert_eq!(actual.len(), expected.len(), "{dir:?}");
for (a, b) in actual.iter().zip(&expected) {
assert_eq!((&a.0, a.1, a.2), (&b.0, b.1, b.2), "{dir:?}");
assert!(
(a.3 - b.3).abs() <= 1 && (a.4 - b.4).abs() <= 1,
"{dir:?}: {a:?} != {b:?}"
);
}
assert_eq!(actual_rules.len(), rules.len(), "{dir:?}");
for (a, b) in actual_rules.iter().zip(&rules) {
assert!(
(a.0 - b.0).abs() <= 1
&& (a.1 - b.1).abs() <= 1
&& (a.2 - b.2).abs() <= 1
&& (a.3 - b.3).abs() <= 1,
"{dir:?}: {a:?} != {b:?}"
);
}
}
}