Skip to content

Commit d5139f4

Browse files
committed
Auto merge of #95119 - OliverMD:method_suggestions, r=davidtwco
Improve method name suggestions Attempts to improve method name suggestions when a matching method name is not found. The approach taken is use the Levenshtein distance and account for substrings having a high distance but can sometimes be very close to the intended method (eg. empty vs is_empty). resolves #94747
2 parents 2ed6786 + e2dfa23 commit d5139f4

File tree

9 files changed

+104
-10
lines changed

9 files changed

+104
-10
lines changed

compiler/rustc_span/src/lev_distance.rs

+71-2
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,62 @@ pub fn lev_distance(a: &str, b: &str, limit: usize) -> Option<usize> {
4646
(dcol[m] <= limit).then_some(dcol[m])
4747
}
4848

49+
/// Provides a word similarity score between two words that accounts for substrings being more
50+
/// meaningful than a typical Levenshtein distance. The lower the score, the closer the match.
51+
/// 0 is an identical match.
52+
///
53+
/// Uses the Levenshtein distance between the two strings and removes the cost of the length
54+
/// difference. If this is 0 then it is either a substring match or a full word match, in the
55+
/// substring match case we detect this and return `1`. To prevent finding meaningless substrings,
56+
/// eg. "in" in "shrink", we only perform this subtraction of length difference if one of the words
57+
/// is not greater than twice the length of the other. For cases where the words are close in size
58+
/// but not an exact substring then the cost of the length difference is discounted by half.
59+
///
60+
/// Returns `None` if the distance exceeds the limit.
61+
pub fn lev_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<usize> {
62+
let n = a.chars().count();
63+
let m = b.chars().count();
64+
65+
// Check one isn't less than half the length of the other. If this is true then there is a
66+
// big difference in length.
67+
let big_len_diff = (n * 2) < m || (m * 2) < n;
68+
let len_diff = if n < m { m - n } else { n - m };
69+
let lev = lev_distance(a, b, limit + len_diff)?;
70+
71+
// This is the crux, subtracting length difference means exact substring matches will now be 0
72+
let score = lev - len_diff;
73+
74+
// If the score is 0 but the words have different lengths then it's a substring match not a full
75+
// word match
76+
let score = if score == 0 && len_diff > 0 && !big_len_diff {
77+
1 // Exact substring match, but not a total word match so return non-zero
78+
} else if !big_len_diff {
79+
// Not a big difference in length, discount cost of length difference
80+
score + (len_diff + 1) / 2
81+
} else {
82+
// A big difference in length, add back the difference in length to the score
83+
score + len_diff
84+
};
85+
86+
(score <= limit).then_some(score)
87+
}
88+
89+
/// Finds the best match for given word in the given iterator where substrings are meaningful.
90+
///
91+
/// A version of [`find_best_match_for_name`] that uses [`lev_distance_with_substrings`] as the score
92+
/// for word similarity. This takes an optional distance limit which defaults to one-third of the
93+
/// given word.
94+
///
95+
/// Besides the modified Levenshtein, we use case insensitive comparison to improve accuracy
96+
/// on an edge case with a lower(upper)case letters mismatch.
97+
pub fn find_best_match_for_name_with_substrings(
98+
candidates: &[Symbol],
99+
lookup: Symbol,
100+
dist: Option<usize>,
101+
) -> Option<Symbol> {
102+
find_best_match_for_name_impl(true, candidates, lookup, dist)
103+
}
104+
49105
/// Finds the best match for a given word in the given iterator.
50106
///
51107
/// As a loose rule to avoid the obviously incorrect suggestions, it takes
@@ -54,11 +110,20 @@ pub fn lev_distance(a: &str, b: &str, limit: usize) -> Option<usize> {
54110
///
55111
/// Besides Levenshtein, we use case insensitive comparison to improve accuracy
56112
/// on an edge case with a lower(upper)case letters mismatch.
57-
#[cold]
58113
pub fn find_best_match_for_name(
59114
candidates: &[Symbol],
60115
lookup: Symbol,
61116
dist: Option<usize>,
117+
) -> Option<Symbol> {
118+
find_best_match_for_name_impl(false, candidates, lookup, dist)
119+
}
120+
121+
#[cold]
122+
fn find_best_match_for_name_impl(
123+
use_substring_score: bool,
124+
candidates: &[Symbol],
125+
lookup: Symbol,
126+
dist: Option<usize>,
62127
) -> Option<Symbol> {
63128
let lookup = lookup.as_str();
64129
let lookup_uppercase = lookup.to_uppercase();
@@ -74,7 +139,11 @@ pub fn find_best_match_for_name(
74139
let mut dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3);
75140
let mut best = None;
76141
for c in candidates {
77-
match lev_distance(lookup, c.as_str(), dist) {
142+
match if use_substring_score {
143+
lev_distance_with_substrings(lookup, c.as_str(), dist)
144+
} else {
145+
lev_distance(lookup, c.as_str(), dist)
146+
} {
78147
Some(0) => return Some(*c),
79148
Some(d) => {
80149
dist = d - 1;

compiler/rustc_span/src/lev_distance/tests.rs

+11
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,17 @@ fn test_lev_distance_limit() {
2727
assert_eq!(lev_distance("abc", "xyz", 2), None);
2828
}
2929

30+
#[test]
31+
fn test_method_name_similarity_score() {
32+
assert_eq!(lev_distance_with_substrings("empty", "is_empty", 1), Some(1));
33+
assert_eq!(lev_distance_with_substrings("shrunk", "rchunks", 2), None);
34+
assert_eq!(lev_distance_with_substrings("abc", "abcd", 1), Some(1));
35+
assert_eq!(lev_distance_with_substrings("a", "abcd", 1), None);
36+
assert_eq!(lev_distance_with_substrings("edf", "eq", 1), None);
37+
assert_eq!(lev_distance_with_substrings("abc", "xyz", 3), Some(3));
38+
assert_eq!(lev_distance_with_substrings("abcdef", "abcdef", 2), Some(0));
39+
}
40+
3041
#[test]
3142
fn test_find_best_match_for_name() {
3243
use crate::create_default_session_globals_then;

compiler/rustc_typeck/src/check/method/probe.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ use rustc_middle::ty::GenericParamDefKind;
2424
use rustc_middle::ty::{self, ParamEnvAnd, ToPredicate, Ty, TyCtxt, TypeFoldable};
2525
use rustc_session::lint;
2626
use rustc_span::def_id::LocalDefId;
27-
use rustc_span::lev_distance::{find_best_match_for_name, lev_distance};
27+
use rustc_span::lev_distance::{
28+
find_best_match_for_name_with_substrings, lev_distance_with_substrings,
29+
};
2830
use rustc_span::{symbol::Ident, Span, Symbol, DUMMY_SP};
2931
use rustc_trait_selection::autoderef::{self, Autoderef};
3032
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
@@ -1699,7 +1701,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
16991701
.iter()
17001702
.map(|cand| cand.name)
17011703
.collect::<Vec<Symbol>>();
1702-
find_best_match_for_name(&names, self.method_name.unwrap().name, None)
1704+
find_best_match_for_name_with_substrings(
1705+
&names,
1706+
self.method_name.unwrap().name,
1707+
None,
1708+
)
17031709
}
17041710
.unwrap();
17051711
Ok(applicable_close_candidates.into_iter().find(|method| method.name == best_name))
@@ -1856,7 +1862,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
18561862
if x.kind.namespace() != Namespace::ValueNS {
18571863
return false;
18581864
}
1859-
match lev_distance(name.as_str(), x.name.as_str(), max_dist) {
1865+
match lev_distance_with_substrings(name.as_str(), x.name.as_str(), max_dist)
1866+
{
18601867
Some(d) => d > 0,
18611868
None => false,
18621869
}

src/test/ui/associated-item/associated-item-enum.stderr

+4-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ LL | enum Enum { Variant }
1717
| --------- variant or associated item `mispellable_trait` not found here
1818
...
1919
LL | Enum::mispellable_trait();
20-
| ^^^^^^^^^^^^^^^^^ variant or associated item not found in `Enum`
20+
| ^^^^^^^^^^^^^^^^^
21+
| |
22+
| variant or associated item not found in `Enum`
23+
| help: there is an associated function with a similar name: `misspellable`
2124

2225
error[E0599]: no variant or associated item named `MISPELLABLE` found for enum `Enum` in the current scope
2326
--> $DIR/associated-item-enum.rs:19:11

src/test/ui/derives/issue-91550.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ LL | struct Value(u32);
88
| doesn't satisfy `Value: Hash`
99
...
1010
LL | hs.insert(Value(0));
11-
| ^^^^^^ method cannot be called on `HashSet<Value>` due to unsatisfied trait bounds
11+
| ^^^^^^
1212
|
1313
= note: the following trait bounds were not satisfied:
1414
`Value: Eq`

src/test/ui/issues/issue-50264-inner-deref-trait/option-as_deref_mut.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0599]: the method `as_deref_mut` exists for enum `Option<{integer}>`, but
22
--> $DIR/option-as_deref_mut.rs:2:33
33
|
44
LL | let _result = &mut Some(42).as_deref_mut();
5-
| ^^^^^^^^^^^^ method cannot be called on `Option<{integer}>` due to unsatisfied trait bounds
5+
| ^^^^^^^^^^^^
66
|
77
= note: the following trait bounds were not satisfied:
88
`{integer}: Deref`

src/test/ui/issues/issue-50264-inner-deref-trait/result-as_deref_mut.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0599]: the method `as_deref_mut` exists for enum `Result<{integer}, _>`,
22
--> $DIR/result-as_deref_mut.rs:2:31
33
|
44
LL | let _result = &mut Ok(42).as_deref_mut();
5-
| ^^^^^^^^^^^^ method cannot be called on `Result<{integer}, _>` due to unsatisfied trait bounds
5+
| ^^^^^^^^^^^^
66
|
77
= note: the following trait bounds were not satisfied:
88
`{integer}: Deref`

src/test/ui/rust-2018/trait-import-suggestions.stderr

+4
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ help: the following trait is implemented but not in scope; perhaps add a `use` f
4545
|
4646
LL | use std::str::FromStr;
4747
|
48+
help: there is an associated function with a similar name
49+
|
50+
LL | let y = u32::from_str_radix("33");
51+
| ~~~~~~~~~~~~~~
4852

4953
error: aborting due to 4 previous errors
5054

src/test/ui/suggestions/suggest-methods.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ error[E0599]: no method named `count_o` found for type `u32` in the current scop
2323
--> $DIR/suggest-methods.rs:28:19
2424
|
2525
LL | let _ = 63u32.count_o();
26-
| ^^^^^^^ method not found in `u32`
26+
| ^^^^^^^ help: there is an associated function with a similar name: `count_ones`
2727

2828
error: aborting due to 4 previous errors
2929

0 commit comments

Comments
 (0)