2 constants, snippet, snippet_opt, span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then,
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;
10 use syntax::source_map::Span;
11 use syntax::visit::{walk_expr, FnKind, Visitor};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for structure field patterns bound to wildcards.
16 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
17 /// the fields that are actually bound.
19 /// **Known problems:** None.
23 /// let { a: _, b: ref b, c: _ } = ..
25 pub UNNEEDED_FIELD_PATTERN,
27 "struct fields bound to a wildcard instead of using `..`"
30 declare_clippy_lint! {
31 /// **What it does:** Checks for function arguments having the similar names
32 /// differing by an underscore.
34 /// **Why is this bad?** It affects code readability.
36 /// **Known problems:** None.
40 /// fn foo(a: i32, _a: i32) {}
42 pub DUPLICATE_UNDERSCORE_ARGUMENT,
44 "function arguments having names which only differ by an underscore"
47 declare_clippy_lint! {
48 /// **What it does:** Detects closures called in the same expression where they
51 /// **Why is this bad?** It is unnecessarily adding to the expression's
54 /// **Known problems:** None.
60 pub REDUNDANT_CLOSURE_CALL,
62 "throwaway closures called in the expression they are defined"
65 declare_clippy_lint! {
66 /// **What it does:** Detects expressions of the form `--x`.
68 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
71 /// **Known problems:** None.
80 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
83 declare_clippy_lint! {
84 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
87 /// **Why is this bad?** It looks confusing.
89 /// **Known problems:** None.
93 /// let y = 0x1a9BAcD;
95 pub MIXED_CASE_HEX_LITERALS,
97 "hex literals whose letter digits are not consistently upper- or lowercased"
100 declare_clippy_lint! {
101 /// **What it does:** Warns if literal suffixes are not separated by an
104 /// **Why is this bad?** It is much less readable.
106 /// **Known problems:** None.
110 /// let y = 123832i32;
112 pub UNSEPARATED_LITERAL_SUFFIX,
114 "literals whose suffix is not separated by an underscore"
117 declare_clippy_lint! {
118 /// **What it does:** Warns if an integral constant literal starts with `0`.
120 /// **Why is this bad?** In some languages (including the infamous C language
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.
126 /// **Known problems:** None.
134 /// println!("{}", a);
138 /// prints `123`, while in C:
141 /// #include <stdio.h>
145 /// printf("%d\n", a);
149 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
150 pub ZERO_PREFIXED_LITERAL,
152 "integer literals starting with `0`"
155 declare_clippy_lint! {
156 /// **What it does:** Warns if a generic shadows a built-in type.
158 /// **Why is this bad?** This gives surprising type errors.
160 /// **Known problems:** None.
165 /// impl<u32> Foo<u32> {
166 /// fn impl_func(&self) -> u32 {
171 pub BUILTIN_TYPE_SHADOW,
173 "shadowing a builtin type"
176 declare_clippy_lint! {
177 /// **What it does:** Checks for patterns in the form `name @ _`.
179 /// **Why is this bad?** It's almost always more readable to just use direct
182 /// **Known problems:** None.
186 /// # let v = Some("abc");
190 /// y @ _ => (), // easier written as `y`,
193 pub REDUNDANT_PATTERN,
195 "using `name @ _` in a pattern"
198 declare_clippy_lint! {
199 /// **What it does:** Checks for tuple patterns with a wildcard
200 /// pattern (`_`) is next to a rest pattern (`..`).
202 /// _NOTE_: While `_, ..` means there is at least one element left, `..`
203 /// means there are 0 or more elements left. This can make a difference
204 /// when refactoring, but shouldn't result in errors in the refactored code,
205 /// since the wildcard pattern isn't used anyway.
206 /// **Why is this bad?** The wildcard pattern is unneeded as the rest pattern
207 /// can match that element as well.
209 /// **Known problems:** None.
213 /// # struct TupleStruct(u32, u32, u32);
214 /// # let t = TupleStruct(1, 2, 3);
217 /// TupleStruct(0, .., _) => (),
221 /// can be written as
223 /// # struct TupleStruct(u32, u32, u32);
224 /// # let t = TupleStruct(1, 2, 3);
227 /// TupleStruct(0, ..) => (),
231 pub UNNEEDED_WILDCARD_PATTERN,
233 "tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`)"
236 declare_lint_pass!(MiscEarlyLints => [
237 UNNEEDED_FIELD_PATTERN,
238 DUPLICATE_UNDERSCORE_ARGUMENT,
239 REDUNDANT_CLOSURE_CALL,
241 MIXED_CASE_HEX_LITERALS,
242 UNSEPARATED_LITERAL_SUFFIX,
243 ZERO_PREFIXED_LITERAL,
246 UNNEEDED_WILDCARD_PATTERN,
249 // Used to find `return` statements or equivalents e.g., `?`
250 struct ReturnVisitor {
256 Self { found_return: false }
260 impl<'ast> Visitor<'ast> for ReturnVisitor {
261 fn visit_expr(&mut self, ex: &'ast Expr) {
262 if let ExprKind::Ret(_) = ex.node {
263 self.found_return = true;
264 } else if let ExprKind::Try(_) = ex.node {
265 self.found_return = true;
272 impl EarlyLintPass for MiscEarlyLints {
273 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
274 for param in &gen.params {
275 if let GenericParamKind::Type { .. } = param.kind {
276 let name = param.ident.as_str();
277 if constants::BUILTIN_TYPES.contains(&&*name) {
282 &format!("This generic shadows the built-in type `{}`", name),
289 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
290 if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
295 .expect("A path must have at least one segment")
299 for field in pfields {
300 if let PatKind::Wild = field.pat.node {
304 if !pfields.is_empty() && wilds == pfields.len() {
307 UNNEEDED_FIELD_PATTERN,
309 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
310 &format!("Try with `{} {{ .. }}` instead", type_name),
315 let mut normal = vec![];
317 for field in pfields {
318 match field.pat.node {
321 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
327 for field in pfields {
328 if let PatKind::Wild = field.pat.node {
333 UNNEEDED_FIELD_PATTERN,
335 "You matched a field with a wildcard pattern. Consider using `..` instead",
340 UNNEEDED_FIELD_PATTERN,
342 "You matched a field with a wildcard pattern. Consider using `..` \
344 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
352 if let PatKind::Ident(_, ident, Some(ref right)) = pat.node {
353 if let PatKind::Wild = right.node {
359 "the `{} @ _` pattern can be written as just `{}`",
360 ident.name, ident.name,
363 format!("{}", ident.name),
364 Applicability::MachineApplicable,
369 check_unneeded_wildcard_pattern(cx, pat);
372 fn check_fn(&mut self, cx: &EarlyContext<'_>, _: FnKind<'_>, decl: &FnDecl, _: Span, _: NodeId) {
373 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
375 for arg in &decl.inputs {
376 if let PatKind::Ident(_, ident, None) = arg.pat.node {
377 let arg_name = ident.to_string();
379 if arg_name.starts_with('_') {
380 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
383 DUPLICATE_UNDERSCORE_ARGUMENT,
386 "`{}` already exists, having another argument having almost the same \
387 name makes code comprehension and documentation more difficult",
388 arg_name[1..].to_owned()
393 registered_names.insert(arg_name, arg.pat.span);
399 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
400 if in_external_macro(cx.sess(), expr.span) {
404 ExprKind::Call(ref paren, _) => {
405 if let ExprKind::Paren(ref closure) = paren.node {
406 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.node {
407 let mut visitor = ReturnVisitor::new();
408 visitor.visit_expr(block);
409 if !visitor.found_return {
412 REDUNDANT_CLOSURE_CALL,
414 "Try not to call a closure in the expression where it is declared.",
416 if decl.inputs.is_empty() {
417 let hint = snippet(cx, block.span, "..").into_owned();
420 "Try doing something like: ",
422 Applicability::MachineApplicable, // snippet
431 ExprKind::Unary(UnOp::Neg, ref inner) => {
432 if let ExprKind::Unary(UnOp::Neg, _) = inner.node {
437 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
441 ExprKind::Lit(ref lit) => self.check_lit(cx, lit),
446 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
447 for w in block.stmts.windows(2) {
449 if let StmtKind::Local(ref local) = w[0].node;
450 if let Option::Some(ref t) = local.init;
451 if let ExprKind::Closure(..) = t.node;
452 if let PatKind::Ident(_, ident, _) = local.pat.node;
453 if let StmtKind::Semi(ref second) = w[1].node;
454 if let ExprKind::Assign(_, ref call) = second.node;
455 if let ExprKind::Call(ref closure, _) = call.node;
456 if let ExprKind::Path(_, ref path) = closure.node;
458 if ident == path.segments[0].ident {
461 REDUNDANT_CLOSURE_CALL,
463 "Closure called just once immediately after it was declared",
472 impl MiscEarlyLints {
473 fn check_lit(self, cx: &EarlyContext<'_>, lit: &Lit) {
474 // We test if first character in snippet is a number, because the snippet could be an expansion
475 // from a built-in macro like `line!()` or a proc-macro like `#[wasm_bindgen]`.
476 // Note that this check also covers special case that `line!()` is eagerly expanded by compiler.
477 // See <https://github.com/rust-lang/rust-clippy/issues/4507> for a regression.
478 // FIXME: Find a better way to detect those cases.
479 let lit_snip = match snippet_opt(cx, lit.span) {
480 Some(snip) if snip.chars().next().map_or(false, |c| c.is_digit(10)) => snip,
484 if let LitKind::Int(value, lit_int_type) = lit.node {
485 let suffix = match lit_int_type {
486 LitIntType::Signed(ty) => ty.ty_to_string(),
487 LitIntType::Unsigned(ty) => ty.ty_to_string(),
488 LitIntType::Unsuffixed => "",
491 let maybe_last_sep_idx = lit_snip.len() - suffix.len() - 1;
492 // Do not lint when literal is unsuffixed.
493 if !suffix.is_empty() && lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
496 UNSEPARATED_LITERAL_SUFFIX,
498 "integer type suffix should be separated by an underscore",
500 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
501 Applicability::MachineApplicable,
505 if lit_snip.starts_with("0x") {
506 let mut seen = (false, false);
507 for ch in lit_snip.as_bytes()[2..=maybe_last_sep_idx].iter() {
509 b'a'..=b'f' => seen.0 = true,
510 b'A'..=b'F' => seen.1 = true,
513 if seen.0 && seen.1 {
516 MIXED_CASE_HEX_LITERALS,
518 "inconsistent casing in hexadecimal literal",
523 } else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
525 } else if value != 0 && lit_snip.starts_with('0') {
528 ZERO_PREFIXED_LITERAL,
530 "this is a decimal constant",
534 "if you mean to use a decimal constant, remove the `0` to avoid confusion",
535 lit_snip.trim_start_matches(|c| c == '_' || c == '0').to_string(),
536 Applicability::MaybeIncorrect,
540 "if you mean to use an octal constant, use `0o`",
541 format!("0o{}", lit_snip.trim_start_matches(|c| c == '_' || c == '0')),
542 Applicability::MaybeIncorrect,
547 } else if let LitKind::Float(_, float_ty) = lit.node {
548 let suffix = float_ty.ty_to_string();
549 let maybe_last_sep_idx = lit_snip.len() - suffix.len() - 1;
550 if lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
553 UNSEPARATED_LITERAL_SUFFIX,
555 "float type suffix should be separated by an underscore",
557 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
558 Applicability::MachineApplicable,
565 fn check_unneeded_wildcard_pattern(cx: &EarlyContext<'_>, pat: &Pat) {
566 if let PatKind::TupleStruct(_, ref patterns) | PatKind::Tuple(ref patterns) = pat.node {
567 fn span_lint(cx: &EarlyContext<'_>, span: Span, only_one: bool) {
570 UNNEEDED_WILDCARD_PATTERN,
573 "this pattern is unneeded as the `..` pattern can match that element"
575 "these patterns are unneeded as the `..` pattern can match those elements"
577 if only_one { "remove it" } else { "remove them" },
579 Applicability::MachineApplicable,
583 #[allow(clippy::trivially_copy_pass_by_ref)]
584 fn is_wild<P: std::ops::Deref<Target = Pat>>(pat: &&P) -> bool {
585 if let PatKind::Wild = pat.node {
592 if let Some(rest_index) = patterns.iter().position(|pat| pat.is_rest()) {
593 if let Some((left_index, left_pat)) = patterns[..rest_index]
600 span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0);
603 if let Some((right_index, right_pat)) =
604 patterns[rest_index + 1..].iter().take_while(is_wild).enumerate().last()
608 patterns[rest_index].span.shrink_to_hi().to(right_pat.span),