Skip to main content

rustc_interface/
callbacks.rs

1//! Throughout the compiler tree, there are several places which want to have
2//! access to state or queries while being inside crates that are dependencies
3//! of `rustc_middle`. To facilitate this, we have the
4//! `rustc_data_structures::AtomicRef` type, which allows us to setup a global
5//! static which can then be set in this file at program startup.
6//!
7//! See `SPAN_TRACK` for an example of how to set things up.
8//!
9//! The functions in this file should fall back to the default set in their
10//! origin crate when the `TyCtxt` is not present in TLS.
11
12use std::fmt;
13
14use rustc_errors::DiagInner;
15use rustc_middle::dep_graph::{DepNodeIndex, QuerySideEffect, TaskDepsRef};
16use rustc_middle::ty::tls;
17use rustc_span::Symbol;
18
19fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) {
20    tls::with_context_opt(|icx| {
21        if let Some(icx) = icx {
22            // `track_span_parent` gets called a lot from HIR lowering code.
23            // Skip doing anything if we aren't tracking dependencies.
24            let tracks_deps = match icx.task_deps {
25                TaskDepsRef::Allow(..) => true,
26                TaskDepsRef::EvalAlways | TaskDepsRef::Ignore | TaskDepsRef::Forbid => false,
27            };
28            if tracks_deps {
29                let _span = icx.tcx.source_span(def_id);
30                // Sanity check: relative span's parent must be an absolute span.
31                if true {
    match (&_span.data_untracked().parent, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(_span.data_untracked().parent, None);
32            }
33        }
34    })
35}
36
37/// This is a callback from `rustc_errors` as it cannot access the implicit state
38/// in `rustc_middle` otherwise. It is used when diagnostic messages are
39/// emitted and stores them in the current query, if there is one.
40fn track_diagnostic<R>(diagnostic: DiagInner, f: &mut dyn FnMut(DiagInner) -> R) -> R {
41    tls::with_context_opt(|icx| {
42        if let Some(icx) = icx {
43            icx.tcx.dep_graph.record_diagnostic(icx.tcx, &diagnostic);
44
45            // Diagnostics are tracked, we can ignore the dependency.
46            let icx = tls::ImplicitCtxt { task_deps: TaskDepsRef::Ignore, ..*icx };
47            tls::enter_context(&icx, move || (*f)(diagnostic))
48        } else {
49            // In any other case, invoke diagnostics anyway.
50            (*f)(diagnostic)
51        }
52    })
53}
54
55fn track_feature(feature: Symbol) {
56    tls::with_context_opt(|icx| {
57        let Some(icx) = icx else {
58            return;
59        };
60        let tcx = icx.tcx;
61
62        if let Some(dep_node_index) = tcx.sess.used_features.lock().get(&feature).copied() {
63            tcx.dep_graph.read_index(DepNodeIndex::from_u32(dep_node_index));
64        } else {
65            let dep_node_index = tcx
66                .dep_graph
67                .encode_side_effect(tcx, QuerySideEffect::CheckFeature { symbol: feature });
68            tcx.sess.used_features.lock().insert(feature, dep_node_index.as_u32());
69            tcx.dep_graph.read_index(dep_node_index);
70        }
71    })
72}
73
74/// This is a callback from `rustc_hir` as it cannot access the implicit state
75/// in `rustc_middle` otherwise.
76fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77    f.write_fmt(format_args!("DefId({0}:{1}", def_id.krate, def_id.index.index()))write!(f, "DefId({}:{}", def_id.krate, def_id.index.index())?;
78    tls::with_opt(|opt_tcx| {
79        if let Some(tcx) = opt_tcx {
80            f.write_fmt(format_args!(" ~ {0}", tcx.def_path_debug_str(def_id)))write!(f, " ~ {}", tcx.def_path_debug_str(def_id))?;
81        }
82        Ok(())
83    })?;
84    f.write_fmt(format_args!(")"))write!(f, ")")
85}
86
87/// Sets up the callbacks in prior crates which we want to refer to the
88/// TyCtxt in.
89pub fn setup_callbacks() {
90    rustc_span::SPAN_TRACK.swap(&(track_span_parent as fn(_)));
91    rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
92    rustc_errors::TRACK_DIAGNOSTIC.swap(&(track_diagnostic as _));
93    rustc_feature::TRACK_FEATURE.swap(&(track_feature as _));
94}