Skip to content

Commit ef68bf3

Browse files
committed
Try to suggest dereferences when trait selection failed.
1 parent 5155518 commit ef68bf3

11 files changed

+254
-1
lines changed

src/librustc_trait_selection/traits/error_reporting/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
402402
err.span_label(enclosing_scope_span, s.as_str());
403403
}
404404

405+
self.suggest_dereferences(&obligation, &mut err, &trait_ref, points_at_arg);
405406
self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
406407
self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
407408
self.suggest_remove_reference(&obligation, &mut err, &trait_ref);

src/librustc_trait_selection/traits/error_reporting/suggestions.rs

+66-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use super::{
33
SelectionContext,
44
};
55

6+
use crate::autoderef::Autoderef;
67
use crate::infer::InferCtxt;
78
use crate::traits::normalize_projection_type;
89

@@ -13,11 +14,11 @@ use rustc_hir::def_id::DefId;
1314
use rustc_hir::intravisit::Visitor;
1415
use rustc_hir::lang_items;
1516
use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
16-
use rustc_middle::ty::TypeckTables;
1717
use rustc_middle::ty::{
1818
self, suggest_constraining_type_param, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty,
1919
TyCtxt, TypeFoldable, WithConstness,
2020
};
21+
use rustc_middle::ty::{TypeAndMut, TypeckTables};
2122
use rustc_span::symbol::{kw, sym, Ident, Symbol};
2223
use rustc_span::{MultiSpan, Span, DUMMY_SP};
2324
use std::fmt;
@@ -48,6 +49,14 @@ pub trait InferCtxtExt<'tcx> {
4849
err: &mut DiagnosticBuilder<'_>,
4950
);
5051

52+
fn suggest_dereferences(
53+
&self,
54+
obligation: &PredicateObligation<'tcx>,
55+
err: &mut DiagnosticBuilder<'tcx>,
56+
trait_ref: &ty::PolyTraitRef<'tcx>,
57+
points_at_arg: bool,
58+
);
59+
5160
fn get_closure_name(
5261
&self,
5362
def_id: DefId,
@@ -450,6 +459,62 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
450459
}
451460
}
452461

