1 use std::panic::{self, PanicInfo};
2 use std::sync::atomic::*;
3 use std::sync::Once;
4
5 static WORKS: AtomicUsize = AtomicUsize::new(0);
6 static INIT: Once = Once::new();
7
inside_proc_macro() -> bool8 pub(crate) fn inside_proc_macro() -> bool {
9 match WORKS.load(Ordering::SeqCst) {
10 1 => return false,
11 2 => return true,
12 _ => {}
13 }
14
15 INIT.call_once(initialize);
16 inside_proc_macro()
17 }
18
force_fallback()19 pub(crate) fn force_fallback() {
20 WORKS.store(1, Ordering::SeqCst);
21 }
22
unforce_fallback()23 pub(crate) fn unforce_fallback() {
24 initialize();
25 }
26
27 // Swap in a null panic hook to avoid printing "thread panicked" to stderr,
28 // then use catch_unwind to determine whether the compiler's proc_macro is
29 // working. When proc-macro2 is used from outside of a procedural macro all
30 // of the proc_macro crate's APIs currently panic.
31 //
32 // The Once is to prevent the possibility of this ordering:
33 //
34 // thread 1 calls take_hook, gets the user's original hook
35 // thread 1 calls set_hook with the null hook
36 // thread 2 calls take_hook, thinks null hook is the original hook
37 // thread 2 calls set_hook with the null hook
38 // thread 1 calls set_hook with the actual original hook
39 // thread 2 calls set_hook with what it thinks is the original hook
40 //
41 // in which the user's hook has been lost.
42 //
43 // There is still a race condition where a panic in a different thread can
44 // happen during the interval that the user's original panic hook is
45 // unregistered such that their hook is incorrectly not called. This is
46 // sufficiently unlikely and less bad than printing panic messages to stderr
47 // on correct use of this crate. Maybe there is a libstd feature request
48 // here. For now, if a user needs to guarantee that this failure mode does
49 // not occur, they need to call e.g. `proc_macro2::Span::call_site()` from
50 // the main thread before launching any other threads.
initialize()51 fn initialize() {
52 type PanicHook = dyn Fn(&PanicInfo) + Sync + Send + 'static;
53
54 let null_hook: Box<PanicHook> = Box::new(|_panic_info| { /* ignore */ });
55 let sanity_check = &*null_hook as *const PanicHook;
56 let original_hook = panic::take_hook();
57 panic::set_hook(null_hook);
58
59 let works = panic::catch_unwind(proc_macro::Span::call_site).is_ok();
60 WORKS.store(works as usize + 1, Ordering::SeqCst);
61
62 let hopefully_null_hook = panic::take_hook();
63 panic::set_hook(original_hook);
64 if sanity_check != &*hopefully_null_hook {
65 panic!("observed race condition in proc_macro2::inside_proc_macro");
66 }
67 }
68