Skip to content

use structured suggestion for method calls #57291

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/librustc_typeck/check/method/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub use self::CandidateSource::*;
pub use self::suggest::{SelfSource, TraitInfo};

use check::FnCtxt;
use errors::{Applicability, DiagnosticBuilder};
use namespace::Namespace;
use rustc_data_structures::sync::Lrc;
use rustc::hir;
Expand Down Expand Up @@ -123,6 +124,42 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
}
}

/// Add a suggestion to call the given method to the provided diagnostic.
crate fn suggest_method_call(
&self,
err: &mut DiagnosticBuilder<'a>,
msg: &str,
method_name: ast::Ident,
self_ty: Ty<'tcx>,
call_expr_id: ast::NodeId,
) {
let has_params = self
.probe_for_name(
method_name.span,
probe::Mode::MethodCall,
method_name,
IsSuggestion(false),
self_ty,
call_expr_id,
ProbeScope::TraitsInScope,
)
.and_then(|pick| {
let sig = self.tcx.fn_sig(pick.item.def_id);
Ok(sig.inputs().skip_binder().len() > 1)
});

let (suggestion, applicability) = if has_params.unwrap_or_default() {
(
format!("{}(...)", method_name),
Applicability::HasPlaceholders,
)
} else {
(format!("{}()", method_name), Applicability::MaybeIncorrect)
};

err.span_suggestion_with_applicability(method_name.span, msg, suggestion, applicability);
}

/// Performs method lookup. If lookup is successful, it will return the callee
/// and store an appropriate adjustment for the self-expr. In some cases it may
/// report an error (e.g., invoking the `drop` method).
Expand Down
52 changes: 46 additions & 6 deletions src/librustc_typeck/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3412,19 +3412,37 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
"field `{}` of struct `{}` is private",
field, struct_path);
// Also check if an accessible method exists, which is often what is meant.
if self.method_exists(field, expr_t, expr.id, false) {
err.note(&format!("a method `{}` also exists, perhaps you wish to call it", field));
if self.method_exists(field, expr_t, expr.id, false) && !self.expr_in_place(expr.id) {
self.suggest_method_call(
&mut err,
&format!("a method `{}` also exists, call it with parentheses", field),
field,
expr_t,
expr.id,
);
}
err.emit();
field_ty
} else if field.name == keywords::Invalid.name() {
self.tcx().types.err
} else if self.method_exists(field, expr_t, expr.id, true) {
type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
"attempted to take value of method `{}` on type `{}`",
field, expr_t)
.help("maybe a `()` to call it is missing?")
.emit();
field, expr_t);

if !self.expr_in_place(expr.id) {
self.suggest_method_call(
&mut err,
"use parentheses to call the method",
field,
expr_t,
expr.id
);
} else {
err.help("methods are immutable and cannot be assigned to");
}

err.emit();
self.tcx().types.err
} else {
if !expr_t.is_primitive_ty() {
Expand Down Expand Up @@ -5435,6 +5453,28 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
original_values,
query_result)
}

/// Returns whether an expression is contained inside the LHS of an assignment expression.
fn expr_in_place(&self, mut expr_id: ast::NodeId) -> bool {
let mut contained_in_place = false;

while let hir::Node::Expr(parent_expr) =
self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id))
{
match &parent_expr.node {
hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
if lhs.id == expr_id {
contained_in_place = true;
break;
}
}
_ => (),
}
expr_id = parent_expr.id;
}

contained_in_place
}
}

pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
Expand Down
1 change: 1 addition & 0 deletions src/test/ui/assign-to-method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ fn cat(in_x : usize, in_y : isize) -> Cat {
fn main() {
let nyan : Cat = cat(52, 99);
nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method
nyan.speak += || println!("meow"); //~ ERROR attempted to take value of method
}
12 changes: 10 additions & 2 deletions src/test/ui/assign-to-method.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,16 @@ error[E0615]: attempted to take value of method `speak` on type `Cat`
LL | nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method
| ^^^^^
|
= help: maybe a `()` to call it is missing?
= help: methods are immutable and cannot be assigned to

error: aborting due to previous error
error[E0615]: attempted to take value of method `speak` on type `Cat`
--> $DIR/assign-to-method.rs:21:8
|
LL | nyan.speak += || println!("meow"); //~ ERROR attempted to take value of method
| ^^^^^
|
= help: methods are immutable and cannot be assigned to

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0615`.
8 changes: 2 additions & 6 deletions src/test/ui/did_you_mean/issue-40396.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,13 @@ error[E0615]: attempted to take value of method `collect` on type `std::ops::Ran
--> $DIR/issue-40396.rs:2:13
|
LL | (0..13).collect<Vec<i32>>();
| ^^^^^^^
|
= help: maybe a `()` to call it is missing?
| ^^^^^^^ help: use parentheses to call the method: `collect()`

error[E0615]: attempted to take value of method `collect` on type `std::ops::Range<{integer}>`
--> $DIR/issue-40396.rs:18:13
|
LL | (0..13).collect<Vec<i32>();
| ^^^^^^^
|
= help: maybe a `()` to call it is missing?
| ^^^^^^^ help: use parentheses to call the method: `collect()`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestions in src/test/ui/did_you_mean/issue-40396.stderr are suboptimal. I could check if the containing expression is BinOp, but I'm not sure if that's general enough. Any ideas?

Though this is a case that will need to be accounted for specifically, as the ideal case would be for the parser to actually be able to parse type setting without the turbofish and emit a customized relevant suggestion to use the turbofish. If we do that, then this error will not trigger.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would I distinguish this case from something like

struct Foo;

impl Foo {
    fn bar(&self) -> i32 {
        0
    }
}

fn main() {
    let foo = 1;
    Foo.bar<foo>();
}

where we should still apply the suggestion?

Copy link
Contributor

@estebank estebank Jan 3, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What would be the "perfect" suggestion in that case? IMO, that's borderline "unrecoverable": the code is attempting (assumption 1) to set a type argument without using turbofish and (assumption 2) calling that method. Because this requires not one but two assumptions, the likelihood of a suggestion being incorrect increases. In this case we would emit the following, which I think is "good enough" (at least for now):

error: chained comparison operators require parentheses
  --> src/main.rs:11:12
   |
11 |     Foo.bar<foo>();
   |            ^^^^^^
   |
   = help: use `::<...>` instead of `<...>` if you meant to specify type arguments
   = help: or use `(...)` if you meant to specify fn arguments

error[E0615]: attempted to take value of method `bar` on type `Foo`
  --> src/main.rs:11:9
   |
11 |     Foo.bar<foo>();
   |         ^^^ help: use parentheses to call the method: `bar()`

error[E0308]: mismatched types
  --> src/main.rs:11:17
   |
11 |     Foo.bar<foo>();
   |                 ^^ expected bool, found ()
   |
   = note: expected type `bool`
              found type `()`

In an ideal compiler, we could keep around enough information about parse recoveries like the above and figure out if the call and boolean comparison looked like a missing turbofish, and effectively elide errors:

error: chained comparison operators require parentheses
  --> src/main.rs:11:12
   |
11 |     Foo.bar<foo>();
   |            ^^^^^^
   |
   = help: use `::<...>` instead of `<...>` if you meant to specify type arguments
   = help: or use `(...)` if you meant to specify fn arguments

error[E0615]: attempted to take value of method `bar` on type `Foo`
  --> src/main.rs:11:9
   |
11 |     Foo.bar<foo>();
   |         ^^^^^^^^^^ help: it seems like you tried to use type arguments in a method that doesn't require them: `bar()`

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose a better example is this:

struct Foo;

impl Foo {
    fn bar(&self) -> i32 {
        0
    }
}

fn main() {
    let Vec = 1;
    Foo.bar < Vec;
}

The user is attempting to compare the result of a method call, but forgot the parens. If we don't emit the suggestion because it's parsed as part of a BinOp <, it would be incorrect. How can I distinguish this from a missing turbofish?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'd need to keep track of either NodeIds or Spans where the turbofish note due to chained comparison operators in a set owned by the parser. We then need to keep that arround in the Sess. When finding this case in the type checker, we look back at the sess to see if the place where we're about to suggest adding a () is covered by the turbofish suggestion or not. All of this should be done in a separate PR, as it might quickly become very involved.


error[E0308]: mismatched types
--> $DIR/issue-40396.rs:18:29
Expand Down
4 changes: 1 addition & 3 deletions src/test/ui/error-codes/E0615.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ error[E0615]: attempted to take value of method `method` on type `Foo`
--> $DIR/E0615.rs:11:7
|
LL | f.method; //~ ERROR E0615
| ^^^^^^
|
= help: maybe a `()` to call it is missing?
| ^^^^^^ help: use parentheses to call the method: `method()`

error: aborting due to previous error

Expand Down
4 changes: 1 addition & 3 deletions src/test/ui/implicit-method-bind.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ error[E0615]: attempted to take value of method `abs` on type `i32`
--> $DIR/implicit-method-bind.rs:2:20
|
LL | let _f = 10i32.abs; //~ ERROR attempted to take value of method
| ^^^
|
= help: maybe a `()` to call it is missing?
| ^^^ help: use parentheses to call the method: `abs()`

error: aborting due to previous error

Expand Down
4 changes: 1 addition & 3 deletions src/test/ui/issues/issue-13853-2.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ error[E0615]: attempted to take value of method `get` on type `std::boxed::Box<(
--> $DIR/issue-13853-2.rs:5:39
|
LL | fn foo(res : Box<ResponseHook>) { res.get } //~ ERROR attempted to take value of method
| ^^^
|
= help: maybe a `()` to call it is missing?
| ^^^ help: use parentheses to call the method: `get()`

error: aborting due to previous error

Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/issues/issue-26472.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ mod sub {

fn main() {
let s = sub::S::new();
let v = s.len;
//~^ ERROR field `len` of struct `sub::S` is private
let v = s.len; //~ ERROR field `len` of struct `sub::S` is private
s.len = v; //~ ERROR field `len` of struct `sub::S` is private
}
14 changes: 10 additions & 4 deletions src/test/ui/issues/issue-26472.stderr
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
error[E0616]: field `len` of struct `sub::S` is private
--> $DIR/issue-26472.rs:11:13
|
LL | let v = s.len;
| ^^^^^
LL | let v = s.len; //~ ERROR field `len` of struct `sub::S` is private
| ^^---
| |
| help: a method `len` also exists, call it with parentheses: `len()`

error[E0616]: field `len` of struct `sub::S` is private
--> $DIR/issue-26472.rs:12:5
|
= note: a method `len` also exists, perhaps you wish to call it
LL | s.len = v; //~ ERROR field `len` of struct `sub::S` is private
| ^^^^^

error: aborting due to previous error
error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0616`.
8 changes: 2 additions & 6 deletions src/test/ui/methods/method-missing-call.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,13 @@ error[E0615]: attempted to take value of method `get_x` on type `Point`
--> $DIR/method-missing-call.rs:22:26
|
LL | .get_x;//~ ERROR attempted to take value of method `get_x` on type `Point`
| ^^^^^
|
= help: maybe a `()` to call it is missing?
| ^^^^^ help: use parentheses to call the method: `get_x()`

error[E0615]: attempted to take value of method `filter_map` on type `std::iter::Filter<std::iter::Map<std::slice::Iter<'_, {integer}>, [closure@$DIR/method-missing-call.rs:27:20: 27:25]>, [closure@$DIR/method-missing-call.rs:28:23: 28:35]>`
--> $DIR/method-missing-call.rs:29:16
|
LL | .filter_map; //~ ERROR attempted to take value of method `filter_map` on type
| ^^^^^^^^^^
|
= help: maybe a `()` to call it is missing?
| ^^^^^^^^^^ help: use parentheses to call the method: `filter_map(...)`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be amazing if we inspected the arguments of filter_map to suggest even more (like |item| { /**/ }), but that's definitely part of the scope of this PR :)


error: aborting due to 2 previous errors

Expand Down
3 changes: 2 additions & 1 deletion src/test/ui/union/union-suggest-field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ fn main() {
//~| SUGGESTION principal

let y = u.calculate; //~ ERROR attempted to take value of method `calculate` on type `U`
//~| HELP maybe a `()` to call it is missing
//~| HELP use parentheses to call the method
//~| SUGGESTION calculate()
}
4 changes: 1 addition & 3 deletions src/test/ui/union/union-suggest-field.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ error[E0615]: attempted to take value of method `calculate` on type `U`
--> $DIR/union-suggest-field.rs:18:15
|
LL | let y = u.calculate; //~ ERROR attempted to take value of method `calculate` on type `U`
| ^^^^^^^^^
|
= help: maybe a `()` to call it is missing?
| ^^^^^^^^^ help: use parentheses to call the method: `calculate()`

error: aborting due to 3 previous errors

Expand Down