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