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