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