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