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

275 lines
9.2 KiB
Rust

use std::{
fs,
path::PathBuf,
process::Command,
sync::atomic::{AtomicU64, Ordering},
};
use texrra_tex_core::execution::*;
const HEADER: &str = r"\catcode123=1\catcode125=2\pdfoutput=0\vbadness=10000\hbadness=10000\hsize=10pt\topskip=10pt\maxdepth=2pt\baselineskip=12pt\lineskip=1pt\lineskiplimit=0pt\setbox0=\hbox{\vrule width2pt height6pt depth2pt} ";
fn directory() -> PathBuf {
static N: AtomicU64 = AtomicU64::new(0);
let p = std::env::temp_dir().join(format!(
"texrra-page-trace-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&p).unwrap();
p
}
#[derive(Default)]
struct Host {
lines: Vec<(WriteDestination, String)>,
fail: bool,
}
impl SourceProvider for Host {
fn read(&mut self, n: &str, f: &str) -> Result<SourceFile, String> {
NoFiles.read(n, f)
}
fn observe_diagnostic(&mut self, d: WriteDestination, s: &str) -> Result<(), String> {
if self.fail {
return Err("actual page trace sink failure".into());
}
self.lines.push((d, s.into()));
Ok(())
}
}
fn native(s: &str, h: &mut Host) -> Result<Execution, Error> {
Executor::new(State::initex().with_etex(), Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: s.as_bytes().to_vec(),
},
h,
)
}
fn reports(e: &Execution) -> Vec<&PageTraceReport> {
e.events
.iter()
.filter_map(|e| {
if let Event::PageTrace(r) = e {
Some(r.as_ref())
} else {
None
}
})
.collect()
}
fn canonical_records(text: &str) -> Vec<String> {
let lines: Vec<_> = text.lines().collect();
let mut out = vec![];
let mut i = 0;
while i < lines.len() {
let Some(start) = lines[i]
.find("%% goal height=")
.or_else(|| lines[i].find("% t="))
else {
i += 1;
continue;
};
let mut value = lines[i][start..].to_string();
while lines[i].len() == 79 && i + 1 < lines.len() {
i += 1;
value.push_str(lines[i]);
}
let marker = if value.starts_with("%%") {
", max depth="
} else {
" c="
};
let at = value.find(marker).expect("complete diagnostic record") + marker.len();
let end = at
+ value[at..]
.chars()
.take_while(|c| c.is_ascii_digit() || matches!(c, '-' | '.' | '*' | '#'))
.map(char::len_utf8)
.sum::<usize>();
out.push(value[..end].to_owned());
i += 1;
}
out
}
fn reference(s: &str, p: &std::path::Path) -> (Vec<String>, Vec<String>) {
fs::write(p.join("probe.tex"), s).unwrap();
let r = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(p)
.output()
.unwrap();
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stdout));
(
canonical_records(&String::from_utf8_lossy(&r.stdout)),
canonical_records(&fs::read_to_string(p.join("probe.log")).unwrap()),
)
}
#[test]
fn actual_frozen_page_goals_all_glue_orders_badness_penalties_and_best_breaks_match_tex() {
let p = directory();
let bodies = [
r"\copy0\vskip4pt\copy0\vskip4pt\copy0\vskip4pt",
r"\copy0\vskip4pt plus2pt minus1pt\penalty50\copy0\vskip4pt plus2pt minus1pt\copy0",
r"\copy0\vskip0pt plus1fil\copy0\penalty-10000\copy0",
r"\copy0\vskip0pt plus2fill\copy0\penalty-10000\copy0",
r"\copy0\vskip0pt plus3filll\copy0\penalty-10000\copy0",
r"\copy0\vskip1pt plus1pt\vskip2pt plus1fil\vskip3pt plus1fill\vskip4pt plus1filll minus2pt\copy0",
r"\copy0\kern2pt\vskip4pt\copy0\penalty10000\copy0\penalty-10000",
r"\copy0\mark{A}\vskip4pt\copy0\vskip2pt\penalty-20000",
r"\copy0\vsize=40pt\vskip4pt\copy0\vskip4pt\copy0\penalty-10000\copy0",
r"\output={\global\vsize=40pt\shipout\box255}\copy0\vskip4pt\copy0\penalty-10000\copy0\vskip4pt\copy0",
];
let mut cases = 0;
for goal in [10, 20, 40] {
for body in bodies {
let s = format!(r"{HEADER}\vsize={goal}pt\tracingpages=1\tracingonline=1 {body}\end");
let mut h = Host::default();
let e = native(&s, &mut h).unwrap();
let actual: Vec<_> = reports(&e)
.iter()
.map(|r| r.text.replace('\n', ""))
.collect();
let (terminal, log) = reference(&s, &p);
assert_eq!(actual, log, "goal{goal}: {body}");
assert_eq!(actual, terminal, "terminal goal{goal}: {body}");
assert!(
reports(&e)
.iter()
.all(|r| r.destination == WriteDestination::TerminalAndLog)
);
cases += 1;
}
}
assert_eq!(cases, 30);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn local_trace_switches_channels_and_disabled_diagnostics_preserve_actual_pages() {
let p = directory();
for online in [0, 1] {
let body = r"\copy0\vskip4pt\copy0\penalty-10000\copy0\vskip4pt\copy0";
let mut results = vec![];
for level in [0, 1] {
let s = format!(
r"{HEADER}\vsize=20pt\tracingpages={level}\tracingonline={online} {body}\end"
);
let mut h = Host::default();
let e = native(&s, &mut h).unwrap();
let (term, log) = reference(&s, &p);
assert_eq!(
reports(&e)
.iter()
.map(|r| r.text.replace('\n', ""))
.collect::<Vec<_>>(),
log
);
if online == 0 {
assert!(term.is_empty());
assert!(
reports(&e)
.iter()
.all(|r| r.destination == WriteDestination::Log)
);
}
results.push(e);
}
assert_eq!(
results[0].shipout_display_lists().unwrap(),
results[1].shipout_display_lists().unwrap()
);
}
let s = format!(
r"{HEADER}\vsize=20pt\tracingonline=1\copy0{{\tracingpages=1\vskip2pt\copy0}}\vskip4pt\copy0\penalty-10000\end"
);
let e = native(&s, &mut Host::default()).unwrap();
let (term, log) = reference(&s, &p);
assert_eq!(
reports(&e)
.iter()
.map(|r| r.text.replace('\n', ""))
.collect::<Vec<_>>(),
log
);
assert_eq!(term, log);
assert!(
!reports(&e)
.iter()
.any(|r| matches!(r.trace, PageTrace::Freeze { .. })),
"do not invent a start event when tracing is enabled after freeze"
);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn ignored_insertion_shrink_is_log_only_and_follows_page_observation_order() {
let s = r"\catcode123=1 \catcode125=2
\tracingpages=1 \tracingonline=1 \ignoreprimitiveerror=1
\vsize=60pt \topskip=0pt \maxdepth=0pt
\splittopskip=0pt \splitmaxdepth=0pt
\count1=1000 \dimen1=25pt \skip1=0pt
\output={\shipout\vbox{\unvbox255\ifvoid1\else\box1\fi}}
\hrule height4pt width8pt
\insert1{\hrule height8pt width8pt \vskip2pt minus1fil
\hrule height8pt width8pt \vskip4pt minus2fill
\hrule height8pt width8pt}
\penalty-10000 \end";
let mut host = Host::default();
native(s, &mut host).unwrap();
let records: Vec<_> = host
.lines
.iter()
.map(|(destination, text)| (*destination, text.trim()))
.filter(|(_, text)| {
text.starts_with("%% goal height=")
|| text.starts_with("ignored:")
|| text.starts_with("% split")
})
.collect();
const IGNORED: &str = "ignored: Infinite glue shrinkage found in box being split";
assert_eq!(
records,
[
(WriteDestination::TerminalAndLog, "%% goal height=60.0, max depth=0.0"),
(WriteDestination::Log, IGNORED),
(WriteDestination::Log, IGNORED),
(WriteDestination::TerminalAndLog, "% split1 to 25.0,18.0 p=0"),
(WriteDestination::TerminalAndLog, "%% goal height=60.0, max depth=0.0"),
]
);
}
#[test]
fn page_diagnostic_sink_failures_and_capacity_errors_do_not_become_success() {
let s = format!(r"{HEADER}\vsize=20pt\tracingpages=1\copy0\vskip2pt\copy0\end");
let e = native(
&s,
&mut Host {
fail: true,
..Host::default()
},
)
.unwrap_err();
assert!(e.message.contains("actual page trace sink failure"));
let e = Executor::new(
State::initex().with_etex(),
Limits {
tokens: 20,
..Limits::default()
},
)
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: s.into_bytes(),
},
&mut Host::default(),
)
.unwrap_err();
assert!(e.message.contains("limit exceeded"));
}