1 use if_chain::if_chain;
2 use rustc_ast::ast::LitKind;
3 use rustc_errors::Applicability;
4 use rustc_hir::intravisit::FnKind;
6 def, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind, Stmt, StmtKind, Ty,
9 use rustc_lint::{LateContext, LateLintPass};
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.
42 /// fn foo(ref x: u8) -> bool {
48 "an entire binding declared as `ref`, in a function argument or a `let` statement"
51 declare_clippy_lint! {
52 /// **What it does:** Checks for comparisons to NaN.
54 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
55 /// even itself – so those comparisons are simply wrong.
57 /// **Known problems:** None.
63 /// if x == f32::NAN { }
67 "comparisons to `NAN`, which will always return false, probably not intended"
70 declare_clippy_lint! {
71 /// **What it does:** Checks for (in-)equality comparisons on floating-point
72 /// values (apart from zero), except in functions called `*eq*` (which probably
73 /// implement equality for a type involving floats).
75 /// **Why is this bad?** Floating point calculations are usually imprecise, so
76 /// asking if two values are *exactly* equal is asking for trouble. For a good
77 /// guide on what to do, see [the floating point
78 /// guide](http://www.floating-point-gui.de/errors/comparison).
80 /// **Known problems:** None.
84 /// let x = 1.2331f64;
85 /// let y = 1.2332f64;
86 /// if y == 1.23f64 { }
87 /// if y != x {} // where both are floats
91 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
94 declare_clippy_lint! {
95 /// **What it does:** Checks for conversions to owned values just for the sake
98 /// **Why is this bad?** The comparison can operate on a reference, so creating
99 /// an owned value effectively throws it away directly afterwards, which is
100 /// needlessly consuming code and heap space.
102 /// **Known problems:** None.
107 /// # let y = String::from("foo");
108 /// if x.to_owned() == y {}
110 /// Could be written as
113 /// # let y = String::from("foo");
118 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
121 declare_clippy_lint! {
122 /// **What it does:** Checks for getting the remainder of a division by one.
124 /// **Why is this bad?** The result can only ever be zero. No one will write
125 /// such code deliberately, unless trying to win an Underhanded Rust
126 /// Contest. Even for that contest, it's probably a bad idea. Use something more
129 /// **Known problems:** None.
138 "taking a number modulo 1, which always returns 0"
141 declare_clippy_lint! {
142 /// **What it does:** Checks for the use of bindings with a single leading
145 /// **Why is this bad?** A single leading underscore is usually used to indicate
146 /// that a binding will not be used. Using such a binding breaks this
149 /// **Known problems:** The lint does not work properly with desugaring and
150 /// macro, it has been allowed in the mean time.
155 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
156 /// // underscore. We should rename `_x` to `x`
158 pub USED_UNDERSCORE_BINDING,
160 "using a binding which is prefixed with an underscore"
163 declare_clippy_lint! {
164 /// **What it does:** Checks for the use of short circuit boolean conditions as
168 /// **Why is this bad?** Using a short circuit boolean condition as a statement
169 /// may hide the fact that the second part is executed or not depending on the
170 /// outcome of the first part.
172 /// **Known problems:** None.
176 /// f() && g(); // We should write `if f() { g(); }`.
178 pub SHORT_CIRCUIT_STATEMENT,
180 "using a short circuit boolean condition as a statement"
183 declare_clippy_lint! {
184 /// **What it does:** Catch casts from `0` to some pointer type
186 /// **Why is this bad?** This generally means `null` and is better expressed as
187 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
189 /// **Known problems:** None.
194 /// let a = 0 as *const u32;
198 "using `0 as *{const, mut} T`"
201 declare_clippy_lint! {
202 /// **What it does:** Checks for (in-)equality comparisons on floating-point
203 /// value and constant, except in functions called `*eq*` (which probably
204 /// implement equality for a type involving floats).
206 /// **Why is this bad?** Floating point calculations are usually imprecise, so
207 /// asking if two values are *exactly* equal is asking for trouble. For a good
208 /// guide on what to do, see [the floating point
209 /// guide](http://www.floating-point-gui.de/errors/comparison).
211 /// **Known problems:** None.
215 /// let x: f64 = 1.0;
216 /// const ONE: f64 = 1.00;
217 /// x == ONE; // where both are floats
221 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
224 declare_lint_pass!(MiscLints => [
230 USED_UNDERSCORE_BINDING,
231 SHORT_CIRCUIT_STATEMENT,
236 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints {
239 cx: &LateContext<'a, 'tcx>,
241 decl: &'tcx FnDecl<'_>,
242 body: &'tcx Body<'_>,
246 if let FnKind::Closure(_) = k {
247 // Does not apply to closures
250 for arg in iter_input_pats(decl, body) {
252 PatKind::Binding(BindingAnnotation::Ref, ..) | PatKind::Binding(BindingAnnotation::RefMut, ..) => {
257 "`ref` directly on a function argument is ignored. Consider using a reference type \
266 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
268 if let StmtKind::Local(ref local) = stmt.kind;
269 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
270 if let Some(ref init) = local.init;
271 if !higher::is_from_for_desugar(local);
273 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
274 let sugg_init = if init.span.from_expansion() {
275 Sugg::hir_with_macro_callsite(cx, init, "..")
277 Sugg::hir(cx, init, "..")
279 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
280 ("mut ", sugg_init.mut_addr())
282 ("", sugg_init.addr())
284 let tyopt = if let Some(ref ty) = local.ty {
285 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
289 span_lint_hir_and_then(
294 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
296 diag.span_suggestion(
300 "let {name}{tyopt} = {initref};",
301 name=snippet(cx, name.span, "_"),
305 Applicability::MachineApplicable,
313 if let StmtKind::Semi(ref expr) = stmt.kind;
314 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.kind;
315 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
316 if let Some(sugg) = Sugg::hir_opt(cx, a);
318 span_lint_and_then(cx,
319 SHORT_CIRCUIT_STATEMENT,
321 "boolean short circuit operator in statement may be clearer using an explicit test",
323 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
324 diag.span_suggestion(
330 &snippet(cx, b.span, ".."),
332 Applicability::MachineApplicable, // snippet
339 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
341 ExprKind::Cast(ref e, ref ty) => {
342 check_cast(cx, expr.span, e, ty);
345 ExprKind::Binary(ref cmp, ref left, ref right) => {
347 if op.is_comparison() {
348 check_nan(cx, left, expr);
349 check_nan(cx, right, expr);
350 check_to_owned(cx, left, right);
351 check_to_owned(cx, right, left);
353 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
354 if is_allowed(cx, left) || is_allowed(cx, right) {
358 // Allow comparing the results of signum()
359 if is_signum(cx, left) && is_signum(cx, right) {
363 if let Some(name) = get_item_name(cx, expr) {
364 let name = name.as_str();
368 || name.starts_with("eq_")
369 || name.ends_with("_eq")
374 let is_comparing_arrays = is_array(cx, left) || is_array(cx, right);
375 let (lint, msg) = get_lint_and_message(
376 is_named_constant(cx, left) || is_named_constant(cx, right),
379 span_lint_and_then(cx, lint, expr.span, msg, |diag| {
380 let lhs = Sugg::hir(cx, left, "..");
381 let rhs = Sugg::hir(cx, right, "..");
383 if !is_comparing_arrays {
384 diag.span_suggestion(
386 "consider comparing them within some error",
388 "({}).abs() {} error",
390 if op == BinOpKind::Eq { '<' } else { '>' }
392 Applicability::HasPlaceholders, // snippet
395 diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error`");
397 } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) {
398 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
403 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
404 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
407 let binding = match expr.kind {
408 ExprKind::Path(ref qpath) => {
409 let binding = last_path_segment(qpath).ident.as_str();
410 if binding.starts_with('_') &&
411 !binding.starts_with("__") &&
412 binding != "_result" && // FIXME: #944
414 // don't lint if the declaration is in a macro
415 non_macro_local(cx, cx.tables.qpath_res(qpath, expr.hir_id))
422 ExprKind::Field(_, ident) => {
423 let name = ident.as_str();
424 if name.starts_with('_') && !name.starts_with("__") {
432 if let Some(binding) = binding {
435 USED_UNDERSCORE_BINDING,
438 "used binding `{}` which is prefixed with an underscore. A leading \
439 underscore signals that a binding will not be used.",
447 fn get_lint_and_message(
448 is_comparing_constants: bool,
449 is_comparing_arrays: bool,
450 ) -> (&'static rustc_lint::Lint, &'static str) {
451 if is_comparing_constants {
454 if is_comparing_arrays {
455 "strict comparison of `f32` or `f64` constant arrays"
457 "strict comparison of `f32` or `f64` constant"
463 if is_comparing_arrays {
464 "strict comparison of `f32` or `f64` arrays"
466 "strict comparison of `f32` or `f64`"
472 fn check_nan(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) {
474 if !in_constant(cx, cmp_expr.hir_id);
475 if let Some((value, _)) = constant(cx, cx.tables, expr);
477 let needs_lint = match value {
478 Constant::F32(num) => num.is_nan(),
479 Constant::F64(num) => num.is_nan(),
488 "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead",
495 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> bool {
496 if let Some((_, res)) = constant(cx, cx.tables, expr) {
503 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> bool {
504 match constant(cx, cx.tables, expr) {
505 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
506 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
507 Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f {
508 Constant::F32(f) => *f == 0.0 || (*f).is_infinite(),
509 Constant::F64(f) => *f == 0.0 || (*f).is_infinite(),
516 // Return true if `expr` is the result of `signum()` invoked on a float value.
517 fn is_signum(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
518 // The negation of a signum is still a signum
519 if let ExprKind::Unary(UnOp::UnNeg, ref child_expr) = expr.kind {
520 return is_signum(cx, &child_expr);
524 if let ExprKind::MethodCall(ref method_name, _, ref expressions) = expr.kind;
525 if sym!(signum) == method_name.ident.name;
526 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
529 return is_float(cx, &expressions[0]);
535 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
536 let value = &walk_ptrs_ty(cx.tables.expr_ty(expr)).kind;
538 if let ty::Array(arr_ty, _) = value {
539 return matches!(arr_ty.kind, ty::Float(_));
542 matches!(value, ty::Float(_))
545 fn is_array(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
546 matches!(&walk_ptrs_ty(cx.tables.expr_ty(expr)).kind, ty::Array(_, _))
549 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr<'_>, other: &Expr<'_>) {
550 let (arg_ty, snip) = match expr.kind {
551 ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
552 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
553 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
558 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
559 if let ExprKind::Path(ref path) = path.kind {
560 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
561 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
572 let other_ty = cx.tables.expr_ty_adjusted(other);
573 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
578 let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
579 implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
581 let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
582 implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
584 let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
586 if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
590 let other_gets_derefed = match other.kind {
591 ExprKind::Unary(UnOp::UnDeref, _) => true,
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");
613 let try_hint = if deref_arg_impl_partial_eq_other {
614 // suggest deref on the left
617 // suggest dropping the to_owned on the left
621 diag.span_suggestion(
625 Applicability::MachineApplicable, // snippet
631 /// Heuristic to see if an expression is used. Should be compatible with
632 /// `unused_variables`'s idea
633 /// of what it means for an expression to be "used".
634 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
635 if let Some(parent) = get_parent_expr(cx, expr) {
637 ExprKind::Assign(_, ref rhs, _) | ExprKind::AssignOp(_, _, ref rhs) => {
638 SpanlessEq::new(cx).eq_expr(rhs, expr)
640 _ => is_used(cx, parent),
647 /// Tests whether an expression is in a macro expansion (e.g., something
648 /// generated by `#[derive(...)]` or the like).
649 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
650 use rustc_span::hygiene::MacroKind;
651 if expr.span.from_expansion() {
652 let data = expr.span.ctxt().outer_expn_data();
654 if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind {
664 /// Tests whether `res` is a variable defined outside a macro.
665 fn non_macro_local(cx: &LateContext<'_, '_>, res: def::Res) -> bool {
666 if let def::Res::Local(id) = res {
667 !cx.tcx.hir().span(id).from_expansion()
673 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr<'_>, ty: &Ty<'_>) {
675 if let TyKind::Ptr(ref mut_ty) = ty.kind;
676 if let ExprKind::Lit(ref lit) = e.kind;
677 if let LitKind::Int(0, _) = lit.node;
678 if !in_constant(cx, e.hir_id);
680 let (msg, sugg_fn) = match mut_ty.mutbl {
681 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
682 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
685 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
686 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
687 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
688 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
690 // `MaybeIncorrect` as type inference may not work with the suggested code
691 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
693 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);