Skip to content

Commit fad04ff

Browse files
authoredMay 18, 2021
Rollup merge of #85369 - FabianWolff:issue-84973, r=jackh726
Suggest borrowing if a trait implementation is found for &/&mut <type> This pull request fixes #84973 by suggesting to borrow if a trait is not implemented for some type `T`, but it is for `&T` or `&mut T`. For instance: ```rust trait Ti {} impl<T> Ti for &T {} fn foo<T: Ti>(_: T) {} trait Tm {} impl<T> Tm for &mut T {} fn bar<T: Tm>(_: T) {} fn main() { let a: i32 = 5; foo(a); let b: Box<i32> = Box::new(42); bar(b); } ``` gives, on current nightly: ``` error[E0277]: the trait bound `i32: Ti` is not satisfied --> t2.rs:11:9 | 3 | fn foo<T: Ti>(_: T) {} | -- required by this bound in `foo` ... 11 | foo(a); | ^ the trait `Ti` is not implemented for `i32` error[E0277]: the trait bound `Box<i32>: Tm` is not satisfied --> t2.rs:14:9 | 7 | fn bar<T: Tm>(_: T) {} | -- required by this bound in `bar` ... 14 | bar(b); | ^ the trait `Tm` is not implemented for `Box<i32>` error: aborting due to 2 previous errors ``` whereas with my changes, I get: ``` error[E0277]: the trait bound `i32: Ti` is not satisfied --> t2.rs:11:9 | 3 | fn foo<T: Ti>(_: T) {} | -- required by this bound in `foo` ... 11 | foo(a); | ^ | | | expected an implementor of trait `Ti` | help: consider borrowing here: `&a` error[E0277]: the trait bound `Box<i32>: Tm` is not satisfied --> t2.rs:14:9 | 7 | fn bar<T: Tm>(_: T) {} | -- required by this bound in `bar` ... 14 | bar(b); | ^ | | | expected an implementor of trait `Tm` | help: consider borrowing mutably here: `&mut b` error: aborting due to 2 previous errors ``` In my implementation, I have added a "blacklist" to make these suggestions flexible. In particular, suggesting to borrow can interfere with other suggestions, such as to add another trait bound to a generic argument. I have tried to configure this blacklist to cause the least amount of test case failures, i.e. to model the current behavior as closely as possible (I only had to change one existing test case, and this change was quite clearly an improvement).
2 parents 1bfd987 + 572bb13 commit fad04ff

10 files changed

+277
-17
lines changed
 

‎compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+68-13
Original file line numberDiff line numberDiff line change
@@ -686,17 +686,36 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
686686
return false;
687687
}
688688

689+
// Blacklist traits for which it would be nonsensical to suggest borrowing.
690+
// For instance, immutable references are always Copy, so suggesting to
691+
// borrow would always succeed, but it's probably not what the user wanted.
692+
let blacklist: Vec<_> =
693+
[LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized, LangItem::Send]
694+
.iter()
695+
.filter_map(|lang_item| self.tcx.lang_items().require(*lang_item).ok())
696+
.collect();
697+
689698
let span = obligation.cause.span;
690699
let param_env = obligation.param_env;
691700
let trait_ref = trait_ref.skip_binder();
692701

