2 constants, snippet_opt, snippet_with_applicability, span_lint, span_lint_and_help, span_lint_and_sugg,
5 use if_chain::if_chain;
7 BindingMode, Block, Expr, ExprKind, GenericParamKind, Generics, Lit, LitFloatType, LitIntType, LitKind, Mutability,
8 NodeId, Pat, PatKind, StmtKind, UnOp,
10 use rustc_ast::visit::{walk_expr, FnKind, Visitor};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_errors::Applicability;
13 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
14 use rustc_middle::lint::in_external_macro;
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::source_map::Span;
18 declare_clippy_lint! {
19 /// **What it does:** Checks for structure field patterns bound to wildcards.
21 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
22 /// the fields that are actually bound.
24 /// **Known problems:** None.
33 /// let f = Foo { a: 0, b: 0, c: 0 };
37 /// Foo { a: _, b: 0, .. } => {},
38 /// Foo { a: _, b: _, c: _ } => {},
43 /// Foo { b: 0, .. } => {},
47 pub UNNEEDED_FIELD_PATTERN,
49 "struct fields bound to a wildcard instead of using `..`"
52 declare_clippy_lint! {
53 /// **What it does:** Checks for function arguments having the similar names
54 /// differing by an underscore.
56 /// **Why is this bad?** It affects code readability.
58 /// **Known problems:** None.
63 /// fn foo(a: i32, _a: i32) {}
66 /// fn bar(a: i32, _b: i32) {}
68 pub DUPLICATE_UNDERSCORE_ARGUMENT,
70 "function arguments having names which only differ by an underscore"
73 declare_clippy_lint! {
74 /// **What it does:** Detects closures called in the same expression where they
77 /// **Why is this bad?** It is unnecessarily adding to the expression's
80 /// **Known problems:** None.
90 pub REDUNDANT_CLOSURE_CALL,
92 "throwaway closures called in the expression they are defined"
95 declare_clippy_lint! {
96 /// **What it does:** Detects expressions of the form `--x`.
98 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
101 /// **Known problems:** None.
110 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
113 declare_clippy_lint! {
114 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
117 /// **Why is this bad?** It looks confusing.
119 /// **Known problems:** None.
124 /// let y = 0x1a9BAcD;
127 /// let y = 0x1A9BACD;
129 pub MIXED_CASE_HEX_LITERALS,
131 "hex literals whose letter digits are not consistently upper- or lowercased"
134 declare_clippy_lint! {
135 /// **What it does:** Warns if literal suffixes are not separated by an
138 /// **Why is this bad?** It is much less readable.
140 /// **Known problems:** None.
145 /// let y = 123832i32;
148 /// let y = 123832_i32;
150 pub UNSEPARATED_LITERAL_SUFFIX,
152 "literals whose suffix is not separated by an underscore"
155 declare_clippy_lint! {
156 /// **What it does:** Warns if an integral constant literal starts with `0`.
158 /// **Why is this bad?** In some languages (including the infamous C language
160 /// family), this marks an octal constant. In Rust however, this is a decimal
161 /// constant. This could
162 /// be confusing for both the writer and a reader of the constant.
164 /// **Known problems:** None.
172 /// println!("{}", a);
176 /// prints `123`, while in C:
179 /// #include <stdio.h>
183 /// printf("%d\n", a);
187 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
188 pub ZERO_PREFIXED_LITERAL,
190 "integer literals starting with `0`"
193 declare_clippy_lint! {
194 /// **What it does:** Warns if a generic shadows a built-in type.
196 /// **Why is this bad?** This gives surprising type errors.
198 /// **Known problems:** None.
203 /// impl<u32> Foo<u32> {
204 /// fn impl_func(&self) -> u32 {
209 pub BUILTIN_TYPE_SHADOW,
211 "shadowing a builtin type"
214 declare_clippy_lint! {
215 /// **What it does:** Checks for patterns in the form `name @ _`.
217 /// **Why is this bad?** It's almost always more readable to just use direct
220 /// **Known problems:** None.
224 /// # let v = Some("abc");
238 pub REDUNDANT_PATTERN,
240 "using `name @ _` in a pattern"
243 declare_clippy_lint! {
244 /// **What it does:** Checks for tuple patterns with a wildcard
245 /// pattern (`_`) is next to a rest pattern (`..`).
247 /// _NOTE_: While `_, ..` means there is at least one element left, `..`
248 /// means there are 0 or more elements left. This can make a difference
249 /// when refactoring, but shouldn't result in errors in the refactored code,
250 /// since the wildcard pattern isn't used anyway.
251 /// **Why is this bad?** The wildcard pattern is unneeded as the rest pattern
252 /// can match that element as well.
254 /// **Known problems:** None.
258 /// # struct TupleStruct(u32, u32, u32);
259 /// # let t = TupleStruct(1, 2, 3);
263 /// TupleStruct(0, .., _) => (),
269 /// TupleStruct(0, ..) => (),
273 pub UNNEEDED_WILDCARD_PATTERN,
275 "tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`)"
278 declare_lint_pass!(MiscEarlyLints => [
279 UNNEEDED_FIELD_PATTERN,
280 DUPLICATE_UNDERSCORE_ARGUMENT,
281 REDUNDANT_CLOSURE_CALL,
283 MIXED_CASE_HEX_LITERALS,
284 UNSEPARATED_LITERAL_SUFFIX,
285 ZERO_PREFIXED_LITERAL,
288 UNNEEDED_WILDCARD_PATTERN,
291 // Used to find `return` statements or equivalents e.g., `?`
292 struct ReturnVisitor {
299 Self { found_return: false }
303 impl<'ast> Visitor<'ast> for ReturnVisitor {
304 fn visit_expr(&mut self, ex: &'ast Expr) {
305 if let ExprKind::Ret(_) = ex.kind {
306 self.found_return = true;
307 } else if let ExprKind::Try(_) = ex.kind {
308 self.found_return = true;
315 impl EarlyLintPass for MiscEarlyLints {
316 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
317 for param in &gen.params {
318 if let GenericParamKind::Type { .. } = param.kind {
319 let name = param.ident.as_str();
320 if constants::BUILTIN_TYPES.contains(&&*name) {
325 &format!("This generic shadows the built-in type `{}`", name),
332 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
333 if let PatKind::Struct(ref npat, ref pfields, _) = pat.kind {
338 .expect("A path must have at least one segment")
342 for field in pfields {
343 if let PatKind::Wild = field.pat.kind {
347 if !pfields.is_empty() && wilds == pfields.len() {
350 UNNEEDED_FIELD_PATTERN,
352 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
354 &format!("Try with `{} {{ .. }}` instead", type_name),
359 for field in pfields {
360 if let PatKind::Wild = field.pat.kind {
365 UNNEEDED_FIELD_PATTERN,
367 "You matched a field with a wildcard pattern. Consider using `..` instead",
370 let mut normal = vec![];
372 for field in pfields {
373 match field.pat.kind {
376 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
385 UNNEEDED_FIELD_PATTERN,
387 "You matched a field with a wildcard pattern. Consider using `..` \
390 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
398 if let PatKind::Ident(left, ident, Some(ref right)) = pat.kind {
399 let left_binding = match left {
400 BindingMode::ByRef(Mutability::Mut) => "ref mut ",
401 BindingMode::ByRef(Mutability::Not) => "ref ",
402 BindingMode::ByValue(..) => "",
405 if let PatKind::Wild = right.kind {
411 "the `{} @ _` pattern can be written as just `{}`",
412 ident.name, ident.name,
415 format!("{}{}", left_binding, ident.name),
416 Applicability::MachineApplicable,
421 check_unneeded_wildcard_pattern(cx, pat);
424 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
425 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
427 for arg in &fn_kind.decl().inputs {
428 if let PatKind::Ident(_, ident, None) = arg.pat.kind {
429 let arg_name = ident.to_string();
431 if arg_name.starts_with('_') {
432 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
435 DUPLICATE_UNDERSCORE_ARGUMENT,
438 "`{}` already exists, having another argument having almost the same \
439 name makes code comprehension and documentation more difficult",
440 arg_name[1..].to_owned()
445 registered_names.insert(arg_name, arg.pat.span);
451 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
452 if in_external_macro(cx.sess(), expr.span) {
456 ExprKind::Call(ref paren, _) => {
457 if let ExprKind::Paren(ref closure) = paren.kind {
458 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind {
459 let mut visitor = ReturnVisitor::new();
460 visitor.visit_expr(block);
461 if !visitor.found_return {
464 REDUNDANT_CLOSURE_CALL,
466 "Try not to call a closure in the expression where it is declared.",
468 if decl.inputs.is_empty() {
469 let mut app = Applicability::MachineApplicable;
471 snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
472 diag.span_suggestion(expr.span, "Try doing something like: ", hint, app);
480 ExprKind::Unary(UnOp::Neg, ref inner) => {
481 if let ExprKind::Unary(UnOp::Neg, _) = inner.kind {
486 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
490 ExprKind::Lit(ref lit) => Self::check_lit(cx, lit),
495 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
496 for w in block.stmts.windows(2) {
498 if let StmtKind::Local(ref local) = w[0].kind;
499 if let Option::Some(ref t) = local.init;
500 if let ExprKind::Closure(..) = t.kind;
501 if let PatKind::Ident(_, ident, _) = local.pat.kind;
502 if let StmtKind::Semi(ref second) = w[1].kind;
503 if let ExprKind::Assign(_, ref call, _) = second.kind;
504 if let ExprKind::Call(ref closure, _) = call.kind;
505 if let ExprKind::Path(_, ref path) = closure.kind;
507 if ident == path.segments[0].ident {
510 REDUNDANT_CLOSURE_CALL,
512 "Closure called just once immediately after it was declared",
521 impl MiscEarlyLints {
522 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
523 // We test if first character in snippet is a number, because the snippet could be an expansion
524 // from a built-in macro like `line!()` or a proc-macro like `#[wasm_bindgen]`.
525 // Note that this check also covers special case that `line!()` is eagerly expanded by compiler.
526 // See <https://github.com/rust-lang/rust-clippy/issues/4507> for a regression.
527 // FIXME: Find a better way to detect those cases.
528 let lit_snip = match snippet_opt(cx, lit.span) {
529 Some(snip) if snip.chars().next().map_or(false, |c| c.is_digit(10)) => snip,
533 if let LitKind::Int(value, lit_int_type) = lit.kind {
534 let suffix = match lit_int_type {
535 LitIntType::Signed(ty) => ty.name_str(),
536 LitIntType::Unsigned(ty) => ty.name_str(),
537 LitIntType::Unsuffixed => "",
540 let maybe_last_sep_idx = if let Some(val) = lit_snip.len().checked_sub(suffix.len() + 1) {
543 return; // It's useless so shouldn't lint.
545 // Do not lint when literal is unsuffixed.
546 if !suffix.is_empty() && lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
549 UNSEPARATED_LITERAL_SUFFIX,
551 "integer type suffix should be separated by an underscore",
553 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
554 Applicability::MachineApplicable,
558 if lit_snip.starts_with("0x") {
559 if maybe_last_sep_idx <= 2 {
560 // It's meaningless or causes range error.
563 let mut seen = (false, false);
564 for ch in lit_snip.as_bytes()[2..=maybe_last_sep_idx].iter() {
566 b'a'..=b'f' => seen.0 = true,
567 b'A'..=b'F' => seen.1 = true,
570 if seen.0 && seen.1 {
573 MIXED_CASE_HEX_LITERALS,
575 "inconsistent casing in hexadecimal literal",
580 } else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
582 } else if value != 0 && lit_snip.starts_with('0') {
585 ZERO_PREFIXED_LITERAL,
587 "this is a decimal constant",
589 diag.span_suggestion(
591 "if you mean to use a decimal constant, remove the `0` to avoid confusion",
592 lit_snip.trim_start_matches(|c| c == '_' || c == '0').to_string(),
593 Applicability::MaybeIncorrect,
595 diag.span_suggestion(
597 "if you mean to use an octal constant, use `0o`",
598 format!("0o{}", lit_snip.trim_start_matches(|c| c == '_' || c == '0')),
599 Applicability::MaybeIncorrect,
604 } else if let LitKind::Float(_, LitFloatType::Suffixed(float_ty)) = lit.kind {
605 let suffix = float_ty.name_str();
606 let maybe_last_sep_idx = if let Some(val) = lit_snip.len().checked_sub(suffix.len() + 1) {
609 return; // It's useless so shouldn't lint.
611 if lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
614 UNSEPARATED_LITERAL_SUFFIX,
616 "float type suffix should be separated by an underscore",
618 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
619 Applicability::MachineApplicable,
626 fn check_unneeded_wildcard_pattern(cx: &EarlyContext<'_>, pat: &Pat) {
627 if let PatKind::TupleStruct(_, ref patterns) | PatKind::Tuple(ref patterns) = pat.kind {
628 fn span_lint(cx: &EarlyContext<'_>, span: Span, only_one: bool) {
631 UNNEEDED_WILDCARD_PATTERN,
634 "this pattern is unneeded as the `..` pattern can match that element"
636 "these patterns are unneeded as the `..` pattern can match those elements"
638 if only_one { "remove it" } else { "remove them" },
640 Applicability::MachineApplicable,
644 if let Some(rest_index) = patterns.iter().position(|pat| pat.is_rest()) {
645 if let Some((left_index, left_pat)) = patterns[..rest_index]
648 .take_while(|pat| matches!(pat.kind, PatKind::Wild))
652 span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0);
655 if let Some((right_index, right_pat)) = patterns[rest_index + 1..]
657 .take_while(|pat| matches!(pat.kind, PatKind::Wild))
663 patterns[rest_index].span.shrink_to_hi().to(right_pat.span),