rustc_trait_selection/solve/
delegate.rs

1use std::ops::Deref;
2
3use rustc_data_structures::fx::FxHashSet;
4use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
5use rustc_infer::infer::canonical::query_response::make_query_region_constraints;
6use rustc_infer::infer::canonical::{
7    Canonical, CanonicalExt as _, CanonicalQueryInput, CanonicalVarInfo, CanonicalVarValues,
8};
9use rustc_infer::infer::{InferCtxt, RegionVariableOrigin, TyCtxtInferExt};
10use rustc_infer::traits::solve::Goal;
11use rustc_middle::traits::query::NoSolution;
12use rustc_middle::traits::solve::Certainty;
13use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _, TypingMode};
14use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
15
16use crate::traits::{EvaluateConstErr, specialization_graph};
17
18#[repr(transparent)]
19pub struct SolverDelegate<'tcx>(InferCtxt<'tcx>);
20
21impl<'a, 'tcx> From<&'a InferCtxt<'tcx>> for &'a SolverDelegate<'tcx> {
22    fn from(infcx: &'a InferCtxt<'tcx>) -> Self {
23        // SAFETY: `repr(transparent)`
24        unsafe { std::mem::transmute(infcx) }
25    }
26}
27
28impl<'tcx> Deref for SolverDelegate<'tcx> {
29    type Target = InferCtxt<'tcx>;
30
31    fn deref(&self) -> &Self::Target {
32        &self.0
33    }
34}
35
36impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<'tcx> {
37    type Infcx = InferCtxt<'tcx>;
38    type Interner = TyCtxt<'tcx>;
39
40    fn cx(&self) -> TyCtxt<'tcx> {
41        self.0.tcx
42    }
43
44    fn build_with_canonical<V>(
45        interner: TyCtxt<'tcx>,
46        canonical: &CanonicalQueryInput<'tcx, V>,
47    ) -> (Self, V, CanonicalVarValues<'tcx>)
48    where
49        V: TypeFoldable<TyCtxt<'tcx>>,
50    {
51        let (infcx, value, vars) = interner
52            .infer_ctxt()
53            .with_next_trait_solver(true)
54            .build_with_canonical(DUMMY_SP, canonical);
55        (SolverDelegate(infcx), value, vars)
56    }
57
58    fn fresh_var_for_kind_with_span(
59        &self,
60        arg: ty::GenericArg<'tcx>,
61        span: Span,
62    ) -> ty::GenericArg<'tcx> {
63        match arg.unpack() {
64            ty::GenericArgKind::Lifetime(_) => {
65                self.next_region_var(RegionVariableOrigin::MiscVariable(span)).into()
66            }
67            ty::GenericArgKind::Type(_) => self.next_ty_var(span).into(),
68            ty::GenericArgKind::Const(_) => self.next_const_var(span).into(),
69        }
70    }
71
72    fn leak_check(&self, max_input_universe: ty::UniverseIndex) -> Result<(), NoSolution> {
73        self.0.leak_check(max_input_universe, None).map_err(|_| NoSolution)
74    }
75
76    fn evaluate_const(
77        &self,
78        param_env: ty::ParamEnv<'tcx>,
79        uv: ty::UnevaluatedConst<'tcx>,
80    ) -> Option<ty::Const<'tcx>> {
81        let ct = ty::Const::new_unevaluated(self.tcx, uv);
82
83        match crate::traits::try_evaluate_const(&self.0, ct, param_env) {
84            Ok(ct) => Some(ct),
85            Err(EvaluateConstErr::EvaluationFailure(e)) => Some(ty::Const::new_error(self.tcx, e)),
86            Err(
87                EvaluateConstErr::InvalidConstParamTy(_) | EvaluateConstErr::HasGenericsOrInfers,
88            ) => None,
89        }
90    }
91
92    fn well_formed_goals(
93        &self,
94        param_env: ty::ParamEnv<'tcx>,
95        term: ty::Term<'tcx>,
96    ) -> Option<Vec<Goal<'tcx, ty::Predicate<'tcx>>>> {
97        crate::traits::wf::unnormalized_obligations(
98            &self.0,
99            param_env,
100            term,
101            DUMMY_SP,
102            CRATE_DEF_ID,
103        )
104        .map(|obligations| obligations.into_iter().map(|obligation| obligation.as_goal()).collect())
105    }
106
107    fn make_deduplicated_outlives_constraints(
108        &self,
109    ) -> Vec<ty::OutlivesPredicate<'tcx, ty::GenericArg<'tcx>>> {
110        // Cannot use `take_registered_region_obligations` as we may compute the response
111        // inside of a `probe` whenever we have multiple choices inside of the solver.
112        let region_obligations = self.0.inner.borrow().region_obligations().to_owned();
113        let region_constraints = self.0.with_region_constraints(|region_constraints| {
114            make_query_region_constraints(
115                self.tcx,
116                region_obligations
117                    .iter()
118                    .map(|r_o| (r_o.sup_type, r_o.sub_region, r_o.origin.to_constraint_category())),
119                region_constraints,
120            )
121        });
122
123        let mut seen = FxHashSet::default();
124        region_constraints
125            .outlives
126            .into_iter()
127            .filter(|&(outlives, _)| seen.insert(outlives))
128            .map(|(outlives, _)| outlives)
129            .collect()
130    }
131
132    fn instantiate_canonical<V>(
133        &self,
134        canonical: Canonical<'tcx, V>,
135        values: CanonicalVarValues<'tcx>,
136    ) -> V
137    where
138        V: TypeFoldable<TyCtxt<'tcx>>,
139    {
140        canonical.instantiate(self.tcx, &values)
141    }
142
143    fn instantiate_canonical_var_with_infer(
144        &self,
145        cv_info: CanonicalVarInfo<'tcx>,
146        span: Span,
147        universe_map: impl Fn(ty::UniverseIndex) -> ty::UniverseIndex,
148    ) -> ty::GenericArg<'tcx> {
149        self.0.instantiate_canonical_var(span, cv_info, universe_map)
150    }
151
152    fn add_item_bounds_for_hidden_type(
153        &self,
154        def_id: DefId,
155        args: ty::GenericArgsRef<'tcx>,
156        param_env: ty::ParamEnv<'tcx>,
157        hidden_ty: Ty<'tcx>,
158        goals: &mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
159    ) {
160        self.0.add_item_bounds_for_hidden_type(def_id, args, param_env, hidden_ty, goals);
161    }
162
163    fn fetch_eligible_assoc_item(
164        &self,
165        goal_trait_ref: ty::TraitRef<'tcx>,
166        trait_assoc_def_id: DefId,
167        impl_def_id: DefId,
168    ) -> Result<Option<DefId>, ErrorGuaranteed> {
169        let node_item = specialization_graph::assoc_def(self.tcx, impl_def_id, trait_assoc_def_id)?;
170
171        let eligible = if node_item.is_final() {
172            // Non-specializable items are always projectable.
173            true
174        } else {
175            // Only reveal a specializable default if we're past type-checking
176            // and the obligation is monomorphic, otherwise passes such as
177            // transmute checking and polymorphic MIR optimizations could
178            // get a result which isn't correct for all monomorphizations.
179            match self.typing_mode() {
180                TypingMode::Coherence
181                | TypingMode::Analysis { .. }
182                | TypingMode::Borrowck { .. }
183                | TypingMode::PostBorrowckAnalysis { .. } => false,
184                TypingMode::PostAnalysis => {
185                    let poly_trait_ref = self.resolve_vars_if_possible(goal_trait_ref);
186                    !poly_trait_ref.still_further_specializable()
187                }
188            }
189        };
190
191        // FIXME: Check for defaultness here may cause diagnostics problems.
192        if eligible { Ok(Some(node_item.item.def_id)) } else { Ok(None) }
193    }
194
195    // FIXME: This actually should destructure the `Result` we get from transmutability and
196    // register candidates. We probably need to register >1 since we may have an OR of ANDs.
197    fn is_transmutable(
198        &self,
199        dst: Ty<'tcx>,
200        src: Ty<'tcx>,
201        assume: ty::Const<'tcx>,
202    ) -> Result<Certainty, NoSolution> {
203        // Erase regions because we compute layouts in `rustc_transmute`,
204        // which will ICE for region vars.
205        let (dst, src) = self.tcx.erase_regions((dst, src));
206
207        let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
208            return Err(NoSolution);
209        };
210
211        // FIXME(transmutability): This really should be returning nested goals for `Answer::If*`
212        match rustc_transmute::TransmuteTypeEnv::new(self.0.tcx)
213            .is_transmutable(rustc_transmute::Types { src, dst }, assume)
214        {
215            rustc_transmute::Answer::Yes => Ok(Certainty::Yes),
216            rustc_transmute::Answer::No(_) | rustc_transmute::Answer::If(_) => Err(NoSolution),
217        }
218    }
219}