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