]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/inherited.rs
Inherited use constness and assoc change predicate
[rust.git] / compiler / rustc_typeck / src / check / inherited.rs
1 use super::callee::DeferredCallResolution;
2 use super::MaybeInProgressTables;
3
4 use rustc_hir as hir;
5 use rustc_hir::def_id::{DefIdMap, LocalDefId};
6 use rustc_hir::HirIdMap;
7 use rustc_infer::infer;
8 use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
9 use rustc_middle::ty::fold::TypeFoldable;
10 use rustc_middle::ty::{self, Ty, TyCtxt};
11 use rustc_span::{self, Span};
12 use rustc_trait_selection::infer::InferCtxtExt as _;
13 use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};
14
15 use std::cell::RefCell;
16 use std::ops::Deref;
17
18 /// Closures defined within the function. For example:
19 ///
20 ///     fn foo() {
21 ///         bar(move|| { ... })
22 ///     }
23 ///
24 /// Here, the function `foo()` and the closure passed to
25 /// `bar()` will each have their own `FnCtxt`, but they will
26 /// share the inherited fields.
27 pub struct Inherited<'a, 'tcx> {
28     pub(super) infcx: InferCtxt<'a, 'tcx>,
29
30     pub(super) typeck_results: super::MaybeInProgressTables<'a, 'tcx>,
31
32     pub(super) locals: RefCell<HirIdMap<super::LocalTy<'tcx>>>,
33
34     pub(super) fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>,
35
36     // Some additional `Sized` obligations badly affect type inference.
37     // These obligations are added in a later stage of typeck.
38     pub(super) deferred_sized_obligations:
39         RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'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<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>,
49
50     pub(super) deferred_cast_checks: RefCell<Vec<super::cast::CastCheck<'tcx>>>,
51
52     pub(super) deferred_generator_interiors:
53         RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,
54
55     /// Reports whether this is in a const context.
56     pub(super) constness: hir::Constness,
57
58     pub(super) body_id: Option<hir::BodyId>,
59 }
60
61 impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> {
62     type Target = InferCtxt<'a, 'tcx>;
63     fn deref(&self) -> &Self::Target {
64         &self.infcx
65     }
66 }
67
68 /// Helper type of a temporary returned by `Inherited::build(...)`.
69 /// Necessary because we can't write the following bound:
70 /// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`.
71 pub struct InheritedBuilder<'tcx> {
72     infcx: infer::InferCtxtBuilder<'tcx>,
73     def_id: LocalDefId,
74 }
75
76 impl Inherited<'_, 'tcx> {
77     pub fn build(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> InheritedBuilder<'tcx> {
78         let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner;
79
80         InheritedBuilder {
81             infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner),
82             def_id,
83         }
84     }
85 }
86
87 impl<'tcx> InheritedBuilder<'tcx> {
88     pub fn enter<F, R>(&mut self, f: F) -> R
89     where
90         F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R,
91     {
92         let def_id = self.def_id;
93         self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
94     }
95 }
96
97 impl Inherited<'a, 'tcx> {
98     pub(super) fn new(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
99         let tcx = infcx.tcx;
100         let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
101         Self::with_constness(infcx, def_id, tcx.hir().get(item_id).constness())
102     }
103
104     pub(super) fn with_constness(infcx: InferCtxt<'a, 'tcx>, def_id: LocalDefId, constness: hir::Constness) -> Self {
105         let tcx = infcx.tcx;
106         let item_id = tcx.hir().local_def_id_to_hir_id(def_id);
107         let body_id = tcx.hir().maybe_body_owned_by(item_id);
108
109         Inherited {
110             typeck_results: MaybeInProgressTables {
111                 maybe_typeck_results: infcx.in_progress_typeck_results,
112             },
113             infcx,
114             fulfillment_cx: RefCell::new(<dyn TraitEngine<'_>>::new(tcx)),
115             locals: RefCell::new(Default::default()),
116             deferred_sized_obligations: RefCell::new(Vec::new()),
117             deferred_call_resolutions: RefCell::new(Default::default()),
118             deferred_cast_checks: RefCell::new(Vec::new()),
119             deferred_generator_interiors: RefCell::new(Vec::new()),
120             constness,
121             body_id,
122         }
123     }
124
125     #[instrument(level = "debug", skip(self))]
126     fn transform_predicate(&self, p: &mut ty::Predicate<'tcx>) {
127         // Don't transform non-const bounds into const bounds,
128         // but transform const bounds to non-const when we are
129         // not in a const context.
130         if let hir::Constness::NotConst = self.constness {
131             let kind = p.kind();
132             if let ty::PredicateKind::Trait(pred) = kind.as_ref().skip_binder() {
133                 let mut pred = *pred;
134                 pred.constness = hir::Constness::NotConst;
135                 *p = kind.rebind(ty::PredicateKind::Trait(pred)).to_predicate(self.tcx);
136             }
137         }
138     }
139
140     pub(super) fn register_predicate(&self, mut obligation: traits::PredicateObligation<'tcx>) {
141         debug!("register_predicate({:?})", obligation);
142         self.transform_predicate(&mut obligation.predicate);
143         if obligation.has_escaping_bound_vars() {
144             span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation);
145         }
146         self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation);
147     }
148
149     pub(super) fn register_predicates<I>(&self, obligations: I)
150     where
151         I: IntoIterator<Item = traits::PredicateObligation<'tcx>>,
152     {
153         for obligation in obligations {
154             self.register_predicate(obligation);
155         }
156     }
157
158     pub(super) fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
159         self.register_predicates(infer_ok.obligations);
160         infer_ok.value
161     }
162
163     pub(super) fn normalize_associated_types_in<T>(
164         &self,
165         span: Span,
166         body_id: hir::HirId,
167         param_env: ty::ParamEnv<'tcx>,
168         value: T,
169     ) -> T
170     where
171         T: TypeFoldable<'tcx>,
172     {
173         self.normalize_associated_types_in_with_cause(
174             ObligationCause::misc(span, body_id),
175             param_env,
176             value,
177         )
178     }
179
180     pub(super) fn normalize_associated_types_in_with_cause<T>(
181         &self,
182         cause: ObligationCause<'tcx>,
183         param_env: ty::ParamEnv<'tcx>,
184         value: T,
185     ) -> T
186     where
187         T: TypeFoldable<'tcx>,
188     {
189         let ok = self.partially_normalize_associated_types_in(cause, param_env, value);
190         debug!(?ok);
191         self.register_infer_ok_obligations(ok)
192     }
193 }