]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/non_expressive_names.rs
Fix deploy.sh III
[rust.git] / clippy_lints / src / non_expressive_names.rs
1 use rustc::lint::*;
2 use syntax::codemap::Span;
3 use syntax::parse::token::InternedString;
4 use syntax::ast::*;
5 use syntax::attr;
6 use syntax::visit::{Visitor, walk_block, walk_pat, walk_expr};
7 use utils::{span_lint_and_then, in_macro, span_lint};
8
9 /// **What it does:** This lint warns about names that are very similar and thus confusing
10 ///
11 /// **Why is this bad?** It's hard to distinguish between names that differ only by a single character
12 ///
13 /// **Known problems:** None?
14 ///
15 /// **Example:** `checked_exp` and `checked_expr`
16 declare_lint! {
17     pub SIMILAR_NAMES,
18     Allow,
19     "similarly named items and bindings"
20 }
21
22 /// **What it does:** This lint warns about having too many variables whose name consists of a single character
23 ///
24 /// **Why is this bad?** It's hard to memorize what a variable means without a descriptive name.
25 ///
26 /// **Known problems:** None?
27 ///
28 /// **Example:**
29 ///
30 /// ```rust
31 /// let (a, b, c, d, e, f, g) = (...);
32 /// ```
33 declare_lint! {
34     pub MANY_SINGLE_CHAR_NAMES,
35     Warn,
36     "too many single character bindings"
37 }
38
39 pub struct NonExpressiveNames {
40     pub max_single_char_names: u64,
41 }
42
43 impl LintPass for NonExpressiveNames {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES)
46     }
47 }
48
49 struct ExistingName {
50     interned: InternedString,
51     span: Span,
52     len: usize,
53     whitelist: &'static [&'static str],
54 }
55
56 struct SimilarNamesLocalVisitor<'a, 'b: 'a> {
57     names: Vec<ExistingName>,
58     cx: &'a EarlyContext<'b>,
59     lint: &'a NonExpressiveNames,
60     single_char_names: Vec<char>,
61 }
62
63 // this list contains lists of names that are allowed to be similar
64 // the assumption is that no name is ever contained in multiple lists.
65 #[cfg_attr(rustfmt, rustfmt_skip)]
66 const WHITELIST: &'static [&'static [&'static str]] = &[
67     &["parsed", "parser"],
68     &["lhs", "rhs"],
69     &["tx", "rx"],
70     &["set", "get"],
71 ];
72
73 struct SimilarNamesNameVisitor<'a, 'b: 'a, 'c: 'b>(&'a mut SimilarNamesLocalVisitor<'b, 'c>);
74
75 impl<'a, 'b, 'c> Visitor for SimilarNamesNameVisitor<'a, 'b, 'c> {
76     fn visit_pat(&mut self, pat: &Pat) {
77         match pat.node {
78             PatKind::Ident(_, id, _) => self.check_name(id.span, id.node.name),
79             PatKind::Struct(_, ref fields, _) => {
80                 for field in fields {
81                     if !field.node.is_shorthand {
82                         self.visit_pat(&field.node.pat);
83                     }
84                 }
85             }
86             _ => walk_pat(self, pat),
87         }
88     }
89 }
90
91 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
92     for &allow in WHITELIST {
93         if whitelisted(interned_name, allow) {
94             return Some(allow);
95         }
96     }
97     None
98 }
99
100 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
101     if list.iter().any(|&name| interned_name == name) {
102         return true;
103     }
104     for name in list {
105         // name_*
106         if interned_name.chars().zip(name.chars()).all(|(l, r)| l == r) {
107             return true;
108         }
109         // *_name
110         if interned_name.chars().rev().zip(name.chars().rev()).all(|(l, r)| l == r) {
111             return true;
112         }
113     }
114     false
115 }
116
117 impl<'a, 'b, 'c> SimilarNamesNameVisitor<'a, 'b, 'c> {
118     fn check_short_name(&mut self, c: char, span: Span) {
119         // make sure we ignore shadowing
120         if self.0.single_char_names.contains(&c) {
121             return;
122         }
123         self.0.single_char_names.push(c);
124         if self.0.single_char_names.len() as u64 >= self.0.lint.max_single_char_names {
125             span_lint(self.0.cx,
126                       MANY_SINGLE_CHAR_NAMES,
127                       span,
128                       &format!("{}th binding whose name is just one char", self.0.single_char_names.len()));
129         }
130     }
131     fn check_name(&mut self, span: Span, name: Name) {
132         if in_macro(self.0.cx, span) {
133             return;
134         }
135         let interned_name = name.as_str();
136         if interned_name.chars().any(char::is_uppercase) {
137             return;
138         }
139         let count = interned_name.chars().count();
140         if count < 3 {
141             if count == 1 {
142                 let c = interned_name.chars().next().expect("already checked");
143                 self.check_short_name(c, span);
144             }
145             return;
146         }
147         for existing_name in &self.0.names {
148             if whitelisted(&interned_name, existing_name.whitelist) {
149                 continue;
150             }
151             let mut split_at = None;
152             if existing_name.len > count {
153                 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
154                     continue;
155                 }
156             } else if existing_name.len < count {
157                 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
158                     continue;
159                 }
160             } else {
161                 let mut interned_chars = interned_name.chars();
162                 let mut existing_chars = existing_name.interned.chars();
163                 let first_i = interned_chars.next().expect("we know we have at least one char");
164                 let first_e = existing_chars.next().expect("we know we have at least one char");
165                 let eq_or_numeric = |a: char, b: char| a == b || a.is_numeric() && b.is_numeric();
166
167                 if eq_or_numeric(first_i, first_e) {
168                     let last_i = interned_chars.next_back().expect("we know we have at least two chars");
169                     let last_e = existing_chars.next_back().expect("we know we have at least two chars");
170                     if eq_or_numeric(last_i, last_e) {
171                         if interned_chars.zip(existing_chars).filter(|&(i, e)| !eq_or_numeric(i, e)).count() != 1 {
172                             continue;
173                         }
174                     } else {
175                         let second_last_i = interned_chars.next_back().expect("we know we have at least three chars");
176                         let second_last_e = existing_chars.next_back().expect("we know we have at least three chars");
177                         if !eq_or_numeric(second_last_i, second_last_e) || second_last_i == '_' ||
178                            !interned_chars.zip(existing_chars).all(|(i, e)| eq_or_numeric(i, e)) {
179                             // allowed similarity foo_x, foo_y
180                             // or too many chars differ (foo_x, boo_y) or (foox, booy)
181                             continue;
182                         }
183                         split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
184                     }
185                 } else {
186                     let second_i = interned_chars.next().expect("we know we have at least two chars");
187                     let second_e = existing_chars.next().expect("we know we have at least two chars");
188                     if !eq_or_numeric(second_i, second_e) || second_i == '_' ||
189                        !interned_chars.zip(existing_chars).all(|(i, e)| eq_or_numeric(i, e)) {
190                         // allowed similarity x_foo, y_foo
191                         // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
192                         continue;
193                     }
194                     split_at = interned_name.chars().next().map(|c| c.len_utf8());
195                 }
196             }
197             span_lint_and_then(self.0.cx,
198                                SIMILAR_NAMES,
199                                span,
200                                "binding's name is too similar to existing binding",
201                                |diag| {
202                 diag.span_note(existing_name.span, "existing binding defined here");
203                 if let Some(split) = split_at {
204                     diag.span_help(span,
205                                    &format!("separate the discriminating character by an \
206                                                                 underscore like: `{}_{}`",
207                                                                &interned_name[..split],
208                                                                &interned_name[split..]));
209                 }
210             });
211             return;
212         }
213         self.0.names.push(ExistingName {
214             whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
215             interned: interned_name,
216             span: span,
217             len: count,
218         });
219     }
220 }
221
222 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
223     /// ensure scoping rules work
224     fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
225         let n = self.names.len();
226         let single_char_count = self.single_char_names.len();
227         f(self);
228         self.names.truncate(n);
229         self.single_char_names.truncate(single_char_count);
230     }
231 }
232
233 impl<'a, 'b> Visitor for SimilarNamesLocalVisitor<'a, 'b> {
234     fn visit_local(&mut self, local: &Local) {
235         if let Some(ref init) = local.init {
236             self.apply(|this| walk_expr(this, &**init));
237         }
238         // add the pattern after the expression because the bindings aren't available yet in the init expression
239         SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
240     }
241     fn visit_block(&mut self, blk: &Block) {
242         self.apply(|this| walk_block(this, blk));
243     }
244     fn visit_arm(&mut self, arm: &Arm) {
245         self.apply(|this| {
246             // just go through the first pattern, as either all patterns bind the same bindings or rustc would have errored much earlier
247             SimilarNamesNameVisitor(this).visit_pat(&arm.pats[0]);
248             this.apply(|this| walk_expr(this, &arm.body));
249         });
250     }
251     fn visit_item(&mut self, _: &Item) {
252         // do not recurse into inner items
253     }
254 }
255
256 impl EarlyLintPass for NonExpressiveNames {
257     fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
258         if let ItemKind::Fn(ref decl, _, _, _, _, ref blk) = item.node {
259             if !attr::contains_name(&item.attrs, "test") {
260                 let mut visitor = SimilarNamesLocalVisitor {
261                     names: Vec::new(),
262                     cx: cx,
263                     lint: self,
264                     single_char_names: Vec::new(),
265                 };
266                 // initialize with function arguments
267                 for arg in &decl.inputs {
268                     SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
269                 }
270                 // walk all other bindings
271                 walk_block(&mut visitor, blk);
272             }
273         }
274     }
275 }
276
277 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
278 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
279     debug_assert!(a_name.chars().count() < b_name.chars().count());
280     let mut a_chars = a_name.chars();
281     let mut b_chars = b_name.chars();
282     while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
283         if a == b {
284             continue;
285         }
286         if let Some(b2) = b_chars.next() {
287             // check if there's just one character inserted
288             return a != b2 || a_chars.ne(b_chars);
289         } else {
290             // tuple
291             // ntuple
292             return true;
293         }
294     }
295     // for item in items
296     true
297 }