]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/inherited.rs
Rollup merge of #90895 - RalfJung:read-discriminant-valid, r=oli-obk
[rust.git] / compiler / rustc_typeck / src / check / inherited.rs
1 use super::callee::DeferredCallResolution;
2 use super::MaybeInProgressTables;
3
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::{DefIdMap, 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::{self, Ty, TyCtxt};
12 use rustc_span::{self, Span};
13 use rustc_trait_selection::infer::InferCtxtExt as _;
14 use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
15
16 use std::cell::RefCell;
17 use std::ops::Deref;
18
19 /// Closures defined within the function. For example:
20 ///
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<'a, 'tcx> {
29     pub(super) infcx: InferCtxt<'a, 'tcx>,
30
31     pub(super) typeck_results: super::MaybeInProgressTables<'a, '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     pub(super) deferred_sized_obligations:
40         RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>,
41
42     // When we process a call like `c()` where `c` is a closure type,
43     // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
44     // `FnOnce` closure. In that case, we defer full resolution of the
45     // call until upvar inference can kick in and make the
46     // decision. We keep these deferred resolutions grouped by the
47     // def-id of the closure, so that once we decide, we can easily go
48     // back and process them.
49     pub(super) deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
50
51     pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
52
53     pub(super) deferred_generator_interiors:
54         RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
55
56     /// Reports whether this is in a const context.
57     pub(super) constness: hir::Constness,
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 /// Helper type of a temporary returned by `Inherited::build(...)`.
75 /// Necessary because we can't write the following bound:
76 /// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
77 pub struct InheritedBuilder<'tcx> {
78     infcx: infer::InferCtxtBuilder<'tcx>,
79     def_id: LocalDefId,
80 }
81
82 impl 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.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
88             def_id,
89         }
90     }
91 }
92
93 impl<'tcx> InheritedBuilder<'tcx> {
94     pub fn enter<F, R>(&mut self, f: F) -> R
95     where
96         F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
97     {
98         let def_id = self.def_id;
99         self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
100     }
101 }
102
103 impl Inherited<'a, 'tcx> {
104     pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
105         let tcx = infcx.tcx;
106         let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
107         Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness_for_typeck())
108     }
109
110     pub(super) fn with_constness(
111         infcx: InferCtxt<'a, 'tcx>,
112         def_id: LocalDefId,
113         constness: hir::Constness,
114     ) -> Self {
115         let tcx = infcx.tcx;
116         let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
117         let body_id = tcx.hir().maybe_body_owned_by(item_id);
118
119         Inherited {
120             typeck_results: MaybeInProgressTables {
121                 maybe_typeck_results: infcx.in_progress_typeck_results,
122             },
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_generator_interiors: RefCell::new(Vec::new()),
130             diverging_type_vars: RefCell::new(Default::default()),
131             constness,
132             body_id,
133         }
134     }
135
136     pub(super) fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
137         debug!("register_predicate({:?})", obligation);
138         if obligation.has_escaping_bound_vars() {
139             span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
140         }
141         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
142     }
143
144     pub(super) fn register_predicates<I>(&self, obligations: I)
145     where
146         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
147     {
148         for obligation in obligations {
149             self.register_predicate(obligation);
150         }
151     }
152
153     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
154         self.register_predicates(infer_ok.obligations);
155         infer_ok.value
156     }
157
158     pub(super) fn normalize_associated_types_in<T>(
159         &self,
160         span: Span,
161         body_id: hir::HirId,
162         param_env: ty::ParamEnv<'tcx>,
163         value: T,
164     ) -> T
165     where
166         T: TypeFoldable<'tcx>,
167     {
168         self.normalize_associated_types_in_with_cause(
169             ObligationCause::misc(span, body_id),
170             param_env,
171             value,
172         )
173     }
174
175     pub(super) fn normalize_associated_types_in_with_cause<T>(
176         &self,
177         cause: ObligationCause<'tcx>,
178         param_env: ty::ParamEnv<'tcx>,
179         value: T,
180     ) -> T
181     where
182         T: TypeFoldable<'tcx>,
183     {
184         let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
185         debug!(?ok);
186         self.register_infer_ok_obligations(ok)
187     }
188 }