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.
28 /// let { a: _, b: ref b, c: _ } = ..
30 pub UNNEEDED_FIELD_PATTERN,
32 "struct fields bound to a wildcard instead of using `..`"
35 declare_clippy_lint! {
36 /// **What it does:** Checks for function arguments having the similar names
37 /// differing by an underscore.
39 /// **Why is this bad?** It affects code readability.
41 /// **Known problems:** None.
45 /// fn foo(a: i32, _a: i32) {}
47 pub DUPLICATE_UNDERSCORE_ARGUMENT,
49 "function arguments having names which only differ by an underscore"
52 declare_clippy_lint! {
53 /// **What it does:** Detects closures called in the same expression where they
56 /// **Why is this bad?** It is unnecessarily adding to the expression's
59 /// **Known problems:** None.
65 pub REDUNDANT_CLOSURE_CALL,
67 "throwaway closures called in the expression they are defined"
70 declare_clippy_lint! {
71 /// **What it does:** Detects expressions of the form `--x`.
73 /// **Why is this bad?** It can mislead C/C++ programmers to think `x` was
76 /// **Known problems:** None.
85 "`--x`, which is a double negation of `x` and not a pre-decrement as in C/C++"
88 declare_clippy_lint! {
89 /// **What it does:** Warns on hexadecimal literals with mixed-case letter
92 /// **Why is this bad?** It looks confusing.
94 /// **Known problems:** None.
98 /// let y = 0x1a9BAcD;
100 pub MIXED_CASE_HEX_LITERALS,
102 "hex literals whose letter digits are not consistently upper- or lowercased"
105 declare_clippy_lint! {
106 /// **What it does:** Warns if literal suffixes are not separated by an
109 /// **Why is this bad?** It is much less readable.
111 /// **Known problems:** None.
115 /// let y = 123832i32;
117 pub UNSEPARATED_LITERAL_SUFFIX,
119 "literals whose suffix is not separated by an underscore"
122 declare_clippy_lint! {
123 /// **What it does:** Warns if an integral constant literal starts with `0`.
125 /// **Why is this bad?** In some languages (including the infamous C language
127 /// family), this marks an octal constant. In Rust however, this is a decimal
128 /// constant. This could
129 /// be confusing for both the writer and a reader of the constant.
131 /// **Known problems:** None.
139 /// println!("{}", a);
143 /// prints `123`, while in C:
146 /// #include <stdio.h>
150 /// printf("%d\n", a);
154 /// prints `83` (as `83 == 0o123` while `123 == 0o173`).
155 pub ZERO_PREFIXED_LITERAL,
157 "integer literals starting with `0`"
160 declare_clippy_lint! {
161 /// **What it does:** Warns if a generic shadows a built-in type.
163 /// **Why is this bad?** This gives surprising type errors.
165 /// **Known problems:** None.
170 /// impl<u32> Foo<u32> {
171 /// fn impl_func(&self) -> u32 {
176 pub BUILTIN_TYPE_SHADOW,
178 "shadowing a builtin type"
181 declare_clippy_lint! {
182 /// **What it does:** Checks for patterns in the form `name @ _`.
184 /// **Why is this bad?** It's almost always more readable to just use direct
187 /// **Known problems:** None.
191 /// # let v = Some("abc");
195 /// y @ _ => (), // easier written as `y`,
198 pub REDUNDANT_PATTERN,
200 "using `name @ _` in a pattern"
203 declare_clippy_lint! {
204 /// **What it does:** Checks for tuple patterns with a wildcard
205 /// pattern (`_`) is next to a rest pattern (`..`).
207 /// _NOTE_: While `_, ..` means there is at least one element left, `..`
208 /// means there are 0 or more elements left. This can make a difference
209 /// when refactoring, but shouldn't result in errors in the refactored code,
210 /// since the wildcard pattern isn't used anyway.
211 /// **Why is this bad?** The wildcard pattern is unneeded as the rest pattern
212 /// can match that element as well.
214 /// **Known problems:** None.
218 /// # struct TupleStruct(u32, u32, u32);
219 /// # let t = TupleStruct(1, 2, 3);
222 /// TupleStruct(0, .., _) => (),
226 /// can be written as
228 /// # struct TupleStruct(u32, u32, u32);
229 /// # let t = TupleStruct(1, 2, 3);
232 /// TupleStruct(0, ..) => (),
236 pub UNNEEDED_WILDCARD_PATTERN,
238 "tuple patterns with a wildcard pattern (`_`) is next to a rest pattern (`..`)"
241 declare_lint_pass!(MiscEarlyLints => [
242 UNNEEDED_FIELD_PATTERN,
243 DUPLICATE_UNDERSCORE_ARGUMENT,
244 REDUNDANT_CLOSURE_CALL,
246 MIXED_CASE_HEX_LITERALS,
247 UNSEPARATED_LITERAL_SUFFIX,
248 ZERO_PREFIXED_LITERAL,
251 UNNEEDED_WILDCARD_PATTERN,
254 // Used to find `return` statements or equivalents e.g., `?`
255 struct ReturnVisitor {
262 Self { found_return: false }
266 impl<'ast> Visitor<'ast> for ReturnVisitor {
267 fn visit_expr(&mut self, ex: &'ast Expr) {
268 if let ExprKind::Ret(_) = ex.kind {
269 self.found_return = true;
270 } else if let ExprKind::Try(_) = ex.kind {
271 self.found_return = true;
278 impl EarlyLintPass for MiscEarlyLints {
279 fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
280 for param in &gen.params {
281 if let GenericParamKind::Type { .. } = param.kind {
282 let name = param.ident.as_str();
283 if constants::BUILTIN_TYPES.contains(&&*name) {
288 &format!("This generic shadows the built-in type `{}`", name),
295 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &Pat) {
296 if let PatKind::Struct(ref npat, ref pfields, _) = pat.kind {
301 .expect("A path must have at least one segment")
305 for field in pfields {
306 if let PatKind::Wild = field.pat.kind {
310 if !pfields.is_empty() && wilds == pfields.len() {
313 UNNEEDED_FIELD_PATTERN,
315 "All the struct fields are matched to a wildcard pattern, consider using `..`.",
317 &format!("Try with `{} {{ .. }}` instead", type_name),
322 for field in pfields {
323 if let PatKind::Wild = field.pat.kind {
328 UNNEEDED_FIELD_PATTERN,
330 "You matched a field with a wildcard pattern. Consider using `..` instead",
333 let mut normal = vec![];
335 for field in pfields {
336 match field.pat.kind {
339 if let Ok(n) = cx.sess().source_map().span_to_snippet(field.span) {
348 UNNEEDED_FIELD_PATTERN,
350 "You matched a field with a wildcard pattern. Consider using `..` \
353 &format!("Try with `{} {{ {}, .. }}`", type_name, normal[..].join(", ")),
361 if let PatKind::Ident(left, ident, Some(ref right)) = pat.kind {
362 let left_binding = match left {
363 BindingMode::ByRef(Mutability::Mut) => "ref mut ",
364 BindingMode::ByRef(Mutability::Not) => "ref ",
368 if let PatKind::Wild = right.kind {
374 "the `{} @ _` pattern can be written as just `{}`",
375 ident.name, ident.name,
378 format!("{}{}", left_binding, ident.name),
379 Applicability::MachineApplicable,
384 check_unneeded_wildcard_pattern(cx, pat);
387 fn check_fn(&mut self, cx: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
388 let mut registered_names: FxHashMap<String, Span> = FxHashMap::default();
390 for arg in &fn_kind.decl().inputs {
391 if let PatKind::Ident(_, ident, None) = arg.pat.kind {
392 let arg_name = ident.to_string();
394 if arg_name.starts_with('_') {
395 if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
398 DUPLICATE_UNDERSCORE_ARGUMENT,
401 "`{}` already exists, having another argument having almost the same \
402 name makes code comprehension and documentation more difficult",
403 arg_name[1..].to_owned()
408 registered_names.insert(arg_name, arg.pat.span);
414 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
415 if in_external_macro(cx.sess(), expr.span) {
419 ExprKind::Call(ref paren, _) => {
420 if let ExprKind::Paren(ref closure) = paren.kind {
421 if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind {
422 let mut visitor = ReturnVisitor::new();
423 visitor.visit_expr(block);
424 if !visitor.found_return {
427 REDUNDANT_CLOSURE_CALL,
429 "Try not to call a closure in the expression where it is declared.",
431 if decl.inputs.is_empty() {
432 let mut app = Applicability::MachineApplicable;
434 snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
435 diag.span_suggestion(expr.span, "Try doing something like: ", hint, app);
443 ExprKind::Unary(UnOp::Neg, ref inner) => {
444 if let ExprKind::Unary(UnOp::Neg, _) = inner.kind {
449 "`--x` could be misinterpreted as pre-decrement by C programmers, is usually a no-op",
453 ExprKind::Lit(ref lit) => Self::check_lit(cx, lit),
458 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
459 for w in block.stmts.windows(2) {
461 if let StmtKind::Local(ref local) = w[0].kind;
462 if let Option::Some(ref t) = local.init;
463 if let ExprKind::Closure(..) = t.kind;
464 if let PatKind::Ident(_, ident, _) = local.pat.kind;
465 if let StmtKind::Semi(ref second) = w[1].kind;
466 if let ExprKind::Assign(_, ref call, _) = second.kind;
467 if let ExprKind::Call(ref closure, _) = call.kind;
468 if let ExprKind::Path(_, ref path) = closure.kind;
470 if ident == path.segments[0].ident {
473 REDUNDANT_CLOSURE_CALL,
475 "Closure called just once immediately after it was declared",
484 impl MiscEarlyLints {
485 fn check_lit(cx: &EarlyContext<'_>, lit: &Lit) {
486 // We test if first character in snippet is a number, because the snippet could be an expansion
487 // from a built-in macro like `line!()` or a proc-macro like `#[wasm_bindgen]`.
488 // Note that this check also covers special case that `line!()` is eagerly expanded by compiler.
489 // See <https://github.com/rust-lang/rust-clippy/issues/4507> for a regression.
490 // FIXME: Find a better way to detect those cases.
491 let lit_snip = match snippet_opt(cx, lit.span) {
492 Some(snip) if snip.chars().next().map_or(false, |c| c.is_digit(10)) => snip,
496 if let LitKind::Int(value, lit_int_type) = lit.kind {
497 let suffix = match lit_int_type {
498 LitIntType::Signed(ty) => ty.name_str(),
499 LitIntType::Unsigned(ty) => ty.name_str(),
500 LitIntType::Unsuffixed => "",
503 let maybe_last_sep_idx = if let Some(val) = lit_snip.len().checked_sub(suffix.len() + 1) {
506 return; // It's useless so shouldn't lint.
508 // Do not lint when literal is unsuffixed.
509 if !suffix.is_empty() && lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
512 UNSEPARATED_LITERAL_SUFFIX,
514 "integer type suffix should be separated by an underscore",
516 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
517 Applicability::MachineApplicable,
521 if lit_snip.starts_with("0x") {
522 if maybe_last_sep_idx <= 2 {
523 // It's meaningless or causes range error.
526 let mut seen = (false, false);
527 for ch in lit_snip.as_bytes()[2..=maybe_last_sep_idx].iter() {
529 b'a'..=b'f' => seen.0 = true,
530 b'A'..=b'F' => seen.1 = true,
533 if seen.0 && seen.1 {
536 MIXED_CASE_HEX_LITERALS,
538 "inconsistent casing in hexadecimal literal",
543 } else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
545 } else if value != 0 && lit_snip.starts_with('0') {
548 ZERO_PREFIXED_LITERAL,
550 "this is a decimal constant",
552 diag.span_suggestion(
554 "if you mean to use a decimal constant, remove the `0` to avoid confusion",
555 lit_snip.trim_start_matches(|c| c == '_' || c == '0').to_string(),
556 Applicability::MaybeIncorrect,
558 diag.span_suggestion(
560 "if you mean to use an octal constant, use `0o`",
561 format!("0o{}", lit_snip.trim_start_matches(|c| c == '_' || c == '0')),
562 Applicability::MaybeIncorrect,
567 } else if let LitKind::Float(_, LitFloatType::Suffixed(float_ty)) = lit.kind {
568 let suffix = float_ty.name_str();
569 let maybe_last_sep_idx = if let Some(val) = lit_snip.len().checked_sub(suffix.len() + 1) {
572 return; // It's useless so shouldn't lint.
574 if lit_snip.as_bytes()[maybe_last_sep_idx] != b'_' {
577 UNSEPARATED_LITERAL_SUFFIX,
579 "float type suffix should be separated by an underscore",
581 format!("{}_{}", &lit_snip[..=maybe_last_sep_idx], suffix),
582 Applicability::MachineApplicable,
589 fn check_unneeded_wildcard_pattern(cx: &EarlyContext<'_>, pat: &Pat) {
590 if let PatKind::TupleStruct(_, ref patterns) | PatKind::Tuple(ref patterns) = pat.kind {
591 fn span_lint(cx: &EarlyContext<'_>, span: Span, only_one: bool) {
594 UNNEEDED_WILDCARD_PATTERN,
597 "this pattern is unneeded as the `..` pattern can match that element"
599 "these patterns are unneeded as the `..` pattern can match those elements"
601 if only_one { "remove it" } else { "remove them" },
603 Applicability::MachineApplicable,
607 #[allow(clippy::trivially_copy_pass_by_ref)]
608 fn is_wild<P: std::ops::Deref<Target = Pat>>(pat: &&P) -> bool {
609 if let PatKind::Wild = pat.kind {
616 if let Some(rest_index) = patterns.iter().position(|pat| pat.is_rest()) {
617 if let Some((left_index, left_pat)) = patterns[..rest_index]
624 span_lint(cx, left_pat.span.until(patterns[rest_index].span), left_index == 0);
627 if let Some((right_index, right_pat)) =
628 patterns[rest_index + 1..].iter().take_while(is_wild).enumerate().last()
632 patterns[rest_index].span.shrink_to_hi().to(right_pat.span),