Skip to content

Commit 574fcaa

Browse files
Only prefer param-env candidates if they remain non-global after norm
1 parent a23c4f9 commit 574fcaa

File tree

8 files changed

+262
-141
lines changed

8 files changed

+262
-141
lines changed

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

+159-24
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,18 @@
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

16+
use super::inspect;
1317
use super::trait_goals::TraitGoalProvenVia;
1418
use crate::delegate::SolverDelegate;
1519
use crate::solve::inspect::ProbeKind;
@@ -48,18 +52,6 @@ where
4852

4953
fn trait_def_id(self, cx: I) -> I::DefId;
5054

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

113+
fn probe_and_consider_param_env_candidate(
114+
ecx: &mut EvalCtxt<'_, D>,
115+
goal: Goal<I, Self>,
116+
assumption: I::Clause,
117+
idx: usize,
118+
) -> Result<Candidate<I>, NoSolution> {
119+
Self::fast_reject_assumption(ecx, goal, assumption)?;
120+
121+
ecx.probe(|candidate: &Result<Candidate<I>, NoSolution>| match candidate {
122+
Ok(candidate) => inspect::ProbeKind::TraitCandidate {
123+
source: candidate.source,
124+
result: Ok(candidate.result),
125+
},
126+
Err(NoSolution) => inspect::ProbeKind::TraitCandidate {
127+
source: CandidateSource::BuiltinImpl(BuiltinImplSource::Misc),
128+
result: Err(NoSolution),
129+
},
130+
})
131+
.enter(|ecx| {
132+
Self::match_assumption(ecx, goal, assumption)?;
133+
let source = ecx.characterize_param_env_assumption(goal.param_env, assumption, idx)?;
134+
Ok(Candidate {
135+
source,
136+
result: ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)?,
137+
})
138+
})
139+
}
140+
141+
/// Try equating an assumption predicate against a goal's predicate. If it
142+
/// holds, then execute the `then` callback, which should do any additional
143+
/// work, then produce a response (typically by executing
144+
/// [`EvalCtxt::evaluate_added_goals_and_make_canonical_response`]).
145+
fn probe_and_match_goal_against_assumption(
146+
ecx: &mut EvalCtxt<'_, D>,
147+
source: CandidateSource<I>,
148+
goal: Goal<I, Self>,
149+
assumption: I::Clause,
150+
then: impl FnOnce(&mut EvalCtxt<'_, D>) -> QueryResult<I>,
151+
) -> Result<Candidate<I>, NoSolution> {
152+
Self::fast_reject_assumption(ecx, goal, assumption)?;
153+
154+
ecx.probe_trait_candidate(source).enter(|ecx| {
155+
Self::match_assumption(ecx, goal, assumption)?;
156+
then(ecx)
157+
})
158+
}
159+
160+
/// Try to reject the assumption based off of simple heuristics, such as [`ty::ClauseKind`]
161+
/// and [`I::DefId`].
162+
fn fast_reject_assumption(
163+
ecx: &mut EvalCtxt<'_, D>,
164+
goal: Goal<I, Self>,
165+
assumption: I::Clause,
166+
) -> Result<(), NoSolution>;
167+
168+
/// Relate the goal and assumption.
169+
fn match_assumption(
170+
ecx: &mut EvalCtxt<'_, D>,
171+
goal: Goal<I, Self>,
172+
assumption: I::Clause,
173+
) -> Result<(), NoSolution>;
174+
121175
fn consider_impl_candidate(
122176
ecx: &mut EvalCtxt<'_, D>,
123177
goal: Goal<I, Self>,
@@ -508,13 +562,7 @@ where
508562
candidates: &mut Vec<Candidate<I>>,
509563
) {
510564
for (i, assumption) in goal.param_env.caller_bounds().iter().enumerate() {
511-
candidates.extend(G::probe_and_consider_implied_clause(
512-
self,
513-
CandidateSource::ParamEnv(i),
514-
goal,
515-
assumption,
516-
[],
517-
));
565+
candidates.extend(G::probe_and_consider_param_env_candidate(self, goal, assumption, i));
518566
}
519567
}
520568

@@ -831,11 +879,20 @@ where
831879
// See `tests/ui/winnowing/norm-where-bound-gt-alias-bound.rs`.
832880
let mut considered_candidates: Vec<_> = if candidates_from_env_and_bounds
833881
.iter()
834-
.any(|c| matches!(c.source, CandidateSource::ParamEnv(_)))
835-
{
882+
.any(|c| {
883+
matches!(
884+
c.source,
885+
CandidateSource::ParamEnv(_) | CandidateSource::GlobalParamEnv(_)
886+
)
887+
}) {
836888
candidates_from_env_and_bounds
837889
.into_iter()
838-
.filter(|c| matches!(c.source, CandidateSource::ParamEnv(_)))
890+
.filter(|c| {
891+
matches!(
892+
c.source,
893+
CandidateSource::ParamEnv(_) | CandidateSource::GlobalParamEnv(_)
894+
)
895+
})
839896
.map(|c| c.result)
840897
.collect()
841898
} else {
@@ -864,7 +921,12 @@ where
864921
// (for example, and ideally only) when proving item bounds for an impl.
865922
let candidates_from_env: Vec<_> = candidates
866923
.iter()
867-
.filter(|c| matches!(c.source, CandidateSource::ParamEnv(_)))
924+
.filter(|c| {
925+
matches!(
926+
c.source,
927+
CandidateSource::ParamEnv(_) | CandidateSource::GlobalParamEnv(_)
928+
)
929+
})
868930
.map(|c| c.result)
869931
.collect();
870932
if let Some(response) = self.try_merge_responses(&candidates_from_env) {
@@ -880,4 +942,77 @@ where
880942
}
881943
}
882944
}
945+
946+
fn characterize_param_env_assumption(
947+
&mut self,
948+
param_env: I::ParamEnv,
949+
assumption: I::Clause,
950+
idx: usize,
951+
) -> Result<CandidateSource<I>, NoSolution> {
952+
// FIXME:
953+
if assumption.has_bound_vars() {
954+
return Ok(CandidateSource::ParamEnv(idx));
955+
}
956+
957+
match assumption.visit_with(&mut FindParamInClause { ecx: self, param_env }) {
958+
ControlFlow::Break(Err(NoSolution)) => Err(NoSolution),
959+
ControlFlow::Break(Ok(())) => Ok(CandidateSource::ParamEnv(idx)),
960+
ControlFlow::Continue(()) => Ok(CandidateSource::GlobalParamEnv(idx)),
961+
}
962+
}
963+
}
964+
965+
struct FindParamInClause<'a, 'b, D: SolverDelegate<Interner = I>, I: Interner> {
966+
ecx: &'a mut EvalCtxt<'b, D>,
967+
param_env: I::ParamEnv,
968+
}
969+
970+
impl<D, I> TypeVisitor<I> for FindParamInClause<'_, '_, D, I>
971+
where
972+
D: SolverDelegate<Interner = I>,
973+
I: Interner,
974+
{
975+
type Result = ControlFlow<Result<(), NoSolution>>;
976+
977+
fn visit_binder<T: TypeFoldable<I>>(&mut self, t: &ty::Binder<I, T>) -> Self::Result {
978+
self.ecx.enter_forall(t.clone(), |ecx, v| {
979+
v.visit_with(&mut FindParamInClause { ecx, param_env: self.param_env })
980+
})
981+
}
982+
983+
fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
984+
let Ok(ty) = self.ecx.structurally_normalize_ty(self.param_env, ty) else {
985+
return ControlFlow::Break(Err(NoSolution));
986+
};
987+
let ty = self.ecx.eager_resolve(ty);
988+
989+
if let ty::Placeholder(_) = ty.kind() {
990+
ControlFlow::Break(Ok(()))
991+
} else {
992+
ty.super_visit_with(self)
993+
}
994+
}
995+
996+
fn visit_const(&mut self, ct: I::Const) -> Self::Result {
997+
let Ok(ct) = self.ecx.structurally_normalize_const(self.param_env, ct) else {
998+
return ControlFlow::Break(Err(NoSolution));
999+
};
1000+
let ct = self.ecx.eager_resolve(ct);
1001+
1002+
if let ty::ConstKind::Placeholder(_) = ct.kind() {
1003+
ControlFlow::Break(Ok(()))
1004+
} else {
1005+
ct.super_visit_with(self)
1006+
}
1007+
}
1008+
1009+
fn visit_region(&mut self, r: I::Region) -> Self::Result {
1010+
match r.kind() {
1011+
ty::ReStatic | ty::ReError(_) => ControlFlow::Continue(()),
1012+
ty::ReVar(_) | ty::RePlaceholder(_) => ControlFlow::Break(Ok(())),
1013+
ty::ReErased | ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReBound(..) => {
1014+
unreachable!()
1015+
}
1016+
}
1017+
}
8831018
}

