1 use crate::utils::{span_lint, span_lint_and_then};
3 Arm, AssocItem, AssocItemKind, Attribute, Block, FnDecl, 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_middle::lint::in_external_macro;
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::Span;
11 use rustc_span::symbol::{Ident, Symbol};
12 use std::cmp::Ordering;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for names that are very similar and thus confusing.
17 /// **Why is this bad?** It's hard to distinguish between names that differ only
18 /// by a single character.
20 /// **Known problems:** None?
24 /// let checked_exp = something;
25 /// let checked_expr = something_else;
29 "similarly named items and bindings"
32 declare_clippy_lint! {
33 /// **What it does:** Checks for too many variables whose name consists of a
36 /// **Why is this bad?** It's hard to memorize what a variable means without a
39 /// **Known problems:** None?
43 /// let (a, b, c, d, e, f, g) = (...);
45 pub MANY_SINGLE_CHAR_NAMES,
47 "too many single character bindings"
50 declare_clippy_lint! {
51 /// **What it does:** Checks if you have variables whose name consists of just
52 /// underscores and digits.
54 /// **Why is this bad?** It's hard to memorize what a variable means without a
57 /// **Known problems:** None?
65 pub JUST_UNDERSCORES_AND_DIGITS,
70 #[derive(Copy, Clone)]
71 pub struct NonExpressiveNames {
72 pub single_char_binding_names_threshold: u64,
75 impl_lint_pass!(NonExpressiveNames => [SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES, JUST_UNDERSCORES_AND_DIGITS]);
81 exemptions: &'static [&'static str],
84 struct SimilarNamesLocalVisitor<'a, 'tcx> {
85 names: Vec<ExistingName>,
86 cx: &'a EarlyContext<'tcx>,
87 lint: &'a NonExpressiveNames,
89 /// A stack of scopes containing the single-character bindings in each scope.
90 single_char_names: Vec<Vec<Ident>>,
93 impl<'a, 'tcx> SimilarNamesLocalVisitor<'a, 'tcx> {
94 fn check_single_char_names(&self) {
95 let num_single_char_names = self.single_char_names.iter().flatten().count();
96 let threshold = self.lint.single_char_binding_names_threshold;
97 if num_single_char_names as u64 > threshold {
102 .map(|ident| ident.span)
103 .collect::<Vec<_>>();
106 MANY_SINGLE_CHAR_NAMES,
109 "{} bindings with single-character names in scope",
110 num_single_char_names
117 // this list contains lists of names that are allowed to be similar
118 // the assumption is that no name is ever contained in multiple lists.
120 const ALLOWED_TO_BE_SIMILAR: &[&[&str]] = &[
121 &["parsed", "parser"],
130 struct SimilarNamesNameVisitor<'a, 'tcx, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
132 impl<'a, 'tcx, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
133 fn visit_pat(&mut self, pat: &'tcx Pat) {
135 PatKind::Ident(_, ident, _) => {
136 if !pat.span.from_expansion() {
137 self.check_ident(ident);
140 PatKind::Struct(_, ref fields, _) => {
141 for field in fields {
142 if !field.is_shorthand {
143 self.visit_pat(&field.pat);
147 // just go through the first pattern, as either all patterns
148 // bind the same bindings or rustc would have errored much earlier
149 PatKind::Or(ref pats) => self.visit_pat(&pats[0]),
150 _ => walk_pat(self, pat),
153 fn visit_mac(&mut self, _mac: &MacCall) {
159 fn get_exemptions(interned_name: &str) -> Option<&'static [&'static str]> {
160 for &list in ALLOWED_TO_BE_SIMILAR {
161 if allowed_to_be_similar(interned_name, list) {
169 fn allowed_to_be_similar(interned_name: &str, list: &[&str]) -> bool {
171 .any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
174 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
175 fn check_short_ident(&mut self, ident: Ident) {
182 .any(|id| id.name == ident.name)
187 if let Some(scope) = &mut self.0.single_char_names.last_mut() {
192 #[allow(clippy::too_many_lines)]
193 fn check_ident(&mut self, ident: Ident) {
194 let interned_name = ident.name.as_str();
195 if interned_name.chars().any(char::is_uppercase) {
198 if interned_name.chars().all(|c| c.is_digit(10) || c == '_') {
201 JUST_UNDERSCORES_AND_DIGITS,
203 "consider choosing a more descriptive name",
207 let count = interned_name.chars().count();
210 self.check_short_ident(ident);
214 for existing_name in &self.0.names {
215 if allowed_to_be_similar(&interned_name, existing_name.exemptions) {
218 let mut split_at = None;
219 match existing_name.len.cmp(&count) {
220 Ordering::Greater => {
221 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned.as_str()) {
226 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned.as_str(), &interned_name) {
231 let mut interned_chars = interned_name.chars();
232 let interned_str = existing_name.interned.as_str();
233 let mut existing_chars = interned_str.chars();
234 let first_i = interned_chars.next().expect("we know we have at least one char");
235 let first_e = existing_chars.next().expect("we know we have at least one char");
236 let eq_or_numeric = |(a, b): (char, char)| a == b || a.is_numeric() && b.is_numeric();
238 if eq_or_numeric((first_i, first_e)) {
239 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
240 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
241 if eq_or_numeric((last_i, last_e)) {
244 .filter(|&ie| !eq_or_numeric(ie))
251 let second_last_i = interned_chars
253 .expect("we know we have at least three chars");
254 let second_last_e = existing_chars
256 .expect("we know we have at least three chars");
257 if !eq_or_numeric((second_last_i, second_last_e))
258 || second_last_i == '_'
259 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
261 // allowed similarity foo_x, foo_y
262 // or too many chars differ (foo_x, boo_y) or (foox, booy)
265 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
268 let second_i = interned_chars.next().expect("we know we have at least two chars");
269 let second_e = existing_chars.next().expect("we know we have at least two chars");
270 if !eq_or_numeric((second_i, second_e))
272 || !interned_chars.zip(existing_chars).all(eq_or_numeric)
274 // allowed similarity x_foo, y_foo
275 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
278 split_at = interned_name.chars().next().map(char::len_utf8);
286 "binding's name is too similar to existing binding",
288 diag.span_note(existing_name.span, "existing binding defined here");
289 if let Some(split) = split_at {
293 "separate the discriminating character by an \
294 underscore like: `{}_{}`",
295 &interned_name[..split],
296 &interned_name[split..]
304 self.0.names.push(ExistingName {
305 exemptions: get_exemptions(&interned_name).unwrap_or(&[]),
306 interned: ident.name,
313 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
314 /// ensure scoping rules work
315 fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
316 let n = self.names.len();
317 let single_char_count = self.single_char_names.len();
319 self.names.truncate(n);
320 self.single_char_names.truncate(single_char_count);
324 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
325 fn visit_local(&mut self, local: &'tcx Local) {
326 if let Some(ref init) = local.init {
327 self.apply(|this| walk_expr(this, &**init));
329 // add the pattern after the expression because the bindings aren't available
332 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
334 fn visit_block(&mut self, blk: &'tcx Block) {
335 self.single_char_names.push(vec![]);
337 self.apply(|this| walk_block(this, blk));
339 self.check_single_char_names();
340 self.single_char_names.pop();
342 fn visit_arm(&mut self, arm: &'tcx Arm) {
343 self.single_char_names.push(vec![]);
346 SimilarNamesNameVisitor(this).visit_pat(&arm.pat);
347 this.apply(|this| walk_expr(this, &arm.body));
350 self.check_single_char_names();
351 self.single_char_names.pop();
353 fn visit_item(&mut self, _: &Item) {
354 // do not recurse into inner items
356 fn visit_mac(&mut self, _mac: &MacCall) {
361 impl EarlyLintPass for NonExpressiveNames {
362 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
363 if in_external_macro(cx.sess, item.span) {
367 if let ItemKind::Fn(_, ref sig, _, Some(ref blk)) = item.kind {
368 do_check(self, cx, &item.attrs, &sig.decl, blk);
372 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, item: &AssocItem) {
373 if in_external_macro(cx.sess, item.span) {
377 if let AssocItemKind::Fn(_, ref sig, _, Some(ref blk)) = item.kind {
378 do_check(self, cx, &item.attrs, &sig.decl, blk);
383 fn do_check(lint: &mut NonExpressiveNames, cx: &EarlyContext<'_>, attrs: &[Attribute], decl: &FnDecl, blk: &Block) {
384 if !attr::contains_name(attrs, sym!(test)) {
385 let mut visitor = SimilarNamesLocalVisitor {
389 single_char_names: vec![vec![]],
392 // initialize with function arguments
393 for arg in &decl.inputs {
394 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
396 // walk all other bindings
397 walk_block(&mut visitor, blk);
399 visitor.check_single_char_names();
403 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
405 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
406 debug_assert!(a_name.chars().count() < b_name.chars().count());
407 let mut a_chars = a_name.chars();
408 let mut b_chars = b_name.chars();
409 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
413 if let Some(b2) = b_chars.next() {
414 // check if there's just one character inserted
415 return a != b2 || a_chars.ne(b_chars);