]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_traits/src/type_op.rs
(almost) Always use ObligationCtxt when dealing with canonical queries
[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.register_infer_ok_obligations(
91             self.ocx
92                 .infcx
93                 .at(&ObligationCause::dummy_with_span(self.span), self.param_env)
94                 .eq(a, b)?,
95         ))
96     }
97
98     fn prove_predicate(&self, predicate: Predicate<'tcx>, cause: ObligationCause<'tcx>) {
99         self.ocx.register_obligation(Obligation::new(cause, self.param_env, predicate));
100     }
101
102     fn tcx(&self) -> TyCtxt<'tcx> {
103         self.ocx.infcx.tcx
104     }
105
106     #[instrument(level = "debug", skip(self))]
107     fn relate_mir_and_user_ty(
108         &self,
109         mir_ty: Ty<'tcx>,
110         def_id: DefId,
111         user_substs: UserSubsts<'tcx>,
112     ) -> Result<(), NoSolution> {
113         let UserSubsts { user_self_ty, substs } = user_substs;
114         let tcx = self.tcx();
115
116         let ty = tcx.bound_type_of(def_id).subst(tcx, substs);
117         let ty = self.normalize(ty);
118         debug!("relate_type_and_user_type: ty of def-id is {:?}", ty);
119
120         self.eq(mir_ty, ty)?;
121
122         // Prove the predicates coming along with `def_id`.
123         //
124         // Also, normalize the `instantiated_predicates`
125         // because otherwise we wind up with duplicate "type
126         // outlives" error messages.
127         let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
128
129         let cause = ObligationCause::dummy_with_span(self.span);
130
131         debug!(?instantiated_predicates);
132         for (instantiated_predicate, predicate_span) in
133             zip(instantiated_predicates.predicates, instantiated_predicates.spans)
134         {
135             let span = if self.span == DUMMY_SP { predicate_span } else { self.span };
136             let cause = ObligationCause::new(
137                 span,
138                 hir::CRATE_HIR_ID,
139                 ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span),
140             );
141             let instantiated_predicate =
142                 self.normalize_with_cause(instantiated_predicate, cause.clone());
143             self.prove_predicate(instantiated_predicate, cause);
144         }
145
146         if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
147             let impl_self_ty = tcx.bound_type_of(impl_def_id).subst(tcx, substs);
148             let impl_self_ty = self.normalize(impl_self_ty);
149
150             self.eq(self_ty, impl_self_ty)?;
151
152             self.prove_predicate(
153                 ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into()))
154                     .to_predicate(tcx),
155                 cause.clone(),
156             );
157         }
158
159         // In addition to proving the predicates, we have to
160         // prove that `ty` is well-formed -- this is because
161         // the WF of `ty` is predicated on the substs being
162         // well-formed, and we haven't proven *that*. We don't
163         // want to prove the WF of types from  `substs` directly because they
164         // haven't been normalized.
165         //
166         // FIXME(nmatsakis): Well, perhaps we should normalize
167         // them?  This would only be relevant if some input
168         // type were ill-formed but did not appear in `ty`,
169         // which...could happen with normalization...
170         self.prove_predicate(
171             ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())).to_predicate(tcx),
172             cause,
173         );
174         Ok(())
175     }
176 }
177
178 fn type_op_eq<'tcx>(
179     tcx: TyCtxt<'tcx>,
180     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Eq<'tcx>>>,
181 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
182     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |ocx, key| {
183         let (param_env, Eq { a, b }) = key.into_parts();
184         ocx.register_infer_ok_obligations(
185             ocx.infcx.at(&ObligationCause::dummy(), param_env).eq(a, b)?,
186         );
187         Ok(())
188     })
189 }
190
191 fn type_op_normalize<'tcx, T>(
192     ocx: &ObligationCtxt<'_, 'tcx>,
193     key: ParamEnvAnd<'tcx, Normalize<T>>,
194 ) -> Fallible<T>
195 where
196     T: fmt::Debug + TypeFoldable<'tcx> + Lift<'tcx>,
197 {
198     let (param_env, Normalize { value }) = key.into_parts();
199     let Normalized { value, obligations } =
200         ocx.infcx.at(&ObligationCause::dummy(), param_env).normalize(value)?;
201     ocx.register_obligations(obligations);
202     Ok(value)
203 }
204
205 fn type_op_normalize_ty<'tcx>(
206     tcx: TyCtxt<'tcx>,
207     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<Ty<'tcx>>>>,
208 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, NoSolution> {
209     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
210 }
211
212 fn type_op_normalize_predicate<'tcx>(
213     tcx: TyCtxt<'tcx>,
214     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<Predicate<'tcx>>>>,
215 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, Predicate<'tcx>>>, NoSolution> {
216     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
217 }
218
219 fn type_op_normalize_fn_sig<'tcx>(
220     tcx: TyCtxt<'tcx>,
221     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<FnSig<'tcx>>>>,
222 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, FnSig<'tcx>>>, NoSolution> {
223     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
224 }
225
226 fn type_op_normalize_poly_fn_sig<'tcx>(
227     tcx: TyCtxt<'tcx>,
228     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<PolyFnSig<'tcx>>>>,
229 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, PolyFnSig<'tcx>>>, NoSolution> {
230     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
231 }
232
233 fn type_op_subtype<'tcx>(
234     tcx: TyCtxt<'tcx>,
235     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Subtype<'tcx>>>,
236 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
237     tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |ocx, key| {
238         let (param_env, Subtype { sub, sup }) = key.into_parts();
239         ocx.register_infer_ok_obligations(
240             ocx.infcx.at(&ObligationCause::dummy(), param_env).sup(sup, sub)?,
241         );
242         Ok(())
243     })
244 }
245
246 fn type_op_prove_predicate<'tcx>(
247     tcx: TyCtxt<'tcx>,
248     canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, ProvePredicate<'tcx>>>,
249 ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
250     // HACK This bubble is required for this test to pass:
251     // impl-trait/issue-99642.rs
252     tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bubble).enter_canonical_trait_query(
253         &canonicalized,
254         |ocx, key| {
255             type_op_prove_predicate_with_cause(ocx, key, ObligationCause::dummy());
256             Ok(())
257         },
258     )
259 }
260
261 /// The core of the `type_op_prove_predicate` query: for diagnostics purposes in NLL HRTB errors,
262 /// this query can be re-run to better track the span of the obligation cause, and improve the error
263 /// message. Do not call directly unless you're in that very specific context.
264 pub fn type_op_prove_predicate_with_cause<'tcx>(
265     ocx: &ObligationCtxt<'_, 'tcx>,
266     key: ParamEnvAnd<'tcx, ProvePredicate<'tcx>>,
267     cause: ObligationCause<'tcx>,
268 ) {
269     let (param_env, ProvePredicate { predicate }) = key.into_parts();
270     ocx.register_obligation(Obligation::new(cause, param_env, predicate));
271 }