693-
if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
694-
// Try to apply the original trait binding obligation by borrowing.
695-
let self_ty = trait_ref.self_ty();
696-
let found = self_ty.to_string();
697-
let new_self_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, self_ty);
698-
let substs = self.tcx.mk_substs_trait(new_self_ty, &[]);
699-
let new_trait_ref = ty::TraitRef::new(obligation.parent_trait_ref.def_id(), substs);
702+
let found_ty = trait_ref.self_ty();
703+
let found_ty_str = found_ty.to_string();
704+
let imm_borrowed_found_ty = self.tcx.mk_imm_ref(self.tcx.lifetimes.re_static, found_ty);
705+
let imm_substs = self.tcx.mk_substs_trait(imm_borrowed_found_ty, &[]);
706+
let mut_borrowed_found_ty = self.tcx.mk_mut_ref(self.tcx.lifetimes.re_static, found_ty);
707+
let mut_substs = self.tcx.mk_substs_trait(mut_borrowed_found_ty, &[]);
708+
709+
// Try to apply the original trait binding obligation by borrowing.
710+
let mut try_borrowing = |new_trait_ref: ty::TraitRef<'tcx>,
711+
expected_trait_ref: ty::TraitRef<'tcx>,
712+
mtbl: bool,
713+
blacklist: &[DefId]|
714+
-> bool {
715+
if blacklist.contains(&expected_trait_ref.def_id) {
716+
return false;
717+
}
718+
700719
let new_obligation = Obligation::new(
701720
ObligationCause::dummy(),
702721
param_env,
@@ -713,8 +732,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
713732

714733
let msg = format!(
715734
"the trait bound `{}: {}` is not satisfied",
716-
found,
717-
obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
735+
found_ty_str,
736+
expected_trait_ref.print_only_trait_path(),
718737
);
719738
if has_custom_message {
720739
err.note(&msg);
@@ -730,7 +749,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
730749
span,
731750
&format!(
732751
"expected an implementor of trait `{}`",
733-
obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
752+
expected_trait_ref.print_only_trait_path(),
734753
),
735754
);
736755

@@ -745,16 +764,52 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
745764

746765
err.span_suggestion(
747766
span,
748-
"consider borrowing here",
749-
format!("&{}", snippet),
767+
&format!(
768+
"consider{} borrowing here",
769+
if mtbl { " mutably" } else { "" }
770+
),
771+
format!("&{}{}", if mtbl { "mut " } else { "" }, snippet),
750772
Applicability::MaybeIncorrect,
751773
);
752774
}
753775
return true;
754776
}
755777
}
778+
return false;
779+
};
780+
781+
if let ObligationCauseCode::ImplDerivedObligation(obligation) = &obligation.cause.code {
782+
let expected_trait_ref = obligation.parent_trait_ref.skip_binder();
783+
let new_imm_trait_ref =
784+
ty::TraitRef::new(obligation.parent_trait_ref.def_id(), imm_substs);
785+
let new_mut_trait_ref =
786+
ty::TraitRef::new(obligation.parent_trait_ref.def_id(), mut_substs);
787+
if try_borrowing(new_imm_trait_ref, expected_trait_ref, false, &[]) {
788+
return true;
789+
} else {
790+
return try_borrowing(new_mut_trait_ref, expected_trait_ref, true, &[]);
791+
}
792+
} else if let ObligationCauseCode::BindingObligation(_, _)
793+
| ObligationCauseCode::ItemObligation(_) = &obligation.cause.code
794+
{
795+
if try_borrowing(
796+
ty::TraitRef::new(trait_ref.def_id, imm_substs),
797+
trait_ref,
798+
false,
799+
&blacklist[..],
800+
) {
801+
return true;
802+
} else {
803+
return try_borrowing(
804+
ty::TraitRef::new(trait_ref.def_id, mut_substs),
805+
trait_ref,
806+
true,
807+
&blacklist[..],
808+
);
809+
}
810+
} else {
811+
false
756812
}
757-
false
758813
}
759814

760815
/// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,

‎src/test/ui/suggestions/imm-ref-trait-object-literal.stderr

+4-4
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ LL | fn foo<X: Trait>(_: X) {}
2121
| ----- required by this bound in `foo`
2222
...
2323
LL | foo(s);
24-
| ^ the trait `Trait` is not implemented for `S`
25-
|
26-
= help: the following implementations were found:
27-
<&'a mut S as Trait>
24+
| ^
25+
| |
26+
| expected an implementor of trait `Trait`
27+
| help: consider mutably borrowing here: `&mut s`
2828

