//! Native vertical-center noads, with actual TeX lists and shipped effects. #[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 SETUP: &str = r#"\catcode38=4\delcode`\(="028300\delcode`\)="029301\newlinechar=-1\showboxbreadth=1000\showboxdepth=40 "#; struct Host; impl SourceProvider for Host { font_world::font_resources!(); fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } } fn directory() -> std::path::PathBuf { static ID: AtomicU64 = AtomicU64::new(0); let p = std::env::temp_dir().join(format!( "texrra-vcenter-{}-{}", std::process::id(), ID.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&p).unwrap(); p } fn markers(text: &str) -> Vec { let mut out = Vec::new(); let mut rest = text; while let Some(i) = rest.find("VC[") { rest = &rest[i..]; let end = rest.find(';').unwrap() + 1; out.push(rest[..end].into()); rest = &rest[end..]; } out } fn compare(body: &str) -> Execution { let p = directory(); let source = format!( "{FONTS}{SETUP}{body}\\message{{VC[PACK]=\\number\\wd0,\\number\\ht0,\\number\\dp0,\\the\\badness;}}\\showbox0\\end\n" ); fs::write(p.join("probe.tex"), &source).unwrap(); let reference = 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!(reference.status.code(), Some(1), "{p:?}: {log}"); for line in log.lines().filter(|line| line.starts_with("! ")) { assert_eq!(line, "! OK.", "{p:?}: {body}\n{log}"); } let e = Executor::new( State::initex().with_etex(), Limits { steps: 1_000_000, ..Limits::default() }, ) .run( SourceFile { name: "probe.tex".into(), data: source.into_bytes(), }, &mut Host, ) .unwrap_or_else(|error| panic!("{p:?}: {body}: {error}")); fs::write(p.join("native.json"), serde_json::to_vec(&e).unwrap()).unwrap(); let actual: Vec<_> = e .events .iter() .filter_map(|v| match v { Event::Message { text, .. } => Some(markers(text)), _ => None, }) .flatten() .collect(); assert_eq!(actual, markers(&log), "{p:?}: {body}"); let reports: Vec<_> = e .events .iter() .filter_map(|v| match v { Event::ShowBox(r) => Some(r), _ => None, }) .collect(); assert_eq!(reports.len(), 1); assert!( log.contains(&reports[0].text), "{p:?}: {body}\nnative:\n{}\nreference:\n{log}", reports[0].text ); e } #[test] fn axis_centering_styles_pack_specs_and_odd_extents_match_pdftex_lists() { for style in [ "displaystyle", "textstyle", "scriptstyle", "scriptscriptstyle", ] { for spec in ["", "to0pt", "to20pt", "spread5pt", "spread-3pt"] { for material in [ "", r"\hbox{Ag}", r"\hbox{A}\kern2pt\hbox{gj}", r"\hrule width10pt height3pt depth1pt", r"\vfil\hbox{Ag}\vfil", ] { compare(&format!( r"\setbox0=\hbox{{$\{style}\vcenter {spec}{{{material}}}$}}" )); } } } for extent in [-5, -3, -1, 0, 1, 3, 5] { compare(&format!(r"\setbox0=\hbox{{$\vcenter{{\kern{extent}sp}}$}}")); } } #[test] fn vcenter_groups_hooks_scripts_and_nested_alignment_use_real_lists() { for body in [ r"\everyvbox={\message{VC[GROUP]=\the\currentgrouptype,\the\currentgrouplevel;}\ifinner\message{VC[INNER]=YES;}\fi}\count0=7\setbox0=\hbox{$\vcenter{\count0=9\hbox{Ag}}$}\message{VC[OUT]=\the\count0,\the\currentgrouptype;}", r"\setbox0=\hbox{$A\vcenter{\hbox{Ag}}^{xy}_{gj}+B$}", r"\setbox0=\hbox{$\scriptstyle\vcenter{\hbox{$\vcenter{\hbox{Ag}}$}}_{x^y}$}", r"\setbox0=\hbox{$\vcenter{\halign{#\hfil&\hskip3pt#\hfil\cr A&B\cr C&D\cr}}$}", r"\setbox0=\hbox{$\mathop{\vcenter{\hbox{Ag}}}\limits^{x}_{y}$}", r"\boxmaxdepth=-5pt\setbox0=\hbox{$\vcenter{\hbox{gj}}$}", r"\fontdimen22\sevensy=5pt\fontdimen22\fivesy=-1pt\setbox0=\hbox{$\vcenter{\hbox{A}}+\scriptstyle\vcenter{\hbox{B}}+\scriptscriptstyle\vcenter{\hbox{C}}$}", r"\setbox0=\hbox{$\left(\vcenter{\hbox{Ag}\hbox{B}}\right)$}", r"\setbox0=\hbox{$\vcenter{\hsize=25pt\noindent Alpha beta gamma delta.\par}$}", r"\setbox0=\vbox{\noindent Before$$\vcenter{\hbox{Ag}\hbox{B}}$$After\par}", ] { compare(body); } } #[test] fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let seed = format!( r"{FONTS}{SETUP}\fontdimen22\sevensy=5pt\def\VC#1{{\vcenter{{\hbox{{#1}}\kern1sp}}}}\setbox2=\hbox{{$\VC{{SEED}}$}}\dump" ); let source = r"\setbox0=\hbox{$\scriptstyle\VC{Ag}^{xy}_{z}$}\setbox1=\copy2\end"; 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(), Vec::new(), Vec::new()) .unwrap() .encode() .unwrap(); let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); assert_eq!(payload["schema"], 38); 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 document = || SourceFile { name: "document.tex".into(), data: source.as_bytes().to_vec(), }; let loaded = executor.run(document(), &mut Host).unwrap(); let fresh = Executor::from_execution(bootstrap(), Limits::default()) .run(document(), &mut Host) .unwrap(); for index in [0, 1, 2] { let a = loaded.state.box_register(index).unwrap(); let b = fresh.state.box_register(index).unwrap(); assert_eq!((a.width, a.height, a.depth), (b.width, b.height, b.depth)); assert!( a.geometry().unwrap() == b.geometry().unwrap(), "dump/load changed glyphs, font identity or source provenance for box {index}" ); } } #[test] fn operators_math_lists_and_extensible_delimiters_keep_actual_box_shapes() { for body in [ r#"\setbox0=\hbox{$\displaystyle\mathchar"1350\limits^{n}_{i}$}"#, r#"\setbox0=\hbox{$\textstyle\mathchar"1352\nolimits^{xy}_{gj}$}"#, r#"\setbox0=\hbox{$\scriptstyle\mathchar"1352\nolimits^{x}_{y}$}"#, r"\setbox0=\hbox{$\mathop{ABC}\limits^{xy}_{gj}$}", r"\setbox0=\hbox{$\mathop{ABC}\nolimits^{xy}_{gj}$}", r"\setbox0=\hbox{$\mathop{\hbox to20pt{X\hfil}}\limits^{long}_{wide}$}", r"\setbox0=\hbox{$\mathop{\vbox{\hbox{G}}}\limits_{x}^{yy}$}", r"\setbox0=\hbox{$\mathop{}\limits_{x}^{yy}$}", r"\setbox0=\hbox{$\left(\vcenter{\hrule width1pt height40pt depth2pt}\right)$}", r"\setbox0=\hbox{$\left(\vcenter{\hrule width1pt height100pt depth2pt}\right)$}", r"\setbox0=\hbox{${\vcenter{\hbox{Ag}}}+\mathord{\vcenter{\hbox{B}}}$}", r"\fontdimen9\tenex=-2pt\fontdimen10\tenex=-3pt\fontdimen11\tenex=-4pt\fontdimen12\tenex=-5pt\fontdimen13\tenex=-6pt\setbox0=\hbox{$\mathop{A}\limits^{x}_{y}$}", ] { compare(body); } } #[test] fn retained_noad_is_centered_only_at_math_conversion_and_serializes() { let e = compare(r"\setbox0=\hbox{$\scriptstyle\vcenter{\hbox{Ag}\kern1sp}$}"); let m = e .events .iter() .find_map(|event| match event { Event::BuiltMath(m) => Some(m), _ => None, }) .unwrap(); let n = m .noads .iter() .find_map(|n| match n { MathNode::Noad(n) if n.vcenter => Some(n), _ => None, }) .unwrap(); let MathField::Box(natural) = &n.nucleus else { panic!("owned vcenter nucleus") }; assert_eq!(natural.kind, BoxKind::Vertical); let centered = m .horizontal .iter() .find_map(|n| match n { TextNode::Box(b) => b.native_box.as_ref(), _ => None, }) .unwrap(); assert_eq!( natural.height + natural.depth, centered.height + centered.depth ); assert_ne!(natural.height, centered.height); assert!(!centered.geometry().unwrap().items.is_empty()); let copy: Execution = serde_json::from_slice(&serde_json::to_vec(&e).unwrap()).unwrap(); assert!(copy == e, "noad/list provenance changed in roundtrip"); } #[test] fn invalid_vcenter_modes_and_unbraced_fields_fail() { for body in [ r"\vcenter{}", r"\setbox0=\vcenter{}", r"\hbox{$a^\vcenter{}$}", r"\hbox{$\vcenter{\end}$}", r"\hbox{$\vcenter{\hbox{A}$}", ] { let source = format!("{FONTS}{SETUP}{body}\\end"); assert!( Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "bad.tex".into(), data: source.into_bytes() }, &mut Host ) .is_err(), "{body}" ); } } #[test] fn owned_math_boxes_scripts_and_operator_limits_defer_actual_files_until_shipout() { use std::{collections::BTreeMap, io::Write, path::PathBuf}; struct Files { root: PathBuf, files: BTreeMap, observed: Vec<(String, Vec)>, } impl SourceProvider for Files { font_world::font_resources!(); fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } fn open_out(&mut self, stream: u8, name: &str, _: &str) -> Result { 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,math) in [ r"\vcenter{\write1{BODY-\the\count0}\hbox{B}}^{\vcenter{\write1{SUP-\the\count0}\hbox{S}}}_{\vcenter{\write1{SUB-\the\count0}\hbox{L}}}", r"\mathop{\vcenter{\write1{BODY-\the\count0}\hbox{B}}}\limits^{\vcenter{\write1{SUP-\the\count0}\hbox{S}}}_{\vcenter{\write1{SUB-\the\count0}\hbox{L}}}", r"\hbox{\write1{BODY-\the\count0}B}^{\hbox{\write1{SUP-\the\count0}S}}_{\hbox{\write1{SUB-\the\count0}L}}", ].iter().enumerate() { let p = directory(); 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}{SETUP}\immediate\openout1=proof.dat\count0=7\setbox2=\hbox{{$\vcenter{{\write1{{UNSHIPPED}}\hbox{{N}}}}$}}\setbox0=\hbox{{${math}$}}\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 = if case==1 {b"SUP-9\nBODY-9\nSUB-9\n"} else {b"BODY-9\nSUP-9\nSUB-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 ); } } #[test] fn vcenter_shipouts_match_independent_dvi_glyphs_and_rules() { use texrra_tex_core::math_engine_tex::MathItem; for (case, body) in [ r"\hbox{$A\vcenter{\hbox{Ag}}B$}", r"\hbox{$\scriptstyle A\vcenter{\hbox{Ag}\kern1sp}B$}", r"\hbox{$\scriptscriptstyle\vcenter{\hrule width10pt height3pt depth1pt}$}", r"\hbox{$\vcenter{\hbox{Ag}}^{xy}_{gj}$}", r"\hbox{$\vcenter{\halign{#\hfil&#\hfil\cr A&B\cr C&D\cr}}$}", r"\hbox{$\left(\vcenter{\hbox{Ag}\hbox{B}}\right)$}", r"\hbox{$\vcenter{\hbox{$\scriptstyle\vcenter{\hbox{Ag}}$}}$}", ] .iter() .enumerate() { let dir = std::env::temp_dir().join(format!("texrra-vcenter-dvi-{}-{case}", std::process::id())); fs::create_dir_all(&dir).unwrap(); let source = format!( "{FONTS}{SETUP}\\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"), } } 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:?}" ); } } }