Skip to content

Commit 55ecb79

Browse files
committed
Note when a mutable trait object is needed
1 parent f2023ac commit 55ecb79

13 files changed

+271
-46
lines changed

src/librustc/traits/error_reporting.rs

+90-21
Original file line numberDiff line numberDiff line change
@@ -453,21 +453,17 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
453453
}
454454
}
455455

456-
fn find_similar_impl_candidates(&self,
457-
trait_ref: ty::PolyTraitRef<'tcx>)
458-
-> Vec<ty::TraitRef<'tcx>>
459-
{
460-
let simp = fast_reject::simplify_type(self.tcx,
461-
trait_ref.skip_binder().self_ty(),
462-
true);
456+
fn find_similar_impl_candidates(
457+
&self,
458+
trait_ref: ty::PolyTraitRef<'tcx>,
459+
) -> Vec<ty::TraitRef<'tcx>> {
460+
let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
463461
let all_impls = self.tcx.all_impls(trait_ref.def_id());
464462

465463
match simp {
466464
Some(simp) => all_impls.iter().filter_map(|&def_id| {
467465
let imp = self.tcx.impl_trait_ref(def_id).unwrap();
468-
let imp_simp = fast_reject::simplify_type(self.tcx,
469-
imp.self_ty(),
470-
true);
466+
let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
471467
if let Some(imp_simp) = imp_simp {
472468
if simp != imp_simp {
473469
return None
@@ -482,10 +478,11 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
482478
}
483479
}
484480

485-
fn report_similar_impl_candidates(&self,
486-
impl_candidates: Vec<ty::TraitRef<'tcx>>,
487-
err: &mut DiagnosticBuilder<'_>)
488-
{
481+
fn report_similar_impl_candidates(
482+
&self,
483+
impl_candidates: Vec<ty::TraitRef<'tcx>>,
484+
err: &mut DiagnosticBuilder<'_>,
485+
) {
489486
if impl_candidates.is_empty() {
490487
return;
491488
}
@@ -720,10 +717,18 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
720717
// which is somewhat confusing.
721718
err.help(&format!("consider adding a `where {}` bound",
722719
trait_ref.to_predicate()));
723-
} else if !have_alt_message {
724-
// Can't show anything else useful, try to find similar impls.
725-
let impl_candidates = self.find_similar_impl_candidates(trait_ref);
726-
self.report_similar_impl_candidates(impl_candidates, &mut err);
720+
} else {
721+
if !have_alt_message {
722+
// Can't show anything else useful, try to find similar impls.
723+
let impl_candidates = self.find_similar_impl_candidates(trait_ref);
724+
self.report_similar_impl_candidates(impl_candidates, &mut err);
725+
}
726+
self.suggest_change_mut(
727+
&obligation,
728+
&mut err,
729+
&trait_ref,
730+
points_at_arg,
731+
);
727732
}
728733

729734
// If this error is due to `!: Trait` not implemented but `(): Trait` is
@@ -1081,9 +1086,11 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
10811086

10821087
let substs = self.tcx.mk_substs_trait(trait_type, &[]);
10831088
let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
1084-
let new_obligation = Obligation::new(ObligationCause::dummy(),
1085-
obligation.param_env,
1086-
new_trait_ref.to_predicate());
1089+
let new_obligation = Obligation::new(
1090+
ObligationCause::dummy(),
1091+
obligation.param_env,
1092+
new_trait_ref.to_predicate(),
1093+
);
10871094

10881095
if self.predicate_may_hold(&new_obligation) {
10891096
let sp = self.tcx.sess.source_map()
@@ -1105,6 +1112,68 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
11051112
}
11061113
}
11071114

1115+
/// Check if the trait bound is implemented for a different mutability and note it in the
1116+
/// final error.
1117+
fn suggest_change_mut(
1118+
&self,
1119+
obligation: &PredicateObligation<'tcx>,
1120+
err: &mut DiagnosticBuilder<'tcx>,
1121+
trait_ref: &ty::Binder<ty::TraitRef<'tcx>>,
1122+
points_at_arg: bool,
1123+
) {
1124+
let span = obligation.cause.span;
1125+
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1126+
let refs_number = snippet.chars()
1127+
.filter(|c| !c.is_whitespace())
1128+
.take_while(|c| *c == '&')
1129+
.count();
1130+
if let Some('\'') = snippet.chars()
1131+
.filter(|c| !c.is_whitespace())
1132+
.skip(refs_number)
1133+
.next()
1134+
{ // Do not suggest removal of borrow from type arguments.
1135+
return;
1136+
}
1137+
1138+
if let ty::Ref(region, t_type, mutability) = trait_ref.skip_binder().self_ty().kind {
1139+
let trait_type = match mutability {
1140+
hir::Mutability::MutMutable => self.tcx.mk_imm_ref(region, t_type),
1141+
hir::Mutability::MutImmutable => self.tcx.mk_mut_ref(region, t_type),
1142+
};
1143+
1144+
let substs = self.tcx.mk_substs_trait(&trait_type, &[]);
1145+
let new_trait_ref = ty::TraitRef::new(trait_ref.skip_binder().def_id, substs);
1146+
let new_obligation = Obligation::new(
1147+
ObligationCause::dummy(),
1148+
obligation.param_env,
1149+
new_trait_ref.to_predicate(),
1150+
);
1151+
1152+
if self.predicate_may_hold(&new_obligation) {
1153+
let sp = self.tcx.sess.source_map()
1154+
.span_take_while(span, |c| c.is_whitespace() || *c == '&');
1155+
if points_at_arg &&
1156+
mutability == hir::Mutability::MutImmutable &&
1157+
refs_number > 0
1158+
{
1159+
err.span_suggestion(
1160+
sp,
1161+
"consider changing this borrow's mutability",
1162+
"&mut ".to_string(),
1163+
Applicability::MachineApplicable,
1164+
);
1165+
} else {
1166+
err.note(&format!(
1167+
"`{}` is implemented for `{:?}`",
1168+
trait_ref,
1169+
trait_type,
1170+
));
1171+
}
1172+
}
1173+
}
1174+
}
1175+
}
1176+
11081177
fn suggest_semicolon_removal(
11091178
&self,
11101179
obligation: &PredicateObligation<'tcx>,

src/librustc_typeck/check/method/mod.rs

+40-24
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ pub enum MethodError<'tcx> {
5858

5959
// Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have
6060
// forgotten to import a trait.
61-
IllegalSizedBound(Vec<DefId>),
61+
IllegalSizedBound(Vec<DefId>, bool),
6262

6363
// Found a match, but the return type is wrong
6464
BadReturnType,
@@ -213,33 +213,49 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
213213
segment,
214214
);
215215

216+
let mut needs_mut = false;
217+
if let ty::Ref(region, t_type, mutability) = self_ty.kind {
218+
let trait_type = match mutability {
219+
hir::Mutability::MutMutable => self.tcx.mk_imm_ref(region, t_type),
220+
hir::Mutability::MutImmutable => self.tcx.mk_mut_ref(region, t_type),
221+
};
222+
match self.lookup_probe(
223+
span,
224+
segment.ident,
225+
trait_type,
226+
call_expr,
227+
ProbeScope::TraitsInScope
228+
) {
229+
Ok(ref new_pick) if *new_pick != pick => {
230+
needs_mut = true;
231+
}
232+
_ => {}
233+
}
234+
}
235+
216236
if result.illegal_sized_bound {
217237
// We probe again, taking all traits into account (not only those in scope).
218-
let candidates =
219-
match self.lookup_probe(span,
220-
segment.ident,
221-
self_ty,
222-
call_expr,
223-
ProbeScope::AllTraits) {
224-
225-
// If we find a different result the caller probably forgot to import a trait.
226-
Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
227-
Err(Ambiguity(ref sources)) => {
228-
sources.iter()
229-
.filter_map(|source| {
230-
match *source {
231-
// Note: this cannot come from an inherent impl,
232-
// because the first probing succeeded.
233-
ImplSource(def) => self.tcx.trait_id_of_impl(def),
234-
TraitSource(_) => None,
235-
}
236-
})
237-
.collect()
238+
let candidates = match self.lookup_probe(
239+
span,
240+
segment.ident,
241+
self_ty,
242+
call_expr,
243+
ProbeScope::AllTraits,
244+
) {
245+
// If we find a different result the caller probably forgot to import a trait.
246+
Ok(ref new_pick) if *new_pick != pick => vec![new_pick.item.container.id()],
247+
Err(Ambiguity(ref sources)) => sources.iter().filter_map(|source| {
248+
match *source {
249+
// Note: this cannot come from an inherent impl,
250+
// because the first probing succeeded.
251+
ImplSource(def) => self.tcx.trait_id_of_impl(def),
252+
TraitSource(_) => None,
238253
}
239-
_ => Vec::new(),
240-
};
254+
}).collect(),
255+
_ => Vec::new(),
256+
};
241257

242-
return Err(IllegalSizedBound(candidates));
258+
return Err(IllegalSizedBound(candidates, needs_mut));
243259
}
244260

245261
Ok(result.callee)

src/librustc_typeck/check/method/suggest.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -553,7 +553,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
553553
err.emit();
554554
}
555555

556-
MethodError::IllegalSizedBound(candidates) => {
556+
MethodError::IllegalSizedBound(candidates, needs_mut) => {
557557
let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
558558
let mut err = self.sess().struct_span_err(span, &msg);
559559
if !candidates.is_empty() {
@@ -569,6 +569,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
569569
});
570570
self.suggest_use_candidates(&mut err, help, candidates);
571571
}
572+
if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind {
573+
let trait_type = match mutability {
574+
hir::Mutability::MutMutable => self.tcx.mk_imm_ref(region, t_type),
575+
hir::Mutability::MutImmutable => self.tcx.mk_mut_ref(region, t_type),
576+
};
577+
if needs_mut {
578+
err.note(&format!("you need `{}` instead", trait_type));
579+
}
580+
}
572581
err.emit();
573582
}
574583

src/test/ui/not-panic/not-panic-safe.stderr

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ LL | assert::<&mut i32>();
88
| ^^^^^^^^^^^^^^^^^^ `&mut i32` may not be safely transferred across an unwind boundary
99
|
1010
= help: the trait `std::panic::UnwindSafe` is not implemented for `&mut i32`
11+
= note: `std::panic::UnwindSafe` is implemented for `&i32`
1112

1213
error: aborting due to previous error
1314

src/test/ui/parser/lex-bad-char-literals-6.stderr

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ LL | if x == y {}
3535
| ^^ no implementation for `&str == char`
3636
|
3737
= help: the trait `std::cmp::PartialEq<char>` is not implemented for `&str`
38+
= note: `std::cmp::PartialEq<char>` is implemented for `&mut str`
3839

3940
error[E0308]: mismatched types
4041
--> $DIR/lex-bad-char-literals-6.rs:15:20
@@ -52,6 +53,7 @@ LL | if x == z {}
5253
| ^^ no implementation for `&str == char`
5354
|
5455
= help: the trait `std::cmp::PartialEq<char>` is not implemented for `&str`
56+
= note: `std::cmp::PartialEq<char>` is implemented for `&mut str`
5557

5658
error: aborting due to 6 previous errors
5759

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
trait Trait {}
2+
3+
struct S;
4+
5+
impl<'a> Trait for &'a mut S {}
6+
7+
fn foo<X: Trait>(_: X) {}
8+
9+
10+
fn main() {
11+
let s = S;
12+
foo(&s); //~ ERROR the trait bound `&S: Trait` is not satisfied
13+
foo(s); //~ ERROR the trait bound `S: Trait` is not satisfied
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
error[E0277]: the trait bound `&S: Trait` is not satisfied
2+
--> $DIR/imm-ref-trait-object-literal.rs:12:7
3+
|
4+
LL | fn foo<X: Trait>(_: X) {}
5+
| --- ----- required by this bound in `foo`
6+
...
7+
LL | foo(&s);
8+
| -^
9+
| |
10+
| the trait `Trait` is not implemented for `&S`
11+
| help: consider changing this borrow's mutability: `&mut`
12+
|
13+
= help: the following implementations were found:
14+
<&'a mut S as Trait>
15+
16+
error[E0277]: the trait bound `S: Trait` is not satisfied
17+
--> $DIR/imm-ref-trait-object-literal.rs:13:7
18+
|
19+
LL | fn foo<X: Trait>(_: X) {}
20+
| --- ----- required by this bound in `foo`
21+
...
22+
LL | foo(s);
23+
| ^ the trait `Trait` is not implemented for `S`
24+
|
25+
= help: the following implementations were found:
26+
<&'a mut S as Trait>
27+
28+
error: aborting due to 2 previous errors
29+
30+
For more information about this error, try `rustc --explain E0277`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn test(t: &dyn Iterator<Item=&u64>) -> u64 {
2+
t.min().unwrap() //~ ERROR the `min` method cannot be invoked on a trait object
3+
}
4+
5+
fn main() {
6+
let array = [0u64];
7+
test(&mut array.iter());
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: the `min` method cannot be invoked on a trait object
2+
--> $DIR/imm-ref-trait-object.rs:2:8
3+
|
4+
LL | t.min().unwrap()
5+
| ^^^
6+
|
7+
= note: you need `&mut dyn std::iter::Iterator<Item = &u64>` instead
8+
9+
error: aborting due to previous error
10+

src/test/ui/suggestions/into-str.stderr

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ LL | foo(String::new());
88
| ^^^ the trait `std::convert::From<std::string::String>` is not implemented for `&str`
99
|
1010
= note: to coerce a `std::string::String` into a `&str`, use `&*` as a prefix
11+
= note: `std::convert::From<std::string::String>` is implemented for `&mut str`
1112
= note: required because of the requirements on the impl of `std::convert::Into<&str>` for `std::string::String`
1213

1314
error: aborting due to previous error
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use std::env::args;
2+
use std::fs::File;
3+
use std::io::{stdout, Write, BufWriter};
4+
5+
fn main() {
6+
let mut args = args();
7+
let _ = args.next();
8+
let dest = args.next();
9+
10+
let h1; let h2; let h3;
11+
12+
let fp: &dyn Write = match dest {
13+
Some(path) => { h1 = File::create(path).unwrap(); &h1 },
14+
None => { h2 = stdout(); h3 = h2.lock(); &h3 }
15+
};
16+
17+
let fp = BufWriter::new(fp);
18+
//~^ ERROR the trait bound `&dyn std::io::Write: std::io::Write` is not satisfied
19+
//~| ERROR the trait bound `&dyn std::io::Write: std::io::Write` is not satisfied
20+
//~| ERROR the trait bound `&dyn std::io::Write: std::io::Write` is not satisfied
21+
22+
writeln!(fp, "hello world").unwrap(); //~ ERROR no method named `write_fmt` found for type
23+
}

0 commit comments

Comments
 (0)