Skip to content

Commit b0d17f3

Browse files
committed
Typo suggestion to change bindings with leading underscore
When encountering a binding that isn't found but has a typo suggestion for a binding with a leading underscore, suggest changing the binding definition instead of the use place. Fix #60164.
1 parent cc705b8 commit b0d17f3

File tree

4 files changed

+39
-2
lines changed

4 files changed

+39
-2
lines changed

compiler/rustc_resolve/src/diagnostics.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -1511,17 +1511,30 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
15111511
),
15121512
);
15131513
}
1514+
1515+
let (span, sugg, post) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
1516+
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
1517+
&& let Some(span) = suggestion.span
1518+
&& let Some(candidate) = suggestion.candidate.as_str().strip_prefix("_")
1519+
&& snippet == candidate
1520+
{
1521+
// When the suggested binding change would be from `x` to `_x`, suggest changing the
1522+
// original binding definition instead. (#60164)
1523+
(span, snippet, ", consider changing it")
1524+
} else {
1525+
(span, suggestion.candidate.to_string(), "")
1526+
};
15141527
let msg = match suggestion.target {
15151528
SuggestionTarget::SimilarlyNamed => format!(
1516-
"{} {} with a similar name exists",
1529+
"{} {} with a similar name exists{post}",
15171530
suggestion.res.article(),
15181531
suggestion.res.descr()
15191532
),
15201533
SuggestionTarget::SingleItem => {
15211534
format!("maybe you meant this {}", suggestion.res.descr())
15221535
}
15231536
};
1524-
err.span_suggestion(span, msg, suggestion.candidate, Applicability::MaybeIncorrect);
1537+
err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
15251538
true
15261539
}
15271540

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// run-rustfix
2+
fn main() {
3+
let x = 42; //~ HELP
4+
let _y = x; //~ ERROR
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// run-rustfix
2+
fn main() {
3+
let _x = 42; //~ HELP
4+
let _y = x; //~ ERROR
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error[E0425]: cannot find value `x` in this scope
2+
--> $DIR/silenced-binding-typo.rs:4:14
3+
|
4+
LL | let _y = x;
5+
| ^
6+
|
7+
help: a local variable with a similar name exists, consider changing it
8+
|
9+
LL | let x = 42;
10+
| ~
11+
12+
error: aborting due to previous error
13+
14+
For more information about this error, try `rustc --explain E0425`.

0 commit comments

Comments
 (0)