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