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

476 lines
15 KiB
Rust

//! Native tokens -> math fields/noads -> geometry, glue and real penalties.
#[path = "support/font_world.rs"]
mod font_world;
use font_world::FontFiles;
use std::{fs, process::Command};
use texrra_tex_core::execution::*;
const SETUP: &str = include_str!("../../../examples/native-bootstrap/math-fonts.tex");
fn run(body: &str) -> Execution {
Executor::new(
State::initex().with_etex(),
Limits {
steps: 1_000_000,
..Limits::default()
},
)
.run(
SourceFile {
name: "math.tex".into(),
data: (format!("{SETUP}\n{body}\\end\n")).as_bytes().to_vec(),
},
&mut FontFiles,
)
.unwrap()
}
fn math(e: &Execution) -> Vec<&NativeMath> {
e.events
.iter()
.filter_map(|e| {
if let Event::BuiltMath(m) = e {
Some(m.as_ref())
} else {
None
}
})
.collect()
}
fn penalties(m: &NativeMath) -> Vec<i32> {
m.horizontal
.iter()
.filter_map(|n| {
if let TextNode::Penalty(p) = n {
Some(*p)
} else {
None
}
})
.collect()
}
#[test]
fn math_noads_have_real_classes_scopes_and_penalty_consumers() {
let e = run(
r"$a+b=c$\par\hbox{$a+b=c$}$+a+a+\mathrel=b$\par${a+b}=c$\par$a==b$\par$a+\penalty7 b$\par",
);
let m = math(&e);
assert_eq!(penalties(m[0]), [700, 500]);
assert!(penalties(m[1]).is_empty());
assert!(!m[1].penalties_enabled);
assert_eq!(penalties(m[2]), [700, 500]);
assert_eq!(penalties(m[3]), [500]);
assert_eq!(penalties(m[4]), [500]);
assert_eq!(penalties(m[5]), [7]);
let e = run(
r"\binoppenalty=10000$a+b=c$\par{$a+b\binoppenalty=-10\relpenalty=-20=c$\par}$a+b=c$\par",
);
let m = math(&e);
assert_eq!(penalties(m[0]), [500]);
assert_eq!(penalties(m[1]), [-10, -20]);
assert_eq!(penalties(m[2]), [500]);
let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(e, copy);
assert!(e.reads.contains(&Dependency::MathCode(b'+')));
assert!(
e.reads
.contains(&Dependency::MathFamily { size: 0, family: 1 })
);
}
#[test]
fn mathcodes_active_characters_families_scripts_and_modes_execute() {
let e = run(
r#"\def\plus{+}\mathchardef\eq="303D\message{\the\mathcode`\a/\the\thinmuskip}$\ifmmode\ifinner\message{MATH}\fi\fi a\plus b\eq c^2_{ij}$\par{\mathcode`\+="002B$a+b$\par}$a+b$\par"#,
);
let m = math(&e);
assert!(
e.events
.iter()
.any(|e| matches!(e,Event::Message{text,..} if text=="MATH"))
);
assert!(penalties(m[1]).is_empty());
assert_eq!(penalties(m[2]), [700]);
let e = run(
r#"\def\setactive{\mathcode`\~="8000}\setactive\catcode126=13\def~{+}\catcode126=12 $a~b$\par"#,
);
assert_eq!(penalties(math(&e)[0]), [700]);
let e = run(r"\setbox0=\hbox{$\fam0 a$}\setbox1=\hbox{$a$}");
assert_ne!(
e.state.box_register(0).unwrap().width,
e.state.box_register(1).unwrap().width
);
}
#[test]
fn incomplete_math_fonts_modes_and_fields_are_strict_errors() {
for body in [
r"$a",
r"$\message{\the\spacefactor}$",
r"$a^$",
r"$a^2^3$",
r"${a$",
r"$\eqno1$",
r"$a^\hbox{a}$",
r"$a\over b\over c$",
r"\mathcode0=32769",
r"\textfont16=\tenrm",
r"\textfont2=\tenrm $a$",
r"$\limits a$",
r"\advance\mathcode0 by1",
] {
assert!(
Executor::new(
State::initex().with_etex().with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(
SourceFile {
name: "bad.tex".into(),
data: (format!("{SETUP}{body}")).as_bytes().to_vec(),
},
&mut FontFiles
)
.is_err(),
"{body}"
);
}
assert!(
Executor::default()
.run(
SourceFile {
name: "null.tex".into(),
data: ("$a$").as_bytes().to_vec(),
},
&mut FontFiles
)
.unwrap_err()
.message
.contains("math family")
);
let body = format!("${}a{}$", "{".repeat(40), "}".repeat(40));
assert!(
Executor::new(State::initex(), Limits::default())
.run(
SourceFile {
name: "deep.tex".into(),
data: (format!("{SETUP}{body}")).as_bytes().to_vec(),
},
&mut FontFiles
)
.unwrap_err()
.message
.contains("capacity")
);
}
#[test]
fn raw_math_geometry_and_hlist_penalties_match_real_initex() {
let dir = std::env::temp_dir().join(format!("texrra-math-list-oracle-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let formulas = [
"a",
"a+b=c",
"+a",
"a+",
"a++b",
"a+=b",
"a==b",
"(a+b)",
"{a+b}=c",
r"a+\penalty3 b",
r"a^2+b_i=c",
r"x_i^j",
r"x^{ij}_{kl}",
r"{ab}^{cd}",
r"a\over b",
r"{a+b\over c+d}=e",
r"{a\atop b}",
r"\scriptstyle a+b=c",
r"\scriptscriptstyle a+b=c",
r"\mathop a+b",
r"\mathinner{a+b}=c",
r"a\mskip3mu plus2mu b",
r"a\mkern2mu b",
r"a\kern2pt b",
r"a+\textstyle b",
r"a\noboundary+b",
r"\noboundary a^2+b_i=c",
r"a+\mathrel{=}b",
r"\fam0 AV",
r"x^i",
r"x_i",
r"a\setbox2=\hbox{X}\copy2 b",
r"a\setbox2=\hbox{X}\wd2=7pt\ht2=5pt\dp2=1pt\copy2 b",
r"x_{\setbox9=\hbox{a}\ht9=2pt\copy9}",
r"\setbox8=\hbox{A}{\setbox8=\hbox{B}\copy8}\copy8",
r"\let\s\setbox\let\height\ht \s4=\hbox{Y}\height4=2pt\box4",
];
let mut cases: Vec<(String, String)> = formulas
.iter()
.map(|s| (String::new(), s.to_string()))
.collect();
for script in [0, 32768, 65536] {
for f in ["x_i^j", r"a\over b", r"{x_i\over y^j}"] {
cases.push((format!("\\scriptspace={script}sp "), f.into()));
}
}
for prefix in [
r"\mathsurround=2pt ",
r"\fam0 ",
r"\medmuskip=6mu plus1mu minus2mu ",
] {
cases.push((prefix.into(), "a+b=c".into()));
}
for left in [
"mathord",
"mathop",
"mathbin",
"mathrel",
"mathopen",
"mathclose",
"mathpunct",
"mathinner",
] {
for right in [
"mathord",
"mathop",
"mathbin",
"mathrel",
"mathopen",
"mathclose",
"mathpunct",
"mathinner",
] {
cases.push((String::new(), format!(r"a\{left}{{b}}\{right}{{c}}d")));
}
}
for prefix in [
r"\textfont1=\sevenrm ",
r"\textfont2=\sevensy ",
r"\scriptfont1=\fiverm ",
] {
cases.push((prefix.into(), r"a+b_i^2=c".into()));
}
for formula in [
"a-b*c",
r#"\mathchar"010B+\mathchar"010C"#,
r"a+{}=b",
r"a+\mathrel{=}b",
r"a+\penalty10000 b",
r"a+\mskip1mu b",
r"a+\scriptstyle b",
r"\mathop x_i^2",
r"$a$",
] {
cases.push((String::new(), formula.into()));
}
for (index, (prefix, formula)) in cases.iter().enumerate() {
let common = format!(
"{SETUP}{prefix}\\setbox0=\\hbox{{$ {formula} $}}\\message{{DIMS=\\number\\wd0,\\number\\ht0,\\number\\dp0;}}"
);
let e = run(&format!(
"{prefix}\\setbox0=\\hbox{{$ {formula} $}}\\message{{DIMS=\\number\\wd0,\\number\\ht0,\\number\\dp0;}}"
));
fs::write(
dir.join("probe.tex"),
format!(
"{common}\\showboxbreadth=10000\\showboxdepth=20\\tracingonline=1\\showbox0\\end\n"
),
)
.unwrap();
let output = match Command::new("pdftex")
.args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"])
.current_dir(&dir)
.output()
{
Ok(o) => o,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
eprintln!("pdftex absent: native math oracle skipped");
fs::remove_dir_all(dir).unwrap();
return;
}
Err(e) => panic!("{e}"),
};
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert!(
log.contains("! OK."),
"{}",
String::from_utf8_lossy(&output.stdout)
);
let dims = log
.split("DIMS=")
.nth(1)
.unwrap()
.split(';')
.next()
.unwrap()
.split(',')
.map(|s| s.trim().parse::<i64>().unwrap())
.collect::<Vec<_>>();
let b = e.state.box_register(0).unwrap();
for (a, b) in [b.width, b.height, b.depth].iter().zip(&dims) {
assert!(
(a - b).abs() <= 1,
"case {index}: {prefix} {formula}: native {:?}, ref {dims:?}\n{log}",
[
e.state.box_register(0).unwrap().width,
e.state.box_register(0).unwrap().height,
e.state.box_register(0).unwrap().depth
]
);
}
let reference: Vec<i32> = log
.split("> \\box0=")
.nth(1)
.unwrap()
.lines()
.filter_map(|l| l.strip_prefix(".\\penalty ").and_then(|n| n.parse().ok()))
.collect();
assert_eq!(
penalties(math(&e)[0]),
reference,
"case {index}: {formula}\n{log}"
);
}
eprintln!(
"{} native math INITEX geometry/list cases passed",
cases.len()
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn actual_binop_rel_penalties_control_paragraph_breaks_like_initex() {
let dir = std::env::temp_dir().join(format!("texrra-math-break-oracle-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let mut count = 0;
let mut variants = Vec::new();
for width in [40, 55, 70, 85, 100] {
for bin in [-10000, 0, 700, 10000] {
for rel in [-10000, 0, 500, 10000] {
variants.push((width, bin, rel, 0, "$a+b+c=d+e+f=g+h+i$"));
}
}
}
for width in [45, 70] {
for bin in [0, 10000] {
for surround in [0, 2] {
variants.push((
width,
bin,
500,
surround,
"Alpha $a+b=c$ beta gamma $d+e=f$ omega.",
));
}
}
}
for (width, bin, rel, surround, text) in variants {
let body = format!(
r"\hsize={width}pt\binoppenalty={bin}\relpenalty={rel}\mathsurround={surround}pt\setbox0=\vbox{{\noindent {text}\par}}"
);
let e = run(&body);
let b = e.state.box_register(0).unwrap();
let BoxContent::Vertical(nodes) = &b.content else {
panic!()
};
let native: Vec<String> = nodes
.iter()
.filter_map(|n| {
if let NativeVerticalNode::Line(p) = n {
Some(font_world::painted_text(&p.horizontal_items().unwrap()))
} else {
None
}
})
.collect();
fs::write(dir.join("probe.tex"),format!("{SETUP}{body}\\showboxbreadth=10000\\showboxdepth=20\\tracingonline=1\\showbox0\\end\n")).unwrap();
let output = match Command::new("pdftex")
.args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"])
.current_dir(&dir)
.output()
{
Ok(o) => o,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
eprintln!("pdftex absent: math paragraph oracle skipped");
fs::remove_dir_all(dir).unwrap();
return;
}
Err(e) => panic!("{e}"),
};
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert!(
log.contains("! OK."),
"{}",
String::from_utf8_lossy(&output.stdout)
);
let mut reference = Vec::<String>::new();
for l in log.split("> \\box0=").nth(1).unwrap().lines() {
if l.starts_with(".\\hbox(") {
reference.push(String::new());
} else if let Some((font, glyph)) =
l.strip_prefix("..\\").and_then(|l| l.split_once(' '))
&& ["teni", "tenrm", "tensy"].contains(&font)
&& let Some(row) = reference.last_mut()
{
row.push_str(glyph);
}
}
assert_eq!(
native, reference,
"measure {width}, bin {bin}, rel {rel}\n{log}"
);
if text.starts_with('$') && bin == 10000 && rel == 10000 {
assert_eq!(native.len(), 1, "math glue cannot bypass prohibited breaks");
}
count += 1;
}
eprintln!("{count} real native math paragraph penalty cases passed");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn actual_math_packages_update_last_badness_like_tex() {
let body = r"\setbox0=\hbox to0pt{Wide}\message{B0=\the\badness;}$ $\message{B1=\the\badness;}$a+b$\message{B2=\the\badness;}$a^2$\message{B3=\the\badness;}\par";
let e = run(body);
let m = math(&e);
assert_eq!(m[0].horizontal_packs, 0);
assert_eq!(m[1].last_pack_badness, Some(0));
assert_eq!(m[2].last_pack_badness, Some(0));
assert!(m[1].horizontal_packs > 0);
let messages: Vec<_> = e
.events
.iter()
.filter_map(|e| {
if let Event::Message { text, .. } = e {
Some(text.as_str())
} else {
None
}
})
.collect();
assert_eq!(messages, ["B0=1000000;", "B1=1000000;", "B2=0;", "B3=0;"]);
let dir = std::env::temp_dir().join(format!("texrra-math-pack-state-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("probe.tex"), format!("{SETUP}{body}\\end\n")).unwrap();
match Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&dir)
.output()
{
Ok(o) => {
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stdout));
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
for msg in messages {
assert!(log.contains(msg), "{log}");
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
eprintln!("pdftex absent: clean-box state probe skipped")
}
Err(e) => panic!("{e}"),
};
fs::remove_dir_all(dir).unwrap();
}