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

438 lines
16 KiB
Rust

//! Font resource identity, global integers and mathaccent against actual INITEX.
#[path = "support/font_world.rs"]
mod font_world;
use font_world::FontFiles;
use std::{fs, process::Command};
use texrra_tex_core::{execution::*, math_engine_tex::MathItem};
const SETUP: &str = include_str!("../../../examples/native-bootstrap/math-fonts.tex");
fn execute(source: &str) -> Result<Execution, Error> {
Executor::new(State::initex().with_etex(), Limits::default()).run(
SourceFile {
name: "font-state.tex".into(),
data: source.as_bytes().to_vec(),
},
&mut FontFiles,
)
}
fn directory(label: &str) -> std::path::PathBuf {
let dir =
std::env::temp_dir().join(format!("texrra-font-state-{label}-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
dir
}
fn reference(dir: &std::path::Path, source: &str) -> Option<String> {
fs::write(dir.join("probe.tex"), source).unwrap();
let o = match Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(dir)
.output()
{
Ok(o) => o,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
eprintln!("pdftex absent: font-state oracle skipped");
return None;
}
Err(e) => panic!("{e}"),
};
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert!(o.status.success(), "{log}");
Some(log)
}
#[test]
fn font_integer_defaults_global_mutations_load_reuse_and_scans_match_initex() {
let source = r"\catcode123=1\catcode125=2\catcode35=6\newlinechar=33
\message{!INITIAL=\the\defaulthyphenchar/\the\defaultskewchar/\the\hyphenchar\nullfont/\the\skewchar\nullfont!}
\defaulthyphenchar=45\defaultskewchar=127\font\a=cmmi10
{\font\b=cmr10\skewchar\b=94\hyphenchar\b=33}
\defaultskewchar=-1\defaulthyphenchar=-1\font\c=cmr10\font\d=cmmi10\font\e=cmmi7
\message{!LOAD=\the\skewchar\a/\the\skewchar\c/\the\hyphenchar\c/\the\skewchar\d/\the\skewchar\e!}
\let\alias\a\textfont1=\alias\a
{\globaldefs=-1\global\skewchar\a=1000\hyphenchar\textfont1=-12}
\message{!GLOBAL=\the\skewchar\font/\the\skewchar\alias/\the\hyphenchar\a!}
\count0=\skewchar\a\advance\count0 by\hyphenchar\a
\def\which{\alias}\edef\readback{\the\skewchar\which}
\message{!SCAN=\number\count0/\readback/\ifnum\skewchar\which=1000 Y\else N\fi!}
\skewchar\nullfont=2147483647\hyphenchar\nullfont=-2147483647
\message{!NULL=\the\skewchar\nullfont/\the\hyphenchar\nullfont!}
{\defaultskewchar=65\defaulthyphenchar=46\font\local=cmsy10 }
\font\persist=cmsy10\message{!LOCALLOAD=\the\skewchar\persist/\the\hyphenchar\persist/\the\defaultskewchar/\the\defaulthyphenchar!}\end";
let e = execute(source).unwrap();
let dir = directory("integers");
let Some(log) = reference(&dir, source) else {
return;
};
let messages: Vec<_> = e
.events
.iter()
.filter_map(|e| {
if let Event::Message { text, .. } = e {
Some(text.trim())
} else {
None
}
})
.collect();
for m in &messages {
assert!(log.contains(m), "{m}\n{log}");
}
assert_eq!(messages.len(), 6);
assert_eq!(
e.state.font_integers(e.state.math_font(0, 1)),
FontIntegers {
hyphen: -12,
skew: 1000
}
);
let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(e, copy);
assert!(e.reads.contains(&Dependency::FontResources));
fs::remove_dir_all(dir).unwrap();
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Glyph {
font: String,
size: i64,
slot: u8,
x: i64,
y: i64,
}
#[test]
fn math_accent_dimensions_raw_slots_and_dvi_positions_match_real_initex() {
let mut cases: Vec<(String, String)> = Vec::new();
let formulas = [
r#"\mathaccent"705E a"#,
r#"\mathaccent"705E i"#,
r#"\mathaccent"705E x_i^2"#,
r#"\mathaccent"705E {x_i^2}"#,
r#"\mathaccent"705E {a+b}"#,
r#"\mathaccent"705E {}"#,
r#"\mathaccent"0362 x"#,
r#"\mathaccent"0362 {ab}"#,
r#"\mathaccent"0362 {a+b+c}"#,
r#"\mathaccent"015E x"#,
r#"\mathaccent"016F a"#,
r#"\mathaccent"016F g_i^2"#,
r#"\mathaccent"705E {\mathaccent"705E x}"#,
r#"a+\mathaccent"705E b=c"#,
r#"{\mathaccent"705E x\over\mathaccent"705E y_i}"#,
r#"x^{\mathaccent"705E y}_{\mathaccent"705E z}"#,
r#"\mathaccent"705E a\mathaccent"705E b"#,
r#"\mathaccent"705E {a\over b}_i^j"#,
];
for skew in [-1, 0, 45, 127, 255, 256] {
for style in [
"",
r"\displaystyle ",
r"\scriptstyle ",
r"\scriptscriptstyle ",
] {
for formula in formulas {
cases.push((
format!(
"\\skewchar\\teni={skew}\\skewchar\\seveni={skew}\\skewchar\\fivei={skew}"
),
format!("{style}{formula}"),
));
}
}
}
cases.extend([
(String::new(), r#"\fam1\mathaccent"705E x"#.into()),
(String::new(), r#"\mathaccent"00C8 x_i^2"#.into()),
(String::new(), r#"\mathaccent"705E\mathchar"01C8"#.into()),
(
String::new(),
r#"\mathaccent"705E\mathchar"01C8_i^2"#.into(),
),
(
String::new(),
r#"\mathaccent"00C8\mathchar"01C8_i^2"#.into(),
),
(
String::new(),
r#"\mathaccent"705E x\skewchar\teni=127"#.into(),
),
]);
let mut native = Vec::new();
let mut source = format!("{SETUP}\\pdfoutput=0\\newlinechar=33");
for (i, (prefix, formula)) in cases.iter().enumerate() {
let body = format!(
"\\skewchar\\teni=0\\skewchar\\seveni=0\\skewchar\\fivei=0 {prefix}\\setbox0=\\hbox{{A$ {formula} $}}\\message{{!D{i}=\\number\\wd0,\\number\\ht0,\\number\\dp0;!}}"
);
let e = execute(&format!("{SETUP}{body}\\end"))
.unwrap_or_else(|e| panic!("{prefix} {formula}: {e:?}"));
source.push_str(&format!("{{{body}\\shipout\\box0}}\n"));
native.push(e);
}
source.push_str("\\end");
let dir = directory("accent");
let Some(log) = reference(&dir, &source) else {
return;
};
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../scripts/native-math-dvi-oracle.py");
let output = Command::new("python3")
.arg(script)
.arg(dir.join("probe.dvi"))
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let pages: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(pages.as_array().unwrap().len(), cases.len());
for (i, e) in native.iter().enumerate() {
let context = format!("case {i}: {:?}", cases[i]);
let dims: Vec<i64> = log
.split(&format!("D{i}="))
.nth(1)
.unwrap()
.split(';')
.next()
.unwrap()
.split(',')
.map(|s| s.trim().parse().unwrap())
.collect();
let b = e.state.box_register(0).unwrap();
for (a, b) in [b.width, b.height, b.depth].into_iter().zip(dims) {
assert!((a - b).abs() <= 1, "{context}: dim {a} != {b}");
}
let page = &pages[i];
let array = page["glyphs"].as_array().unwrap();
let anchor = &array[0];
assert_eq!(anchor["slot"], 65);
let ox = anchor["x"].as_i64().unwrap() + anchor["advance"].as_i64().unwrap();
let oy = anchor["y"].as_i64().unwrap();
let mut expected: Vec<Glyph> = array[1..]
.iter()
.map(|g| Glyph {
font: g["font"].as_str().unwrap().into(),
size: g["size"].as_i64().unwrap(),
slot: g["slot"].as_u64().unwrap() as u8,
x: g["x"].as_i64().unwrap() - ox,
y: g["y"].as_i64().unwrap() - oy,
})
.collect();
let m = e
.events
.iter()
.find_map(|e| {
if let Event::BuiltMath(m) = e {
Some(m)
} else {
None
}
})
.unwrap();
let mut actual = Vec::new();
let mut rules = Vec::new();
let mut x = 0;
for n in &m.horizontal {
match n {
TextNode::Box(b) | TextNode::MathChar(b) => {
if let Some(g) = font_world::math_geometry(b) {
for item in &g.items {
match &item.item {
MathItem::NativeGlyph {
font, slot, size, ..
} => actual.push(Glyph {
font: font.name.clone(),
size: *size,
slot: *slot,
x: x + item.x,
y: item.y,
}),
MathItem::Glyph { .. } | MathItem::PdfImage(_) => {
panic!("legacy glyph identity in strict native math")
}
MathItem::Rule { width, height } => {
rules.push((x + item.x, item.y, *width, *height))
}
}
}
}
x += b.width;
}
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => x += g.width as i64,
TextNode::Kern { width, .. } => x += *width as i64,
_ => {}
}
}
actual.sort();
expected.sort();
assert_eq!(
actual.len(),
expected.len(),
"{context}: {actual:?} / {expected:?}"
);
for (a, b) in actual.iter().zip(&expected) {
assert_eq!(
(&a.font, a.size, a.slot),
(&b.font, b.size, b.slot),
"{context}"
);
assert!(
(a.x - b.x).abs() <= 1 && (a.y - b.y).abs() <= 1,
"{context}: {a:?} != {b:?}"
);
}
let mut expected_rules: Vec<_> = page["rules"]
.as_array()
.unwrap()
.iter()
.map(|r| {
(
r["x"].as_i64().unwrap() - ox,
r["y"].as_i64().unwrap() - oy,
r["width"].as_i64().unwrap(),
r["height"].as_i64().unwrap(),
)
})
.collect();
rules.sort();
expected_rules.sort();
assert_eq!(rules.len(), expected_rules.len(), "{context}");
for (a, b) in rules.iter().zip(&expected_rules) {
for (a, b) in [a.0, a.1, a.2, a.3].into_iter().zip([b.0, b.1, b.2, b.3]) {
assert!((a - b).abs() <= 1, "{context}: rule {a} != {b}");
}
}
}
eprintln!(
"{} actual INITEX mathaccent dimensions, raw font slots and DVI glyph/rule positions passed",
cases.len()
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn mutable_hyphen_font_state_is_consumed_at_actual_construction_time() {
let dir = directory("hyphen");
let mut count = 0;
for value in [-1, 0, 33, 45, 127, 200, 256] {
for body in [
format!(r"\hyphenchar\tenrm={value}\setbox0=\hbox{{a\-b}}"),
format!(r"\hyphenchar\tenrm=45\setbox0=\hbox{{a\-\hyphenchar\tenrm={value}b}}"),
format!(r"\hyphenchar\tenrm={value}\setbox0=\hbox{{a-b}}"),
format!(
r"\hyphenchar\tenrm=45\setbox0=\vbox{{\hsize=38pt\noindent A alphabet alphabet\hyphenchar\tenrm={value}\par}}"
),
] {
let source = format!(
r"{SETUP}\lefthyphenmin=1\righthyphenmin=1\pretolerance=-1\tolerance=10000\tracinglostchars=2\hyphenation{{al-pha-bet}}{body}\newlinechar=33\message{{!DIM=\number\wd0,\number\ht0,\number\dp0;!}}\end"
);
let e = execute(&source).unwrap();
let Some(log) = reference(&dir, &source) else {
return;
};
let dims: Vec<i64> = log
.split("DIM=")
.nth(1)
.unwrap()
.split(';')
.next()
.unwrap()
.split(',')
.map(|n| n.parse().unwrap())
.collect();
let b = e.state.box_register(0).unwrap();
for (a, b) in [b.width, b.height, b.depth].into_iter().zip(dims) {
assert!((a - b).abs() <= 1, "{body}: {a} != {b}\n{log}");
}
let actual = e
.events
.iter()
.filter(|e| matches!(e, Event::MissingGlyph(_)))
.count();
let expected = log
.lines()
.filter(|l| l.starts_with("Missing character:"))
.count();
assert_eq!(actual, expected, "{body}\n{log}");
count += 1;
}
}
eprintln!("{count} mutable hyphenchar dimension/missing-count/timing cases passed");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn accent_fields_frozen_geometry_and_font_state_failures_stay_native() {
let e=execute(&format!(r#"{SETUP}\let\hat=\mathaccent\skewchar\teni=127\setbox0=\hbox{{$\hat"705E x_i^2$}}\skewchar\teni=-1\copy0\end"#)).unwrap();
let m = e
.events
.iter()
.find_map(|e| {
if let Event::BuiltMath(m) = e {
Some(m)
} else {
None
}
})
.unwrap();
assert!(
matches!(&m.noads[0],MathNode::Noad(n) if n.accent==Some(MathChar{family:0,slot:94}) && n.sup.is_some() && n.sub.is_some())
);
assert!(e.reads.contains(&Dependency::FontResources));
let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(e, copy);
let source = format!(
r"{SETUP}\font\x=cmmi10 at12pt \x\setbox0=\hbox{{AV}}\message{{NATIVE-SIZED=\number\wd0}}\end"
);
let sized = execute(&source).unwrap();
assert_eq!(
sized
.state
.fonts()
.font(sized.state.text_font())
.unwrap()
.size_sp(),
12 * 65536
);
let dir = directory("sized");
if let Some(log) = reference(&dir, &source) {
let width = sized.state.box_register(0).unwrap().width;
assert!(log.contains(&format!("NATIVE-SIZED={width}")), "{log}");
}
fs::remove_dir_all(dir).unwrap();
let source = format!(r"{SETUP}\teni\-\end");
execute(&source).unwrap();
let dir = directory("math-font-discretionary");
reference(&dir, &source);
let source =
format!(r"{SETUP}\setbox0=\hbox{{\teni a\-b}}\message{{NATIVE-DISC=\number\wd0}}\end");
let disc = execute(&source).unwrap();
if let Some(log) = reference(&dir, &source) {
assert!(
log.contains(&format!(
"NATIVE-DISC={}",
disc.state.box_register(0).unwrap().width
)),
"{log}"
);
}
fs::remove_dir_all(dir).unwrap();
for body in [
r"\skewchar=1",
r"\hyphenchar\undefined=45",
r"\skewchar\textfont16=1",
r"\hyphenchar\nullfont=2147483648",
r"\advance\skewchar\nullfont by1",
r"\long\skewchar\nullfont=1",
r#"$\mathaccent"8000 x$"#,
r#"$\mathaccent"705E$"#,
r#"$x^\mathaccent"705E a$"#,
r#"$\mathaccent"705E x^^$"#,
r#"\mathaccent"705E x"#,
r"\errorcontextlines=2147483648",
] {
assert!(execute(&format!("{SETUP}{body}\\end")).is_err(), "{body}");
}
}