Skip to content

Commit 50dde2e

Browse files
committed
Normalize when finding trait object candidates
1 parent 6c43a64 commit 50dde2e

File tree

5 files changed

+107
-66
lines changed

5 files changed

+107
-66
lines changed

compiler/rustc_middle/src/traits/select.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,10 @@ pub enum SelectionCandidate<'tcx> {
127127

128128
TraitAliasCandidate(DefId),
129129

130-
ObjectCandidate,
130+
/// Matching `dyn Trait` with a supertrait of `Trait`. The index is the
131+
/// position in the iterator returned by
132+
/// `rustc_infer::traits::util::supertraits`.
133+
ObjectCandidate(usize),
131134

132135
BuiltinObjectCandidate,
133136

compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs

+17-11
Original file line numberDiff line numberDiff line change
@@ -642,24 +642,30 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
642642

643643
debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
644644

645+
let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
646+
let placeholder_trait_predicate =
647+
self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
648+
645649
// Count only those upcast versions that match the trait-ref
646650
// we are looking for. Specifically, do not only check for the
647651
// correct trait, but also the correct type parameters.
648652
// For example, we may be trying to upcast `Foo` to `Bar<i32>`,
649653
// but `Foo` is declared as `trait Foo: Bar<u32>`.
650-
let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
651-
.filter(|upcast_trait_ref| {
652-
self.infcx
653-
.probe(|_| self.match_poly_trait_ref(obligation, *upcast_trait_ref).is_ok())
654+
let candidate_supertraits = util::supertraits(self.tcx(), poly_trait_ref)
655+
.enumerate()
656+
.filter(|&(_, upcast_trait_ref)| {
657+
self.infcx.probe(|_| {
658+
self.match_normalize_trait_ref(
659+
obligation,
660+
upcast_trait_ref,
661+
placeholder_trait_predicate.trait_ref,
662+
)
663+
.is_ok()
664+
})
654665
})
655-
.count();
666+
.map(|(idx, _)| ObjectCandidate(idx));
656667

657-
if upcast_trait_refs > 1 {
658-
// Can be upcast in many ways; need more type information.
659-
candidates.ambiguous = true;
660-
} else if upcast_trait_refs == 1 {
661-
candidates.vec.push(ObjectCandidate);
662-
}
668+
candidates.vec.extend(candidate_supertraits);
663669
})
664670
}
665671

compiler/rustc_trait_selection/src/traits/select/confirmation.rs

+38-41
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
7373
Ok(ImplSource::Param(obligations))
7474
}
7575

76+
ObjectCandidate(idx) => {
77+
let data = self.confirm_object_candidate(obligation, idx)?;
78+
Ok(ImplSource::Object(data))
79+
}
80+
7681
ClosureCandidate => {
7782
let vtable_closure = self.confirm_closure_candidate(obligation)?;
7883
Ok(ImplSource::Closure(vtable_closure))
@@ -97,11 +102,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
97102
Ok(ImplSource::TraitAlias(data))
98103
}
99104

100-
ObjectCandidate => {
101-
let data = self.confirm_object_candidate(obligation);
102-
Ok(ImplSource::Object(data))
103-
}
104-
105105
BuiltinObjectCandidate => {
106106
// This indicates something like `Trait + Send: Send`. In this case, we know that
107107
// this holds because that's what the object type is telling us, and there's really
@@ -365,9 +365,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
365365
fn confirm_object_candidate(
366366
&mut self,
367367
obligation: &TraitObligation<'tcx>,
368-
) -> ImplSourceObjectData<'tcx, PredicateObligation<'tcx>> {
369-
debug!(?obligation, "confirm_object_candidate");
368+
index: usize,
369+
) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
370370
let tcx = self.tcx();
371+
debug!(?obligation, ?index, "confirm_object_candidate");
371372

372373
let trait_predicate =
373374
self.infcx.replace_bound_vars_with_placeholders(&obligation.predicate);
@@ -393,43 +394,39 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
393394
})
394395
.with_self_ty(self.tcx(), self_ty);
395396

