2 use syntax::codemap::Span;
3 use syntax::symbol::InternedString;
6 use syntax::visit::{Visitor, walk_block, walk_pat, walk_expr};
7 use utils::{span_lint_and_then, in_macro, span_lint};
9 /// **What it does:** Checks for names that are very similar and thus confusing.
11 /// **Why is this bad?** It's hard to distinguish between names that differ only
12 /// by a single character.
14 /// **Known problems:** None?
18 /// let checked_exp = something;
19 /// let checked_expr = something_else;
24 "similarly named items and bindings"
27 /// **What it does:** Checks for too many variables whose name consists of a
30 /// **Why is this bad?** It's hard to memorize what a variable means without a
33 /// **Known problems:** None?
37 /// let (a, b, c, d, e, f, g) = (...);
40 pub MANY_SINGLE_CHAR_NAMES,
42 "too many single character bindings"
45 pub struct NonExpressiveNames {
46 pub single_char_binding_names_threshold: u64,
49 impl LintPass for NonExpressiveNames {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(SIMILAR_NAMES, MANY_SINGLE_CHAR_NAMES)
56 interned: InternedString,
59 whitelist: &'static [&'static str],
62 struct SimilarNamesLocalVisitor<'a, 'tcx: 'a> {
63 names: Vec<ExistingName>,
64 cx: &'a EarlyContext<'tcx>,
65 lint: &'a NonExpressiveNames,
66 single_char_names: Vec<char>,
69 // this list contains lists of names that are allowed to be similar
70 // the assumption is that no name is ever contained in multiple lists.
71 #[cfg_attr(rustfmt, rustfmt_skip)]
72 const WHITELIST: &'static [&'static [&'static str]] = &[
73 &["parsed", "parser"],
79 struct SimilarNamesNameVisitor<'a: 'b, 'tcx: 'a, 'b>(&'b mut SimilarNamesLocalVisitor<'a, 'tcx>);
81 impl<'a, 'tcx: 'a, 'b> Visitor<'tcx> for SimilarNamesNameVisitor<'a, 'tcx, 'b> {
82 fn visit_pat(&mut self, pat: &'tcx Pat) {
84 PatKind::Ident(_, id, _) => self.check_name(id.span, id.node.name),
85 PatKind::Struct(_, ref fields, _) => {
87 if !field.node.is_shorthand {
88 self.visit_pat(&field.node.pat);
92 _ => walk_pat(self, pat),
97 fn get_whitelist(interned_name: &str) -> Option<&'static [&'static str]> {
98 for &allow in WHITELIST {
99 if whitelisted(interned_name, allow) {
106 fn whitelisted(interned_name: &str, list: &[&str]) -> bool {
107 if list.iter().any(|&name| interned_name == name) {
112 if interned_name.chars().zip(name.chars()).all(|(l, r)| l == r) {
116 if interned_name.chars().rev().zip(name.chars().rev()).all(|(l, r)| l == r) {
123 impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
124 fn check_short_name(&mut self, c: char, span: Span) {
125 // make sure we ignore shadowing
126 if self.0.single_char_names.contains(&c) {
129 self.0.single_char_names.push(c);
130 if self.0.single_char_names.len() as u64 >= self.0.lint.single_char_binding_names_threshold {
132 MANY_SINGLE_CHAR_NAMES,
134 &format!("{}th binding whose name is just one char", self.0.single_char_names.len()));
137 fn check_name(&mut self, span: Span, name: Name) {
141 let interned_name = name.as_str();
142 if interned_name.chars().any(char::is_uppercase) {
145 let count = interned_name.chars().count();
148 let c = interned_name.chars().next().expect("already checked");
149 self.check_short_name(c, span);
153 for existing_name in &self.0.names {
154 if whitelisted(&interned_name, existing_name.whitelist) {
157 let mut split_at = None;
158 if existing_name.len > count {
159 if existing_name.len - count != 1 || levenstein_not_1(&interned_name, &existing_name.interned) {
162 } else if existing_name.len < count {
163 if count - existing_name.len != 1 || levenstein_not_1(&existing_name.interned, &interned_name) {
167 let mut interned_chars = interned_name.chars();
168 let mut existing_chars = existing_name.interned.chars();
169 let first_i = interned_chars.next().expect("we know we have at least one char");
170 let first_e = existing_chars.next().expect("we know we have at least one char");
171 let eq_or_numeric = |a: char, b: char| a == b || a.is_numeric() && b.is_numeric();
173 if eq_or_numeric(first_i, first_e) {
174 let last_i = interned_chars.next_back().expect("we know we have at least two chars");
175 let last_e = existing_chars.next_back().expect("we know we have at least two chars");
176 if eq_or_numeric(last_i, last_e) {
177 if interned_chars.zip(existing_chars).filter(|&(i, e)| !eq_or_numeric(i, e)).count() != 1 {
181 let second_last_i = interned_chars.next_back().expect("we know we have at least three chars");
182 let second_last_e = existing_chars.next_back().expect("we know we have at least three chars");
183 if !eq_or_numeric(second_last_i, second_last_e) || second_last_i == '_' ||
184 !interned_chars.zip(existing_chars).all(|(i, e)| eq_or_numeric(i, e)) {
185 // allowed similarity foo_x, foo_y
186 // or too many chars differ (foo_x, boo_y) or (foox, booy)
189 split_at = interned_name.char_indices().rev().next().map(|(i, _)| i);
192 let second_i = interned_chars.next().expect("we know we have at least two chars");
193 let second_e = existing_chars.next().expect("we know we have at least two chars");
194 if !eq_or_numeric(second_i, second_e) || second_i == '_' ||
195 !interned_chars.zip(existing_chars).all(|(i, e)| eq_or_numeric(i, e)) {
196 // allowed similarity x_foo, y_foo
197 // or too many chars differ (x_foo, y_boo) or (xfoo, yboo)
200 split_at = interned_name.chars().next().map(|c| c.len_utf8());
203 span_lint_and_then(self.0.cx,
206 "binding's name is too similar to existing binding",
208 diag.span_note(existing_name.span, "existing binding defined here");
209 if let Some(split) = split_at {
211 &format!("separate the discriminating character by an \
212 underscore like: `{}_{}`",
213 &interned_name[..split],
214 &interned_name[split..]));
219 self.0.names.push(ExistingName {
220 whitelist: get_whitelist(&interned_name).unwrap_or(&[]),
221 interned: interned_name,
228 impl<'a, 'b> SimilarNamesLocalVisitor<'a, 'b> {
229 /// ensure scoping rules work
230 fn apply<F: for<'c> Fn(&'c mut Self)>(&mut self, f: F) {
231 let n = self.names.len();
232 let single_char_count = self.single_char_names.len();
234 self.names.truncate(n);
235 self.single_char_names.truncate(single_char_count);
239 impl<'a, 'tcx> Visitor<'tcx> for SimilarNamesLocalVisitor<'a, 'tcx> {
240 fn visit_local(&mut self, local: &'tcx Local) {
241 if let Some(ref init) = local.init {
242 self.apply(|this| walk_expr(this, &**init));
244 // add the pattern after the expression because the bindings aren't available yet in the init
246 SimilarNamesNameVisitor(self).visit_pat(&*local.pat);
248 fn visit_block(&mut self, blk: &'tcx Block) {
249 self.apply(|this| walk_block(this, blk));
251 fn visit_arm(&mut self, arm: &'tcx Arm) {
253 // just go through the first pattern, as either all patterns
254 // bind the same bindings or rustc would have errored much earlier
255 SimilarNamesNameVisitor(this).visit_pat(&arm.pats[0]);
256 this.apply(|this| walk_expr(this, &arm.body));
259 fn visit_item(&mut self, _: &Item) {
260 // do not recurse into inner items
264 impl EarlyLintPass for NonExpressiveNames {
265 fn check_item(&mut self, cx: &EarlyContext, item: &Item) {
266 if let ItemKind::Fn(ref decl, _, _, _, _, ref blk) = item.node {
267 if !attr::contains_name(&item.attrs, "test") {
268 let mut visitor = SimilarNamesLocalVisitor {
272 single_char_names: Vec::new(),
274 // initialize with function arguments
275 for arg in &decl.inputs {
276 SimilarNamesNameVisitor(&mut visitor).visit_pat(&arg.pat);
278 // walk all other bindings
279 walk_block(&mut visitor, blk);
285 /// Precondition: `a_name.chars().count() < b_name.chars().count()`.
286 fn levenstein_not_1(a_name: &str, b_name: &str) -> bool {
287 debug_assert!(a_name.chars().count() < b_name.chars().count());
288 let mut a_chars = a_name.chars();
289 let mut b_chars = b_name.chars();
290 while let (Some(a), Some(b)) = (a_chars.next(), b_chars.next()) {
294 if let Some(b2) = b_chars.next() {
295 // check if there's just one character inserted
296 return a != b2 || a_chars.ne(b_chars);