]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc_early.rs
rustup https://github.com/rust-lang/rust/pull/55852/
[rust.git] / clippy_lints / src / misc_early.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, LintContext, in_external_macro};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_data_structures::fx::FxHashMap;
14 use if_chain::if_chain;
15 use std::char;
16 use crate::syntax::ast::*;
17 use crate::syntax::source_map::Span;
18 use crate::syntax::visit::{FnKind, Visitor, walk_expr};
19 use crate::utils::{constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_then};
20 use crate::rustc_errors::Applicability;
21
22 /// **What it does:** Checks for structure field patterns bound to wildcards.
23 ///
24 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
25 /// the fields that are actually bound.
26 ///
27 /// **Known problems:** None.
28 ///
29 /// **Example:**
30 /// ```rust
31 /// let { a: _, b: ref b, c: _ } = ..
32 /// ```
33 declare_clippy_lint! {
34     pub UNNEEDED_FIELD_PATTERN,
35     style,
36     "struct fields bound to a wildcard instead of using `..`"
37 }
38
39 /// **What it does:** Checks for function arguments having the similar names
40 /// differing by an underscore.
41 ///
42 /// **Why is this bad?** It affects code readability.
43 ///
44 /// **Known problems:** None.
45 ///
46 /// **Example:**
47 /// ```rust
48 /// fn foo(a: i32, _a: i32) {}
49 /// ```
50 declare_clippy_lint! {
51     pub DUPLICATE_UNDERSCORE_ARGUMENT,
52     style,
53     "function arguments having names which only differ by an underscore"
54 }
55
56 /// **What it does:** Detects closures called in the same expression where they
57 /// are defined.
58 ///
59 /// **Why is this bad?** It is unnecessarily adding to the expression's
60 /// complexity.
61 ///
62 /// **Known problems:** None.
63 ///
64 /// **Example:**
65 /// ```rust
66 /// (|| 42)()
67 /// ```
68 declare_clippy_lint! {
69     pub REDUNDANT_CLOSURE_CALL,
70     complexity,
71     "throwaway closures called in the expression they are defined"
72 }
73
74 /// **What it does:** Detects expressions of the form `--x`.
75 ///
76 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
77 /// decremented.
78 ///
79 /// **Known problems:** None.
80 ///
81 /// **Example:**
82 /// ```rust
83 /// --x;
84 /// ```
85 declare_clippy_lint! {
86     pub DOUBLE_NEG,
87     style,
88     "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
89 }
90
91 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
92 /// digits.
93 ///
94 /// **Why is this bad?** It looks confusing.
95 ///
96 /// **Known problems:** None.
97 ///
98 /// **Example:**
99 /// ```rust
100 /// let y = 0x1a9BAcD;
101 /// ```
102 declare_clippy_lint! {
103     pub MIXED_CASE_HEX_LITERALS,
104     style,
105     "hex literals whose letter digits are not consistently upper- or lowercased"
106 }
107
108 /// **What it does:** Warns if literal suffixes are not separated by an
109 /// underscore.
110 ///
111 /// **Why is this bad?** It is much less readable.
112 ///
113 /// **Known problems:** None.
114 ///
115 /// **Example:**
116 /// ```rust
117 /// let y = 123832i32;
118 /// ```
119 declare_clippy_lint! {
120     pub UNSEPARATED_LITERAL_SUFFIX,
121     pedantic,
122     "literals whose suffix is not separated by an underscore"
123 }
124
125 /// **What it does:** Warns if an integral constant literal starts with `0`.
126 ///
127 /// **Why is this bad?** In some languages (including the infamous C language
128 /// and most of its
129 /// family), this marks an octal constant. In Rust however, this is a decimal
130 /// constant. This could
131 /// be confusing for both the writer and a reader of the constant.
132 ///
133 /// **Known problems:** None.
134 ///
135 /// **Example:**
136 ///
137 /// In Rust:
138 /// ```rust
139 /// fn main() {
140 ///     let a = 0123;
141 ///     println!("{}", a);
142 /// }
143 /// ```
144 ///
145 /// prints `123`, while in C:
146 ///
147 /// ```c
148 /// #include <stdio.h>
149 ///
150 /// int main() {
151 ///     int a = 0123;
152 ///     printf("%d\n", a);
153 /// }
154 /// ```
155 ///
156 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
157 declare_clippy_lint! {
158     pub ZERO_PREFIXED_LITERAL,
159     complexity,
160     "integer literals starting with `0`"
161 }
162
163 /// **What it does:** Warns if a generic shadows a built-in type.
164 ///
165 /// **Why is this bad?** This gives surprising type errors.
166 ///
167 /// **Known problems:** None.
168 ///
169 /// **Example:**
170 ///
171 /// ```rust
172 /// impl<u32> Foo<u32> {
173 ///     fn impl_func(&self) -> u32 {
174 ///         42
175 ///     }
176 /// }
177 /// ```
178 declare_clippy_lint! {
179     pub BUILTIN_TYPE_SHADOW,
180     style,
181     "shadowing a builtin type"
182 }
183
184 #[derive(Copy, Clone)]
185 pub struct MiscEarly;
186
187 impl LintPass for MiscEarly {
188     fn get_lints(&self) -> LintArray {
189         lint_array!(
190             UNNEEDED_FIELD_PATTERN,
191             DUPLICATE_UNDERSCORE_ARGUMENT,
192             REDUNDANT_CLOSURE_CALL,
193             DOUBLE_NEG,
194             MIXED_CASE_HEX_LITERALS,
195             UNSEPARATED_LITERAL_SUFFIX,
196             ZERO_PREFIXED_LITERAL,
197             BUILTIN_TYPE_SHADOW
198         )
199     }
200 }
201
202 // Used to find `return` statements or equivalents e.g. `?`
203 struct ReturnVisitor {
204     found_return: bool,
205 }
206
207 impl ReturnVisitor {
208     fn new() -> Self {
209         Self {
210             found_return: false,
211         }
212     }
213 }
214
215 impl<'ast> Visitor<'ast> for ReturnVisitor {
216     fn visit_expr(&mut self, ex: &'ast Expr) {
217         if let ExprKind::Ret(_) = ex.node {
218             self.found_return = true;
219         } else if let ExprKind::Try(_) = ex.node {
220             self.found_return = true;
221         }
222
223         walk_expr(self, ex)
224     }
225 }
226
227 impl EarlyLintPass for MiscEarly {
228     fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
229         for param in &gen.params {
230             if let GenericParamKind::Type { .. } = param.kind {
231                 let name = param.ident.as_str();
232                 if constants::BUILTIN_TYPES.contains(&&*name) {
233                     span_lint(
234                         cx,
235                         BUILTIN_TYPE_SHADOW,
236                         param.ident.span,
237                         &format!("This generic shadows the built-in type `{}`", name),
238                     );
239                 }
240             }
241         }
242     }
243
244     fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat, _: &mut bool) {
245         if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
246             let mut wilds = 0;
247             let type_name = npat.segments
248                 .last()
249                 .expect("A path must have at least one segment")
250                 .ident
251                 .name;
252
253             for field in pfields {
254                 if let PatKind::Wild = field.node.pat.node {
255                     wilds += 1;
256                 }
257             }
258             if !pfields.is_empty() && wilds == pfields.len() {
259                 span_help_and_lint(
260                     cx,
261                     UNNEEDED_FIELD_PATTERN,
262                     pat.span,
263                     "All the struct fields are matched to a wildcard pattern, consider using `..`.",
264                     &format!("Try with `{} {{ .. }}` instead", type_name),
265                 );
266                 return;
267             }
268             if wilds > 0 {
269                 let mut normal = vec![];
270
271                 for field in pfields {
272                     match field.node.pat.node {
273                         PatKind::Wild => {},
274                         _ => if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
275                             normal.push(n);
276                         },
277                     }
278                 }
279                 for field in pfields {
280                     if let PatKind::Wild = field.node.pat.node {
281                         wilds -= 1;
282                         if wilds > 0 {
283                             span_lint(
284                                 cx,
285                                 UNNEEDED_FIELD_PATTERN,
286                                 field.span,
287                                 "You matched a field with a wildcard pattern. Consider using `..` instead",
288                             );
289                         } else {
290                             span_help_and_lint(
291                                 cx,
292                                 UNNEEDED_FIELD_PATTERN,
293                                 field.span,
294                                 "You matched a field with a wildcard pattern. Consider using `..` \
295                                  instead",
296                                 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
297                             );
298                         }
299                     }
300                 }
301             }
302         }
303     }
304
305     fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
306         let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
307
308         for arg in &decl.inputs {
309             if let PatKind::Ident(_, ident, None) = arg.pat.node {
310                 let arg_name = ident.to_string();
311
312                 if arg_name.starts_with('_') {
313                     if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
314                         span_lint(
315                             cx,
316                             DUPLICATE_UNDERSCORE_ARGUMENT,
317                             *correspondence,
318                             &format!(
319                                 "`{}` already exists, having another argument having almost the same \
320                                  name makes code comprehension and documentation more difficult",
321                                 arg_name[1..].to_owned()
322                             ),
323                         );;
324                     }
325                 } else {
326                     registered_names.insert(arg_name, arg.pat.span);
327                 }
328             }
329         }
330     }
331
332     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
333         if in_external_macro(cx.sess(), expr.span) {
334             return;
335         }
336         match expr.node {
337             ExprKind::Call(ref paren, _) => if let ExprKind::Paren(ref closure) = paren.node {
338                 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
339                     let mut visitor = ReturnVisitor::new();
340                     visitor.visit_expr(block);
341                     if !visitor.found_return {
342                         span_lint_and_then(
343                             cx,
344                             REDUNDANT_CLOSURE_CALL,
345                             expr.span,
346                             "Try not to call a closure in the expression where it is declared.",
347                             |db| if decl.inputs.is_empty() {
348                                 let hint = snippet(cx, block.span, "..").into_owned();
349                                 db.span_suggestion_with_applicability(
350                                     expr.span,
351                                     "Try doing something like: ",
352                                     hint,
353                                     Applicability::MachineApplicable, // snippet
354                                 );
355                             },
356                         );
357                     }
358                 }
359             },
360             ExprKind::Unary(UnOp::Neg, ref inner) => if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
361                 span_lint(
362                     cx,
363                     DOUBLE_NEG,
364                     expr.span,
365                     "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
366                 );
367             },
368             ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
369             _ => (),
370         }
371     }
372
373     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
374         for w in block.stmts.windows(2) {
375             if_chain! {
376                 if let StmtKind::Local(ref local) = w[0].node;
377                 if let Option::Some(ref t) = local.init;
378                 if let ExprKind::Closure(..) = t.node;
379                 if let PatKind::Ident(_, ident, _) = local.pat.node;
380                 if let StmtKind::Semi(ref second) = w[1].node;
381                 if let ExprKind::Assign(_, ref call) = second.node;
382                 if let ExprKind::Call(ref closure, _) = call.node;
383                 if let ExprKind::Path(_, ref path) = closure.node;
384                 then {
385                     if ident == path.segments[0].ident {
386                         span_lint(
387                             cx,
388                             REDUNDANT_CLOSURE_CALL,
389                             second.span,
390                             "Closure called just once immediately after it was declared",
391                         );
392                     }
393                 }
394             }
395         }
396     }
397 }
398
399 impl MiscEarly {
400     fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
401         if_chain! {
402             if let LitKind::Int(value, ..) = lit.node;
403             if let Some(src) = snippet_opt(cx, lit.span);
404             if let Some(firstch) = src.chars().next();
405             if char::to_digit(firstch, 10).is_some();
406             then {
407                 let mut prev = '\0';
408                 for ch in src.chars() {
409                     if ch == 'i' || ch == 'u' {
410                         if prev != '_' {
411                             span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
412                                         "integer type suffix should be separated by an underscore");
413                         }
414                         break;
415                     }
416                     prev = ch;
417                 }
418                 if src.starts_with("0x") {
419                     let mut seen = (false, false);
420                     for ch in src.chars() {
421                         match ch {
422                             'a' ..= 'f' => seen.0 = true,
423                             'A' ..= 'F' => seen.1 = true,
424                             'i' | 'u'   => break,   // start of suffix already
425                             _ => ()
426                         }
427                     }
428                     if seen.0 && seen.1 {
429                         span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
430                                     "inconsistent casing in hexadecimal literal");
431                     }
432                 } else if src.starts_with("0b") || src.starts_with("0o") {
433                     /* nothing to do */
434                 } else if value != 0 && src.starts_with('0') {
435                     span_lint_and_then(cx,
436                                         ZERO_PREFIXED_LITERAL,
437                                         lit.span,
438                                         "this is a decimal constant",
439                                         |db| {
440                         db.span_suggestion_with_applicability(
441                             lit.span,
442                             "if you mean to use a decimal constant, remove the `0` to remove confusion",
443                             src.trim_left_matches(|c| c == '_' || c == '0').to_string(),
444                             Applicability::MaybeIncorrect,
445                         );
446                         db.span_suggestion_with_applicability(
447                             lit.span,
448                             "if you mean to use an octal constant, use `0o`",
449                             format!("0o{}", src.trim_left_matches(|c| c == '_' || c == '0')),
450                             Applicability::MaybeIncorrect,
451                         );
452                     });
453                 }
454             }
455         }
456         if_chain! {
457             if let LitKind::Float(..) = lit.node;
458             if let Some(src) = snippet_opt(cx, lit.span);
459             if let Some(firstch) = src.chars().next();
460             if char::to_digit(firstch, 10).is_some();
461             then {
462                 let mut prev = '\0';
463                 for ch in src.chars() {
464                     if ch == 'f' {
465                         if prev != '_' {
466                             span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
467                                         "float type suffix should be separated by an underscore");
468                         }
469                         break;
470                     }
471                     prev = ch;
472                 }
473             }
474         }
475     }
476 }