Skip to content

Commit 6471682

Browse files
authored
Rollup merge of #92191 - jackh726:issue-89352, r=nikomatsakis
Prefer projection candidates instead of param_env candidates for Sized predicates Fixes #89352 Also includes some drive by logging and verbose printing changes that I found useful when debugging this, but I can remove this if needed. This is a little hacky - but imo no more than the rest of `candidate_should_be_dropped_in_favor_of`. Importantly, in a Chalk-like world, both candidates should be completely compatible. r? ```@nikomatsakis```
2 parents b0ec3e0 + d3aecc1 commit 6471682

File tree

13 files changed

+84
-34
lines changed

13 files changed

+84
-34
lines changed

compiler/rustc_infer/src/traits/util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ impl<'tcx> Elaborator<'tcx> {
152152
obligation.cause.clone(),
153153
)
154154
});
155-
debug!("super_predicates: data={:?}", data);
155+
debug!(?data, ?obligations, "super_predicates");
156156

157157
// Only keep those bounds that we haven't already seen.
158158
// This is necessary to prevent infinite recursion in some

compiler/rustc_middle/src/ty/print/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,11 @@ pub trait Printer<'tcx>: Sized {
188188
own_params.start = 1;
189189
}
190190

191+
// If we're in verbose mode, then print default-equal args too
192+
if self.tcx().sess.verbose() {
193+
return &substs[own_params];
194+
}
195+
191196
// Don't print args that are the defaults of their respective parameters.
192197
own_params.end -= generics
193198
.params

compiler/rustc_middle/src/ty/print/pretty.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -1784,10 +1784,11 @@ impl<'tcx, F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
17841784
self = print_prefix(self)?;
17851785

