Skip to content

Commit 662fb06

Browse files
Rollup merge of rust-lang#52647 - csmoe:closure_arg_ignore, r=estebank
Suggest to take and ignore args while closure args count mismatching Closes rust-lang#52473
2 parents c7555ce + 1d79588 commit 662fb06

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/librustc/traits/error_reporting.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,6 +1050,30 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
10501050
if let Some(found_span) = found_span {
10511051
err.span_label(found_span, format!("takes {}", found_str));
10521052

1053+
// Suggest to take and ignore the arguments with expected_args_length `_`s if
1054+
// found arguments is empty (assume the user just wants to ignore args in this case).
1055+
// For example, if `expected_args_length` is 2, suggest `|_, _|`.
1056+
if found_args.is_empty() && is_closure {
1057+
let mut underscores = "_".repeat(expected_args.len())
1058+
.split("")
1059+
.filter(|s| !s.is_empty())
1060+
.collect::<Vec<_>>()
1061+
.join(", ");
1062+
err.span_suggestion_with_applicability(
1063+
found_span,
1064+
&format!(
1065+
"consider changing the closure to take and ignore the expected argument{}",
1066+
if expected_args.len() < 2 {
1067+
""
1068+
} else {
1069+
"s"
1070+
}
1071+
),
1072+
format!("|{}|", underscores),
1073+
Applicability::MachineApplicable,
1074+
);
1075+
}
1076+
10531077
if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
10541078
if fields.len() == expected_args.len() {
10551079
let sugg = fields.iter()

src/test/ui/mismatched_types/closure-arg-count.stderr

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ LL | [1, 2, 3].sort_by(|| panic!());
55
| ^^^^^^^ -- takes 0 arguments
66
| |
77
| expected closure that takes 2 arguments
8+
help: consider changing the closure to take and ignore the expected arguments
9+
|
10+
LL | [1, 2, 3].sort_by(|_, _| panic!());
11+
| ^^^^^^
812

913
error[E0593]: closure is expected to take 2 arguments, but it takes 1 argument
1014
--> $DIR/closure-arg-count.rs:17:15
@@ -51,6 +55,10 @@ note: required by `f`
5155
|
5256
LL | fn f<F: Fn<usize>>(_: F) {}
5357
| ^^^^^^^^^^^^^^^^^^^^^^^^
58+
help: consider changing the closure to take and ignore the expected argument
59+
|
60+
LL | f(|_| panic!());
61+
| ^^^
5462

5563
error[E0593]: closure is expected to take a single 2-tuple as argument, but it takes 2 distinct arguments
5664
--> $DIR/closure-arg-count.rs:26:53

0 commit comments

Comments
 (0)