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: 'a> {
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: 'a> 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: 'b, 'tcx: 'a, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
128 impl<'a, 'tcx: 'a, '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)
172 } else if let Some(scope) = &mut self.0.single_char_names.last_mut() {
177 #[allow(clippy::too_many_lines)]
178 fn check_ident(&mut self, ident: Ident) {
179 let interned_name = ident.name.as_str();
180 if interned_name.chars().any(char::is_uppercase) {
183 if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
186 JUST_UNDERSCORES_AND_DIGITS,
188 "consider choosing a more descriptive name",
192 let count = interned_name.chars().count();
195 self.check_short_ident(ident);
199 for existing_name in &self.0.names {
200 if whitelisted(&interned_name, existing_name.whitelist) {
203 let mut split_at = None;
204 if existing_name.len > count {
205 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
208 } else if existing_name.len < count {
209 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
213 let mut interned_chars = interned_name.chars();
214 let mut existing_chars = existing_name.interned.chars();
215 let first_i = interned_chars.next().expect("we know we have at least one char");
216 let first_e = existing_chars.next().expect("we know we have at least one char");
217 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
219 if eq_or_numeric((first_i, first_e)) {
220 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
221 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
222 if eq_or_numeric((last_i, last_e)) {
225 .filter(|&ie| !eq_or_numeric(ie))
232 let second_last_i = interned_chars
234 .expect("we know we have at least three chars");
235 let second_last_e = existing_chars
237 .expect("we know we have at least three chars");
238 if !eq_or_numeric((second_last_i, second_last_e))
239 || second_last_i == '_'
240 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
242 // allowed similarity foo_x, foo_y
243 // or too many chars differ (foo_x, boo_y) or (foox, booy)
246 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
249 let second_i = interned_chars.next().expect("we know we have at least two chars");
250 let second_e = existing_chars.next().expect("we know we have at least two chars");
251 if !eq_or_numeric((second_i, second_e))
253 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
255 // allowed similarity x_foo, y_foo
256 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
259 split_at = interned_name.chars().next().map(char::len_utf8);
266 "binding's name is too similar to existing binding",
268 diag.span_note(existing_name.span, "existing binding defined here");
269 if let Some(split) = split_at {
273 "separate the discriminating character by an \
274 underscore like: `{}_{}`",
275 &interned_name[..split],
276 &interned_name[split..]
284 self.0.names.push(ExistingName {
285 whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
286 interned: interned_name,
293 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
294 /// ensure scoping rules work
295 fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
296 let n = self.names.len();
297 let single_char_count = self.single_char_names.len();
299 self.names.truncate(n);
300 self.single_char_names.truncate(single_char_count);
304 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
305 fn visit_local(&mut self, local: &'tcx Local) {
306 if let Some(ref init) = local.init {
307 self.apply(|this| walk_expr(this, &**init));
309 // add the pattern after the expression because the bindings aren't available
312 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
314 fn visit_block(&mut self, blk: &'tcx Block) {
315 self.single_char_names.push(vec![]);
317 self.apply(|this| walk_block(this, blk));
319 self.check_single_char_names();
320 self.single_char_names.pop();
322 fn visit_arm(&mut self, arm: &'tcx Arm) {
323 self.single_char_names.push(vec![]);
326 // just go through the first pattern, as either all patterns
327 // bind the same bindings or rustc would have errored much earlier
328 SimilarNamesNameVisitor(this).visit_pat(&arm.pats[0]);
329 this.apply(|this| walk_expr(this, &arm.body));
332 self.check_single_char_names();
333 self.single_char_names.pop();
335 fn visit_item(&mut self, _: &Item) {
336 // do not recurse into inner items
338 fn visit_mac(&mut self, _mac: &Mac) {
343 impl EarlyLintPass for NonExpressiveNames {
344 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
345 if let ItemKind::Fn(ref decl, _, _, ref blk) = item.node {
346 do_check(self, cx, &item.attrs, decl, blk);
350 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &ImplItem) {
351 if let ImplItemKind::Method(ref sig, ref blk) = item.node {
352 do_check(self, cx, &item.attrs, &sig.decl, blk);
357 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
358 if !attr::contains_name(attrs, "test") {
359 let mut visitor = SimilarNamesLocalVisitor {
363 single_char_names: vec![vec![]],
366 // initialize with function arguments
367 for arg in &decl.inputs {
368 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
370 // walk all other bindings
371 walk_block(&mut visitor, blk);
373 visitor.check_single_char_names();
377 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
378 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
379 debug_assert!(a_name.chars().count() < b_name.chars().count());
380 let mut a_chars = a_name.chars();
381 let mut b_chars = b_name.chars();
382 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
386 if let Some(b2) = b_chars.next() {
387 // check if there's just one character inserted
388 return a != b2 || a_chars.ne(b_chars);