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