rustc_span/
edit_distance.rs

1//! Edit distances.
2//!
3//! The [edit distance] is a metric for measuring the difference between two strings.
4//!
5//! [edit distance]: https://en.wikipedia.org/wiki/Edit_distance
6
7// The current implementation is the restricted Damerau-Levenshtein algorithm. It is restricted
8// because it does not permit modifying characters that have already been transposed. The specific
9// algorithm should not matter to the caller of the methods, which is why it is not noted in the
10// documentation.
11
12use std::{cmp, mem};
13
14use crate::Symbol;
15
16#[cfg(test)]
17mod tests;
18
19/// Finds the [edit distance] between two strings.
20///
21/// Returns `None` if the distance exceeds the limit.
22///
23/// [edit distance]: https://en.wikipedia.org/wiki/Edit_distance
24pub fn edit_distance(a: &str, b: &str, limit: usize) -> Option<usize> {
25    let mut a = &a.chars().collect::<Vec<_>>()[..];
26    let mut b = &b.chars().collect::<Vec<_>>()[..];
27
28    // Ensure that `b` is the shorter string, minimizing memory use.
29    if a.len() < b.len() {
30        mem::swap(&mut a, &mut b);
31    }
32
33    let min_dist = a.len() - b.len();
34    // If we know the limit will be exceeded, we can return early.
35    if min_dist > limit {
36        return None;
37    }
38
39    // Strip common prefix.
40    while let Some(((b_char, b_rest), (a_char, a_rest))) = b.split_first().zip(a.split_first())
41        && a_char == b_char
42    {
43        a = a_rest;
44        b = b_rest;
45    }
46    // Strip common suffix.
47    while let Some(((b_char, b_rest), (a_char, a_rest))) = b.split_last().zip(a.split_last())
48        && a_char == b_char
49    {
50        a = a_rest;
51        b = b_rest;
52    }
53
54    // If either string is empty, the distance is the length of the other.
55    // We know that `b` is the shorter string, so we don't need to check `a`.
56    if b.len() == 0 {
57        return Some(min_dist);
58    }
59
60    let mut prev_prev = vec![usize::MAX; b.len() + 1];
61    let mut prev = (0..=b.len()).collect::<Vec<_>>();
62    let mut current = vec![0; b.len() + 1];
63
64    // row by row
65    for i in 1..=a.len() {
66        current[0] = i;
67        let a_idx = i - 1;
68
69        // column by column
70        for j in 1..=b.len() {
71            let b_idx = j - 1;
72
73            // There is no cost to substitute a character with itself.
74            let substitution_cost = if a[a_idx] == b[b_idx] { 0 } else { 1 };
75
76            current[j] = cmp::min(
77                // deletion
78                prev[j] + 1,
79                cmp::min(
80                    // insertion
81                    current[j - 1] + 1,
82                    // substitution
83                    prev[j - 1] + substitution_cost,
84                ),
85            );
86
87            if (i > 1) && (j > 1) && (a[a_idx] == b[b_idx - 1]) && (a[a_idx - 1] == b[b_idx]) {
88                // transposition
89                current[j] = cmp::min(current[j], prev_prev[j - 2] + 1);
90            }
91        }
92
93        // Rotate the buffers, reusing the memory.
94        [prev_prev, prev, current] = [prev, current, prev_prev];
95    }
96
97    // `prev` because we already rotated the buffers.
98    let distance = prev[b.len()];
99    (distance <= limit).then_some(distance)
100}
101
102/// Provides a word similarity score between two words that accounts for substrings being more
103/// meaningful than a typical edit distance. The lower the score, the closer the match. 0 is an
104/// identical match.
105///
106/// Uses the edit distance between the two strings and removes the cost of the length difference.
107/// If this is 0 then it is either a substring match or a full word match, in the substring match
108/// case we detect this and return `1`. To prevent finding meaningless substrings, eg. "in" in
109/// "shrink", we only perform this subtraction of length difference if one of the words is not
110/// greater than twice the length of the other. For cases where the words are close in size but not
111/// an exact substring then the cost of the length difference is discounted by half.
112///
113/// Returns `None` if the distance exceeds the limit.
114pub fn edit_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<usize> {
115    let n = a.chars().count();
116    let m = b.chars().count();
117
118    // Check one isn't less than half the length of the other. If this is true then there is a
119    // big difference in length.
120    let big_len_diff = (n * 2) < m || (m * 2) < n;
121    let len_diff = m.abs_diff(n);
122    let distance = edit_distance(a, b, limit + len_diff)?;
123
124    // This is the crux, subtracting length difference means exact substring matches will now be 0
125    let score = distance - len_diff;
126
127    // If the score is 0 but the words have different lengths then it's a substring match not a full
128    // word match
129    let score = if score == 0 && len_diff > 0 && !big_len_diff {
130        1 // Exact substring match, but not a total word match so return non-zero
131    } else if !big_len_diff {
132        // Not a big difference in length, discount cost of length difference
133        score + (len_diff + 1) / 2
134    } else {
135        // A big difference in length, add back the difference in length to the score
136        score + len_diff
137    };
138
139    (score <= limit).then_some(score)
140}
141
142/// Finds the best match for given word in the given iterator where substrings are meaningful.
143///
144/// A version of [`find_best_match_for_name`] that uses [`edit_distance_with_substrings`] as the
145/// score for word similarity. This takes an optional distance limit which defaults to one-third of
146/// the given word.
147///
148/// We use case insensitive comparison to improve accuracy on an edge case with a lower(upper)case
149/// letters mismatch.
150pub fn find_best_match_for_name_with_substrings(
151    candidates: &[Symbol],
152    lookup: Symbol,
153    dist: Option<usize>,
154) -> Option<Symbol> {
155    find_best_match_for_name_impl(true, candidates, lookup, dist)
156}
157
158/// Finds the best match for a given word in the given iterator.
159///
160/// As a loose rule to avoid the obviously incorrect suggestions, it takes
161/// an optional limit for the maximum allowable edit distance, which defaults
162/// to one-third of the given word.
163///
164/// We use case insensitive comparison to improve accuracy on an edge case with a lower(upper)case
165/// letters mismatch.
166pub fn find_best_match_for_name(
167    candidates: &[Symbol],
168    lookup: Symbol,
169    dist: Option<usize>,
170) -> Option<Symbol> {
171    find_best_match_for_name_impl(false, candidates, lookup, dist)
172}
173
174/// Find the best match for multiple words
175///
176/// This function is intended for use when the desired match would never be
177/// returned due to a substring in `lookup` which is superfluous.
178///
179/// For example, when looking for the closest lint name to `clippy:missing_docs`,
180/// we would find `clippy::erasing_op`, despite `missing_docs` existing and being a better suggestion.
181/// `missing_docs` would have a larger edit distance because it does not contain the `clippy` tool prefix.
182/// In order to find `missing_docs`, this function takes multiple lookup strings, computes the best match
183/// for each and returns the match which had the lowest edit distance. In our example, `clippy:missing_docs` and
184/// `missing_docs` would be `lookups`, enabling `missing_docs` to be the best match, as desired.
185pub fn find_best_match_for_names(
186    candidates: &[Symbol],
187    lookups: &[Symbol],
188    dist: Option<usize>,
189) -> Option<Symbol> {
190    lookups
191        .iter()
192        .map(|s| (s, find_best_match_for_name_impl(false, candidates, *s, dist)))
193        .filter_map(|(s, r)| r.map(|r| (s, r)))
194        .min_by(|(s1, r1), (s2, r2)| {
195            let d1 = edit_distance(s1.as_str(), r1.as_str(), usize::MAX).unwrap();
196            let d2 = edit_distance(s2.as_str(), r2.as_str(), usize::MAX).unwrap();
197            d1.cmp(&d2)
198        })
199        .map(|(_, r)| r)
200}
201
202#[cold]
203fn find_best_match_for_name_impl(
204    use_substring_score: bool,
205    candidates: &[Symbol],
206    lookup_symbol: Symbol,
207    dist: Option<usize>,
208) -> Option<Symbol> {
209    let lookup = lookup_symbol.as_str();
210    let lookup_uppercase = lookup.to_uppercase();
211
212    // Priority of matches:
213    // 1. Exact case insensitive match
214    // 2. Edit distance match
215    // 3. Sorted word match
216    if let Some(c) = candidates.iter().find(|c| c.as_str().to_uppercase() == lookup_uppercase) {
217        return Some(*c);
218    }
219
220    // `fn edit_distance()` use `chars()` to calculate edit distance, so we must
221    // also use `chars()` (and not `str::len()`) to calculate length here.
222    let lookup_len = lookup.chars().count();
223
224    let mut dist = dist.unwrap_or_else(|| cmp::max(lookup_len, 3) / 3);
225    let mut best = None;
226    // store the candidates with the same distance, only for `use_substring_score` current.
227    let mut next_candidates = vec![];
228    for c in candidates {
229        match if use_substring_score {
230            edit_distance_with_substrings(lookup, c.as_str(), dist)
231        } else {
232            edit_distance(lookup, c.as_str(), dist)
233        } {
234            Some(0) => return Some(*c),
235            Some(d) => {
236                if use_substring_score {
237                    if d < dist {
238                        dist = d;
239                        next_candidates.clear();
240                    } else {
241                        // `d == dist` here, we need to store the candidates with the same distance
242                        // so we won't decrease the distance in the next loop.
243                    }
244                    next_candidates.push(*c);
245                } else {
246                    dist = d - 1;
247                }
248                best = Some(*c);
249            }
250            None => {}
251        }
252    }
253
254    // We have a tie among several candidates, try to select the best among them ignoring substrings.
255    // For example, the candidates list `force_capture`, `capture`, and user inputted `forced_capture`,
256    // we select `force_capture` with a extra round of edit distance calculation.
257    if next_candidates.len() > 1 {
258        debug_assert!(use_substring_score);
259        best = find_best_match_for_name_impl(
260            false,
261            &next_candidates,
262            lookup_symbol,
263            Some(lookup.len()),
264        );
265    }
266    if best.is_some() {
267        return best;
268    }
269
270    find_match_by_sorted_words(candidates, lookup)
271}
272
273fn find_match_by_sorted_words(iter_names: &[Symbol], lookup: &str) -> Option<Symbol> {
274    let lookup_sorted_by_words = sort_by_words(lookup);
275    iter_names.iter().fold(None, |result, candidate| {
276        if sort_by_words(candidate.as_str()) == lookup_sorted_by_words {
277            Some(*candidate)
278        } else {
279            result
280        }
281    })
282}
283
284fn sort_by_words(name: &str) -> Vec<&str> {
285    let mut split_words: Vec<&str> = name.split('_').collect();
286    // We are sorting primitive &strs and can use unstable sort here.
287    split_words.sort_unstable();
288    split_words
289}