1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then, span_lint_hir_and_then};
2 use clippy_utils::source::{snippet, snippet_opt};
3 use clippy_utils::ty::implements_trait;
4 use if_chain::if_chain;
5 use rustc_ast::ast::LitKind;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::FnKind;
9 self as hir, def, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind, Stmt,
10 StmtKind, TyKind, UnOp,
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::lint::in_external_macro;
14 use rustc_middle::ty::{self, Ty};
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::hygiene::DesugaringKind;
17 use rustc_span::source_map::{ExpnKind, Span};
18 use rustc_span::symbol::sym;
20 use crate::consts::{constant, Constant};
21 use clippy_utils::sugg::Sugg;
23 get_item_name, get_parent_expr, higher, in_constant, is_diagnostic_assoc_item, is_integer_const, iter_input_pats,
24 last_path_segment, match_qpath, unsext, SpanlessEq,
27 declare_clippy_lint! {
28 /// **What it does:** Checks for function arguments and let bindings denoted as
31 /// **Why is this bad?** The `ref` declaration makes the function take an owned
32 /// value, but turns the argument into a reference (which means that the value
33 /// is destroyed when exiting the function). This adds not much value: either
34 /// take a reference type, or take an owned value and create references in the
37 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
38 /// type of `x` is more obvious with the former.
40 /// **Known problems:** If the argument is dereferenced within the function,
41 /// removing the `ref` will lead to errors. This can be fixed by removing the
42 /// dereferences, e.g., changing `*x` to `x` within the function.
47 /// fn foo(ref x: u8) -> bool {
52 /// fn foo(x: &u8) -> bool {
58 "an entire binding declared as `ref`, in a function argument or a `let` statement"
61 declare_clippy_lint! {
62 /// **What it does:** Checks for comparisons to NaN.
64 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
65 /// even itself – so those comparisons are simply wrong.
67 /// **Known problems:** None.
74 /// if x == f32::NAN { }
81 "comparisons to `NAN`, which will always return false, probably not intended"
84 declare_clippy_lint! {
85 /// **What it does:** Checks for (in-)equality comparisons on floating-point
86 /// values (apart from zero), except in functions called `*eq*` (which probably
87 /// implement equality for a type involving floats).
89 /// **Why is this bad?** Floating point calculations are usually imprecise, so
90 /// asking if two values are *exactly* equal is asking for trouble. For a good
91 /// guide on what to do, see [the floating point
92 /// guide](http://www.floating-point-gui.de/errors/comparison).
94 /// **Known problems:** None.
98 /// let x = 1.2331f64;
99 /// let y = 1.2332f64;
102 /// if y == 1.23f64 { }
103 /// if y != x {} // where both are floats
106 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
107 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
108 /// // let error_margin = std::f64::EPSILON;
109 /// if (y - 1.23f64).abs() < error_margin { }
110 /// if (y - x).abs() > error_margin { }
114 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
117 declare_clippy_lint! {
118 /// **What it does:** Checks for conversions to owned values just for the sake
121 /// **Why is this bad?** The comparison can operate on a reference, so creating
122 /// an owned value effectively throws it away directly afterwards, which is
123 /// needlessly consuming code and heap space.
125 /// **Known problems:** None.
130 /// # let y = String::from("foo");
131 /// if x.to_owned() == y {}
133 /// Could be written as
136 /// # let y = String::from("foo");
141 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
144 declare_clippy_lint! {
145 /// **What it does:** Checks for getting the remainder of a division by one or minus
148 /// **Why is this bad?** The result for a divisor of one can only ever be zero; for
149 /// minus one it can cause panic/overflow (if the left operand is the minimal value of
150 /// the respective integer type) or results in zero. No one will write such code
151 /// deliberately, unless trying to win an Underhanded Rust Contest. Even for that
152 /// contest, it's probably a bad idea. Use something more underhanded.
154 /// **Known problems:** None.
164 "taking a number modulo +/-1, which can either panic/overflow or always returns 0"
167 declare_clippy_lint! {
168 /// **What it does:** Checks for the use of bindings with a single leading
171 /// **Why is this bad?** A single leading underscore is usually used to indicate
172 /// that a binding will not be used. Using such a binding breaks this
175 /// **Known problems:** The lint does not work properly with desugaring and
176 /// macro, it has been allowed in the mean time.
181 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
182 /// // underscore. We should rename `_x` to `x`
184 pub USED_UNDERSCORE_BINDING,
186 "using a binding which is prefixed with an underscore"
189 declare_clippy_lint! {
190 /// **What it does:** Checks for the use of short circuit boolean conditions as
194 /// **Why is this bad?** Using a short circuit boolean condition as a statement
195 /// may hide the fact that the second part is executed or not depending on the
196 /// outcome of the first part.
198 /// **Known problems:** None.
202 /// f() && g(); // We should write `if f() { g(); }`.
204 pub SHORT_CIRCUIT_STATEMENT,
206 "using a short circuit boolean condition as a statement"
209 declare_clippy_lint! {
210 /// **What it does:** Catch casts from `0` to some pointer type
212 /// **Why is this bad?** This generally means `null` and is better expressed as
213 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
215 /// **Known problems:** None.
221 /// let a = 0 as *const u32;
224 /// let a = std::ptr::null::<u32>();
228 "using `0 as *{const, mut} T`"
231 declare_clippy_lint! {
232 /// **What it does:** Checks for (in-)equality comparisons on floating-point
233 /// value and constant, except in functions called `*eq*` (which probably
234 /// implement equality for a type involving floats).
236 /// **Why is this bad?** Floating point calculations are usually imprecise, so
237 /// asking if two values are *exactly* equal is asking for trouble. For a good
238 /// guide on what to do, see [the floating point
239 /// guide](http://www.floating-point-gui.de/errors/comparison).
241 /// **Known problems:** None.
245 /// let x: f64 = 1.0;
246 /// const ONE: f64 = 1.00;
249 /// if x == ONE { } // where both are floats
252 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
253 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
254 /// // let error_margin = std::f64::EPSILON;
255 /// if (x - ONE).abs() < error_margin { }
259 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
262 declare_lint_pass!(MiscLints => [
268 USED_UNDERSCORE_BINDING,
269 SHORT_CIRCUIT_STATEMENT,
274 impl<'tcx> LateLintPass<'tcx> for MiscLints {
277 cx: &LateContext<'tcx>,
279 decl: &'tcx FnDecl<'_>,
280 body: &'tcx Body<'_>,
284 if let FnKind::Closure = k {
285 // Does not apply to closures
288 if in_external_macro(cx.tcx.sess, span) {
291 for arg in iter_input_pats(decl, body) {
292 if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = arg.pat.kind {
297 "`ref` directly on a function argument is ignored. \
298 Consider using a reference type instead",
304 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
306 if !in_external_macro(cx.tcx.sess, stmt.span);
307 if let StmtKind::Local(ref local) = stmt.kind;
308 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
309 if let Some(ref init) = local.init;
310 if !higher::is_from_for_desugar(local);
311 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut;
313 // use the macro callsite when the init span (but not the whole local span)
314 // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
315 let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
316 Sugg::hir_with_macro_callsite(cx, init, "..")
318 Sugg::hir(cx, init, "..")
320 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
321 ("mut ", sugg_init.mut_addr())
323 ("", sugg_init.addr())
325 let tyopt = if let Some(ref ty) = local.ty {
326 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, ".."))
330 span_lint_hir_and_then(
335 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
337 diag.span_suggestion(
341 "let {name}{tyopt} = {initref};",
342 name=snippet(cx, name.span, ".."),
346 Applicability::MachineApplicable,
353 if let StmtKind::Semi(ref expr) = stmt.kind;
354 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.kind;
355 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
356 if let Some(sugg) = Sugg::hir_opt(cx, a);
358 span_lint_and_then(cx,
359 SHORT_CIRCUIT_STATEMENT,
361 "boolean short circuit operator in statement may be clearer using an explicit test",
363 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
364 diag.span_suggestion(
370 &snippet(cx, b.span, ".."),
372 Applicability::MachineApplicable, // snippet
379 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
381 ExprKind::Cast(ref e, ref ty) => {
382 check_cast(cx, expr.span, e, ty);
385 ExprKind::Binary(ref cmp, ref left, ref right) => {
386 check_binary(cx, expr, cmp, left, right);
391 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
392 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
395 let binding = match expr.kind {
396 ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
397 let binding = last_path_segment(qpath).ident.as_str();
398 if binding.starts_with('_') &&
399 !binding.starts_with("__") &&
400 binding != "_result" && // FIXME: #944
402 // don't lint if the declaration is in a macro
403 non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
410 ExprKind::Field(_, ident) => {
411 let name = ident.as_str();
412 if name.starts_with('_') && !name.starts_with("__") {
420 if let Some(binding) = binding {
423 USED_UNDERSCORE_BINDING,
426 "used binding `{}` which is prefixed with an underscore. A leading \
427 underscore signals that a binding will not be used",
435 fn get_lint_and_message(
436 is_comparing_constants: bool,
437 is_comparing_arrays: bool,
438 ) -> (&'static rustc_lint::Lint, &'static str) {
439 if is_comparing_constants {
442 if is_comparing_arrays {
443 "strict comparison of `f32` or `f64` constant arrays"
445 "strict comparison of `f32` or `f64` constant"
451 if is_comparing_arrays {
452 "strict comparison of `f32` or `f64` arrays"
454 "strict comparison of `f32` or `f64`"
460 fn check_nan(cx: &LateContext<'_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) {
462 if !in_constant(cx, cmp_expr.hir_id);
463 if let Some((value, _)) = constant(cx, cx.typeck_results(), expr);
465 Constant::F32(num) => num.is_nan(),
466 Constant::F64(num) => num.is_nan(),
474 "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead",
480 fn is_named_constant<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
481 if let Some((_, res)) = constant(cx, cx.typeck_results(), expr) {
488 fn is_allowed<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
489 match constant(cx, cx.typeck_results(), expr) {
490 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
491 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
492 Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f {
493 Constant::F32(f) => *f == 0.0 || (*f).is_infinite(),
494 Constant::F64(f) => *f == 0.0 || (*f).is_infinite(),
501 // Return true if `expr` is the result of `signum()` invoked on a float value.
502 fn is_signum(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
503 // The negation of a signum is still a signum
504 if let ExprKind::Unary(UnOp::Neg, ref child_expr) = expr.kind {
505 return is_signum(cx, &child_expr);
509 if let ExprKind::MethodCall(ref method_name, _, ref expressions, _) = expr.kind;
510 if sym!(signum) == method_name.ident.name;
511 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
514 return is_float(cx, &expressions[0]);
520 fn is_float(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
521 let value = &cx.typeck_results().expr_ty(expr).peel_refs().kind();
523 if let ty::Array(arr_ty, _) = value {
524 return matches!(arr_ty.kind(), ty::Float(_));
527 matches!(value, ty::Float(_))
530 fn is_array(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
531 matches!(&cx.typeck_results().expr_ty(expr).peel_refs().kind(), ty::Array(_, _))
534 fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) {
542 fn is_implemented(&self) -> bool {
543 self.ty_eq_other || self.other_eq_ty
547 fn symmetric_partial_eq<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, other: Ty<'tcx>) -> Option<EqImpl> {
548 cx.tcx.lang_items().eq_trait().map(|def_id| EqImpl {
549 ty_eq_other: implements_trait(cx, ty, def_id, &[other.into()]),
550 other_eq_ty: implements_trait(cx, other, def_id, &[ty.into()]),
554 let (arg_ty, snip) = match expr.kind {
555 ExprKind::MethodCall(.., ref args, _) if args.len() == 1 => {
557 if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
558 if is_diagnostic_assoc_item(cx, expr_def_id, sym::ToString)
559 || is_diagnostic_assoc_item(cx, expr_def_id, sym::ToOwned);
561 (cx.typeck_results().expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
567 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
568 if let ExprKind::Path(ref path) = path.kind {
569 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
570 (cx.typeck_results().expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
581 let other_ty = cx.typeck_results().expr_ty(other);
583 let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default();
584 let with_deref = arg_ty
586 .and_then(|tam| symmetric_partial_eq(cx, tam.ty, other_ty))
587 .unwrap_or_default();
589 if !with_deref.is_implemented() && !without_deref.is_implemented() {
593 let other_gets_derefed = matches!(other.kind, ExprKind::Unary(UnOp::Deref, _));
595 let lint_span = if other_gets_derefed {
596 expr.span.to(other.span)
605 "this creates an owned instance just for comparison",
607 // This also catches `PartialEq` implementations that call `to_owned`.
608 if other_gets_derefed {
609 diag.span_label(lint_span, "try implementing the comparison without allocating");
615 if with_deref.is_implemented() {
616 expr_snip = format!("*{}", snip);
617 eq_impl = with_deref;
619 expr_snip = snip.to_string();
620 eq_impl = without_deref;
625 if (eq_impl.ty_eq_other && left) || (eq_impl.other_eq_ty && !left) {
629 span = expr.span.to(other.span);
630 if eq_impl.ty_eq_other {
631 hint = format!("{} == {}", expr_snip, snippet(cx, other.span, ".."));
633 hint = format!("{} == {}", snippet(cx, other.span, ".."), expr_snip);
637 diag.span_suggestion(
641 Applicability::MachineApplicable, // snippet
647 /// Heuristic to see if an expression is used. Should be compatible with
648 /// `unused_variables`'s idea
649 /// of what it means for an expression to be "used".
650 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
651 get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
652 ExprKind::Assign(_, ref rhs, _) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
653 _ => is_used(cx, parent),
657 /// Tests whether an expression is in a macro expansion (e.g., something
658 /// generated by `#[derive(...)]` or the like).
659 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
660 use rustc_span::hygiene::MacroKind;
661 if expr.span.from_expansion() {
662 let data = expr.span.ctxt().outer_expn_data();
663 matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _))
669 /// Tests whether `res` is a variable defined outside a macro.
670 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
671 if let def::Res::Local(id) = res {
672 !cx.tcx.hir().span(id).from_expansion()
678 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
680 if let TyKind::Ptr(ref mut_ty) = ty.kind;
681 if let ExprKind::Lit(ref lit) = e.kind;
682 if let LitKind::Int(0, _) = lit.node;
683 if !in_constant(cx, e.hir_id);
685 let (msg, sugg_fn) = match mut_ty.mutbl {
686 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
687 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
690 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
691 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
692 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
693 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
695 // `MaybeIncorrect` as type inference may not work with the suggested code
696 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
698 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);
704 cx: &LateContext<'a>,
706 cmp: &rustc_span::source_map::Spanned<rustc_hir::BinOpKind>,
711 if op.is_comparison() {
712 check_nan(cx, left, expr);
713 check_nan(cx, right, expr);
714 check_to_owned(cx, left, right, true);
715 check_to_owned(cx, right, left, false);
717 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
718 if is_allowed(cx, left) || is_allowed(cx, right) {
722 // Allow comparing the results of signum()
723 if is_signum(cx, left) && is_signum(cx, right) {
727 if let Some(name) = get_item_name(cx, expr) {
728 let name = name.as_str();
729 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") || name.ends_with("_eq") {
733 let is_comparing_arrays = is_array(cx, left) || is_array(cx, right);
734 let (lint, msg) = get_lint_and_message(
735 is_named_constant(cx, left) || is_named_constant(cx, right),
738 span_lint_and_then(cx, lint, expr.span, msg, |diag| {
739 let lhs = Sugg::hir(cx, left, "..");
740 let rhs = Sugg::hir(cx, right, "..");
742 if !is_comparing_arrays {
743 diag.span_suggestion(
745 "consider comparing them within some margin of error",
747 "({}).abs() {} error_margin",
749 if op == BinOpKind::Eq { '<' } else { '>' }
751 Applicability::HasPlaceholders, // snippet
754 diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error_margin`");
756 } else if op == BinOpKind::Rem {
757 if is_integer_const(cx, right, 1) {
758 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
761 if let ty::Int(ity) = cx.typeck_results().expr_ty(right).kind() {
762 if is_integer_const(cx, right, unsext(cx.tcx, -1, *ity)) {
767 "any number modulo -1 will panic/overflow or result in 0",