]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc_early.rs
Auto merge of #4445 - phansch:fix_unused_unit_sugg, r=flip1995
[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_lint_pass!(MiscEarlyLints => [
177     UNNEEDED_FIELD_PATTERN,
178     DUPLICATE_UNDERSCORE_ARGUMENT,
179     REDUNDANT_CLOSURE_CALL,
180     DOUBLE_NEG,
181     MIXED_CASE_HEX_LITERALS,
182     UNSEPARATED_LITERAL_SUFFIX,
183     ZERO_PREFIXED_LITERAL,
184     BUILTIN_TYPE_SHADOW
185 ]);
186
187 // Used to find `return` statements or equivalents e.g., `?`
188 struct ReturnVisitor {
189     found_return: bool,
190 }
191
192 impl ReturnVisitor {
193     fn new() -> Self {
194         Self { found_return: false }
195     }
196 }
197
198 impl<'ast> Visitor<'ast> for ReturnVisitor {
199     fn visit_expr(&mut self, ex: &'ast Expr) {
200         if let ExprKind::Ret(_) = ex.node {
201             self.found_return = true;
202         } else if let ExprKind::Try(_) = ex.node {
203             self.found_return = true;
204         }
205
206         walk_expr(self, ex)
207     }
208 }
209
210 impl EarlyLintPass for MiscEarlyLints {
211     fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
212         for param in &gen.params {
213             if let GenericParamKind::Type { .. } = param.kind {
214                 let name = param.ident.as_str();
215                 if constants::BUILTIN_TYPES.contains(&&*name) {
216                     span_lint(
217                         cx,
218                         BUILTIN_TYPE_SHADOW,
219                         param.ident.span,
220                         &format!("This generic shadows the built-in type `{}`", name),
221                     );
222                 }
223             }
224         }
225     }
226
227     fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
228         if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
229             let mut wilds = 0;
230             let type_name = npat
231                 .segments
232                 .last()
233                 .expect("A path must have at least one segment")
234                 .ident
235                 .name;
236
237             for field in pfields {
238                 if let PatKind::Wild = field.pat.node {
239                     wilds += 1;
240                 }
241             }
242             if !pfields.is_empty() && wilds == pfields.len() {
243                 span_help_and_lint(
244                     cx,
245                     UNNEEDED_FIELD_PATTERN,
246                     pat.span,
247                     "All the struct fields are matched to a wildcard pattern, consider using `..`.",
248                     &format!("Try with `{} {{ .. }}` instead", type_name),
249                 );
250                 return;
251             }
252             if wilds > 0 {
253                 let mut normal = vec![];
254
255                 for field in pfields {
256                     match field.pat.node {
257                         PatKind::Wild => {},
258                         _ => {
259                             if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
260                                 normal.push(n);
261                             }
262                         },
263                     }
264                 }
265                 for field in pfields {
266                     if let PatKind::Wild = field.pat.node {
267                         wilds -= 1;
268                         if wilds > 0 {
269                             span_lint(
270                                 cx,
271                                 UNNEEDED_FIELD_PATTERN,
272                                 field.span,
273                                 "You matched a field with a wildcard pattern. Consider using `..` instead",
274                             );
275                         } else {
276                             span_help_and_lint(
277                                 cx,
278                                 UNNEEDED_FIELD_PATTERN,
279                                 field.span,
280                                 "You matched a field with a wildcard pattern. Consider using `..` \
281                                  instead",
282                                 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
283                             );
284                         }
285                     }
286                 }
287             }
288         }
289     }
290
291     fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
292         let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
293
294         for arg in &decl.inputs {
295             if let PatKind::Ident(_, ident, None) = arg.pat.node {
296                 let arg_name = ident.to_string();
297
298                 if arg_name.starts_with('_') {
299                     if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
300                         span_lint(
301                             cx,
302                             DUPLICATE_UNDERSCORE_ARGUMENT,
303                             *correspondence,
304                             &format!(
305                                 "`{}` already exists, having another argument having almost the same \
306                                  name makes code comprehension and documentation more difficult",
307                                 arg_name[1..].to_owned()
308                             ),
309                         );
310                     }
311                 } else {
312                     registered_names.insert(arg_name, arg.pat.span);
313                 }
314             }
315         }
316     }
317
318     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
319         if in_external_macro(cx.sess(), expr.span) {
320             return;
321         }
322         match expr.node {
323             ExprKind::Call(ref paren, _) => {
324                 if let ExprKind::Paren(ref closure) = paren.node {
325                     if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
326                         let mut visitor = ReturnVisitor::new();
327                         visitor.visit_expr(block);
328                         if !visitor.found_return {
329                             span_lint_and_then(
330                                 cx,
331                                 REDUNDANT_CLOSURE_CALL,
332                                 expr.span,
333                                 "Try not to call a closure in the expression where it is declared.",
334                                 |db| {
335                                     if decl.inputs.is_empty() {
336                                         let hint = snippet(cx, block.span, "..").into_owned();
337                                         db.span_suggestion(
338                                             expr.span,
339                                             "Try doing something like: ",
340                                             hint,
341                                             Applicability::MachineApplicable, // snippet
342                                         );
343                                     }
344                                 },
345                             );
346                         }
347                     }
348                 }
349             },
350             ExprKind::Unary(UnOp::Neg, ref inner) => {
351                 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
352                     span_lint(
353                         cx,
354                         DOUBLE_NEG,
355                         expr.span,
356                         "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
357                     );
358                 }
359             },
360             ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
361             _ => (),
362         }
363     }
364
365     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
366         for w in block.stmts.windows(2) {
367             if_chain! {
368                 if let StmtKind::Local(ref local) = w[0].node;
369                 if let Option::Some(ref t) = local.init;
370                 if let ExprKind::Closure(..) = t.node;
371                 if let PatKind::Ident(_, ident, _) = local.pat.node;
372                 if let StmtKind::Semi(ref second) = w[1].node;
373                 if let ExprKind::Assign(_, ref call) = second.node;
374                 if let ExprKind::Call(ref closure, _) = call.node;
375                 if let ExprKind::Path(_, ref path) = closure.node;
376                 then {
377                     if ident == path.segments[0].ident {
378                         span_lint(
379                             cx,
380                             REDUNDANT_CLOSURE_CALL,
381                             second.span,
382                             "Closure called just once immediately after it was declared",
383                         );
384                     }
385                 }
386             }
387         }
388     }
389 }
390
391 impl MiscEarlyLints {
392     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
393         // The `line!()` macro is compiler built-in and a special case for these lints.
394         let lit_snip = match snippet_opt(cx, lit.span) {
395             Some(snip) => {
396                 if snip.contains('!') {
397                     return;
398                 }
399                 snip
400             },
401             _ => return,
402         };
403
404         if let LitKind::Int(value, lit_int_type) = lit.node {
405             let suffix = match lit_int_type {
406                 LitIntType::Signed(ty) => ty.ty_to_string(),
407                 LitIntType::Unsigned(ty) => ty.ty_to_string(),
408                 LitIntType::Unsuffixed => "",
409             };
410
411             let maybe_last_sep_idx = lit_snip.len() - suffix.len() - 1;
412             // Do not lint when literal is unsuffixed.
413             if !suffix.is_empty() && lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
414                 span_lint_and_sugg(
415                     cx,
416                     UNSEPARATED_LITERAL_SUFFIX,
417                     lit.span,
418                     "integer type suffix should be separated by an underscore",
419                     "add an underscore",
420                     format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
421                     Applicability::MachineApplicable,
422                 );
423             }
424
425             if lit_snip.starts_with("0x") {
426                 let mut seen = (false, false);
427                 for ch in lit_snip.as_bytes()[2..=maybe_last_sep_idx].iter() {
428                     match ch {
429                         b'a'..=b'f' => seen.0 = true,
430                         b'A'..=b'F' => seen.1 = true,
431                         _ => {},
432                     }
433                     if seen.0 && seen.1 {
434                         span_lint(
435                             cx,
436                             MIXED_CASE_HEX_LITERALS,
437                             lit.span,
438                             "inconsistent casing in hexadecimal literal",
439                         );
440                         break;
441                     }
442                 }
443             } else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
444                 /* nothing to do */
445             } else if value != 0 && lit_snip.starts_with('0') {
446                 span_lint_and_then(
447                     cx,
448                     ZERO_PREFIXED_LITERAL,
449                     lit.span,
450                     "this is a decimal constant",
451                     |db| {
452                         db.span_suggestion(
453                             lit.span,
454                             "if you mean to use a decimal constant, remove the `0` to avoid confusion",
455                             lit_snip.trim_start_matches(|c| c == '_' || c == '0').to_string(),
456                             Applicability::MaybeIncorrect,
457                         );
458                         db.span_suggestion(
459                             lit.span,
460                             "if you mean to use an octal constant, use `0o`",
461                             format!("0o{}", lit_snip.trim_start_matches(|c| c == '_' || c == '0')),
462                             Applicability::MaybeIncorrect,
463                         );
464                     },
465                 );
466             }
467         } else if let LitKind::Float(_, float_ty) = lit.node {
468             let suffix = float_ty.ty_to_string();
469             let maybe_last_sep_idx = lit_snip.len() - suffix.len() - 1;
470             if lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
471                 span_lint_and_sugg(
472                     cx,
473                     UNSEPARATED_LITERAL_SUFFIX,
474                     lit.span,
475                     "float type suffix should be separated by an underscore",
476                     "add an underscore",
477                     format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
478                     Applicability::MachineApplicable,
479                 );
480             }
481         }
482     }
483 }