1use std::{
2 borrow::Cow,
3 cell::RefCell,
4 error::Error as ErrorTrait,
5 fmt, io,
6 num::{ParseFloatError, ParseIntError},
7 result,
8 sync::LazyLock,
9};
10
11use rustc_hash::FxHashSet;
12
13use crate::common::arena::SymHashMap;
14
15#[derive(Debug, Clone, Default)]
16pub struct LogState {
17 pub undefined: SymHashMap<usize>,
18 pub missing: SymHashMap<usize>,
19 pub debug: usize,
20 pub info: usize,
21 pub warning: usize,
22 pub error: usize,
23 pub fatal: bool,
24 pub status_code: usize,
25}
26pub enum LogStatus {
27 Debug,
28 Info,
29 Warning,
30 Error,
31 Fatal,
32 Undefined,
33 Missing,
34}
35
36thread_static! {
37 pub static REPORT: RefCell<LogState> = RefCell::new(LogState::default());
38}
39
40thread_local! {
41 static MACRO_DIAG_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
45}
46
47pub struct MacroDiagGuard(());
58impl Drop for MacroDiagGuard {
59 fn drop(&mut self) { MACRO_DIAG_DEPTH.set(MACRO_DIAG_DEPTH.get().saturating_sub(1)); }
60}
61#[must_use = "the guard must live across the log emission it marks"]
62pub fn macro_diag_guard() -> MacroDiagGuard {
63 MACRO_DIAG_DEPTH.set(MACRO_DIAG_DEPTH.get() + 1);
64 MacroDiagGuard(())
65}
66
67pub fn note_status_from_logger(status: LogStatus) {
73 if MACRO_DIAG_DEPTH.get() > 0 || REPORT.try_borrow_mut().is_err() {
74 return;
75 }
76 note_status(status, None);
77}
78
79thread_local! {
80 static SUPPRESS_LOG_OUTPUT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
86}
87
88pub fn set_suppress_log_output(suppress: bool) -> bool {
90 let prev = SUPPRESS_LOG_OUTPUT.get();
91 SUPPRESS_LOG_OUTPUT.set(suppress);
92 prev
93}
94
95#[must_use = "the suppression ends when the guard is dropped"]
100pub struct SuppressLogOutputGuard {
101 prev: bool,
102}
103
104impl SuppressLogOutputGuard {
105 pub fn new(suppress: bool) -> Self {
107 SuppressLogOutputGuard {
108 prev: set_suppress_log_output(suppress),
109 }
110 }
111}
112
113impl Drop for SuppressLogOutputGuard {
114 fn drop(&mut self) { SUPPRESS_LOG_OUTPUT.set(self.prev); }
115}
116
117pub fn reset_suppress_log_output() {
120 SUPPRESS_LOG_OUTPUT.set(false);
121 SILENCE_PROGRESS_NOTES.set(false);
122 DEFERRED_NOTES.borrow_mut().clear();
123}
124
125pub(crate) fn shrink_error_notes() {
127 *DEFERRED_NOTES.borrow_mut() = Vec::new();
128 *LAST_ERROR_KEY.borrow_mut() = None;
129}
130
131thread_local! {
141 static DEMOTE_FATALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
142}
143
144pub fn set_demote_fatals(demote: bool) -> bool {
146 DEMOTE_FATALS.with(|c| {
147 let prev = c.get();
148 c.set(demote);
149 prev
150 })
151}
152
153pub fn is_demote_fatals() -> bool { DEMOTE_FATALS.with(|c| c.get()) }
155
156pub fn is_log_output_suppressed() -> bool { SUPPRESS_LOG_OUTPUT.get() }
158
159thread_local! {
160 static IGNORE_DIAGNOSTICS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
161}
162
163pub fn set_ignore_diagnostics(ignore: bool) -> bool {
171 let prev = IGNORE_DIAGNOSTICS.get();
172 IGNORE_DIAGNOSTICS.set(ignore);
173 prev
174}
175pub fn diagnostics_ignored() -> bool { IGNORE_DIAGNOSTICS.get() }
178
179thread_local! {
180 static IGNORED_RECORDS: std::cell::Cell<IgnoredRecords> =
182 const { std::cell::Cell::new(IgnoredRecords { errors: 0, fatals: 0 }) };
183}
184
185#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
187pub struct IgnoredRecords {
188 pub errors: usize,
189 pub fatals: usize,
190}
191
192pub struct IgnoreDiagnosticsScope {
196 previous: bool,
197 before: IgnoredRecords,
198}
199impl IgnoreDiagnosticsScope {
200 pub fn new() -> Self {
201 Self {
202 previous: set_ignore_diagnostics(true),
203 before: IGNORED_RECORDS.get(),
204 }
205 }
206 pub fn dropped(&self) -> IgnoredRecords {
209 let now = IGNORED_RECORDS.get();
210 IgnoredRecords {
211 errors: now.errors - self.before.errors,
212 fatals: now.fatals - self.before.fatals,
213 }
214 }
215}
216impl Default for IgnoreDiagnosticsScope {
217 fn default() -> Self { Self::new() }
218}
219impl Drop for IgnoreDiagnosticsScope {
220 fn drop(&mut self) { set_ignore_diagnostics(self.previous); }
221}
222
223thread_local! {
224 static FATALS_LOGGED: RefCell<FxHashSet<String>> = RefCell::new(FxHashSet::default());
228}
229
230thread_static! {
231 static LAST_ERROR_KEY: RefCell<Option<String>> = RefCell::new(None);
239}
240thread_local! {
241 static CONSECUTIVE_ERROR_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
242}
243
244pub const MAX_CONSECUTIVE_ERRORS: usize = 500;
254
255pub fn note_consecutive_error(key: &str) -> usize {
259 let mut last = LAST_ERROR_KEY.borrow_mut();
260 if last.as_deref() == Some(key) {
261 let c = CONSECUTIVE_ERROR_COUNT.get() + 1;
262 CONSECUTIVE_ERROR_COUNT.set(c);
263 c
264 } else {
265 *last = Some(key.to_string());
266 CONSECUTIVE_ERROR_COUNT.set(1);
267 1
268 }
269}
270
271pub fn runaway_message(key: &str) -> String {
273 format!("Runaway: same error '{key}' fired over {MAX_CONSECUTIVE_ERRORS} times in a row")
274}
275
276pub fn runaway_reraise(key: &str) -> Error {
280 let fatal = Error::from(ErrorData {
281 target: ErrorTarget::TooManyErrors,
282 category: ErrorCategory::MaxLimit(MAX_CONSECUTIVE_ERRORS),
283 message: runaway_message(key),
284 });
285 fatal.mark_logged_fatal();
286 fatal
287}
288
289pub fn message_object<'a>(object: &'a str, fallback: &'a str) -> &'a str {
294 match object.trim_start() {
295 "" => fallback,
296 trimmed => trimmed,
297 }
298}
299
300fn record_target(target: &str) -> Cow<'_, str> {
303 let body = target.strip_prefix("Fatal:").unwrap_or(target);
304 let Some((category, object)) = body.split_once(':') else {
305 return Cow::Borrowed(target);
306 };
307 let what = message_object(object, "unknown");
308 if what == object {
310 return Cow::Borrowed(target);
311 }
312 let fatal = if body.len() < target.len() {
313 "Fatal:"
314 } else {
315 ""
316 };
317 Cow::Owned(format!("{fatal}{category}:{what}"))
318}
319
320pub fn emit_record(status: LogStatus, target: &str, message: &str) {
330 let _diag_guard = macro_diag_guard();
331 let target = &*record_target(target);
332 if diagnostics_ignored() {
335 let mut tally = IGNORED_RECORDS.get();
336 match status {
337 LogStatus::Error => tally.errors += 1,
338 LogStatus::Fatal => tally.fatals += 1,
339 _ => {},
340 }
341 IGNORED_RECORDS.set(tally);
342 return;
343 }
344 if matches!(status, LogStatus::Error) && errors_ignored_after_fatal() {
355 MUTED_ERRORS.set(MUTED_ERRORS.get() + 1);
356 return;
357 }
358 let level = match status {
359 LogStatus::Debug => log::Level::Debug,
360 LogStatus::Info => log::Level::Info,
361 LogStatus::Warning => log::Level::Warn,
362 _ => log::Level::Error,
363 };
364 let unconditional = matches!(status, LogStatus::Error | LogStatus::Fatal);
365 note_status(status, None);
366 if unconditional || !is_log_output_suppressed() {
367 log::log!(target: target, level, "{message}");
368 }
369}
370
371pub fn emit_info(category: &str, object: &str, message: &str) {
388 emit_record(LogStatus::Info, &format!("{category}:{object}"), message);
389}
390
391pub fn emit_warn(category: &str, object: &str, message: &str) {
393 emit_record(LogStatus::Warning, &format!("{category}:{object}"), message);
394}
395
396pub const APPROXIMATED_MEASURE: &str = "lx_approximated_measure";
399const APPROXIMATED_MEASURE_REPORTED: &str = "lx_approximated_measure_reported";
400
401pub fn approximated_measure() -> Option<(String, bool)> {
406 let name = crate::state::try_lookup_string(APPROXIMATED_MEASURE)?;
407 let first = crate::state::try_lookup_string(APPROXIMATED_MEASURE_REPORTED).as_deref()
408 != Some(name.as_str());
409 if first {
410 crate::state::try_assign_value_global(APPROXIMATED_MEASURE_REPORTED, name.clone().into());
411 }
412 Some((
413 format!("in {name}, set as one box where TeX breaks it: the size is ours"),
414 first,
415 ))
416}
417
418pub fn emit_error(category: &str, object: &str, message: &str) {
425 emit_record(LogStatus::Error, &format!("{category}:{object}"), message);
426 note_error_cap(&format!("{category}:{object}"));
427}
428
429pub fn note_error_cap(key: &str) {
433 if is_demote_fatals() || diagnostics_ignored() || FATAL_MUTE.with(|m| m.borrow().is_some()) {
436 return;
437 }
438 let maxerrors = match crate::state::try_lookup_int("MAX_ERRORS") {
439 None => usize::MAX, Some(v) if v > 0 => v as usize,
441 Some(_) => 100,
442 };
443 let consec = note_consecutive_error(key);
444 if too_many_errors_latched() {
448 return;
449 }
450 let over_total = get_status(LogStatus::Error) > maxerrors;
451 let over_consec = consec > MAX_CONSECUTIVE_ERRORS;
452 if (over_total && get_status(LogStatus::Error) == maxerrors + 1)
454 || (over_consec && consec == MAX_CONSECUTIVE_ERRORS + 1)
455 {
456 latch_too_many_errors();
457 emit_fatal(
458 "TooManyErrors",
459 "MaxLimit",
460 &format!(
461 "Too many errors (> {})!",
462 if over_total {
463 maxerrors
464 } else {
465 MAX_CONSECUTIVE_ERRORS
466 }
467 ),
468 );
469 }
470}
471
472pub fn emit_fatal(category: &str, object: &str, message: &str) {
478 mute_errors_after_fatal(format!("{category}:{object}:{message}"));
479 emit_record(
480 LogStatus::Fatal,
481 &format!("Fatal:{category}:{object}"),
482 message,
483 );
484}
485
486fn reset_consecutive_error_tracker() {
488 *LAST_ERROR_KEY.borrow_mut() = None;
489 CONSECUTIVE_ERROR_COUNT.set(0);
490 TOO_MANY_ERRORS_LATCHED.set(false);
491 TOO_MANY_ERRORS_SPENT.set(false);
492}
493
494thread_local! {
495 static TOO_MANY_ERRORS_LATCHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
496}
497
498pub fn latch_too_many_errors() { TOO_MANY_ERRORS_LATCHED.set(true); }
503pub fn too_many_errors_latched() -> bool { TOO_MANY_ERRORS_LATCHED.get() }
505
506thread_local! {
507 static TOO_MANY_ERRORS_SPENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
508}
509
510pub fn spend_too_many_errors() {
515 if too_many_errors_latched() {
516 TOO_MANY_ERRORS_SPENT.set(true);
517 }
518}
519pub fn too_many_errors_spent() -> bool { TOO_MANY_ERRORS_SPENT.get() }
521
522#[derive(Clone, Default)]
529pub struct DiagnosticGates {
530 pub report: LogState,
532 last_error_key: Option<String>,
533 consecutive: usize,
534 too_many_errors: bool,
535 too_many_spent: bool,
536 fatals_logged: FxHashSet<String>,
537 fatal_mute: Option<String>,
538 pub muted_errors: usize,
540}
541
542pub fn save_diagnostic_gates() -> DiagnosticGates {
544 DiagnosticGates {
545 report: REPORT.borrow().clone(),
546 last_error_key: LAST_ERROR_KEY.borrow().clone(),
547 consecutive: CONSECUTIVE_ERROR_COUNT.get(),
548 too_many_errors: TOO_MANY_ERRORS_LATCHED.get(),
549 too_many_spent: TOO_MANY_ERRORS_SPENT.get(),
550 fatals_logged: FATALS_LOGGED.with(|c| c.borrow().clone()),
551 fatal_mute: FATAL_MUTE.with(|m| m.borrow().clone()),
552 muted_errors: MUTED_ERRORS.get(),
553 }
554}
555
556pub fn restore_diagnostic_gates(gates: DiagnosticGates) {
558 *REPORT.borrow_mut() = gates.report;
559 *LAST_ERROR_KEY.borrow_mut() = gates.last_error_key;
560 CONSECUTIVE_ERROR_COUNT.set(gates.consecutive);
561 TOO_MANY_ERRORS_LATCHED.set(gates.too_many_errors);
562 TOO_MANY_ERRORS_SPENT.set(gates.too_many_spent);
563 FATALS_LOGGED.with(|c| *c.borrow_mut() = gates.fatals_logged);
564 FATAL_MUTE.with(|m| *m.borrow_mut() = gates.fatal_mute);
565 MUTED_ERRORS.set(gates.muted_errors);
566}
567#[macro_export]
568macro_rules! report {
569 () => {
570 (*$crate::common::error::REPORT).borrow()
571 };
572}
573#[macro_export]
574macro_rules! report_mut {
575 () => {
576 (*$crate::common::error::REPORT).borrow_mut()
577 };
578}
579
580pub fn note_status(status: LogStatus, what: Option<&str>) {
581 let mut report = REPORT.borrow_mut();
582 use LogStatus::*;
583 match status {
584 Debug => report.debug += 1,
585 Info => report.info += 1,
586 Warning => report.warning += 1,
587 Error => report.error += 1,
588 Fatal => {
589 if !report.fatal && debug_fatal_enabled() {
594 eprintln!("[debug-fatal] LogStatus::Fatal first noted here:");
595 eprintln!("{}", std::backtrace::Backtrace::force_capture());
596 }
597 report.fatal = true;
598 },
599 Undefined => {
600 let entry = report
603 .undefined
604 .entry(what.unwrap_or_default())
605 .or_insert(0);
606 *entry += 1;
607 },
608 Missing => {
609 let entry = report.missing.entry(what.unwrap_or_default()).or_insert(0);
610 *entry += 1;
611 },
612 }
613}
614
615pub fn get_status(status: LogStatus) -> usize {
616 let report = REPORT.borrow();
617 use LogStatus::*;
618 match status {
619 Debug => report.debug,
620 Info => report.info,
621 Warning => report.warning,
622 Error => report.error,
623 Fatal => {
624 if report.fatal {
625 1
626 } else {
627 0
628 }
629 },
630 Undefined => report.undefined.0.values().sum(),
631 Missing => report.missing.0.values().sum(),
632 }
633}
634
635pub fn debug_fatal_enabled() -> bool {
640 use std::sync::OnceLock;
641 static FLAG: OnceLock<bool> = OnceLock::new();
642 *FLAG.get_or_init(|| std::env::var_os("LATEXML_DEBUG_FATAL").is_some())
643}
644
645pub fn initialize_report() {
646 crate::reset_conversion_state();
648 let mut report = REPORT.borrow_mut();
649 *report = LogState::default();
650 reset_consecutive_error_tracker();
651 LAST_RESOURCE_FATAL.with(|c| *c.borrow_mut() = None);
652 RESOURCE_FATAL_SEEN.with(|c| c.set(false));
653 FATALS_LOGGED.with(|c| c.borrow_mut().clear());
654 FATAL_MUTE.with(|m| *m.borrow_mut() = None);
655 MUTED_ERRORS.set(0);
656 IGNORE_DIAGNOSTICS.set(false);
659 drop(report);
660 log_session_warnings();
661}
662
663pub fn log_session_warnings() {
666 for (target, message) in SESSION_WARNINGS.with(|held| std::mem::take(&mut *held.borrow_mut())) {
667 emit_record(LogStatus::Warning, &target, &message);
668 }
669}
670
671thread_local! {
672 static SESSION_WARNINGS: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
674}
675
676pub fn clear_session_warnings() { SESSION_WARNINGS.with(|held| held.borrow_mut().clear()) }
679
680pub fn warn_at_session_start(category: &str, object: &str, message: String) {
684 SESSION_WARNINGS.with(|held| {
685 held
686 .borrow_mut()
687 .push((format!("{category}:{object}"), message))
688 });
689}
690
691pub fn reset_arena_keyed_reports() {
697 let mut report = REPORT.borrow_mut();
698 report.undefined = Default::default();
699 report.missing = Default::default();
700}
701
702pub fn preserve_arena_keyed_reports_across(f: impl FnOnce()) {
708 let (undef, miss) = {
709 let mut report = REPORT.borrow_mut();
710 let u: Vec<(String, usize)> = report
711 .undefined
712 .0
713 .drain()
714 .map(|(k, v)| (crate::common::arena::to_string(k), v))
715 .collect();
716 let m: Vec<(String, usize)> = report
717 .missing
718 .0
719 .drain()
720 .map(|(k, v)| (crate::common::arena::to_string(k), v))
721 .collect();
722 (u, m)
723 };
724 f();
725 if !undef.is_empty() || !miss.is_empty() {
726 let mut report = REPORT.borrow_mut();
727 for (s, count) in undef {
728 *report.undefined.entry(&s).or_insert(0) += count;
729 }
730 for (s, count) in miss {
731 *report.missing.entry(&s).or_insert(0) += count;
732 }
733 }
734}
735
736thread_local! {
737 static LAST_RESOURCE_FATAL: RefCell<Option<Error>> = const { RefCell::new(None) };
747 static RESOURCE_FATAL_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
756}
757
758pub fn resource_fatal_latched() -> bool { RESOURCE_FATAL_SEEN.with(|c| c.get()) }
761
762thread_local! {
763 static FATAL_MUTE: RefCell<Option<String>> = const { RefCell::new(None) };
767 static MUTED_ERRORS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
768}
769
770pub fn muted_errors() -> usize { MUTED_ERRORS.get() }
772
773fn mute_errors_after_fatal(key: String) {
774 if !diagnostics_ignored() {
775 FATAL_MUTE.with(|m| {
776 m.borrow_mut().get_or_insert(key);
777 });
778 }
779}
780
781pub fn errors_ignored_after_fatal() -> bool {
784 FATAL_MUTE.with(|m| m.borrow().is_some()) || too_many_errors_latched() || resource_fatal_latched()
785}
786
787pub fn unmute_errors_after_caught_fatal(e: &Error) {
790 let key = e.fatal_key();
791 FATAL_MUTE.with(|m| {
792 let mut mute = m.borrow_mut();
793 if mute.as_deref() == Some(key.as_str()) {
794 *mute = None;
795 }
796 });
797}
798
799pub fn record_last_fatal(e: &Error) {
804 use ErrorCategory as C;
805 if !matches!(e.target, ErrorTarget::Timeout) {
806 return;
807 }
808 let category = match &e.category {
809 C::TokenLimit => C::TokenLimit,
810 C::PushbackLimit => C::PushbackLimit,
811 C::Recursion => C::Recursion,
812 C::IfLimit => C::IfLimit,
813 C::MemoryBudget => C::MemoryBudget,
814 C::Convert => C::Convert,
815 _ => return,
816 };
817 LAST_RESOURCE_FATAL.with(|c| {
818 *c.borrow_mut() = Some(Error::from(ErrorData {
819 target: ErrorTarget::Timeout,
820 category,
821 message: e.message.clone(),
822 }));
823 });
824 RESOURCE_FATAL_SEEN.with(|c| c.set(true));
825}
826
827pub fn unlatch_runaway_fatal() -> bool {
833 use ErrorCategory as C;
834 let runaway = LAST_RESOURCE_FATAL.with(|c| {
835 matches!(c.borrow().as_ref(), Some(e) if matches!(e.category, C::PushbackLimit | C::Recursion))
836 });
837 if runaway {
838 LAST_RESOURCE_FATAL.with(|c| *c.borrow_mut() = None);
839 RESOURCE_FATAL_SEEN.with(|c| c.set(false));
840 }
841 runaway
842}
843
844pub fn take_last_resource_fatal() -> Option<Error> {
848 LAST_RESOURCE_FATAL.with(|c| c.borrow_mut().take())
849}
850
851pub fn conversion_status_line(code: usize) -> String { format!("Status:conversion:{code}") }
862
863pub fn conversion_verdict(code: usize) -> String {
869 format!(
870 "Conversion {}: {}",
871 if code >= 3 { "failed" } else { "complete" },
872 get_status_message()
873 )
874}
875
876pub fn get_status_message() -> String {
877 let report = REPORT.borrow();
878 let mut parts = Vec::new();
879 if report.warning > 0 {
880 parts.push(format!(
881 "{} warning{}",
882 report.warning,
883 if report.warning > 1 { "s" } else { "" }
884 ));
885 }
886 if report.error > 0 {
887 parts.push(format!(
888 "{} error{}",
889 report.error,
890 if report.error > 1 { "s" } else { "" }
891 ));
892 }
893 if report.fatal {
894 parts.push("1 fatal error".to_string());
895 }
896 let mut undef_keys: Vec<String> = report
900 .undefined
901 .keys()
902 .map(|k| crate::common::arena::to_string(*k))
903 .collect();
904 undef_keys.sort_unstable();
905 if !undef_keys.is_empty() {
906 parts.push(format!(
907 "{} undefined macro{}[{}]",
908 undef_keys.len(),
909 if undef_keys.len() > 1 { "s" } else { "" },
910 undef_keys.join(", ")
911 ));
912 }
913 let mut miss_keys: Vec<String> = report
914 .missing
915 .keys()
916 .map(|k| crate::common::arena::to_string(*k))
917 .collect();
918 miss_keys.sort_unstable();
919 if !miss_keys.is_empty() {
920 parts.push(format!(
921 "{} missing file{}[{}]",
922 miss_keys.len(),
923 if miss_keys.len() > 1 { "s" } else { "" },
924 miss_keys.join(", ")
925 ));
926 }
927 if parts.is_empty() {
928 "No obvious problems".to_string()
929 } else {
930 parts.join("; ")
931 }
932}
933
934pub fn get_status_code() -> usize {
937 let report = REPORT.borrow();
938 if report.fatal {
939 3
940 } else if report.error > 0 {
941 2
942 } else if report.warning > 0 {
943 1
944 } else {
945 0
946 }
947}
948
949#[derive(Default, Clone, Copy)]
958pub struct ReportCounts {
959 pub debug: usize,
960 pub info: usize,
961 pub warning: usize,
962 pub error: usize,
963 pub fatal: bool,
964}
965
966pub fn snapshot_report_counts() -> ReportCounts {
968 let r = REPORT.borrow();
969 ReportCounts {
970 debug: r.debug,
971 info: r.info,
972 warning: r.warning,
973 error: r.error,
974 fatal: r.fatal,
975 }
976}
977
978pub fn restore_report_counts(c: ReportCounts) {
985 let mut r = REPORT.borrow_mut();
986 r.debug = c.debug;
987 r.info = c.info;
988 r.warning = c.warning;
989 r.error = c.error;
990 r.fatal = c.fatal;
991}
992
993pub fn merge_report_counts(c: ReportCounts) {
998 let mut r = REPORT.borrow_mut();
999 r.debug += c.debug;
1000 r.info += c.info;
1001 r.warning += c.warning;
1002 r.error += c.error;
1003 r.fatal |= c.fatal;
1004}
1005
1006static KNOWN_DEBUG_FEATURES: LazyLock<std::sync::RwLock<std::collections::BTreeSet<String>>> =
1015 LazyLock::new(|| std::sync::RwLock::new(std::collections::BTreeSet::new()));
1016static ENABLED_DEBUG_FEATURES: LazyLock<std::sync::RwLock<FxHashSet<String>>> =
1017 LazyLock::new(|| std::sync::RwLock::new(FxHashSet::default()));
1018
1019pub fn debuggable_feature(name: &str) {
1022 if let Ok(mut known) = KNOWN_DEBUG_FEATURES.write() {
1023 known.insert(name.to_string());
1024 }
1025}
1026
1027pub fn known_debug_features() -> Vec<String> {
1029 KNOWN_DEBUG_FEATURES
1030 .read()
1031 .map(|k| k.iter().cloned().collect())
1032 .unwrap_or_default()
1033}
1034
1035pub fn enable_debug_feature(name: &str) {
1038 if let Ok(mut enabled) = ENABLED_DEBUG_FEATURES.write() {
1039 enabled.insert(name.to_string());
1040 }
1041 log::set_max_level(log::max_level().max(log::LevelFilter::Debug));
1042}
1043
1044pub fn check_debuggable() {
1047 let known = known_debug_features();
1048 let mut unknown: Vec<String> = ENABLED_DEBUG_FEATURES
1049 .read()
1050 .map(|enabled| {
1051 enabled
1052 .iter()
1053 .filter(|f| !known.contains(f))
1054 .cloned()
1055 .collect()
1056 })
1057 .unwrap_or_default();
1058 if !unknown.is_empty() {
1059 unknown.sort();
1060 crate::util::logger::stderr_fresh_line(&format!(
1061 "The debugging feature(s) {} were never declared\n",
1062 unknown.join(", ")
1063 ));
1064 crate::util::logger::stderr_fresh_line(&format!(
1065 "Known debugging features: {}\n",
1066 known.join(", ")
1067 ));
1068 }
1069}
1070
1071pub fn any_debug_feature_enabled() -> bool {
1073 ENABLED_DEBUG_FEATURES
1074 .read()
1075 .map(|enabled| !enabled.is_empty())
1076 .unwrap_or(false)
1077}
1078
1079pub fn debug_enabled(name: &str) -> bool {
1081 ENABLED_DEBUG_FEATURES
1082 .read()
1083 .map(|enabled| enabled.contains(name))
1084 .unwrap_or(false)
1085}
1086
1087#[inline]
1096pub fn debug_record_enabled() -> bool {
1097 crate::util::logger::debug_all() && !is_log_output_suppressed()
1098}
1099
1100#[macro_export]
1108macro_rules! DebugFeature {
1109 ($feature:literal, $($arg:tt)*) => {{
1110 if $crate::common::error::debug_enabled($feature) {
1111 let __diag_guard = $crate::common::error::macro_diag_guard();
1112 $crate::common::error::note_status(
1113 $crate::common::error::LogStatus::Debug, None);
1114 use log::debug;
1115 debug!(target: $feature, $($arg)*);
1116 }
1117 }};
1118}
1119
1120#[macro_export]
1127macro_rules! Debug {
1128 ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1129 if $crate::common::error::debug_record_enabled() {
1130 $crate::common::error::emit_record(
1131 $crate::common::error::LogStatus::Debug,
1132 &format!("{}:{}", $category, $object),
1133 &$crate::generate_message!($message))
1134 } else {
1135 $crate::common::error::note_status(
1136 $crate::common::error::LogStatus::Debug, None);
1137 }
1138 }};
1139 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1140 if $crate::common::error::debug_record_enabled() {
1141 $crate::common::error::emit_record(
1142 $crate::common::error::LogStatus::Debug,
1143 &format!("{}:{}", $category, $object),
1144 &$crate::generate_message!($message, $($details),*))
1145 } else {
1146 $crate::common::error::note_status(
1147 $crate::common::error::LogStatus::Debug, None);
1148 }
1149 }};
1150 ($($simple:expr_2021),*) => {{
1151 $crate::common::error::note_status(
1152 $crate::common::error::LogStatus::Debug, None);
1153 if $crate::common::error::debug_record_enabled() {
1154 let __diag_guard = $crate::common::error::macro_diag_guard();
1155 use log::debug;
1156 debug!($($simple),*);
1157 }
1158 }};
1159
1160}
1161
1162#[macro_export]
1163macro_rules! Info {
1164 ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1165 $crate::common::error::emit_info(
1166 &format!("{}", $category), &format!("{}", $object),
1167 &$crate::generate_message!($message))
1168 }};
1169 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1170 $crate::common::error::emit_info(
1171 &format!("{}", $category), &format!("{}", $object),
1172 &$crate::generate_message!($message, $($details),*))
1173 }};
1174 ($($simple:expr_2021),*) => {{
1175 let __diag_guard = $crate::common::error::macro_diag_guard();
1176 $crate::common::error::note_status(
1177 $crate::common::error::LogStatus::Info, None);
1178 use log::info;
1179 info!($($simple),*);
1180 }};
1181
1182}
1183
1184#[macro_export]
1185macro_rules! Warn {
1186 ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1187 $crate::common::error::emit_warn(
1188 &format!("{}", $category), &format!("{}", $object),
1189 &$crate::generate_message!($message))
1190 }};
1191 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1192 $crate::common::error::emit_warn(
1193 &format!("{}", $category), &format!("{}", $object),
1194 &$crate::generate_message!($message, $($details),*))
1195 }}
1196}
1197
1198#[macro_export]
1199macro_rules! Error {
1200 ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1201 $crate::Error!($category,$object,$message,"")
1202 }};
1203 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1204 $crate::common::error::emit_record(
1205 $crate::common::error::LogStatus::Error,
1206 &format!("{}:{}", $category, $object),
1207 &$crate::generate_message!($message, $($details),*),
1208 );
1209 if !$crate::common::error::is_demote_fatals()
1221 && !$crate::common::error::diagnostics_ignored()
1222 && !$crate::common::error::too_many_errors_spent()
1223 {
1224 let max_from_state = $crate::state::try_lookup_int("MAX_ERRORS");
1229 let maxerrors = match max_from_state {
1235 None => usize::MAX,
1239 Some(v) if v > 0 => v as usize,
1240 Some(_) => 100,
1241 };
1242 if $crate::common::error::get_status($crate::common::error::LogStatus::Error) > maxerrors {
1243 $crate::common::error::latch_too_many_errors();
1244 Fatal!(TooManyErrors, MaxLimit(maxerrors), format!("Too many errors (> {maxerrors})!"));
1245 }
1246 let __consec_key = format!("{}:{}", $category, $object);
1255 let __consec = $crate::common::error::note_consecutive_error(&__consec_key);
1256 if __consec > $crate::common::error::MAX_CONSECUTIVE_ERRORS {
1257 if $crate::common::error::too_many_errors_latched() {
1259 return Err($crate::common::error::runaway_reraise(&__consec_key));
1260 }
1261 $crate::common::error::latch_too_many_errors();
1262 Fatal!(
1263 TooManyErrors,
1264 MaxLimit($crate::common::error::MAX_CONSECUTIVE_ERRORS),
1265 $crate::common::error::runaway_message(&__consec_key)
1266 );
1267 }
1268 }
1269 }}
1270}
1271
1272#[macro_export]
1274macro_rules! Fatal {
1275 ($target:expr_2021, $category:expr_2021, $message:expr_2021) => {{
1276 {
1277 use $crate::common::error::{Error as LatexmlError, ErrorCategory::*, ErrorTarget::*};
1278 let __fatal_err = LatexmlError::from($crate::common::error::ErrorData {
1279 target: $target,
1280 category: $category,
1281 message: $message.to_string(),
1282 });
1283 if $crate::common::error::is_demote_fatals() {
1284 $crate::common::error::emit_record(
1290 $crate::common::error::LogStatus::Error,
1291 "demoted_fatal",
1292 &format!("{}", $message),
1293 );
1294 } else {
1295 __fatal_err.log_fatal();
1301 }
1302 $crate::common::error::record_last_fatal(&__fatal_err);
1306 return Err(__fatal_err);
1307 }
1308 }};
1309}
1310
1311#[macro_export]
1312macro_rules! fatal {
1313 ($target:expr_2021, $category:expr_2021, $message:expr_2021) => {{
1314 use $crate::common::error::{Error as LatexmlError, ErrorCategory::*, ErrorTarget::*};
1315 let __fatal_err = LatexmlError::from($crate::common::error::ErrorData {
1316 target: $target,
1317 category: $category,
1318 message: $message.to_string(),
1319 });
1320 __fatal_err.log_fatal();
1324 $crate::common::error::record_last_fatal(&__fatal_err);
1331 return Err(__fatal_err);
1332 }};
1333}
1334
1335pub fn location_line() -> String {
1337 crate::gullet::get_location_opt()
1338 .map(|at| format!("\n\t{at}"))
1339 .unwrap_or_default()
1340}
1341
1342#[macro_export]
1343macro_rules! generate_message {
1344 ($message:expr_2021) => {
1345 format!(
1346 "{}{}\n\tIn {}:{}:{}\n",
1347 $message,
1348 $crate::common::error::location_line(),
1349 file!(),
1350 line!(),
1351 column!()
1352 )
1353 };
1354 ($message:expr_2021, $detail:expr_2021) => {
1355 format!(
1356 "{}{}\n\t{}\n\tIn {}:{}:{}\n",
1357 $message,
1358 $crate::common::error::location_line(),
1359 $detail,
1360 file!(),
1361 line!(),
1362 column!()
1363 )
1364 };
1365 ($message:expr_2021, $detail:expr_2021, $detail2:expr_2021) => {
1366 format!(
1367 "{}{}\n\t{}\n\t{}\n\tIn {}:{}:{}\n",
1368 $message,
1369 $crate::common::error::location_line(),
1370 $detail,
1371 $detail2,
1372 file!(),
1373 line!(),
1374 column!()
1375 )
1376 };
1377 ($message:expr_2021, $detail:expr_2021, $detail2:expr_2021) => {
1378 format!(
1379 "{}{}\n\t{}\n\t{}\n\tIn {}:{}:{}\n",
1380 $message,
1381 $crate::common::error::location_line(),
1382 $detail,
1383 $detail2,
1384 file!(),
1385 line!(),
1386 column!()
1387 )
1388 };
1389 ($message:expr_2021, $detail:expr_2021, $detail2:expr_2021, $location:expr_2021) => {
1390 format!(
1391 "{}\n\t{}\n\t{}\n\t{}\n\tIn {}:{}:{}\n",
1392 $message,
1393 $location,
1394 $detail,
1395 $detail2,
1396 file!(),
1397 line!(),
1398 column!()
1399 )
1400 };
1401}
1402
1403#[macro_export]
1410macro_rules! Note {
1411 ($input:expr_2021) => {{
1412 let msg = $input;
1413 $crate::util::logger::note_to_log(&msg.to_string());
1414 if !$crate::common::error::is_log_output_suppressed()
1415 && $crate::util::logger::stderr_shows_info()
1416 {
1417 $crate::util::logger::stderr_fresh_line(&format!("{msg}\n"));
1419 }
1420 }};
1421}
1422
1423#[macro_export]
1426macro_rules! NoteLog {
1427 ($input:expr_2021) => {
1428 $crate::util::logger::note_to_log(&($input).to_string());
1429 };
1430}
1431
1432#[macro_export]
1437macro_rules! NoteSTDERR {
1438 ($input:expr_2021) => {
1439 if !$crate::common::error::is_log_output_suppressed()
1440 && $crate::util::logger::stderr_shows_info()
1441 {
1442 let msg = $input;
1443 $crate::common::error::print_deferred_notes();
1445 $crate::util::logger::stderr_fresh_line(&format!("{msg}\n"));
1446 }
1447 };
1448}
1449
1450pub type Result<T> = result::Result<T, Error>;
1451
1452pub struct Error(Box<ErrorData>);
1453
1454impl fmt::Debug for Error {
1457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458 f.debug_struct("Error")
1459 .field("target", &self.target)
1460 .field("category", &self.category)
1461 .field("message", &self.message)
1462 .finish()
1463 }
1464}
1465
1466#[derive(Debug)]
1470pub struct ErrorData {
1471 pub target: ErrorTarget,
1472 pub category: ErrorCategory,
1473 pub message: String,
1474}
1475
1476impl From<ErrorData> for Error {
1477 fn from(data: ErrorData) -> Self { Error(Box::new(data)) }
1478}
1479
1480impl std::ops::Deref for Error {
1481 type Target = ErrorData;
1482
1483 fn deref(&self) -> &ErrorData { &self.0 }
1484}
1485
1486impl std::ops::DerefMut for Error {
1487 fn deref_mut(&mut self) -> &mut ErrorData { &mut self.0 }
1488}
1489impl ErrorTrait for Error {}
1490
1491#[derive(Debug)]
1492pub enum ErrorCategory {
1493 Init,
1494 Io(io::Error),
1495 NotFound,
1496 Unexpected,
1497 Expected,
1498 Misdefined,
1499 Unknown,
1500 MissingFile,
1501 Malformed,
1502 Libxml,
1503 Convert,
1504 Recursion,
1505 EoF,
1506 Endgroup,
1507 FailedParse,
1508 MaxLimit(usize),
1509 Generic(Box<dyn ErrorTrait + Send + Sync>),
1510 Filename(String),
1511 ToDo,
1512 TokenLimit,
1513 PushbackLimit,
1514 IfLimit,
1515 MemoryBudget,
1516 ReadBudget,
1519 StreamingRestart,
1523 Named(String),
1525}
1526
1527#[derive(Debug)]
1528pub enum ErrorTarget {
1529 Package,
1530 Parameter,
1531 ParamSpec,
1532 Prototype,
1533 Converter,
1534 Mouth,
1535 Core,
1536 State,
1537 Stomach,
1538 Codegen,
1539 Macro,
1540 XMath,
1541 MathParser,
1542 Document,
1543 Definition,
1544 TexPool,
1545 Internal,
1546 TargetUnexpected,
1547 TooManyErrors,
1548 Timeout,
1549 Named(String),
1551}
1552
1553impl ErrorTarget {
1554 pub fn log_name(&self) -> String {
1556 match self {
1557 ErrorTarget::Named(name) => name.clone(),
1558 other => format!("{other:?}"),
1559 }
1560 }
1561}
1562
1563impl ErrorCategory {
1564 pub fn log_name(&self) -> String {
1566 match self {
1567 ErrorCategory::Named(name) => name.clone(),
1568 other => format!("{other:?}"),
1569 }
1570 }
1571}
1572
1573impl fmt::Display for ErrorCategory {
1574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1575 use ErrorCategory::*;
1576 match self {
1577 Init => write!(f, "Init"),
1578 Io(err) => err.fmt(f),
1579 NotFound => write!(f, "No matching cities with a population were found."),
1580 MissingFile => write!(f, "missing file"),
1581 Misdefined => write!(f, "misdefined"),
1582 Unknown => write!(f, "unknown"),
1583 Malformed => write!(f, "malformed"),
1584 Expected => write!(f, "expected"),
1585 Unexpected => write!(f, "unexpected"),
1586 Libxml => write!(f, "libxml error"),
1587 Recursion => write!(f, "<recursion>"),
1588 EoF => write!(f, "<EOF>"),
1589 ToDo => write!(f, "TODO"),
1590 Convert => write!(f, "conversion"),
1591 Endgroup => write!(f, "<endgroup>"),
1592 FailedParse => write!(f, "failed to parse"),
1593 MaxLimit(num) => write!(f, "{}", num),
1594 Generic(err) => err.fmt(f),
1595 Filename(name) => write!(f, "file:{name}"),
1596 TokenLimit => write!(f, "token_limit"),
1597 PushbackLimit => write!(f, "pushback_limit"),
1598 IfLimit => write!(f, "if_limit"),
1599 MemoryBudget => write!(f, "memory_budget"),
1600 ReadBudget => write!(f, "read_budget"),
1601 StreamingRestart => write!(f, "streaming-restart"),
1602 Named(name) => write!(f, "{name}"),
1603 }
1604 }
1605}
1606impl fmt::Display for Error {
1607 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1608 write!(
1609 f,
1610 "Error:{}:{:?} {}",
1611 self.category, self.target, self.message
1612 )
1613 }
1614}
1615
1616impl Error {
1617 pub fn log_fatal(&self) {
1618 let key = self.fatal_key();
1629 mute_errors_after_fatal(key.clone());
1630 if self.is_logged_fatal() {
1631 return;
1632 }
1633 emit_record(
1634 LogStatus::Fatal,
1635 &s!(
1636 "Fatal:{}:{}",
1637 self.target.log_name(),
1638 self.category.log_name()
1639 ),
1640 &self.message,
1641 );
1642 FATALS_LOGGED.with(|c| c.borrow_mut().insert(key));
1643 }
1644 fn fatal_key(&self) -> String {
1645 s!(
1646 "{}:{}:{}",
1647 self.target.log_name(),
1648 self.category.log_name(),
1649 self.message
1650 )
1651 }
1652 pub fn is_logged_fatal(&self) -> bool {
1654 let key = self.fatal_key();
1655 FATALS_LOGGED.with(|c| c.borrow().contains(&key))
1656 }
1657 pub fn mark_logged_fatal(&self) {
1660 let key = self.fatal_key();
1661 FATALS_LOGGED.with(|c| c.borrow_mut().insert(key));
1662 }
1663 pub fn todo() -> Self {
1664 Error::from(ErrorData {
1665 target: ErrorTarget::Internal,
1666 category: ErrorCategory::ToDo,
1667 message: String::from(
1668 "This section of the code is not yet implemented / ported over from Perl.",
1669 ),
1670 })
1671 }
1672}
1673
1674#[macro_export]
1675macro_rules! unported {
1676 () => {{ ::latexml_core::common::error::Error::todo() }};
1677}
1678
1679impl From<io::Error> for Error {
1680 fn from(err: io::Error) -> Error {
1681 Error::from(ErrorData {
1682 target: ErrorTarget::Mouth,
1683 category: ErrorCategory::Io(err),
1684 message: s!("IO error"),
1685 })
1686 }
1687}
1688
1689impl From<Box<dyn ErrorTrait>> for Error {
1690 fn from(err: Box<dyn ErrorTrait>) -> Error {
1691 let message = err.to_string();
1692 Error::from(ErrorData {
1693 target: ErrorTarget::Document,
1694 category: ErrorCategory::Generic(From::from(message.clone())),
1695 message,
1696 })
1697 }
1698}
1699impl From<Box<dyn ErrorTrait + Send + Sync>> for Error {
1700 fn from(err: Box<dyn ErrorTrait + Send + Sync>) -> Error {
1701 Error::from(ErrorData {
1702 target: ErrorTarget::Document,
1703 message: err.to_string(),
1704 category: ErrorCategory::Generic(err),
1705 })
1706 }
1707}
1708
1709impl From<String> for Error {
1710 fn from(err: String) -> Error {
1711 Error::from(ErrorData {
1712 target: ErrorTarget::Document,
1713 category: ErrorCategory::Generic(From::from(err.clone())),
1714 message: err,
1715 })
1716 }
1717}
1718
1719impl<'a> From<&'a str> for Error {
1720 fn from(err: &'a str) -> Error {
1721 Error::from(ErrorData {
1722 target: ErrorTarget::Document,
1723 category: ErrorCategory::Generic(From::from(err.to_owned())),
1724 message: err.to_owned(),
1725 })
1726 }
1727}
1728
1729impl From<()> for Error {
1730 fn from(_e: ()) -> Error {
1731 Error::from(ErrorData {
1732 target: ErrorTarget::Document,
1733 category: ErrorCategory::Libxml,
1734 message: s!("LibXML error"),
1735 })
1736 }
1737}
1738
1739impl From<ParseIntError> for Error {
1740 fn from(err: ParseIntError) -> Error {
1741 Error::from(ErrorData {
1742 target: ErrorTarget::Document,
1743 message: err.to_string(),
1744 category: ErrorCategory::Generic(Box::new(err)),
1745 })
1746 }
1747}
1748
1749impl From<ParseFloatError> for Error {
1750 fn from(err: ParseFloatError) -> Error {
1751 Error::from(ErrorData {
1752 target: ErrorTarget::Document,
1753 message: err.to_string(),
1754 category: ErrorCategory::Generic(Box::new(err)),
1755 })
1756 }
1757}
1758
1759thread_local! {
1765 static SILENCE_PROGRESS_NOTES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1770}
1771
1772#[must_use = "the silence ends when the guard is dropped"]
1775pub struct SilenceProgressNotesGuard {
1776 prev: bool,
1777}
1778
1779impl SilenceProgressNotesGuard {
1780 pub fn new() -> Self {
1782 let prev = SILENCE_PROGRESS_NOTES.get();
1783 SILENCE_PROGRESS_NOTES.set(true);
1784 SilenceProgressNotesGuard { prev }
1785 }
1786}
1787
1788impl Default for SilenceProgressNotesGuard {
1789 fn default() -> Self { Self::new() }
1790}
1791
1792impl Drop for SilenceProgressNotesGuard {
1793 fn drop(&mut self) { SILENCE_PROGRESS_NOTES.set(self.prev); }
1794}
1795
1796pub fn progress_step(_note: &str) {
1804 }
1807
1808pub fn note_progress(stuff: &str) {
1809 use log::info;
1810 if SILENCE_PROGRESS_NOTES.get() {
1811 return;
1812 }
1813 info!(target: "note", "{}", stuff);
1814}
1815
1816pub fn note_progress_detailed(stuff: &str) {
1818 use log::debug;
1819 if SILENCE_PROGRESS_NOTES.get() {
1820 return;
1821 }
1822 debug!(target: "note", "{}", stuff);
1823}
1824
1825pub fn note_begin(stage: &str) {
1834 if SILENCE_PROGRESS_NOTES.get() {
1835 return;
1836 }
1837 use log::info;
1839 info!(target: "note", "\n({}...", stage);
1840}
1841
1842pub fn note_end(_stage: &str) {
1848 if SILENCE_PROGRESS_NOTES.get() {
1849 return;
1850 }
1851 use log::info;
1857 info!(target: "note", " )");
1858}
1859
1860thread_static! {
1861 static DEFERRED_NOTES: RefCell<Vec<(String, Option<bool>)>> = RefCell::new(Vec::new());
1863}
1864
1865#[must_use = "the stage ends when the note is dropped"]
1871pub struct DeferredNote {
1872 depth: usize,
1873 happened: bool,
1874}
1875
1876impl DeferredNote {
1877 pub fn begin(stage: &str) -> Self {
1879 let silenced = SILENCE_PROGRESS_NOTES.get();
1880 let mut notes = DEFERRED_NOTES.borrow_mut();
1881 notes.push((stage.to_string(), (!silenced).then_some(false)));
1882 DeferredNote {
1883 depth: notes.len() - 1,
1884 happened: false,
1885 }
1886 }
1887
1888 pub fn end(mut self, happened: bool) { self.happened = happened; }
1890}
1891
1892impl Drop for DeferredNote {
1893 fn drop(&mut self) {
1894 let unprinted = matches!(
1895 DEFERRED_NOTES.borrow().get(self.depth),
1896 Some((_, Some(false)))
1897 );
1898 if self.happened && unprinted {
1899 print_deferred_notes();
1900 }
1901 let stage = {
1902 let mut notes = DEFERRED_NOTES.borrow_mut();
1903 let stage = notes.get(self.depth).cloned();
1904 notes.truncate(self.depth);
1905 stage
1906 };
1907 if let Some((stage, Some(true))) = stage {
1908 note_end(&stage);
1909 }
1910 }
1911}
1912
1913pub fn rename_deferred_note(stage: &str) {
1916 if let Some((text, Some(false))) = DEFERRED_NOTES.borrow_mut().last_mut() {
1917 *text = stage.to_string();
1918 }
1919}
1920
1921pub fn print_deferred_notes() {
1924 let pending: Vec<String> = DEFERRED_NOTES
1925 .borrow_mut()
1926 .iter_mut()
1927 .filter(|(_, printed)| *printed == Some(false))
1928 .map(|(stage, printed)| {
1929 *printed = Some(true);
1930 stage.clone()
1931 })
1932 .collect();
1933 for stage in pending {
1934 log::info!(target: "note", "\n({}...", stage);
1935 }
1936}
1937
1938#[cfg(test)]
1939mod tests {
1940 use super::*;
1941
1942 #[test]
1944 fn an_error_debugs_as_a_plain_struct() {
1945 let error = Error::from(ErrorData {
1946 target: ErrorTarget::Mouth,
1947 category: ErrorCategory::Expected,
1948 message: "m".into(),
1949 });
1950 assert_eq!(
1951 format!("{error:?}"),
1952 r#"Error { target: Mouth, category: Expected, message: "m" }"#
1953 );
1954 }
1955
1956 #[test]
1963 fn initialize_report_clears_state() {
1964 note_status(LogStatus::Warning, None);
1965 initialize_report();
1966 assert_eq!(get_status(LogStatus::Warning), 0);
1967 }
1968
1969 #[test]
1970 fn note_status_increments_counters() {
1971 initialize_report();
1972 note_status(LogStatus::Warning, None);
1973 note_status(LogStatus::Warning, None);
1974 note_status(LogStatus::Error, None);
1975 assert_eq!(get_status(LogStatus::Warning), 2);
1976 assert_eq!(get_status(LogStatus::Error), 1);
1977 assert_eq!(get_status(LogStatus::Fatal), 0);
1978 }
1979
1980 #[test]
1983 fn each_fatal_prints_once_however_two_alternate() {
1984 let fatal = |target, category| {
1985 Error::from(ErrorData {
1986 target,
1987 category,
1988 message: "m".into(),
1989 })
1990 };
1991 let fatal_lines = |log: String| log.lines().filter(|l| l.starts_with("Fatal:")).count();
1992 let _ = crate::util::logger::init(log::LevelFilter::Warn);
1993 initialize_report();
1994 crate::util::logger::bind_log();
1995 let runaway = runaway_reraise("expected:<relationaltoken>");
1996 for _ in 0..3 {
1997 runaway.log_fatal();
1998 fatal(ErrorTarget::Timeout, ErrorCategory::Recursion).log_fatal();
1999 fatal(ErrorTarget::Mouth, ErrorCategory::Expected).log_fatal();
2000 }
2001 assert_eq!(fatal_lines(crate::util::logger::flush_log()), 2);
2002 initialize_report();
2003 crate::util::logger::bind_log();
2004 fatal(ErrorTarget::Timeout, ErrorCategory::Recursion).log_fatal();
2005 assert_eq!(fatal_lines(crate::util::logger::flush_log()), 1);
2006 }
2007
2008 #[test]
2011 fn lowercase_fatal_macro_latches_resource_fatals() {
2012 initialize_report();
2013 fn fuse() -> Result<()> {
2014 fatal!(Timeout, MemoryBudget, "Memory budget exceeded (synthetic)");
2015 }
2016 let err = fuse().unwrap_err();
2017 assert!(matches!(err.category, ErrorCategory::MemoryBudget));
2018 assert!(
2019 resource_fatal_latched(),
2020 "the fuse's fatal must set the latch"
2021 );
2022 let latched = take_last_resource_fatal().expect("latch holds the fuse's fatal");
2023 assert!(matches!(latched.category, ErrorCategory::MemoryBudget));
2024 initialize_report();
2025 assert!(!resource_fatal_latched(), "cleared per conversion");
2026 fn missing() -> Result<()> {
2027 fatal!(Mouth, MissingFile, "Can't find file x");
2028 }
2029 let _ = missing();
2030 assert!(
2031 !resource_fatal_latched(),
2032 "a Mouth-target fatal is not a resource fatal"
2033 );
2034 initialize_report();
2035 }
2036
2037 #[test]
2040 fn an_ignoring_scope_tallies_what_it_drops() {
2041 initialize_report();
2042 let outer = IgnoreDiagnosticsScope::new();
2043 emit_record(LogStatus::Error, "undefined:\\x", "synthetic");
2044 emit_record(LogStatus::Warning, "w:w", "synthetic");
2045 {
2046 let inner = IgnoreDiagnosticsScope::new();
2047 emit_record(LogStatus::Error, "undefined:\\y", "synthetic");
2048 emit_record(LogStatus::Fatal, "Fatal:Internal:Unexpected", "synthetic");
2049 assert_eq!(inner.dropped(), IgnoredRecords { errors: 1, fatals: 1 });
2050 }
2051 assert!(
2052 diagnostics_ignored(),
2053 "the inner scope restores the outer one's ignoring"
2054 );
2055 assert_eq!(outer.dropped(), IgnoredRecords { errors: 2, fatals: 1 });
2056 drop(outer);
2057 assert_eq!(get_status(LogStatus::Error), 0, "dropped, not counted");
2058 assert_eq!(get_status(LogStatus::Fatal), 0, "dropped, not counted");
2059 let after = IgnoreDiagnosticsScope::new();
2060 drop(after);
2061 emit_record(LogStatus::Error, "undefined:\\z", "synthetic");
2062 assert_eq!(
2063 get_status(LogStatus::Error),
2064 1,
2065 "outside a scope a record counts"
2066 );
2067 initialize_report();
2068 }
2069
2070 #[test]
2075 fn errors_are_silent_once_a_resource_fatal_is_latched() {
2076 initialize_report();
2077 let before = get_status(LogStatus::Error);
2078 emit_record(
2079 LogStatus::Error,
2080 "expected:\\fi",
2081 "Missing \\fi (synthetic)",
2082 );
2083 assert_eq!(
2084 get_status(LogStatus::Error),
2085 before + 1,
2086 "counted before any Fatal"
2087 );
2088 fn raise() -> Result<()> {
2089 Fatal!(Timeout, MemoryBudget, "Memory budget exceeded (synthetic)");
2090 }
2091 let _ = raise();
2092 assert!(resource_fatal_latched());
2093 let after_fatal = get_status(LogStatus::Error);
2094 emit_record(
2095 LogStatus::Error,
2096 "expected:\\fi",
2097 "Missing \\fi (synthetic drain)",
2098 );
2099 assert_eq!(
2100 get_status(LogStatus::Error),
2101 after_fatal,
2102 "not counted after the latch"
2103 );
2104 initialize_report();
2105 }
2106
2107 #[test]
2110 fn any_fatal_mutes_later_errors_unless_its_probe_is_discarded() {
2111 fn raise(message: &str) -> Result<()> {
2112 Fatal!(Stomach, Recursion, message);
2113 }
2114 let error_counted = || {
2115 let before = get_status(LogStatus::Error);
2116 emit_error("expected:\\fi", "x", "Missing \\fi (synthetic)");
2117 get_status(LogStatus::Error) > before
2118 };
2119 initialize_report();
2120 let hold = crate::util::logger::DiagnosticsHold::begin();
2121 let _ = raise("in a discarded probe");
2122 assert!(!error_counted(), "muted inside the probe");
2123 hold.discard();
2124 assert!(
2125 error_counted(),
2126 "a discarded probe's Fatal does not mute the document's Errors"
2127 );
2128 {
2129 let _scope = IgnoreDiagnosticsScope::new();
2130 let _ = raise("in an ignoring scope");
2131 }
2132 assert!(error_counted(), "an ignored Fatal does not mute");
2133 let caught = raise("caught by a script").unwrap_err();
2135 unmute_errors_after_caught_fatal(&caught);
2136 assert!(error_counted(), "a caught Fatal does not mute");
2137 caught.log_fatal();
2138 assert!(!error_counted(), "a Fatal let through mutes at its sink");
2139 initialize_report();
2140 let _ = raise("the document's");
2141 assert!(
2142 !resource_fatal_latched() && !error_counted(),
2143 "any Fatal mutes"
2144 );
2145 let hold = crate::util::logger::DiagnosticsHold::begin();
2146 assert!(
2147 !error_counted() && hold.errors_raised() == 1,
2148 "a probe still sees its own muted Error"
2149 );
2150 hold.discard();
2151 initialize_report();
2152 assert!(error_counted(), "cleared per conversion");
2153 initialize_report();
2154 }
2155
2156 #[test]
2160 fn a_discarded_inner_hold_takes_back_its_muted_errors() {
2161 use crate::util::logger::DiagnosticsHold;
2162 fn raise() -> Result<()> {
2163 Fatal!(Stomach, Recursion, "the document's");
2164 }
2165 let muted_error = || emit_error("expected:\\fi", "x", "Missing \\fi (synthetic)");
2166 initialize_report();
2167 let _ = raise();
2168 let outer = DiagnosticsHold::begin();
2169 let inner = DiagnosticsHold::begin();
2170 muted_error();
2171 assert!(!inner.is_empty() && inner.is_empty_but_debug());
2172 inner.discard();
2173 assert_eq!(
2174 outer.errors_raised(),
2175 0,
2176 "the inner hold's muted Error is taken back"
2177 );
2178 muted_error();
2179 assert_eq!(outer.errors_raised(), 1);
2180 outer.discard();
2181 muted_error();
2182 assert_eq!(muted_errors(), 1);
2183 initialize_report();
2184 assert_eq!(muted_errors(), 0, "reset per conversion");
2185 }
2186
2187 fn fatal_lines(log: &str) -> usize { log.matches("Fatal:").count() }
2188
2189 #[test]
2195 fn fatal_macro_logs_its_line_at_the_raise_exactly_once() {
2196 let _ = crate::util::logger::init(log::LevelFilter::Warn);
2197 initialize_report();
2198 crate::util::logger::bind_log();
2199 fn raise() -> Result<()> {
2200 Fatal!(Internal, EoF, "synthetic fatal, swallowed by the caller");
2201 }
2202 let err = raise().unwrap_err();
2203 assert_eq!(
2204 fatal_lines(&crate::util::logger::flush_log()),
2205 1,
2206 "logged at the raise"
2207 );
2208 assert_eq!(get_status(LogStatus::Fatal), 1, "and counted");
2209 crate::util::logger::bind_log();
2210 err.log_fatal();
2211 assert_eq!(
2212 fatal_lines(&crate::util::logger::flush_log()),
2213 0,
2214 "the sink does not print it twice"
2215 );
2216 crate::util::logger::bind_log();
2218 fn raise_lower() -> Result<()> {
2219 fatal!(Internal, EoF, "synthetic lowercase fatal");
2220 }
2221 let _ = raise_lower();
2222 assert_eq!(fatal_lines(&crate::util::logger::flush_log()), 1);
2223 initialize_report();
2224 }
2225
2226 #[test]
2228 fn ignored_diagnostics_scope_drops_line_and_count_together() {
2229 let _ = crate::util::logger::init(log::LevelFilter::Warn);
2230 initialize_report();
2231 crate::util::logger::bind_log();
2232 let prev = set_ignore_diagnostics(true);
2233 emit_record(LogStatus::Error, "undefined:\\probe", "probe (ignored)");
2234 emit_record(LogStatus::Warning, "expected:probe", "probe (ignored)");
2235 set_ignore_diagnostics(prev);
2236 emit_record(LogStatus::Error, "undefined:\\real", "real");
2237 let log = crate::util::logger::flush_log();
2238 assert_eq!(get_status(LogStatus::Error), 1);
2239 assert_eq!(get_status(LogStatus::Warning), 0);
2240 assert!(
2241 !log.contains("probe"),
2242 "ignored records leave no line:\n{log}"
2243 );
2244 assert!(log.contains("undefined:\\real"), "{log}");
2245 initialize_report();
2246 }
2247
2248 #[test]
2252 fn diagnostics_hold_commits_or_discards_lines_and_counts_together() {
2253 use crate::util::logger::DiagnosticsHold;
2254 let _ = crate::util::logger::init(log::LevelFilter::Warn);
2255 initialize_report();
2256 crate::util::logger::bind_log();
2257 let hold = DiagnosticsHold::begin();
2258 emit_record(LogStatus::Error, "recursion:\\q_no_value", "speculative");
2259 emit_record(LogStatus::Warning, "expected:held", "speculative");
2260 latch_too_many_errors();
2261 assert_eq!(hold.errors_raised(), 1);
2262 assert_eq!(hold.discard(), 2);
2263 assert_eq!(get_status(LogStatus::Error), 0);
2264 assert_eq!(get_status(LogStatus::Warning), 0);
2265 assert!(!too_many_errors_latched());
2268 assert_eq!(CONSECUTIVE_ERROR_COUNT.get(), 0);
2269 let outer = DiagnosticsHold::begin();
2270 emit_record(LogStatus::Warning, "expected:first", "kept");
2271 let inner = DiagnosticsHold::begin();
2272 emit_record(LogStatus::Error, "undefined:\\second", "kept");
2273 assert_eq!(inner.errors_raised(), 1);
2274 inner.commit();
2275 assert!(
2276 !crate::util::logger::flush_log().contains("kept"),
2277 "an inner commit writes into the enclosing hold"
2278 );
2279 crate::util::logger::bind_log();
2280 outer.commit();
2281 let log = crate::util::logger::flush_log();
2282 assert!(!log.contains("speculative"), "{log}");
2283 let first = log.find("expected:first").expect("first record written");
2284 let second = log
2285 .find("undefined:\\second")
2286 .expect("second record written");
2287 assert!(first < second, "held records keep their order:\n{log}");
2288 assert_eq!(get_status(LogStatus::Error), 1);
2289 assert_eq!(get_status(LogStatus::Warning), 1);
2290 initialize_report();
2291 }
2292
2293 #[test]
2296 fn a_blank_what_field_is_never_logged() {
2297 assert_eq!(
2298 message_object(" ", "\\GenericError"),
2299 "\\GenericError"
2300 );
2301 assert_eq!(message_object(" (mycls) ", "\\ClassError"), "(mycls) ");
2302 assert_eq!(record_target("latex: "), "latex:unknown");
2303 assert_eq!(record_target("latex: "), "latex:unknown");
2304 assert_eq!(record_target("latex: "), "latex:unknown");
2305 assert!(matches!(
2306 record_target("latex:(mycls) "),
2307 Cow::Borrowed("latex:(mycls) ")
2308 ));
2309 assert_eq!(record_target("Fatal:timeout: "), "Fatal:timeout:unknown");
2310 assert!(matches!(
2311 record_target("undefined:\\num"),
2312 Cow::Borrowed("undefined:\\num")
2313 ));
2314 let _ = crate::util::logger::init(log::LevelFilter::Warn);
2315 initialize_report();
2316 crate::util::logger::bind_log();
2317 emit_error(
2318 "latex",
2319 " ",
2320 "LaTeX Error: Unicode character ^^B (U+0002)",
2321 );
2322 let log = crate::util::logger::flush_log();
2323 initialize_report();
2324 let line = log
2325 .lines()
2326 .find(|l| l.starts_with("Error:"))
2327 .unwrap_or_default();
2328 assert!(line.starts_with("Error:latex:unknown LaTeX Error"), "{log}");
2329 }
2330
2331 #[test]
2333 fn emit_error_fires_the_too_many_errors_fatal_once() {
2334 let _ = crate::util::logger::init(log::LevelFilter::Warn);
2335 initialize_report();
2336 crate::util::logger::bind_log();
2337 for _ in 0..(MAX_CONSECUTIVE_ERRORS + 60) {
2338 emit_error("unexpected", "}", "synthetic repeat");
2339 }
2340 let log = crate::util::logger::flush_log();
2341 assert_eq!(
2342 log.matches("Fatal:TooManyErrors").count(),
2343 1,
2344 "{}",
2345 log.len()
2346 );
2347 assert!(log.contains("(> 100)"), "{}", log.len());
2349 assert!(too_many_errors_latched());
2350 initialize_report();
2351 }
2352
2353 #[test]
2356 fn an_error_past_the_spent_cap_raises_nothing() {
2357 let _ = crate::util::logger::init(log::LevelFilter::Warn);
2358 initialize_report();
2359 crate::util::logger::bind_log();
2360 fn raise(i: usize) -> Result<()> {
2361 Error!("unexpected", format!("\\e{i}"), "synthetic distinct error");
2362 Ok(())
2363 }
2364 let outcomes: Vec<bool> = (0..102).map(|i| raise(i).is_err()).collect();
2365 assert_eq!(
2366 outcomes.iter().position(|&err| err),
2367 Some(100),
2368 "the 101st raises the cap"
2369 );
2370 assert!(outcomes[101], "the cap re-raises until it is spent");
2371 spend_too_many_errors();
2372 assert!(raise(102).is_ok() && raise(103).is_ok());
2373 let log = crate::util::logger::flush_log();
2374 assert_eq!(log.matches("Fatal:TooManyErrors").count(), 1, "{log}");
2375 assert_eq!(log.matches("Error:unexpected").count(), 101, "{log}");
2376 initialize_report();
2377 assert!(!too_many_errors_spent());
2378 }
2379
2380 #[test]
2381 fn fatal_macro_latches_resource_fatals() {
2382 initialize_report();
2386 fn raise() -> Result<()> {
2387 Fatal!(
2388 Timeout,
2389 TokenLimit,
2390 "Token limit of 5 exceeded, infinite loop?"
2391 );
2392 }
2393 let err = raise().unwrap_err();
2394 assert!(matches!(err.target, ErrorTarget::Timeout));
2395 let latched = take_last_resource_fatal().expect("latch must hold the fatal");
2396 assert!(matches!(latched.target, ErrorTarget::Timeout));
2397 assert!(matches!(latched.category, ErrorCategory::TokenLimit));
2398 assert_eq!(latched.message, "Token limit of 5 exceeded, infinite loop?");
2399 assert!(take_last_resource_fatal().is_none());
2401 fn raise_other() -> Result<()> {
2403 Fatal!(Internal, EoF, "fell off the end");
2404 }
2405 let _ = raise_other().unwrap_err();
2406 assert!(take_last_resource_fatal().is_none());
2407 let _ = raise().unwrap_err();
2409 initialize_report();
2410 assert!(take_last_resource_fatal().is_none());
2411 }
2412
2413 #[test]
2414 fn fatal_status_is_sticky_and_returns_1() {
2415 initialize_report();
2416 note_status(LogStatus::Fatal, None);
2417 note_status(LogStatus::Fatal, None);
2418 assert_eq!(get_status(LogStatus::Fatal), 1);
2420 }
2421
2422 #[test]
2423 fn get_status_code_priority_order() {
2424 initialize_report();
2425 assert_eq!(get_status_code(), 0, "clean state → 0");
2426 note_status(LogStatus::Warning, None);
2427 assert_eq!(get_status_code(), 1, "warning → 1");
2428 note_status(LogStatus::Error, None);
2429 assert_eq!(get_status_code(), 2, "error wins over warning → 2");
2430 note_status(LogStatus::Fatal, None);
2431 assert_eq!(get_status_code(), 3, "fatal wins over error → 3");
2432 }
2433
2434 #[test]
2435 fn status_message_clean_is_no_obvious_problems() {
2436 initialize_report();
2437 assert_eq!(get_status_message(), "No obvious problems");
2438 }
2439
2440 #[test]
2441 fn status_message_plural_warnings() {
2442 initialize_report();
2443 note_status(LogStatus::Warning, None);
2444 let m = get_status_message();
2445 assert_eq!(m, "1 warning", "singular form");
2446
2447 note_status(LogStatus::Warning, None);
2448 let m = get_status_message();
2449 assert_eq!(m, "2 warnings", "plural form");
2450 }
2451
2452 #[test]
2453 fn status_message_multiple_categories_joined() {
2454 initialize_report();
2455 note_status(LogStatus::Warning, None);
2456 note_status(LogStatus::Warning, None);
2457 note_status(LogStatus::Error, None);
2458 let m = get_status_message();
2459 assert!(
2460 m.contains("2 warnings") && m.contains("1 error") && m.contains("; "),
2461 "got {m:?}"
2462 );
2463 }
2464
2465 #[test]
2466 fn suppress_log_output_returns_prior_value() {
2467 let prior = set_suppress_log_output(true);
2468 assert!(is_log_output_suppressed());
2469 let prior2 = set_suppress_log_output(false);
2470 assert!(prior2, "round-trip prior value");
2471 assert!(!is_log_output_suppressed());
2472 set_suppress_log_output(prior);
2474 }
2475
2476 #[test]
2479 fn suppress_log_output_guard_restores_on_drop_and_unwind() {
2480 set_suppress_log_output(false);
2481 {
2482 let _guard = SuppressLogOutputGuard::new(true);
2483 assert!(is_log_output_suppressed());
2484 }
2485 assert!(!is_log_output_suppressed());
2486 let unwound = std::panic::catch_unwind(|| {
2487 let _guard = SuppressLogOutputGuard::new(true);
2488 panic!("speculative run panicked");
2489 });
2490 assert!(unwound.is_err());
2491 assert!(!is_log_output_suppressed());
2492 set_suppress_log_output(true);
2493 reset_suppress_log_output();
2494 assert!(!is_log_output_suppressed());
2495 }
2496}