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