2929
error: aborting due to 2 previous errors
3030

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// A slight variation of issue-84973.rs. Here, a mutable borrow is
2+
// required (and the obligation kind is different).
3+
4+
trait Tr {}
5+
impl Tr for &mut i32 {}
6+
7+
fn foo<T: Tr>(i: T) {}
8+
9+
fn main() {
10+
let a: i32 = 32;
11+
foo(a);
12+
//~^ ERROR: the trait bound `i32: Tr` is not satisfied [E0277]
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: the trait bound `i32: Tr` is not satisfied
2+
--> $DIR/issue-84973-2.rs:11:9
3+
|
4+
LL | fn foo<T: Tr>(i: T) {}
5+
| -- required by this bound in `foo`
6+
...
7+
LL | foo(a);
8+
| ^
9+
| |
10+
| expected an implementor of trait `Tr`
11+
| help: consider mutably borrowing here: `&mut a`
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0277`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Checks that certain traits for which we don't want to suggest borrowing
2+
// are blacklisted and don't cause the suggestion to be issued.
3+
4+
#![feature(generators)]
5+
6+
fn f_copy<T: Copy>(t: T) {}
7+
fn f_clone<T: Clone>(t: T) {}
8+
fn f_unpin<T: Unpin>(t: T) {}
9+
fn f_sized<T: Sized>(t: T) {}
10+
fn f_send<T: Send>(t: T) {}
11+
12+
struct S;
13+
14+
fn main() {
15+
f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277]
16+
f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277]
17+
f_unpin(static || { yield; });
18+
//~^ ERROR: cannot be unpinned [E0277]
19+
20+
let cl = || ();
21+
let ref_cl: &dyn Fn() -> () = &cl;
22+
f_sized(*ref_cl);
23+
//~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
24+
//~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277]
25+
26+
use std::rc::Rc;
27+
let rc = Rc::new(0);
28+
f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277]
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
error[E0277]: the trait bound `String: Copy` is not satisfied
2+
--> $DIR/issue-84973-blacklist.rs:15:12
3+
|
4+
LL | fn f_copy<T: Copy>(t: T) {}
5+
| ---- required by this bound in `f_copy`
6+
...
7+
LL | f_copy("".to_string());
8+
| ^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
9+
10+
error[E0277]: the trait bound `S: Clone` is not satisfied
11+
--> $DIR/issue-84973-blacklist.rs:16:13
12+
|
13+
LL | fn f_clone<T: Clone>(t: T) {}
14+
| ----- required by this bound in `f_clone`
15+
...
16+
LL | f_clone(S);
17+
| ^ the trait `Clone` is not implemented for `S`
18+
19+
error[E0277]: `[static generator@$DIR/issue-84973-blacklist.rs:17:13: 17:33]` cannot be unpinned
20+
--> $DIR/issue-84973-blacklist.rs:17:5
21+
|
22+
LL | fn f_unpin<T: Unpin>(t: T) {}
23+
| ----- required by this bound in `f_unpin`
24+
...
25+
LL | f_unpin(static || { yield; });
26+
| ^^^^^^^ the trait `Unpin` is not implemented for `[static generator@$DIR/issue-84973-blacklist.rs:17:13: 17:33]`
27+
|
28+
= note: consider using `Box::pin`
29+
30+
error[E0277]: the size for values of type `dyn Fn()` cannot be known at compilation time
31+
--> $DIR/issue-84973-blacklist.rs:22:13
32+
|
33+
LL | fn f_sized<T: Sized>(t: T) {}
34+
| - required by this bound in `f_sized`
35+
...
36+
LL | f_sized(*ref_cl);
37+
| ^^^^^^^ doesn't have a size known at compile-time
38+
|
39+
= help: the trait `Sized` is not implemented for `dyn Fn()`
40+
41+
error[E0277]: `Rc<{integer}>` cannot be sent between threads safely
42+
--> $DIR/issue-84973-blacklist.rs:28:12
43+
|
44+
LL | fn f_send<T: Send>(t: T) {}
45+
| ---- required by this bound in `f_send`
46+
...
47+
LL | f_send(rc);
48+
| ^^ `Rc<{integer}>` cannot be sent between threads safely
49+
|
50+
= help: the trait `Send` is not implemented for `Rc<{integer}>`
51+
52+
error[E0277]: the size for values of type `dyn Fn()` cannot be known at compilation time
53+
--> $DIR/issue-84973-blacklist.rs:22:5
54+
|
55+
LL | f_sized(*ref_cl);
56+
| ^^^^^^^ doesn't have a size known at compile-time
57+
|
58+
= help: the trait `Sized` is not implemented for `dyn Fn()`
59+
= note: all function arguments must have a statically known size
60+
= help: unsized fn params are gated as an unstable feature
61+
62+
error: aborting due to 6 previous errors
63+
64+
For more information about this error, try `rustc --explain E0277`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Checks that we only suggest borrowing if &T actually implements the trait.
2+
3+
trait Tr {}
4+
impl Tr for &f32 {}
5+
fn bar<T: Tr>(t: T) {}
6+
7+
fn main() {
8+
let a = 0i32;
9+
let b = 0.0f32;
10+
bar(a); //~ ERROR: the trait bound `i32: Tr` is not satisfied [E0277]
11+
bar(b); //~ ERROR: the trait bound `f32: Tr` is not satisfied [E0277]
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
error[E0277]: the trait bound `i32: Tr` is not satisfied
2+
--> $DIR/issue-84973-negative.rs:10:9
3+
|
4+
LL | fn bar<T: Tr>(t: T) {}
5+
| -- required by this bound in `bar`
6+
...
7+
LL | bar(a);
8+
| ^ the trait `Tr` is not implemented for `i32`
9+
10+
error[E0277]: the trait bound `f32: Tr` is not satisfied
11+
--> $DIR/issue-84973-negative.rs:11:9
12+
|
13+
LL | fn bar<T: Tr>(t: T) {}
14+
| -- required by this bound in `bar`
15+
...
16+
LL | bar(b);
17+
| ^
18+
| |
19+
| expected an implementor of trait `Tr`
20+
| help: consider borrowing here: `&b`
21+
22+
error: aborting due to 2 previous errors
23+
24+
For more information about this error, try `rustc --explain E0277`.
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Checks whether borrowing is suggested when a trait bound is not satisfied
2+
// for found type `T`, but is for `&/&mut T`.
3+
4+
fn main() {
5+
let f = Fancy{};
6+
let o = Other::new(f);
7+
//~^ ERROR: the trait bound `Fancy: SomeTrait` is not satisfied [E0277]
8+
}
9+
10+
struct Fancy {}
11+
12+
impl <'a> SomeTrait for &'a Fancy {
13+
}
14+
15+
trait SomeTrait {}
16+
17+
struct Other<'a, G> {
18+
a: &'a str,
19+
g: G,
20+
}
21+
22+
// Broadly copied from https://docs.rs/petgraph/0.5.1/src/petgraph/dot.rs.html#70
23+
impl<'a, G> Other<'a, G>
24+
where
25+
G: SomeTrait,
26+
{
27+
pub fn new(g: G) -> Self {
28+
Other {
29+
a: "hi",
30+
g: g,
31+
}
32+
}
33+
}
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: the trait bound `Fancy: SomeTrait` is not satisfied
2+
--> $DIR/issue-84973.rs:6:24
3+
|
4+
LL | let o = Other::new(f);
5+
| ^
6+
| |
7+
| expected an implementor of trait `SomeTrait`
8+
| help: consider borrowing here: `&f`
9+
...
10+
LL | pub fn new(g: G) -> Self {
11+
| ------------------------ required by `Other::<'a, G>::new`
12+
13+
error: aborting due to previous error
14+
15+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)
Please sign in to comment.