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