1 use if_chain::if_chain;
2 use rustc_ast::ast::LitKind;
3 use rustc_errors::Applicability;
4 use rustc_hir::intravisit::FnKind;
6 self as hir, def, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind, Stmt,
7 StmtKind, TyKind, UnOp,
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::{self, Ty};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::hygiene::DesugaringKind;
13 use rustc_span::source_map::{ExpnKind, Span};
15 use crate::consts::{constant, Constant};
16 use crate::utils::sugg::Sugg;
18 get_item_name, get_parent_expr, higher, implements_trait, in_constant, is_integer_const, iter_input_pats,
19 last_path_segment, match_qpath, match_trait_method, paths, snippet, snippet_opt, span_lint, span_lint_and_sugg,
20 span_lint_and_then, span_lint_hir_and_then, walk_ptrs_ty, SpanlessEq,
23 declare_clippy_lint! {
24 /// **What it does:** Checks for function arguments and let bindings denoted as
27 /// **Why is this bad?** The `ref` declaration makes the function take an owned
28 /// value, but turns the argument into a reference (which means that the value
29 /// is destroyed when exiting the function). This adds not much value: either
30 /// take a reference type, or take an owned value and create references in the
33 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
34 /// type of `x` is more obvious with the former.
36 /// **Known problems:** If the argument is dereferenced within the function,
37 /// removing the `ref` will lead to errors. This can be fixed by removing the
38 /// dereferences, e.g., changing `*x` to `x` within the function.
43 /// fn foo(ref x: u8) -> bool {
48 /// fn foo(x: &u8) -> bool {
54 "an entire binding declared as `ref`, in a function argument or a `let` statement"
57 declare_clippy_lint! {
58 /// **What it does:** Checks for comparisons to NaN.
60 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
61 /// even itself – so those comparisons are simply wrong.
63 /// **Known problems:** None.
70 /// if x == f32::NAN { }
77 "comparisons to `NAN`, which will always return false, probably not intended"
80 declare_clippy_lint! {
81 /// **What it does:** Checks for (in-)equality comparisons on floating-point
82 /// values (apart from zero), except in functions called `*eq*` (which probably
83 /// implement equality for a type involving floats).
85 /// **Why is this bad?** Floating point calculations are usually imprecise, so
86 /// asking if two values are *exactly* equal is asking for trouble. For a good
87 /// guide on what to do, see [the floating point
88 /// guide](http://www.floating-point-gui.de/errors/comparison).
90 /// **Known problems:** None.
94 /// let x = 1.2331f64;
95 /// let y = 1.2332f64;
98 /// if y == 1.23f64 { }
99 /// if y != x {} // where both are floats
102 /// let error = 0.01f64; // Use an epsilon for comparison
103 /// if (y - 1.23f64).abs() < error { }
104 /// if (y - x).abs() > error { }
108 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
111 declare_clippy_lint! {
112 /// **What it does:** Checks for conversions to owned values just for the sake
115 /// **Why is this bad?** The comparison can operate on a reference, so creating
116 /// an owned value effectively throws it away directly afterwards, which is
117 /// needlessly consuming code and heap space.
119 /// **Known problems:** None.
124 /// # let y = String::from("foo");
125 /// if x.to_owned() == y {}
127 /// Could be written as
130 /// # let y = String::from("foo");
135 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
138 declare_clippy_lint! {
139 /// **What it does:** Checks for getting the remainder of a division by one.
141 /// **Why is this bad?** The result can only ever be zero. No one will write
142 /// such code deliberately, unless trying to win an Underhanded Rust
143 /// Contest. Even for that contest, it's probably a bad idea. Use something more
146 /// **Known problems:** None.
155 "taking a number modulo 1, which always returns 0"
158 declare_clippy_lint! {
159 /// **What it does:** Checks for the use of bindings with a single leading
162 /// **Why is this bad?** A single leading underscore is usually used to indicate
163 /// that a binding will not be used. Using such a binding breaks this
166 /// **Known problems:** The lint does not work properly with desugaring and
167 /// macro, it has been allowed in the mean time.
172 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
173 /// // underscore. We should rename `_x` to `x`
175 pub USED_UNDERSCORE_BINDING,
177 "using a binding which is prefixed with an underscore"
180 declare_clippy_lint! {
181 /// **What it does:** Checks for the use of short circuit boolean conditions as
185 /// **Why is this bad?** Using a short circuit boolean condition as a statement
186 /// may hide the fact that the second part is executed or not depending on the
187 /// outcome of the first part.
189 /// **Known problems:** None.
193 /// f() && g(); // We should write `if f() { g(); }`.
195 pub SHORT_CIRCUIT_STATEMENT,
197 "using a short circuit boolean condition as a statement"
200 declare_clippy_lint! {
201 /// **What it does:** Catch casts from `0` to some pointer type
203 /// **Why is this bad?** This generally means `null` and is better expressed as
204 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
206 /// **Known problems:** None.
212 /// let a = 0 as *const u32;
215 /// let a = std::ptr::null::<u32>();
219 "using `0 as *{const, mut} T`"
222 declare_clippy_lint! {
223 /// **What it does:** Checks for (in-)equality comparisons on floating-point
224 /// value and constant, except in functions called `*eq*` (which probably
225 /// implement equality for a type involving floats).
227 /// **Why is this bad?** Floating point calculations are usually imprecise, so
228 /// asking if two values are *exactly* equal is asking for trouble. For a good
229 /// guide on what to do, see [the floating point
230 /// guide](http://www.floating-point-gui.de/errors/comparison).
232 /// **Known problems:** None.
236 /// let x: f64 = 1.0;
237 /// const ONE: f64 = 1.00;
240 /// if x == ONE { } // where both are floats
243 /// let error = 0.1f64; // Use an epsilon for comparison
244 /// if (x - ONE).abs() < error { }
248 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
251 declare_lint_pass!(MiscLints => [
257 USED_UNDERSCORE_BINDING,
258 SHORT_CIRCUIT_STATEMENT,
263 impl<'tcx> LateLintPass<'tcx> for MiscLints {
266 cx: &LateContext<'tcx>,
268 decl: &'tcx FnDecl<'_>,
269 body: &'tcx Body<'_>,
273 if let FnKind::Closure(_) = k {
274 // Does not apply to closures
277 for arg in iter_input_pats(decl, body) {
278 if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = arg.pat.kind {
283 "`ref` directly on a function argument is ignored. \
284 Consider using a reference type instead.",
290 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
292 if let StmtKind::Local(ref local) = stmt.kind;
293 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
294 if let Some(ref init) = local.init;
295 if !higher::is_from_for_desugar(local);
297 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
298 let sugg_init = if init.span.from_expansion() {
299 Sugg::hir_with_macro_callsite(cx, init, "..")
301 Sugg::hir(cx, init, "..")
303 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
304 ("mut ", sugg_init.mut_addr())
306 ("", sugg_init.addr())
308 let tyopt = if let Some(ref ty) = local.ty {
309 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
313 span_lint_hir_and_then(
318 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
320 diag.span_suggestion(
324 "let {name}{tyopt} = {initref};",
325 name=snippet(cx, name.span, "_"),
329 Applicability::MachineApplicable,
337 if let StmtKind::Semi(ref expr) = stmt.kind;
338 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.kind;
339 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
340 if let Some(sugg) = Sugg::hir_opt(cx, a);
342 span_lint_and_then(cx,
343 SHORT_CIRCUIT_STATEMENT,
345 "boolean short circuit operator in statement may be clearer using an explicit test",
347 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
348 diag.span_suggestion(
354 &snippet(cx, b.span, ".."),
356 Applicability::MachineApplicable, // snippet
363 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
365 ExprKind::Cast(ref e, ref ty) => {
366 check_cast(cx, expr.span, e, ty);
369 ExprKind::Binary(ref cmp, ref left, ref right) => {
371 if op.is_comparison() {
372 check_nan(cx, left, expr);
373 check_nan(cx, right, expr);
374 check_to_owned(cx, left, right, true);
375 check_to_owned(cx, right, left, false);
377 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
378 if is_allowed(cx, left) || is_allowed(cx, right) {
382 // Allow comparing the results of signum()
383 if is_signum(cx, left) && is_signum(cx, right) {
387 if let Some(name) = get_item_name(cx, expr) {
388 let name = name.as_str();
392 || name.starts_with("eq_")
393 || name.ends_with("_eq")
398 let is_comparing_arrays = is_array(cx, left) || is_array(cx, right);
399 let (lint, msg) = get_lint_and_message(
400 is_named_constant(cx, left) || is_named_constant(cx, right),
403 span_lint_and_then(cx, lint, expr.span, msg, |diag| {
404 let lhs = Sugg::hir(cx, left, "..");
405 let rhs = Sugg::hir(cx, right, "..");
407 if !is_comparing_arrays {
408 diag.span_suggestion(
410 "consider comparing them within some error",
412 "({}).abs() {} error",
414 if op == BinOpKind::Eq { '<' } else { '>' }
416 Applicability::HasPlaceholders, // snippet
419 diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error`");
421 } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) {
422 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
427 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
428 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
431 let binding = match expr.kind {
432 ExprKind::Path(ref qpath) => {
433 let binding = last_path_segment(qpath).ident.as_str();
434 if binding.starts_with('_') &&
435 !binding.starts_with("__") &&
436 binding != "_result" && // FIXME: #944
438 // don't lint if the declaration is in a macro
439 non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
446 ExprKind::Field(_, ident) => {
447 let name = ident.as_str();
448 if name.starts_with('_') && !name.starts_with("__") {
456 if let Some(binding) = binding {
459 USED_UNDERSCORE_BINDING,
462 "used binding `{}` which is prefixed with an underscore. A leading \
463 underscore signals that a binding will not be used.",
471 fn get_lint_and_message(
472 is_comparing_constants: bool,
473 is_comparing_arrays: bool,
474 ) -> (&'static rustc_lint::Lint, &'static str) {
475 if is_comparing_constants {
478 if is_comparing_arrays {
479 "strict comparison of `f32` or `f64` constant arrays"
481 "strict comparison of `f32` or `f64` constant"
487 if is_comparing_arrays {
488 "strict comparison of `f32` or `f64` arrays"
490 "strict comparison of `f32` or `f64`"
496 fn check_nan(cx: &LateContext<'_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) {
498 if !in_constant(cx, cmp_expr.hir_id);
499 if let Some((value, _)) = constant(cx, cx.tables(), expr);
501 let needs_lint = match value {
502 Constant::F32(num) => num.is_nan(),
503 Constant::F64(num) => num.is_nan(),
512 "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead",
519 fn is_named_constant<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
520 if let Some((_, res)) = constant(cx, cx.tables(), expr) {
527 fn is_allowed<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
528 match constant(cx, cx.tables(), expr) {
529 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
530 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
531 Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f {
532 Constant::F32(f) => *f == 0.0 || (*f).is_infinite(),
533 Constant::F64(f) => *f == 0.0 || (*f).is_infinite(),
540 // Return true if `expr` is the result of `signum()` invoked on a float value.
541 fn is_signum(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
542 // The negation of a signum is still a signum
543 if let ExprKind::Unary(UnOp::UnNeg, ref child_expr) = expr.kind {
544 return is_signum(cx, &child_expr);
548 if let ExprKind::MethodCall(ref method_name, _, ref expressions, _) = expr.kind;
549 if sym!(signum) == method_name.ident.name;
550 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
553 return is_float(cx, &expressions[0]);
559 fn is_float(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
560 let value = &walk_ptrs_ty(cx.tables().expr_ty(expr)).kind;
562 if let ty::Array(arr_ty, _) = value {
563 return matches!(arr_ty.kind, ty::Float(_));
566 matches!(value, ty::Float(_))
569 fn is_array(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
570 matches!(&walk_ptrs_ty(cx.tables().expr_ty(expr)).kind, ty::Array(_, _))
573 fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) {
581 fn is_implemented(&self) -> bool {
582 self.ty_eq_other || self.other_eq_ty
586 fn symmetric_partial_eq<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, other: Ty<'tcx>) -> Option<EqImpl> {
587 cx.tcx.lang_items().eq_trait().map(|def_id| EqImpl {
588 ty_eq_other: implements_trait(cx, ty, def_id, &[other.into()]),
589 other_eq_ty: implements_trait(cx, other, def_id, &[ty.into()]),
593 let (arg_ty, snip) = match expr.kind {
594 ExprKind::MethodCall(.., ref args, _) if args.len() == 1 => {
595 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
596 (cx.tables().expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
601 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
602 if let ExprKind::Path(ref path) = path.kind {
603 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
604 (cx.tables().expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
615 let other_ty = cx.tables().expr_ty(other);
617 let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default();
618 let with_deref = arg_ty
620 .and_then(|tam| symmetric_partial_eq(cx, tam.ty, other_ty))
621 .unwrap_or_default();
623 if !with_deref.is_implemented() && !without_deref.is_implemented() {
627 let other_gets_derefed = matches!(other.kind, ExprKind::Unary(UnOp::UnDeref, _));
629 let lint_span = if other_gets_derefed {
630 expr.span.to(other.span)
639 "this creates an owned instance just for comparison",
641 // This also catches `PartialEq` implementations that call `to_owned`.
642 if other_gets_derefed {
643 diag.span_label(lint_span, "try implementing the comparison without allocating");
649 if with_deref.is_implemented() {
650 expr_snip = format!("*{}", snip);
651 eq_impl = with_deref;
653 expr_snip = snip.to_string();
654 eq_impl = without_deref;
659 if (eq_impl.ty_eq_other && left) || (eq_impl.other_eq_ty && !left) {
663 span = expr.span.to(other.span);
664 if eq_impl.ty_eq_other {
665 hint = format!("{} == {}", expr_snip, snippet(cx, other.span, ".."));
667 hint = format!("{} == {}", snippet(cx, other.span, ".."), expr_snip);
671 diag.span_suggestion(
675 Applicability::MachineApplicable, // snippet
681 /// Heuristic to see if an expression is used. Should be compatible with
682 /// `unused_variables`'s idea
683 /// of what it means for an expression to be "used".
684 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
685 get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
686 ExprKind::Assign(_, ref rhs, _) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
687 _ => is_used(cx, parent),
691 /// Tests whether an expression is in a macro expansion (e.g., something
692 /// generated by `#[derive(...)]` or the like).
693 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
694 use rustc_span::hygiene::MacroKind;
695 if expr.span.from_expansion() {
696 let data = expr.span.ctxt().outer_expn_data();
697 matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _))
703 /// Tests whether `res` is a variable defined outside a macro.
704 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
705 if let def::Res::Local(id) = res {
706 !cx.tcx.hir().span(id).from_expansion()
712 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
714 if let TyKind::Ptr(ref mut_ty) = ty.kind;
715 if let ExprKind::Lit(ref lit) = e.kind;
716 if let LitKind::Int(0, _) = lit.node;
717 if !in_constant(cx, e.hir_id);
719 let (msg, sugg_fn) = match mut_ty.mutbl {
720 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
721 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
724 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
725 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
726 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
727 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
729 // `MaybeIncorrect` as type inference may not work with the suggested code
730 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
732 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);