Skip to main content

proc_macro2/
detection.rs

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