]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/inherited.rs
Rollup merge of #103192 - petrochenkov:noalltraits, r=jyn514
[rust.git] / compiler / rustc_hir_typeck / src / inherited.rs
1 use super::callee::DeferredCallResolution;
2
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_data_structures::sync::Lrc;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::LocalDefId;
7 use rustc_hir::HirIdMap;
8 use rustc_infer::infer;
9 use rustc_infer::infer::{DefiningAnchor, InferCtxt, InferOk, TyCtxtInferExt};
10 use rustc_middle::ty::fold::TypeFoldable;
11 use rustc_middle::ty::visit::TypeVisitable;
12 use rustc_middle::ty::{self, Ty, TyCtxt};
13 use rustc_span::def_id::LocalDefIdMap;
14 use rustc_span::{self, Span};
15 use rustc_trait_selection::infer::InferCtxtExt as _;
16 use rustc_trait_selection::traits::{
17     self, ObligationCause, ObligationCtxt, TraitEngine, TraitEngineExt as _,
18 };
19
20 use std::cell::RefCell;
21 use std::ops::Deref;
22
23 /// 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 inherited fields.
32 pub struct Inherited<'tcx> {
33     pub(super) infcx: InferCtxt<'tcx>,
34
35     pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
36
37     pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
38
39     pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
40
41     // Some additional `Sized` obligations badly affect type inference.
42     // These obligations are added in a later stage of typeck.
43     // Removing these may also cause additional complications, see #101066.
44     pub(super) deferred_sized_obligations:
45         RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
46
47     // When we process a call like `c()` where `c` is a closure type,
48     // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
49     // `FnOnce` closure. In that case, we defer full resolution of the
50     // call until upvar inference can kick in and make the
51     // decision. We keep these deferred resolutions grouped by the
52     // def-id of the closure, so that once we decide, we can easily go
53     // back and process them.
54     pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
55
56     pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
57
58     pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, hir::HirId)>>,
59
60     pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>,
61
62     pub(super) deferred_generator_interiors:
63         RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
64
65     pub(super) body_id: Option<hir::BodyId>,
66
67     /// Whenever we introduce an adjustment from `!` into a type variable,
68     /// we record that type variable here. This is later used to inform
69     /// fallback. See the `fallback` module for details.
70     pub(super) diverging_type_vars: RefCell<FxHashSet<Ty<'tcx>>>,
71 }
72
73 impl<'tcx> Deref for Inherited<'tcx> {
74     type Target = InferCtxt<'tcx>;
75     fn deref(&self) -> &Self::Target {
76         &self.infcx
77     }
78 }
79
80 /// A temporary returned by `Inherited::build(...)`. This is necessary
81 /// for multiple `InferCtxt` to share the same `typeck_results`
82 /// without using `Rc` or something similar.
83 pub struct InheritedBuilder<'tcx> {
84     infcx: infer::InferCtxtBuilder<'tcx>,
85     def_id: LocalDefId,
86     typeck_results: RefCell<ty::TypeckResults<'tcx>>,
87 }
88
89 impl<'tcx> Inherited<'tcx> {
90     pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
91         let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
92
93         InheritedBuilder {
94             infcx: tcx
95                 .infer_ctxt()
96                 .ignoring_regions()
97                 .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id))
98                 .with_normalize_fn_sig_for_diagnostic(Lrc::new(move |infcx, fn_sig| {
99                     if fn_sig.has_escaping_bound_vars() {
100                         return fn_sig;
101                     }
102                     infcx.probe(|_| {
103                         let ocx = ObligationCtxt::new_in_snapshot(infcx);
104                         let normalized_fn_sig = ocx.normalize(
105                             ObligationCause::dummy(),
106                             // FIXME(compiler-errors): This is probably not the right param-env...
107                             infcx.tcx.param_env(def_id),
108                             fn_sig,
109                         );
110                         if ocx.select_all_or_error().is_empty() {
111                             let normalized_fn_sig =
112                                 infcx.resolve_vars_if_possible(normalized_fn_sig);
113                             if !normalized_fn_sig.needs_infer() {
114                                 return normalized_fn_sig;
115                             }
116                         }
117                         fn_sig
118                     })
119                 })),
120             def_id,
121             typeck_results: RefCell::new(ty::TypeckResults::new(hir_owner)),
122         }
123     }
124 }
125
126 impl<'tcx> InheritedBuilder<'tcx> {
127     pub fn enter<F, R>(mut self, f: F) -> R
128     where
129         F: FnOnce(&Inherited<'tcx>) -> R,
130     {
131         let def_id = self.def_id;
132         f(&Inherited::new(self.infcx.build(), def_id, self.typeck_results))
133     }
134 }
135
136 impl<'tcx> Inherited<'tcx> {
137     fn new(
138         infcx: InferCtxt<'tcx>,
139         def_id: LocalDefId,
140         typeck_results: RefCell<ty::TypeckResults<'tcx>>,
141     ) -> Self {
142         let tcx = infcx.tcx;
143         let body_id = tcx.hir().maybe_body_owned_by(def_id);
144
145         Inherited {
146             typeck_results,
147             infcx,
148             fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
149             locals: RefCell::new(Default::default()),
150             deferred_sized_obligations: RefCell::new(Vec::new()),
151             deferred_call_resolutions: RefCell::new(Default::default()),
152             deferred_cast_checks: RefCell::new(Vec::new()),
153             deferred_transmute_checks: RefCell::new(Vec::new()),
154             deferred_asm_checks: RefCell::new(Vec::new()),
155             deferred_generator_interiors: RefCell::new(Vec::new()),
156             diverging_type_vars: RefCell::new(Default::default()),
157             body_id,
158         }
159     }
160
161     #[instrument(level = "debug", skip(self))]
162     pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
163         if obligation.has_escaping_bound_vars() {
164             span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
165         }
166         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
167     }
168
169     pub(super) fn register_predicates<I>(&self, obligations: I)
170     where
171         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
172     {
173         for obligation in obligations {
174             self.register_predicate(obligation);
175         }
176     }
177
178     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
179         self.register_predicates(infer_ok.obligations);
180         infer_ok.value
181     }
182
183     pub(super) fn normalize_associated_types_in<T>(
184         &self,
185         span: Span,
186         body_id: hir::HirId,
187         param_env: ty::ParamEnv<'tcx>,
188         value: T,
189     ) -> T
190     where
191         T: TypeFoldable<'tcx>,
192     {
193         self.normalize_associated_types_in_with_cause(
194             ObligationCause::misc(span, body_id),
195             param_env,
196             value,
197         )
198     }
199
200     pub(super) fn normalize_associated_types_in_with_cause<T>(
201         &self,
202         cause: ObligationCause<'tcx>,
203         param_env: ty::ParamEnv<'tcx>,
204         value: T,
205     ) -> T
206     where
207         T: TypeFoldable<'tcx>,
208     {
209         let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
210         debug!(?ok);
211         self.register_infer_ok_obligations(ok)
212     }
213 }