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, TRACK_DIAGNOSTIC};
15use rustc_middle::dep_graph::{DepNodeExt, TaskDepsRef};
16use rustc_middle::ty::tls;
17use rustc_query_system::dep_graph::dep_node::default_dep_kind_debug;
18use rustc_query_system::dep_graph::{DepContext, DepKind, DepNode};
19
20fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) {
21    tls::with_context_opt(|icx| {
22        if let Some(icx) = icx {
23            // `track_span_parent` gets called a lot from HIR lowering code.
24            // Skip doing anything if we aren't tracking dependencies.
25            let tracks_deps = match icx.task_deps {
26                TaskDepsRef::Allow(..) => true,
27                TaskDepsRef::EvalAlways | TaskDepsRef::Ignore | TaskDepsRef::Forbid => false,
28            };
29            if tracks_deps {
30                let _span = icx.tcx.source_span(def_id);
31                // Sanity check: relative span's parent must be an absolute span.
32                debug_assert_eq!(_span.data_untracked().parent, None);
33            }
34        }
35    })
36}
37
38/// This is a callback from `rustc_errors` as it cannot access the implicit state
39/// in `rustc_middle` otherwise. It is used when diagnostic messages are
40/// emitted and stores them in the current query, if there is one.
41fn track_diagnostic<R>(diagnostic: DiagInner, f: &mut dyn FnMut(DiagInner) -> R) -> R {
42    tls::with_context_opt(|icx| {
43        if let Some(icx) = icx {
44            if let Some(diagnostics) = icx.diagnostics {
45                diagnostics.lock().extend(Some(diagnostic.clone()));
46            }
47
48            // Diagnostics are tracked, we can ignore the dependency.
49            let icx = tls::ImplicitCtxt { task_deps: TaskDepsRef::Ignore, ..icx.clone() };
50            tls::enter_context(&icx, move || (*f)(diagnostic))
51        } else {
52            // In any other case, invoke diagnostics anyway.
53            (*f)(diagnostic)
54        }
55    })
56}
57
58/// This is a callback from `rustc_hir` as it cannot access the implicit state
59/// in `rustc_middle` otherwise.
60fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61    write!(f, "DefId({}:{}", def_id.krate, def_id.index.index())?;
62    tls::with_opt(|opt_tcx| {
63        if let Some(tcx) = opt_tcx {
64            write!(f, " ~ {}", tcx.def_path_debug_str(def_id))?;
65        }
66        Ok(())
67    })?;
68    write!(f, ")")
69}
70
71/// This is a callback from `rustc_query_system` as it cannot access the implicit state
72/// in `rustc_middle` otherwise.
73pub fn dep_kind_debug(kind: DepKind, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74    tls::with_opt(|opt_tcx| {
75        if let Some(tcx) = opt_tcx {
76            write!(f, "{}", tcx.dep_kind_info(kind).name)
77        } else {
78            default_dep_kind_debug(kind, f)
79        }
80    })
81}
82
83/// This is a callback from `rustc_query_system` as it cannot access the implicit state
84/// in `rustc_middle` otherwise.
85pub fn dep_node_debug(node: DepNode, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86    write!(f, "{:?}(", node.kind)?;
87
88    tls::with_opt(|opt_tcx| {
89        if let Some(tcx) = opt_tcx {
90            if let Some(def_id) = node.extract_def_id(tcx) {
91                write!(f, "{}", tcx.def_path_debug_str(def_id))?;
92            } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(node) {
93                write!(f, "{s}")?;
94            } else {
95                write!(f, "{}", node.hash)?;
96            }
97        } else {
98            write!(f, "{}", node.hash)?;
99        }
100        Ok(())
101    })?;
102
103    write!(f, ")")
104}
105
106/// Sets up the callbacks in prior crates which we want to refer to the
107/// TyCtxt in.
108pub fn setup_callbacks() {
109    rustc_span::SPAN_TRACK.swap(&(track_span_parent as fn(_)));
110    rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
111    rustc_query_system::dep_graph::dep_node::DEP_KIND_DEBUG
112        .swap(&(dep_kind_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
113    rustc_query_system::dep_graph::dep_node::DEP_NODE_DEBUG
114        .swap(&(dep_node_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
115    TRACK_DIAGNOSTIC.swap(&(track_diagnostic as _));
116}