rustc_hir_typeck/
typeck_root_ctxt.rs

1use std::cell::RefCell;
2use std::ops::Deref;
3
4use rustc_data_structures::unord::{UnordMap, UnordSet};
5use rustc_hir as hir;
6use rustc_hir::def_id::LocalDefId;
7use rustc_hir::{HirId, HirIdMap};
8use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
9use rustc_middle::span_bug;
10use rustc_middle::ty::visit::TypeVisitableExt;
11use rustc_middle::ty::{self, Ty, TyCtxt, TypingMode};
12use rustc_span::Span;
13use rustc_span::def_id::LocalDefIdMap;
14use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
15use rustc_trait_selection::traits::{
16    self, FulfillmentError, PredicateObligation, TraitEngine, TraitEngineExt as _,
17};
18use tracing::{debug, instrument};
19
20use super::callee::DeferredCallResolution;
21
22/// Data shared between a "typeck root" and its nested bodies,
23/// e.g. closures defined within the function. For example:
24/// ```ignore (illustrative)
25/// fn foo() {
26///     bar(move || { ... })
27/// }
28/// ```
29/// Here, the function `foo()` and the closure passed to
30/// `bar()` will each have their own `FnCtxt`, but they will
31/// share the inference context, will process obligations together,
32/// can access each other's local types (scoping permitted), etc.
33pub(crate) struct TypeckRootCtxt<'tcx> {
34    pub(super) infcx: InferCtxt<'tcx>,
35
36    pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
37
38    pub(super) locals: RefCell<HirIdMap<Ty<'tcx>>>,
39
40    pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx, FulfillmentError<'tcx>>>>,
41
42    /// Some additional `Sized` obligations badly affect type inference.
43    /// These obligations are added in a later stage of typeck.
44    /// Removing these may also cause additional complications, see #101066.
45    pub(super) deferred_sized_obligations:
46        RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
47
48    /// When we process a call like `c()` where `c` is a closure type,
49    /// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
50    /// `FnOnce` closure. In that case, we defer full resolution of the
51    /// call until upvar inference can kick in and make the
52    /// decision. We keep these deferred resolutions grouped by the
53    /// def-id of the closure, so that once we decide, we can easily go
54    /// back and process them.
55    pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
56
57    pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
58
59    pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, HirId)>>,
60
61    pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, HirId)>>,
62
63    pub(super) deferred_coroutine_interiors: RefCell<Vec<(LocalDefId, hir::BodyId, Ty<'tcx>)>>,
64
65    /// Whenever we introduce an adjustment from `!` into a type variable,
66    /// we record that type variable here. This is later used to inform
67    /// fallback. See the `fallback` module for details.
68    pub(super) diverging_type_vars: RefCell<UnordSet<Ty<'tcx>>>,
69
70    pub(super) infer_var_info: RefCell<UnordMap<ty::TyVid, ty::InferVarInfo>>,
71}
72
73impl<'tcx> Deref for TypeckRootCtxt<'tcx> {
74    type Target = InferCtxt<'tcx>;
75    fn deref(&self) -> &Self::Target {
76        &self.infcx
77    }
78}
79
80impl<'tcx> TypeckRootCtxt<'tcx> {
81    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
82        let hir_owner = tcx.local_def_id_to_hir_id(def_id).owner;
83
84        let infcx =
85            tcx.infer_ctxt().ignoring_regions().build(TypingMode::analysis_in_body(tcx, def_id));
86        let typeck_results = RefCell::new(ty::TypeckResults::new(hir_owner));
87
88        TypeckRootCtxt {
89            typeck_results,
90            fulfillment_cx: RefCell::new(<dyn TraitEngine<'_, _>>::new(&infcx)),
91            infcx,
92            locals: RefCell::new(Default::default()),
93            deferred_sized_obligations: RefCell::new(Vec::new()),
94            deferred_call_resolutions: RefCell::new(Default::default()),
95            deferred_cast_checks: RefCell::new(Vec::new()),
96            deferred_transmute_checks: RefCell::new(Vec::new()),
97            deferred_asm_checks: RefCell::new(Vec::new()),
98            deferred_coroutine_interiors: RefCell::new(Vec::new()),
99            diverging_type_vars: RefCell::new(Default::default()),
100            infer_var_info: RefCell::new(Default::default()),
101        }
102    }
103
104    #[instrument(level = "debug", skip(self))]
105    pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
106        if obligation.has_escaping_bound_vars() {
107            span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
108        }
109
110        self.update_infer_var_info(&obligation);
111
112        self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
113    }
114
115    pub(super) fn register_predicates<I>(&self, obligations: I)
116    where
117        I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
118    {
119        for obligation in obligations {
120            self.register_predicate(obligation);
121        }
122    }
123
124    pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
125        self.register_predicates(infer_ok.obligations);
126        infer_ok.value
127    }
128
129    fn update_infer_var_info(&self, obligation: &PredicateObligation<'tcx>) {
130        let infer_var_info = &mut self.infer_var_info.borrow_mut();
131
132        // (*) binder skipped
133        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(tpred)) =
134            obligation.predicate.kind().skip_binder()
135            && let Some(ty) =
136                self.shallow_resolve(tpred.self_ty()).ty_vid().map(|t| self.root_var(t))
137            && self.tcx.lang_items().sized_trait().is_some_and(|st| st != tpred.trait_ref.def_id)
138        {
139            let new_self_ty = self.tcx.types.unit;
140
141            // Then construct a new obligation with Self = () added
142            // to the ParamEnv, and see if it holds.
143            let o = obligation.with(
144                self.tcx,
145                obligation.predicate.kind().rebind(
146                    // (*) binder moved here
147                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(
148                        tpred.with_self_ty(self.tcx, new_self_ty),
149                    )),
150                ),
151            );
152            // Don't report overflow errors. Otherwise equivalent to may_hold.
153            if let Ok(result) = self.probe(|_| self.evaluate_obligation(&o))
154                && result.may_apply()
155            {
156                infer_var_info.entry(ty).or_default().self_in_trait = true;
157            }
158        }
159
160        if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) =
161            obligation.predicate.kind().skip_binder()
162        {
163            // If the projection predicate (Foo::Bar == X) has X as a non-TyVid,
164            // we need to make it into one.
165            if let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) {
166                debug!("infer_var_info: {:?}.output = true", vid);
167                infer_var_info.entry(vid).or_default().output = true;
168            }
169        }
170    }
171}