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