// SPDX-License-Identifier: Apache-2.0 OR MIT12use core::sync::atomic::{AtomicUsize, Ordering};3use std::sync::Once;45static WORKS: AtomicUsize = AtomicUsize::new(0);6static INIT: Once = Once::new();78pub(crate) fn inside_proc_macro() -> bool {9match WORKS.load(Ordering::Relaxed) {101 => return false,112 => return true,12_ => {}13}1415INIT.call_once(initialize);16inside_proc_macro()17}1819pub(crate) fn force_fallback() {20WORKS.store(1, Ordering::Relaxed);21}2223pub(crate) fn unforce_fallback() {24initialize();25}2627#[cfg(not(no_is_available))]28fn initialize() {29let available = proc_macro::is_available();30WORKS.store(available as usize + 1, Ordering::Relaxed);31}3233// Swap in a null panic hook to avoid printing "thread panicked" to stderr,34// then use catch_unwind to determine whether the compiler's proc_macro is35// working. When proc-macro2 is used from outside of a procedural macro all36// of the proc_macro crate's APIs currently panic.37//38// The Once is to prevent the possibility of this ordering:39//40// thread 1 calls take_hook, gets the user's original hook41// thread 1 calls set_hook with the null hook42// thread 2 calls take_hook, thinks null hook is the original hook43// thread 2 calls set_hook with the null hook44// thread 1 calls set_hook with the actual original hook45// thread 2 calls set_hook with what it thinks is the original hook46//47// in which the user's hook has been lost.48//49// There is still a race condition where a panic in a different thread can50// happen during the interval that the user's original panic hook is51// unregistered such that their hook is incorrectly not called. This is52// sufficiently unlikely and less bad than printing panic messages to stderr53// on correct use of this crate. Maybe there is a libstd feature request54// here. For now, if a user needs to guarantee that this failure mode does55// not occur, they need to call e.g. `proc_macro2::Span::call_site()` from56// the main thread before launching any other threads.57#[cfg(no_is_available)]58fn initialize() {59use std::panic::{self, PanicInfo};6061type PanicHook = dyn Fn(&PanicInfo) + Sync + Send + 'static;6263let null_hook: Box<PanicHook> = Box::new(|_panic_info| { /* ignore */ });64let sanity_check = &*null_hook as *const PanicHook;65let original_hook = panic::take_hook();66panic::set_hook(null_hook);6768let works = panic::catch_unwind(proc_macro::Span::call_site).is_ok();69WORKS.store(works as usize + 1, Ordering::Relaxed);7071let hopefully_null_hook = panic::take_hook();72panic::set_hook(original_hook);73if sanity_check != &*hopefully_null_hook {74panic!("observed race condition in proc_macro2::inside_proc_macro");75}76}777879