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, is_copy};
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 clippy_utils::consts::{constant, Constant};
21 use clippy_utils::sugg::Sugg;
23 get_item_name, get_parent_expr, in_constant, is_integer_const, iter_input_pats, last_path_segment,
24 match_any_def_paths, path_def_id, paths, unsext, SpanlessEq,
27 declare_clippy_lint! {
29 /// Checks for function arguments and let bindings denoted as
32 /// ### Why is this bad?
33 /// The `ref` declaration makes the function take an owned
34 /// value, but turns the argument into a reference (which means that the value
35 /// is destroyed when exiting the function). This adds not much value: either
36 /// take a reference type, or take an owned value and create references in the
39 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
40 /// type of `x` is more obvious with the former.
42 /// ### Known problems
43 /// If the argument is dereferenced within the function,
44 /// removing the `ref` will lead to errors. This can be fixed by removing the
45 /// dereferences, e.g., changing `*x` to `x` within the function.
49 /// fn foo(ref _x: u8) {}
54 /// fn foo(_x: &u8) {}
56 #[clippy::version = "pre 1.29.0"]
59 "an entire binding declared as `ref`, in a function argument or a `let` statement"
62 declare_clippy_lint! {
64 /// Checks for comparisons to NaN.
66 /// ### Why is this bad?
67 /// NaN does not compare meaningfully to anything – not
68 /// even itself – so those comparisons are simply wrong.
73 /// if x == f32::NAN { }
81 #[clippy::version = "pre 1.29.0"]
84 "comparisons to `NAN`, which will always return false, probably not intended"
87 declare_clippy_lint! {
89 /// Checks for (in-)equality comparisons on floating-point
90 /// values (apart from zero), except in functions called `*eq*` (which probably
91 /// implement equality for a type involving floats).
93 /// ### Why is this bad?
94 /// Floating point calculations are usually imprecise, so
95 /// asking if two values are *exactly* equal is asking for trouble. For a good
96 /// guide on what to do, see [the floating point
97 /// guide](http://www.floating-point-gui.de/errors/comparison).
101 /// let x = 1.2331f64;
102 /// let y = 1.2332f64;
104 /// if y == 1.23f64 { }
105 /// if y != x {} // where both are floats
110 /// # let x = 1.2331f64;
111 /// # let y = 1.2332f64;
112 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
113 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
114 /// // let error_margin = std::f64::EPSILON;
115 /// if (y - 1.23f64).abs() < error_margin { }
116 /// if (y - x).abs() > error_margin { }
118 #[clippy::version = "pre 1.29.0"]
121 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
124 declare_clippy_lint! {
126 /// Checks for conversions to owned values just for the sake
129 /// ### Why is this bad?
130 /// The comparison can operate on a reference, so creating
131 /// an owned value effectively throws it away directly afterwards, which is
132 /// needlessly consuming code and heap space.
137 /// # let y = String::from("foo");
138 /// if x.to_owned() == y {}
144 /// # let y = String::from("foo");
147 #[clippy::version = "pre 1.29.0"]
150 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
153 declare_clippy_lint! {
155 /// Checks for getting the remainder of a division by one or minus
158 /// ### Why is this bad?
159 /// The result for a divisor of one can only ever be zero; for
160 /// minus one it can cause panic/overflow (if the left operand is the minimal value of
161 /// the respective integer type) or results in zero. No one will write such code
162 /// deliberately, unless trying to win an Underhanded Rust Contest. Even for that
163 /// contest, it's probably a bad idea. Use something more underhanded.
171 #[clippy::version = "pre 1.29.0"]
174 "taking a number modulo +/-1, which can either panic/overflow or always returns 0"
177 declare_clippy_lint! {
179 /// Checks for the use of bindings with a single leading
182 /// ### Why is this bad?
183 /// A single leading underscore is usually used to indicate
184 /// that a binding will not be used. Using such a binding breaks this
187 /// ### Known problems
188 /// The lint does not work properly with desugaring and
189 /// macro, it has been allowed in the mean time.
194 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
195 /// // underscore. We should rename `_x` to `x`
197 #[clippy::version = "pre 1.29.0"]
198 pub USED_UNDERSCORE_BINDING,
200 "using a binding which is prefixed with an underscore"
203 declare_clippy_lint! {
205 /// Checks for the use of short circuit boolean conditions as
209 /// ### Why is this bad?
210 /// Using a short circuit boolean condition as a statement
211 /// may hide the fact that the second part is executed or not depending on the
212 /// outcome of the first part.
216 /// f() && g(); // We should write `if f() { g(); }`.
218 #[clippy::version = "pre 1.29.0"]
219 pub SHORT_CIRCUIT_STATEMENT,
221 "using a short circuit boolean condition as a statement"
224 declare_clippy_lint! {
226 /// Catch casts from `0` to some pointer type
228 /// ### Why is this bad?
229 /// This generally means `null` and is better expressed as
230 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
234 /// let a = 0 as *const u32;
239 /// let a = std::ptr::null::<u32>();
241 #[clippy::version = "pre 1.29.0"]
244 "using `0 as *{const, mut} T`"
247 declare_clippy_lint! {
249 /// Checks for (in-)equality comparisons on floating-point
250 /// value and constant, except in functions called `*eq*` (which probably
251 /// implement equality for a type involving floats).
253 /// ### Why is this bad?
254 /// Floating point calculations are usually imprecise, so
255 /// asking if two values are *exactly* equal is asking for trouble. For a good
256 /// guide on what to do, see [the floating point
257 /// guide](http://www.floating-point-gui.de/errors/comparison).
261 /// let x: f64 = 1.0;
262 /// const ONE: f64 = 1.00;
264 /// if x == ONE { } // where both are floats
269 /// # let x: f64 = 1.0;
270 /// # const ONE: f64 = 1.00;
271 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
272 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
273 /// // let error_margin = std::f64::EPSILON;
274 /// if (x - ONE).abs() < error_margin { }
276 #[clippy::version = "pre 1.29.0"]
279 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
282 declare_lint_pass!(MiscLints => [
288 USED_UNDERSCORE_BINDING,
289 SHORT_CIRCUIT_STATEMENT,
294 impl<'tcx> LateLintPass<'tcx> for MiscLints {
297 cx: &LateContext<'tcx>,
299 decl: &'tcx FnDecl<'_>,
300 body: &'tcx Body<'_>,
304 if let FnKind::Closure = k {
305 // Does not apply to closures
308 if in_external_macro(cx.tcx.sess, span) {
311 for arg in iter_input_pats(decl, body) {
312 if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = arg.pat.kind {
317 "`ref` directly on a function argument is ignored. \
318 Consider using a reference type instead",
324 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
326 if !in_external_macro(cx.tcx.sess, stmt.span);
327 if let StmtKind::Local(local) = stmt.kind;
328 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
329 if let Some(init) = local.init;
330 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut;
332 // use the macro callsite when the init span (but not the whole local span)
333 // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
334 let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
335 Sugg::hir_with_macro_callsite(cx, init, "..")
337 Sugg::hir(cx, init, "..")
339 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
340 ("mut ", sugg_init.mut_addr())
342 ("", sugg_init.addr())
344 let tyopt = if let Some(ty) = local.ty {
345 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, ".."))
349 span_lint_hir_and_then(
354 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
356 diag.span_suggestion(
360 "let {name}{tyopt} = {initref};",
361 name=snippet(cx, name.span, ".."),
365 Applicability::MachineApplicable,
372 if let StmtKind::Semi(expr) = stmt.kind;
373 if let ExprKind::Binary(ref binop, a, b) = expr.kind;
374 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
375 if let Some(sugg) = Sugg::hir_opt(cx, a);
377 span_lint_hir_and_then(
379 SHORT_CIRCUIT_STATEMENT,
382 "boolean short circuit operator in statement may be clearer using an explicit test",
384 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
385 diag.span_suggestion(
391 &snippet(cx, b.span, ".."),
393 Applicability::MachineApplicable, // snippet
400 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
402 ExprKind::Cast(e, ty) => {
403 check_cast(cx, expr.span, e, ty);
406 ExprKind::Binary(ref cmp, left, right) => {
407 check_binary(cx, expr, cmp, left, right);
412 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
413 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
417 let binding = match expr.kind {
418 ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
419 let binding = last_path_segment(qpath).ident.as_str();
420 if binding.starts_with('_') &&
421 !binding.starts_with("__") &&
422 binding != "_result" && // FIXME: #944
424 // don't lint if the declaration is in a macro
425 non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
432 ExprKind::Field(_, ident) => {
434 let name = sym.as_str();
435 if name.starts_with('_') && !name.starts_with("__") {
443 if let Some(binding) = binding {
446 USED_UNDERSCORE_BINDING,
449 "used binding `{}` which is prefixed with an underscore. A leading \
450 underscore signals that a binding will not be used",
458 fn get_lint_and_message(
459 is_comparing_constants: bool,
460 is_comparing_arrays: bool,
461 ) -> (&'static rustc_lint::Lint, &'static str) {
462 if is_comparing_constants {
465 if is_comparing_arrays {
466 "strict comparison of `f32` or `f64` constant arrays"
468 "strict comparison of `f32` or `f64` constant"
474 if is_comparing_arrays {
475 "strict comparison of `f32` or `f64` arrays"
477 "strict comparison of `f32` or `f64`"
483 fn check_nan(cx: &LateContext<'_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) {
485 if !in_constant(cx, cmp_expr.hir_id);
486 if let Some((value, _)) = constant(cx, cx.typeck_results(), expr);
488 Constant::F32(num) => num.is_nan(),
489 Constant::F64(num) => num.is_nan(),
497 "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead",
503 fn is_named_constant<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
504 if let Some((_, res)) = constant(cx, cx.typeck_results(), expr) {
511 fn is_allowed<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
512 match constant(cx, cx.typeck_results(), expr) {
513 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
514 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
515 Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f {
516 Constant::F32(f) => *f == 0.0 || (*f).is_infinite(),
517 Constant::F64(f) => *f == 0.0 || (*f).is_infinite(),
524 // Return true if `expr` is the result of `signum()` invoked on a float value.
525 fn is_signum(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
526 // The negation of a signum is still a signum
527 if let ExprKind::Unary(UnOp::Neg, child_expr) = expr.kind {
528 return is_signum(cx, child_expr);
532 if let ExprKind::MethodCall(method_name, [ref self_arg, ..], _) = expr.kind;
533 if sym!(signum) == method_name.ident.name;
534 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
537 return is_float(cx, self_arg);
543 fn is_float(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
544 let value = &cx.typeck_results().expr_ty(expr).peel_refs().kind();
546 if let ty::Array(arr_ty, _) = value {
547 return matches!(arr_ty.kind(), ty::Float(_));
550 matches!(value, ty::Float(_))
553 fn is_array(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
554 matches!(&cx.typeck_results().expr_ty(expr).peel_refs().kind(), ty::Array(_, _))
557 #[expect(clippy::too_many_lines)]
558 fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) {
566 fn is_implemented(&self) -> bool {
567 self.ty_eq_other || self.other_eq_ty
571 fn symmetric_partial_eq<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, other: Ty<'tcx>) -> Option<EqImpl> {
572 cx.tcx.lang_items().eq_trait().map(|def_id| EqImpl {
573 ty_eq_other: implements_trait(cx, ty, def_id, &[other.into()]),
574 other_eq_ty: implements_trait(cx, other, def_id, &[ty.into()]),
578 let typeck = cx.typeck_results();
579 let (arg, arg_span) = match expr.kind {
580 ExprKind::MethodCall(.., [arg], _)
582 .type_dependent_def_id(expr.hir_id)
583 .and_then(|id| cx.tcx.trait_of_item(id))
584 .map_or(false, |id| {
585 matches!(cx.tcx.get_diagnostic_name(id), Some(sym::ToString | sym::ToOwned))
590 ExprKind::Call(path, [arg])
591 if path_def_id(cx, path)
592 .and_then(|id| match_any_def_paths(cx, id, &[&paths::FROM_STR_METHOD, &paths::FROM_FROM]))
593 .map_or(false, |idx| match idx {
595 1 => !is_copy(cx, typeck.expr_ty(expr)),
604 let arg_ty = typeck.expr_ty(arg);
605 let other_ty = typeck.expr_ty(other);
607 let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default();
608 let with_deref = arg_ty
610 .and_then(|tam| symmetric_partial_eq(cx, tam.ty, other_ty))
611 .unwrap_or_default();
613 if !with_deref.is_implemented() && !without_deref.is_implemented() {
617 let other_gets_derefed = matches!(other.kind, ExprKind::Unary(UnOp::Deref, _));
619 let lint_span = if other_gets_derefed {
620 expr.span.to(other.span)
629 "this creates an owned instance just for comparison",
631 // This also catches `PartialEq` implementations that call `to_owned`.
632 if other_gets_derefed {
633 diag.span_label(lint_span, "try implementing the comparison without allocating");
637 let arg_snip = snippet(cx, arg_span, "..");
640 if with_deref.is_implemented() {
641 expr_snip = format!("*{}", arg_snip);
642 eq_impl = with_deref;
644 expr_snip = arg_snip.to_string();
645 eq_impl = without_deref;
650 if (eq_impl.ty_eq_other && left) || (eq_impl.other_eq_ty && !left) {
654 span = expr.span.to(other.span);
656 let cmp_span = if other.span < expr.span {
657 other.span.between(expr.span)
659 expr.span.between(other.span)
661 if eq_impl.ty_eq_other {
665 snippet(cx, cmp_span, ".."),
666 snippet(cx, other.span, "..")
671 snippet(cx, other.span, ".."),
672 snippet(cx, cmp_span, ".."),
678 diag.span_suggestion(
682 Applicability::MachineApplicable, // snippet
688 /// Heuristic to see if an expression is used. Should be compatible with
689 /// `unused_variables`'s idea
690 /// of what it means for an expression to be "used".
691 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
692 get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
693 ExprKind::Assign(_, rhs, _) | ExprKind::AssignOp(_, _, rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
694 _ => is_used(cx, parent),
698 /// Tests whether an expression is in a macro expansion (e.g., something
699 /// generated by `#[derive(...)]` or the like).
700 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
701 use rustc_span::hygiene::MacroKind;
702 if expr.span.from_expansion() {
703 let data = expr.span.ctxt().outer_expn_data();
704 matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _))
710 /// Tests whether `res` is a variable defined outside a macro.
711 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
712 if let def::Res::Local(id) = res {
713 !cx.tcx.hir().span(id).from_expansion()
719 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
721 if let TyKind::Ptr(ref mut_ty) = ty.kind;
722 if let ExprKind::Lit(ref lit) = e.kind;
723 if let LitKind::Int(0, _) = lit.node;
724 if !in_constant(cx, e.hir_id);
726 let (msg, sugg_fn) = match mut_ty.mutbl {
727 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
728 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
731 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
732 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
733 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
734 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
736 // `MaybeIncorrect` as type inference may not work with the suggested code
737 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
739 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);
745 cx: &LateContext<'a>,
747 cmp: &rustc_span::source_map::Spanned<rustc_hir::BinOpKind>,
752 if op.is_comparison() {
753 check_nan(cx, left, expr);
754 check_nan(cx, right, expr);
755 check_to_owned(cx, left, right, true);
756 check_to_owned(cx, right, left, false);
758 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
759 if is_allowed(cx, left) || is_allowed(cx, right) {
763 // Allow comparing the results of signum()
764 if is_signum(cx, left) && is_signum(cx, right) {
768 if let Some(name) = get_item_name(cx, expr) {
769 let name = name.as_str();
770 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") || name.ends_with("_eq") {
774 let is_comparing_arrays = is_array(cx, left) || is_array(cx, right);
775 let (lint, msg) = get_lint_and_message(
776 is_named_constant(cx, left) || is_named_constant(cx, right),
779 span_lint_and_then(cx, lint, expr.span, msg, |diag| {
780 let lhs = Sugg::hir(cx, left, "..");
781 let rhs = Sugg::hir(cx, right, "..");
783 if !is_comparing_arrays {
784 diag.span_suggestion(
786 "consider comparing them within some margin of error",
788 "({}).abs() {} error_margin",
790 if op == BinOpKind::Eq { '<' } else { '>' }
792 Applicability::HasPlaceholders, // snippet
795 diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error_margin`");
797 } else if op == BinOpKind::Rem {
798 if is_integer_const(cx, right, 1) {
799 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
802 if let ty::Int(ity) = cx.typeck_results().expr_ty(right).kind() {
803 if is_integer_const(cx, right, unsext(cx.tcx, -1, *ity)) {
808 "any number modulo -1 will panic/overflow or result in 0",