]> git.proxmox.com Git - rustc.git/blame - src/librustc_interface/callbacks.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_interface / callbacks.rs
CommitLineData
dfeec247
XL
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
ba9703b0 3//! of librustc_middle. To facilitate this, we have the
dfeec247
XL
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_DEBUG` 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
dfeec247 12use rustc_errors::{Diagnostic, TRACK_DIAGNOSTICS};
ba9703b0 13use rustc_middle::ty::tls;
dfeec247
XL
14use std::fmt;
15
74b04a01 16/// This is a callback from librustc_ast as it cannot access the implicit state
ba9703b0 17/// in librustc_middle otherwise.
dfeec247
XL
18fn span_debug(span: rustc_span::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 tls::with_opt(|tcx| {
20 if let Some(tcx) = tcx {
21 write!(f, "{}", tcx.sess.source_map().span_to_string(span))
22 } else {
23 rustc_span::default_span_debug(span, f)
24 }
25 })
26}
27
74b04a01 28/// This is a callback from librustc_ast as it cannot access the implicit state
ba9703b0 29/// in librustc_middle otherwise. It is used to when diagnostic messages are
dfeec247
XL
30/// emitted and stores them in the current query, if there is one.
31fn track_diagnostic(diagnostic: &Diagnostic) {
32 tls::with_context_opt(|icx| {
33 if let Some(icx) = icx {
34 if let Some(ref diagnostics) = icx.diagnostics {
35 let mut diagnostics = diagnostics.lock();
36 diagnostics.extend(Some(diagnostic.clone()));
37 }
38 }
39 })
40}
41
42/// This is a callback from librustc_hir as it cannot access the implicit state
ba9703b0 43/// in librustc_middle otherwise.
dfeec247
XL
44fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 write!(f, "DefId({}:{}", def_id.krate, def_id.index.index())?;
46 tls::with_opt(|opt_tcx| {
47 if let Some(tcx) = opt_tcx {
48 write!(f, " ~ {}", tcx.def_path_debug_str(def_id))?;
49 }
50 Ok(())
51 })?;
52 write!(f, ")")
53}
54
55/// Sets up the callbacks in prior crates which we want to refer to the
56/// TyCtxt in.
57pub fn setup_callbacks() {
58 rustc_span::SPAN_DEBUG.swap(&(span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
59 rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
60 TRACK_DIAGNOSTICS.swap(&(track_diagnostic as fn(&_)));
61}