rustc_trait_selection/error_reporting/
mod.rs

1use std::ops::Deref;
2
3use rustc_errors::DiagCtxtHandle;
4use rustc_infer::infer::InferCtxt;
5use rustc_infer::traits::PredicateObligations;
6use rustc_macros::extension;
7use rustc_middle::bug;
8use rustc_middle::ty::{self, Ty};
9
10pub mod infer;
11pub mod traits;
12
13/// A helper for building type related errors. The `typeck_results`
14/// field is only populated during an in-progress typeck.
15/// Get an instance by calling `InferCtxt::err_ctxt` or `FnCtxt::err_ctxt`.
16///
17/// You must only create this if you intend to actually emit an error (or
18/// perhaps a warning, though preferably not.) It provides a lot of utility
19/// methods which should not be used during the happy path.
20pub struct TypeErrCtxt<'a, 'tcx> {
21    pub infcx: &'a InferCtxt<'tcx>,
22
23    pub typeck_results: Option<std::cell::Ref<'a, ty::TypeckResults<'tcx>>>,
24    pub fallback_has_occurred: bool,
25
26    pub normalize_fn_sig: Box<dyn Fn(ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx> + 'a>,
27
28    pub autoderef_steps: Box<dyn Fn(Ty<'tcx>) -> Vec<(Ty<'tcx>, PredicateObligations<'tcx>)> + 'a>,
29}
30
31#[extension(pub trait InferCtxtErrorExt<'tcx>)]
32impl<'tcx> InferCtxt<'tcx> {
33    /// Creates a `TypeErrCtxt` for emitting various inference errors.
34    /// During typeck, use `FnCtxt::err_ctxt` instead.
35    fn err_ctxt(&self) -> TypeErrCtxt<'_, 'tcx> {
36        TypeErrCtxt {
37            infcx: self,
38            typeck_results: None,
39            fallback_has_occurred: false,
40            normalize_fn_sig: Box::new(|fn_sig| fn_sig),
41            autoderef_steps: Box::new(|ty| {
42                debug_assert!(false, "shouldn't be using autoderef_steps outside of typeck");
43                vec![(ty, PredicateObligations::new())]
44            }),
45        }
46    }
47}
48
49impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
50    pub fn dcx(&self) -> DiagCtxtHandle<'a> {
51        self.infcx.dcx()
52    }
53
54    /// This is just to avoid a potential footgun of accidentally
55    /// dropping `typeck_results` by calling `InferCtxt::err_ctxt`
56    #[deprecated(note = "you already have a `TypeErrCtxt`")]
57    #[allow(unused)]
58    pub fn err_ctxt(&self) -> ! {
59        bug!("called `err_ctxt` on `TypeErrCtxt`. Try removing the call");
60    }
61}
62
63impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> {
64    type Target = InferCtxt<'tcx>;
65    fn deref(&self) -> &InferCtxt<'tcx> {
66        self.infcx
67    }
68}