1 use super::callee::DeferredCallResolution;
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_hir::def_id::LocalDefId;
6 use rustc_hir::HirIdMap;
7 use rustc_infer::infer;
8 use rustc_infer::infer::{DefiningAnchor, InferCtxt, InferOk, TyCtxtInferExt};
9 use rustc_middle::ty::visit::TypeVisitable;
10 use rustc_middle::ty::{self, Ty, TyCtxt};
11 use rustc_span::def_id::LocalDefIdMap;
12 use rustc_span::{self, Span};
13 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
14 use rustc_trait_selection::traits::{self, PredicateObligation, TraitEngine, TraitEngineExt as _};
16 use std::cell::RefCell;
19 /// Closures defined within the function. For example:
20 /// ```ignore (illustrative)
22 /// bar(move|| { ... })
25 /// Here, the function `foo()` and the closure passed to
26 /// `bar()` will each have their own `FnCtxt`, but they will
27 /// share the inherited fields.
28 pub struct Inherited<'tcx> {
29 pub(super) infcx: InferCtxt<'tcx>,
31 pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
33 pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
35 pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
37 /// Some additional `Sized` obligations badly affect type inference.
38 /// These obligations are added in a later stage of typeck.
39 /// Removing these may also cause additional complications, see #101066.
40 pub(super) deferred_sized_obligations:
41 RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
43 /// When we process a call like `c()` where `c` is a closure type,
44 /// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
45 /// `FnOnce` closure. In that case, we defer full resolution of the
46 /// call until upvar inference can kick in and make the
47 /// decision. We keep these deferred resolutions grouped by the
48 /// def-id of the closure, so that once we decide, we can easily go
49 /// back and process them.
50 pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
52 pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
54 pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, hir::HirId)>>,
56 pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>,
58 pub(super) deferred_generator_interiors:
59 RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
61 pub(super) body_id: Option<hir::BodyId>,
63 /// Whenever we introduce an adjustment from `!` into a type variable,
64 /// we record that type variable here. This is later used to inform
65 /// fallback. See the `fallback` module for details.
66 pub(super) diverging_type_vars: RefCell<FxHashSet<Ty<'tcx>>>,
68 pub(super) relationships: RefCell<FxHashMap<ty::TyVid, ty::FoundRelationships>>,
71 impl<'tcx> Deref for Inherited<'tcx> {
72 type Target = InferCtxt<'tcx>;
73 fn deref(&self) -> &Self::Target {
78 /// A temporary returned by `Inherited::build(...)`. This is necessary
79 /// for multiple `InferCtxt` to share the same `typeck_results`
80 /// without using `Rc` or something similar.
81 pub struct InheritedBuilder<'tcx> {
82 infcx: infer::InferCtxtBuilder<'tcx>,
84 typeck_results: RefCell<ty::TypeckResults<'tcx>>,
87 impl<'tcx> Inherited<'tcx> {
88 pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
89 let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
95 .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)),
97 typeck_results: RefCell::new(ty::TypeckResults::new(hir_owner)),
102 impl<'tcx> InheritedBuilder<'tcx> {
103 pub fn enter<F, R>(mut self, f: F) -> R
105 F: FnOnce(&Inherited<'tcx>) -> R,
107 let def_id = self.def_id;
108 f(&Inherited::new(self.infcx.build(), def_id, self.typeck_results))
112 impl<'tcx> Inherited<'tcx> {
114 infcx: InferCtxt<'tcx>,
116 typeck_results: RefCell<ty::TypeckResults<'tcx>>,
119 let body_id = tcx.hir().maybe_body_owned_by(def_id);
124 fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
125 locals: RefCell::new(Default::default()),
126 deferred_sized_obligations: RefCell::new(Vec::new()),
127 deferred_call_resolutions: RefCell::new(Default::default()),
128 deferred_cast_checks: RefCell::new(Vec::new()),
129 deferred_transmute_checks: RefCell::new(Vec::new()),
130 deferred_asm_checks: RefCell::new(Vec::new()),
131 deferred_generator_interiors: RefCell::new(Vec::new()),
132 diverging_type_vars: RefCell::new(Default::default()),
134 relationships: RefCell::new(Default::default()),
138 #[instrument(level = "debug", skip(self))]
139 pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
140 if obligation.has_escaping_bound_vars() {
141 span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
144 self.update_infer_var_info(&obligation);
146 self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
149 pub(super) fn register_predicates<I>(&self, obligations: I)
151 I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
153 for obligation in obligations {
154 self.register_predicate(obligation);
158 pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
159 self.register_predicates(infer_ok.obligations);
163 pub fn update_infer_var_info(&self, obligation: &PredicateObligation<'tcx>) {
164 let relationships = &mut self.relationships.borrow_mut();
166 // (*) binder skipped
167 if let ty::PredicateKind::Clause(ty::Clause::Trait(tpred)) = obligation.predicate.kind().skip_binder()
168 && let Some(ty) = self.shallow_resolve(tpred.self_ty()).ty_vid().map(|t| self.root_var(t))
169 && self.tcx.lang_items().sized_trait().map_or(false, |st| st != tpred.trait_ref.def_id)
171 let new_self_ty = self.tcx.types.unit;
173 // Then construct a new obligation with Self = () added
174 // to the ParamEnv, and see if it holds.
175 let o = obligation.with(self.tcx,
180 // (*) binder moved here
181 ty::PredicateKind::Clause(ty::Clause::Trait(tpred.with_self_ty(self.tcx, new_self_ty)))
184 // Don't report overflow errors. Otherwise equivalent to may_hold.
185 if let Ok(result) = self.probe(|_| self.evaluate_obligation(&o)) && result.may_apply() {
186 relationships.entry(ty).or_default().self_in_trait = true;
190 if let ty::PredicateKind::Clause(ty::Clause::Projection(predicate)) =
191 obligation.predicate.kind().skip_binder()
193 // If the projection predicate (Foo::Bar == X) has X as a non-TyVid,
194 // we need to make it into one.
195 if let Some(vid) = predicate.term.ty().and_then(|ty| ty.ty_vid()) {
196 debug!("relationships: {:?}.output = true", vid);
197 relationships.entry(vid).or_default().output = true;