1 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::source::snippet_opt;
4 BindingMode, Expr, ExprKind, GenericParamKind, Generics, Lit, LitFloatType, LitIntType, LitKind, Mutability,
5 NodeId, Pat, PatKind, UnOp,
7 use rustc_ast::visit::FnKind;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::Applicability;
10 use rustc_hir::PrimTy;
11 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::source_map::Span;
16 declare_clippy_lint! {
17 /// **What it does:** Checks for structure field patterns bound to wildcards.
19 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on
20 /// the fields that are actually bound.
22 /// **Known problems:** None.
31 /// let f = Foo { a: 0, b: 0, c: 0 };
35 /// Foo { a: _, b: 0, .. } => {},
36 /// Foo { a: _, b: _, c: _ } => {},
41 /// Foo { b: 0, .. } => {},
45 pub UNNEEDED_FIELD_PATTERN,
47 "struct fields bound to a wildcard instead of using `..`"
50 declare_clippy_lint! {
51 /// **What it does:** Checks for function arguments having the similar names
52 /// differing by an underscore.
54 /// **Why is this bad?** It affects code readability.
56 /// **Known problems:** None.
61 /// fn foo(a: i32, _a: i32) {}
64 /// fn bar(a: i32, _b: i32) {}
66 pub DUPLICATE_UNDERSCORE_ARGUMENT,
68 "function arguments having names which only differ by an underscore"
71 declare_clippy_lint! {
72 /// **What it does:** Detects expressions of the form `--x`.
74 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
77 /// **Known problems:** None.
86 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
89 declare_clippy_lint! {
90 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
93 /// **Why is this bad?** It looks confusing.
95 /// **Known problems:** None.
100 /// let y = 0x1a9BAcD;
103 /// let y = 0x1A9BACD;
105 pub MIXED_CASE_HEX_LITERALS,
107 "hex literals whose letter digits are not consistently upper- or lowercased"
110 declare_clippy_lint! {
111 /// **What it does:** Warns if literal suffixes are not separated by an
114 /// **Why is this bad?** It is much less readable.
116 /// **Known problems:** None.
121 /// let y = 123832i32;
124 /// let y = 123832_i32;
126 pub UNSEPARATED_LITERAL_SUFFIX,
128 "literals whose suffix is not separated by an underscore"
131 declare_clippy_lint! {
132 /// **What it does:** Warns if an integral constant literal starts with `0`.
134 /// **Why is this bad?** In some languages (including the infamous C language
136 /// family), this marks an octal constant. In Rust however, this is a decimal
137 /// constant. This could
138 /// be confusing for both the writer and a reader of the constant.
140 /// **Known problems:** None.
148 /// println!("{}", a);
152 /// prints `123`, while in C:
155 /// #include <stdio.h>
159 /// printf("%d\n", a);
163 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
164 pub ZERO_PREFIXED_LITERAL,
166 "integer literals starting with `0`"
169 declare_clippy_lint! {
170 /// **What it does:** Warns if a generic shadows a built-in type.
172 /// **Why is this bad?** This gives surprising type errors.
174 /// **Known problems:** None.
179 /// impl<u32> Foo<u32> {
180 /// fn impl_func(&self) -> u32 {
185 pub BUILTIN_TYPE_SHADOW,
187 "shadowing a builtin type"
190 declare_clippy_lint! {
191 /// **What it does:** Checks for patterns in the form `name @ _`.
193 /// **Why is this bad?** It's almost always more readable to just use direct
196 /// **Known problems:** None.
200 /// # let v = Some("abc");
214 pub REDUNDANT_PATTERN,
216 "using `name @ _` in a pattern"
219 declare_clippy_lint! {
220 /// **What it does:** Checks for tuple patterns with a wildcard
221 /// pattern (`_`) is next to a rest pattern (`..`).
223 /// _NOTE_: While `_, ..` means there is at least one element left, `..`
224 /// means there are 0 or more elements left. This can make a difference
225 /// when refactoring, but shouldn't result in errors in the refactored code,
226 /// since the wildcard pattern isn't used anyway.
227 /// **Why is this bad?** The wildcard pattern is unneeded as the rest pattern
228 /// can match that element as well.
230 /// **Known problems:** None.
234 /// # struct TupleStruct(u32, u32, u32);
235 /// # let t = TupleStruct(1, 2, 3);
238 /// TupleStruct(0, .., _) => (),
244 /// TupleStruct(0, ..) => (),
248 pub UNNEEDED_WILDCARD_PATTERN,
250 "tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`)"
253 declare_lint_pass!(MiscEarlyLints => [
254 UNNEEDED_FIELD_PATTERN,
255 DUPLICATE_UNDERSCORE_ARGUMENT,
257 MIXED_CASE_HEX_LITERALS,
258 UNSEPARATED_LITERAL_SUFFIX,
259 ZERO_PREFIXED_LITERAL,
262 UNNEEDED_WILDCARD_PATTERN,
265 impl EarlyLintPass for MiscEarlyLints {
266 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
267 for param in &gen.params {
268 if let GenericParamKind::Type { .. } = param.kind {
269 if let Some(prim_ty) = PrimTy::from_name(param.ident.name) {
274 &format!("this generic shadows the built-in type `{}`", prim_ty.name()),
281 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
282 if let PatKind::Struct(ref npat, ref pfields, _) = pat.kind {
287 .expect("A path must have at least one segment")
291 for field in pfields {
292 if let PatKind::Wild = field.pat.kind {
296 if !pfields.is_empty() && wilds == pfields.len() {
299 UNNEEDED_FIELD_PATTERN,
301 "all the struct fields are matched to a wildcard pattern, consider using `..`",
303 &format!("try with `{} {{ .. }}` instead", type_name),
308 for field in pfields {
309 if let PatKind::Wild = field.pat.kind {
314 UNNEEDED_FIELD_PATTERN,
316 "you matched a field with a wildcard pattern, consider using `..` instead",
319 let mut normal = vec![];
321 for field in pfields {
322 match field.pat.kind {
325 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
334 UNNEEDED_FIELD_PATTERN,
336 "you matched a field with a wildcard pattern, consider using `..` \
339 &format!("try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
347 if let PatKind::Ident(left, ident, Some(ref right)) = pat.kind {
348 let left_binding = match left {
349 BindingMode::ByRef(Mutability::Mut) => "ref mut ",
350 BindingMode::ByRef(Mutability::Not) => "ref ",
351 BindingMode::ByValue(..) => "",
354 if let PatKind::Wild = right.kind {
360 "the `{} @ _` pattern can be written as just `{}`",
361 ident.name, ident.name,
364 format!("{}{}", left_binding, ident.name),
365 Applicability::MachineApplicable,
370 check_unneeded_wildcard_pattern(cx, pat);
373 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
374 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
376 for arg in &fn_kind.decl().inputs {
377 if let PatKind::Ident(_, ident, None) = arg.pat.kind {
378 let arg_name = ident.to_string();
380 if let Some(arg_name) = arg_name.strip_prefix('_') {
381 if let Some(correspondence) = registered_names.get(arg_name) {
384 DUPLICATE_UNDERSCORE_ARGUMENT,
387 "`{}` already exists, having another argument having almost the same \
388 name makes code comprehension and documentation more difficult",
394 registered_names.insert(arg_name, arg.pat.span);
400 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
401 if in_external_macro(cx.sess(), expr.span) {
405 ExprKind::Unary(UnOp::Neg, ref inner) => {
406 if let ExprKind::Unary(UnOp::Neg, _) = inner.kind {
411 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
415 ExprKind::Lit(ref lit) => Self::check_lit(cx, lit),
421 impl MiscEarlyLints {
422 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
423 // We test if first character in snippet is a number, because the snippet could be an expansion
424 // from a built-in macro like `line!()` or a proc-macro like `#[wasm_bindgen]`.
425 // Note that this check also covers special case that `line!()` is eagerly expanded by compiler.
426 // See <https://github.com/rust-lang/rust-clippy/issues/4507> for a regression.
427 // FIXME: Find a better way to detect those cases.
428 let lit_snip = match snippet_opt(cx, lit.span) {
429 Some(snip) if snip.chars().next().map_or(false, |c| c.is_digit(10)) => snip,
433 if let LitKind::Int(value, lit_int_type) = lit.kind {
434 let suffix = match lit_int_type {
435 LitIntType::Signed(ty) => ty.name_str(),
436 LitIntType::Unsigned(ty) => ty.name_str(),
437 LitIntType::Unsuffixed => "",
440 let maybe_last_sep_idx = if let Some(val) = lit_snip.len().checked_sub(suffix.len() + 1) {
443 return; // It's useless so shouldn't lint.
445 // Do not lint when literal is unsuffixed.
446 if !suffix.is_empty() && lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
449 UNSEPARATED_LITERAL_SUFFIX,
451 "integer type suffix should be separated by an underscore",
453 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
454 Applicability::MachineApplicable,
458 if lit_snip.starts_with("0x") {
459 if maybe_last_sep_idx <= 2 {
460 // It's meaningless or causes range error.
463 let mut seen = (false, false);
464 for ch in lit_snip.as_bytes()[2..=maybe_last_sep_idx].iter() {
466 b'a'..=b'f' => seen.0 = true,
467 b'A'..=b'F' => seen.1 = true,
470 if seen.0 && seen.1 {
473 MIXED_CASE_HEX_LITERALS,
475 "inconsistent casing in hexadecimal literal",
480 } else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
482 } else if value != 0 && lit_snip.starts_with('0') {
485 ZERO_PREFIXED_LITERAL,
487 "this is a decimal constant",
489 diag.span_suggestion(
491 "if you mean to use a decimal constant, remove the `0` to avoid confusion",
492 lit_snip.trim_start_matches(|c| c == '_' || c == '0').to_string(),
493 Applicability::MaybeIncorrect,
495 diag.span_suggestion(
497 "if you mean to use an octal constant, use `0o`",
498 format!("0o{}", lit_snip.trim_start_matches(|c| c == '_' || c == '0')),
499 Applicability::MaybeIncorrect,
504 } else if let LitKind::Float(_, LitFloatType::Suffixed(float_ty)) = lit.kind {
505 let suffix = float_ty.name_str();
506 let maybe_last_sep_idx = if let Some(val) = lit_snip.len().checked_sub(suffix.len() + 1) {
509 return; // It's useless so shouldn't lint.
511 if lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
514 UNSEPARATED_LITERAL_SUFFIX,
516 "float type suffix should be separated by an underscore",
518 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
519 Applicability::MachineApplicable,
526 fn check_unneeded_wildcard_pattern(cx: &EarlyContext<'_>, pat: &Pat) {
527 if let PatKind::TupleStruct(_, ref patterns) | PatKind::Tuple(ref patterns) = pat.kind {
528 fn span_lint(cx: &EarlyContext<'_>, span: Span, only_one: bool) {
531 UNNEEDED_WILDCARD_PATTERN,
534 "this pattern is unneeded as the `..` pattern can match that element"
536 "these patterns are unneeded as the `..` pattern can match those elements"
538 if only_one { "remove it" } else { "remove them" },
540 Applicability::MachineApplicable,
544 if let Some(rest_index) = patterns.iter().position(|pat| pat.is_rest()) {
545 if let Some((left_index, left_pat)) = patterns[..rest_index]
548 .take_while(|pat| matches!(pat.kind, PatKind::Wild))
552 span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0);
555 if let Some((right_index, right_pat)) = patterns[rest_index + 1..]
557 .take_while(|pat| matches!(pat.kind, PatKind::Wild))
563 patterns[rest_index].span.shrink_to_hi().to(right_pat.span),