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

294 lines
11 KiB
Rust

//! Genuine owned pre/post/replacement lists, native scanning and actual line
//! selection, checked against independent real pdfTeX INITEX box diagnostics.
#[path = "support/font_world.rs"]
mod font_world;
use std::{
fs,
path::PathBuf,
process::Command,
sync::atomic::{AtomicU64, Ordering},
};
use texrra_tex_core::execution::*;
const SETUP: &str = r"\catcode123=1\catcode125=2\catcode35=6\font\p=cmr10\p\defaulthyphenchar=45\hyphenchar\p=45\showboxbreadth=1000\showboxdepth=30\tracingonline=1\newlinechar=-1\hbadness=10000\vbadness=10000\hfuzz=1000pt\vfuzz=1000pt\boxmaxdepth=1000pt\baselineskip=12pt\parindent=0pt\hsize=100pt\parfillskip=0pt plus1fil\pretolerance=10000\tolerance=10000\linepenalty=10\hyphenpenalty=50\exhyphenpenalty=50\adjdemerits=10000\doublehyphendemerits=10000\finalhyphendemerits=5000 ";
fn dir() -> PathBuf {
static ID: AtomicU64 = AtomicU64::new(0);
let p = std::env::temp_dir().join(format!(
"texrra-disc-{}-{}",
std::process::id(),
ID.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&p).unwrap();
p
}
fn native(source: &str) -> Result<Execution, Error> {
Executor::new(
State::initex().with_etex(),
Limits {
steps: 5_000_000,
tokens: 16_000_000,
..Limits::default()
},
)
.run(
SourceFile {
name: "probe.tex".into(),
data: source.as_bytes().to_vec(),
},
&mut font_world::FontFiles,
)
}
fn compare(body: &str, labels: &[String]) -> Execution {
let source = format!("{SETUP}{body}\\end\n");
let p = dir();
fs::write(p.join("probe.tex"), &source).unwrap();
let e = native(&source).unwrap();
let r = 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!(r.status.code(), Some(1), "{log}");
for l in log.lines().filter(|l| l.starts_with("! ")) {
assert_eq!(l, "! OK.", "{log}");
}
let actual: Vec<_> = e
.events
.iter()
.filter_map(|e| {
if let Event::ShowBox(r) = e {
Some(&r.text)
} else {
None
}
})
.collect();
let expected: Vec<_> = log
.split("> \\box0=")
.skip(1)
.map(|s| format!("> \\box0={}", s.split("! OK.").next().unwrap()))
.collect();
assert_eq!(actual.len(), labels.len());
assert_eq!(expected.len(), labels.len());
for ((a, b), label) in actual.iter().zip(&expected).zip(labels) {
assert_eq!(a.trim_end(), b.trim_end(), "{label}; {p:?}");
}
let messages: Vec<_> = e
.events
.iter()
.filter_map(|e| {
if let Event::Message { text, .. } = e {
Some(text)
} else {
None
}
})
.collect();
for message in messages {
assert!(log.contains(message), "{message}\n{log}");
}
eprintln!(
"{} exact discretionary boxes matched real INITEX",
labels.len()
);
fs::remove_dir_all(p).unwrap();
e
}
#[test]
fn explicit_branch_lists_boxes_fonts_groups_and_no_hbox_hook_match_initex() {
let mut body = String::new();
let mut labels = Vec::new();
for (pre, post, repl) in [
("", "", ""),
("-", "", ""),
("fi", "fl", "ffi"),
("AB", "CD", "EF"),
(r"A\kern2pt B", r"\kern-1pt g", r"f\kern0pt i"),
(r"\hbox{A}", r"\vbox{\hbox{g}}", r"\hbox{C}"),
(
r"{\font\F=cmr7 at9pt\F fi}",
r"{\font\G=cmti10 at12pt\G gy}",
r"{\font\H=cmbx10 scaled1201\H ffi}",
),
(
r"\count0=7\message{DCS=PRE:\the\currentgrouptype/\the\currentgrouplevel}",
r"\message{DCS=POST:\the\currentgrouptype/\the\currentgrouplevel}",
r"\message{DCS=REPL:\the\currentgrouptype/\the\currentgrouplevel}",
),
(r"\aftergroup\relax A", "B", "C"),
] {
body.push_str(&format!(
"\\setbox0=\\hbox{{x\\discretionary{{{pre}}}{{{post}}}{{{repl}}}y}}\\showbox0\n"
));
labels.push(format!("{pre}/{post}/{repl}"));
}
body.push_str(r"\count0=0\everyhbox{\global\advance\count0 by1}\setbox0=\hbox{A\discretionary{B}{C}{D}E}\showbox0\message{DCS=HOOK:\the\count0}\everyhbox{} ");
labels.push("everyhbox only runs for a real hbox".into());
let e = compare(&body, &labels);
let b = e.state.box_register(0).unwrap();
let BoxContent::Horizontal(nodes) = &b.content else {
panic!("original horizontal list required")
};
assert!(nodes.iter().any(|n|matches!(n,TextNode::Discretionary{pre_break,post_break,replacement_count:1,..}if pre_break.len()==1 && post_break.len()==1)));
assert!(
e.events
.iter()
.any(|e| matches!(e,Event::Message{text,..}if text=="DCS=HOOK:1"))
);
let restored: Execution = serde_json::from_slice(&serde_json::to_vec(&e).unwrap()).unwrap();
assert_eq!(e, restored);
}
#[test]
fn actual_breaks_transplant_pre_post_skip_replacement_and_consume_penalties() {
let mut body = String::new();
let mut labels = Vec::new();
for width in [15, 23, 35, 50, 80, 120] {
for penalty in [-10000, 0, 50, 10000] {
for (pre, post, repl) in [
("f-", "fi", "ffi"),
("", "XY", "zz"),
("-", "", "X"),
(r"\hbox{j}", r"\kern2pt g", r"\hbox{X}"),
] {
body.push_str(&format!("\\hsize={width}pt\\hyphenpenalty={penalty}\\exhyphenpenalty={penalty}\\setbox0=\\vbox{{AA\\discretionary{{{pre}}}{{{post}}}{{{repl}}}VV extra words after the branch.\\par}}\\showbox0\n"));
labels.push(format!("{width}/{penalty}/{pre}/{post}/{repl}"));
}
}
}
compare(&body, &labels);
}
#[test]
fn improper_branch_nodes_missing_groups_and_replacement_capacity_are_real_errors() {
let p = dir();
for source in [
r"\discretionary{A B}{}{}".to_owned(),
r"\discretionary{\penalty1}{}{}".into(),
r"\discretionary{\setlanguage1}{}{}".into(),
r"\discretionary{\discretionary{}{}{}}{}{}".into(),
format!("\\discretionary{{}}{{}}{{{}}}", "A".repeat(256)),
r"\discretionary{}".into(),
] {
let source = format!("{SETUP}\\setbox0=\\hbox{{{source}}}\\end");
assert!(native(&source).is_err(), "{source}");
fs::write(p.join("probe.tex"), &source).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(), "{source}");
}
for length in [127, 128, 255] {
let body = format!(
"\\setbox0=\\hbox{{\\discretionary{{{}}}{{}}{{{}}}}}\\showbox0",
"A".repeat(128),
"A".repeat(length)
);
compare(&body, &[format!("pre length and replacement {length}")]);
}
fs::remove_dir_all(p).unwrap();
}
#[test]
fn automatic_ligature_hyphens_build_real_pre_post_and_replacement_like_initex() {
let mut body = String::from(
r"\pretolerance=-1\lefthyphenmin=1\righthyphenmin=1\hyphenation{of-fice of-fi-ce dif-fi-cult af-fine af-fix fluf-fy ef-fi-cient}",
);
let mut labels = Vec::new();
for font in ["cmr10", "cmr7 at9pt", "cmti10 at12pt", "cmbx10 scaled1201"] {
body.push_str(&format!("\\font\\F={font} \\F "));
for width in [18, 24, 30, 40, 55, 90] {
for text in [
"X office difficult affine affix fluffy efficient",
"X ``office'' (difficult) @affine",
"X office office office",
] {
body.push_str(&format!(
"\\hsize={width}pt\\setbox0=\\vbox{{{text}\\par}}\\showbox0\n"
));
labels.push(format!("{font}/{width}/{text}"));
}
}
}
let e = compare(&body, &labels);
assert!(e.events.iter().any(|e|matches!(e,Event::BuiltParagraph(p)if p.nodes.iter().any(|n|matches!(n,TextNode::Discretionary{automatic:true,post_break,replacement_count,..}if !post_break.is_empty() && *replacement_count>0)))));
}
#[test]
fn mathematical_discretionaries_restore_noads_modes_and_have_empty_replacements() {
let mut body = String::from(include_str!(
"../../../examples/native-bootstrap/math-fonts.tex"
));
let mut labels = Vec::new();
for text in [
r"$a\discretionary{f-}{fi}{}b$",
r"$a\-b$",
r"$a+\discretionary{A}{B}{}b=c$",
r"$\discretionary{\message{DCS=MODE:\ifhmode H\else BAD\fi/\the\currentgrouptype}}{}{}x_i^2$",
r"$a\discretionary{\hbox{X}}{\hbox{Y}}{}b$",
] {
if text.contains("x_i^2") {
body.push_str(&format!("\\setbox0=\\hbox{{{text}}}\\message{{DCS=SCRIPTS:\\number\\wd0/\\number\\ht0/\\number\\dp0}}\n"));
} else {
body.push_str(&format!("\\setbox0=\\hbox{{{text}}}\\showbox0\n"));
labels.push(text.to_owned());
}
}
for width in [15, 25, 40, 70] {
body.push_str(&format!(r"\hsize={width}pt\hyphenpenalty=-10000\setbox0=\vbox{{AA $a\discretionary{{f-}}{{fi}}{{}}b$ VV\par}}\showbox0"));
labels.push(format!("inline math actual break {width}"));
}
compare(&body, &labels);
let source = format!(
"{SETUP}{}\\setbox0=\\hbox{{$a\\discretionary{{X}}{{Y}}{{Z}}b$}}\\end",
include_str!("../../../examples/native-bootstrap/math-fonts.tex")
);
assert!(
native(&source)
.unwrap_err()
.message
.contains("math discretionary replacement must be empty")
);
let p = dir();
fs::write(p.join("probe.tex"), source).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());
fs::remove_dir_all(p).unwrap();
}
#[test]
fn real_patterns_inside_ligatures_keep_hyphen_candidates_and_actual_lists() {
let mut body = String::from(
r"\pretolerance=-1\lefthyphenmin=1\righthyphenmin=1\patterns{f1f f1i of3f i1c c1e}",
);
let mut labels = Vec::new();
for width in [17, 23, 30, 40, 55, 80] {
for text in [
"X office office office",
"X (office) ``office''",
"X affine difficult efficient",
] {
body.push_str(&format!(
"\\hsize={width}pt\\setbox0=\\vbox{{{text}\\par}}\\showbox0\n"
));
labels.push(format!("patterns/{width}/{text}"));
}
}
compare(&body, &labels);
}