1 use crate::utils::{span_lint, span_lint_and_then};
3 Arm, AssocItem, AssocItemKind, Attribute, Block, FnDecl, Ident, Item, ItemKind, Local, MacCall, Pat, PatKind,
6 use rustc_ast::visit::{walk_block, walk_expr, walk_pat, Visitor};
7 use rustc_lint::{EarlyContext, EarlyLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::Span;
10 use rustc_span::symbol::SymbolStr;
11 use std::cmp::Ordering;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for names that are very similar and thus confusing.
16 /// **Why is this bad?** It's hard to distinguish between names that differ only
17 /// by a single character.
19 /// **Known problems:** None?
23 /// let checked_exp = something;
24 /// let checked_expr = something_else;
28 "similarly named items and bindings"
31 declare_clippy_lint! {
32 /// **What it does:** Checks for too many variables whose name consists of a
35 /// **Why is this bad?** It's hard to memorize what a variable means without a
38 /// **Known problems:** None?
42 /// let (a, b, c, d, e, f, g) = (...);
44 pub MANY_SINGLE_CHAR_NAMES,
46 "too many single character bindings"
49 declare_clippy_lint! {
50 /// **What it does:** Checks if you have variables whose name consists of just
51 /// underscores and digits.
53 /// **Why is this bad?** It's hard to memorize what a variable means without a
56 /// **Known problems:** None?
64 pub JUST_UNDERSCORES_AND_DIGITS,
69 #[derive(Copy, Clone)]
70 pub struct NonExpressiveNames {
71 pub single_char_binding_names_threshold: u64,
74 impl_lint_pass!(NonExpressiveNames => [SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS]);
80 whitelist: &'static [&'static str],
83 struct SimilarNamesLocalVisitor<'a, 'tcx> {
84 names: Vec<ExistingName>,
85 cx: &'a EarlyContext<'tcx>,
86 lint: &'a NonExpressiveNames,
88 /// A stack of scopes containing the single-character bindings in each scope.
89 single_char_names: Vec<Vec<Ident>>,
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 {
101 .map(|ident| ident.span)
102 .collect::<Vec<_>>();
105 MANY_SINGLE_CHAR_NAMES,
108 "{} bindings with single-character names in scope",
109 num_single_char_names
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.
119 const WHITELIST: &[&[&str]] = &[
120 &["parsed", "parser"],
129 struct SimilarNamesNameVisitor<'a, 'tcx, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
131 impl<'a, 'tcx, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
132 fn visit_pat(&mut self, pat: &'tcx Pat) {
134 PatKind::Ident(_, ident, _) => self.check_ident(ident),
135 PatKind::Struct(_, ref fields, _) => {
136 for field in fields {
137 if !field.is_shorthand {
138 self.visit_pat(&field.pat);
142 // just go through the first pattern, as either all patterns
143 // bind the same bindings or rustc would have errored much earlier
144 PatKind::Or(ref pats) => self.visit_pat(&pats[0]),
145 _ => walk_pat(self, pat),
148 fn visit_mac(&mut self, _mac: &MacCall) {
154 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
155 for &allow in WHITELIST {
156 if whitelisted(interned_name, allow) {
164 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
166 .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
169 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
170 fn check_short_ident(&mut self, ident: Ident) {
177 .any(|id| id.name == ident.name)
182 if let Some(scope) = &mut self.0.single_char_names.last_mut() {
187 #[allow(clippy::too_many_lines)]
188 fn check_ident(&mut self, ident: Ident) {
189 let interned_name = ident.name.as_str();
190 if interned_name.chars().any(char::is_uppercase) {
193 if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
196 JUST_UNDERSCORES_AND_DIGITS,
198 "consider choosing a more descriptive name",
202 let count = interned_name.chars().count();
205 self.check_short_ident(ident);
209 for existing_name in &self.0.names {
210 if whitelisted(&interned_name, existing_name.whitelist) {
213 let mut split_at = None;
214 match existing_name.len.cmp(&count) {
215 Ordering::Greater => {
216 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
221 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
226 let mut interned_chars = interned_name.chars();
227 let mut existing_chars = existing_name.interned.chars();
228 let first_i = interned_chars.next().expect("we know we have at least one char");
229 let first_e = existing_chars.next().expect("we know we have at least one char");
230 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
232 if eq_or_numeric((first_i, first_e)) {
233 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
234 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
235 if eq_or_numeric((last_i, last_e)) {
238 .filter(|&ie| !eq_or_numeric(ie))
245 let second_last_i = interned_chars
247 .expect("we know we have at least three chars");
248 let second_last_e = existing_chars
250 .expect("we know we have at least three chars");
251 if !eq_or_numeric((second_last_i, second_last_e))
252 || second_last_i == '_'
253 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
255 // allowed similarity foo_x, foo_y
256 // or too many chars differ (foo_x, boo_y) or (foox, booy)
259 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
262 let second_i = interned_chars.next().expect("we know we have at least two chars");
263 let second_e = existing_chars.next().expect("we know we have at least two chars");
264 if !eq_or_numeric((second_i, second_e))
266 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
268 // allowed similarity x_foo, y_foo
269 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
272 split_at = interned_name.chars().next().map(char::len_utf8);
280 "binding's name is too similar to existing binding",
282 diag.span_note(existing_name.span, "existing binding defined here");
283 if let Some(split) = split_at {
287 "separate the discriminating character by an \
288 underscore like: `{}_{}`",
289 &interned_name[..split],
290 &interned_name[split..]
298 self.0.names.push(ExistingName {
299 whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
300 interned: interned_name,
307 impl<'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();
313 self.names.truncate(n);
314 self.single_char_names.truncate(single_char_count);
318 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
319 fn visit_local(&mut self, local: &'tcx Local) {
320 if let Some(ref init) = local.init {
321 self.apply(|this| walk_expr(this, &**init));
323 // add the pattern after the expression because the bindings aren't available
326 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
328 fn visit_block(&mut self, blk: &'tcx Block) {
329 self.single_char_names.push(vec![]);
331 self.apply(|this| walk_block(this, blk));
333 self.check_single_char_names();
334 self.single_char_names.pop();
336 fn visit_arm(&mut self, arm: &'tcx Arm) {
337 self.single_char_names.push(vec![]);
340 SimilarNamesNameVisitor(this).visit_pat(&arm.pat);
341 this.apply(|this| walk_expr(this, &arm.body));
344 self.check_single_char_names();
345 self.single_char_names.pop();
347 fn visit_item(&mut self, _: &Item) {
348 // do not recurse into inner items
350 fn visit_mac(&mut self, _mac: &MacCall) {
355 impl EarlyLintPass for NonExpressiveNames {
356 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
357 if let ItemKind::Fn(_, ref sig, _, Some(ref blk)) = item.kind {
358 do_check(self, cx, &item.attrs, &sig.decl, blk);
362 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &AssocItem) {
363 if let AssocItemKind::Fn(_, ref sig, _, Some(ref blk)) = item.kind {
364 do_check(self, cx, &item.attrs, &sig.decl, blk);
369 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
370 if !attr::contains_name(attrs, sym!(test)) {
371 let mut visitor = SimilarNamesLocalVisitor {
375 single_char_names: vec![vec![]],
378 // initialize with function arguments
379 for arg in &decl.inputs {
380 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
382 // walk all other bindings
383 walk_block(&mut visitor, blk);
385 visitor.check_single_char_names();
389 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
391 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
392 debug_assert!(a_name.chars().count() < b_name.chars().count());
393 let mut a_chars = a_name.chars();
394 let mut b_chars = b_name.chars();
395 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
399 if let Some(b2) = b_chars.next() {
400 // check if there's just one character inserted
401 return a != b2 || a_chars.ne(b_chars);