]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/util/lev_distance.rs
Auto merge of #65202 - pietroalbini:scriptify-ci-config, r=alexcrichton
[rust.git] / src / libsyntax / util / lev_distance.rs
1 use std::cmp;
2 use crate::symbol::Symbol;
3
4 #[cfg(test)]
5 mod tests;
6
7 /// Finds the Levenshtein distance between two strings
8 pub fn lev_distance(a: &str, b: &str) -> usize {
9     // cases which don't require further computation
10     if a.is_empty() {
11         return b.chars().count();
12     } else if b.is_empty() {
13         return a.chars().count();
14     }
15
16     let mut dcol: Vec<_> = (0..=b.len()).collect();
17     let mut t_last = 0;
18
19     for (i, sc) in a.chars().enumerate() {
20         let mut current = i;
21         dcol[0] = current + 1;
22
23         for (j, tc) in b.chars().enumerate() {
24             let next = dcol[j + 1];
25             if sc == tc {
26                 dcol[j + 1] = current;
27             } else {
28                 dcol[j + 1] = cmp::min(current, next);
29                 dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
30             }
31             current = next;
32             t_last = j;
33         }
34     }
35     dcol[t_last + 1]
36 }
37
38 /// Finds the best match for a given word in the given iterator
39 ///
40 /// As a loose rule to avoid the obviously incorrect suggestions, it takes
41 /// an optional limit for the maximum allowable edit distance, which defaults
42 /// to one-third of the given word.
43 ///
44 /// Besides Levenshtein, we use case insensitive comparison to improve accuracy on an edge case with
45 /// a lower(upper)case letters mismatch.
46 pub fn find_best_match_for_name<'a, T>(iter_names: T,
47                                        lookup: &str,
48                                        dist: Option<usize>) -> Option<Symbol>
49     where T: Iterator<Item = &'a Symbol> {
50     let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d);
51
52     let (case_insensitive_match, levenstein_match) = iter_names
53     .filter_map(|&name| {
54         let dist = lev_distance(lookup, &name.as_str());
55         if dist <= max_dist {
56             Some((name, dist))
57         } else {
58             None
59         }
60     })
61     // Here we are collecting the next structure:
62     // (case_insensitive_match, (levenstein_match, levenstein_distance))
63     .fold((None, None), |result, (candidate, dist)| {
64         (
65             if candidate.as_str().to_uppercase() == lookup.to_uppercase() {
66                 Some(candidate)
67             } else {
68                 result.0
69             },
70             match result.1 {
71                 None => Some((candidate, dist)),
72                 Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) })
73             }
74         )
75     });
76
77     if let Some(candidate) = case_insensitive_match {
78         Some(candidate) // exact case insensitive match has a higher priority
79     } else {
80         if let Some((candidate, _)) = levenstein_match { Some(candidate) } else { None }
81     }
82 }