Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit c3bb3e0

Browse files
compiler-errorslcnr
authored andcommitted
Only prefer param-env candidates if they remain non-global after norm
1 parent 2522234 commit c3bb3e0

File tree

8 files changed

+300
-174
lines changed

8 files changed

+300
-174
lines changed

compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs

Lines changed: 140 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,24 @@
22
33
pub(super) mod structural_traits;
44

5+
use std::ops::ControlFlow;
6+
57
use derive_where::derive_where;
68
use rustc_type_ir::inherent::*;
79
use rustc_type_ir::lang_items::TraitSolverLangItem;
810
use rustc_type_ir::{
9-
self as ty, Interner, TypeFoldable, TypeVisitableExt as _, TypingMode, Upcast as _, elaborate,
11+
self as ty, Interner, TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt as _,
12+
TypeVisitor, TypingMode, Upcast as _, elaborate,
1013
};
1114
use tracing::{debug, instrument};
1215

13-
use super::has_only_region_constraints;
1416
use super::trait_goals::TraitGoalProvenVia;
17+
use super::{has_only_region_constraints, inspect};
1518
use crate::delegate::SolverDelegate;
1619
use crate::solve::inspect::ProbeKind;
1720
use crate::solve::{
1821
BuiltinImplSource, CandidateSource, CanonicalResponse, Certainty, EvalCtxt, Goal, GoalSource,
19-
MaybeCause, NoSolution, QueryResult,
22+
MaybeCause, NoSolution, ParamEnvSource, QueryResult,
2023
};
2124

2225
enum AliasBoundKind {
@@ -49,18 +52,6 @@ where
4952

5053
fn trait_def_id(self, cx: I) -> I::DefId;
5154

52-
/// Try equating an assumption predicate against a goal's predicate. If it
53-
/// holds, then execute the `then` callback, which should do any additional
54-
/// work, then produce a response (typically by executing
55-
/// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
56-
fn probe_and_match_goal_against_assumption(
57-
ecx: &mut EvalCtxt<'_, D>,
58-
source: CandidateSource<I>,
59-
goal: Goal<I, Self>,
60-
assumption: I::Clause,
61-
then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
62-
) -> Result<Candidate<I>, NoSolution>;
63-
6455
/// Consider a clause, which consists of a "assumption" and some "requirements",
6556
/// to satisfy a goal. If the requirements hold, then attempt to satisfy our
6657
/// goal by equating it with the assumption.
@@ -119,6 +110,66 @@ where
119110
alias_ty: ty::AliasTy<I>,
120111
) -> Vec<Candidate<I>>;
121112

