]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc_early.rs
Apply review suggestions
[rust.git] / clippy_lints / src / misc_early.rs
1 use crate::utils::{
2     constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then,
3 };
4 use if_chain::if_chain;
5 use rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::Applicability;
9 use syntax::ast::*;
10 use syntax::source_map::Span;
11 use syntax::visit::{walk_expr, FnKind, Visitor};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for structure field patterns bound to wildcards.
15     ///
16     /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
17     /// the fields that are actually bound.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     /// ```ignore
23     /// let { a: _, b: ref b, c: _ } = ..
24     /// ```
25     pub UNNEEDED_FIELD_PATTERN,
26     style,
27     "struct fields bound to a wildcard instead of using `..`"
28 }
29
30 declare_clippy_lint! {
31     /// **What it does:** Checks for function arguments having the similar names
32     /// differing by an underscore.
33     ///
34     /// **Why is this bad?** It affects code readability.
35     ///
36     /// **Known problems:** None.
37     ///
38     /// **Example:**
39     /// ```rust
40     /// fn foo(a: i32, _a: i32) {}
41     /// ```
42     pub DUPLICATE_UNDERSCORE_ARGUMENT,
43     style,
44     "function arguments having names which only differ by an underscore"
45 }
46
47 declare_clippy_lint! {
48     /// **What it does:** Detects closures called in the same expression where they
49     /// are defined.
50     ///
51     /// **Why is this bad?** It is unnecessarily adding to the expression's
52     /// complexity.
53     ///
54     /// **Known problems:** None.
55     ///
56     /// **Example:**
57     /// ```rust,ignore
58     /// (|| 42)()
59     /// ```
60     pub REDUNDANT_CLOSURE_CALL,
61     complexity,
62     "throwaway closures called in the expression they are defined"
63 }
64
65 declare_clippy_lint! {
66     /// **What it does:** Detects expressions of the form `--x`.
67     ///
68     /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
69     /// decremented.
70     ///
71     /// **Known problems:** None.
72     ///
73     /// **Example:**
74     /// ```rust
75     /// let mut x = 3;
76     /// --x;
77     /// ```
78     pub DOUBLE_NEG,
79     style,
80     "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
81 }
82
83 declare_clippy_lint! {
84     /// **What it does:** Warns on hexadecimal literals with mixed-case letter
85     /// digits.
86     ///
87     /// **Why is this bad?** It looks confusing.
88     ///
89     /// **Known problems:** None.
90     ///
91     /// **Example:**
92     /// ```rust
93     /// let y = 0x1a9BAcD;
94     /// ```
95     pub MIXED_CASE_HEX_LITERALS,
96     style,
97     "hex literals whose letter digits are not consistently upper- or lowercased"
98 }
99
100 declare_clippy_lint! {
101     /// **What it does:** Warns if literal suffixes are not separated by an
102     /// underscore.
103     ///
104     /// **Why is this bad?** It is much less readable.
105     ///
106     /// **Known problems:** None.
107     ///
108     /// **Example:**
109     /// ```rust
110     /// let y = 123832i32;
111     /// ```
112     pub UNSEPARATED_LITERAL_SUFFIX,
113     pedantic,
114     "literals whose suffix is not separated by an underscore"
115 }
116
117 declare_clippy_lint! {
118     /// **What it does:** Warns if an integral constant literal starts with `0`.
119     ///
120     /// **Why is this bad?** In some languages (including the infamous C language
121     /// and most of its
122     /// family), this marks an octal constant. In Rust however, this is a decimal
123     /// constant. This could
124     /// be confusing for both the writer and a reader of the constant.
125     ///
126     /// **Known problems:** None.
127     ///
128     /// **Example:**
129     ///
130     /// In Rust:
131     /// ```rust
132     /// fn main() {
133     ///     let a = 0123;
134     ///     println!("{}", a);
135     /// }
136     /// ```
137     ///
138     /// prints `123`, while in C:
139     ///
140     /// ```c
141     /// #include <stdio.h>
142     ///
143     /// int main() {
144     ///     int a = 0123;
145     ///     printf("%d\n", a);
146     /// }
147     /// ```
148     ///
149     /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
150     pub ZERO_PREFIXED_LITERAL,
151     complexity,
152     "integer literals starting with `0`"
153 }
154
155 declare_clippy_lint! {
156     /// **What it does:** Warns if a generic shadows a built-in type.
157     ///
158     /// **Why is this bad?** This gives surprising type errors.
159     ///
160     /// **Known problems:** None.
161     ///
162     /// **Example:**
163     ///
164     /// ```ignore
165     /// impl<u32> Foo<u32> {
166     ///     fn impl_func(&self) -> u32 {
167     ///         42
168     ///     }
169     /// }
170     /// ```
171     pub BUILTIN_TYPE_SHADOW,
172     style,
173     "shadowing a builtin type"
174 }
175
176 declare_clippy_lint! {
177     /// **What it does:** Checks for patterns in the form `name @ _`.
178     ///
179     /// **Why is this bad?** It's almost always more readable to just use direct
180     /// bindings.
181     ///
182     /// **Known problems:** None.
183     ///
184     /// **Example:**
185     /// ```rust
186     /// # let v = Some("abc");
187     ///
188     /// match v {
189     ///     Some(x) => (),
190     ///     y @ _ => (), // easier written as `y`,
191     /// }
192     /// ```
193     pub REDUNDANT_PATTERN,
194     style,
195     "using `name @ _` in a pattern"
196 }
197
198 declare_clippy_lint! {
199     /// **What it does:** Checks for tuple patterns with a wildcard
200     /// pattern (`_`) is next to a rest pattern (`..`).
201     ///
202     /// **Why is this bad?** The wildcard pattern is unneeded as the rest pattern
203     /// can match that element as well.
204     ///
205     /// **Known problems:** None.
206     ///
207     /// **Example:**
208     /// ```rust
209     /// # struct TupleStruct(u32, u32, u32);
210     /// # let t = TupleStruct(1, 2, 3);
211     ///
212     /// match t {
213     ///     TupleStruct(0, .., _) => (),
214     ///     _ => (),
215     /// }
216     /// ```
217     /// can be written as
218     /// ```rust
219     /// # struct TupleStruct(u32, u32, u32);
220     /// # let t = TupleStruct(1, 2, 3);
221     ///
222     /// match t {
223     ///     TupleStruct(0, ..) => (),
224     ///     _ => (),
225     /// }
226     /// ```
227     pub UNNEEDED_WILDCARD_PATTERN,
228     complexity,
229     "tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`)"
230 }
231
232 declare_lint_pass!(MiscEarlyLints => [
233     UNNEEDED_FIELD_PATTERN,
234     DUPLICATE_UNDERSCORE_ARGUMENT,
235     REDUNDANT_CLOSURE_CALL,
236     DOUBLE_NEG,
237     MIXED_CASE_HEX_LITERALS,
238     UNSEPARATED_LITERAL_SUFFIX,
239     ZERO_PREFIXED_LITERAL,
240     BUILTIN_TYPE_SHADOW,
241     REDUNDANT_PATTERN,
242     UNNEEDED_WILDCARD_PATTERN,
243 ]);
244
245 // Used to find `return` statements or equivalents e.g., `?`
246 struct ReturnVisitor {
247     found_return: bool,
248 }
249
250 impl ReturnVisitor {
251     fn new() -> Self {
252         Self { found_return: false }
253     }
254 }
255
256 impl<'ast> Visitor<'ast> for ReturnVisitor {
257     fn visit_expr(&mut self, ex: &'ast Expr) {
258         if let ExprKind::Ret(_) = ex.node {
259             self.found_return = true;
260         } else if let ExprKind::Try(_) = ex.node {
261             self.found_return = true;
262         }
263
264         walk_expr(self, ex)
265     }
266 }
267
268 impl EarlyLintPass for MiscEarlyLints {
269     fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
270         for param in &gen.params {
271             if let GenericParamKind::Type { .. } = param.kind {
272                 let name = param.ident.as_str();
273                 if constants::BUILTIN_TYPES.contains(&&*name) {
274                     span_lint(
275                         cx,
276                         BUILTIN_TYPE_SHADOW,
277                         param.ident.span,
278                         &format!("This generic shadows the built-in type `{}`", name),
279                     );
280                 }
281             }
282         }
283     }
284
285     fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
286         if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
287             let mut wilds = 0;
288             let type_name = npat
289                 .segments
290                 .last()
291                 .expect("A path must have at least one segment")
292                 .ident
293                 .name;
294
295             for field in pfields {
296                 if let PatKind::Wild = field.pat.node {
297                     wilds += 1;
298                 }
299             }
300             if !pfields.is_empty() && wilds == pfields.len() {
301                 span_help_and_lint(
302                     cx,
303                     UNNEEDED_FIELD_PATTERN,
304                     pat.span,
305                     "All the struct fields are matched to a wildcard pattern, consider using `..`.",
306                     &format!("Try with `{} {{ .. }}` instead", type_name),
307                 );
308                 return;
309             }
310             if wilds > 0 {
311                 let mut normal = vec![];
312
313                 for field in pfields {
314                     match field.pat.node {
315                         PatKind::Wild => {},
316                         _ => {
317                             if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
318                                 normal.push(n);
319                             }
320                         },
321                     }
322                 }
323                 for field in pfields {
324                     if let PatKind::Wild = field.pat.node {
325                         wilds -= 1;
326                         if wilds > 0 {
327                             span_lint(
328                                 cx,
329                                 UNNEEDED_FIELD_PATTERN,
330                                 field.span,
331                                 "You matched a field with a wildcard pattern. Consider using `..` instead",
332                             );
333                         } else {
334                             span_help_and_lint(
335                                 cx,
336                                 UNNEEDED_FIELD_PATTERN,
337                                 field.span,
338                                 "You matched a field with a wildcard pattern. Consider using `..` \
339                                  instead",
340                                 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
341                             );
342                         }
343                     }
344                 }
345             }
346         }
347
348         if let PatKind::Ident(_, ident, Some(ref right)) = pat.node {
349             if let PatKind::Wild = right.node {
350                 span_lint_and_sugg(
351                     cx,
352                     REDUNDANT_PATTERN,
353                     pat.span,
354                     &format!(
355                         "the `{} @ _` pattern can be written as just `{}`",
356                         ident.name, ident.name,
357                     ),
358                     "try",
359                     format!("{}", ident.name),
360                     Applicability::MachineApplicable,
361                 );
362             }
363         }
364
365         check_unneeded_wildcard_pattern(cx, pat);
366     }
367
368     fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
369         let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
370
371         for arg in &decl.inputs {
372             if let PatKind::Ident(_, ident, None) = arg.pat.node {
373                 let arg_name = ident.to_string();
374
375                 if arg_name.starts_with('_') {
376                     if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
377                         span_lint(
378                             cx,
379                             DUPLICATE_UNDERSCORE_ARGUMENT,
380                             *correspondence,
381                             &format!(
382                                 "`{}` already exists, having another argument having almost the same \
383                                  name makes code comprehension and documentation more difficult",
384                                 arg_name[1..].to_owned()
385                             ),
386                         );
387                     }
388                 } else {
389                     registered_names.insert(arg_name, arg.pat.span);
390                 }
391             }
392         }
393     }
394
395     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
396         if in_external_macro(cx.sess(), expr.span) {
397             return;
398         }
399         match expr.node {
400             ExprKind::Call(ref paren, _) => {
401                 if let ExprKind::Paren(ref closure) = paren.node {
402                     if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
403                         let mut visitor = ReturnVisitor::new();
404                         visitor.visit_expr(block);
405                         if !visitor.found_return {
406                             span_lint_and_then(
407                                 cx,
408                                 REDUNDANT_CLOSURE_CALL,
409                                 expr.span,
410                                 "Try not to call a closure in the expression where it is declared.",
411                                 |db| {
412                                     if decl.inputs.is_empty() {
413                                         let hint = snippet(cx, block.span, "..").into_owned();
414                                         db.span_suggestion(
415                                             expr.span,
416                                             "Try doing something like: ",
417                                             hint,
418                                             Applicability::MachineApplicable, // snippet
419                                         );
420                                     }
421                                 },
422                             );
423                         }
424                     }
425                 }
426             },
427             ExprKind::Unary(UnOp::Neg, ref inner) => {
428                 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
429                     span_lint(
430                         cx,
431                         DOUBLE_NEG,
432                         expr.span,
433                         "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
434                     );
435                 }
436             },
437             ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
438             _ => (),
439         }
440     }
441
442     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
443         for w in block.stmts.windows(2) {
444             if_chain! {
445                 if let StmtKind::Local(ref local) = w[0].node;
446                 if let Option::Some(ref t) = local.init;
447                 if let ExprKind::Closure(..) = t.node;
448                 if let PatKind::Ident(_, ident, _) = local.pat.node;
449                 if let StmtKind::Semi(ref second) = w[1].node;
450                 if let ExprKind::Assign(_, ref call) = second.node;
451                 if let ExprKind::Call(ref closure, _) = call.node;
452                 if let ExprKind::Path(_, ref path) = closure.node;
453                 then {
454                     if ident == path.segments[0].ident {
455                         span_lint(
456                             cx,
457                             REDUNDANT_CLOSURE_CALL,
458                             second.span,
459                             "Closure called just once immediately after it was declared",
460                         );
461                     }
462                 }
463             }
464         }
465     }
466 }
467
468 impl MiscEarlyLints {
469     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
470         // We test if first character in snippet is a number, because the snippet could be an expansion
471         // from a built-in macro like `line!()` or a proc-macro like `#[wasm_bindgen]`.
472         // Note that this check also covers special case that `line!()` is eagerly expanded by compiler.
473         // See <https://github.com/rust-lang/rust-clippy/issues/4507> for a regression.
474         // FIXME: Find a better way to detect those cases.
475         let lit_snip = match snippet_opt(cx, lit.span) {
476             Some(snip) if snip.chars().next().map_or(false, |c| c.is_digit(10)) => snip,
477             _ => return,
478         };
479
480         if let LitKind::Int(value, lit_int_type) = lit.node {
481             let suffix = match lit_int_type {
482                 LitIntType::Signed(ty) => ty.ty_to_string(),
483                 LitIntType::Unsigned(ty) => ty.ty_to_string(),
484                 LitIntType::Unsuffixed => "",
485             };
486
487             let maybe_last_sep_idx = lit_snip.len() - suffix.len() - 1;
488             // Do not lint when literal is unsuffixed.
489             if !suffix.is_empty() && lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
490                 span_lint_and_sugg(
491                     cx,
492                     UNSEPARATED_LITERAL_SUFFIX,
493                     lit.span,
494                     "integer type suffix should be separated by an underscore",
495                     "add an underscore",
496                     format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
497                     Applicability::MachineApplicable,
498                 );
499             }
500
501             if lit_snip.starts_with("0x") {
502                 let mut seen = (false, false);
503                 for ch in lit_snip.as_bytes()[2..=maybe_last_sep_idx].iter() {
504                     match ch {
505                         b'a'..=b'f' => seen.0 = true,
506                         b'A'..=b'F' => seen.1 = true,
507                         _ => {},
508                     }
509                     if seen.0 && seen.1 {
510                         span_lint(
511                             cx,
512                             MIXED_CASE_HEX_LITERALS,
513                             lit.span,
514                             "inconsistent casing in hexadecimal literal",
515                         );
516                         break;
517                     }
518                 }
519             } else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
520                 /* nothing to do */
521             } else if value != 0 && lit_snip.starts_with('0') {
522                 span_lint_and_then(
523                     cx,
524                     ZERO_PREFIXED_LITERAL,
525                     lit.span,
526                     "this is a decimal constant",
527                     |db| {
528                         db.span_suggestion(
529                             lit.span,
530                             "if you mean to use a decimal constant, remove the `0` to avoid confusion",
531                             lit_snip.trim_start_matches(|c| c == '_' || c == '0').to_string(),
532                             Applicability::MaybeIncorrect,
533                         );
534                         db.span_suggestion(
535                             lit.span,
536                             "if you mean to use an octal constant, use `0o`",
537                             format!("0o{}", lit_snip.trim_start_matches(|c| c == '_' || c == '0')),
538                             Applicability::MaybeIncorrect,
539                         );
540                     },
541                 );
542             }
543         } else if let LitKind::Float(_, float_ty) = lit.node {
544             let suffix = float_ty.ty_to_string();
545             let maybe_last_sep_idx = lit_snip.len() - suffix.len() - 1;
546             if lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
547                 span_lint_and_sugg(
548                     cx,
549                     UNSEPARATED_LITERAL_SUFFIX,
550                     lit.span,
551                     "float type suffix should be separated by an underscore",
552                     "add an underscore",
553                     format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
554                     Applicability::MachineApplicable,
555                 );
556             }
557         }
558     }
559 }
560
561 fn check_unneeded_wildcard_pattern(cx: &EarlyContext<'_>, pat: &Pat) {
562     if let PatKind::TupleStruct(_, ref patterns) | PatKind::Tuple(ref patterns) = pat.node {
563         fn span_lint(cx: &EarlyContext<'_>, span: Span, only_one: bool) {
564             span_lint_and_sugg(
565                 cx,
566                 UNNEEDED_WILDCARD_PATTERN,
567                 span,
568                 if only_one {
569                     "this pattern is unneeded as the `..` pattern can match that element"
570                 } else {
571                     "these patterns are unneeded as the `..` pattern can match those elements"
572                 },
573                 if only_one { "remove it" } else { "remove them" },
574                 "".to_string(),
575                 Applicability::MachineApplicable,
576             );
577         }
578
579         #[allow(clippy::trivially_copy_pass_by_ref)]
580         fn is_wild<P: std::ops::Deref<Target = Pat>>(pat: &&P) -> bool {
581             if let PatKind::Wild = pat.node {
582                 true
583             } else {
584                 false
585             }
586         }
587
588         if let Some(rest_index) = patterns.iter().position(|pat| pat.is_rest()) {
589             if let Some((left_index, left_pat)) = patterns[..rest_index]
590                 .iter()
591                 .rev()
592                 .take_while(is_wild)
593                 .enumerate()
594                 .last()
595             {
596                 span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0);
597             }
598
599             if let Some((right_index, right_pat)) =
600                 patterns[rest_index + 1..].iter().take_while(is_wild).enumerate().last()
601             {
602                 span_lint(
603                     cx,
604                     patterns[rest_index].span.shrink_to_hi().to(right_pat.span),
605                     right_index == 0,
606                 );
607             }
608         }
609     }
610 }