compiler/rustc_next_trait_solver/src/solve/effect_goals.rs

+24-23
Original file line numberDiff line numberDiff line change
@@ -36,39 +36,40 @@ 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+
) -> Result<(), NoSolution> {
65+
let Some(host_clause) = assumption.as_host_effect_clause() else {
66+
panic!("fast_reject_assumption should have avoided this");
67+
};
68+
69+
let assumption_trait_pred = ecx.instantiate_binder_with_infer(host_clause);
70+
ecx.eq(goal.param_env, goal.predicate.trait_ref, assumption_trait_pred.trait_ref)?;
71+
72+
Ok(())
7273
}
7374

7475
/// Register additional assumptions for aliases corresponding to `~const` item bounds.
@@ -124,7 +125,7 @@ where
124125
fn consider_impl_candidate(
125126
ecx: &mut EvalCtxt<'_, D>,
126127
goal: Goal<I, Self>,
127-
impl_def_id: <I as Interner>::DefId,
128+
impl_def_id: I::DefId,
128129
) -> Result<Candidate<I>, NoSolution> {
129130
let cx = ecx.cx();
130131

@@ -178,7 +179,7 @@ where
178179

179180
fn consider_error_guaranteed_candidate(
180181
ecx: &mut EvalCtxt<'_, D>,
181-
_guar: <I as Interner>::ErrorGuaranteed,
182+
_guar: I::ErrorGuaranteed,
182183
) -> Result<Candidate<I>, NoSolution> {
183184
ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc)
184185
.enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes))

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

+8
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use tracing::{instrument, trace};
1919

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::{
@@ -1030,6 +1031,13 @@ where
10301031
self.delegate.resolve_vars_if_possible(value)
10311032
}
10321033

1034+
pub(super) fn eager_resolve<T>(&self, value: T) -> T
1035+
where
1036+
T: TypeFoldable<I>,
1037+
{
1038+
value.fold_with(&mut EagerResolver::new(self.delegate))
1039+
}
1040+
10331041
pub(super) fn fresh_args_for_item(&mut self, def_id: I::DefId) -> I::GenericArgs {
10341042
let args = self.delegate.fresh_args_for_item(def_id);
10351043
for arg in args.iter() {

0 commit comments

Comments
 (0)