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