Skip to content

Commit b420a66

Browse files
authored
Rollup merge of #163049 - estebank:dyn-compat-receiver, r=ShoyuVanilla
Tweak dyn compatibility error when pointing at receiver Account for receivers with arbitrary self types to suggest idiomatic code. ``` error[E0038]: the trait `Fetcher` is not dyn compatible --> $DIR/undispatchable-receiver-and-wc-references-Self.rs:19:21 | LL | fn fetcher() -> Box<dyn Fetcher> { | ^^^^^^^^^^^ `Fetcher` is not dyn compatible | note: for a trait to be dyn compatible it needs to allow building a vtable for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility> --> $DIR/undispatchable-receiver-and-wc-references-Self.rs:11:16 | LL | pub trait Fetcher: Send + Sync { | ------- this trait is not dyn compatible... LL | fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>> | ^^^^^^^^^^^^^^^^^^^ ...because method `get`'s `self` parameter cannot be dispatched on help: consider changing method `get`'s `self` parameter to be `&self` | LL - fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>> LL + fn get<'a>(&'a self) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>> | ``` Instead of ``` help: consider changing method `get`'s `self` parameter to be `&self` | LL - fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>> LL + fn get<'a>(self: &Self) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>> | ```
2 parents 88638df + 41fede0 commit b420a66

10 files changed

Lines changed: 98 additions & 57 deletions

‎compiler/rustc_middle/src/traits/mod.rs‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use rustc_macros::{
2121
Decodable, Encodable, StableHash, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
2222
};
2323
use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId};
24-
use rustc_span::{DUMMY_SP, Span, Symbol};
24+
use rustc_span::{DUMMY_SP, Span, Symbol, sym};
2525
use smallvec::{SmallVec, smallvec};
2626
use thin_vec::ThinVec;
2727

