Variable name corrections should take type into account
I'm not sure whether this is feasible in all cases, but as far as possible, suggestions to rename variables that are typos should take the types of the suggestions into account.
Consider:
fn index(i: usize, a: &[i32]) -> i32 {
a[j]
// ^ did you mean `a`?
}
Here, a is clearly not a valid index for the slice (and we get an error if we attempt the suggestion), but it is suggested anyway. On the other hand, i clearly has the correct type and is a more sensible suggestion.
I'm not sure whether this is feasible in all cases, but as far as possible, suggestions to rename variables that are typos should take the types of the suggestions into account.
Consider:
fn index(i: usize, a: &[i32]) -> i32 { a[j] // ^ did you mean `a`? }Here,
<!-- TRIAGEBOT_START --> <!-- TRIAGEBOT_ASSIGN_START --> <!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":null}$$TRIAGEBOT_ASSIGN_DATA_END --> <!-- TRIAGEBOT_ASSIGN_END --> <!-- TRIAGEBOT_END -->ais clearly not a valid index for the slice (and we get an error if we attempt the suggestion), but it is suggested anyway. On the other hand,iclearly has the correct type and is a more sensible suggestion.rustbot at 2021-10-19 22:30:54
@rustbot claim
pierwill at 2021-10-19 22:30:53
-
Compiling playground v0.0.1 (/playground) error[E0425]: cannot find value `j` in this scope --> src/lib.rs:2:7 | 2 | a[j] | ^ help: a local variable with a similar name exists: `a` For more information about this error, try `rustc --explain E0425`.pierwill at 2021-10-24 20:53:39
The relevant code:
https://github.com/rust-lang/rust/blob/00d5e42e776da900049fe19087bc9b0057ec70cd/compiler/rustc_resolve/src/diagnostics.rs#L1047
https://github.com/rust-lang/rust/blob/00d5e42e776da900049fe19087bc9b0057ec70cd/compiler/rustc_resolve/src/diagnostics.rs#L1104-L1109
pierwill at 2021-10-24 20:55:31
I'd like to start with at least addressing the particular case in this issue.
For the fix, would it make sense to trying using the data given here
https://github.com/rust-lang/rust/blob/00d5e42e776da900049fe19087bc9b0057ec70cd/compiler/rustc_resolve/src/diagnostics.rs#L1047-L1051
to test for something like the presence of a
rustc_ast::ast::ExprKind(Index)orrustc_hir::hir::ExprKind(Index)?@estebank
pierwill at 2021-10-24 21:01:24
That would work for this case in particular, but what the original report is asking is taking advantage of typeck to provide more appropriate suggestions. The problem is that typeck happens after name resolution. To make this work, we'd have to stash the errors with enough metadata around until typeck, and then look at what the types involved are. This seems like it would be quite an undertaking, but possible.
Esteban Kuber at 2021-10-24 21:29:19
Thanks, @estebank. I'll take a look at a naive approach to fixing the particular case in the issue (since it's really not nice at all). In the meantime, @rustbot release-assignment
pierwill at 2021-10-25 17:40:42