396-
let mut upcast_trait_ref = None;
397397
let mut nested = vec![];
398-
let vtable_base;
399398

400-
{
401-
// We want to find the first supertrait in the list of
402-
// supertraits that we can unify with, and do that
403-
// unification. We know that there is exactly one in the list
404-
// where we can unify, because otherwise select would have
405-
// reported an ambiguity. (When we do find a match, also
406-
// record it for later.)
407-
let nonmatching = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref))
408-
.take_while(|&t| {
409-
match self.infcx.commit_if_ok(|_| {
410-
self.infcx
411-
.at(&obligation.cause, obligation.param_env)
412-
.sup(obligation_trait_ref, t)
413-
.map(|InferOk { obligations, .. }| obligations)
414-
.map_err(|_| ())
415-
}) {
416-
Ok(obligations) => {
417-
upcast_trait_ref = Some(t);
418-
nested.extend(obligations);
419-
false
420-
}
421-
Err(_) => true,
422-
}
423-
});
399+
let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
424400

425-
// Additionally, for each of the non-matching predicates that
426-
// we pass over, we sum up the set of number of vtable
427-
// entries, so that we can compute the offset for the selected
428-
// trait.
429-
vtable_base = nonmatching.map(|t| super::util::count_own_vtable_entries(tcx, t)).sum();
430-
}
401+
// For each of the non-matching predicates that
402+
// we pass over, we sum up the set of number of vtable
403+
// entries, so that we can compute the offset for the selected
404+
// trait.
405+
let vtable_base = supertraits
406+
.by_ref()
407+
.take(index)
408+
.map(|t| super::util::count_own_vtable_entries(tcx, t))
409+
.sum();
410+
411+
let unnormalized_upcast_trait_ref =
412+
supertraits.next().expect("supertraits iterator no longer has as many elements");
413+
414+
let upcast_trait_ref = normalize_with_depth_to(
415+
self,
416+
obligation.param_env,
417+
obligation.cause.clone(),
418+
obligation.recursion_depth + 1,
419+
&unnormalized_upcast_trait_ref,
420+
&mut nested,
421+
);
431422

432-
let upcast_trait_ref = upcast_trait_ref.unwrap();
423+
nested.extend(self.infcx.commit_if_ok(|_| {
424+
self.infcx
425+
.at(&obligation.cause, obligation.param_env)
426+
.sup(obligation_trait_ref, upcast_trait_ref)
427+
.map(|InferOk { obligations, .. }| obligations)
428+
.map_err(|_| Unimplemented)
429+
})?);
433430

434431
// Check supertraits hold. This is so that their associated type bounds
435432
// will be checked in the code below.
@@ -495,7 +492,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
495492
}
496493

497494
debug!(?nested, "object nested obligations");
498-
ImplSourceObjectData { upcast_trait_ref, vtable_base, nested }
495+
Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
499496
}
500497

