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