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