]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_traits/src/type_op.rs
Rollup merge of #91804 - woppopo:const_clone, r=oli-obk
[rust.git] / compiler / rustc_traits / src / type_op.rs
1 use rustc_hir as hir;
2 use rustc_hir::def_id::DefId;
3 use rustc_infer::infer::at::ToTrace;
4 use rustc_infer::infer::canonical::{Canonical, QueryResponse};
5 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
6 use rustc_infer::traits::TraitEngineExt as _;
7 use rustc_middle::ty::query::Providers;
8 use rustc_middle::ty::subst::{GenericArg, Subst, UserSelfTy, UserSubsts};
9 use rustc_middle::ty::{self, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable, Variance};
10 use rustc_middle::ty::{ParamEnv, ParamEnvAnd, Predicate, ToPredicate};
11 use rustc_span::{Span, DUMMY_SP};
12 use rustc_trait_selection::infer::InferCtxtBuilderExt;
13 use rustc_trait_selection::infer::InferCtxtExt;
14 use rustc_trait_selection::traits::query::normalize::AtExt;
15 use rustc_trait_selection::traits::query::type_op::ascribe_user_type::AscribeUserType;
16 use rustc_trait_selection::traits::query::type_op::eq::Eq;
17 use rustc_trait_selection::traits::query::type_op::normalize::Normalize;
18 use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate;
19 use rustc_trait_selection::traits::query::type_op::subtype::Subtype;
20 use rustc_trait_selection::traits::query::{Fallible, NoSolution};
21 use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, TraitEngine};
22 use std::fmt;
23
24 crate fn provide(p: &mut Providers) {
25     *p = Providers {
26         type_op_ascribe_user_type,
27         type_op_eq,
28         type_op_prove_predicate,
29         type_op_subtype,
30         type_op_normalize_ty,
31         type_op_normalize_predicate,
32         type_op_normalize_fn_sig,
33         type_op_normalize_poly_fn_sig,
34         ..*p
35     };
36 }
37
38 fn type_op_ascribe_user_type<'tcx>(
39     tcx: TyCtxt<'tcx>,
40     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, AscribeUserType<'tcx>>>,
41 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
42     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
43         type_op_ascribe_user_type_with_span(infcx, fulfill_cx, key, None)
44     })
45 }
46
47 /// The core of the `type_op_ascribe_user_type` query: for diagnostics purposes in NLL HRTB errors,
48 /// this query can be re-run to better track the span of the obligation cause, and improve the error
49 /// message. Do not call directly unless you're in that very specific context.
50 pub fn type_op_ascribe_user_type_with_span<'a, 'tcx: 'a>(
51     infcx: &'a InferCtxt<'a, 'tcx>,
52     fulfill_cx: &'a mut dyn TraitEngine<'tcx>,
53     key: ParamEnvAnd<'tcx, AscribeUserType<'tcx>>,
54     span: Option<Span>,
55 ) -> Result<(), NoSolution> {
56     let (param_env, AscribeUserType { mir_ty, def_id, user_substs }) = key.into_parts();
57     debug!(
58         "type_op_ascribe_user_type: mir_ty={:?} def_id={:?} user_substs={:?}",
59         mir_ty, def_id, user_substs
60     );
61
62     let mut cx = AscribeUserTypeCx { infcx, param_env, fulfill_cx };
63     cx.relate_mir_and_user_ty(mir_ty, def_id, user_substs, span)?;
64     Ok(())
65 }
66
67 struct AscribeUserTypeCx<'me, 'tcx> {
68     infcx: &'me InferCtxt<'me, 'tcx>,
69     param_env: ParamEnv<'tcx>,
70     fulfill_cx: &'me mut dyn TraitEngine<'tcx>,
71 }
72
73 impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
74     fn normalize<T>(&mut self, value: T) -> T
75     where
76         T: TypeFoldable<'tcx>,
77     {
78         self.infcx
79             .partially_normalize_associated_types_in(
80                 ObligationCause::misc(DUMMY_SP, hir::CRATE_HIR_ID),
81                 self.param_env,
82                 value,
83             )
84             .into_value_registering_obligations(self.infcx, self.fulfill_cx)
85     }
86
87     fn relate<T>(&mut self, a: T, variance: Variance, b: T) -> Result<(), NoSolution>
88     where
89         T: ToTrace<'tcx>,
90     {
91         self.infcx
92             .at(&ObligationCause::dummy(), self.param_env)
93             .relate(a, variance, b)?
94             .into_value_registering_obligations(self.infcx, self.fulfill_cx);
95         Ok(())
96     }
97
98     fn prove_predicate(&mut self, predicate: Predicate<'tcx>, span: Option<Span>) {
99         let cause = if let Some(span) = span {
100             ObligationCause::dummy_with_span(span)
101         } else {
102             ObligationCause::dummy()
103         };
104         self.fulfill_cx.register_predicate_obligation(
105             self.infcx,
106             Obligation::new(cause, self.param_env, predicate),
107         );
108     }
109
110     fn tcx(&self) -> TyCtxt<'tcx> {
111         self.infcx.tcx
112     }
113
114     fn subst<T>(&self, value: T, substs: &[GenericArg<'tcx>]) -> T
115     where
116         T: TypeFoldable<'tcx>,
117     {
118         value.subst(self.tcx(), substs)
119     }
120
121     fn relate_mir_and_user_ty(
122         &mut self,
123         mir_ty: Ty<'tcx>,
124         def_id: DefId,
125         user_substs: UserSubsts<'tcx>,
126         span: Option<Span>,
127     ) -> Result<(), NoSolution> {
128         let UserSubsts { user_self_ty, substs } = user_substs;
129         let tcx = self.tcx();
130
131         let ty = tcx.type_of(def_id);
132         let ty = self.subst(ty, substs);
133         debug!("relate_type_and_user_type: ty of def-id is {:?}", ty);
134         let ty = self.normalize(ty);
135
136         self.relate(mir_ty, Variance::Invariant, ty)?;
137
138         // Prove the predicates coming along with `def_id`.
139         //
140         // Also, normalize the `instantiated_predicates`
141         // because otherwise we wind up with duplicate "type
142         // outlives" error messages.
143         let instantiated_predicates =
144             self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
145         debug!(?instantiated_predicates.predicates);
146         for instantiated_predicate in instantiated_predicates.predicates {
147             let instantiated_predicate = self.normalize(instantiated_predicate);
148             self.prove_predicate(instantiated_predicate, span);
149         }
150
151         if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
152             let impl_self_ty = self.tcx().type_of(impl_def_id);
153             let impl_self_ty = self.subst(impl_self_ty, &substs);
154             let impl_self_ty = self.normalize(impl_self_ty);
155
156             self.relate(self_ty, Variance::Invariant, impl_self_ty)?;
157
158             self.prove_predicate(
159                 ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into()))
160                     .to_predicate(self.tcx()),
161                 span,
162             );
163         }
164
165         // In addition to proving the predicates, we have to
166         // prove that `ty` is well-formed -- this is because
167         // the WF of `ty` is predicated on the substs being
168         // well-formed, and we haven't proven *that*. We don't
169         // want to prove the WF of types from  `substs` directly because they
170         // haven't been normalized.
171         //
172         // FIXME(nmatsakis): Well, perhaps we should normalize
173         // them?  This would only be relevant if some input
174         // type were ill-formed but did not appear in `ty`,
175         // which...could happen with normalization...
176         self.prove_predicate(
177             ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())).to_predicate(self.tcx()),
178             span,
179         );
180         Ok(())
181     }
182 }
183
184 fn type_op_eq<'tcx>(
185     tcx: TyCtxt<'tcx>,
186     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Eq<'tcx>>>,
187 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
188     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
189         let (param_env, Eq { a, b }) = key.into_parts();
190         infcx
191             .at(&ObligationCause::dummy(), param_env)
192             .eq(a, b)?
193             .into_value_registering_obligations(infcx, fulfill_cx);
194         Ok(())
195     })
196 }
197
198 fn type_op_normalize<'tcx, T>(
199     infcx: &InferCtxt<'_, 'tcx>,
200     fulfill_cx: &mut dyn TraitEngine<'tcx>,
201     key: ParamEnvAnd<'tcx, Normalize<T>>,
202 ) -> Fallible<T>
203 where
204     T: fmt::Debug + TypeFoldable<'tcx> + Lift<'tcx>,
205 {
206     let (param_env, Normalize { value }) = key.into_parts();
207     let Normalized { value, obligations } =
208         infcx.at(&ObligationCause::dummy(), param_env).normalize(value)?;
209     fulfill_cx.register_predicate_obligations(infcx, obligations);
210     Ok(value)
211 }
212
213 fn type_op_normalize_ty<'tcx>(
214     tcx: TyCtxt<'tcx>,
215     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<Ty<'tcx>>>>,
216 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, NoSolution> {
217     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
218 }
219
220 fn type_op_normalize_predicate<'tcx>(
221     tcx: TyCtxt<'tcx>,
222     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<Predicate<'tcx>>>>,
223 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, Predicate<'tcx>>>, NoSolution> {
224     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
225 }
226
227 fn type_op_normalize_fn_sig<'tcx>(
228     tcx: TyCtxt<'tcx>,
229     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<FnSig<'tcx>>>>,
230 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, FnSig<'tcx>>>, NoSolution> {
231     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
232 }
233
234 fn type_op_normalize_poly_fn_sig<'tcx>(
235     tcx: TyCtxt<'tcx>,
236     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<PolyFnSig<'tcx>>>>,
237 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, PolyFnSig<'tcx>>>, NoSolution> {
238     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
239 }
240
241 fn type_op_subtype<'tcx>(
242     tcx: TyCtxt<'tcx>,
243     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Subtype<'tcx>>>,
244 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
245     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
246         let (param_env, Subtype { sub, sup }) = key.into_parts();
247         infcx
248             .at(&ObligationCause::dummy(), param_env)
249             .sup(sup, sub)?
250             .into_value_registering_obligations(infcx, fulfill_cx);
251         Ok(())
252     })
253 }
254
255 fn type_op_prove_predicate<'tcx>(
256     tcx: TyCtxt<'tcx>,
257     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, ProvePredicate<'tcx>>>,
258 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
259     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
260         type_op_prove_predicate_with_cause(infcx, fulfill_cx, key, ObligationCause::dummy());
261         Ok(())
262     })
263 }
264
265 /// The core of the `type_op_prove_predicate` query: for diagnostics purposes in NLL HRTB errors,
266 /// this query can be re-run to better track the span of the obligation cause, and improve the error
267 /// message. Do not call directly unless you're in that very specific context.
268 pub fn type_op_prove_predicate_with_cause<'a, 'tcx: 'a>(
269     infcx: &'a InferCtxt<'a, 'tcx>,
270     fulfill_cx: &'a mut dyn TraitEngine<'tcx>,
271     key: ParamEnvAnd<'tcx, ProvePredicate<'tcx>>,
272     cause: ObligationCause<'tcx>,
273 ) {
274     let (param_env, ProvePredicate { predicate }) = key.into_parts();
275     fulfill_cx.register_predicate_obligation(infcx, Obligation::new(cause, param_env, predicate));
276 }