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::def_id::LocalDefId;
6use rustc_hir::{self as hir, HirId, HirIdMap, LangItem};
7use rustc_infer::infer::{InferCtxt, InferOk, 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    /// Some additional `Sized` obligations badly affect type inference.
41    /// These obligations are added in a later stage of typeck.
42    /// Removing these may also cause additional complications, see #101066.
43    pub(super) deferred_sized_obligations:
44        RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
45
46    /// When we process a call like `c()` where `c` is a closure type,
47    /// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
48    /// `FnOnce` closure. In that case, we defer full resolution of the
49    /// call until upvar inference can kick in and make the
50    /// decision. We keep these deferred resolutions grouped by the
51    /// def-id of the closure, so that once we decide, we can easily go
52    /// back and process them.
53    pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
54
55    pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
56
57    pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, HirId)>>,
58
59    pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, HirId)>>,
60
61    pub(super) deferred_coroutine_interiors: RefCell<Vec<(LocalDefId, Ty<'tcx>)>>,
62
63    pub(super) deferred_repeat_expr_checks:
64        RefCell<Vec<(&'tcx hir::Expr<'tcx>, Ty<'tcx>, ty::Const<'tcx>)>>,
65
66    /// Whenever we introduce an adjustment from `!` into a type variable,
67    /// we record that type variable here. This is later used to inform
68    /// fallback. See the `fallback` module for details.
69    pub(super) diverging_type_vars: RefCell<UnordSet<Ty<'tcx>>>,
70
71    pub(super) infer_var_info: RefCell<UnordMap<ty::TyVid, ty::InferVarInfo>>,
72}
73
74impl<'tcx> Deref for TypeckRootCtxt<'tcx> {
75    type Target = InferCtxt<'tcx>;
76    fn deref(&self) -> &Self::Target {
77        &self.infcx
78    }
79}
80
81impl<'tcx> TypeckRootCtxt<'tcx> {
82    pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
83        let hir_owner = tcx.local_def_id_to_hir_id(def_id).owner;
84
85        let infcx =
86            tcx.infer_ctxt().ignoring_regions().build(TypingMode::analysis_in_body(tcx, def_id));
87        let typeck_results = RefCell::new(ty::TypeckResults::new(hir_owner));
88
89        TypeckRootCtxt {
90            typeck_results,
91            fulfillment_cx: RefCell::new(<dyn TraitEngine<'_, _>>::new(&infcx)),
92            infcx,
93            locals: RefCell::new(Default::default()),
94            deferred_sized_obligations: RefCell::new(Vec::new()),
95            deferred_call_resolutions: RefCell::new(Default::default()),
96            deferred_cast_checks: RefCell::new(Vec::new()),
97            deferred_transmute_checks: RefCell::new(Vec::new()),
98            deferred_asm_checks: RefCell::new(Vec::new()),
99            deferred_coroutine_interiors: RefCell::new(Vec::new()),
100            deferred_repeat_expr_checks: RefCell::new(Vec::new()),
101            diverging_type_vars: RefCell::new(Default::default()),
102            infer_var_info: RefCell::new(Default::default()),
103        }
104    }
105
106    #[instrument(level = "debug", skip(self))]
107    pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
108        if obligation.has_escaping_bound_vars() {
109            span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
110        }
111
112        self.update_infer_var_info(&obligation);
113
114        self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
115    }
116
117    pub(super) fn register_predicates<I>(&self, obligations: I)
118    where
119        I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
120    {
121        for obligation in obligations {
122            self.register_predicate(obligation);
123        }
124    }
125
126    pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
127        self.register_predicates(infer_ok.obligations);
128        infer_ok.value
129    }
130
131    fn update_infer_var_info(&self, obligation: &PredicateObligation<'tcx>) {
132        let infer_var_info = &mut self.infer_var_info.borrow_mut();
133
134        // (*) binder skipped
135        if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(tpred)) =
136            obligation.predicate.kind().skip_binder()
137            && let Some(ty) =
138                self.shallow_resolve(tpred.self_ty()).ty_vid().map(|t| self.root_var(t))
139            && !self.tcx.is_lang_item(tpred.trait_ref.def_id, LangItem::Sized)
140        {
141            let new_self_ty = self.tcx.types.unit;
142
143            // Then construct a new obligation with Self = () added
144            // to the ParamEnv, and see if it holds.
145            let o = obligation.with(
146                self.tcx,
147                obligation.predicate.kind().rebind(
148                    // (*) binder moved here
149                    ty::PredicateKind::Clause(ty::ClauseKind::Trait(
150                        tpred.with_self_ty(self.tcx, new_self_ty),
151                    )),
152                ),
153            );
154            // Don't report overflow errors. Otherwise equivalent to may_hold.
155            if let Ok(result) = self.probe(|_| self.evaluate_obligation(&o))
156                && result.may_apply()
157            {
158                infer_var_info.entry(ty).or_default().self_in_trait = true;
159            }
160        }
161
162        if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(predicate)) =
163            obligation.predicate.kind().skip_binder()
164        {
165            // If the projection predicate (Foo::Bar == X) has X as a non-TyVid,
166            // we need to make it into one.
167            if let Some(vid) = predicate.term.as_type().and_then(|ty| ty.ty_vid()) {
168                debug!("infer_var_info: {:?}.output = true", vid);
169                infer_var_info.entry(vid).or_default().output = true;
170            }
171        }
172    }
173}