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