rustc_trait_selection/
infer.rs

1use std::fmt::Debug;
2
3use rustc_hir::def_id::DefId;
4use rustc_hir::lang_items::LangItem;
5pub use rustc_infer::infer::*;
6use rustc_macros::extension;
7use rustc_middle::arena::ArenaAllocatable;
8use rustc_middle::infer::canonical::{
9    Canonical, CanonicalQueryInput, CanonicalQueryResponse, QueryResponse,
10};
11use rustc_middle::traits::query::NoSolution;
12use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast};
13use rustc_span::DUMMY_SP;
14use tracing::instrument;
15
16use crate::infer::at::ToTrace;
17use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
18use crate::traits::{self, Obligation, ObligationCause, ObligationCtxt};
19
20#[extension(pub trait InferCtxtExt<'tcx>)]
21impl<'tcx> InferCtxt<'tcx> {
22    fn can_eq<T: ToTrace<'tcx>>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool {
23        self.probe(|_| {
24            let ocx = ObligationCtxt::new(self);
25            let Ok(()) = ocx.eq(&ObligationCause::dummy(), param_env, a, b) else {
26                return false;
27            };
28            ocx.select_where_possible().is_empty()
29        })
30    }
31
32    fn type_is_copy_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
33        let ty = self.resolve_vars_if_possible(ty);
34
35        // FIXME(#132279): This should be removed as it causes us to incorrectly
36        // handle opaques in their defining scope.
37        if !(param_env, ty).has_infer() {
38            return self.tcx.type_is_copy_modulo_regions(self.typing_env(param_env), ty);
39        }
40
41        let copy_def_id = self.tcx.require_lang_item(LangItem::Copy, None);
42
43        // This can get called from typeck (by euv), and `moves_by_default`
44        // rightly refuses to work with inference variables, but
45        // moves_by_default has a cache, which we want to use in other
46        // cases.
47        traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id)
48    }
49
50    fn type_is_clone_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
51        let ty = self.resolve_vars_if_possible(ty);
52        let clone_def_id = self.tcx.require_lang_item(LangItem::Clone, None);
53        traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, clone_def_id)
54    }
55
56    fn type_is_use_cloned_modulo_regions(
57        &self,
58        param_env: ty::ParamEnv<'tcx>,
59        ty: Ty<'tcx>,
60    ) -> bool {
61        let ty = self.resolve_vars_if_possible(ty);
62        let use_cloned_def_id = self.tcx.require_lang_item(LangItem::UseCloned, None);
63        traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, use_cloned_def_id)
64    }
65
66    fn type_is_sized_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
67        let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
68        traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, lang_item)
69    }
70
71    /// Check whether a `ty` implements given trait(trait_def_id) without side-effects.
72    ///
73    /// The inputs are:
74    ///
75    /// - the def-id of the trait
76    /// - the type parameters of the trait, including the self-type
77    /// - the parameter environment
78    ///
79    /// Invokes `evaluate_obligation`, so in the event that evaluating
80    /// `Ty: Trait` causes overflow, EvaluatedToAmbigStackDependent will be returned.
81    ///
82    /// `type_implements_trait` is a convenience function for simple cases like
83    ///
84    /// ```ignore (illustrative)
85    /// let copy_trait = infcx.tcx.require_lang_item(LangItem::Copy, span);
86    /// let implements_copy = infcx.type_implements_trait(copy_trait, [ty], param_env)
87    /// .must_apply_modulo_regions();
88    /// ```
89    ///
90    /// In most cases you should instead create an [Obligation] and check whether
91    ///  it holds via [`evaluate_obligation`] or one of its helper functions like
92    /// [`predicate_must_hold_modulo_regions`], because it properly handles higher ranked traits
93    /// and it is more convenient and safer when your `params` are inside a [`Binder`].
94    ///
95    /// [Obligation]: traits::Obligation
96    /// [`evaluate_obligation`]: crate::traits::query::evaluate_obligation::InferCtxtExt::evaluate_obligation
97    /// [`predicate_must_hold_modulo_regions`]: crate::traits::query::evaluate_obligation::InferCtxtExt::predicate_must_hold_modulo_regions
98    /// [`Binder`]: ty::Binder
99    #[instrument(level = "debug", skip(self, params), ret)]
100    fn type_implements_trait(
101        &self,
102        trait_def_id: DefId,
103        params: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
104        param_env: ty::ParamEnv<'tcx>,
105    ) -> traits::EvaluationResult {
106        let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, params);
107
108        let obligation = traits::Obligation {
109            cause: traits::ObligationCause::dummy(),
110            param_env,
111            recursion_depth: 0,
112            predicate: trait_ref.upcast(self.tcx),
113        };
114        self.evaluate_obligation(&obligation).unwrap_or(traits::EvaluationResult::EvaluatedToErr)
115    }
116
117    /// Returns `Some` if a type implements a trait shallowly, without side-effects,
118    /// along with any errors that would have been reported upon further obligation
119    /// processing.
120    ///
121    /// - If this returns `Some([])`, then the trait holds modulo regions.
122    /// - If this returns `Some([errors..])`, then the trait has an impl for
123    /// the self type, but some nested obligations do not hold.
124    /// - If this returns `None`, no implementation that applies could be found.
125    fn type_implements_trait_shallow(
126        &self,
127        trait_def_id: DefId,
128        ty: Ty<'tcx>,
129        param_env: ty::ParamEnv<'tcx>,
130    ) -> Option<Vec<traits::FulfillmentError<'tcx>>> {
131        self.probe(|_snapshot| {
132            let ocx = ObligationCtxt::new_with_diagnostics(self);
133            ocx.register_obligation(Obligation::new(
134                self.tcx,
135                ObligationCause::dummy(),
136                param_env,
137                ty::TraitRef::new(self.tcx, trait_def_id, [ty]),
138            ));
139            let errors = ocx.select_where_possible();
140            // Find the original predicate in the list of predicates that could definitely not be fulfilled.
141            // If it is in that list, then we know this doesn't even shallowly implement the trait.
142            // If it is not in that list, it was fulfilled, but there may be nested obligations, which we don't care about here.
143            for error in &errors {
144                let Some(trait_clause) = error.obligation.predicate.as_trait_clause() else {
145                    continue;
146                };
147                let Some(bound_ty) = trait_clause.self_ty().no_bound_vars() else { continue };
148                if trait_clause.def_id() == trait_def_id
149                    && ocx.eq(&ObligationCause::dummy(), param_env, bound_ty, ty).is_ok()
150                {
151                    return None;
152                }
153            }
154            Some(errors)
155        })
156    }
157}
158
159#[extension(pub trait InferCtxtBuilderExt<'tcx>)]
160impl<'tcx> InferCtxtBuilder<'tcx> {
161    /// The "main method" for a canonicalized trait query. Given the
162    /// canonical key `canonical_key`, this method will create a new
163    /// inference context, instantiate the key, and run your operation
164    /// `op`. The operation should yield up a result (of type `R`) as
165    /// well as a set of trait obligations that must be fully
166    /// satisfied. These obligations will be processed and the
167    /// canonical result created.
168    ///
169    /// Returns `NoSolution` in the event of any error.
170    ///
171    /// (It might be mildly nicer to implement this on `TyCtxt`, and
172    /// not `InferCtxtBuilder`, but that is a bit tricky right now.
173    /// In part because we would need a `for<'tcx>` sort of
174    /// bound for the closure and in part because it is convenient to
175    /// have `'tcx` be free on this function so that we can talk about
176    /// `K: TypeFoldable<TyCtxt<'tcx>>`.)
177    fn enter_canonical_trait_query<K, R>(
178        self,
179        canonical_key: &CanonicalQueryInput<'tcx, K>,
180        operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Result<R, NoSolution>,
181    ) -> Result<CanonicalQueryResponse<'tcx, R>, NoSolution>
182    where
183        K: TypeFoldable<TyCtxt<'tcx>>,
184        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
185        Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>,
186    {
187        let (infcx, key, canonical_inference_vars) =
188            self.build_with_canonical(DUMMY_SP, canonical_key);
189        let ocx = ObligationCtxt::new(&infcx);
190        let value = operation(&ocx, key)?;
191        ocx.make_canonicalized_query_response(canonical_inference_vars, value)
192    }
193}