]> git.lizzy.rs Git - rust.git/commitdiff
Try to suggest dereferences when trait selection failed.
authorDonough Liu <ldm2993593805@163.com>
Sat, 20 Jun 2020 10:30:12 +0000 (18:30 +0800)
committerDonough Liu <ldm2993593805@163.com>
Sat, 20 Jun 2020 10:53:59 +0000 (18:53 +0800)
src/librustc_trait_selection/traits/error_reporting/mod.rs
src/librustc_trait_selection/traits/error_reporting/suggestions.rs
src/test/ui/traits/trait-suggest-deferences-issue-39029.fixed [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-issue-39029.rs [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-issue-39029.stderr [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-issue-62530.fixed [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-issue-62530.rs [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-issue-62530.stderr [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-multiple.fixed [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-multiple.rs [new file with mode: 0644]
src/test/ui/traits/trait-suggest-deferences-multiple.stderr [new file with mode: 0644]

index 060877f80adefd9dc6b1fb0c563f5159a5cabdc5..fd0c1a54d27adec8a6fcbca44a7c9f026a025e31 100644 (file)
@@ -402,6 +402,7 @@ fn report_selection_error(
                             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);
index dfd7dac72d8e1702996d1cec1954a39415d038d7..0c86e33884d6a30f7adf4982186a6a4e44bcdf22 100644 (file)
@@ -3,6 +3,7 @@
     SelectionContext,
 };
 
+use crate::autoderef::Autoderef;
 use crate::infer::InferCtxt;
 use crate::traits::normalize_projection_type;
 
 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 @@ fn suggest_borrow_on_unsized_slice(
         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 @@ fn suggest_restricting_param_bound(
         }
     }
 
+    /// 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 (file)
index 0000000..2bb34b0
--- /dev/null
@@ -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 (file)
index 0000000..33d5246
--- /dev/null
@@ -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 (file)
index 0000000..0bf9794
--- /dev/null
@@ -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 (file)
index 0000000..fa7b916
--- /dev/null
@@ -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 (file)
index 0000000..e785f01
--- /dev/null
@@ -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 (file)
index 0000000..9c2a582
--- /dev/null
@@ -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 (file)
index 0000000..b7160b7
--- /dev/null
@@ -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 (file)
index 0000000..9ac5517
--- /dev/null
@@ -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 (file)
index 0000000..f9b8bba
--- /dev/null
@@ -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`.