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

721 lines
32 KiB
Rust

//! Owned native alignment execution, independently checked against pdfTeX.
#[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 DISPLAY: &str = r"\catcode38=4\newlinechar=-1
\predisplaypenalty19\postdisplaypenalty23
\abovedisplayskip11pt plus2pt\belowdisplayskip13pt minus1pt
\abovedisplayshortskip47pt\belowdisplayshortskip53pt ";
const NESTED_UNSET: &str = r"\halign{#&#\cr A&B\cr\noalign{\noindent Before$$\displayindent7pt\halign{#&#\cr C&D\cr\noalign{\hrule height1pt}}$$After\par}E&F\cr}";
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 markers(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = text;
while let Some(i) = rest.find("DISPLAY[") {
rest = &rest[i..];
let end = rest.find(';').expect("complete alignment audit") + 1;
out.push(rest[..end].to_owned());
rest = &rest[end..];
}
out
}
fn compare(body: &str) -> Execution {
static ID: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"texrra-display-align-{}-{}",
std::process::id(),
ID.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&dir).unwrap();
let source = format!(
"{FONTS}{DISPLAY}{body}\\message{{DISPLAY[PACK]=\\number\\wd0,\\number\\ht0,\\number\\dp0,\\the\\badness;}}\\showboxbreadth=1000\\showboxdepth=30\\showbox0\\end\n"
);
fs::write(dir.join("probe.tex"), &source).unwrap();
// Preserve source and reference before running native, so failures retain
// both sides instead of preventing the independent oracle from executing.
let reference = Command::new("pdftex")
.args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"])
.current_dir(&dir)
.output()
.unwrap();
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert_eq!(reference.status.code(), Some(1), "{dir:?}: {body}\n{log}");
for line in log.lines().filter(|line| line.starts_with("! ")) {
assert_eq!(line, "! OK.", "{dir:?}: {body}\n{log}");
}
let e = Executor::new(
State::initex().with_etex(),
Limits {
steps: 2_000_000,
..Limits::default()
},
)
.run(
SourceFile {
name: "probe.tex".into(),
data: source.into_bytes(),
},
&mut Host,
)
.unwrap_or_else(|error| panic!("{dir:?}: {body}: {error}"));
let actual: Vec<_> = e
.events
.iter()
.filter_map(|event| match event {
Event::Message { text, .. } => Some(markers(text)),
_ => None,
})
.flatten()
.collect();
fs::write(dir.join("native.json"), serde_json::to_vec(&e).unwrap()).unwrap();
assert_eq!(actual, markers(&log), "{dir:?}: {body}");
let reports: Vec<_> = e
.events
.iter()
.filter_map(|event| match event {
Event::ShowBox(r) => Some(r),
_ => None,
})
.collect();
assert_eq!(reports.len(), 1);
assert!(
log.contains(&reports[0].text),
"{dir:?}: {body}\nnative:\n{}\nreference:\n{log}",
reports[0].text
);
e
}
#[test]
fn display_rows_rules_and_noalign_boxes_match_real_pdftex_lists() {
for body in [
r"#\hfil&\hskip3pt#\hfil\cr A&B\cr C&g\cr",
r"#\hfil&#\cr A&B\cr\noalign{\hrule height1pt\vskip2pt}C&g\cr",
r"#&#\cr A&B\cr\noalign{\moveright4pt\hbox{Z}}C&D\cr",
r"#&#\cr\vbox{\halign{#&#\cr A&B\cr C&D\cr}}&g\cr",
] {
for spec in ["", "to90pt", "spread7pt"] {
for indent in ["0pt", "7pt", "-5pt"] {
compare(&format!(
r"\setbox0=\vbox{{\noindent Before$$\displayindent={indent}\halign {spec}{{{body}}}$$After\par}}"
));
}
}
}
}
#[test]
fn closing_assignments_and_math_mode_use_the_actual_display_save_level() {
for body in [
r"\noindent Before$$\displayindent7pt\halign{#&#\cr A&B\cr C&g\cr}\displayindent17pt$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr C&g\cr}\count1=7\advance\count1 by2\relax$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr C&g\cr}\def\finish{$$}\finish After\par",
r"\def\finish{\count2=13}\noindent Before$$\halign{#&#\cr A&B\cr\noalign{\afterassignment\finish}}\count1=9$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}$\ifmmode$\else X\fi After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}\global\relax\count3=7$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}\long\relax\def\finish{$$}\finish After\par",
r"\noindent Before$$\displayindent7pt\halign to90pt{#&#\cr A&B\cr\noalign{\hrule height1pt}}\global\count3=\badness$$After\par",
r"\noindent Before$$\halign to90pt{#&#\cr A&B\cr}\global\count3=\badness$$After\par",
r"\def\unused{FORBIDDEN}\noindent Before$$\halign{#&#\cr A&B\cr}\global\noexpand\unused\count3=11$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}\global\noexpand\undefined\count3=13$$After\par",
] {
compare(&format!(
r"\setbox0=\vbox{{{body}}}\message{{DISPLAY[RESTORED]=\the\count1,\the\count2,\the\count3,\the\displayindent;}}"
));
}
}
#[test]
fn display_alignment_hooks_math_cells_and_paragraph_continuation_match_pdftex() {
for body in [
r"\noindent Before$$\halign{#&#\cr}$$After\par",
r"\noindent Before$$\halign{\hfil$#$&$#$\hfil\cr x_2&y^2\cr a+b&c=d\cr}$$After\par",
r"\noindent Before$$\displayindent7pt\halign{#&#\cr A&B\cr\noalign{\global\displayindent9pt}C&D\cr}$$After\par",
r"\noindent Before$$\displayindent7pt\halign{#&#\cr A&B\cr\noalign{\displayindent15pt}C&D\cr}$$After\par",
r"\everycr{\noalign{\penalty17}}\noindent Before$$\halign{#&#\cr A&B\cr C&g\cr}$$After\par",
r"\everydisplay{\message{DISPLAY[ENTER]=\the\currentgrouptype;}}\everycr{\noalign{\message{DISPLAY[ROW]=\the\currentgrouptype,\ifinner I\else O\fi;}}}\noindent Before$$\halign{#&#\cr A&B\cr C&D\cr}$$After\par",
r"\hangafter1\hangindent9pt\noindent Before\penalty-10000 Next$$\halign{#&#\cr A&B\cr C&g\cr}$$After\penalty-10000 Next\par",
r"\noindent Before$$\halign{#&#\cr\hbox{A}\span B\cr C&D\cr}$$After\par",
r"\noindent Before$$\tabskip1pt plus1fil\halign to90pt{#&#&#\cr\omit Wide\span\omit text&Z\cr A&B&C\cr}$$After\par",
r"\noindent Before$$\displayindent-5pt\halign{#&#\cr A&B\cr\noalign{\prevdepth3pt\hrule height2pt depth1pt\vskip-2pt}C&g\cr}$$After\par",
] {
compare(&format!(r"\setbox0=\vbox{{{body}}}"));
}
}
#[test]
fn paragraph_penalty_breakpoints_remain_owned_nodes_in_justified_lines() {
for penalty in [-20000, -10000, -9999, -50, 0, 50, 9999] {
compare(&format!(
r"\hsize24pt\setbox0=\vbox{{\noindent ABC\penalty{penalty}DEF\par}}"
));
}
}
#[test]
fn list_tail_identity_keeps_following_material_queries_and_groups_like_pdftex() {
let prefix = r"\noindent Before$$\displayindent7pt\halign to90pt{#&#\cr A&B\cr\noalign{\hrule height1pt}}$$";
for (case, tail) in [
r"After\par Again\par",
r"After\par\message{DISPLAY[TAIL]=\the\lastnodetype,\the\lastskip;}",
r"After\par\vskip3pt\penalty17\message{DISPLAY[TAIL]=\the\lastnodetype,\the\lastpenalty;}\unpenalty\message{DISPLAY[SKIP]=\the\lastskip;}\unskip",
r"After\par\hbox{Later}\kern2pt\message{DISPLAY[KERN]=\the\lastkern;}\unkern",
r"After\par\noindent More$$x+1$$End\par",
r"After\par\noindent More$$\displayindent5pt\halign{#&#\cr C&D\cr\noalign{\hrule height2pt}}$$End\par",
r"After\par\setbox1=\vbox{\hbox{Separate}}\copy1\box1",
r"After\par\setbox1=\vbox{\hbox{Separate}\kern2pt}\unvcopy1\unvbox1",
r"After\par{\noindent Grouped$$\displayindent-3pt\halign{#\cr Z\cr}$$Rest\par}\hbox{Final}",
].iter().enumerate() {
if matches!(case, 2 | 3) {
// These exact inputs crash real pdfTeX: delete_last walks the root
// linkage toward a tail now owned inside the wrapped rule box.
// Retain that real failure; native must diagnose the broken unlink.
let dir = std::env::temp_dir().join(format!("texrra-display-tail-crash-{}-{case}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let source = format!(r"{FONTS}{DISPLAY}\tracingstats1\setbox0=\vbox{{{prefix}{tail}}}\showbox0\end");
fs::write(dir.join("probe.tex"), &source).unwrap();
let reference = Command::new("pdftex").args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"]).current_dir(&dir).output().unwrap();
fs::write(dir.join("stdout.log"), &reference.stdout).unwrap();
fs::write(dir.join("stderr.log"), &reference.stderr).unwrap();
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert!(!reference.status.success() && !log.contains("! OK."), "{dir:?}: reference unexpectedly completed; reevaluate the actual tail contract");
fs::write(dir.join("reference-status.json"), serde_json::to_vec(&serde_json::json!({"status":reference.status.to_string(),"success":reference.status.success(),"scope":"actual reference failure, not stable-output equivalence"})).unwrap()).unwrap();
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();
assert!(failure.error.message.contains("not reachable from its active head"),"{}",failure.error);
continue;
}
compare(&format!(r"\setbox0=\vbox{{{prefix}{tail}}}"));
}
}
#[test]
fn illegal_display_material_and_closing_commands_fail_like_real_pdftex() {
for (case, body) in [
r"\noindent Before$$X\halign{#&#\cr A&B\cr}$$After\par",
r"\noindent Before$$\over\halign{#&#\cr A&B\cr}$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}\setbox1=\hbox{X}$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}\global\setbox1=\hbox{X}$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}\message{FORBIDDEN}$$After\par",
r"\noindent Before$\halign{#&#\cr A&B\cr}$After\par",
r"\noindent Before$$\begingroup\halign{#&#\cr A&B\cr}\endgroup$$After\par",
r"\noindent Before$$\halign{#&#\cr A&B\cr}$ $After\par",
]
.iter()
.enumerate()
{
let dir = std::env::temp_dir().join(format!(
"texrra-display-invalid-{}-{case}",
std::process::id()
));
fs::create_dir_all(&dir).unwrap();
let source = format!("{FONTS}{DISPLAY}\\setbox0=\\vbox{{{body}}}\\end\n");
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();
assert_eq!(reference.status.code(), Some(1), "{dir:?}");
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert!(log.lines().any(|s| s.starts_with("! ") && s != "! OK."));
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();
assert!(
failure.error.message.contains("display"),
"{dir:?}: {}",
failure.error
);
assert!(
!failure
.evidence
.events
.iter()
.any(|e| matches!(e, Event::Message { text, .. } if text == "FORBIDDEN"))
);
fs::write(
dir.join("native-failure.json"),
serde_json::to_vec(&failure).unwrap(),
)
.unwrap();
}
}
#[test]
fn actual_unset_nodes_survive_nested_tail_ownership_and_root_finalization() {
for body in [
NESTED_UNSET,
r"\halign{#&#\cr A&B\cr\noalign{\noindent Before$$\displayindent7pt\halign{#&#\cr C&D\cr\noalign{\hrule height1pt}}$$After\par}\omit Wide\span\omit text\cr}",
r"\halign{#&#\cr A&B\cr\noalign{\noindent Before$$\displayindent7pt\halign{#&#\cr C&D\cr\noalign{\hrule height1pt}}$$After\par}\tabskip1pt plus2fil minus2pt\hfil E\hskip2pt plus3fil minus1fil&F\cr\noalign{\message{DISPLAY[UNSET]=\the\lastnodetype;}}}",
r"\halign{#&#\cr A&B\cr\noalign{\setbox1=\lastbox\ifvoid1\message{DISPLAY[VOID]=YES;}\else\message{DISPLAY[VOID]=NO;}\fi}E&F\cr}",
] {
compare(&format!(r"\setbox0=\vbox{{{body}}}"));
}
}
#[test]
fn nested_owned_tail_capacity_keeps_real_lists_and_does_not_publish() {
let segment = r"\noindent Before$$\displayindent7pt\halign{#\cr A\cr\noalign{\hrule height1pt}}$$After\par";
let body = format!(r"\setbox0=\vbox{{{}}}", segment.repeat(14));
// The same finite source completes in real pdfTeX and with normal limits.
compare(&body);
let source = format!(r"{FONTS}{DISPLAY}\tracingstats1{body}\end");
let failure = Executor::new(
State::initex().with_etex(),
Limits {
input_depth: 12,
..Limits::default()
},
)
.run_detailed(
SourceFile {
name: "capacity.tex".into(),
data: source.into_bytes(),
},
&mut Host,
)
.unwrap_err();
assert!(
failure
.error
.message
.contains("owned list tail depth capacity"),
"{}",
failure.error
);
assert!(
!failure
.evidence
.events
.iter()
.any(|e| matches!(e, Event::Shipout(_)))
);
assert!(failure.evidence.events.iter().any(|e|matches!(e,Event::Statistics(s) if matches!(&s.phase,StatisticsPhase::End{success:false,usage} if usage.active_material.boxes>=12))));
let dir = std::env::temp_dir().join(format!(
"texrra-display-tail-capacity-{}",
std::process::id()
));
fs::create_dir_all(&dir).unwrap();
fs::write(
dir.join("native-failure.json"),
serde_json::to_vec(&failure).unwrap(),
)
.unwrap();
}
#[test]
fn pending_display_rows_remain_owned_on_actual_errors_and_cancellation() {
struct Stop {
cancellation: Cancellation,
}
impl SourceProvider for Stop {
font_world::font_resources!();
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
assert_eq!(name, "cancel");
self.cancellation.cancel();
Ok(SourceFile {
name: "cancel.tex".into(),
data: br"\message{FORBIDDEN}".to_vec(),
})
}
}
for cancelled in [false, true] {
let mut counts = Vec::new();
for rows in 0..3 {
let cancellation = Cancellation::default();
let mut host = Stop {
cancellation: cancellation.clone(),
};
let tail = if cancelled {
r"\input cancel "
} else {
r"\message{FORBIDDEN}"
};
let source = format!(
r"{FONTS}{DISPLAY}\tracingstats1\setbox0=\vbox{{\noindent Before$$\halign{{#&#\cr {}}}{tail}$$After\par}}\end",
r"A&B\cr ".repeat(rows)
);
let failure = Executor::new(State::initex().with_etex(), Limits::default())
.with_cancellation(cancellation)
.run_detailed(
SourceFile {
name: "pending.tex".into(),
data: source.into_bytes(),
},
&mut host,
)
.unwrap_err();
assert!(
failure.error.message.contains(if cancelled {
"compilation cancelled"
} else {
"two math shifts"
}),
"{}",
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,
})
.expect("actual failure resource observation");
assert_eq!(usage.stacks.math_frames, 1);
assert_eq!(usage.stacks.box_frames, 1);
counts.push(usage.active_material.boxes);
let dir = std::env::temp_dir().join(format!(
"texrra-display-pending-{}-{cancelled}-{rows}",
std::process::id()
));
fs::create_dir_all(&dir).unwrap();
fs::write(
dir.join("native-failure.json"),
serde_json::to_vec(&failure).unwrap(),
)
.unwrap();
}
assert_eq!(
counts[1] - counts[0],
3,
"one real row and two real cell boxes"
);
assert_eq!(
counts[2] - counts[0],
6,
"two real rows and four real cell boxes"
);
}
}
#[test]
fn display_alignment_macros_hooks_and_owned_rows_survive_real_format_roundtrip() {
let seed = format!(
r"{FONTS}{DISPLAY}\everydisplay{{\displayindent7pt}}\def\rows{{\halign{{##&##\cr A&B\cr C&g\cr}}}}\setbox2=\vbox{{{NESTED_UNSET}}}\dump"
);
let state = State::initex().with_etex();
let bootstrap = Executor::new(state.clone(), Limits::default())
.run(
SourceFile {
name: "seed.tex".into(),
data: seed.as_bytes().to_vec(),
},
&mut Host,
)
.unwrap();
let bytes = FormatImage::from_dump(bootstrap.clone(), Vec::new(), Vec::new())
.unwrap()
.encode()
.unwrap();
let executor = 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 source = br"\setbox0=\vbox{\noindent Before$$\rows$$After\par}\end";
let loaded = executor
.run(
SourceFile {
name: "document.tex".into(),
data: source.to_vec(),
},
&mut Host,
)
.unwrap();
let fresh = Executor::from_execution(bootstrap, Limits::default())
.run(
SourceFile {
name: "document.tex".into(),
data: source.to_vec(),
},
&mut Host,
)
.unwrap();
let a = loaded.state.box_register(0).unwrap();
let b = fresh.state.box_register(0).unwrap();
assert!(
serde_json::to_vec(a).unwrap() == serde_json::to_vec(b).unwrap(),
"format roundtrip changed actual owned row/cell/paragraph nodes or source origins"
);
assert!(
a.geometry().unwrap() == b.geometry().unwrap(),
"format roundtrip changed actual glyph/font geometry"
);
assert_eq!(
loaded.state.parameter(Parameter::Displayindent),
fresh.state.parameter(Parameter::Displayindent)
);
fn count_unset(b: &NativeBox) -> usize {
usize::from(b.kind.is_unset())
+ match &b.content {
BoxContent::Horizontal(v) => v
.iter()
.filter_map(|n| match n {
TextNode::Box(b) => b.native_box.as_deref(),
_ => None,
})
.map(count_unset)
.sum::<usize>(),
BoxContent::Vertical(v) => v
.iter()
.filter_map(|n| match n {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => {
Some(b.as_ref())
}
_ => None,
})
.map(count_unset)
.sum::<usize>(),
}
}
let a = loaded.state.box_register(2).unwrap();
let b = fresh.state.box_register(2).unwrap();
assert_eq!(count_unset(a), 3);
assert!(
serde_json::to_vec(a).unwrap() == serde_json::to_vec(b).unwrap(),
"format changed actual unset node types or span/flex/source state"
);
let dir = std::env::temp_dir().join(format!("texrra-display-format-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("seed.tex"), &seed).unwrap();
fs::write(dir.join("document.tex"), source).unwrap();
fs::write(dir.join("format.tfx"), &bytes).unwrap();
fs::write(
dir.join("loaded.json"),
serde_json::to_vec(&loaded).unwrap(),
)
.unwrap();
fs::write(dir.join("fresh.json"), serde_json::to_vec(&fresh).unwrap()).unwrap();
}
#[test]
fn display_alignment_shipouts_match_independent_dvi_glyphs_and_rules() {
use texrra_tex_core::math_engine_tex::MathItem;
for (case,(body,automatic)) in [
(r"\vbox{\noindent Before$$\displayindent7pt\halign{#&#\cr A&B\cr C&g\cr}$$After\par}",false),
(r"\vbox{\noindent Before$$\displayindent7pt\halign{#&#\cr A&B\cr\noalign{\hrule height1pt}C&g\cr}$$After\par}",false),
(r"\vbox{\noindent Before$$\halign{#&#\cr A&B\cr\noalign{\hrule height1pt}C&g\cr}$$After\par}",false),
(r"\vbox{\noindent Before$$\halign{#&#\cr\vbox{\halign{#&#\cr A&B\cr C&D\cr}}&Z\cr}$$After\par}",false),
(r"\vbox{\noindent Before$$\halign{$#$&$#$\cr x_2&y^2\cr a+b&c=d\cr}$$After\par}",false),
(r"\vbox{\hangafter1\hangindent9pt\noindent Before\penalty-10000 Next$$\halign{#&#\cr A&B\cr C&g\cr}$$After\par}",false),
(r"\vbox{\noindent Before$$\displayindent7pt\halign to90pt{#&#\cr A&B\cr\noalign{\hrule height1pt}}$$After\par}",false),
(r"\vbox{\noindent Before$$\displayindent7pt\halign to90pt{#&#\cr A&B\cr\noalign{\hrule height1pt}}$$After\par\noindent More$$\displayindent5pt\halign{#&#\cr C&D\cr\noalign{\hrule height2pt}}$$End\par}",false),
(r"\noindent XBefore$$\displayindent7pt\halign to90pt{#&#\cr A&B\cr\noalign{\hrule height1pt}}$$After\par",true),
(r"\noindent XBefore$$\displayindent7pt\halign to90pt{#&#\cr A&B\cr\noalign{\hrule height1pt}}$$After\par\noindent More$$\displayindent5pt\halign{#&#\cr C&D\cr\noalign{\hrule height2pt}}$$End\par",true),
(r"\vbox{\halign{#&#\cr A&B\cr\noalign{\noindent Before$$\displayindent7pt\halign{#&#\cr C&D\cr\noalign{\hrule height1pt}}$$After\par}E&F\cr}}",false),
].iter().enumerate() {
let dir=std::env::temp_dir().join(format!("texrra-display-align-dvi-{}-{case}",std::process::id()));
fs::create_dir_all(&dir).unwrap();
let source=if *automatic {
format!("{FONTS}{DISPLAY}\\pdfoutput0\\vsize200pt\\topskip10pt\\maxdepth4pt\\output{{\\shipout\\box255}}{body}\\end\n")
} else {
format!("{FONTS}{DISPLAY}\\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"),
}
}
let anchor=actual.iter().find(|a|a.2==88).expect("same real X anchor");
let (ax,ay)=(anchor.3,anchor.4);
for a in &mut actual {a.3-=ax;a.4-=ay;}
for a in &mut actual_rules {a.0-=ax;a.1-=ay;}
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:?}");
}
}
}
#[test]
fn display_alignment_rows_and_noalign_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 (case,body) in [
r"\noindent Before$$\halign{#&#\cr\write1{A-\the\count0}A&\write1{B-\the\count0}B\cr\write1{C-\the\count0}C&\write1{D-\the\count0}D\cr}$$After\par",
r"\noindent Before$$\halign{#\cr\write1{FIRST-\the\count0}A\cr\noalign{\write1{MIDDLE-\the\count0}}\write1{LAST-\the\count0}B\cr}$$After\par",
r"\noindent Before$$\halign{$#$&#\cr\vcenter{\write1{INNER-\the\count0}\hbox{M}}&\write1{RIGHT-\the\count0}R\cr}$$After\par",
r"\halign{#&#\cr A&B\cr\noalign{\noindent Before$$\displayindent7pt\halign{#&#\cr C&D\cr\noalign{\hrule height1pt}}$$After\write1{KEPT-\the\count0}\par}\write1{SKIPPED-E-\the\count0}E&\write1{SKIPPED-F-\the\count0}F\cr}",
].iter().enumerate() {
let p = std::env::temp_dir().join(format!("texrra-display-effects-{}-{case}",std::process::id()));
fs::create_dir_all(&p).unwrap();
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}{DISPLAY}\immediate\openout1=proof.dat\count0=7\setbox2=\vbox{{\noindent Unshipped$$\halign{{#\cr\write1{{UNSHIPPED}}N\cr}}$$\par}}\setbox0=\vbox{{{body}}}\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: &[u8] = match case {
0 => b"A-9\nB-9\nC-9\nD-9\n",
1 => b"FIRST-9\nMIDDLE-9\nLAST-9\n",
2 => b"INNER-9\nRIGHT-9\n",
_ => b"KEPT-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
);
}
}