about summary refs log tree commit diff
diff options
context:
space:
mode:
authorDonough Liu <ldm2993593805@163.com>2020-06-20 18:30:12 +0800
committerDonough Liu <ldm2993593805@163.com>2020-06-20 18:53:59 +0800
commitef68bf3929e5073e84b48fd76a689b071842d756 (patch)
tree2cdc25dd135655956ddb2dccdcb81da64ae21122
parent51555186b680ffc63b1daf362456f7f8ca537763 (diff)
downloadrust-ef68bf3929e5073e84b48fd76a689b071842d756.tar.gz
rust-ef68bf3929e5073e84b48fd76a689b071842d756.zip
Try to suggest dereferences when trait selection failed.
-rw-r--r--src/librustc_trait_selection/traits/error_reporting/mod.rs1
-rw-r--r--src/librustc_trait_selection/traits/error_reporting/suggestions.rs67
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-issue-39029.fixed18
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-issue-39029.rs18
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-issue-39029.stderr19
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-issue-62530.fixed15
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-issue-62530.rs15
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-issue-62530.stderr15
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-multiple.fixed36
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-multiple.rs36
-rw-r--r--src/test/ui/traits/trait-suggest-deferences-multiple.stderr15
11 files changed, 254 insertions, 1 deletions
diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs
index 060877f80ad..fd0c1a54d27 100644
--- a/src/librustc_trait_selection/traits/error_reporting/mod.rs
+++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs
@@ -402,6 +402,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
                             err.span_label(enclosing_scope_span, s.as_str());
                         }
 
+                        self.suggest_dereferences(&obligation, &mut err, &trait_ref, points_at_arg);
                         self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
                         self.suggest_fn_call(&obligation, &mut err, &trait_ref, points_at_arg);
                         self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs
index dfd7dac72d8..0c86e33884d 100644
--- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs
+++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs
@@ -3,6 +3,7 @@ use super::{
     SelectionContext,
 };
 
+use crate::autoderef::Autoderef;
 use crate::infer::InferCtxt;
 use crate::traits::normalize_projection_type;
 
@@ -13,11 +14,11 @@ use rustc_hir::def_id::DefId;
 use rustc_hir::intravisit::Visitor;
 use rustc_hir::lang_items;
 use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
-use rustc_middle::ty::TypeckTables;
 use rustc_middle::ty::{
     self, suggest_constraining_type_param, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty,
     TyCtxt, TypeFoldable, WithConstness,
 };
+use rustc_middle::ty::{TypeAndMut, TypeckTables};
 use rustc_span::symbol::{kw, sym, Ident, Symbol};
 use rustc_span::{MultiSpan, Span, DUMMY_SP};
 use std::fmt;
@@ -48,6 +49,14 @@ pub trait InferCtxtExt<'tcx> {
         err: &mut DiagnosticBuilder<'_>,
     );
 
+    fn suggest_dereferences(
+        &self,
+        obligation: &PredicateObligation<'tcx>,
+        err: &mut DiagnosticBuilder<'tcx>,
+        trait_ref: &ty::PolyTraitRef<'tcx>,
+        points_at_arg: bool,
+    );
+
     fn get_closure_name(
         &self,
         def_id: DefId,
@@ -450,6 +459,62 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
         }
     }
 
