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