]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_expressive_names.rs
Auto merge of #4478 - tsurai:master, r=flip1995
[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, impl_lint_pass};
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 #[derive(Copy, Clone)]
67 pub struct NonExpressiveNames {
68     pub single_char_binding_names_threshold: u64,
69 }
70
71 impl_lint_pass!(NonExpressiveNames => [SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS]);
72
73 struct ExistingName {
74     interned: LocalInternedString,
75     span: Span,
76     len: usize,
77     whitelist: &'static [&'static str],
78 }
79
80 struct SimilarNamesLocalVisitor<'a, 'tcx> {
81     names: Vec<ExistingName>,
82     cx: &'a EarlyContext<'tcx>,
83     lint: &'a NonExpressiveNames,
84
85     /// A stack of scopes containing the single-character bindings in each scope.
86     single_char_names: Vec<Vec<Ident>>,
87 }
88
89 impl<'a, 'tcx> SimilarNamesLocalVisitor<'a, 'tcx> {
90     fn check_single_char_names(&self) {
91         let num_single_char_names = self.single_char_names.iter().flatten().count();
92         let threshold = self.lint.single_char_binding_names_threshold;
93         if num_single_char_names as u64 >= threshold {
94             let span = self
95                 .single_char_names
96                 .iter()
97                 .flatten()
98                 .map(|ident| ident.span)
99                 .collect::<Vec<_>>();
100             span_lint(
101                 self.cx,
102                 MANY_SINGLE_CHAR_NAMES,
103                 span,
104                 &format!(
105                     "{} bindings with single-character names in scope",
106                     num_single_char_names
107                 ),
108             );
109         }
110     }
111 }
112
113 // this list contains lists of names that are allowed to be similar
114 // the assumption is that no name is ever contained in multiple lists.
115 #[rustfmt::skip]
116 const WHITELIST: &[&[&str]] = &[
117     &["parsed", "parser"],
118     &["lhs", "rhs"],
119     &["tx", "rx"],
120     &["set", "get"],
121     &["args", "arms"],
122     &["qpath", "path"],
123     &["lit", "lint"],
124 ];
125
126 struct SimilarNamesNameVisitor<'a, 'tcx, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
127
128 impl<'a, 'tcx, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
129     fn visit_pat(&mut self, pat: &'tcx Pat) {
130         match pat.node {
131             PatKind::Ident(_, ident, _) => self.check_ident(ident),
132             PatKind::Struct(_, ref fields, _) => {
133                 for field in fields {
134                     if !field.is_shorthand {
135                         self.visit_pat(&field.pat);
136                     }
137                 }
138             },
139             // just go through the first pattern, as either all patterns
140             // bind the same bindings or rustc would have errored much earlier
141             PatKind::Or(ref pats) => self.visit_pat(&pats[0]),
142             _ => walk_pat(self, pat),
143         }
144     }
145     fn visit_mac(&mut self, _mac: &Mac) {
146         // do not check macs
147     }
148 }
149
150 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
151     for &allow in WHITELIST {
152         if whitelisted(interned_name, allow) {
153             return Some(allow);
154         }
155     }
156     None
157 }
158
159 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
160     list.iter()
161         .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
162 }
163
164 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
165     fn check_short_ident(&mut self, ident: Ident) {
166         // Ignore shadowing
167         if self
168             .0
169             .single_char_names
170             .iter()
171             .flatten()
172             .any(|id| id.name == ident.name)
173         {
174             return;
175         }
176
177         if let Some(scope) = &mut self.0.single_char_names.last_mut() {
178             scope.push(ident);
179         }
180     }
181
182     #[allow(clippy::too_many_lines)]
183     fn check_ident(&mut self, ident: Ident) {
184         let interned_name = ident.name.as_str();
185         if interned_name.chars().any(char::is_uppercase) {
186             return;
187         }
188         if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
189             span_lint(
190                 self.0.cx,
191                 JUST_UNDERSCORES_AND_DIGITS,
192                 ident.span,
193                 "consider choosing a more descriptive name",
194             );
195             return;
196         }
197         let count = interned_name.chars().count();
198         if count < 3 {
199             if count == 1 {
200                 self.check_short_ident(ident);
201             }
202             return;
203         }
204         for existing_name in &self.0.names {
205             if whitelisted(&interned_name, existing_name.whitelist) {
206                 continue;
207             }
208             let mut split_at = None;
209             if existing_name.len > count {
210                 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
211                     continue;
212                 }
213             } else if existing_name.len < count {
214                 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
215                     continue;
216                 }
217             } else {
218                 let mut interned_chars = interned_name.chars();
219                 let mut existing_chars = existing_name.interned.chars();
220                 let first_i = interned_chars.next().expect("we know we have at least one char");
221                 let first_e = existing_chars.next().expect("we know we have at least one char");
222                 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
223
224                 if eq_or_numeric((first_i, first_e)) {
225                     let last_i = interned_chars.next_back().expect("we know we have at least two chars");
226                     let last_e = existing_chars.next_back().expect("we know we have at least two chars");
227                     if eq_or_numeric((last_i, last_e)) {
228                         if interned_chars
229                             .zip(existing_chars)
230                             .filter(|&ie| !eq_or_numeric(ie))
231                             .count()
232                             != 1
233                         {
234                             continue;
235                         }
236                     } else {
237                         let second_last_i = interned_chars
238                             .next_back()
239                             .expect("we know we have at least three chars");
240                         let second_last_e = existing_chars
241                             .next_back()
242                             .expect("we know we have at least three chars");
243                         if !eq_or_numeric((second_last_i, second_last_e))
244                             || second_last_i == '_'
245                             || !interned_chars.zip(existing_chars).all(eq_or_numeric)
246                         {
247                             // allowed similarity foo_x, foo_y
248                             // or too many chars differ (foo_x, boo_y) or (foox, booy)
249                             continue;
250                         }
251                         split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
252                     }
253                 } else {
254                     let second_i = interned_chars.next().expect("we know we have at least two chars");
255                     let second_e = existing_chars.next().expect("we know we have at least two chars");
256                     if !eq_or_numeric((second_i, second_e))
257                         || second_i == '_'
258                         || !interned_chars.zip(existing_chars).all(eq_or_numeric)
259                     {
260                         // allowed similarity x_foo, y_foo
261                         // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
262                         continue;
263                     }
264                     split_at = interned_name.chars().next().map(char::len_utf8);
265                 }
266             }
267             span_lint_and_then(
268                 self.0.cx,
269                 SIMILAR_NAMES,
270                 ident.span,
271                 "binding's name is too similar to existing binding",
272                 |diag| {
273                     diag.span_note(existing_name.span, "existing binding defined here");
274                     if let Some(split) = split_at {
275                         diag.span_help(
276                             ident.span,
277                             &format!(
278                                 "separate the discriminating character by an \
279                                  underscore like: `{}_{}`",
280                                 &interned_name[..split],
281                                 &interned_name[split..]
282                             ),
283                         );
284                     }
285                 },
286             );
287             return;
288         }
289         self.0.names.push(ExistingName {
290             whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
291             interned: interned_name,
292             span: ident.span,
293             len: count,
294         });
295     }
296 }
297
298 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
299     /// ensure scoping rules work
300     fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
301         let n = self.names.len();
302         let single_char_count = self.single_char_names.len();
303         f(self);
304         self.names.truncate(n);
305         self.single_char_names.truncate(single_char_count);
306     }
307 }
308
309 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
310     fn visit_local(&mut self, local: &'tcx Local) {
311         if let Some(ref init) = local.init {
312             self.apply(|this| walk_expr(this, &**init));
313         }
314         // add the pattern after the expression because the bindings aren't available
315         // yet in the init
316         // expression
317         SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
318     }
319     fn visit_block(&mut self, blk: &'tcx Block) {
320         self.single_char_names.push(vec![]);
321
322         self.apply(|this| walk_block(this, blk));
323
324         self.check_single_char_names();
325         self.single_char_names.pop();
326     }
327     fn visit_arm(&mut self, arm: &'tcx Arm) {
328         self.single_char_names.push(vec![]);
329
330         self.apply(|this| {
331             SimilarNamesNameVisitor(this).visit_pat(&arm.pat);
332             this.apply(|this| walk_expr(this, &arm.body));
333         });
334
335         self.check_single_char_names();
336         self.single_char_names.pop();
337     }
338     fn visit_item(&mut self, _: &Item) {
339         // do not recurse into inner items
340     }
341     fn visit_mac(&mut self, _mac: &Mac) {
342         // do not check macs
343     }
344 }
345
346 impl EarlyLintPass for NonExpressiveNames {
347     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
348         if let ItemKind::Fn(ref decl, _, _, ref blk) = item.node {
349             do_check(self, cx, &item.attrs, decl, blk);
350         }
351     }
352
353     fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &ImplItem) {
354         if let ImplItemKind::Method(ref sig, ref blk) = item.node {
355             do_check(self, cx, &item.attrs, &sig.decl, blk);
356         }
357     }
358 }
359
360 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
361     if !attr::contains_name(attrs, sym!(test)) {
362         let mut visitor = SimilarNamesLocalVisitor {
363             names: Vec::new(),
364             cx,
365             lint,
366             single_char_names: vec![vec![]],
367         };
368
369         // initialize with function arguments
370         for arg in &decl.inputs {
371             SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
372         }
373         // walk all other bindings
374         walk_block(&mut visitor, blk);
375
376         visitor.check_single_char_names();
377     }
378 }
379
380 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
381 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
382     debug_assert!(a_name.chars().count() < b_name.chars().count());
383     let mut a_chars = a_name.chars();
384     let mut b_chars = b_name.chars();
385     while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
386         if a == b {
387             continue;
388         }
389         if let Some(b2) = b_chars.next() {
390             // check if there's just one character inserted
391             return a != b2 || a_chars.ne(b_chars);
392         } else {
393             // tuple
394             // ntuple
395             return true;
396         }
397     }
398     // for item in items
399     true
400 }