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