//! Trace the same actual break decisions and raw short lists as independent TeX. #[path = "support/font_world.rs"] mod font_world; use std::{ fs, process::Command, sync::atomic::{AtomicU64, Ordering}, }; use texrra_tex_core::execution::*; const HEADER: &str = r"\catcode123=1\catcode125=2\font\f=cmr10 \f\hbadness=10000\vbadness=10000\tracingparagraphs=1\tracingonline=1\parfillskip=0pt plus1fil\baselineskip=12pt "; #[derive(Default)] struct Host { diagnostics: Vec<(WriteDestination, String)>, fail: bool, } impl SourceProvider for Host { fn read(&mut self, n: &str, f: &str) -> Result { NoFiles.read(n, f) } font_world::font_resources!(); fn observe_diagnostic(&mut self, d: WriteDestination, s: &str) -> Result<(), String> { if self.fail { return Err("actual paragraph diagnostic sink failure".into()); } self.diagnostics.push((d, s.into())); Ok(()) } fn diagnostic(&mut self, d: WriteDestination, s: &str) -> Result<(), String> { self.observe_diagnostic(d, s) } } fn native(s: &str) -> Execution { Executor::new(State::initex().with_etex(), Limits::default()) .with_native_pages() .run( SourceFile { name: "probe.tex".into(), data: s.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap() } fn reports(e: &Execution) -> Vec<&ParagraphTraceReport> { e.events .iter() .filter_map(|e| { if let Event::ParagraphTrace(r) = e { Some(r.as_ref()) } else { None } }) .collect() } fn reference_outputs(s: &str) -> (String, String) { static N: AtomicU64 = AtomicU64::new(0); let dir = std::env::temp_dir().join(format!( "texrra-paragraph-trace-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&dir).unwrap(); fs::write(dir.join("probe.tex"), s).unwrap(); let r = Command::new("pdftex") .args([ "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "probe.tex", ]) .current_dir(&dir) .output() .unwrap(); assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stdout)); let log = fs::read_to_string(dir.join("probe.log")).unwrap(); fs::remove_dir_all(dir).unwrap(); (log, String::from_utf8(r.stdout).unwrap()) } fn reference(s: &str) -> String { let (log, _) = reference_outputs(s); let start = [log.find("\n@"), log.find("\n\\f ")] .into_iter() .flatten() .min() .unwrap() + 1; let end = start + log[start..].find("\n\n").unwrap(); let trace = log[start..end].to_string(); trace } fn decision_lines(s: &str) -> Vec<&str> { s.lines().filter(|line| line.starts_with('@')).collect() } #[test] fn real_passes_feasible_edges_passive_nodes_and_short_lists_match_tex() { let bodies = [ r"\noindent The quick brown fox jumps over the lazy dog. This paragraph has actual line breaking.\par", r"\noindent AAA\penalty50 BBB\penalty-50 CCC\penalty10000 DDD\penalty-10000 EEE FFF GGG\par", r"\noindent ab\discretionary{c-}{de}{fg}h ij kl mn op qr st uv wx yz\par", r"\noindent ab\kern2pt cd ef\kern-1pt gh ij kl mn op qr st uv wx yz\par", r"\noindent aa \hbox{bb cc} dd \vrule width2pt height5pt ee ff gg hh\par", r"\noindent a \textfont0=\f\scriptfont0=\f\scriptscriptfont0=\f\mathsurround=2pt$\fam=0 b+c$ d e f g h i j k l\par", r"\hangindent=12pt\hangafter=1\noindent The quick brown fox jumps over the lazy dog. This paragraph has actual line breaking.\par", r"\looseness=1\noindent The quick brown fox jumps over the lazy dog. This paragraph has actual line breaking.\par", ]; for width in [40, 75, 120] { for pretolerance in [-1, 100] { for body in bodies { let s = format!( r"{HEADER}\hsize={width}pt\pretolerance={pretolerance}\tolerance=200\emergencystretch=10pt {body}\end" ); let e = native(&s); let rs = reports(&e); assert_eq!(rs.len(), 1); assert_eq!( rs[0].text.trim_end(), reference(&s), "width={width}, pretolerance={pretolerance}: {body}" ); assert_selected_path(rs[0], &e); let roundtrip: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); assert_eq!(e, roundtrip); } } } } #[test] fn ragged_shaped_paragraphs_preserve_pdftex_ties_at_the_last_special_line() { for geometry in [ r"\hangindent=26pt\hangafter=1", r"\hangindent=26pt\hangafter=-1", r"\parshape=2 0pt 91pt 26pt 65pt", r"\prevgraf=1\hangindent=26pt\hangafter=2", ] { let source = format!( r"{HEADER}\hsize=91pt\rightskip=0pt plus1fil\linepenalty=10\pretolerance=100\noindent {geometry} aaaa bbbb cccc dddd eeee ffff\par\end" ); let execution = native(&source); let reports = reports(&execution); assert_eq!(reports.len(), 1); assert_eq!(reports[0].text.trim_end(), reference(&source), "{geometry}"); assert_selected_path(reports[0], &execution); } } fn assert_selected_path(r: &ParagraphTraceReport, e: &Execution) { use std::collections::BTreeMap; let mut active = BTreeMap::::new(); let mut edges = BTreeMap::new(); for record in &r.records { match *record { ParagraphTrace::Pass { .. } => { active.clear(); edges.clear(); } ParagraphTrace::Feasible { position, via, badness, demerits, .. } => { edges.insert((position, via), (badness, demerits.unwrap_or(0))); } ParagraphTrace::Active { serial, position, line, demerits, previous, .. } => { assert_eq!(serial, active.len() + 1); let previous_cost = if previous == 0 { 0 } else { active[&previous].3 }; assert_eq!(demerits, previous_cost + edges[&(position, previous)].1); active.insert(serial, (position, previous, line, demerits)); } ParagraphTrace::Selection { serial, accepted: true, .. } => { let mut chosen = serial; let mut badness = Vec::new(); while chosen != 0 { let (position, previous, _, _) = active[&chosen]; badness.push(edges[&(position, previous)].0); chosen = previous; } badness.reverse(); let p = e .events .iter() .find_map(|e| { if let Event::BuiltParagraph(p) = e && p.span == r.span { Some(p) } else { None } }) .unwrap(); assert_eq!(badness, p.badness); assert_eq!(active[&serial].2, p.previous_lines + p.line_boxes.len()); } _ => {} } } } #[test] fn default_scope_alias_arithmetic_channels_and_disabled_layout_are_real() { assert_eq!( State::initex() .parameter(Parameter::Tracingparagraphs) .width(), 0 ); let body = r"\hsize=75pt\pretolerance=100\tolerance=200\emergencystretch=10pt\noindent The quick brown fox jumps over the lazy dog. This paragraph has actual line breaking.\par"; let mut baseline = None; for level in [-1, 0, 1, 2] { for online in [0, 1] { let s = format!(r"{HEADER}\tracingparagraphs={level:02}\tracingonline={online} {body}\end"); let mut h = Host::default(); let e = Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "probe.tex".into(), data: s.as_bytes().to_vec(), }, &mut h, ) .unwrap(); let (log, terminal) = reference_outputs(&s); let actual_log = h .diagnostics .iter() .map(|(_, s)| s.as_str()) .collect::>() .join(""); let actual_terminal = h .diagnostics .iter() .filter(|(d, _)| *d == WriteDestination::TerminalAndLog) .map(|(_, s)| s.as_str()) .collect::>() .join(""); assert_eq!(decision_lines(&actual_log), decision_lines(&log)); assert_eq!(decision_lines(&actual_terminal), decision_lines(&terminal)); let rs = reports(&e); if level <= 0 { assert!(rs.is_empty()); assert!(h.diagnostics.is_empty()); } else { assert_eq!(rs.len(), 1); let expected = if online == 0 { WriteDestination::Log } else { WriteDestination::TerminalAndLog }; assert_eq!(rs[0].destination, expected); assert_eq!(h.diagnostics, vec![(expected, rs[0].text.clone())]); } let p = e .events .iter() .find_map(|e| { if let Event::BuiltParagraph(p) = e { Some(p) } else { None } }) .unwrap(); if let Some(lines) = &baseline { assert!( &p.line_boxes == lines, "trace level={level}, online={online} changed raw line boxes" ); } else { baseline = Some(p.line_boxes.clone()); } } } let s = format!( r"{HEADER}\let\trace=\tracingparagraphs\trace=0 {{\advance\trace by2 {body}}}\par\setbox0=\hbox{{restricted}}\par\end" ); let e = native(&s); assert_eq!(reports(&e).len(), 1); assert_eq!(e.state.parameter(Parameter::Tracingparagraphs).width(), 0); assert_selected_path(reports(&e)[0], &e); } #[test] fn real_sink_and_diagnostic_capacity_failures_do_not_publish_success() { let s = format!( r"{HEADER}\hsize=40pt\noindent alpha beta gamma delta epsilon zeta eta theta iota kappa.\par\end" ); let mut h = Host { fail: true, ..Host::default() }; let e = Executor::new(State::initex(), Limits::default()) .run( SourceFile { name: "probe.tex".into(), data: s.as_bytes().to_vec(), }, &mut h, ) .unwrap_err(); assert!( e.message .contains("actual paragraph diagnostic sink failure") ); let e = Executor::new( State::initex(), Limits { tokens: 128, ..Limits::default() }, ) .run( SourceFile { name: "probe.tex".into(), data: s.into_bytes(), }, &mut Host::default(), ) .unwrap_err(); assert!( e.message .contains("native diagnostic output limit exceeded"), "{e:?}" ); } #[test] fn canonical_zero_literal_arithmetic_expressions_fonts_ligatures_and_raw_slots_match_tex() { let zero = r"\hsize=1000pt\noindent a\hskip0pt b\hskip\skip0 c\hskip-\skip0 d\hskip\glueexpr0pt\relax e\hskip\glueexpr\skip0\relax f\par"; let body = r"\hsize=75pt\pretolerance=100\tolerance=200\emergencystretch=10pt "; for content in [ zero.to_string(), r"\skip0=0pt plus0fil\skip1=1pt\advance\skip1 by-1pt\hsize=1000pt\noindent a\hskip\skip0 b\hskip\skip1 c\hskip\glueexpr(\skip0)\relax d\hskip\glueexpr\skip0*1\relax e\hskip\glueexpr\skip0+0pt\relax f\par".into(), format!( r"{body}\defaulthyphenchar=45\font\it=cmti10\noindent office {{\it efficient affinity}} difficult ffi fly fluff.\par" ), format!( r"{body}\font\longfontidentifierwithmanylettersthatwrapsdiagnostics=cmr10 at11pt\longfontidentifierwithmanylettersthatwrapsdiagnostics\noindent\char0\char1\char11 ABCDEFGHIJKLMNOPQRSTUVWXYZ alpha beta gamma delta.\par" ), format!( r"{body}\noindent aaa\hskip0pt bbb\hskip\leftskip ccc\mark{{actual}} ddd\write16{{LATE}} eee fff ggg hhh iii.\par" ), ] { let s = format!(r"{HEADER}{content}\end"); let e = native(&s); assert_eq!(reports(&e)[0].text.trim_end(), reference(&s), "{content}"); assert_selected_path(reports(&e)[0], &e); } // The canonical zero reference and an allocated zero have equal dimensions, // while short_display and copying retain their actual specification identity. let e = native(&format!(r"{HEADER}{zero}\end")); let p = e .events .iter() .find_map(|e| { if let Event::BuiltParagraph(p) = e { Some(p) } else { None } }) .unwrap(); let flags: Vec<_> = p .nodes .iter() .filter_map(|n| { if let TextNode::Glue(g) = n { Some(g.canonical_zero) } else { None } }) .collect(); assert_eq!(flags, [false, true, false, false, true]); } #[test] fn actual_automatic_hyphenation_reconstruction_and_display_continuation_match_tex() { let codes: String = (b'a'..=b'z') .map(|c| format!("\\lccode{}={} ", c, c)) .collect(); for width in [40, 70] { for pretolerance in [-1, 100] { for body in [ r"\hyphenation{hy-phen-a-tion al-go-rithm}\noindent hyphenation algorithm hyphenation algorithm hyphenation.\par", r"\hyphenation{of-fice ef-fi-cient dif-fi-cult}\noindent office efficient difficult office efficient difficult office.\par", r"\patterns{a1b b1c c1d}\noindent abcdef abcdef abcdef abcdef abcdef abcdef.\par", ] { let s = format!( r"{HEADER}{codes}\hyphenchar\f=45\lefthyphenmin=1\righthyphenmin=1\hyphenpenalty=50\exhyphenpenalty=50\hsize={width}pt\pretolerance={pretolerance}\tolerance=200\emergencystretch=5pt {body}\end" ); let e = native(&s); let r = reports(&e)[0]; assert_eq!( r.text.trim_end(), reference(&s), "w={width}, p={pretolerance}: {body}" ); assert_selected_path(r, &e); } } } let fonts = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); let s = format!( r"{fonts}{HEADER}\vsize=1000pt\hsize=80pt\pretolerance=100\tolerance=200\emergencystretch=10pt\noindent alpha beta gamma delta epsilon zeta $$x+1$$ after display alpha beta gamma delta epsilon zeta eta theta.\par\end" ); let e = native(&s); let rs = reports(&e); assert_eq!(rs.len(), 2); let text = rs .iter() .map(|r| r.text.as_str()) .collect::>() .join(""); let (log, terminal) = reference_outputs(&s); assert_eq!(decision_lines(&text), decision_lines(&log)); assert_eq!(decision_lines(&text), decision_lines(&terminal)); for r in rs { assert_selected_path(r, &e); } }