]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/util/lev_distance.rs
Rollup merge of #68438 - Aaron1011:fix/tait-non-defining, r=estebank
[rust.git] / src / libsyntax / util / lev_distance.rs
1 // FIXME(Centril): Move to rustc_span?
2
3 use rustc_span::symbol::Symbol;
4 use std::cmp;
5
6 #[cfg(test)]
7 mod tests;
8
9 /// Finds the Levenshtein distance between two strings
10 pub fn lev_distance(a: &str, b: &str) -> usize {
11     // cases which don't require further computation
12     if a.is_empty() {
13         return b.chars().count();
14     } else if b.is_empty() {
15         return a.chars().count();
16     }
17
18     let mut dcol: Vec<_> = (0..=b.len()).collect();
19     let mut t_last = 0;
20
21     for (i, sc) in a.chars().enumerate() {
22         let mut current = i;
23         dcol[0] = current + 1;
24
25         for (j, tc) in b.chars().enumerate() {
26             let next = dcol[j + 1];
27             if sc == tc {
28                 dcol[j + 1] = current;
29             } else {
30                 dcol[j + 1] = cmp::min(current, next);
31                 dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
32             }
33             current = next;
34             t_last = j;
35         }
36     }
37     dcol[t_last + 1]
38 }
39
40 /// Finds the best match for a given word in the given iterator
41 ///
42 /// As a loose rule to avoid the obviously incorrect suggestions, it takes
43 /// an optional limit for the maximum allowable edit distance, which defaults
44 /// to one-third of the given word.
45 ///
46 /// Besides Levenshtein, we use case insensitive comparison to improve accuracy on an edge case with
47 /// a lower(upper)case letters mismatch.
48 pub fn find_best_match_for_name<'a, T>(
49     iter_names: T,
50     lookup: &str,
51     dist: Option<usize>,
52 ) -> Option<Symbol>
53 where
54     T: Iterator<Item = &'a Symbol>,
55 {
56     let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d);
57     let name_vec: Vec<&Symbol> = iter_names.collect();
58
59     let (case_insensitive_match, levenshtein_match) = name_vec
60         .iter()
61         .filter_map(|&name| {
62             let dist = lev_distance(lookup, &name.as_str());
63             if dist <= max_dist { Some((name, dist)) } else { None }
64         })
65         // Here we are collecting the next structure:
66         // (case_insensitive_match, (levenshtein_match, levenshtein_distance))
67         .fold((None, None), |result, (candidate, dist)| {
68             (
69                 if candidate.as_str().to_uppercase() == lookup.to_uppercase() {
70                     Some(candidate)
71                 } else {
72                     result.0
73                 },
74                 match result.1 {
75                     None => Some((candidate, dist)),
76                     Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }),
77                 },
78             )
79         });
80     // Priority of matches:
81     // 1. Exact case insensitive match
82     // 2. Levenshtein distance match
83     // 3. Sorted word match
84     if let Some(candidate) = case_insensitive_match {
85         Some(*candidate)
86     } else if levenshtein_match.is_some() {
87         levenshtein_match.map(|(candidate, _)| *candidate)
88     } else {
89         find_match_by_sorted_words(name_vec, lookup)
90     }
91 }
92
93 fn find_match_by_sorted_words<'a>(iter_names: Vec<&'a Symbol>, lookup: &str) -> Option<Symbol> {
94     iter_names.iter().fold(None, |result, candidate| {
95         if sort_by_words(&candidate.as_str()) == sort_by_words(lookup) {
96             Some(**candidate)
97         } else {
98             result
99         }
100     })
101 }
102
103 fn sort_by_words(name: &str) -> String {
104     let mut split_words: Vec<&str> = name.split('_').collect();
105     split_words.sort();
106     split_words.join("_")
107 }