]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/inherited.rs
Auto merge of #104940 - cjgillot:query-feed-simple, r=oli-obk
[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::visit::TypeVisitable;
11 use rustc_middle::ty::{self, Ty, TyCtxt};
12 use rustc_span::def_id::LocalDefIdMap;
13 use rustc_span::{self, Span};
14 use rustc_trait_selection::traits::{
15     self, ObligationCause, ObligationCtxt, TraitEngine, TraitEngineExt as _,
16 };
17
18 use std::cell::RefCell;
19 use std::ops::Deref;
20
21 /// 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 inherited fields.
30 pub struct Inherited<'tcx> {
31     pub(super) infcx: InferCtxt<'tcx>,
32
33     pub(super) typeck_results: RefCell<ty::TypeckResults<'tcx>>,
34
35     pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
36
37     pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
38
39     /// Some additional `Sized` obligations badly affect type inference.
40     /// These obligations are added in a later stage of typeck.
41     /// Removing these may also cause additional complications, see #101066.
42     pub(super) deferred_sized_obligations:
43         RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
44
45     /// When we process a call like `c()` where `c` is a closure type,
46     /// we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
47     /// `FnOnce` closure. In that case, we defer full resolution of the
48     /// call until upvar inference can kick in and make the
49     /// decision. We keep these deferred resolutions grouped by the
50     /// def-id of the closure, so that once we decide, we can easily go
51     /// back and process them.
52     pub(super) deferred_call_resolutions: RefCell<LocalDefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
53
54     pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
55
56     pub(super) deferred_transmute_checks: RefCell<Vec<(Ty<'tcx>, Ty<'tcx>, hir::HirId)>>,
57
58     pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>,
59
60     pub(super) deferred_generator_interiors:
61         RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
62
63     pub(super) body_id: Option<hir::BodyId>,
64
65     /// Whenever we introduce an adjustment from `!` into a type variable,
66     /// we record that type variable here. This is later used to inform
67     /// fallback. See the `fallback` module for details.
68     pub(super) diverging_type_vars: RefCell<FxHashSet<Ty<'tcx>>>,
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                 .with_normalize_fn_sig_for_diagnostic(Lrc::new(move |infcx, fn_sig| {
97                     if fn_sig.has_escaping_bound_vars() {
98                         return fn_sig;
99                     }
100                     infcx.probe(|_| {
101                         let ocx = ObligationCtxt::new_in_snapshot(infcx);
102                         let normalized_fn_sig = ocx.normalize(
103                             &ObligationCause::dummy(),
104                             // FIXME(compiler-errors): This is probably not the right param-env...
105                             infcx.tcx.param_env(def_id),
106                             fn_sig,
107                         );
108                         if ocx.select_all_or_error().is_empty() {
109                             let normalized_fn_sig =
110                                 infcx.resolve_vars_if_possible(normalized_fn_sig);
111                             if !normalized_fn_sig.needs_infer() {
112                                 return normalized_fn_sig;
113                             }
114                         }
115                         fn_sig
116                     })
117                 })),
118             def_id,
119             typeck_results: RefCell::new(ty::TypeckResults::new(hir_owner)),
120         }
121     }
122 }
123
124 impl<'tcx> InheritedBuilder<'tcx> {
125     pub fn enter<F, R>(mut self, f: F) -> R
126     where
127         F: FnOnce(&Inherited<'tcx>) -> R,
128     {
129         let def_id = self.def_id;
130         f(&Inherited::new(self.infcx.build(), def_id, self.typeck_results))
131     }
132 }
133
134 impl<'tcx> Inherited<'tcx> {
135     fn new(
136         infcx: InferCtxt<'tcx>,
137         def_id: LocalDefId,
138         typeck_results: RefCell<ty::TypeckResults<'tcx>>,
139     ) -> Self {
140         let tcx = infcx.tcx;
141         let body_id = tcx.hir().maybe_body_owned_by(def_id);
142
143         Inherited {
144             typeck_results,
145             infcx,
146             fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
147             locals: RefCell::new(Default::default()),
148             deferred_sized_obligations: RefCell::new(Vec::new()),
149             deferred_call_resolutions: RefCell::new(Default::default()),
150             deferred_cast_checks: RefCell::new(Vec::new()),
151             deferred_transmute_checks: RefCell::new(Vec::new()),
152             deferred_asm_checks: RefCell::new(Vec::new()),
153             deferred_generator_interiors: RefCell::new(Vec::new()),
154             diverging_type_vars: RefCell::new(Default::default()),
155             body_id,
156         }
157     }
158
159     #[instrument(level = "debug", skip(self))]
160     pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
161         if obligation.has_escaping_bound_vars() {
162             span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
163         }
164         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
165     }
166
167     pub(super) fn register_predicates<I>(&self, obligations: I)
168     where
169         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
170     {
171         for obligation in obligations {
172             self.register_predicate(obligation);
173         }
174     }
175
176     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
177         self.register_predicates(infer_ok.obligations);
178         infer_ok.value
179     }
180 }