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