rustc_hir_typeck/
typeck_root_ctxt.rs

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