]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/infer.rs
Auto merge of #86901 - sexxi-goose:query_remove, r=nikomatsakis
[rust.git] / compiler / rustc_trait_selection / src / infer.rs
1 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
2 use crate::traits::query::outlives_bounds::InferCtxtExt as _;
3 use crate::traits::{self, TraitEngine, TraitEngineExt};
4
5 use rustc_hir as hir;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::lang_items::LangItem;
8 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
9 use rustc_infer::traits::ObligationCause;
10 use rustc_middle::arena::ArenaAllocatable;
11 use rustc_middle::infer::canonical::{Canonical, CanonicalizedQueryResponse, QueryResponse};
12 use rustc_middle::traits::query::Fallible;
13 use rustc_middle::ty::subst::SubstsRef;
14 use rustc_middle::ty::ToPredicate;
15 use rustc_middle::ty::WithConstness;
16 use rustc_middle::ty::{self, Ty, TypeFoldable};
17 use rustc_span::{Span, DUMMY_SP};
18
19 use std::fmt::Debug;
20
21 pub use rustc_infer::infer::*;
22
23 pub trait InferCtxtExt<'tcx> {
24     fn type_is_copy_modulo_regions(
25         &self,
26         param_env: ty::ParamEnv<'tcx>,
27         ty: Ty<'tcx>,
28         span: Span,
29     ) -> bool;
30
31     fn partially_normalize_associated_types_in<T>(
32         &self,
33         span: Span,
34         body_id: hir::HirId,
35         param_env: ty::ParamEnv<'tcx>,
36         value: T,
37     ) -> InferOk<'tcx, T>
38     where
39         T: TypeFoldable<'tcx>;
40
41     /// Check whether a `ty` implements given trait(trait_def_id).
42     /// The inputs are:
43     ///
44     /// - the def-id of the trait
45     /// - the self type
46     /// - the *other* type parameters of the trait, excluding the self-type
47     /// - the parameter environment
48     fn type_implements_trait(
49         &self,
50         trait_def_id: DefId,
51         ty: Ty<'tcx>,
52         params: SubstsRef<'tcx>,
53         param_env: ty::ParamEnv<'tcx>,
54     ) -> traits::EvaluationResult;
55 }
56 impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> {
57     fn type_is_copy_modulo_regions(
58         &self,
59         param_env: ty::ParamEnv<'tcx>,
60         ty: Ty<'tcx>,
61         span: Span,
62     ) -> bool {
63         let ty = self.resolve_vars_if_possible(ty);
64
65         if !(param_env, ty).needs_infer() {
66             return ty.is_copy_modulo_regions(self.tcx.at(span), param_env);
67         }
68
69         let copy_def_id = self.tcx.require_lang_item(LangItem::Copy, None);
70
71         // This can get called from typeck (by euv), and `moves_by_default`
72         // rightly refuses to work with inference variables, but
73         // moves_by_default has a cache, which we want to use in other
74         // cases.
75         traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
76     }
77
78     /// Normalizes associated types in `value`, potentially returning
79     /// new obligations that must further be processed.
80     fn partially_normalize_associated_types_in<T>(
81         &self,
82         span: Span,
83         body_id: hir::HirId,
84         param_env: ty::ParamEnv<'tcx>,
85         value: T,
86     ) -> InferOk<'tcx, T>
87     where
88         T: TypeFoldable<'tcx>,
89     {
90         debug!("partially_normalize_associated_types_in(value={:?})", value);
91         let mut selcx = traits::SelectionContext::new(self);
92         let cause = ObligationCause::misc(span, body_id);
93         let traits::Normalized { value, obligations } =
94             traits::normalize(&mut selcx, param_env, cause, value);
95         debug!(
96             "partially_normalize_associated_types_in: result={:?} predicates={:?}",
97             value, obligations
98         );
99         InferOk { value, obligations }
100     }
101
102     fn type_implements_trait(
103         &self,
104         trait_def_id: DefId,
105         ty: Ty<'tcx>,
106         params: SubstsRef<'tcx>,
107         param_env: ty::ParamEnv<'tcx>,
108     ) -> traits::EvaluationResult {
109         debug!(
110             "type_implements_trait: trait_def_id={:?}, type={:?}, params={:?}, param_env={:?}",
111             trait_def_id, ty, params, param_env
112         );
113
114         let trait_ref =
115             ty::TraitRef { def_id: trait_def_id, substs: self.tcx.mk_substs_trait(ty, params) };
116
117         let obligation = traits::Obligation {
118             cause: traits::ObligationCause::dummy(),
119             param_env,
120             recursion_depth: 0,
121             predicate: trait_ref.without_const().to_predicate(self.tcx),
122         };
123         self.evaluate_obligation_no_overflow(&obligation)
124     }
125 }
126
127 pub trait InferCtxtBuilderExt<'tcx> {
128     fn enter_canonical_trait_query<K, R>(
129         &mut self,
130         canonical_key: &Canonical<'tcx, K>,
131         operation: impl FnOnce(&InferCtxt<'_, 'tcx>, &mut dyn TraitEngine<'tcx>, K) -> Fallible<R>,
132     ) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
133     where
134         K: TypeFoldable<'tcx>,
135         R: Debug + TypeFoldable<'tcx>,
136         Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>;
137 }
138
139 impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> {
140     /// The "main method" for a canonicalized trait query. Given the
141     /// canonical key `canonical_key`, this method will create a new
142     /// inference context, instantiate the key, and run your operation
143     /// `op`. The operation should yield up a result (of type `R`) as
144     /// well as a set of trait obligations that must be fully
145     /// satisfied. These obligations will be processed and the
146     /// canonical result created.
147     ///
148     /// Returns `NoSolution` in the event of any error.
149     ///
150     /// (It might be mildly nicer to implement this on `TyCtxt`, and
151     /// not `InferCtxtBuilder`, but that is a bit tricky right now.
152     /// In part because we would need a `for<'tcx>` sort of
153     /// bound for the closure and in part because it is convenient to
154     /// have `'tcx` be free on this function so that we can talk about
155     /// `K: TypeFoldable<'tcx>`.)
156     fn enter_canonical_trait_query<K, R>(
157         &mut self,
158         canonical_key: &Canonical<'tcx, K>,
159         operation: impl FnOnce(&InferCtxt<'_, 'tcx>, &mut dyn TraitEngine<'tcx>, K) -> Fallible<R>,
160     ) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
161     where
162         K: TypeFoldable<'tcx>,
163         R: Debug + TypeFoldable<'tcx>,
164         Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>,
165     {
166         self.enter_with_canonical(
167             DUMMY_SP,
168             canonical_key,
169             |ref infcx, key, canonical_inference_vars| {
170                 let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
171                 let value = operation(infcx, &mut *fulfill_cx, key)?;
172                 infcx.make_canonicalized_query_response(
173                     canonical_inference_vars,
174                     value,
175                     &mut *fulfill_cx,
176                 )
177             },
178         )
179     }
180 }
181
182 pub trait OutlivesEnvironmentExt<'tcx> {
183     fn add_implied_bounds(
184         &mut self,
185         infcx: &InferCtxt<'a, 'tcx>,
186         fn_sig_tys: &[Ty<'tcx>],
187         body_id: hir::HirId,
188         span: Span,
189     );
190 }
191
192 impl<'tcx> OutlivesEnvironmentExt<'tcx> for OutlivesEnvironment<'tcx> {
193     /// This method adds "implied bounds" into the outlives environment.
194     /// Implied bounds are outlives relationships that we can deduce
195     /// on the basis that certain types must be well-formed -- these are
196     /// either the types that appear in the function signature or else
197     /// the input types to an impl. For example, if you have a function
198     /// like
199     ///
200     /// ```
201     /// fn foo<'a, 'b, T>(x: &'a &'b [T]) { }
202     /// ```
203     ///
204     /// we can assume in the caller's body that `'b: 'a` and that `T:
205     /// 'b` (and hence, transitively, that `T: 'a`). This method would
206     /// add those assumptions into the outlives-environment.
207     ///
208     /// Tests: `src/test/ui/regions/regions-free-region-ordering-*.rs`
209     fn add_implied_bounds(
210         &mut self,
211         infcx: &InferCtxt<'a, 'tcx>,
212         fn_sig_tys: &[Ty<'tcx>],
213         body_id: hir::HirId,
214         span: Span,
215     ) {
216         debug!("add_implied_bounds()");
217
218         for &ty in fn_sig_tys {
219             let ty = infcx.resolve_vars_if_possible(ty);
220             debug!("add_implied_bounds: ty = {}", ty);
221             let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span);
222             self.add_outlives_bounds(Some(infcx), implied_bounds)
223         }
224     }
225 }