1 use crate::utils::{span_lint, span_lint_and_then};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, impl_lint_pass};
6 use syntax::source_map::Span;
7 use syntax::symbol::LocalInternedString;
8 use syntax::visit::{walk_block, walk_expr, walk_pat, Visitor};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for names that are very similar and thus confusing.
13 /// **Why is this bad?** It's hard to distinguish between names that differ only
14 /// by a single character.
16 /// **Known problems:** None?
20 /// let checked_exp = something;
21 /// let checked_expr = something_else;
25 "similarly named items and bindings"
28 declare_clippy_lint! {
29 /// **What it does:** Checks for too many variables whose name consists of a
32 /// **Why is this bad?** It's hard to memorize what a variable means without a
35 /// **Known problems:** None?
39 /// let (a, b, c, d, e, f, g) = (...);
41 pub MANY_SINGLE_CHAR_NAMES,
43 "too many single character bindings"
46 declare_clippy_lint! {
47 /// **What it does:** Checks if you have variables whose name consists of just
48 /// underscores and digits.
50 /// **Why is this bad?** It's hard to memorize what a variable means without a
53 /// **Known problems:** None?
61 pub JUST_UNDERSCORES_AND_DIGITS,
66 #[derive(Copy, Clone)]
67 pub struct NonExpressiveNames {
68 pub single_char_binding_names_threshold: u64,
71 impl_lint_pass!(NonExpressiveNames => [SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS]);
74 interned: LocalInternedString,
77 whitelist: &'static [&'static str],
80 struct SimilarNamesLocalVisitor<'a, 'tcx> {
81 names: Vec<ExistingName>,
82 cx: &'a EarlyContext<'tcx>,
83 lint: &'a NonExpressiveNames,
85 /// A stack of scopes containing the single-character bindings in each scope.
86 single_char_names: Vec<Vec<Ident>>,
89 impl<'a, 'tcx> SimilarNamesLocalVisitor<'a, 'tcx> {
90 fn check_single_char_names(&self) {
91 let num_single_char_names = self.single_char_names.iter().flatten().count();
92 let threshold = self.lint.single_char_binding_names_threshold;
93 if num_single_char_names as u64 >= threshold {
98 .map(|ident| ident.span)
102 MANY_SINGLE_CHAR_NAMES,
105 "{} bindings with single-character names in scope",
106 num_single_char_names
113 // this list contains lists of names that are allowed to be similar
114 // the assumption is that no name is ever contained in multiple lists.
116 const WHITELIST: &[&[&str]] = &[
117 &["parsed", "parser"],
126 struct SimilarNamesNameVisitor<'a, 'tcx, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
128 impl<'a, 'tcx, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
129 fn visit_pat(&mut self, pat: &'tcx Pat) {
131 PatKind::Ident(_, ident, _) => self.check_ident(ident),
132 PatKind::Struct(_, ref fields, _) => {
133 for field in fields {
134 if !field.node.is_shorthand {
135 self.visit_pat(&field.node.pat);
139 _ => walk_pat(self, pat),
142 fn visit_mac(&mut self, _mac: &Mac) {
147 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
148 for &allow in WHITELIST {
149 if whitelisted(interned_name, allow) {
156 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
158 .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
161 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
162 fn check_short_ident(&mut self, ident: Ident) {
169 .any(|id| id.name == ident.name)
174 if let Some(scope) = &mut self.0.single_char_names.last_mut() {
179 #[allow(clippy::too_many_lines)]
180 fn check_ident(&mut self, ident: Ident) {
181 let interned_name = ident.name.as_str();
182 if interned_name.chars().any(char::is_uppercase) {
185 if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
188 JUST_UNDERSCORES_AND_DIGITS,
190 "consider choosing a more descriptive name",
194 let count = interned_name.chars().count();
197 self.check_short_ident(ident);
201 for existing_name in &self.0.names {
202 if whitelisted(&interned_name, existing_name.whitelist) {
205 let mut split_at = None;
206 if existing_name.len > count {
207 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
210 } else if existing_name.len < count {
211 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
215 let mut interned_chars = interned_name.chars();
216 let mut existing_chars = existing_name.interned.chars();
217 let first_i = interned_chars.next().expect("we know we have at least one char");
218 let first_e = existing_chars.next().expect("we know we have at least one char");
219 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
221 if eq_or_numeric((first_i, first_e)) {
222 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
223 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
224 if eq_or_numeric((last_i, last_e)) {
227 .filter(|&ie| !eq_or_numeric(ie))
234 let second_last_i = interned_chars
236 .expect("we know we have at least three chars");
237 let second_last_e = existing_chars
239 .expect("we know we have at least three chars");
240 if !eq_or_numeric((second_last_i, second_last_e))
241 || second_last_i == '_'
242 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
244 // allowed similarity foo_x, foo_y
245 // or too many chars differ (foo_x, boo_y) or (foox, booy)
248 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
251 let second_i = interned_chars.next().expect("we know we have at least two chars");
252 let second_e = existing_chars.next().expect("we know we have at least two chars");
253 if !eq_or_numeric((second_i, second_e))
255 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
257 // allowed similarity x_foo, y_foo
258 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
261 split_at = interned_name.chars().next().map(char::len_utf8);
268 "binding's name is too similar to existing binding",
270 diag.span_note(existing_name.span, "existing binding defined here");
271 if let Some(split) = split_at {
275 "separate the discriminating character by an \
276 underscore like: `{}_{}`",
277 &interned_name[..split],
278 &interned_name[split..]
286 self.0.names.push(ExistingName {
287 whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
288 interned: interned_name,
295 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
296 /// ensure scoping rules work
297 fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
298 let n = self.names.len();
299 let single_char_count = self.single_char_names.len();
301 self.names.truncate(n);
302 self.single_char_names.truncate(single_char_count);
306 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
307 fn visit_local(&mut self, local: &'tcx Local) {
308 if let Some(ref init) = local.init {
309 self.apply(|this| walk_expr(this, &**init));
311 // add the pattern after the expression because the bindings aren't available
314 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
316 fn visit_block(&mut self, blk: &'tcx Block) {
317 self.single_char_names.push(vec![]);
319 self.apply(|this| walk_block(this, blk));
321 self.check_single_char_names();
322 self.single_char_names.pop();
324 fn visit_arm(&mut self, arm: &'tcx Arm) {
325 self.single_char_names.push(vec![]);
328 // just go through the first pattern, as either all patterns
329 // bind the same bindings or rustc would have errored much earlier
330 SimilarNamesNameVisitor(this).visit_pat(&arm.pats[0]);
331 this.apply(|this| walk_expr(this, &arm.body));
334 self.check_single_char_names();
335 self.single_char_names.pop();
337 fn visit_item(&mut self, _: &Item) {
338 // do not recurse into inner items
340 fn visit_mac(&mut self, _mac: &Mac) {
345 impl EarlyLintPass for NonExpressiveNames {
346 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
347 if let ItemKind::Fn(ref decl, _, _, ref blk) = item.node {
348 do_check(self, cx, &item.attrs, decl, blk);
352 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &ImplItem) {
353 if let ImplItemKind::Method(ref sig, ref blk) = item.node {
354 do_check(self, cx, &item.attrs, &sig.decl, blk);
359 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
360 if !attr::contains_name(attrs, sym!(test)) {
361 let mut visitor = SimilarNamesLocalVisitor {
365 single_char_names: vec![vec![]],
368 // initialize with function arguments
369 for arg in &decl.inputs {
370 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
372 // walk all other bindings
373 walk_block(&mut visitor, blk);
375 visitor.check_single_char_names();
379 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
380 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
381 debug_assert!(a_name.chars().count() < b_name.chars().count());
382 let mut a_chars = a_name.chars();
383 let mut b_chars = b_name.chars();
384 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
388 if let Some(b2) = b_chars.next() {
389 // check if there's just one character inserted
390 return a != b2 || a_chars.ne(b_chars);