]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/callbacks.rs
rustc_typeck to rustc_hir_analysis
[rust.git] / compiler / rustc_interface / src / 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
12 use rustc_errors::{Diagnostic, TRACK_DIAGNOSTICS};
13 use rustc_middle::ty::tls;
14 use std::fmt;
15
16 fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) {
17     tls::with_opt(|tcx| {
18         if let Some(tcx) = tcx {
19             let _span = tcx.source_span(def_id);
20             // Sanity check: relative span's parent must be an absolute span.
21             debug_assert_eq!(_span.data_untracked().parent, None);
22         }
23     })
24 }
25
26 /// This is a callback from `rustc_ast` as it cannot access the implicit state
27 /// in `rustc_middle` otherwise. It is used when diagnostic messages are
28 /// emitted and stores them in the current query, if there is one.
29 fn track_diagnostic(diagnostic: &Diagnostic) {
30     tls::with_context_opt(|icx| {
31         if let Some(icx) = icx {
32             if let Some(diagnostics) = icx.diagnostics {
33                 let mut diagnostics = diagnostics.lock();
34                 diagnostics.extend(Some(diagnostic.clone()));
35             }
36         }
37     })
38 }
39
40 /// This is a callback from `rustc_hir` as it cannot access the implicit state
41 /// in `rustc_middle` otherwise.
42 fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43     write!(f, "DefId({}:{}", def_id.krate, def_id.index.index())?;
44     tls::with_opt(|opt_tcx| {
45         if let Some(tcx) = opt_tcx {
46             write!(f, " ~ {}", tcx.def_path_debug_str(def_id))?;
47         }
48         Ok(())
49     })?;
50     write!(f, ")")
51 }
52
53 /// Sets up the callbacks in prior crates which we want to refer to the
54 /// TyCtxt in.
55 pub fn setup_callbacks() {
56     rustc_span::SPAN_TRACK.swap(&(track_span_parent as fn(_)));
57     rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
58     TRACK_DIAGNOSTICS.swap(&(track_diagnostic as fn(&_)));
59 }