501498
fn confirm_fn_pointer_candidate(

compiler/rustc_trait_selection/src/traits/select/mod.rs

+11-13
Original file line numberDiff line numberDiff line change
@@ -1174,7 +1174,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
11741174
if let ty::PredicateAtom::Trait(pred, _) = bound_predicate.skip_binder() {
11751175
let bound = bound_predicate.rebind(pred.trait_ref);
11761176
if self.infcx.probe(|_| {
1177-
match self.match_projection(
1177+
match self.match_normalize_trait_ref(
11781178
obligation,
11791179
bound,
11801180
placeholder_trait_predicate.trait_ref,
@@ -1202,7 +1202,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
12021202
/// Equates the trait in `obligation` with trait bound. If the two traits
12031203
/// can be equated and the normalized trait bound doesn't contain inference
12041204
/// variables or placeholders, the normalized bound is returned.
1205-
fn match_projection(
1205+
fn match_normalize_trait_ref(
12061206
&mut self,
12071207
obligation: &TraitObligation<'tcx>,
12081208
trait_bound: ty::PolyTraitRef<'tcx>,
@@ -1352,10 +1352,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
13521352
| BuiltinUnsizeCandidate
13531353
| BuiltinCandidate { .. }
13541354
| TraitAliasCandidate(..)
1355-
| ObjectCandidate
1355+
| ObjectCandidate(_)
13561356
| ProjectionCandidate(_),
13571357
) => !is_global(cand),
1358-
(ObjectCandidate | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1358+
(ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
13591359
// Prefer these to a global where-clause bound
13601360
// (see issue #50825).
13611361
is_global(cand)
@@ -1376,20 +1376,20 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
13761376
is_global(cand) && other.evaluation.must_apply_modulo_regions()
13771377
}
13781378

1379-
(ProjectionCandidate(i), ProjectionCandidate(j)) => {
1379+
(ProjectionCandidate(i), ProjectionCandidate(j))
1380+
| (ObjectCandidate(i), ObjectCandidate(j)) => {
13801381
// Arbitrarily pick the lower numbered candidate for backwards
13811382
// compatibility reasons. Don't let this affect inference.
13821383
i < j && !needs_infer
13831384
}
1384-
(ObjectCandidate, ObjectCandidate) => bug!("Duplicate object candidate"),
1385-
(ObjectCandidate, ProjectionCandidate(_))
1386-
| (ProjectionCandidate(_), ObjectCandidate) => {
1385+
(ObjectCandidate(_), ProjectionCandidate(_))
1386+
| (ProjectionCandidate(_), ObjectCandidate(_)) => {
13871387
bug!("Have both object and projection candidate")
13881388
}
13891389

13901390
// Arbitrarily give projection and object candidates priority.
13911391
(
1392-
ObjectCandidate | ProjectionCandidate(_),
1392+
ObjectCandidate(_) | ProjectionCandidate(_),
13931393
ImplCandidate(..)
13941394
| ClosureCandidate
13951395
| GeneratorCandidate
@@ -1409,7 +1409,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
14091409
| BuiltinUnsizeCandidate
14101410
| BuiltinCandidate { .. }
14111411
| TraitAliasCandidate(..),
1412-
ObjectCandidate | ProjectionCandidate(_),
1412+
ObjectCandidate(_) | ProjectionCandidate(_),
14131413
) => false,
14141414

14151415
(&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
@@ -1885,9 +1885,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
18851885

18861886
/// Normalize `where_clause_trait_ref` and try to match it against
18871887
/// `obligation`. If successful, return any predicates that
1888-
/// result from the normalization. Normalization is necessary
1889-
/// because where-clauses are stored in the parameter environment
1890-
/// unnormalized.
1888+
/// result from the normalization.
18911889
fn match_where_clause_trait_ref(
18921890
&mut self,
18931891
obligation: &TraitObligation<'tcx>,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Regression test for #77653
2+
// When monomorphizing `f` we need to prove `dyn Derived<()>: Base<()>`. This
3+
// requires us to normalize the `Base<<() as Proj>::S>` to `Base<()>` when
4+
// comparing the supertrait `Derived<()>` to the expected trait.
5+
6+
// build-pass
7+
8+
trait Proj {
9+
type S;
10+
}
11+
12+
impl Proj for () {
13+
type S = ();
14+
}
15+
16+
impl Proj for i32 {
17+
type S = i32;
18+
}
19+
20+
trait Base<T> {
21+
fn is_base(&self);
22+
}
23+
24+
trait Derived<B: Proj>: Base<B::S> + Base<()> {
25+
fn is_derived(&self);
26+
}
27+
28+
fn f<P: Proj>(obj: &dyn Derived<P>) {
29+
obj.is_derived();
30+
Base::<P::S>::is_base(obj);
31+
Base::<()>::is_base(obj);
32+
}
33+
34+
fn main() {
35+
let x: fn(_) = f::<()>;
36+
let x: fn(_) = f::<i32>;
37+
}

0 commit comments

Comments
 (0)