]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/inherited.rs
Rollup merge of #107780 - compiler-errors:instantiate-binder, r=lcnr
[rust.git] / compiler / rustc_hir_typeck / src / inherited.rs
1 use super::callee::DeferredCallResolution;
2
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir as hir;
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 _};
15
16 use std::cell::RefCell;
17 use std::ops::Deref;
18
19 /// Closures defined within the function. For example:
20 /// ```ignore (illustrative)
21 /// fn foo() {
22 ///     bar(move|| { ... })
23 /// }
24 /// ```
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>,
30
31     pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
32
33     pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
34
35     pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
36
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>)>>,
42
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>>>>,
51
52     pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
53
54     pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, hir::HirId)>>,
55
56     pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>,
57
58     pub(super) deferred_generator_interiors:
59         RefCell<Vec<(LocalDefId, hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
60
61     pub(super) body_id: Option<hir::BodyId>,
62
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>>>,
67
68     pub(super) infer_var_info: RefCell<FxHashMap<ty::TyVid, ty::InferVarInfo>>,
69 }
70
71 impl<'tcx> Deref for Inherited<'tcx> {
72     type Target = InferCtxt<'tcx>;
73     fn deref(&self) -> &Self::Target {
74         &self.infcx
75     }
76 }
77
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>,
83     def_id: LocalDefId,
84     typeck_results: RefCell<ty::TypeckResults<'tcx>>,
85 }
86
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;
90
91         InheritedBuilder {
92             infcx: tcx
93                 .infer_ctxt()
94                 .ignoring_regions()
95                 .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)),
96             def_id,
97             typeck_results: RefCell::new(ty::TypeckResults::new(hir_owner)),
98         }
99     }
100 }
101
102 impl<'tcx> InheritedBuilder<'tcx> {
103     pub fn enter<F, R>(mut self, f: F) -> R
104     where
105         F: FnOnce(&Inherited<'tcx>) -> R,
106     {
107         let def_id = self.def_id;
108         f(&Inherited::new(self.infcx.build(), def_id, self.typeck_results))
109     }
110 }
111
112 impl<'tcx> Inherited<'tcx> {
113     fn new(
114         infcx: InferCtxt<'tcx>,
115         def_id: LocalDefId,
116         typeck_results: RefCell<ty::TypeckResults<'tcx>>,
117     ) -> Self {
118         let tcx = infcx.tcx;
119         let body_id = tcx.hir().maybe_body_owned_by(def_id);
120
121         Inherited {
122             typeck_results,
123             infcx,
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()),
133             body_id,
134             infer_var_info: RefCell::new(Default::default()),
135         }
136     }
137
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);
142         }
143
144         self.update_infer_var_info(&obligation);
145
146         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
147     }
148
149     pub(super) fn register_predicates<I>(&self, obligations: I)
150     where
151         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
152     {
153         for obligation in obligations {
154             self.register_predicate(obligation);
155         }
156     }
157
158     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
159         self.register_predicates(infer_ok.obligations);
160         infer_ok.value
161     }
162
163     pub fn update_infer_var_info(&self, obligation: &PredicateObligation<'tcx>) {
164         let infer_var_info = &mut self.infer_var_info.borrow_mut();
165
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)
170         {
171             let new_self_ty = self.tcx.types.unit;
172
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,
176                 obligation
177                     .predicate
178                     .kind()
179                     .rebind(
180                         // (*) binder moved here
181                         ty::PredicateKind::Clause(ty::Clause::Trait(tpred.with_self_ty(self.tcx, new_self_ty)))
182                     ),
183             );
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                 infer_var_info.entry(ty).or_default().self_in_trait = true;
187             }
188         }
189
190         if let ty::PredicateKind::Clause(ty::Clause::Projection(predicate)) =
191             obligation.predicate.kind().skip_binder()
192         {
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!("infer_var_info: {:?}.output = true", vid);
197                 infer_var_info.entry(vid).or_default().output = true;
198             }
199         }
200     }
201 }