rustc_trait_selection/solve/
delegate.rs1use std::ops::Deref;
2
3use rustc_data_structures::fx::FxHashSet;
4use rustc_hir::LangItem;
5use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
6use rustc_infer::infer::canonical::query_response::make_query_region_constraints;
7use rustc_infer::infer::canonical::{
8 Canonical, CanonicalExt as _, CanonicalQueryInput, CanonicalVarKind, CanonicalVarValues,
9};
10use rustc_infer::infer::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt};
11use rustc_infer::traits::solve::Goal;
12use rustc_middle::traits::query::NoSolution;
13use rustc_middle::traits::solve::Certainty;
14use rustc_middle::ty::{
15 self, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeVisitableExt as _, TypingMode,
16};
17use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
18
19use crate::traits::{EvaluateConstErr, ObligationCause, specialization_graph};
20
21#[repr(transparent)]
22pub struct SolverDelegate<'tcx>(InferCtxt<'tcx>);
23
24impl<'a, 'tcx> From<&'a InferCtxt<'tcx>> for &'a SolverDelegate<'tcx> {
25 fn from(infcx: &'a InferCtxt<'tcx>) -> Self {
26 unsafe { std::mem::transmute(infcx) }
28 }
29}
30
31impl<'tcx> Deref for SolverDelegate<'tcx> {
32 type Target = InferCtxt<'tcx>;
33
34 fn deref(&self) -> &Self::Target {
35 &self.0
36 }
37}
38
39impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<'tcx> {
40 type Infcx = InferCtxt<'tcx>;
41 type Interner = TyCtxt<'tcx>;
42
43 fn cx(&self) -> TyCtxt<'tcx> {
44 self.0.tcx
45 }
46
47 fn build_with_canonical<V>(
48 interner: TyCtxt<'tcx>,
49 canonical: &CanonicalQueryInput<'tcx, V>,
50 ) -> (Self, V, CanonicalVarValues<'tcx>)
51 where
52 V: TypeFoldable<TyCtxt<'tcx>>,
53 {
54 let (infcx, value, vars) = interner
55 .infer_ctxt()
56 .with_next_trait_solver(true)
57 .build_with_canonical(DUMMY_SP, canonical);
58 (SolverDelegate(infcx), value, vars)
59 }
60
61 fn compute_goal_fast_path(
62 &self,
63 goal: Goal<'tcx, ty::Predicate<'tcx>>,
64 span: Span,
65 ) -> Option<Certainty> {
66 if let Some(trait_pred) = goal.predicate.as_trait_clause() {
67 if trait_pred.polarity() == ty::PredicatePolarity::Positive {
68 match self.0.tcx.as_lang_item(trait_pred.def_id()) {
69 Some(LangItem::Sized)
70 if self
71 .resolve_vars_if_possible(trait_pred.self_ty().skip_binder())
72 .is_trivially_sized(self.0.tcx) =>
73 {
74 return Some(Certainty::Yes);
75 }
76 Some(LangItem::Copy | LangItem::Clone) => {
77 let self_ty =
78 self.resolve_vars_if_possible(trait_pred.self_ty().skip_binder());
79 if !self_ty
85 .has_type_flags(TypeFlags::HAS_FREE_REGIONS | TypeFlags::HAS_INFER)
86 && self_ty.is_trivially_pure_clone_copy()
87 {
88 return Some(Certainty::Yes);
89 }
90 }
91 _ => {}
92 }
93 }
94 }
95
96 let pred = goal.predicate.kind();
97 match pred.no_bound_vars()? {
98 ty::PredicateKind::DynCompatible(def_id) if self.0.tcx.is_dyn_compatible(def_id) => {
99 Some(Certainty::Yes)
100 }
101 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(outlives)) => {
102 self.0.sub_regions(
103 SubregionOrigin::RelateRegionParamBound(span, None),
104 outlives.1,
105 outlives.0,
106 );
107 Some(Certainty::Yes)
108 }
109 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(outlives)) => {
110 self.0.register_type_outlives_constraint(
111 outlives.0,
112 outlives.1,
113 &ObligationCause::dummy_with_span(span),
114 );
115
116 Some(Certainty::Yes)
117 }
118 _ => None,
119 }
120 }
121
122 fn fresh_var_for_kind_with_span(
123 &self,
124 arg: ty::GenericArg<'tcx>,
125 span: Span,
126 ) -> ty::GenericArg<'tcx> {
127 match arg.kind() {
128 ty::GenericArgKind::Lifetime(_) => {
129 self.next_region_var(RegionVariableOrigin::MiscVariable(span)).into()
130 }
131 ty::GenericArgKind::Type(_) => self.next_ty_var(span).into(),
132 ty::GenericArgKind::Const(_) => self.next_const_var(span).into(),
133 }
134 }
135
136 fn leak_check(&self, max_input_universe: ty::UniverseIndex) -> Result<(), NoSolution> {
137 self.0.leak_check(max_input_universe, None).map_err(|_| NoSolution)
138 }
139
140 fn evaluate_const(
141 &self,
142 param_env: ty::ParamEnv<'tcx>,
143 uv: ty::UnevaluatedConst<'tcx>,
144 ) -> Option<ty::Const<'tcx>> {
145 let ct = ty::Const::new_unevaluated(self.tcx, uv);
146
147 match crate::traits::try_evaluate_const(&self.0, ct, param_env) {
148 Ok(ct) => Some(ct),
149 Err(EvaluateConstErr::EvaluationFailure(e)) => Some(ty::Const::new_error(self.tcx, e)),
150 Err(
151 EvaluateConstErr::InvalidConstParamTy(_) | EvaluateConstErr::HasGenericsOrInfers,
152 ) => None,
153 }
154 }
155
156 fn well_formed_goals(
157 &self,
158 param_env: ty::ParamEnv<'tcx>,
159 term: ty::Term<'tcx>,
160 ) -> Option<Vec<Goal<'tcx, ty::Predicate<'tcx>>>> {
161 crate::traits::wf::unnormalized_obligations(
162 &self.0,
163 param_env,
164 term,
165 DUMMY_SP,
166 CRATE_DEF_ID,
167 )
168 .map(|obligations| obligations.into_iter().map(|obligation| obligation.as_goal()).collect())
169 }
170
171 fn make_deduplicated_outlives_constraints(
172 &self,
173 ) -> Vec<ty::OutlivesPredicate<'tcx, ty::GenericArg<'tcx>>> {
174 let region_obligations = self.0.inner.borrow().region_obligations().to_owned();
177 let region_constraints = self.0.with_region_constraints(|region_constraints| {
178 make_query_region_constraints(
179 self.tcx,
180 region_obligations
181 .iter()
182 .map(|r_o| (r_o.sup_type, r_o.sub_region, r_o.origin.to_constraint_category())),
183 region_constraints,
184 )
185 });
186
187 let mut seen = FxHashSet::default();
188 region_constraints
189 .outlives
190 .into_iter()
191 .filter(|&(outlives, _)| seen.insert(outlives))
192 .map(|(outlives, _)| outlives)
193 .collect()
194 }
195
196 fn instantiate_canonical<V>(
197 &self,
198 canonical: Canonical<'tcx, V>,
199 values: CanonicalVarValues<'tcx>,
200 ) -> V
201 where
202 V: TypeFoldable<TyCtxt<'tcx>>,
203 {
204 canonical.instantiate(self.tcx, &values)
205 }
206
207 fn instantiate_canonical_var_with_infer(
208 &self,
209 kind: CanonicalVarKind<'tcx>,
210 span: Span,
211 universe_map: impl Fn(ty::UniverseIndex) -> ty::UniverseIndex,
212 ) -> ty::GenericArg<'tcx> {
213 self.0.instantiate_canonical_var(span, kind, universe_map)
214 }
215
216 fn add_item_bounds_for_hidden_type(
217 &self,
218 def_id: DefId,
219 args: ty::GenericArgsRef<'tcx>,
220 param_env: ty::ParamEnv<'tcx>,
221 hidden_ty: Ty<'tcx>,
222 goals: &mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
223 ) {
224 self.0.add_item_bounds_for_hidden_type(def_id, args, param_env, hidden_ty, goals);
225 }
226
227 fn fetch_eligible_assoc_item(
228 &self,
229 goal_trait_ref: ty::TraitRef<'tcx>,
230 trait_assoc_def_id: DefId,
231 impl_def_id: DefId,
232 ) -> Result<Option<DefId>, ErrorGuaranteed> {
233 let node_item = specialization_graph::assoc_def(self.tcx, impl_def_id, trait_assoc_def_id)?;
234
235 let eligible = if node_item.is_final() {
236 true
238 } else {
239 match self.typing_mode() {
244 TypingMode::Coherence
245 | TypingMode::Analysis { .. }
246 | TypingMode::Borrowck { .. }
247 | TypingMode::PostBorrowckAnalysis { .. } => false,
248 TypingMode::PostAnalysis => {
249 let poly_trait_ref = self.resolve_vars_if_possible(goal_trait_ref);
250 !poly_trait_ref.still_further_specializable()
251 }
252 }
253 };
254
255 if eligible { Ok(Some(node_item.item.def_id)) } else { Ok(None) }
257 }
258
259 fn is_transmutable(
262 &self,
263 dst: Ty<'tcx>,
264 src: Ty<'tcx>,
265 assume: ty::Const<'tcx>,
266 ) -> Result<Certainty, NoSolution> {
267 let (dst, src) = self.tcx.erase_regions((dst, src));
270
271 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
272 return Err(NoSolution);
273 };
274
275 match rustc_transmute::TransmuteTypeEnv::new(self.0.tcx)
277 .is_transmutable(rustc_transmute::Types { src, dst }, assume)
278 {
279 rustc_transmute::Answer::Yes => Ok(Certainty::Yes),
280 rustc_transmute::Answer::No(_) | rustc_transmute::Answer::If(_) => Err(NoSolution),
281 }
282 }
283}