1use std::any::Any;
6use std::cell::{Cell, RefCell};
7use std::panic::{self as std_panic, AssertUnwindSafe};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::Once;
10
11use crate::host::{Host, LogLevel};
12
13thread_local! {
14 static CATCHING: Cell<u32> = const { Cell::new(0) };
15 static MESSAGE: RefCell<Option<String>> = const { RefCell::new(None) };
16}
17
18static HOOK: Once = Once::new();
19
20pub(crate) fn install_hook() {
23 HOOK.call_once(|| {
24 let previous = std_panic::take_hook();
26 std_panic::set_hook(Box::new(move |info| {
27 let text = match info.location() {
28 Some(at) => format!(
29 "{} at {}:{}",
30 payload_text(info.payload()),
31 at.file(),
32 at.line()
33 ),
34 None => payload_text(info.payload()),
35 };
36 if CATCHING.try_with(Cell::get).unwrap_or(0) > 0 {
38 let _ = MESSAGE.try_with(|message| *message.borrow_mut() = Some(text));
39 } else {
40 if let Some(host) = Host::current() {
41 host.log(LogLevel::Error, format_args!("panic: {text}"));
42 }
43 previous(info);
44 }
45 }));
46 });
47}
48
49fn payload_text(payload: &(dyn Any + Send)) -> String {
50 if let Some(text) = payload.downcast_ref::<&str>() {
51 (*text).to_owned()
52 } else if let Some(text) = payload.downcast_ref::<String>() {
53 text.clone()
54 } else {
55 "a panic without a message".to_owned()
56 }
57}
58
59fn text_of(kept: Option<String>, payload: &(dyn Any + Send)) -> String {
64 let own = payload_text(payload);
65 match kept {
67 Some(kept)
68 if kept
69 .strip_prefix(own.as_str())
70 .is_some_and(|rest| rest.is_empty() || rest.starts_with(" at ")) =>
71 {
72 kept
73 }
74 _ => own,
75 }
76}
77
78pub(crate) fn catch<R>(body: impl FnOnce() -> R) -> Result<R, String> {
80 catch_raw(body).map_err(|payload| {
81 let text = text_of(
82 MESSAGE.with(|message| message.borrow_mut().take()),
83 &*payload,
84 );
85 let _ = std_panic::catch_unwind(AssertUnwindSafe(move || drop(payload)));
87 text
88 })
89}
90
91pub(crate) fn catch_raw<R>(body: impl FnOnce() -> R) -> std::thread::Result<R> {
93 CATCHING.with(|n| n.set(n.get() + 1));
94 let result = std_panic::catch_unwind(AssertUnwindSafe(body));
95 CATCHING.with(|n| n.set(n.get() - 1));
96 result
97}
98
99pub(crate) fn resume(payload: Box<dyn Any + Send>) -> ! {
104 if CATCHING.try_with(Cell::get).unwrap_or(0) == 0 {
105 let kept = MESSAGE
106 .try_with(|message| message.borrow_mut().take())
107 .ok()
108 .flatten();
109 let text = text_of(kept, &*payload);
110 let _ = catch(|| {
111 if let Some(host) = Host::current() {
112 host.log(LogLevel::Error, format_args!("panic: {text}"));
113 }
114 });
115 }
116 std_panic::resume_unwind(payload)
117}
118
119pub(crate) fn run_callback<R>(
122 what: &str,
123 logged: &AtomicBool,
124 fallback: R,
125 body: impl FnOnce() -> R,
126) -> R {
127 match catch(body) {
128 Ok(value) => value,
129 Err(text) => {
130 if !logged.swap(true, Ordering::AcqRel) {
131 let _ = catch(|| {
132 if let Some(host) = Host::current() {
133 host.log(
134 LogLevel::Error,
135 format_args!(
136 "{what}: the callback panicked ({text}); the game carries on, and later panics of this callback are not logged"
137 ),
138 );
139 }
140 });
141 }
142 fallback
143 }
144 }
145}
146
147pub fn catch_panic<R>(what: &str, fallback: R, body: impl FnOnce() -> R) -> R {
152 match catch(body) {
153 Ok(value) => value,
154 Err(text) => {
155 let _ = catch(|| {
156 if let Some(host) = Host::current() {
157 host.log(
158 LogLevel::Error,
159 format_args!("{what} panicked ({text}); carrying on"),
160 );
161 }
162 });
163 fallback
164 }
165 }
166}