17861786
// Don't print `'_` if there's no unerased regions.
1787-
let print_regions = args.iter().any(|arg| match arg.unpack() {
1788-
GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1789-
_ => false,
1790-
});
1787+
let print_regions = self.tcx.sess.verbose()
1788+
|| args.iter().any(|arg| match arg.unpack() {
1789+
GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1790+
_ => false,
1791+
});
17911792
let args = args.iter().cloned().filter(|arg| match arg.unpack() {
17921793
GenericArgKind::Lifetime(_) => print_regions,
17931794
_ => true,

compiler/rustc_trait_selection/src/traits/project.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -1225,6 +1225,10 @@ fn assemble_candidates_from_object_ty<'cx, 'tcx>(
12251225
);
12261226
}
12271227

1228+
#[tracing::instrument(
1229+
level = "debug",
1230+
skip(selcx, candidate_set, ctor, env_predicates, potentially_unnormalized_candidates)
1231+
)]
12281232
fn assemble_candidates_from_predicates<'cx, 'tcx>(
12291233
selcx: &mut SelectionContext<'cx, 'tcx>,
12301234
obligation: &ProjectionTyObligation<'tcx>,
@@ -1233,8 +1237,6 @@ fn assemble_candidates_from_predicates<'cx, 'tcx>(
12331237
env_predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
12341238
potentially_unnormalized_candidates: bool,
12351239
) {
1236-
debug!(?obligation, "assemble_candidates_from_predicates");
1237-
12381240
let infcx = selcx.infcx();
12391241
for predicate in env_predicates {
12401242
debug!(?predicate);
@@ -1270,13 +1272,12 @@ fn assemble_candidates_from_predicates<'cx, 'tcx>(
12701272
}
12711273
}
12721274

1275+
#[tracing::instrument(level = "debug", skip(selcx, obligation, candidate_set))]
12731276
fn assemble_candidates_from_impls<'cx, 'tcx>(
12741277
selcx: &mut SelectionContext<'cx, 'tcx>,
12751278
obligation: &ProjectionTyObligation<'tcx>,
12761279
candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
12771280
) {
1278-
debug!("assemble_candidates_from_impls");
1279-
12801281
// If we are resolving `<T as TraitRef<...>>::Item == Type`,
12811282
// start out by selecting the predicate `T as TraitRef<...>`:
12821283
let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx()));

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

+10-6
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
173173

174174
let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
175175

176+
let sized_predicate = self.tcx().lang_items().sized_trait()
177+
== Some(stack.obligation.predicate.skip_binder().def_id());
178+
176179
// If there are STILL multiple candidates, we can further
177180
// reduce the list by dropping duplicates -- including
178181
// resolving specializations.
@@ -181,6 +184,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
181184
while i < candidates.len() {
182185
let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
183186
self.candidate_should_be_dropped_in_favor_of(
187+
sized_predicate,
184188
&candidates[i],
185189
&candidates[j],
186190
needs_infer,
@@ -338,13 +342,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
338342
Ok(candidates)
339343
}
340344

345+
#[tracing::instrument(level = "debug", skip(self, candidates))]
341346
fn assemble_candidates_from_projected_tys(
342347
&mut self,
343348
obligation: &TraitObligation<'tcx>,
344349
candidates: &mut SelectionCandidateSet<'tcx>,
345350
) {
346-
debug!(?obligation, "assemble_candidates_from_projected_tys");
347-
348351
// Before we go into the whole placeholder thing, just
349352
// quickly check if the self-type is a projection at all.
350353
match obligation.predicate.skip_binder().trait_ref.self_ty().kind() {
@@ -369,12 +372,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
369372
/// supplied to find out whether it is listed among them.
370373
///
371374
/// Never affects the inference environment.
375+
#[tracing::instrument(level = "debug", skip(self, stack, candidates))]
372376
fn assemble_candidates_from_caller_bounds<'o>(
373377
&mut self,
374378
stack: &TraitObligationStack<'o, 'tcx>,
375379
candidates: &mut SelectionCandidateSet<'tcx>,
376380
) -> Result<(), SelectionError<'tcx>> {
377-
debug!(?stack.obligation, "assemble_candidates_from_caller_bounds");
381+
debug!(?stack.obligation);
378382

379383
let all_bounds = stack
380384
.obligation
@@ -876,14 +880,15 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
876880
};
877881
}
878882

883+
#[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
879884
fn assemble_candidates_for_trait_alias(
880885
&mut self,
881886
obligation: &TraitObligation<'tcx>,
882887
candidates: &mut SelectionCandidateSet<'tcx>,
883888
) {
884889
// Okay to skip binder here because the tests we do below do not involve bound regions.
885890
let self_ty = obligation.self_ty().skip_binder();
886-
debug!(?self_ty, "assemble_candidates_for_trait_alias");
891+
debug!(?self_ty);
887892

888893
let def_id = obligation.predicate.def_id();
889894

@@ -894,21 +899,20 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
894899

895900
/// Assembles the trait which are built-in to the language itself:
896901
/// `Copy`, `Clone` and `Sized`.
902+
#[tracing::instrument(level = "debug", skip(self, candidates))]
897903
fn assemble_builtin_bound_candidates(
898904
&mut self,
899905
conditions: BuiltinImplConditions<'tcx>,
900906
candidates: &mut SelectionCandidateSet<'tcx>,
901907
) {
902908
match conditions {
903909
BuiltinImplConditions::Where(nested) => {
904-
debug!(?nested, "builtin_bound");
905910
candidates
906911
.vec
907912
.push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
908913
}
909914
BuiltinImplConditions::None => {}
910915
BuiltinImplConditions::Ambiguous => {
911-
debug!("assemble_builtin_bound_candidates: ambiguous builtin");
912916
candidates.ambiguous = true;
913917
}
914918
}

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

+14-9
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ struct EvaluatedCandidate<'tcx> {
201201
}
202202

203203
/// When does the builtin impl for `T: Trait` apply?
204+
#[derive(Debug)]
204205
enum BuiltinImplConditions<'tcx> {
205206
/// The impl is conditional on `T1, T2, ...: Trait`.
206207
Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
@@ -344,7 +345,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
344345
}
345346
Err(e) => Err(e),
346347
Ok(candidate) => {
347-
debug!(?candidate);
348+
debug!(?candidate, "confirmed");
348349
Ok(Some(candidate))
349350
}
350351
}
@@ -1523,6 +1524,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
15231524
/// See the comment for "SelectionCandidate" for more details.
15241525
fn candidate_should_be_dropped_in_favor_of(
15251526
&mut self,
1527+
sized_predicate: bool,
15261528
victim: &EvaluatedCandidate<'tcx>,
15271529
other: &EvaluatedCandidate<'tcx>,
15281530
needs_infer: bool,
@@ -1594,6 +1596,16 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
15941596
// Drop otherwise equivalent non-const fn pointer candidates
15951597
(FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
15961598

1599+
// If obligation is a sized predicate or the where-clause bound is
1600+
// global, prefer the projection or object candidate. See issue
1601+
// #50825 and #89352.
1602+
(ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1603+
sized_predicate || is_global(cand)
1604+
}
1605+
(ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => {
1606+
!(sized_predicate || is_global(cand))
1607+
}
1608+
15971609
// Global bounds from the where clause should be ignored
15981610
// here (see issue #50825). Otherwise, we have a where
15991611
// clause so don't go around looking for impls.
@@ -1609,15 +1621,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
16091621
| BuiltinUnsizeCandidate
16101622
| TraitUpcastingUnsizeCandidate(_)
16111623
| BuiltinCandidate { .. }
1612-
| TraitAliasCandidate(..)
1613-
| ObjectCandidate(_)
1614-
| ProjectionCandidate(_),
1624+
| TraitAliasCandidate(..),
16151625
) => !is_global(cand),
1616-
(ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
1617-
// Prefer these to a global where-clause bound
1618-
// (see issue #50825).
1619-
is_global(cand)
1620-
}
16211626
(
16221627
ImplCandidate(_)
16231628
| ClosureCandidate

compiler/rustc_typeck/src/astconv/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
288288
/// Given the type/lifetime/const arguments provided to some path (along with
289289
/// an implicit `Self`, if this is a trait reference), returns the complete
290290
/// set of substitutions. This may involve applying defaulted type parameters.
291-
/// Also returns back constraints on associated types.
291+
/// Constraints on associated typess are created from `create_assoc_bindings_for_generic_args`.
292292
///
293293
/// Example:
294294
///
@@ -302,7 +302,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
302302
/// which will have been resolved to a `def_id`
303303
/// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
304304
/// parameters are returned in the `SubstsRef`, the associated type bindings like
305-
/// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
305+
/// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
306306
///
307307
/// Note that the type listing given here is *exactly* what the user provided.
308308
///

compiler/rustc_typeck/src/check/method/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
359359
let (obligation, substs) =
360360
self.obligation_for_method(span, trait_def_id, self_ty, opt_input_types);
361361

362+
debug!(?obligation);
363+
362364
// Now we want to know if this can be matched
363365
if !self.predicate_may_hold(&obligation) {
364366
debug!("--> Cannot match obligation");

src/test/ui/associated-types/substs-ppaux.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ fn foo<'z>() where &'z (): Sized {
2525
let x: () = <i8 as Foo<'static, 'static, u32>>::bar::<'static, char>;
2626
//[verbose]~^ ERROR mismatched types
2727
//[verbose]~| expected unit type `()`
28-
//[verbose]~| found fn item `fn() {<i8 as Foo<ReStatic, ReStatic>>::bar::<ReStatic, char>}`
28+
//[verbose]~| found fn item `fn() {<i8 as Foo<ReStatic, ReStatic, u32>>::bar::<ReStatic, char>}`
2929
//[normal]~^^^^ ERROR mismatched types
3030
//[normal]~| expected unit type `()`
3131
//[normal]~| found fn item `fn() {<i8 as Foo<'static, 'static>>::bar::<'static, char>}`

src/test/ui/associated-types/substs-ppaux.verbose.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@ error[E0308]: mismatched types
2020
--> $DIR/substs-ppaux.rs:25:17
2121
|
2222
LL | fn bar<'a, T>() where T: 'a {}
23-
| --------------------------- fn() {<i8 as Foo<ReStatic, ReStatic>>::bar::<ReStatic, char>} defined here
23+
| --------------------------- fn() {<i8 as Foo<ReStatic, ReStatic, u32>>::bar::<ReStatic, char>} defined here
2424
...
2525
LL | let x: () = <i8 as Foo<'static, 'static, u32>>::bar::<'static, char>;
2626
| -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found fn item
2727
| |
2828
| expected due to this
2929
|
3030
= note: expected unit type `()`
31-
found fn item `fn() {<i8 as Foo<ReStatic, ReStatic>>::bar::<ReStatic, char>}`
31+
found fn item `fn() {<i8 as Foo<ReStatic, ReStatic, u32>>::bar::<ReStatic, char>}`
3232
help: use parentheses to call this function
3333
|
3434
LL | let x: () = <i8 as Foo<'static, 'static, u32>>::bar::<'static, char>();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// check-pass
2+
3+
#![feature(generic_associated_types)]
4+
5+
use std::marker::PhantomData;
6+
7+
pub trait GenAssoc<T> {
8+
type Iter<'at>;
9+
fn iter(&self) -> Self::Iter<'_>;
10+
fn reborrow<'longt: 'shortt, 'shortt>(iter: Self::Iter<'longt>) -> Self::Iter<'shortt>;
11+
}
12+
13+
pub struct Wrapper<'a, T: 'a, A: GenAssoc<T>> {
14+
a: A::Iter<'a>,
15+
_p: PhantomData<T>,
16+
}
17+
18+
impl<'ai, T: 'ai, A: GenAssoc<T>> GenAssoc<T> for Wrapper<'ai, T, A>
19+
where
20+
A::Iter<'ai>: Clone,
21+
{
22+
type Iter<'b> = ();
23+
fn iter<'s>(&'s self) -> Self::Iter<'s> {
24+
let a = A::reborrow::<'ai, 's>(self.a.clone());
25+
}
26+
27+
fn reborrow<'long: 'short, 'short>(iter: Self::Iter<'long>) -> Self::Iter<'short> {
28+
()
29+
}
30+
}
31+
32+
fn main() {}

