1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::syntax::ast::*;
13 use crate::syntax::attr;
14 use crate::syntax::source_map::Span;
15 use crate::syntax::symbol::LocalInternedString;
16 use crate::syntax::visit::{walk_block, walk_expr, walk_pat, Visitor};
17 use crate::utils::{span_lint, span_lint_and_then};
19 /// **What it does:** Checks for names that are very similar and thus confusing.
21 /// **Why is this bad?** It's hard to distinguish between names that differ only
22 /// by a single character.
24 /// **Known problems:** None?
28 /// let checked_exp = something;
29 /// let checked_expr = something_else;
31 declare_clippy_lint! {
34 "similarly named items and bindings"
37 /// **What it does:** Checks for too many variables whose name consists of a
40 /// **Why is this bad?** It's hard to memorize what a variable means without a
43 /// **Known problems:** None?
47 /// let (a, b, c, d, e, f, g) = (...);
49 declare_clippy_lint! {
50 pub MANY_SINGLE_CHAR_NAMES,
52 "too many single character bindings"
55 /// **What it does:** Checks if you have variables whose name consists of just
56 /// underscores and digits.
58 /// **Why is this bad?** It's hard to memorize what a variable means without a
61 /// **Known problems:** None?
69 declare_clippy_lint! {
70 pub JUST_UNDERSCORES_AND_DIGITS,
75 pub struct NonExpressiveNames {
76 pub single_char_binding_names_threshold: u64,
79 impl LintPass for NonExpressiveNames {
80 fn get_lints(&self) -> LintArray {
81 lint_array!(SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS)
86 interned: LocalInternedString,
89 whitelist: &'static [&'static str],
92 struct SimilarNamesLocalVisitor<'a, 'tcx: 'a> {
93 names: Vec<ExistingName>,
94 cx: &'a EarlyContext<'tcx>,
95 lint: &'a NonExpressiveNames,
96 single_char_names: Vec<char>,
99 // this list contains lists of names that are allowed to be similar
100 // the assumption is that no name is ever contained in multiple lists.
102 const WHITELIST: &[&[&str]] = &[
103 &["parsed", "parser"],
112 struct SimilarNamesNameVisitor<'a: 'b, 'tcx: 'a, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
114 impl<'a, 'tcx: 'a, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
115 fn visit_pat(&mut self, pat: &'tcx Pat) {
117 PatKind::Ident(_, ident, _) => self.check_name(ident.span, ident.name),
118 PatKind::Struct(_, ref fields, _) => {
119 for field in fields {
120 if !field.node.is_shorthand {
121 self.visit_pat(&field.node.pat);
125 _ => walk_pat(self, pat),
128 fn visit_mac(&mut self, _mac: &Mac) {
133 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
134 for &allow in WHITELIST {
135 if whitelisted(interned_name, allow) {
142 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
144 .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
147 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
148 fn check_short_name(&mut self, c: char, span: Span) {
149 // make sure we ignore shadowing
150 if self.0.single_char_names.contains(&c) {
153 self.0.single_char_names.push(c);
154 if self.0.single_char_names.len() as u64 >= self.0.lint.single_char_binding_names_threshold {
157 MANY_SINGLE_CHAR_NAMES,
160 "{}th binding whose name is just one char",
161 self.0.single_char_names.len()
166 fn check_name(&mut self, span: Span, name: Name) {
167 let interned_name = name.as_str();
168 if interned_name.chars().any(char::is_uppercase) {
171 if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
174 JUST_UNDERSCORES_AND_DIGITS,
176 "consider choosing a more descriptive name",
180 let count = interned_name.chars().count();
183 let c = interned_name.chars().next().expect("already checked");
184 self.check_short_name(c, span);
188 for existing_name in &self.0.names {
189 if whitelisted(&interned_name, existing_name.whitelist) {
192 let mut split_at = None;
193 if existing_name.len > count {
194 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
197 } else if existing_name.len < count {
198 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
202 let mut interned_chars = interned_name.chars();
203 let mut existing_chars = existing_name.interned.chars();
204 let first_i = interned_chars.next().expect("we know we have at least one char");
205 let first_e = existing_chars.next().expect("we know we have at least one char");
206 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
208 if eq_or_numeric((first_i, first_e)) {
209 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
210 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
211 if eq_or_numeric((last_i, last_e)) {
214 .filter(|&ie| !eq_or_numeric(ie))
221 let second_last_i = interned_chars
223 .expect("we know we have at least three chars");
224 let second_last_e = existing_chars
226 .expect("we know we have at least three chars");
227 if !eq_or_numeric((second_last_i, second_last_e))
228 || second_last_i == '_'
229 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
231 // allowed similarity foo_x, foo_y
232 // or too many chars differ (foo_x, boo_y) or (foox, booy)
235 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
238 let second_i = interned_chars.next().expect("we know we have at least two chars");
239 let second_e = existing_chars.next().expect("we know we have at least two chars");
240 if !eq_or_numeric((second_i, second_e))
242 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
244 // allowed similarity x_foo, y_foo
245 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
248 split_at = interned_name.chars().next().map(|c| c.len_utf8());
255 "binding's name is too similar to existing binding",
257 diag.span_note(existing_name.span, "existing binding defined here");
258 if let Some(split) = split_at {
262 "separate the discriminating character by an \
263 underscore like: `{}_{}`",
264 &interned_name[..split],
265 &interned_name[split..]
273 self.0.names.push(ExistingName {
274 whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
275 interned: interned_name,
282 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
283 /// ensure scoping rules work
284 fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
285 let n = self.names.len();
286 let single_char_count = self.single_char_names.len();
288 self.names.truncate(n);
289 self.single_char_names.truncate(single_char_count);
293 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
294 fn visit_local(&mut self, local: &'tcx Local) {
295 if let Some(ref init) = local.init {
296 self.apply(|this| walk_expr(this, &**init));
298 // add the pattern after the expression because the bindings aren't available
301 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
303 fn visit_block(&mut self, blk: &'tcx Block) {
304 self.apply(|this| walk_block(this, blk));
306 fn visit_arm(&mut self, arm: &'tcx Arm) {
308 // just go through the first pattern, as either all patterns
309 // bind the same bindings or rustc would have errored much earlier
310 SimilarNamesNameVisitor(this).visit_pat(&arm.pats[0]);
311 this.apply(|this| walk_expr(this, &arm.body));
314 fn visit_item(&mut self, _: &Item) {
315 // do not recurse into inner items
317 fn visit_mac(&mut self, _mac: &Mac) {
322 impl EarlyLintPass for NonExpressiveNames {
323 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
324 if let ItemKind::Fn(ref decl, _, _, ref blk) = item.node {
325 do_check(self, cx, &item.attrs, decl, blk);
329 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &ImplItem) {
330 if let ImplItemKind::Method(ref sig, ref blk) = item.node {
331 do_check(self, cx, &item.attrs, &sig.decl, blk);
336 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
337 if !attr::contains_name(attrs, "test") {
338 let mut visitor = SimilarNamesLocalVisitor {
342 single_char_names: Vec::new(),
344 // initialize with function arguments
345 for arg in &decl.inputs {
346 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
348 // walk all other bindings
349 walk_block(&mut visitor, blk);
353 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
354 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
355 debug_assert!(a_name.chars().count() < b_name.chars().count());
356 let mut a_chars = a_name.chars();
357 let mut b_chars = b_name.chars();
358 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
362 if let Some(b2) = b_chars.next() {
363 // check if there's just one character inserted
364 return a != b2 || a_chars.ne(b_chars);