]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc_early.rs
Merge pull request #2399 from rust-lang-nursery/rustup
[rust.git] / clippy_lints / src / misc_early.rs
1 use rustc::lint::*;
2 use std::collections::HashMap;
3 use std::char;
4 use syntax::ast::*;
5 use syntax::codemap::Span;
6 use syntax::visit::FnKind;
7 use utils::{constants, in_external_macro, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_then};
8
9 /// **What it does:** Checks for structure field patterns bound to wildcards.
10 ///
11 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
12 /// the fields that are actually bound.
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// let { a: _, b: ref b, c: _ } = ..
19 /// ```
20 declare_lint! {
21     pub UNNEEDED_FIELD_PATTERN,
22     Warn,
23     "struct fields bound to a wildcard instead of using `..`"
24 }
25
26 /// **What it does:** Checks for function arguments having the similar names
27 /// differing by an underscore.
28 ///
29 /// **Why is this bad?** It affects code readability.
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// fn foo(a: i32, _a: i32) {}
36 /// ```
37 declare_lint! {
38     pub DUPLICATE_UNDERSCORE_ARGUMENT,
39     Warn,
40     "function arguments having names which only differ by an underscore"
41 }
42
43 /// **What it does:** Detects closures called in the same expression where they
44 /// are defined.
45 ///
46 /// **Why is this bad?** It is unnecessarily adding to the expression's
47 /// complexity.
48 ///
49 /// **Known problems:** None.
50 ///
51 /// **Example:**
52 /// ```rust
53 /// (|| 42)()
54 /// ```
55 declare_lint! {
56     pub REDUNDANT_CLOSURE_CALL,
57     Warn,
58     "throwaway closures called in the expression they are defined"
59 }
60
61 /// **What it does:** Detects expressions of the form `--x`.
62 ///
63 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
64 /// decremented.
65 ///
66 /// **Known problems:** None.
67 ///
68 /// **Example:**
69 /// ```rust
70 /// --x;
71 /// ```
72 declare_lint! {
73     pub DOUBLE_NEG,
74     Warn,
75     "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
76 }
77
78 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
79 /// digits.
80 ///
81 /// **Why is this bad?** It looks confusing.
82 ///
83 /// **Known problems:** None.
84 ///
85 /// **Example:**
86 /// ```rust
87 /// let y = 0x1a9BAcD;
88 /// ```
89 declare_lint! {
90     pub MIXED_CASE_HEX_LITERALS,
91     Warn,
92     "hex literals whose letter digits are not consistently upper- or lowercased"
93 }
94
95 /// **What it does:** Warns if literal suffixes are not separated by an
96 /// underscore.
97 ///
98 /// **Why is this bad?** It is much less readable.
99 ///
100 /// **Known problems:** None.
101 ///
102 /// **Example:**
103 /// ```rust
104 /// let y = 123832i32;
105 /// ```
106 declare_lint! {
107     pub UNSEPARATED_LITERAL_SUFFIX,
108     Allow,
109     "literals whose suffix is not separated by an underscore"
110 }
111
112 /// **What it does:** Warns if an integral constant literal starts with `0`.
113 ///
114 /// **Why is this bad?** In some languages (including the infamous C language
115 /// and most of its
116 /// family), this marks an octal constant. In Rust however, this is a decimal
117 /// constant. This could
118 /// be confusing for both the writer and a reader of the constant.
119 ///
120 /// **Known problems:** None.
121 ///
122 /// **Example:**
123 ///
124 /// In Rust:
125 /// ```rust
126 /// fn main() {
127 ///     let a = 0123;
128 ///     println!("{}", a);
129 /// }
130 /// ```
131 ///
132 /// prints `123`, while in C:
133 ///
134 /// ```c
135 /// #include <stdio.h>
136 ///
137 /// int main() {
138 ///     int a = 0123;
139 ///     printf("%d\n", a);
140 /// }
141 /// ```
142 ///
143 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
144 declare_lint! {
145     pub ZERO_PREFIXED_LITERAL,
146     Warn,
147     "integer literals starting with `0`"
148 }
149
150 /// **What it does:** Warns if a generic shadows a built-in type.
151 ///
152 /// **Why is this bad?** This gives surprising type errors.
153 ///
154 /// **Known problems:** None.
155 ///
156 /// **Example:**
157 ///
158 /// ```rust
159 /// impl<u32> Foo<u32> {
160 ///     fn impl_func(&self) -> u32 {
161 ///         42
162 ///     }
163 /// }
164 /// ```
165 declare_lint! {
166     pub BUILTIN_TYPE_SHADOW,
167     Warn,
168     "shadowing a builtin type"
169 }
170
171 #[derive(Copy, Clone)]
172 pub struct MiscEarly;
173
174 impl LintPass for MiscEarly {
175     fn get_lints(&self) -> LintArray {
176         lint_array!(
177             UNNEEDED_FIELD_PATTERN,
178             DUPLICATE_UNDERSCORE_ARGUMENT,
179             REDUNDANT_CLOSURE_CALL,
180             DOUBLE_NEG,
181             MIXED_CASE_HEX_LITERALS,
182             UNSEPARATED_LITERAL_SUFFIX,
183             ZERO_PREFIXED_LITERAL,
184             BUILTIN_TYPE_SHADOW
185         )
186     }
187 }
188
189 impl EarlyLintPass for MiscEarly {
190     fn check_generics(&mut self, cx: &EarlyContext, gen: &Generics) {
191         for param in &gen.params {
192             if let GenericParam::Type(ref ty) = *param {
193                 let name = ty.ident.name.as_str();
194                 if constants::BUILTIN_TYPES.contains(&&*name) {
195                     span_lint(
196                         cx,
197                         BUILTIN_TYPE_SHADOW,
198                         ty.span,
199                         &format!("This generic shadows the built-in type `{}`", name),
200                     );
201                 }
202             }
203         }
204     }
205
206     fn check_pat(&mut self, cx: &EarlyContext, pat: &Pat) {
207         if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
208             let mut wilds = 0;
209             let type_name = npat.segments
210                 .last()
211                 .expect("A path must have at least one segment")
212                 .identifier
213                 .name;
214
215             for field in pfields {
216                 if field.node.pat.node == PatKind::Wild {
217                     wilds += 1;
218                 }
219             }
220             if !pfields.is_empty() && wilds == pfields.len() {
221                 span_help_and_lint(
222                     cx,
223                     UNNEEDED_FIELD_PATTERN,
224                     pat.span,
225                     "All the struct fields are matched to a wildcard pattern, consider using `..`.",
226                     &format!("Try with `{} {{ .. }}` instead", type_name),
227                 );
228                 return;
229             }
230             if wilds > 0 {
231                 let mut normal = vec![];
232
233                 for field in pfields {
234                     if field.node.pat.node != PatKind::Wild {
235                         if let Ok(n) = cx.sess().codemap().span_to_snippet(field.span) {
236                             normal.push(n);
237                         }
238                     }
239                 }
240                 for field in pfields {
241                     if field.node.pat.node == PatKind::Wild {
242                         wilds -= 1;
243                         if wilds > 0 {
244                             span_lint(
245                                 cx,
246                                 UNNEEDED_FIELD_PATTERN,
247                                 field.span,
248                                 "You matched a field with a wildcard pattern. Consider using `..` instead",
249                             );
250                         } else {
251                             span_help_and_lint(
252                                 cx,
253                                 UNNEEDED_FIELD_PATTERN,
254                                 field.span,
255                                 "You matched a field with a wildcard pattern. Consider using `..` \
256                                  instead",
257                                 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
258                             );
259                         }
260                     }
261                 }
262             }
263         }
264     }
265
266     fn check_fn(&mut self, cx: &EarlyContext, _: FnKind, decl: &FnDecl, _: Span, _: NodeId) {
267         let mut registered_names: HashMap<String, Span> = HashMap::new();
268
269         for arg in &decl.inputs {
270             if let PatKind::Ident(_, sp_ident, None) = arg.pat.node {
271                 let arg_name = sp_ident.node.to_string();
272
273                 if arg_name.starts_with('_') {
274                     if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
275                         span_lint(
276                             cx,
277                             DUPLICATE_UNDERSCORE_ARGUMENT,
278                             *correspondence,
279                             &format!(
280                                 "`{}` already exists, having another argument having almost the same \
281                                  name makes code comprehension and documentation more difficult",
282                                 arg_name[1..].to_owned()
283                             ),
284                         );;
285                     }
286                 } else {
287                     registered_names.insert(arg_name, arg.pat.span);
288                 }
289             }
290         }
291     }
292
293     fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
294         if in_external_macro(cx, expr.span) {
295             return;
296         }
297         match expr.node {
298             ExprKind::Call(ref paren, _) => if let ExprKind::Paren(ref closure) = paren.node {
299                 if let ExprKind::Closure(_, _, ref decl, ref block, _) = closure.node {
300                     span_lint_and_then(
301                         cx,
302                         REDUNDANT_CLOSURE_CALL,
303                         expr.span,
304                         "Try not to call a closure in the expression where it is declared.",
305                         |db| if decl.inputs.is_empty() {
306                             let hint = snippet(cx, block.span, "..").into_owned();
307                             db.span_suggestion(expr.span, "Try doing something like: ", hint);
308                         },
309                     );
310                 }
311             },
312             ExprKind::Unary(UnOp::Neg, ref inner) => if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
313                 span_lint(
314                     cx,
315                     DOUBLE_NEG,
316                     expr.span,
317                     "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
318                 );
319             },
320             ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
321             _ => (),
322         }
323     }
324
325     fn check_block(&mut self, cx: &EarlyContext, block: &Block) {
326         for w in block.stmts.windows(2) {
327             if_chain! {
328                 if let StmtKind::Local(ref local) = w[0].node;
329                 if let Option::Some(ref t) = local.init;
330                 if let ExprKind::Closure(_, _, _, _, _) = t.node;
331                 if let PatKind::Ident(_, sp_ident, _) = local.pat.node;
332                 if let StmtKind::Semi(ref second) = w[1].node;
333                 if let ExprKind::Assign(_, ref call) = second.node;
334                 if let ExprKind::Call(ref closure, _) = call.node;
335                 if let ExprKind::Path(_, ref path) = closure.node;
336                 then {
337                     if sp_ident.node == (&path.segments[0]).identifier {
338                         span_lint(
339                             cx,
340                             REDUNDANT_CLOSURE_CALL,
341                             second.span,
342                             "Closure called just once immediately after it was declared",
343                         );
344                     }
345                 }
346             }
347         }
348     }
349 }
350
351 impl MiscEarly {
352     fn check_lit(&self, cx: &EarlyContext, lit: &Lit) {
353         if_chain! {
354             if let LitKind::Int(value, ..) = lit.node;
355             if let Some(src) = snippet_opt(cx, lit.span);
356             if let Some(firstch) = src.chars().next();
357             if char::to_digit(firstch, 10).is_some();
358             then {
359                 let mut prev = '\0';
360                 for ch in src.chars() {
361                     if ch == 'i' || ch == 'u' {
362                         if prev != '_' {
363                             span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
364                                         "integer type suffix should be separated by an underscore");
365                         }
366                         break;
367                     }
368                     prev = ch;
369                 }
370                 if src.starts_with("0x") {
371                     let mut seen = (false, false);
372                     for ch in src.chars() {
373                         match ch {
374                             'a' ... 'f' => seen.0 = true,
375                             'A' ... 'F' => seen.1 = true,
376                             'i' | 'u'   => break,   // start of suffix already
377                             _ => ()
378                         }
379                     }
380                     if seen.0 && seen.1 {
381                         span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
382                                     "inconsistent casing in hexadecimal literal");
383                     }
384                 } else if src.starts_with("0b") || src.starts_with("0o") {
385                     /* nothing to do */
386                 } else if value != 0 && src.starts_with('0') {
387                     span_lint_and_then(cx,
388                                         ZERO_PREFIXED_LITERAL,
389                                         lit.span,
390                                         "this is a decimal constant",
391                                         |db| {
392                         db.span_suggestion(
393                             lit.span,
394                             "if you mean to use a decimal constant, remove the `0` to remove confusion",
395                             src.trim_left_matches(|c| c == '_' || c == '0').to_string(),
396                         );
397                         db.span_suggestion(
398                             lit.span,
399                             "if you mean to use an octal constant, use `0o`",
400                             format!("0o{}", src.trim_left_matches(|c| c == '_' || c == '0')),
401                         );
402                     });
403                 }
404             }
405         }
406         if_chain! {
407             if let LitKind::Float(..) = lit.node;
408             if let Some(src) = snippet_opt(cx, lit.span);
409             if let Some(firstch) = src.chars().next();
410             if char::to_digit(firstch, 10).is_some();
411             then {
412                 let mut prev = '\0';
413                 for ch in src.chars() {
414                     if ch == 'f' {
415                         if prev != '_' {
416                             span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
417                                         "float type suffix should be separated by an underscore");
418                         }
419                         break;
420                     }
421                     prev = ch;
422                 }
423             }
424         }
425     }
426 }