src/test/ui/nll/ty-outlives/projection-no-regions-closure.stderr

+4-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ LL | with_signature(x, |mut y| Box::new(y.next()))
66
|
77
= note: defining type: no_region::<'_#1r, T>::{closure#0} with closure substs [
88
i32,
9-
extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '_#2r)>,
9+
extern "rust-call" fn((std::boxed::Box<T, std::alloc::Global>,)) -> std::boxed::Box<(dyn Anything + '_#2r), std::alloc::Global>,
1010
(),
1111
]
1212
= note: number of external vids: 3
@@ -42,7 +42,7 @@ LL | with_signature(x, |mut y| Box::new(y.next()))
4242
|
4343
= note: defining type: correct_region::<'_#1r, T>::{closure#0} with closure substs [
4444
i32,
45-
extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '_#2r)>,
45+
extern "rust-call" fn((std::boxed::Box<T, std::alloc::Global>,)) -> std::boxed::Box<(dyn Anything + '_#2r), std::alloc::Global>,
4646
(),
4747
]
4848
= note: number of external vids: 3
@@ -69,7 +69,7 @@ LL | with_signature(x, |mut y| Box::new(y.next()))
6969
|
7070
= note: defining type: wrong_region::<'_#1r, '_#2r, T>::{closure#0} with closure substs [
7171
i32,
72-
extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '_#3r)>,
72+
extern "rust-call" fn((std::boxed::Box<T, std::alloc::Global>,)) -> std::boxed::Box<(dyn Anything + '_#3r), std::alloc::Global>,
7373
(),
7474
]
7575
= note: number of external vids: 4
@@ -105,7 +105,7 @@ LL | with_signature(x, |mut y| Box::new(y.next()))
105105
|
106106
= note: defining type: outlives_region::<'_#1r, '_#2r, T>::{closure#0} with closure substs [
107107
i32,
108-
extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '_#3r)>,
108+
extern "rust-call" fn((std::boxed::Box<T, std::alloc::Global>,)) -> std::boxed::Box<(dyn Anything + '_#3r), std::alloc::Global>,
109109
(),
110110
]
111111
= note: number of external vids: 4

src/test/ui/nll/ty-outlives/ty-param-closure-outlives-from-return-type.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ LL | with_signature(x, |y| y)
66
|
77
= note: defining type: no_region::<'_#1r, T>::{closure#0} with closure substs [
88
i32,
9-
extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn std::fmt::Debug + '_#2r)>,
9+
extern "rust-call" fn((std::boxed::Box<T, std::alloc::Global>,)) -> std::boxed::Box<(dyn std::fmt::Debug + '_#2r), std::alloc::Global>,
1010
(),
1111
]
1212
= note: number of external vids: 3

0 commit comments

Comments
 (0)