@@ -870,8 +870,8 @@ impl DynCompatibilityViolation {
870870
add_self_sugg: add_self_sugg.clone(),
871871
make_sized_sugg: make_sized_sugg.clone(),
872872
},
873-
Self::Method(name, MethodViolation::UndispatchableReceiver(Some(span)), _) => {
874-
DynCompatibilityViolationSolution::ChangeToRefSelf(*name, *span)
873+
Self::Method(name, MethodViolation::UndispatchableReceiver(Some((span, lt))), _) => {
874+
DynCompatibilityViolationSolution::ChangeToRefSelf(*name, *span, *lt)
875875
}
876876
Self::Method(name, ..) | Self::AssocConst(name, ..) | Self::GenericAssocTy(name, _) => {
877877
DynCompatibilityViolationSolution::MoveToAnotherTrait(*name)
@@ -909,7 +909,7 @@ pub enum DynCompatibilityViolationSolution {
909909
add_self_sugg: (String, Span),
910910
make_sized_sugg: (String, Span),
911911
},
912-
ChangeToRefSelf(Symbol, Span),
912+
ChangeToRefSelf(Symbol, Span, Symbol),
913913
MoveToAnotherTrait(Symbol),
914914
}
915915

@@ -922,30 +922,30 @@ impl DynCompatibilityViolationSolution {
922922
add_self_sugg,
923923
make_sized_sugg,
924924
} => {
925-
err.span_suggestion(
925+
err.span_suggestion_verbose(
926926
add_self_sugg.1,
927927
format!(
928-
"consider turning `{name}` into a method by giving it a `&self` \
929-
argument, so that it is accessible through the trait object's vtable"
928+
"consider turning `{name}` into a method by giving it a `&self` argument, \
929+
so that it is accessible through the trait object's vtable",
930930
),
931931
add_self_sugg.0,
932932
Applicability::MaybeIncorrect,
933933
);
934-
err.span_suggestion(
934+
err.span_suggestion_verbose(
935935
make_sized_sugg.1,
936936
format!(
937-
"alternatively, consider constraining `{name}` so it is explicitly \
938-
marked as not applying to trait objects"
937+
"alternatively, consider constraining `{name}` so it is explicitly marked \
938+
as not applying to trait objects",
939939
),
940940
make_sized_sugg.0,
941941
Applicability::MaybeIncorrect,
942942
);
943943
}
944-
DynCompatibilityViolationSolution::ChangeToRefSelf(name, span) => {
945-
err.span_suggestion(
944+
DynCompatibilityViolationSolution::ChangeToRefSelf(name, span, lt) => {
945+
err.span_suggestion_verbose(
946946
span,
947947
format!("consider changing method `{name}`'s `self` parameter to be `&self`"),
948-
"&Self",
948+
format!("&{lt}{}self", if lt != sym::empty { " " } else { "" }),
949949
Applicability::MachineApplicable,
950950
);
951951
}
@@ -983,8 +983,11 @@ pub enum MethodViolation {
983983
/// e.g., `fn (mut ap: ...)`
984984
CVariadic,
985985

986-
/// the method's receiver (`self` argument) can't be dispatched on
987-
UndispatchableReceiver(Option<Span>),
986+
/// The method's receiver (`self` argument) can't be dispatched on
987+
///
988+
/// The `Span` points at the receiver. The `Symbol` is the lifetime's name `'a` when we have
989+
/// Arbitrary Self Types like `self: &'a ()`.
990+
UndispatchableReceiver(Option<(Span, Symbol)>),
988991
}
989992

990993
/// Reasons an associated const might not be dyn compatible.

‎compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use rustc_middle::ty::{
1616
TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
1717
Upcast, elaborate,
1818
};
19-
use rustc_span::{DUMMY_SP, Span};
19+
use rustc_span::{DUMMY_SP, Span, kw, sym};
2020
use smallvec::SmallVec;
2121
use tracing::{debug, instrument};
2222

@@ -403,7 +403,7 @@ pub fn dyn_compatibility_violations_for_assoc_item(
403403
// Get an accurate span depending on the violation.
404404
let span = match (&v, node) {
405405
(MethodViolation::ReferencesSelfInput(Some(span)), _) => *span,
406-
(MethodViolation::UndispatchableReceiver(Some(span)), _) => *span,
406+
(MethodViolation::UndispatchableReceiver(Some((span, _))), _) => *span,
407407
(MethodViolation::ReferencesImplTraitInTrait(span), _) => *span,
408408
(MethodViolation::ReferencesSelfOutput, Some(node)) => {
409409
node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
@@ -519,16 +519,40 @@ fn virtual_call_violations_for_method<'tcx>(
519519
// `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
520520
if receiver_ty != tcx.types.self_param {
521521
if !receiver_is_dispatchable(tcx, method, receiver_ty) {
522-
let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
523-
kind: hir::TraitItemKind::Fn(sig, _),
522+
let span_n_lt = if let Some(hir::Node::TraitItem(hir::TraitItem {
523+
kind: hir::TraitItemKind::Fn(sig, trait_fn),
524524
..
525525
})) = tcx.hir_get_if_local(method.def_id).as_ref()
526526
{
527-
Some(sig.decl.inputs[0].span)
527+
// If we have `self: &'a Ty`, get `'a`, so that we can suggest `&'a self`.
528+
let lt = match sig.decl.inputs[0].kind {
529+
hir::TyKind::Ref(lt, _) if lt.ident.name == kw::UnderscoreLifetime => {
530+
sym::empty
531+
}
532+
hir::TyKind::Ref(lt, _) => lt.ident.name,
533+
_ => sym::empty,
534+
};
535+
// Get the `Span` for all of `self: Ty`, not just `Ty`.
536+
match trait_fn {
537+
hir::TraitFn::Required([Some(name), ..])
538+
if name.span.eq_ctxt(sig.decl.inputs[0].span) =>
539+
{
540+
Some(name.span.to(sig.decl.inputs[0].span))
541+
}
542+
hir::TraitFn::Provided(body_id)
543+
if let body = tcx.hir_body(*body_id)
544+
&& let Some(p) = body.params.get(0)
545+
&& p.span.eq_ctxt(p.ty_span) =>
546+
{
547+
Some(p.span.to(p.ty_span))
548+
}
549+
_ => None,
550+
}
551+
.map(|sp| (sp, lt))
528552
} else {
529553
None
530554
};
531-
errors.push(MethodViolation::UndispatchableReceiver(span));
555+
errors.push(MethodViolation::UndispatchableReceiver(span_n_lt));
532556
} else {
533557
// We confirm that the `receiver_is_dispatchable` is accurate later,
534558
// see `check_receiver_correct`. It should be kept in sync with this code.

‎tests/ui/dyn-compatibility/undispatchable-receiver-and-wc-references-Self.stderr‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,42 @@
11
error[E0038]: the trait `Fetcher` is not dyn compatible
22
--> $DIR/undispatchable-receiver-and-wc-references-Self.rs:19:21
33
|
4-
LL | fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
5-
| ------------- help: consider changing method `get`'s `self` parameter to be `&self`: `&Self`
6-
...
74
LL | fn fetcher() -> Box<dyn Fetcher> {
85
| ^^^^^^^^^^^ `Fetcher` is not dyn compatible
96
|
107
note: for a trait to be dyn compatible it needs to allow building a vtable
118
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
12-
--> $DIR/undispatchable-receiver-and-wc-references-Self.rs:11:22
9+
--> $DIR/undispatchable-receiver-and-wc-references-Self.rs:11:16
1310
|
1411
LL | pub trait Fetcher: Send + Sync {
1512
| ------- this trait is not dyn compatible...
1613
LL | fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
17-
| ^^^^^^^^^^^^^ ...because method `get`'s `self` parameter cannot be dispatched on
14+
| ^^^^^^^^^^^^^^^^^^^ ...because method `get`'s `self` parameter cannot be dispatched on
15+
help: consider changing method `get`'s `self` parameter to be `&self`
16+
|
17+
LL - fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
18+
LL + fn get<'a>(&'a self) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
19+
|
1820

1921
error[E0038]: the trait `Fetcher` is not dyn compatible
2022
--> $DIR/undispatchable-receiver-and-wc-references-Self.rs:25:19
2123
|
22-
LL | fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
23-
| ------------- help: consider changing method `get`'s `self` parameter to be `&self`: `&Self`
24-
...
2524
LL | let fetcher = fetcher();
2625
| ^^^^^^^^^ `Fetcher` is not dyn compatible
2726
|
2827
note: for a trait to be dyn compatible it needs to allow building a vtable
2928
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
30-
--> $DIR/undispatchable-receiver-and-wc-references-Self.rs:11:22
29+
--> $DIR/undispatchable-receiver-and-wc-references-Self.rs:11:16
3130
|
3231
LL | pub trait Fetcher: Send + Sync {
3332
| ------- this trait is not dyn compatible...
3433
LL | fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
35-
| ^^^^^^^^^^^^^ ...because method `get`'s `self` parameter cannot be dispatched on
34+
| ^^^^^^^^^^^^^^^^^^^ ...because method `get`'s `self` parameter cannot be dispatched on
35+
help: consider changing method `get`'s `self` parameter to be `&self`
36+
|
37+
LL - fn get<'a>(self: &'a Box<Self>) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
38+
LL + fn get<'a>(&'a self) -> Pin<Box<dyn Future<Output = Vec<u8>> + 'a>>
39+
|
3640

3741
error: aborting due to 2 previous errors
3842

‎tests/ui/dyn-compatibility/unsafe-binders-bare-trait-object-next-solver.stderr‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,22 @@ LL | fn method(self: &unsafe<'ops> &'a dyn Bar) {}
3232
error[E0038]: the trait `Foo` is not dyn compatible
3333
--> $DIR/unsafe-binders-bare-trait-object-next-solver.rs:17:13
3434
|
35-
LL | fn method(self: &unsafe<'ops> &'a Bar) {}
36-
| --------------------- help: consider changing method `method`'s `self` parameter to be `&self`: `&Self`
37-
...
3835
LL | fn test(x: &dyn Foo) {
3936
| ^^^^^^^ `Foo` is not dyn compatible
4037
|
4138
note: for a trait to be dyn compatible it needs to allow building a vtable
4239
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
43-
--> $DIR/unsafe-binders-bare-trait-object-next-solver.rs:10:21
40+
--> $DIR/unsafe-binders-bare-trait-object-next-solver.rs:10:15
4441
|
4542
LL | trait Foo: Deref<Target = unsafe<'a> &'a dyn Bar> {
4643
| --- this trait is not dyn compatible...
4744
LL | fn method(self: &unsafe<'ops> &'a Bar) {}
48-
| ^^^^^^^^^^^^^^^^^^^^^ ...because method `method`'s `self` parameter cannot be dispatched on
45+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...because method `method`'s `self` parameter cannot be dispatched on
46+
help: consider changing method `method`'s `self` parameter to be `&self`
47+
|
48+
LL - fn method(self: &unsafe<'ops> &'a Bar) {}
49+
LL + fn method(&self) {}
50+
|
4951

5052
error[E0599]: no method named `method` found for reference `&dyn Foo` in the current scope
5153
--> $DIR/unsafe-binders-bare-trait-object-next-solver.rs:19:7

‎tests/ui/feature-gates/feature-gate-dispatch-from-dyn-missing-impl.stderr‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
error[E0038]: the trait `Trait` is not dyn compatible
22
--> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:32:33
33
|
4-
LL | fn ptr(self: Ptr<Self>);
5-
| --------- help: consider changing method `ptr`'s `self` parameter to be `&self`: `&Self`
6-
...
74
LL | Ptr(Box::new(4)) as Ptr<dyn Trait>;
85
| ^^^^^ `Trait` is not dyn compatible
96
|
107
note: for a trait to be dyn compatible it needs to allow building a vtable
118
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
12-
--> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:25:18
9+
--> $DIR/feature-gate-dispatch-from-dyn-missing-impl.rs:25:12
1310
|
1411
LL | trait Trait {
1512
| ----- this trait is not dyn compatible...
1613
LL | fn ptr(self: Ptr<Self>);
17-
| ^^^^^^^^^ ...because method `ptr`'s `self` parameter cannot be dispatched on
14+
| ^^^^^^^^^^^^^^^ ...because method `ptr`'s `self` parameter cannot be dispatched on
1815
= help: only type `i32` implements `Trait`; consider using it directly instead.
16+
help: consider changing method `ptr`'s `self` parameter to be `&self`
17+
|
18+
LL - fn ptr(self: Ptr<Self>);
19+
LL + fn ptr(&self);
20+
|
1921

2022
error: aborting due to 1 previous error
2123

‎tests/ui/self/arbitrary-self-types-dyn-incompatible.stderr‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
error[E0038]: the trait `Foo` is not dyn compatible
22
--> $DIR/arbitrary-self-types-dyn-incompatible.rs:29:39
33
|
4-
LL | fn foo(self: &Rc<Self>) -> usize;
5-
| --------- help: consider changing method `foo`'s `self` parameter to be `&self`: `&Self`
6-
...
74
LL | let x = Rc::new(5usize) as Rc<dyn Foo>;
85
| ^^^ `Foo` is not dyn compatible
96
|
107
note: for a trait to be dyn compatible it needs to allow building a vtable
118
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
12-
--> $DIR/arbitrary-self-types-dyn-incompatible.rs:4:18
9+
--> $DIR/arbitrary-self-types-dyn-incompatible.rs:4:12
1310
|
1411
LL | trait Foo {
1512
| --- this trait is not dyn compatible...
1613
LL | fn foo(self: &Rc<Self>) -> usize;
17-
| ^^^^^^^^^ ...because method `foo`'s `self` parameter cannot be dispatched on
14+
| ^^^^^^^^^^^^^^^ ...because method `foo`'s `self` parameter cannot be dispatched on
1815
= help: only type `usize` implements `Foo`; consider using it directly instead.
16+
help: consider changing method `foo`'s `self` parameter to be `&self`
17+
|
18+
LL - fn foo(self: &Rc<Self>) -> usize;
19+
LL + fn foo(&self) -> usize;
20+
|
1921

2022
error: aborting due to 1 previous error
2123

‎tests/ui/self/dispatch-dyn-incompatible-that-does-not-deref.stderr‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
error[E0038]: the trait `Foo` is not dyn compatible
22
--> $DIR/dispatch-dyn-incompatible-that-does-not-deref.rs:12:13
33
|
4-
LL | fn method(self: &W) {}
5-
| -- help: consider changing method `method`'s `self` parameter to be `&self`: `&Self`
6-
...
74
LL | fn test(x: &dyn Foo) {
85
| ^^^^^^^ `Foo` is not dyn compatible
96
|
107
note: for a trait to be dyn compatible it needs to allow building a vtable
118
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
12-
--> $DIR/dispatch-dyn-incompatible-that-does-not-deref.rs:8:21
9+
--> $DIR/dispatch-dyn-incompatible-that-does-not-deref.rs:8:15
1310
|
1411
LL | trait Foo: Deref<Target = W> {
1512
| --- this trait is not dyn compatible...
1613
LL | fn method(self: &W) {}
17-
| ^^ ...because method `method`'s `self` parameter cannot be dispatched on
14+
| ^^^^^^^^ ...because method `method`'s `self` parameter cannot be dispatched on
15+
help: consider changing method `method`'s `self` parameter to be `&self`
16+
|
17+
LL - fn method(self: &W) {}
18+
LL + fn method(&self) {}
19+
|
1820

1921
error[E0307]: invalid `self` parameter type: `&W`
2022
--> $DIR/dispatch-dyn-incompatible-that-does-not-deref.rs:8:21

‎tests/ui/suggestions/dyn-incompatible-trait-should-use-where-sized.fixed‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
trait Trait {
55
fn foo(&self) where Self: Other, Self: Sized { }
6-
fn bar(self: &Self) {} //~ ERROR invalid `self` parameter type
6+
fn bar(&self) {} //~ ERROR invalid `self` parameter type
77
}
88

99
fn bar(x: &dyn Trait) {} //~ ERROR the trait `Trait` is not dyn compatible

‎tests/ui/suggestions/dyn-incompatible-trait-should-use-where-sized.stderr‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ LL | trait Trait {
1313
LL | fn foo() where Self: Other, { }
1414
| ^^^ ...because associated function `foo` has no `self` parameter
1515
LL | fn bar(self: ()) {}
16-
| ^^ ...because method `bar`'s `self` parameter cannot be dispatched on
16+
| ^^^^^^^^ ...because method `bar`'s `self` parameter cannot be dispatched on
1717
help: consider turning `foo` into a method by giving it a `&self` argument, so that it is accessible through the trait object's vtable
1818
|
1919
LL | fn foo(&self) where Self: Other, { }
@@ -25,7 +25,7 @@ LL | fn foo() where Self: Other, Self: Sized { }
2525
help: consider changing method `bar`'s `self` parameter to be `&self`
2626
|
2727
LL - fn bar(self: ()) {}
28-
LL + fn bar(self: &Self) {}
28+
LL + fn bar(&self) {}
2929
|
3030

3131
error[E0307]: invalid `self` parameter type: `()`

‎tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.stderr‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,6 @@ LL | impl LeakTr for LeakS {}
1919
error[E0038]: the trait `DynCompatCheck2` is not dyn compatible
2020
--> $DIR/maybe-bounds-in-dyn-traits.rs:90:17
2121
|
22-
LL | fn mut_foo(&mut self) {}
23-
| --------- help: consider changing method `mut_foo`'s `self` parameter to be `&self`: `&Self`
24-
...
2522
LL | let _: &dyn DynCompatCheck2 = &NonLeakS;
2623
| ^^^^^^^^^^^^^^^ `DynCompatCheck2` is not dyn compatible
2724
|
@@ -34,6 +31,11 @@ LL | trait DynCompatCheck2: ?Leak {
3431
LL | fn mut_foo(&mut self) {}
3532
| ^^^^^^^^^ ...because method `mut_foo`'s `self` parameter cannot be dispatched on
3633
= help: only type `NonLeakS` implements `DynCompatCheck2`; consider using it directly instead.
34+
help: consider changing method `mut_foo`'s `self` parameter to be `&self`
35+
|
36+
LL - fn mut_foo(&mut self) {}
37+
LL + fn mut_foo(&self) {}
38+
|
3739

3840
error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplied
3941
--> $DIR/maybe-bounds-in-dyn-traits.rs:98:26

0 commit comments

Comments
 (0)