Skip to content

Commit eb3ad28

Browse files
committed
Improve error message for ambiguous numeric types in closure parameters
1 parent 9725c4b commit eb3ad28

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

compiler/rustc_hir_typeck/src/method/suggest.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2568,6 +2568,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25682568
Applicability::MaybeIncorrect,
25692569
);
25702570
}
2571+
// For closure parameters with reference patterns (e.g., |&v|), suggest the type annotation
2572+
// on the pattern itself, e.g., |&v: &i32|
2573+
(FileName::Real(_), Node::Pat(pat))
2574+
if let Node::Pat(binding_pat) = self.tcx.hir_node(hir_id)
2575+
&& let hir::PatKind::Binding(..) = binding_pat.kind
2576+
&& let Node::Pat(parent_pat) = parent_node
2577+
&& matches!(parent_pat.kind, hir::PatKind::Ref(..)) =>
2578+
{
2579+
err.span_label(span, "you must specify a type for this binding");
2580+
err.span_suggestion_verbose(
2581+
pat.span.shrink_to_hi(),
2582+
"specify the type in the closure argument list",
2583+
format!(": &{concrete_type}"),
2584+
Applicability::MaybeIncorrect,
2585+
);
2586+
}
25712587
_ => {
25722588
err.span_label(span, msg);
25732589
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Test for better error message when numeric type is ambiguous in closure parameter with reference
2+
3+
fn main() {
4+
(0..10).filter(|&v| v.pow(2) > 0);
5+
//~^ ERROR can't call method `pow` on ambiguous numeric type `{integer}`
6+
//~| SUGGESTION &i32
7+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0689]: can't call method `pow` on ambiguous numeric type `{integer}`
2+
--> $DIR/ambiguous-numeric-in-closure-ref.rs:4:27
3+
|
4+
LL | (0..10).filter(|&v| v.pow(2) > 0);
5+
| - ^^^
6+
| |
7+
| you must specify a type for this binding
8+
|
9+
help: specify the type in the closure argument list
10+
|
11+
LL | (0..10).filter(|&v: &i32| v.pow(2) > 0);
12+
| ++++++
13+
14+
error: aborting due to 1 previous error
15+
16+
For more information about this error, try `rustc --explain E0689`.

0 commit comments

Comments
 (0)