]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/infer.rs
Check that type_implements_trait actually is passed the right amount of generic params
[rust.git] / compiler / rustc_trait_selection / src / infer.rs
1 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
2 use crate::traits::{self, ObligationCtxt};
3
4 use rustc_hir::def_id::DefId;
5 use rustc_hir::lang_items::LangItem;
6 use rustc_infer::traits::ObligationCause;
7 use rustc_middle::arena::ArenaAllocatable;
8 use rustc_middle::infer::canonical::{Canonical, CanonicalizedQueryResponse, QueryResponse};
9 use rustc_middle::traits::query::Fallible;
10 use rustc_middle::ty::subst::SubstsRef;
11 use rustc_middle::ty::ToPredicate;
12 use rustc_middle::ty::{self, Ty, TypeFoldable, TypeVisitable};
13 use rustc_span::{Span, DUMMY_SP};
14
15 use std::fmt::Debug;
16
17 pub use rustc_infer::infer::*;
18
19 pub trait InferCtxtExt<'tcx> {
20     fn type_is_copy_modulo_regions(
21         &self,
22         param_env: ty::ParamEnv<'tcx>,
23         ty: Ty<'tcx>,
24         span: Span,
25     ) -> bool;
26
27     fn type_is_sized_modulo_regions(
28         &self,
29         param_env: ty::ParamEnv<'tcx>,
30         ty: Ty<'tcx>,
31         span: Span,
32     ) -> bool;
33
34     fn partially_normalize_associated_types_in<T>(
35         &self,
36         cause: ObligationCause<'tcx>,
37         param_env: ty::ParamEnv<'tcx>,
38         value: T,
39     ) -> InferOk<'tcx, T>
40     where
41         T: TypeFoldable<'tcx>;
42
43     /// Check whether a `ty` implements given trait(trait_def_id).
44     /// The inputs are:
45     ///
46     /// - the def-id of the trait
47     /// - the self type
48     /// - the *other* type parameters of the trait, excluding the self-type
49     /// - the parameter environment
50     ///
51     /// Invokes `evaluate_obligation`, so in the event that evaluating
52     /// `Ty: Trait` causes overflow, EvaluatedToRecur (or EvaluatedToUnknown)
53     /// will be returned.
54     fn type_implements_trait(
55         &self,
56         trait_def_id: DefId,
57         ty: Ty<'tcx>,
58         params: SubstsRef<'tcx>,
59         param_env: ty::ParamEnv<'tcx>,
60     ) -> traits::EvaluationResult;
61 }
62 impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
63     fn type_is_copy_modulo_regions(
64         &self,
65         param_env: ty::ParamEnv<'tcx>,
66         ty: Ty<'tcx>,
67         span: Span,
68     ) -> bool {
69         let ty = self.resolve_vars_if_possible(ty);
70
71         if !(param_env, ty).needs_infer() {
72             return ty.is_copy_modulo_regions(self.tcx, param_env);
73         }
74
75         let copy_def_id = self.tcx.require_lang_item(LangItem::Copy, None);
76
77         // This can get called from typeck (by euv), and `moves_by_default`
78         // rightly refuses to work with inference variables, but
79         // moves_by_default has a cache, which we want to use in other
80         // cases.
81         traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
82     }
83
84     fn type_is_sized_modulo_regions(
85         &self,
86         param_env: ty::ParamEnv<'tcx>,
87         ty: Ty<'tcx>,
88         span: Span,
89     ) -> bool {
90         let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
91         traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, lang_item, span)
92     }
93
94     /// Normalizes associated types in `value`, potentially returning
95     /// new obligations that must further be processed.
96     #[instrument(level = "debug", skip(self, cause, param_env), ret)]
97     fn partially_normalize_associated_types_in<T>(
98         &self,
99         cause: ObligationCause<'tcx>,
100         param_env: ty::ParamEnv<'tcx>,
101         value: T,
102     ) -> InferOk<'tcx, T>
103     where
104         T: TypeFoldable<'tcx>,
105     {
106         let mut selcx = traits::SelectionContext::new(self);
107         let traits::Normalized { value, obligations } =
108             traits::normalize(&mut selcx, param_env, cause, value);
109         InferOk { value, obligations }
110     }
111
112     #[instrument(level = "debug", skip(self), ret)]
113     fn type_implements_trait(
114         &self,
115         trait_def_id: DefId,
116         self_ty: Ty<'tcx>,
117         params: SubstsRef<'tcx>,
118         param_env: ty::ParamEnv<'tcx>,
119     ) -> traits::EvaluationResult {
120         let trait_ref = ty::TraitRef {
121             def_id: trait_def_id,
122             substs: self.tcx.mk_substs_trait(self_ty, params),
123         };
124
125         debug_assert_eq!(
126             self.tcx.generics_of(trait_def_id).count() - 1,
127             params.len(),
128             "wrong number of generic parameters for {trait_def_id:?}, did you accidentally include the self-type in the params list?"
129         );
130
131         let obligation = traits::Obligation {
132             cause: traits::ObligationCause::dummy(),
133             param_env,
134             recursion_depth: 0,
135             predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(self.tcx),
136         };
137         self.evaluate_obligation(&obligation).unwrap_or(traits::EvaluationResult::EvaluatedToErr)
138     }
139 }
140
141 pub trait InferCtxtBuilderExt<'tcx> {
142     fn enter_canonical_trait_query<K, R>(
143         &mut self,
144         canonical_key: &Canonical<'tcx, K>,
145         operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Fallible<R>,
146     ) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
147     where
148         K: TypeFoldable<'tcx>,
149         R: Debug + TypeFoldable<'tcx>,
150         Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>;
151 }
152
153 impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> {
154     /// The "main method" for a canonicalized trait query. Given the
155     /// canonical key `canonical_key`, this method will create a new
156     /// inference context, instantiate the key, and run your operation
157     /// `op`. The operation should yield up a result (of type `R`) as
158     /// well as a set of trait obligations that must be fully
159     /// satisfied. These obligations will be processed and the
160     /// canonical result created.
161     ///
162     /// Returns `NoSolution` in the event of any error.
163     ///
164     /// (It might be mildly nicer to implement this on `TyCtxt`, and
165     /// not `InferCtxtBuilder`, but that is a bit tricky right now.
166     /// In part because we would need a `for<'tcx>` sort of
167     /// bound for the closure and in part because it is convenient to
168     /// have `'tcx` be free on this function so that we can talk about
169     /// `K: TypeFoldable<'tcx>`.)
170     fn enter_canonical_trait_query<K, R>(
171         &mut self,
172         canonical_key: &Canonical<'tcx, K>,
173         operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Fallible<R>,
174     ) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
175     where
176         K: TypeFoldable<'tcx>,
177         R: Debug + TypeFoldable<'tcx>,
178         Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>,
179     {
180         let (infcx, key, canonical_inference_vars) =
181             self.build_with_canonical(DUMMY_SP, canonical_key);
182         let ocx = ObligationCtxt::new(&infcx);
183         let value = operation(&ocx, key)?;
184         ocx.make_canonicalized_query_response(canonical_inference_vars, value)
185     }
186 }