462+
/// When after several dereferencing, the reference satisfies the trait
463+
/// binding. This function provides dereference suggestion for this
464+
/// specific situation.
465+
fn suggest_dereferences(
466+
&self,
467+
obligation: &PredicateObligation<'tcx>,
468+
err: &mut DiagnosticBuilder<'tcx>,
469+
trait_ref: &ty::PolyTraitRef<'tcx>,
470+
points_at_arg: bool,
471+
) {
472+
// It only make sense when suggesting dereferences for arguments
473+
if !points_at_arg {
474+
return;
475+
}
476+
let param_env = obligation.param_env;
477+
let body_id = obligation.cause.body_id;
478+
let span = obligation.cause.span;
479+
let real_trait_ref = match &obligation.cause.code {
480+
ObligationCauseCode::ImplDerivedObligation(cause)
481+
| ObligationCauseCode::DerivedObligation(cause)
482+
| ObligationCauseCode::BuiltinDerivedObligation(cause) => &cause.parent_trait_ref,
483+
_ => trait_ref,
484+
};
485+
let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
486+
Some(ty) => ty,
487+
None => return,
488+
};
489+
490+
if let ty::Ref(region, base_ty, mutbl) = real_ty.kind {
491+
let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty);
492+
if let Some(steps) = autoderef.find_map(|(ty, steps)| {
493+
// Re-add the `&`
494+
let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
495+
let obligation =
496+
self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
497+
Some(steps).filter(|_| self.predicate_may_hold(&obligation))
498+
}) {
499+
if steps > 0 {
500+
if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
501+
// Don't care about `&mut` because `DerefMut` is used less
502+
// often and user will not expect autoderef happens.
503+
if src.starts_with("&") {
504+
let derefs = "*".repeat(steps);
505+
err.span_suggestion(
506+
span,
507+
"consider adding dereference here",
508+
format!("&{}{}", derefs, &src[1..]),
509+
Applicability::MachineApplicable,
510+
);
511+
}
512+
}
513+
}
514+
}
515+
}
516+
}
517+
453518
/// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
454519
/// suggestion to borrow the initializer in order to use have a slice instead.
455520
fn suggest_borrow_on_unsized_slice(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// run-rustfix
2+
use std::net::TcpListener;
3+
4+
struct NoToSocketAddrs(String);
5+
6+
impl std::ops::Deref for NoToSocketAddrs {
7+
type Target = String;
8+
fn deref(&self) -> &Self::Target {
9+
&self.0
10+
}
11+
}
12+
13+
fn main() {
14+
let _works = TcpListener::bind("some string");
15+
let bad = NoToSocketAddrs("bad".to_owned());
16+
let _errors = TcpListener::bind(&*bad);
17+
//~^ ERROR the trait bound `NoToSocketAddrs: std::net::ToSocketAddrs` is not satisfied
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// run-rustfix
2+
use std::net::TcpListener;
3+
4+
struct NoToSocketAddrs(String);
5+
6+
impl std::ops::Deref for NoToSocketAddrs {
7+
type Target = String;
8+
fn deref(&self) -> &Self::Target {
9+
&self.0
10+
}
11+
}
12+
13+
fn main() {
14+
let _works = TcpListener::bind("some string");
15+
let bad = NoToSocketAddrs("bad".to_owned());
16+
let _errors = TcpListener::bind(&bad);
17+
//~^ ERROR the trait bound `NoToSocketAddrs: std::net::ToSocketAddrs` is not satisfied
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
error[E0277]: the trait bound `NoToSocketAddrs: std::net::ToSocketAddrs` is not satisfied
2+
--> $DIR/trait-suggest-deferences-issue-39029.rs:16:37
3+
|
4+
LL | let _errors = TcpListener::bind(&bad);
5+
| ^^^^
6+
| |
7+
| the trait `std::net::ToSocketAddrs` is not implemented for `NoToSocketAddrs`
8+
| help: consider adding dereference here: `&*bad`
9+
|
10+
::: $SRC_DIR/libstd/net/tcp.rs:LL:COL
11+
|
12+
LL | pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
13+
| ------------- required by this bound in `std::net::TcpListener::bind`
14+
|
15+
= note: required because of the requirements on the impl of `std::net::ToSocketAddrs` for `&NoToSocketAddrs`
16+
17+
error: aborting due to previous error
18+
19+
For more information about this error, try `rustc --explain E0277`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// run-rustfix
2+
fn takes_str(_x: &str) {}
3+
4+
fn takes_type_parameter<T>(_x: T) where T: SomeTrait {}
5+
6+
trait SomeTrait {}
7+
impl SomeTrait for &'_ str {}
8+
impl SomeTrait for char {}
9+
10+
fn main() {
11+
let string = String::new();
12+
takes_str(&string); // Ok
13+
takes_type_parameter(&*string); // Error
14+
//~^ ERROR the trait bound `&std::string::String: SomeTrait` is not satisfied
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// run-rustfix
2+
fn takes_str(_x: &str) {}
3+
4+
fn takes_type_parameter<T>(_x: T) where T: SomeTrait {}
5+
6+
trait SomeTrait {}
7+
impl SomeTrait for &'_ str {}
8+
impl SomeTrait for char {}
9+
10+
fn main() {
11+
let string = String::new();
12+
takes_str(&string); // Ok
13+
takes_type_parameter(&string); // Error
14+
//~^ ERROR the trait bound `&std::string::String: SomeTrait` is not satisfied
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: the trait bound `&std::string::String: SomeTrait` is not satisfied
2+
--> $DIR/trait-suggest-deferences-issue-62530.rs:13:26
3+
|
4+
LL | fn takes_type_parameter<T>(_x: T) where T: SomeTrait {}
5+
| --------- required by this bound in `takes_type_parameter`
6+
...
7+
LL | takes_type_parameter(&string); // Error
8+
| ^^^^^^^
9+
| |
10+
| the trait `SomeTrait` is not implemented for `&std::string::String`
11+
| help: consider adding dereference here: `&*string`
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,36 @@
1+
// run-rustfix
2+
use std::ops::Deref;
3+
4+
trait Happy {}
5+
struct LDM;
6+
impl Happy for &LDM {}
7+
8+
struct Foo(LDM);
9+
struct Bar(Foo);
10+
struct Baz(Bar);
11+
impl Deref for Foo {
12+
type Target = LDM;
13+
fn deref(&self) -> &Self::Target {
14+
&self.0
15+
}
16+
}
17+
impl Deref for Bar {
18+
type Target = Foo;
19+
fn deref(&self) -> &Self::Target {
20+
&self.0
21+
}
22+
}
23+
impl Deref for Baz {
24+
type Target = Bar;
25+
fn deref(&self) -> &Self::Target {
26+
&self.0
27+
}
28+
}
29+
30+
fn foo<T>(_: T) where T: Happy {}
31+
32+
fn main() {
33+
let baz = Baz(Bar(Foo(LDM)));
34+
foo(&***baz);
35+
//~^ ERROR the trait bound `&Baz: Happy` is not satisfied
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// run-rustfix
2+
use std::ops::Deref;
3+
4+
trait Happy {}
5+
struct LDM;
6+
impl Happy for &LDM {}
7+
8+
struct Foo(LDM);
9+
struct Bar(Foo);
10+
struct Baz(Bar);
11+
impl Deref for Foo {
12+
type Target = LDM;
13+
fn deref(&self) -> &Self::Target {
14+
&self.0
15+
}
16+
}
17+
impl Deref for Bar {
18+
type Target = Foo;
19+
fn deref(&self) -> &Self::Target {
20+
&self.0
21+
}
22+
}
23+
impl Deref for Baz {
24+
type Target = Bar;
25+
fn deref(&self) -> &Self::Target {
26+
&self.0
27+
}
28+
}
29+
30+
fn foo<T>(_: T) where T: Happy {}
31+
32+
fn main() {
33+
let baz = Baz(Bar(Foo(LDM)));
34+
foo(&baz);
35+
//~^ ERROR the trait bound `&Baz: Happy` is not satisfied
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0277]: the trait bound `&Baz: Happy` is not satisfied
2+
--> $DIR/trait-suggest-deferences-multiple.rs:34:9
3+
|
4+
LL | fn foo<T>(_: T) where T: Happy {}
5+
| ----- required by this bound in `foo`
6+
...
7+
LL | foo(&baz);
8+
| ^^^^
9+
| |
10+
| the trait `Happy` is not implemented for `&Baz`
11+
| help: consider adding dereference here: `&***baz`
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)