]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/inherited.rs
partially_normalize_... -> At::normalize
[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::traits::{
16     self, NormalizeExt, ObligationCause, ObligationCtxt, TraitEngine, TraitEngineExt as _,
17 };
18
19 use std::cell::RefCell;
20 use std::ops::Deref;
21
22 /// Closures defined within the function. For example:
23 /// ```ignore (illustrative)
24 /// fn foo() {
25 ///     bar(move|| { ... })
26 /// }
27 /// ```
28 /// Here, the function `foo()` and the closure passed to
29 /// `bar()` will each have their own `FnCtxt`, but they will
30 /// share the inherited fields.
31 pub struct Inherited<'tcx> {
32     pub(super) infcx: InferCtxt<'tcx>,
33
34     pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
35
36     pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
37
38     pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'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>, hir::HirId)>>,
58
59     pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>,
60
61     pub(super) deferred_generator_interiors:
62         RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
63
64     pub(super) body_id: Option<hir::BodyId>,
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<FxHashSet<Ty<'tcx>>>,
70 }
71
72 impl<'tcx> Deref for Inherited<'tcx> {
73     type Target = InferCtxt<'tcx>;
74     fn deref(&self) -> &Self::Target {
75         &self.infcx
76     }
77 }
78
79 /// A temporary returned by `Inherited::build(...)`. This is necessary
80 /// for multiple `InferCtxt` to share the same `typeck_results`
81 /// without using `Rc` or something similar.
82 pub struct InheritedBuilder<'tcx> {
83     infcx: infer::InferCtxtBuilder<'tcx>,
84     def_id: LocalDefId,
85     typeck_results: RefCell<ty::TypeckResults<'tcx>>,
86 }
87
88 impl<'tcx> Inherited<'tcx> {
89     pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
90         let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
91
92         InheritedBuilder {
93             infcx: tcx
94                 .infer_ctxt()
95                 .ignoring_regions()
96                 .with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id))
97                 .with_normalize_fn_sig_for_diagnostic(Lrc::new(move |infcx, fn_sig| {
98                     if fn_sig.has_escaping_bound_vars() {
99                         return fn_sig;
100                     }
101                     infcx.probe(|_| {
102                         let ocx = ObligationCtxt::new_in_snapshot(infcx);
103                         let normalized_fn_sig = ocx.normalize(
104                             ObligationCause::dummy(),
105                             // FIXME(compiler-errors): This is probably not the right param-env...
106                             infcx.tcx.param_env(def_id),
107                             fn_sig,
108                         );
109                         if ocx.select_all_or_error().is_empty() {
110                             let normalized_fn_sig =
111                                 infcx.resolve_vars_if_possible(normalized_fn_sig);
112                             if !normalized_fn_sig.needs_infer() {
113                                 return normalized_fn_sig;
114                             }
115                         }
116                         fn_sig
117                     })
118                 })),
119             def_id,
120             typeck_results: RefCell::new(ty::TypeckResults::new(hir_owner)),
121         }
122     }
123 }
124
125 impl<'tcx> InheritedBuilder<'tcx> {
126     pub fn enter<F, R>(mut self, f: F) -> R
127     where
128         F: FnOnce(&Inherited<'tcx>) -> R,
129     {
130         let def_id = self.def_id;
131         f(&Inherited::new(self.infcx.build(), def_id, self.typeck_results))
132     }
133 }
134
135 impl<'tcx> Inherited<'tcx> {
136     fn new(
137         infcx: InferCtxt<'tcx>,
138         def_id: LocalDefId,
139         typeck_results: RefCell<ty::TypeckResults<'tcx>>,
140     ) -> Self {
141         let tcx = infcx.tcx;
142         let body_id = tcx.hir().maybe_body_owned_by(def_id);
143
144         Inherited {
145             typeck_results,
146             infcx,
147             fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
148             locals: RefCell::new(Default::default()),
149             deferred_sized_obligations: RefCell::new(Vec::new()),
150             deferred_call_resolutions: RefCell::new(Default::default()),
151             deferred_cast_checks: RefCell::new(Vec::new()),
152             deferred_transmute_checks: RefCell::new(Vec::new()),
153             deferred_asm_checks: RefCell::new(Vec::new()),
154             deferred_generator_interiors: RefCell::new(Vec::new()),
155             diverging_type_vars: RefCell::new(Default::default()),
156             body_id,
157         }
158     }
159
160     #[instrument(level = "debug", skip(self))]
161     pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
162         if obligation.has_escaping_bound_vars() {
163             span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
164         }
165         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
166     }
167
168     pub(super) fn register_predicates<I>(&self, obligations: I)
169     where
170         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
171     {
172         for obligation in obligations {
173             self.register_predicate(obligation);
174         }
175     }
176
177     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
178         self.register_predicates(infer_ok.obligations);
179         infer_ok.value
180     }
181
182     pub(super) fn normalize_associated_types_in<T>(
183         &self,
184         span: Span,
185         body_id: hir::HirId,
186         param_env: ty::ParamEnv<'tcx>,
187         value: T,
188     ) -> T
189     where
190         T: TypeFoldable<'tcx>,
191     {
192         self.normalize_associated_types_in_with_cause(
193             ObligationCause::misc(span, body_id),
194             param_env,
195             value,
196         )
197     }
198
199     pub(super) fn normalize_associated_types_in_with_cause<T>(
200         &self,
201         cause: ObligationCause<'tcx>,
202         param_env: ty::ParamEnv<'tcx>,
203         value: T,
204     ) -> T
205     where
206         T: TypeFoldable<'tcx>,
207     {
208         let ok = self.at(&cause, param_env).normalize(value);
209         debug!(?ok);
210         self.register_infer_ok_obligations(ok)
211     }
212 }