use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use rustc_middle::ty::TyCtxt;
use rustc_span::fatal_error::FatalErrorMarker;
type AnalysisFn = for<'tcx> fn(TyCtxt<'tcx>, ());
type IndexJob = Box<dyn for<'tcx> FnOnce(TyCtxt<'tcx>) + Send>;
static COMPILER_ANALYSIS: OnceLock<AnalysisFn> = OnceLock::new();
static PENDING: Mutex<Option<IndexJob>> = Mutex::new(None);
static ON_ERRORS: AtomicBool = AtomicBool::new(false);
pub(crate) fn install(config: &mut rustc_interface::Config, job: IndexJob, on_errors: bool) {
*PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some(job);
ON_ERRORS.store(on_errors, Ordering::SeqCst);
config.override_queries = Some(|_session, providers| {
let _ = COMPILER_ANALYSIS.set(providers.queries.analysis);
providers.queries.analysis = analysis_then_index_on_errors;
});
}
pub(crate) fn run_pending(tcx: TyCtxt<'_>) {
let job = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
if let Some(job) = job {
job(tcx);
}
}
fn analysis_then_index_on_errors(tcx: TyCtxt<'_>, (): ()) {
let Some(analysis) = COMPILER_ANALYSIS.get().copied() else { return };
let Err(stop) = catch_unwind(AssertUnwindSafe(|| analysis(tcx, ()))) else { return };
if ON_ERRORS.load(Ordering::SeqCst) && stop.is::<FatalErrorMarker>() && tcx.dcx().has_errors_excluding_lint_errors().is_some() {
let _ = catch_unwind(AssertUnwindSafe(|| run_pending(tcx)));
}
resume_unwind(stop)
}