113+
fn probe_and_consider_param_env_candidate(
114+
ecx: &mut EvalCtxt<'_, D>,
115+
goal: Goal<I, Self>,
116+
assumption: I::Clause,
117+
) -> Result<Candidate<I>, NoSolution> {
118+
Self::fast_reject_assumption(ecx, goal, assumption)?;
119+
120+
ecx.probe(|candidate: &Result<Candidate<I>, NoSolution>| match candidate {
121+
Ok(candidate) => inspect::ProbeKind::TraitCandidate {
122+
source: candidate.source,
123+
result: Ok(candidate.result),
124+
},
125+
Err(NoSolution) => inspect::ProbeKind::TraitCandidate {
126+
source: CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
127+
result: Err(NoSolution),
128+
},
129+
})
130+
.enter(|ecx| {
131+
let mut source = CandidateSource::ParamEnv(ParamEnvSource::NonGlobal);
132+
let result = Self::match_assumption(ecx, goal, assumption, |ecx| {
133+
source = ecx.characterize_param_env_assumption(goal.param_env, assumption)?;
134+
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
135+
})?;
136+
Ok(Candidate { source, result })
137+
})
138+
}
139+
140+
/// Try equating an assumption predicate against a goal's predicate. If it
141+
/// holds, then execute the `then` callback, which should do any additional
142+
/// work, then produce a response (typically by executing
143+
/// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
144+
fn probe_and_match_goal_against_assumption(
145+
ecx: &mut EvalCtxt<'_, D>,
146+
source: CandidateSource<I>,
147+
goal: Goal<I, Self>,
148+
assumption: I::Clause,
149+
then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
150+
) -> Result<Candidate<I>, NoSolution> {
151+
Self::fast_reject_assumption(ecx, goal, assumption)?;
152+
153+
ecx.probe_trait_candidate(source)
154+
.enter(|ecx| Self::match_assumption(ecx, goal, assumption, then))
155+
}
156+
157+
/// Try to reject the assumption based off of simple heuristics, such as [`ty::ClauseKind`]
158+
/// and [`I::DefId`].
159+
fn fast_reject_assumption(
160+
ecx: &mut EvalCtxt<'_, D>,
161+
goal: Goal<I, Self>,
162+
assumption: I::Clause,
163+
) -> Result<(), NoSolution>;
164+
165+
/// Relate the goal and assumption.
166+
fn match_assumption(
167+
ecx: &mut EvalCtxt<'_, D>,
168+
goal: Goal<I, Self>,
169+
assumption: I::Clause,
170+
then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
171+
) -> QueryResult<I>;
172+
122173
fn consider_impl_candidate(
123174
ecx: &mut EvalCtxt<'_, D>,
124175
goal: Goal<I, Self>,
@@ -500,14 +551,8 @@ where
500551
goal: Goal<I, G>,
501552
candidates: &mut Vec<Candidate<I>>,
502553
) {
503-
for (i, assumption) in goal.param_env.caller_bounds().iter().enumerate() {
504-
candidates.extend(G::probe_and_consider_implied_clause(
505-
self,
506-
CandidateSource::ParamEnv(i),
507-
goal,
508-
assumption,
509-
[],
510-
));
554+
for assumption in goal.param_env.caller_bounds().iter() {
555+
candidates.extend(G::probe_and_consider_param_env_candidate(self, goal, assumption));
511556
}
512557
}
513558

@@ -943,4 +988,76 @@ where
943988
}
944989
}
945990
}
991+
992+
fn characterize_param_env_assumption(
993+
&mut self,
994+
param_env: I::ParamEnv,
995+
assumption: I::Clause,
996+
) -> Result<CandidateSource<I>, NoSolution> {
997+
// FIXME:
998+
if assumption.has_bound_vars() {
999+
return Ok(CandidateSource::ParamEnv(ParamEnvSource::NonGlobal));
1000+
}
1001+
1002+
match assumption.visit_with(&mut FindParamInClause { ecx: self, param_env }) {
1003+
ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
1004+
ControlFlow::Break(Ok(())) => Ok(CandidateSource::ParamEnv(ParamEnvSource::NonGlobal)),
1005+
ControlFlow::Continue(()) => Ok(CandidateSource::ParamEnv(ParamEnvSource::Global)),
1006+
}
1007+
}
1008+
}
1009+
1010+
struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
1011+
ecx: &'a mut EvalCtxt<'b, D>,
1012+
param_env: I::ParamEnv,
1013+
}
1014+
1015+
impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
1016+
where
1017+
D: SolverDelegate<Interner = I>,
1018+
I: Interner,
1019+
{
1020+
type Result = ControlFlow<Result<(), NoSolution>>;
1021+
1022+
fn visit_binder<T: TypeFoldable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
1023+
self.ecx.enter_forall(t.clone(), |ecx, v| {
1024+
v.visit_with(&mut FindParamInClause { ecx, param_env: self.param_env })
1025+
})
1026+
}
1027+
1028+
fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
1029+
let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
1030+
return ControlFlow::Break(Err(NoSolution));
1031+
};
1032+
let ty = self.ecx.eager_resolve(ty);
1033+
1034+
if let ty::Placeholder(_) = ty.kind() {
1035+
ControlFlow::Break(Ok(()))
1036+
} else {
1037+
ty.super_visit_with(self)
1038+
}
1039+
}
1040+
1041+
fn visit_const(&mut self, ct: I::Const) -> Self::Result {
1042+
let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
1043+
return ControlFlow::Break(Err(NoSolution));
1044+
};
1045+
let ct = self.ecx.eager_resolve(ct);
1046+
1047+
if let ty::ConstKind::Placeholder(_) = ct.kind() {
1048+
ControlFlow::Break(Ok(()))
1049+
} else {
1050+
ct.super_visit_with(self)
1051+
}
1052+
}
1053+
1054+
fn visit_region(&mut self, r: I::Region) -> Self::Result {
1055+
match r.kind() {
1056+
ty::ReStatic | ty::ReError(_) => ControlFlow::Continue(()),
1057+
ty::ReVar(_) | ty::RePlaceholder(_) => ControlFlow::Break(Ok(())),
1058+
ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReBound(..) => {
1059+
unreachable!()
1060+
}
1061+
}
1062+
}
9461063
}

