1 use crate::utils::{span_lint, span_lint_and_then};
2 use rustc_lint::{EarlyContext, EarlyLintPass};
3 use rustc_session::{declare_tool_lint, impl_lint_pass};
4 use rustc_span::source_map::Span;
5 use rustc_span::symbol::SymbolStr;
6 use std::cmp::Ordering;
9 use syntax::visit::{walk_block, walk_expr, walk_pat, Visitor};
11 declare_clippy_lint! {
12 /// **What it does:** Checks for names that are very similar and thus confusing.
14 /// **Why is this bad?** It's hard to distinguish between names that differ only
15 /// by a single character.
17 /// **Known problems:** None?
21 /// let checked_exp = something;
22 /// let checked_expr = something_else;
26 "similarly named items and bindings"
29 declare_clippy_lint! {
30 /// **What it does:** Checks for too many variables whose name consists of a
33 /// **Why is this bad?** It's hard to memorize what a variable means without a
36 /// **Known problems:** None?
40 /// let (a, b, c, d, e, f, g) = (...);
42 pub MANY_SINGLE_CHAR_NAMES,
44 "too many single character bindings"
47 declare_clippy_lint! {
48 /// **What it does:** Checks if you have variables whose name consists of just
49 /// underscores and digits.
51 /// **Why is this bad?** It's hard to memorize what a variable means without a
54 /// **Known problems:** None?
62 pub JUST_UNDERSCORES_AND_DIGITS,
67 #[derive(Copy, Clone)]
68 pub struct NonExpressiveNames {
69 pub single_char_binding_names_threshold: u64,
72 impl_lint_pass!(NonExpressiveNames => [SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS]);
78 whitelist: &'static [&'static str],
81 struct SimilarNamesLocalVisitor<'a, 'tcx> {
82 names: Vec<ExistingName>,
83 cx: &'a EarlyContext<'tcx>,
84 lint: &'a NonExpressiveNames,
86 /// A stack of scopes containing the single-character bindings in each scope.
87 single_char_names: Vec<Vec<Ident>>,
90 impl<'a, 'tcx> SimilarNamesLocalVisitor<'a, 'tcx> {
91 fn check_single_char_names(&self) {
92 let num_single_char_names = self.single_char_names.iter().flatten().count();
93 let threshold = self.lint.single_char_binding_names_threshold;
94 if num_single_char_names as u64 >= threshold {
99 .map(|ident| ident.span)
100 .collect::<Vec<_>>();
103 MANY_SINGLE_CHAR_NAMES,
106 "{} bindings with single-character names in scope",
107 num_single_char_names
114 // this list contains lists of names that are allowed to be similar
115 // the assumption is that no name is ever contained in multiple lists.
117 const WHITELIST: &[&[&str]] = &[
118 &["parsed", "parser"],
127 struct SimilarNamesNameVisitor<'a, 'tcx, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
129 impl<'a, 'tcx, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
130 fn visit_pat(&mut self, pat: &'tcx Pat) {
132 PatKind::Ident(_, ident, _) => self.check_ident(ident),
133 PatKind::Struct(_, ref fields, _) => {
134 for field in fields {
135 if !field.is_shorthand {
136 self.visit_pat(&field.pat);
140 // just go through the first pattern, as either all patterns
141 // bind the same bindings or rustc would have errored much earlier
142 PatKind::Or(ref pats) => self.visit_pat(&pats[0]),
143 _ => walk_pat(self, pat),
146 fn visit_mac(&mut self, _mac: &Mac) {
152 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
153 for &allow in WHITELIST {
154 if whitelisted(interned_name, allow) {
162 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
164 .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
167 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
168 fn check_short_ident(&mut self, ident: Ident) {
175 .any(|id| id.name == ident.name)
180 if let Some(scope) = &mut self.0.single_char_names.last_mut() {
185 #[allow(clippy::too_many_lines)]
186 fn check_ident(&mut self, ident: Ident) {
187 let interned_name = ident.name.as_str();
188 if interned_name.chars().any(char::is_uppercase) {
191 if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
194 JUST_UNDERSCORES_AND_DIGITS,
196 "consider choosing a more descriptive name",
200 let count = interned_name.chars().count();
203 self.check_short_ident(ident);
207 for existing_name in &self.0.names {
208 if whitelisted(&interned_name, existing_name.whitelist) {
211 let mut split_at = None;
212 match existing_name.len.cmp(&count) {
213 Ordering::Greater => {
214 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
219 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
224 let mut interned_chars = interned_name.chars();
225 let mut existing_chars = existing_name.interned.chars();
226 let first_i = interned_chars.next().expect("we know we have at least one char");
227 let first_e = existing_chars.next().expect("we know we have at least one char");
228 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
230 if eq_or_numeric((first_i, first_e)) {
231 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
232 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
233 if eq_or_numeric((last_i, last_e)) {
236 .filter(|&ie| !eq_or_numeric(ie))
243 let second_last_i = interned_chars
245 .expect("we know we have at least three chars");
246 let second_last_e = existing_chars
248 .expect("we know we have at least three chars");
249 if !eq_or_numeric((second_last_i, second_last_e))
250 || second_last_i == '_'
251 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
253 // allowed similarity foo_x, foo_y
254 // or too many chars differ (foo_x, boo_y) or (foox, booy)
257 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
260 let second_i = interned_chars.next().expect("we know we have at least two chars");
261 let second_e = existing_chars.next().expect("we know we have at least two chars");
262 if !eq_or_numeric((second_i, second_e))
264 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
266 // allowed similarity x_foo, y_foo
267 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
270 split_at = interned_name.chars().next().map(char::len_utf8);
278 "binding's name is too similar to existing binding",
280 diag.span_note(existing_name.span, "existing binding defined here");
281 if let Some(split) = split_at {
285 "separate the discriminating character by an \
286 underscore like: `{}_{}`",
287 &interned_name[..split],
288 &interned_name[split..]
296 self.0.names.push(ExistingName {
297 whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
298 interned: interned_name,
305 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
306 /// ensure scoping rules work
307 fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
308 let n = self.names.len();
309 let single_char_count = self.single_char_names.len();
311 self.names.truncate(n);
312 self.single_char_names.truncate(single_char_count);
316 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
317 fn visit_local(&mut self, local: &'tcx Local) {
318 if let Some(ref init) = local.init {
319 self.apply(|this| walk_expr(this, &**init));
321 // add the pattern after the expression because the bindings aren't available
324 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
326 fn visit_block(&mut self, blk: &'tcx Block) {
327 self.single_char_names.push(vec![]);
329 self.apply(|this| walk_block(this, blk));
331 self.check_single_char_names();
332 self.single_char_names.pop();
334 fn visit_arm(&mut self, arm: &'tcx Arm) {
335 self.single_char_names.push(vec![]);
338 SimilarNamesNameVisitor(this).visit_pat(&arm.pat);
339 this.apply(|this| walk_expr(this, &arm.body));
342 self.check_single_char_names();
343 self.single_char_names.pop();
345 fn visit_item(&mut self, _: &Item) {
346 // do not recurse into inner items
348 fn visit_mac(&mut self, _mac: &Mac) {
353 impl EarlyLintPass for NonExpressiveNames {
354 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
355 if let ItemKind::Fn(ref sig, _, Some(ref blk)) = item.kind {
356 do_check(self, cx, &item.attrs, &sig.decl, blk);
360 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &AssocItem) {
361 if let AssocItemKind::Fn(ref sig, Some(ref blk)) = item.kind {
362 do_check(self, cx, &item.attrs, &sig.decl, blk);
367 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
368 if !attr::contains_name(attrs, sym!(test)) {
369 let mut visitor = SimilarNamesLocalVisitor {
373 single_char_names: vec![vec![]],
376 // initialize with function arguments
377 for arg in &decl.inputs {
378 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
380 // walk all other bindings
381 walk_block(&mut visitor, blk);
383 visitor.check_single_char_names();
387 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
389 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
390 debug_assert!(a_name.chars().count() < b_name.chars().count());
391 let mut a_chars = a_name.chars();
392 let mut b_chars = b_name.chars();
393 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
397 if let Some(b2) = b_chars.next() {
398 // check if there's just one character inserted
399 return a != b2 || a_chars.ne(b_chars);