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