compiler/rustc_next_trait_solver/src/solve/effect_goals.rs

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -36,39 +36,41 @@ where
3636
self.def_id()
3737
}
3838

39-
fn probe_and_match_goal_against_assumption(
39+
fn fast_reject_assumption(
4040
ecx: &mut EvalCtxt<'_, D>,
41-
source: rustc_type_ir::solve::CandidateSource<I>,
4241
goal: Goal<I, Self>,
43-
assumption: <I as Interner>::Clause,
44-
then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
45-
) -> Result<Candidate<I>, NoSolution> {
42+
assumption: I::Clause,
43+
) -> Result<(), NoSolution> {
4644
if let Some(host_clause) = assumption.as_host_effect_clause() {
4745
if host_clause.def_id() == goal.predicate.def_id()
4846
&& host_clause.constness().satisfies(goal.predicate.constness)
4947
{
50-
if !DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify(
48+
if DeepRejectCtxt::relate_rigid_rigid(ecx.cx()).args_may_unify(
5149
goal.predicate.trait_ref.args,
5250
host_clause.skip_binder().trait_ref.args,
5351
) {
54-
return Err(NoSolution);
52+
return Ok(());
5553
}
56-
57-
ecx.probe_trait_candidate(source).enter(|ecx| {
58-
let assumption_trait_pred = ecx.instantiate_binder_with_infer(host_clause);
59-
ecx.eq(
60-
goal.param_env,
61-
goal.predicate.trait_ref,
62-
assumption_trait_pred.trait_ref,
63-
)?;
64-
then(ecx)
65-
})
66-
} else {
67-
Err(NoSolution)
6854
}
69-
} else {
70-
Err(NoSolution)
7155
}
56+
57+
Err(NoSolution)
58+
}
59+
60+
fn match_assumption(
61+
ecx: &mut EvalCtxt<'_, D>,
62+
goal: Goal<I, Self>,
63+
assumption: I::Clause,
64+
then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
65+
) -> QueryResult<I> {
66+
let Some(host_clause) = assumption.as_host_effect_clause() else {
67+
panic!("fast_reject_assumption should have avoided this");
68+
};
69+
70+
let assumption_trait_pred = ecx.instantiate_binder_with_infer(host_clause);
71+
ecx.eq(goal.param_env, goal.predicate.trait_ref, assumption_trait_pred.trait_ref)?;
72+
73+
then(ecx)
7274
}
7375

7476
/// Register additional assumptions for aliases corresponding to `~const` item bounds.
@@ -124,7 +126,7 @@ where
124126
fn consider_impl_candidate(
125127
ecx: &mut EvalCtxt<'_, D>,
126128
goal: Goal<I, Self>,
127-
impl_def_id: <I as Interner>::DefId,
129+
impl_def_id: I::DefId,
128130
) -> Result<Candidate<I>, NoSolution> {
129131
let cx = ecx.cx();
130132

@@ -178,7 +180,7 @@ where
178180

179181
fn consider_error_guaranteed_candidate(
180182
ecx: &mut EvalCtxt<'_, D>,
181-
_guar: <I as Interner>::ErrorGuaranteed,
183+
_guar: I::ErrorGuaranteed,
182184
) -> Result<Candidate<I>, NoSolution> {
183185
ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
184186
.enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))

compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use tracing::{instrument, trace};
1919
use super::has_only_region_constraints;
2020
use crate::coherence;
2121
use crate::delegate::SolverDelegate;
22+
use crate::resolve::EagerResolver;
2223
use crate::solve::inspect::{self, ProofTreeBuilder};
2324
use crate::solve::search_graph::SearchGraph;
2425
use crate::solve::{
@@ -987,6 +988,13 @@ where
987988
self.delegate.resolve_vars_if_possible(value)
988989
}
989990

991+
pub(super) fn eager_resolve<T>(&self, value: T) -> T
992+
where
993+
T: TypeFoldable<I>,
994+
{
995+
value.fold_with(&mut EagerResolver::new(self.delegate))
996+
}
997+
990998
pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
991999
let args = self.delegate.fresh_args_for_item(def_id);
9921000
for arg in args.iter() {

0 commit comments

Comments
 (0)