1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
10 use crate::rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::rustc_data_structures::fx::FxHashMap;
13 use crate::rustc_errors::Applicability;
14 use crate::syntax::ast::*;
15 use crate::syntax::source_map::Span;
16 use crate::syntax::visit::{walk_expr, FnKind, Visitor};
17 use crate::utils::{constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_then};
18 use if_chain::if_chain;
21 /// **What it does:** Checks for structure field patterns bound to wildcards.
23 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
24 /// the fields that are actually bound.
26 /// **Known problems:** None.
30 /// let { a: _, b: ref b, c: _ } = ..
32 declare_clippy_lint! {
33 pub UNNEEDED_FIELD_PATTERN,
35 "struct fields bound to a wildcard instead of using `..`"
38 /// **What it does:** Checks for function arguments having the similar names
39 /// differing by an underscore.
41 /// **Why is this bad?** It affects code readability.
43 /// **Known problems:** None.
47 /// fn foo(a: i32, _a: i32) {}
49 declare_clippy_lint! {
50 pub DUPLICATE_UNDERSCORE_ARGUMENT,
52 "function arguments having names which only differ by an underscore"
55 /// **What it does:** Detects closures called in the same expression where they
58 /// **Why is this bad?** It is unnecessarily adding to the expression's
61 /// **Known problems:** None.
67 declare_clippy_lint! {
68 pub REDUNDANT_CLOSURE_CALL,
70 "throwaway closures called in the expression they are defined"
73 /// **What it does:** Detects expressions of the form `--x`.
75 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
78 /// **Known problems:** None.
84 declare_clippy_lint! {
87 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
90 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
93 /// **Why is this bad?** It looks confusing.
95 /// **Known problems:** None.
99 /// let y = 0x1a9BAcD;
101 declare_clippy_lint! {
102 pub MIXED_CASE_HEX_LITERALS,
104 "hex literals whose letter digits are not consistently upper- or lowercased"
107 /// **What it does:** Warns if literal suffixes are not separated by an
110 /// **Why is this bad?** It is much less readable.
112 /// **Known problems:** None.
116 /// let y = 123832i32;
118 declare_clippy_lint! {
119 pub UNSEPARATED_LITERAL_SUFFIX,
121 "literals whose suffix is not separated by an underscore"
124 /// **What it does:** Warns if an integral constant literal starts with `0`.
126 /// **Why is this bad?** In some languages (including the infamous C language
128 /// family), this marks an octal constant. In Rust however, this is a decimal
129 /// constant. This could
130 /// be confusing for both the writer and a reader of the constant.
132 /// **Known problems:** None.
140 /// println!("{}", a);
144 /// prints `123`, while in C:
147 /// #include <stdio.h>
151 /// printf("%d\n", a);
155 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
156 declare_clippy_lint! {
157 pub ZERO_PREFIXED_LITERAL,
159 "integer literals starting with `0`"
162 /// **What it does:** Warns if a generic shadows a built-in type.
164 /// **Why is this bad?** This gives surprising type errors.
166 /// **Known problems:** None.
171 /// impl<u32> Foo<u32> {
172 /// fn impl_func(&self) -> u32 {
177 declare_clippy_lint! {
178 pub BUILTIN_TYPE_SHADOW,
180 "shadowing a builtin type"
183 #[derive(Copy, Clone)]
184 pub struct MiscEarly;
186 impl LintPass for MiscEarly {
187 fn get_lints(&self) -> LintArray {
189 UNNEEDED_FIELD_PATTERN,
190 DUPLICATE_UNDERSCORE_ARGUMENT,
191 REDUNDANT_CLOSURE_CALL,
193 MIXED_CASE_HEX_LITERALS,
194 UNSEPARATED_LITERAL_SUFFIX,
195 ZERO_PREFIXED_LITERAL,
201 // Used to find `return` statements or equivalents e.g. `?`
202 struct ReturnVisitor {
208 Self { found_return: false }
212 impl<'ast> Visitor<'ast> for ReturnVisitor {
213 fn visit_expr(&mut self, ex: &'ast Expr) {
214 if let ExprKind::Ret(_) = ex.node {
215 self.found_return = true;
216 } else if let ExprKind::Try(_) = ex.node {
217 self.found_return = true;
224 impl EarlyLintPass for MiscEarly {
225 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
226 for param in &gen.params {
227 if let GenericParamKind::Type { .. } = param.kind {
228 let name = param.ident.as_str();
229 if constants::BUILTIN_TYPES.contains(&&*name) {
234 &format!("This generic shadows the built-in type `{}`", name),
241 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat, _: &mut bool) {
242 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
247 .expect("A path must have at least one segment")
251 for field in pfields {
252 if let PatKind::Wild = field.node.pat.node {
256 if !pfields.is_empty() && wilds == pfields.len() {
259 UNNEEDED_FIELD_PATTERN,
261 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
262 &format!("Try with `{} {{ .. }}` instead", type_name),
267 let mut normal = vec![];
269 for field in pfields {
270 match field.node.pat.node {
273 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
279 for field in pfields {
280 if let PatKind::Wild = field.node.pat.node {
285 UNNEEDED_FIELD_PATTERN,
287 "You matched a field with a wildcard pattern. Consider using `..` instead",
292 UNNEEDED_FIELD_PATTERN,
294 "You matched a field with a wildcard pattern. Consider using `..` \
296 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
305 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
306 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
308 for arg in &decl.inputs {
309 if let PatKind::Ident(_, ident, None) = arg.pat.node {
310 let arg_name = ident.to_string();
312 if arg_name.starts_with('_') {
313 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
316 DUPLICATE_UNDERSCORE_ARGUMENT,
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()
326 registered_names.insert(arg_name, arg.pat.span);
332 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
333 if in_external_macro(cx.sess(), expr.span) {
337 ExprKind::Call(ref paren, _) => {
338 if let ExprKind::Paren(ref closure) = paren.node {
339 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
340 let mut visitor = ReturnVisitor::new();
341 visitor.visit_expr(block);
342 if !visitor.found_return {
345 REDUNDANT_CLOSURE_CALL,
347 "Try not to call a closure in the expression where it is declared.",
349 if decl.inputs.is_empty() {
350 let hint = snippet(cx, block.span, "..").into_owned();
351 db.span_suggestion_with_applicability(
353 "Try doing something like: ",
355 Applicability::MachineApplicable, // snippet
364 ExprKind::Unary(UnOp::Neg, ref inner) => {
365 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
370 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
374 ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
379 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
380 for w in block.stmts.windows(2) {
382 if let StmtKind::Local(ref local) = w[0].node;
383 if let Option::Some(ref t) = local.init;
384 if let ExprKind::Closure(..) = t.node;
385 if let PatKind::Ident(_, ident, _) = local.pat.node;
386 if let StmtKind::Semi(ref second) = w[1].node;
387 if let ExprKind::Assign(_, ref call) = second.node;
388 if let ExprKind::Call(ref closure, _) = call.node;
389 if let ExprKind::Path(_, ref path) = closure.node;
391 if ident == path.segments[0].ident {
394 REDUNDANT_CLOSURE_CALL,
396 "Closure called just once immediately after it was declared",
406 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
408 if let LitKind::Int(value, ..) = lit.node;
409 if let Some(src) = snippet_opt(cx, lit.span);
410 if let Some(firstch) = src.chars().next();
411 if char::to_digit(firstch, 10).is_some();
414 for ch in src.chars() {
415 if ch == 'i' || ch == 'u' {
417 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
418 "integer type suffix should be separated by an underscore");
424 if src.starts_with("0x") {
425 let mut seen = (false, false);
426 for ch in src.chars() {
428 'a' ..= 'f' => seen.0 = true,
429 'A' ..= 'F' => seen.1 = true,
430 'i' | 'u' => break, // start of suffix already
434 if seen.0 && seen.1 {
435 span_lint(cx, MIXED_CASE_HEX_LITERALS, lit.span,
436 "inconsistent casing in hexadecimal literal");
438 } else if src.starts_with("0b") || src.starts_with("0o") {
440 } else if value != 0 && src.starts_with('0') {
441 span_lint_and_then(cx,
442 ZERO_PREFIXED_LITERAL,
444 "this is a decimal constant",
446 db.span_suggestion_with_applicability(
448 "if you mean to use a decimal constant, remove the `0` to remove confusion",
449 src.trim_left_matches(|c| c == '_' || c == '0').to_string(),
450 Applicability::MaybeIncorrect,
452 db.span_suggestion_with_applicability(
454 "if you mean to use an octal constant, use `0o`",
455 format!("0o{}", src.trim_left_matches(|c| c == '_' || c == '0')),
456 Applicability::MaybeIncorrect,
463 if let LitKind::Float(..) = lit.node;
464 if let Some(src) = snippet_opt(cx, lit.span);
465 if let Some(firstch) = src.chars().next();
466 if char::to_digit(firstch, 10).is_some();
469 for ch in src.chars() {
472 span_lint(cx, UNSEPARATED_LITERAL_SUFFIX, lit.span,
473 "float type suffix should be separated by an underscore");