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