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