]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_expressive_names.rs
cbb083a3e161ab4ef2b4c79df6d1800937705ebb
[rust.git] / clippy_lints / src / non_expressive_names.rs
1 use rustc::lint::*;
2 use syntax::codemap::Span;
3 use syntax::parse::token::InternedString;
4 use syntax::ast::*;
5 use syntax::attr;
6 use syntax::visit::{Visitor, walk_block, walk_pat, walk_expr};
7 use utils::{span_lint_and_then, in_macro, span_lint};
8
9 /// **What it does:** This lint warns about names that are very similar and thus confusing
10 ///
11 /// **Why is this bad?** It's hard to distinguish between names that differ only by a single character
12 ///
13 /// **Known problems:** None?
14 ///
15 /// **Example:** `checked_exp` and `checked_expr`
16 declare_lint! {
17     pub SIMILAR_NAMES,
18     Allow,
19     "similarly named items and bindings"
20 }
21
22 /// **What it does:** This lint warns about having too many variables whose name consists of a single character
23 ///
24 /// **Why is this bad?** It's hard to memorize what a variable means without a descriptive name.
25 ///
26 /// **Known problems:** None?
27 ///
28 /// **Example:** let (a, b, c, d, e, f, g) = (...);
29 declare_lint! {
30     pub MANY_SINGLE_CHAR_NAMES,
31     Warn,
32     "too many single character bindings"
33 }
34
35 pub struct NonExpressiveNames {
36     pub max_single_char_names: u64,
37 }
38
39 impl LintPass for NonExpressiveNames {
40     fn get_lints(&self) -> LintArray {
41         lint_array!(SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES)
42     }
43 }
44
45 struct ExistingName {
46     interned: InternedString,
47     span: Span,
48     len: usize,
49     whitelist: &'static [&'static str],
50 }
51
52 struct SimilarNamesLocalVisitor<'a, 'b: 'a> {
53     names: Vec<ExistingName>,
54     cx: &'a EarlyContext<'b>,
55     lint: &'a NonExpressiveNames,
56     single_char_names: Vec<char>,
57 }
58
59 // this list contains lists of names that are allowed to be similar
60 // the assumption is that no name is ever contained in multiple lists.
61 #[cfg_attr(rustfmt, rustfmt_skip)]
62 const WHITELIST: &'static [&'static [&'static str]] = &[
63     &["parsed", "parser"],
64     &["lhs", "rhs"],
65     &["tx", "rx"],
66     &["set", "get"],
67 ];
68
69 struct SimilarNamesNameVisitor<'a, 'b: 'a, 'c: 'b>(&'a mut SimilarNamesLocalVisitor<'b, 'c>);
70
71 impl<'v, 'a, 'b, 'c> Visitor<'v> for SimilarNamesNameVisitor<'a, 'b, 'c> {
72     fn visit_pat(&mut self, pat: &'v Pat) {
73         match pat.node {
74             PatKind::Ident(_, id, _) => self.check_name(id.span, id.node.name),
75             PatKind::Struct(_, ref fields, _) => for field in fields {
76                 if !field.node.is_shorthand {
77                     self.visit_pat(&field.node.pat);
78                 }
79             },
80             _ => walk_pat(self, pat),
81         }
82     }
83 }
84
85 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
86     for &allow in WHITELIST {
87         if whitelisted(interned_name, allow) {
88             return Some(allow);
89         }
90     }
91     None
92 }
93
94 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
95     if list.iter().any(|&name| interned_name == name) {
96         return true;
97     }
98     for name in list {
99         // name_*
100         if interned_name.chars().zip(name.chars()).all(|(l, r)| l == r) {
101             return true;
102         }
103         // *_name
104         if interned_name.chars().rev().zip(name.chars().rev()).all(|(l, r)| l == r) {
105             return true;
106         }
107     }
108     false
109 }
110
111 impl<'a, 'b, 'c> SimilarNamesNameVisitor<'a, 'b, 'c> {
112     fn check_short_name(&mut self, c: char, span: Span) {
113         // make sure we ignore shadowing
114         if self.0.single_char_names.contains(&c) {
115             return;
116         }
117         self.0.single_char_names.push(c);
118         if self.0.single_char_names.len() as u64 >= self.0.lint.max_single_char_names {
119             span_lint(self.0.cx,
120                       MANY_SINGLE_CHAR_NAMES,
121                       span,
122                       &format!("{}th binding whose name is just one char", self.0.single_char_names.len()));
123         }
124     }
125     fn check_name(&mut self, span: Span, name: Name) {
126         if in_macro(self.0.cx, span) {
127             return;
128         }
129         let interned_name = name.as_str();
130         if interned_name.chars().any(char::is_uppercase) {
131             return;
132         }
133         let count = interned_name.chars().count();
134         if count < 3 {
135             if count == 1 {
136                 let c = interned_name.chars().next().expect("already checked");
137                 self.check_short_name(c, span);
138             }
139             return;
140         }
141         for existing_name in &self.0.names {
142             if whitelisted(&interned_name, existing_name.whitelist) {
143                 continue;
144             }
145             let mut split_at = None;
146             if existing_name.len > count {
147                 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
148                     continue;
149                 }
150             } else if existing_name.len < count {
151                 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
152                     continue;
153                 }
154             } else {
155                 let mut interned_chars = interned_name.chars();
156                 let mut existing_chars = existing_name.interned.chars();
157                 let first_i = interned_chars.next().expect("we know we have at least one char");
158                 let first_e = existing_chars.next().expect("we know we have at least one char");
159                 let eq_or_numeric = |a: char, b: char| a == b || a.is_numeric() && b.is_numeric();
160
161                 if eq_or_numeric(first_i, first_e) {
162                     let last_i = interned_chars.next_back().expect("we know we have at least two chars");
163                     let last_e = existing_chars.next_back().expect("we know we have at least two chars");
164                     if eq_or_numeric(last_i, last_e) {
165                         if interned_chars.zip(existing_chars).filter(|&(i, e)| !eq_or_numeric(i, e)).count() != 1 {
166                             continue;
167                         }
168                     } else {
169                         let second_last_i = interned_chars.next_back().expect("we know we have at least three chars");
170                         let second_last_e = existing_chars.next_back().expect("we know we have at least three chars");
171                         if !eq_or_numeric(second_last_i, second_last_e) || second_last_i == '_' ||
172                            !interned_chars.zip(existing_chars).all(|(i, e)| eq_or_numeric(i, e)) {
173                             // allowed similarity foo_x, foo_y
174                             // or too many chars differ (foo_x, boo_y) or (foox, booy)
175                             continue;
176                         }
177                         split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
178                     }
179                 } else {
180                     let second_i = interned_chars.next().expect("we know we have at least two chars");
181                     let second_e = existing_chars.next().expect("we know we have at least two chars");
182                     if !eq_or_numeric(second_i, second_e) || second_i == '_' ||
183                        !interned_chars.zip(existing_chars).all(|(i, e)| eq_or_numeric(i, e)) {
184                         // allowed similarity x_foo, y_foo
185                         // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
186                         continue;
187                     }
188                     split_at = interned_name.chars().next().map(|c| c.len_utf8());
189                 }
190             }
191             span_lint_and_then(self.0.cx,
192                                SIMILAR_NAMES,
193                                span,
194                                "binding's name is too similar to existing binding",
195                                |diag| {
196                                    diag.span_note(existing_name.span, "existing binding defined here");
197                                    if let Some(split) = split_at {
198                                        diag.span_help(span,
199                                                       &format!("separate the discriminating character by an \
200                                                                 underscore like: `{}_{}`",
201                                                                &interned_name[..split],
202                                                                &interned_name[split..]));
203                                    }
204                                });
205             return;
206         }
207         self.0.names.push(ExistingName {
208             whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
209             interned: interned_name,
210             span: span,
211             len: count,
212         });
213     }
214 }
215
216 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
217     /// ensure scoping rules work
218     fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
219         let n = self.names.len();
220         let single_char_count = self.single_char_names.len();
221         f(self);
222         self.names.truncate(n);
223         self.single_char_names.truncate(single_char_count);
224     }
225 }
226
227 impl<'v, 'a, 'b> Visitor<'v> for SimilarNamesLocalVisitor<'a, 'b> {
228     fn visit_local(&mut self, local: &'v Local) {
229         if let Some(ref init) = local.init {
230             self.apply(|this| walk_expr(this, &**init));
231         }
232         // add the pattern after the expression because the bindings aren't available yet in the init expression
233         SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
234     }
235     fn visit_block(&mut self, blk: &'v Block) {
236         self.apply(|this| walk_block(this, blk));
237     }
238     fn visit_arm(&mut self, arm: &'v Arm) {
239         self.apply(|this| {
240             // just go through the first pattern, as either all patterns bind the same bindings or rustc would have errored much earlier
241             SimilarNamesNameVisitor(this).visit_pat(&arm.pats[0]);
242             this.apply(|this| walk_expr(this, &arm.body));
243         });
244     }
245     fn visit_item(&mut self, _: &'v Item) {
246         // do not recurse into inner items
247     }
248 }
249
250 impl EarlyLintPass for NonExpressiveNames {
251     fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
252         if let ItemKind::Fn(ref decl, _, _, _, _, ref blk) = item.node {
253             if !attr::contains_name(&item.attrs, "test") {
254                 let mut visitor = SimilarNamesLocalVisitor {
255                     names: Vec::new(),
256                     cx: cx,
257                     lint: self,
258                     single_char_names: Vec::new(),
259                 };
260                 // initialize with function arguments
261                 for arg in &decl.inputs {
262                     SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
263                 }
264                 // walk all other bindings
265                 walk_block(&mut visitor, blk);
266             }
267         }
268     }
269 }
270
271 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
272 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
273     debug_assert!(a_name.chars().count() < b_name.chars().count());
274     let mut a_chars = a_name.chars();
275     let mut b_chars = b_name.chars();
276     while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
277         if a == b {
278             continue;
279         }
280         if let Some(b2) = b_chars.next() {
281             // check if there's just one character inserted
282             return a != b2 || a_chars.ne(b_chars);
283         } else {
284             // tuple
285             // ntuple
286             return true;
287         }
288     }
289     // for item in items
290     true
291 }