+    /// When after several dereferencing, the reference satisfies the trait
+    /// binding. This function provides dereference suggestion for this
+    /// specific situation.
+    fn suggest_dereferences(
+        &self,
+        obligation: &PredicateObligation<'tcx>,
+        err: &mut DiagnosticBuilder<'tcx>,
+        trait_ref: &ty::PolyTraitRef<'tcx>,
+        points_at_arg: bool,
+    ) {
+        // It only make sense when suggesting dereferences for arguments
+        if !points_at_arg {
+            return;
+        }
+        let param_env = obligation.param_env;
+        let body_id = obligation.cause.body_id;
+        let span = obligation.cause.span;
+        let real_trait_ref = match &obligation.cause.code {
+            ObligationCauseCode::ImplDerivedObligation(cause)
+            | ObligationCauseCode::DerivedObligation(cause)
+            | ObligationCauseCode::BuiltinDerivedObligation(cause) => &cause.parent_trait_ref,
+            _ => trait_ref,
+        };
+        let real_ty = match real_trait_ref.self_ty().no_bound_vars() {
+            Some(ty) => ty,
+            None => return,
+        };
+
+        if let ty::Ref(region, base_ty, mutbl) = real_ty.kind {
+            let mut autoderef = Autoderef::new(self, param_env, body_id, span, base_ty);
+            if let Some(steps) = autoderef.find_map(|(ty, steps)| {
+                // Re-add the `&`
+                let ty = self.tcx.mk_ref(region, TypeAndMut { ty, mutbl });
+                let obligation =
+                    self.mk_trait_obligation_with_new_self_ty(param_env, real_trait_ref, ty);
+                Some(steps).filter(|_| self.predicate_may_hold(&obligation))
+            }) {
+                if steps > 0 {
+                    if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(span) {
+                        // Don't care about `&mut` because `DerefMut` is used less
+                        // often and user will not expect autoderef happens.
+                        if src.starts_with("&") {
+                            let derefs = "*".repeat(steps);
+                            err.span_suggestion(
+                                span,
+                                "consider adding dereference here",
+                                format!("&{}{}", derefs, &src[1..]),
+                                Applicability::MachineApplicable,
+                            );
+                        }
+                    }
+                }
+            }
+        }
+    }
+
     /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
     /// suggestion to borrow the initializer in order to use have a slice instead.
     fn suggest_borrow_on_unsized_slice(
diff --git a/src/test/ui/traits/trait-suggest-deferences-issue-39029.fixed b/src/test/ui/traits/trait-suggest-deferences-issue-39029.fixed
new file mode 100644
index 00000000000..2bb34b0ebee
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-issue-39029.fixed
@@ -0,0 +1,18 @@
+// run-rustfix
+use std::net::TcpListener;
+
+struct NoToSocketAddrs(String);
+
+impl std::ops::Deref for NoToSocketAddrs {
+    type Target = String;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+fn main() {
+    let _works = TcpListener::bind("some string");
+    let bad = NoToSocketAddrs("bad".to_owned());
+    let _errors = TcpListener::bind(&*bad);
+    //~^ ERROR the trait bound `NoToSocketAddrs: std::net::ToSocketAddrs` is not satisfied
+}
diff --git a/src/test/ui/traits/trait-suggest-deferences-issue-39029.rs b/src/test/ui/traits/trait-suggest-deferences-issue-39029.rs
new file mode 100644
index 00000000000..33d524608a0
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-issue-39029.rs
@@ -0,0 +1,18 @@
+// run-rustfix
+use std::net::TcpListener;
+
+struct NoToSocketAddrs(String);
+
+impl std::ops::Deref for NoToSocketAddrs {
+    type Target = String;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+fn main() {
+    let _works = TcpListener::bind("some string");
+    let bad = NoToSocketAddrs("bad".to_owned());
+    let _errors = TcpListener::bind(&bad);
+    //~^ ERROR the trait bound `NoToSocketAddrs: std::net::ToSocketAddrs` is not satisfied
+}
diff --git a/src/test/ui/traits/trait-suggest-deferences-issue-39029.stderr b/src/test/ui/traits/trait-suggest-deferences-issue-39029.stderr
new file mode 100644
index 00000000000..0bf9794a744
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-issue-39029.stderr
@@ -0,0 +1,19 @@
+error[E0277]: the trait bound `NoToSocketAddrs: std::net::ToSocketAddrs` is not satisfied
+  --> $DIR/trait-suggest-deferences-issue-39029.rs:16:37
+   |
+LL |     let _errors = TcpListener::bind(&bad);
+   |                                     ^^^^
+   |                                     |
+   |                                     the trait `std::net::ToSocketAddrs` is not implemented for `NoToSocketAddrs`
+   |                                     help: consider adding dereference here: `&*bad`
+   | 
+  ::: $SRC_DIR/libstd/net/tcp.rs:LL:COL
+   |
+LL |     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
+   |                    ------------- required by this bound in `std::net::TcpListener::bind`
+   |
+   = note: required because of the requirements on the impl of `std::net::ToSocketAddrs` for `&NoToSocketAddrs`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0277`.
diff --git a/src/test/ui/traits/trait-suggest-deferences-issue-62530.fixed b/src/test/ui/traits/trait-suggest-deferences-issue-62530.fixed
new file mode 100644
index 00000000000..fa7b9167d8d
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-issue-62530.fixed
@@ -0,0 +1,15 @@
+// run-rustfix
+fn takes_str(_x: &str) {}
+
+fn takes_type_parameter<T>(_x: T) where T: SomeTrait {}
+
+trait SomeTrait {}
+impl SomeTrait for &'_ str {}
+impl SomeTrait for char {}
+
+fn main() {
+    let string = String::new();
+    takes_str(&string);             // Ok
+    takes_type_parameter(&*string);  // Error
+    //~^ ERROR the trait bound `&std::string::String: SomeTrait` is not satisfied
+}
diff --git a/src/test/ui/traits/trait-suggest-deferences-issue-62530.rs b/src/test/ui/traits/trait-suggest-deferences-issue-62530.rs
new file mode 100644
index 00000000000..e785f012177
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-issue-62530.rs
@@ -0,0 +1,15 @@
+// run-rustfix
+fn takes_str(_x: &str) {}
+
+fn takes_type_parameter<T>(_x: T) where T: SomeTrait {}
+
+trait SomeTrait {}
+impl SomeTrait for &'_ str {}
+impl SomeTrait for char {}
+
+fn main() {
+    let string = String::new();
+    takes_str(&string);             // Ok
+    takes_type_parameter(&string);  // Error
+    //~^ ERROR the trait bound `&std::string::String: SomeTrait` is not satisfied
+}
diff --git a/src/test/ui/traits/trait-suggest-deferences-issue-62530.stderr b/src/test/ui/traits/trait-suggest-deferences-issue-62530.stderr
new file mode 100644
index 00000000000..9c2a582638e
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-issue-62530.stderr
@@ -0,0 +1,15 @@
+error[E0277]: the trait bound `&std::string::String: SomeTrait` is not satisfied
+  --> $DIR/trait-suggest-deferences-issue-62530.rs:13:26
+   |
+LL | fn takes_type_parameter<T>(_x: T) where T: SomeTrait {}
+   |                                            --------- required by this bound in `takes_type_parameter`
+...
+LL |     takes_type_parameter(&string);  // Error
+   |                          ^^^^^^^
+   |                          |
+   |                          the trait `SomeTrait` is not implemented for `&std::string::String`
+   |                          help: consider adding dereference here: `&*string`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0277`.
diff --git a/src/test/ui/traits/trait-suggest-deferences-multiple.fixed b/src/test/ui/traits/trait-suggest-deferences-multiple.fixed
new file mode 100644
index 00000000000..b7160b75c60
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-multiple.fixed
@@ -0,0 +1,36 @@
+// run-rustfix
+use std::ops::Deref;
+
+trait Happy {}
+struct LDM;
+impl Happy for &LDM {}
+
+struct Foo(LDM);
+struct Bar(Foo);
+struct Baz(Bar);
+impl Deref for Foo {
+    type Target = LDM;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+impl Deref for Bar {
+    type Target = Foo;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+impl Deref for Baz {
+    type Target = Bar;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+fn foo<T>(_: T) where T: Happy {}
+
+fn main() {
+    let baz = Baz(Bar(Foo(LDM)));
+    foo(&***baz);
+    //~^ ERROR the trait bound `&Baz: Happy` is not satisfied
+}
diff --git a/src/test/ui/traits/trait-suggest-deferences-multiple.rs b/src/test/ui/traits/trait-suggest-deferences-multiple.rs
new file mode 100644
index 00000000000..9ac55177ffa
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-multiple.rs
@@ -0,0 +1,36 @@
+// run-rustfix
+use std::ops::Deref;
+
+trait Happy {}
+struct LDM;
+impl Happy for &LDM {}
+
+struct Foo(LDM);
+struct Bar(Foo);
+struct Baz(Bar);
+impl Deref for Foo {
+    type Target = LDM;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+impl Deref for Bar {
+    type Target = Foo;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+impl Deref for Baz {
+    type Target = Bar;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+fn foo<T>(_: T) where T: Happy {}
+
+fn main() {
+    let baz = Baz(Bar(Foo(LDM)));
+    foo(&baz);
+    //~^ ERROR the trait bound `&Baz: Happy` is not satisfied
+}
diff --git a/src/test/ui/traits/trait-suggest-deferences-multiple.stderr b/src/test/ui/traits/trait-suggest-deferences-multiple.stderr
new file mode 100644
index 00000000000..f9b8bba4b41
--- /dev/null
+++ b/src/test/ui/traits/trait-suggest-deferences-multiple.stderr
@@ -0,0 +1,15 @@
+error[E0277]: the trait bound `&Baz: Happy` is not satisfied
+  --> $DIR/trait-suggest-deferences-multiple.rs:34:9
+   |
+LL | fn foo<T>(_: T) where T: Happy {}
+   |                          ----- required by this bound in `foo`
+...
+LL |     foo(&baz);
+   |         ^^^^
+   |         |
+   |         the trait `Happy` is not implemented for `&Baz`
+   |         help: consider adding dereference here: `&***baz`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0277`.