rustc_interface/
callbacks.rs
1use 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 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 debug_assert_eq!(_span.data_untracked().parent, None);
33 }
34 }
35 })
36}
37
38fn 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 let icx = tls::ImplicitCtxt { task_deps: TaskDepsRef::Ignore, ..icx.clone() };
50 tls::enter_context(&icx, move || (*f)(diagnostic))
51 } else {
52 (*f)(diagnostic)
54 }
55 })
56}
57
58fn 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
71pub 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
83pub 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
106pub 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}