use std::{ fs, path::{Path, PathBuf}, process::Command, sync::atomic::{AtomicU64, Ordering}, }; use texrra_tex_core::{ execution::*, resources::{FileWorld, LoadedResource, ResourceKind, SearchPath, WorldConfig}, }; const HEADER: &str = r"\catcode123=1\catcode125=2\catcode35=6\newlinechar=33 "; fn directory() -> PathBuf { static N: AtomicU64 = AtomicU64::new(0); let p = std::env::temp_dir().join(format!( "texrra-stats-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&p).unwrap(); p } struct Files { world: FileWorld, output: Vec<(WriteDestination, String)>, reject: bool, errors: usize, } impl Files { fn new(dir: &Path) -> Self { let mut c = WorldConfig::new(dir); c.paths.insert( ResourceKind::Tfm, vec![SearchPath::directory( Path::new(env!("CARGO_MANIFEST_DIR")).join("assets"), false, )], ); Self { world: FileWorld::new(c).unwrap(), output: vec![], reject: false, errors: 0, } } } impl SourceProvider for Files { fn read(&mut self, n: &str, f: &str) -> Result { let r = self.world.read(ResourceKind::Tex, n, Path::new(f))?; Ok(SourceFile { name: r.version.path.display().to_string(), data: r.data, }) } fn resource(&mut self, k: ResourceKind, n: &str, f: &str) -> Result { self.world.read(k, n, Path::new(f)) } fn resource_usage(&mut self) -> Result, String> { Ok(Some(HostResourceUsage::from_trace(self.world.trace()))) } fn observe_diagnostic(&mut self, d: WriteDestination, s: &str) -> Result<(), String> { if self.reject { return Err("actual statistics sink failure".into()); } self.output.push((d, s.into())); Ok(()) } fn observe_error(&mut self, _: &Error) -> Result<(), String> { self.errors += 1; Ok(()) } } fn native(source: &str, files: &mut Files) -> Result { Executor::new(State::initex().with_etex(), Limits::default()) .with_native_pages() .run( SourceFile { name: "probe.tex".into(), data: format!("{HEADER}{source}").into_bytes(), }, files, ) } fn reports(e: &Execution) -> Vec<&StatisticsReport> { e.events .iter() .filter_map(|v| match v { Event::Statistics(s) => Some(s.as_ref()), _ => None, }) .collect() } fn reference(s: &str, p: &Path) -> (Vec, String) { fs::write(p.join("probe.tex"), format!("{HEADER}{s}")).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(), "{}", String::from_utf8_lossy(&r.stdout)); (r.stdout, fs::read_to_string(p.join("probe.log")).unwrap()) } #[test] fn stats_defaults_scopes_aliases_arithmetic_and_end_timing_match_real_tex() { let p = directory(); let s = r"\message{!ST=\number\tracingstats;!}{\let\S=\tracingstats\S=1\advance\S by1\message{!ST=\number\tracingstats;!}}\message{!ST=\number\tracingstats;!}\tracingstats=0\end"; let e = native(s, &mut Files::new(&p)).unwrap(); let (_, log) = reference(s, &p); let actual: Vec<_> = e .events .iter() .filter_map(|e| { if let Event::Message { text, .. } = e { Some(text.trim()) } else { None } }) .collect(); assert_eq!( actual, log.lines() .filter(|s| s.starts_with("ST=")) .collect::>() ); assert!(reports(&e).is_empty()); fs::remove_dir_all(p).unwrap(); } #[test] fn real_trace_levels_channels_and_void_shipouts_match_tex_without_fake_arena_counts() { let p = directory(); for level in [-1, 0, 1, 2, 3] { let s = format!( r"\tracingstats={level}\setbox0=\hbox{{\kern1pt}}\shipout\copy0\shipout\box0\shipout\box0\end" ); let mut files = Files::new(&p); let e = native(&s, &mut files).unwrap(); let (terminal, log) = reference(&s, &p); let r = reports(&e); let native_pages = r .iter() .filter(|s| matches!(s.phase, StatisticsPhase::Shipout { .. })) .count(); let native_end = r .iter() .filter(|s| matches!(s.phase, StatisticsPhase::End { .. })) .count(); assert_eq!( native_pages, String::from_utf8_lossy(&terminal) .matches("Memory usage before:") .count() ); assert_eq!(native_pages, log.matches("Memory usage before:").count()); assert_eq!( native_end, log.matches("Here is how much of TeX's memory you used:") .count() ); assert!(!String::from_utf8_lossy(&terminal).contains("Here is how much")); for report in r { assert!(!report.text.contains("words of memory")); assert!(!report.text.contains("still untouched")); match &report.phase { StatisticsPhase::Shipout { before, after } => { assert_eq!(report.destination, WriteDestination::TerminalAndLog); assert_eq!(after.retained_shipouts, before.retained_shipouts + 1); assert_eq!( before.active_material.records() - after.active_material.records(), after.retained_material.records() - before.retained_material.records() ); assert_eq!(after.retained_events, before.retained_events + 1); } StatisticsPhase::End { success, usage } => { assert!(*success); assert_eq!(report.destination, WriteDestination::Log); assert_eq!(usage.retained_shipouts, 2); assert_eq!(usage.active_material.records(), 0); assert_eq!(usage.source_payload_bytes, format!("{HEADER}{s}").len()); assert_eq!(usage.mouth_payload_bytes, 0); assert!(usage.stack_peaks.input_frames > 0); } } } assert_eq!(files.output.len(), native_pages + native_end); let decoded: Execution = serde_json::from_slice(&serde_json::to_vec(&e).unwrap()).unwrap(); assert_eq!(e, decoded); } fs::remove_dir_all(p).unwrap(); } #[test] fn genuine_macro_aliases_saved_bodies_token_lists_fonts_and_resources_are_measured() { let p = directory(); fs::write( p.join("child.tex"), r"\def\shared#1{#1AB}\let\alias=\shared\toks0={CDE}\font\F=cmr10\F", ) .unwrap(); let s = r"\input child.tex \tracingstats=2\setbox0=\hbox{\shared{X}}{\def\shared{ZZ}\shipout\copy0}\shipout\box0\end"; let mut files = Files::new(&p); let e = native(s, &mut files).unwrap(); let r = reports(&e); let first = r .iter() .find_map(|s| { if let StatisticsPhase::Shipout { before, .. } = &s.phase { Some(before) } else { None } }) .unwrap(); assert_eq!(first.state.macro_bindings, 2); assert_eq!(first.unique_macro_bodies, 2); assert!(first.state.save_entries > 0); assert!(first.token_list_cells >= 3); assert_eq!(first.state.font_instances, 1); assert_eq!(first.state.tfm_resources, 1); assert_eq!( first.state.tfm_resource_bytes, fs::metadata(Path::new(env!("CARGO_MANIFEST_DIR")).join("assets/cmr10.tfm")) .unwrap() .len() ); let last = r .iter() .find_map(|s| { if let StatisticsPhase::End { usage, .. } = &s.phase { Some(usage) } else { None } }) .unwrap(); assert_eq!(last.state.macro_bindings, 2); assert_eq!( last.unique_macro_bodies, 1, "alias and original share the actual Arc, not duplicate fake macro allocations" ); assert_eq!(last.state.save_entries, 0); assert_eq!(last.source_files, 2); let host = last.host.as_ref().unwrap(); assert_eq!(host.resource_reads, 2); assert_eq!( host.resource_bytes_read, files .world .trace() .reads .iter() .map(|r| r.bytes) .sum::() ); assert_eq!(last.retained_shipouts, 2); assert!(e.reads.contains(&Dependency::ResourceStatistics)); fs::remove_dir_all(p).unwrap(); } #[test] fn local_switches_failures_sink_errors_and_unknown_host_metrics_are_not_silenced() { let p = directory(); let s = r"\setbox0=\hbox{\kern1pt}{\tracingstats=2\shipout\copy0}\shipout\box0\end"; let e = native(s, &mut Files::new(&p)).unwrap(); let (term, log) = reference(s, &p); assert_eq!(reports(&e).len(), 1); assert_eq!( String::from_utf8_lossy(&term) .matches("Memory usage before:") .count(), 1 ); assert!(!log.contains("Here is how much")); let mut files = Files::new(&p); let e = native(r"\tracingstats=1\relax\badcommand\end", &mut files).unwrap_err(); assert!(e.message.contains("badcommand")); assert_eq!(files.errors, 1); assert!(files.output.iter().any(|(d,s)|*d==WriteDestination::Log&&s.contains("core execution end (failure)"))); let mut files = Files::new(&p); files.reject = true; let e = native(r"\tracingstats=1\end", &mut files).unwrap_err(); assert!(e.message.contains("actual statistics sink failure")); assert_eq!(files.errors, 1); let e = Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "probe.tex".into(), data: format!(r"{HEADER}\tracingstats=1\end").into_bytes(), }, &mut NoFiles, ) .unwrap(); assert!( reports(&e) .iter() .any(|r| if let StatisticsPhase::End { usage, .. } = &r.phase { usage.host.is_none() } else { false }) ); assert!(reports(&e)[0].text.contains("telemetry unavailable")); fs::remove_dir_all(p).unwrap(); } #[test] fn statistics_observe_real_paragraph_math_output_and_language_data_without_rewriting_lists() { let p = directory(); let fonts = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); let mut executions = Vec::new(); for level in [0, 2] { let source = format!( r"{fonts}\tracingstats={level}\hsize=60pt\vsize=30pt\topskip=10pt\maxdepth=2pt\baselineskip=12pt\lineskip=1pt\lineskiplimit=0pt\pretolerance=-1\tolerance=10000\parfillskip=0pt plus1fil\vbadness=10000\lccode97=97\lccode98=98\patterns{{a1b}}\hyphenation{{a-b}}\setbox3=\hbox{{kept}}\output={{\shipout\box255}}Alpha beta $x_i^2+y$ gamma delta.\par More actual lines with a\discretionary{{X}}{{Y}}{{Z}}b.\par\end" ); executions.push(native(&source, &mut Files::new(&p)).unwrap()); } assert_eq!( executions[0].shipout_display_lists().unwrap(), executions[1].shipout_display_lists().unwrap() ); let report = reports(&executions[1]) .into_iter() .find_map(|r| { if let StatisticsPhase::End { usage, .. } = &r.phase { Some(usage) } else { None } }) .unwrap(); assert!(report.retained_material.math_nodes > 0); assert!(report.retained_material.geometry_items > 0); assert!(report.retained_material.diagnostic_nodes > 0); assert!(report.active_material.boxes > 0); assert_eq!(report.state.hyphenation_exceptions, 1); assert!(report.state.hyphenation_trie_nodes > 0); assert!(report.state.hyphenation_edges > 0); assert!(report.state.pattern_weight_cells > 0); assert!(report.stack_peaks.math_frames > 0); assert!(report.stack_peaks.box_frames > 0); fs::remove_dir_all(p).unwrap(); }