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