//! Actual native box/list displays against independent INITEX diagnostics. #[path = "support/dvi_shipout.rs"] mod dvi_shipout; #[path = "support/font_world.rs"] mod font_world; use std::{fs, process::Command}; use texrra_tex_core::execution::*; const SETUP: &str = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); const PRINT: &str = r"\newlinechar=-1\showboxbreadth=1000\showboxdepth=20\hfuzz=100pt\vfuzz=100pt\tracingonline=1"; #[derive(Default)] struct Host { output: Vec<(WriteDestination, String)>, } impl SourceProvider for Host { font_world::font_resources!(); fn read(&mut self, _: &str, _: &str) -> Result { Err("no source".into()) } fn observe_diagnostic(&mut self, d: WriteDestination, t: &str) -> Result<(), String> { self.output.push((d, t.into())); Ok(()) } } fn execute(source: &str, host: &mut impl SourceProvider) -> Result { Executor::new(State::initex().with_etex(), Limits::default()).run( SourceFile { name: "diagnostics.tex".into(), data: source.as_bytes().to_vec(), }, host, ) } fn directory(label: &str) -> std::path::PathBuf { let p = std::env::temp_dir().join(format!("texrra-showbox-{label}-{}", std::process::id())); fs::create_dir_all(&p).unwrap(); p } fn reference(dir: &std::path::Path, s: &str) -> Option<(String, String)> { fs::write(dir.join("probe.tex"), s).unwrap(); let o = 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: showbox oracle skipped"); return None; } Err(e) => panic!("{e}"), }; let log = fs::read_to_string(dir.join("probe.log")).unwrap(); assert_eq!(o.status.code(), Some(1), "{log}"); for l in log.lines().filter(|l| l.starts_with("! ")) { assert_eq!(l, "! OK.", "{log}"); } Some((log, String::from_utf8_lossy(&o.stdout).into())) } fn reports(e: &Execution) -> Vec<&ShowBoxReport> { e.events .iter() .filter_map(|e| { if let Event::ShowBox(r) = e { Some(r) } else { None } }) .collect() } fn compare(source: &str, label: &str) -> Execution { let e = execute(source, &mut Host::default()).unwrap(); let dir = directory(label); if let Some((log, _)) = reference(&dir, source) { for r in reports(&e) { assert!( log.contains(&r.text), "native:\n{}\nreference:\n{log}", r.text ); } } fs::remove_dir_all(dir).unwrap(); e } #[test] fn actual_box_nodes_breadth_depth_and_glue_settings_match_initex() { let mut s = format!("{SETUP}{PRINT}"); let mut count = 0; for breadth in [-2, 0, 1, 2, 5, 100] { for depth in [-1, 0, 1, 2, 5, 20] { for body in [ r"\hbox to50pt{A ffi\hskip1pt plus2fil minus1pt\kern3pt\penalty5 b\-c}", r"\vbox{\hbox{A}\vskip2pt plus1fil minus1pt\kern-1pt\penalty42\hbox{bg}\hrule}", r"\vtop to40pt{\hbox{A}\hbox{bg}\vfill}", r"\hbox{\hbox{A}\vbox{\hbox{b}\hbox{c}}\hskip0pt plus1filll}", ] { s.push_str(&format!( "\\showboxbreadth={breadth}\\showboxdepth={depth}\\setbox0={body}\\showbox0\n" )); count += 1; } } } for body in [ r"\hbox to9000pt{\hskip0pt plus1sp}", r"\hbox spread1sp{\hskip0pt plus1fil}", r"\hbox to10pt{aaa\hskip2pt minus1pt}", r"\hbox to11pt{\hskip1pt plus3pt}", r"\vbox{\hrule width2pt height3pt depth1pt\vskip0pt plus1filll}", r"\hbox{$a$}", r"\hbox{$ab$}", ] { s.push_str(&format!( "\\showboxbreadth=100\\showboxdepth=20\\setbox0={body}\\showbox0\n" )); count += 1; } s.push_str("\\showbox1\\end"); count += 1; let e = compare(&s, "boxes"); assert_eq!(reports(&e).len(), count); eprintln!("{count} actual INITEX recursive showbox/breadth/depth/glue cases passed"); } #[test] fn actual_paragraph_diagnostics_retain_raw_glue_and_selected_material() { let mut s = format!( "{SETUP}{PRINT}\\hyphenchar\\tenrm=45\\lefthyphenmin=1\\righthyphenmin=1\\hyphenation{{al-pha-bet}}" ); let mut count = 0; for width in [32, 60, 100] { for left in [0, 1] { for text in [ "A short paragraph for box diagnostics.", r"A alphabet alphabet alphabet.", r"A ab\-cdef gh\-ijkl.", r"A ffi AVA To.\par More lines.", ] { s.push_str(&format!("{{\\hsize={width}pt\\leftskip={left}pt\\parskip=3pt\\pretolerance=-1\\tolerance=10000\\showboxdepth=20\\setbox0=\\vbox{{\\noindent {text}\\par}}\\showbox0}}\n")); count += 1; } } } s.push_str("\\end"); let e = compare(&s, "paragraphs"); assert_eq!(reports(&e).len(), count); eprintln!("{count} actual INITEX paragraph diagnostic list cases passed"); } #[test] fn font_identifiers_channels_scope_and_printer_bytes_match_initex() { let source = format!( r"{SETUP}{PRINT}\setbox0=\hbox{{A ffi}}\font\latest=cmr10 \let\alias\latest {{\font\local=cmr10 }}\showbox0 {{\showboxbreadth=1\showboxdepth=1\showbox0}}\showbox0 \tracingonline=0\showbox0\tracingonline=-1\showbox0\tracingonline=1\showbox0 \setbox300=\copy0\showbox300\setbox1=\hbox{{f\showbox0 i}}\showbox1\end" ); let e = compare(&source, "channels"); assert!( reports(&e) .iter() .any(|r| r.destination == WriteDestination::Log) ); assert!( reports(&e) .last() .unwrap() .text .contains("\\local f\n.\\local i") ); let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); assert_eq!(e, copy); let dir = directory("printer"); let mut count = 0; for newline in [-1, 0, 33, 46, 92, 65] { for escape in [-1, 92, 64, 200] { let s = format!( r"{SETUP}{PRINT}\setbox0=\hbox{{\char0\char127 A\hskip1pt plus1fil\kern2pt}}\newlinechar={newline}\escapechar={escape}\showbox0\end" ); let e = execute(&s, &mut Host::default()).unwrap(); fs::write(dir.join("probe.tex"), &s).unwrap(); let o = Command::new("pdftex") .args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"]) .current_dir(&dir) .output() .unwrap(); assert_eq!(o.status.code(), Some(1)); let log = fs::read_to_string(dir.join("probe.log")).unwrap(); for r in reports(&e) { assert!( log.contains(&r.text), "newline={newline} escape={escape}\n{}\n{log}", r.text ); } count += 1; } } fs::remove_dir_all(dir).unwrap(); eprintln!("{count} actual INITEX diagnostic escape/newline byte cases passed"); } #[test] fn honest_unsupported_lists_observer_failures_and_capacity_are_errors() { let mut nested = format!(r"{SETUP}{PRINT}\setbox0=\hbox{{A}}"); for _ in 0..12 { nested.push_str(r"\setbox0=\hbox{\copy0}"); } nested.push_str(r"\showbox0\end"); let e = compare(&nested, "nested-copy"); assert!( serde_json::to_vec(&e).unwrap().len() < 1_000_000, "nested diagnostic copies must not recursively duplicate painted boxes" ); assert_eq!(State::initex().newlinechar, 0); let e = execute( &format!(r"{SETUP}{PRINT}\setbox0=\hbox{{$ab$}}\showbox0\end"), &mut Host::default(), ) .unwrap(); assert!(reports(&e)[0].text.contains("mathon")); let e = compare( &format!(r"{SETUP}{PRINT}\setbox0=\hbox{{$a+b$}}\showbox0\end"), "math-glue", ); assert!(reports(&e)[0].text.contains("medmuskip")); let e = compare( &format!(r"{SETUP}{PRINT}\setbox0=\hbox{{$x_i^2$}}\showbox0\end"), "owned-scripts", ); assert!(reports(&e)[0].text.contains("vbox")); let e = compare( &format!(r"{SETUP}{PRINT}\setbox0=\hbox{{${{x\over y}}$}}\showbox0\end"), "owned-fraction", ); assert!(reports(&e)[0].text.contains("vbox")); let e = execute( &format!(r"{SETUP}{PRINT}\setbox0=\hbox{{$x_i^2$}}\showboxdepth=0\showbox0\end"), &mut Host::default(), ) .unwrap(); assert!(reports(&e)[0].text.contains(" []")); struct Fail; impl SourceProvider for Fail { font_world::font_resources!(); fn read(&mut self, _: &str, _: &str) -> Result { Err("no source".into()) } fn observe_diagnostic(&mut self, _: WriteDestination, _: &str) -> Result<(), String> { Err("actual diagnostic sink failed".into()) } } assert!( execute(&format!(r"{SETUP}{PRINT}\showbox0\end"), &mut Fail) .unwrap_err() .message .contains("sink failed") ); assert!(execute(&format!(r"{SETUP}\showbox32768\end"), &mut Host::default()).is_err()); let text = format!( r"\catcode123=1\catcode125=2\font\p=cmr10 \p\showboxbreadth=1000\showboxdepth=20\setbox0=\hbox{{{}}}\showbox0\end", "a".repeat(200) ); let e = Executor::new( State::initex().with_etex(), Limits { tokens: 500, ..Limits::default() }, ) .run( SourceFile { name: "capacity.tex".into(), data: text.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap_err(); assert!(e.message.contains("diagnostic output capacity"), "{e:?}"); } #[test] fn errmessage_uses_scoped_unexpanded_error_help() { let error = execute( r"\catcode123=1\catcode125=2 \def\hidden{EXPANDED} \errhelp{CUSTOM \hidden} {\errhelp{LOCAL}} \errmessage{BODY}", &mut Host::default(), ) .unwrap_err(); assert_eq!(error.message, "TeX errmessage: BODY"); assert_eq!(error.help.as_deref(), Some("CUSTOM \\hidden ")); let error = execute( r"\catcode123=1\catcode125=2 \errhelp{CUSTOM} \errhelp{} \errmessage{BODY}", &mut Host::default(), ) .unwrap_err(); assert_eq!(error.help, None); } #[test] fn text_accents_preserve_font_metrics_kerns_and_paint_positions() { let case = directory("text-accent"); let source = r"\catcode123=1 \catcode125=2 \font\regular=cmr10 \font\slanted=cmti10 \font\smaller=cmr7 \regular \showboxbreadth=99 \showboxdepth=99 \setbox1=\hbox{\regular\accent19 A} \setbox2=\hbox{\regular\accent19\slanted\char84} \setbox3=\hbox{\regular\accent19\relax} \setbox4=\hbox{\regular\accent255 Z} \setbox5=\hbox{\regular\accent19\let\letter=a\letter} \setbox6=\hbox{\regular\accent19\count0=731 \smaller\char97\message{ACCENT-ASSIGNMENT:\the\count0}} \setbox7=\vbox{\hsize=50pt \baselineskip=12pt \parfillskip=0pt plus1fil \noindent W\hfil\penalty-10000 \accent19 A\par} \setbox8=\vbox{\hsize=50pt \parfillskip=0pt plus1fil \everypar{\global\count2=197}\accent19 A\par} \message{ACCENT-EVERYPAR:\the\count2} \showbox1 \showbox2 \showbox3 \showbox4 \showbox5 \showbox6 \showbox7 \showbox8 \shipout\vbox{\box1\box2\box3\box4\box5\box6\box7\box8} \end "; let log = dvi_shipout::run_reference_with_showboxes(&case, source, 8); assert!(log.contains("ACCENT-ASSIGNMENT:731")); assert!(log.contains("ACCENT-EVERYPAR:197")); let actual = Executor::new(State::initex().with_etex(), Limits::default()) .with_native_pages() .run( SourceFile { name: "text-accent.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap_or_else(|error| panic!("{case:?}: {error}")); assert_eq!(actual.state.count(2), 197); let lists = reports(&actual); assert_eq!(lists.len(), 8); for report in lists { assert!( log.contains(&report.text), "{case:?}\nnative:\n{}\nreference:\n{log}", report.text ); } let pages = dvi_shipout::compare_shipouts(&case, &actual) .unwrap_or_else(|error| panic!("{case:?}: {error}")); assert_eq!(pages.len(), 1); assert_eq!(pages[0]["glyphs"].as_u64(), Some(15)); assert!(pages[0]["max_coordinate_error_sp"].as_i64().unwrap() <= 1); } #[test] fn margin_protrusion_uses_font_slots_in_break_search_and_shipout() { let case = directory("margin-protrusion"); let source = r"\catcode123=1 \catcode125=2 \font\roman=cmr10 \roman \hsize=38pt \baselineskip=12pt \parskip=0pt \parfillskip=0pt plus 1fil \rightskip=0pt plus 1fil \pretolerance=100 \tolerance=200 \linepenalty=10 \showboxbreadth=99 \showboxdepth=99 \begingroup \lpcode\roman65=120 \endgroup \message{GROUP-CODE:\the\lpcode\roman65} \lpcode\roman65=100 \rpcode\roman46=500 \message{LEFT-CODE:\the\lpcode\roman65} \message{RIGHT-CODE:\the\rpcode\roman46} \setbox0=\vbox{\pdfprotrudechars=0 \noindent AA. AA.\par} \setbox1=\vbox{\pdfprotrudechars=1 \noindent AA. AA.\par} \setbox2=\vbox{\pdfprotrudechars=2 \noindent AA. AA.\par} \setbox3=\vbox{\pdfprotrudechars=1 \noindent\hbox{A}A.\par} \lpcode\roman65=-100 \rpcode\roman46=-125 \setbox4=\vbox{\pdfprotrudechars=1 \noindent AA.\par} \pdfprotrudechars=1 \lpcode\roman65=100 \rpcode\roman46=500 \setbox7=\vbox{\noindent AA.\par\global\setbox8=\lastbox} \setbox5=\hbox{\unhcopy8\unskip\unskip\message{COPIED-TAIL:\the\lastnodetype,\the\lastkern}} \setbox6=\hbox{\unhbox8\unskip\unskip\message{MOVED-TAIL:\the\lastnodetype,\the\lastkern}} \showbox0 \showbox1 \showbox2 \showbox3 \showbox4 \showbox5 \showbox6 \shipout\vbox{\box0\kern3pt\box1\kern3pt\box2\kern3pt\box3\kern3pt\box4\kern3pt\box5\kern3pt\box6} \end "; let log = dvi_shipout::run_reference_with_showboxes(&case, source, 7); assert!(log.contains("GROUP-CODE:120 LEFT-CODE:100 RIGHT-CODE:500")); for marker in ["COPIED-TAIL:13,0.0pt", "MOVED-TAIL:13,0.0pt"] { assert!(log.contains(marker)); } let actual = Executor::new(State::initex().with_etex(), Limits::default()) .with_native_pages() .run( SourceFile { name: "margin-protrusion.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap_or_else(|error| panic!("{case:?}: {error}")); let lists = reports(&actual); assert_eq!(lists.len(), 7); for (report, line_count) in lists.into_iter().zip([2, 2, 1, 1, 1, 0, 0]) { assert!(log.contains(&report.text), "{case:?}\nnative:\n{}\nreference:\n{log}", report.text); assert_eq!( report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(), line_count, ); } let page = dvi_shipout::compare_shipout(&case, actual) .unwrap_or_else(|error| panic!("{case:?}: {error}")); assert_eq!(page["glyphs"].as_u64(), Some(30)); assert!(page["max_coordinate_error_sp"].as_i64().unwrap() <= 1); } #[test] fn font_expansion_codes_invalidate_cached_break_geometry() { let source = r"\catcode123=1 \catcode125=2 \font\roman=cmr10 \roman \pdfoutput=1 \pdffontexpand\roman 100 100 10 autoexpand \hsize=30pt \parfillskip=0pt plus1fil \rightskip=0pt plus1fil \pretolerance=100 \tolerance=200 \linepenalty=10 \baselineskip=12pt \showboxbreadth=99 \showboxdepth=99 \setbox0=\vbox{\pdfadjustspacing=1 \noindent AA AA\par} \setbox1=\vbox{\pdfadjustspacing=2 \noindent AA AA\par} \setbox2=\vbox{\pdfadjustspacing=2 \noindent AA AA\par} \begingroup \efcode\roman65=0 \endgroup \ifnum\efcode\roman65=0\else\errmessage{Expansion codes are global}\fi \setbox3=\vbox{\pdfadjustspacing=2 \noindent AA AA\par} \showbox0 \showbox1 \showbox2 \showbox3 \end "; let cache = std::sync::Arc::new(LineBreakCache::default()); let executed = Executor::new(State::initex().with_etex(), Limits::default()) .with_line_break_cache(cache.clone()) .run( SourceFile { name: "font-expansion.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap(); let lists = reports(&executed); assert_eq!(lists.len(), 4); assert!(cache.work().reused_passes > 0); for (report, expected_lines) in lists.iter().zip([2, 1, 1, 2]) { assert_eq!( report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(), expected_lines, "{}", report.text ); assert_eq!(report.text.contains(r"\roman (-100) A"), expected_lines == 1); } } #[test] fn font_expansion_uses_unboxed_inline_math() { let source = r"\catcode123=1 \catcode125=2 \catcode36=3 \font\roman=cmr10 \roman \textfont0=\roman \scriptfont0=\roman \scriptscriptfont0=\roman \font\symbol=cmsy10 \textfont2=\symbol \scriptfont2=\symbol \scriptscriptfont2=\symbol \font\extension=cmex10 \textfont3=\extension \scriptfont3=\extension \scriptscriptfont3=\extension \mathcode65=65 \pdfoutput=1 \pdffontexpand\roman 100 100 10 autoexpand \hsize=31pt \parfillskip=0pt plus1fil \rightskip=0pt plus1fil \pretolerance=100 \tolerance=200 \linepenalty=10 \baselineskip=12pt \showboxbreadth=99 \showboxdepth=99 \setbox0=\vbox{\pdfadjustspacing=1 \noindent $AA$ $AA$\par} \setbox1=\vbox{\pdfadjustspacing=2 \noindent $AA$ $AA$\par} \setbox2=\vbox{\pdfadjustspacing=2 \noindent \hbox{$AA$} $AA$\par} \showbox0 \showbox1 \showbox2 \end "; let executed = execute(source, &mut Host::default()).unwrap(); let lists = reports(&executed); assert_eq!(lists.len(), 3); for (report, (line_count, expanded_chars)) in lists.iter().zip([(2, 0), (1, 4), (2, 0)]) { assert_eq!( report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(), line_count, "{}", report.text ); assert_eq!(report.text.matches(r"\roman (-80) A").count(), expanded_chars); } } #[test] fn autoexpand_assigns_font_numbers_and_shares_parameters() { let declaration = r"\catcode123=1 \catcode125=2 \font\roman=cmr10 \roman \pdfoutput=1 \fontdimen8\roman=2pt \pdffontexpand\roman 50 50 25 autoexpand \pdffontexpand\roman 50 50 25 autoexpand \fontdimen8\roman=3pt "; let body = r"\pdfadjustspacing=1 \parfillskip=0pt \hsize=30.75pt \showboxbreadth=99 \showboxdepth=99 \setbox0=\vbox{\noindent AAAA\par} \showbox0 \end "; let fonts = |input: &str| { execute(input, &mut Host::default()) .unwrap() .state .fonts() .clone() }; let declared = fonts(&format!("{declaration}\\end")); assert_eq!( declared .fonts() .iter() .map(FontInstance::name) .collect::>(), ["nullfont", "cmr10", "cmr10+50", "cmr10-50"] ); assert_eq!(declared.resources().len(), 1); let mut packed = fonts(&format!("{declaration}{body}")); assert_eq!(packed.fonts().len(), 5); assert_eq!(packed.fonts()[4].name(), "cmr10+25"); assert!(packed.fonts()[1..].iter().all(|font| font.parameters()[7] == 3 * 65536)); let mut previous = packed.clone(); let base = packed .load( &mut Host::default(), "cmr10", "diagnostics.tex", texrra_tex_core::tfm::FontSize::Design, CommandName::Control("roman".into()), FontIntegers { hyphen: 45, skew: -1 }, ) .unwrap(); assert!(packed.set_fontdimen(base, 9, 0).unwrap_err().contains("only the last loaded font")); packed.set_fontdimen(base, 8, 4 * 65536).unwrap(); assert!(packed.fonts()[1..].iter().all(|font| font.parameters()[7] == 4 * 65536)); assert_eq!(previous.fontdimen(base, 8).unwrap(), 3 * 65536); }