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::lint::in_external_macro;
11 use rustc_middle::ty::{self, Ty};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::hygiene::DesugaringKind;
14 use rustc_span::source_map::{ExpnKind, Span};
16 use crate::consts::{constant, Constant};
17 use crate::utils::sugg::Sugg;
19 get_item_name, get_parent_expr, higher, implements_trait, in_constant, is_integer_const, iter_input_pats,
20 last_path_segment, match_qpath, match_trait_method, paths, snippet, snippet_opt, span_lint, span_lint_and_sugg,
21 span_lint_and_then, span_lint_hir_and_then, SpanlessEq,
24 declare_clippy_lint! {
25 /// **What it does:** Checks for function arguments and let bindings denoted as
28 /// **Why is this bad?** The `ref` declaration makes the function take an owned
29 /// value, but turns the argument into a reference (which means that the value
30 /// is destroyed when exiting the function). This adds not much value: either
31 /// take a reference type, or take an owned value and create references in the
34 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
35 /// type of `x` is more obvious with the former.
37 /// **Known problems:** If the argument is dereferenced within the function,
38 /// removing the `ref` will lead to errors. This can be fixed by removing the
39 /// dereferences, e.g., changing `*x` to `x` within the function.
44 /// fn foo(ref x: u8) -> bool {
49 /// fn foo(x: &u8) -> bool {
55 "an entire binding declared as `ref`, in a function argument or a `let` statement"
58 declare_clippy_lint! {
59 /// **What it does:** Checks for comparisons to NaN.
61 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
62 /// even itself – so those comparisons are simply wrong.
64 /// **Known problems:** None.
71 /// if x == f32::NAN { }
78 "comparisons to `NAN`, which will always return false, probably not intended"
81 declare_clippy_lint! {
82 /// **What it does:** Checks for (in-)equality comparisons on floating-point
83 /// values (apart from zero), except in functions called `*eq*` (which probably
84 /// implement equality for a type involving floats).
86 /// **Why is this bad?** Floating point calculations are usually imprecise, so
87 /// asking if two values are *exactly* equal is asking for trouble. For a good
88 /// guide on what to do, see [the floating point
89 /// guide](http://www.floating-point-gui.de/errors/comparison).
91 /// **Known problems:** None.
95 /// let x = 1.2331f64;
96 /// let y = 1.2332f64;
99 /// if y == 1.23f64 { }
100 /// if y != x {} // where both are floats
103 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
104 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
105 /// // let error_margin = std::f64::EPSILON;
106 /// if (y - 1.23f64).abs() < error_margin { }
107 /// if (y - x).abs() > error_margin { }
111 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
114 declare_clippy_lint! {
115 /// **What it does:** Checks for conversions to owned values just for the sake
118 /// **Why is this bad?** The comparison can operate on a reference, so creating
119 /// an owned value effectively throws it away directly afterwards, which is
120 /// needlessly consuming code and heap space.
122 /// **Known problems:** None.
127 /// # let y = String::from("foo");
128 /// if x.to_owned() == y {}
130 /// Could be written as
133 /// # let y = String::from("foo");
138 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
141 declare_clippy_lint! {
142 /// **What it does:** Checks for getting the remainder of a division by one.
144 /// **Why is this bad?** The result can only ever be zero. No one will write
145 /// such code deliberately, unless trying to win an Underhanded Rust
146 /// Contest. Even for that contest, it's probably a bad idea. Use something more
149 /// **Known problems:** None.
158 "taking a number modulo 1, which always returns 0"
161 declare_clippy_lint! {
162 /// **What it does:** Checks for the use of bindings with a single leading
165 /// **Why is this bad?** A single leading underscore is usually used to indicate
166 /// that a binding will not be used. Using such a binding breaks this
169 /// **Known problems:** The lint does not work properly with desugaring and
170 /// macro, it has been allowed in the mean time.
175 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
176 /// // underscore. We should rename `_x` to `x`
178 pub USED_UNDERSCORE_BINDING,
180 "using a binding which is prefixed with an underscore"
183 declare_clippy_lint! {
184 /// **What it does:** Checks for the use of short circuit boolean conditions as
188 /// **Why is this bad?** Using a short circuit boolean condition as a statement
189 /// may hide the fact that the second part is executed or not depending on the
190 /// outcome of the first part.
192 /// **Known problems:** None.
196 /// f() && g(); // We should write `if f() { g(); }`.
198 pub SHORT_CIRCUIT_STATEMENT,
200 "using a short circuit boolean condition as a statement"
203 declare_clippy_lint! {
204 /// **What it does:** Catch casts from `0` to some pointer type
206 /// **Why is this bad?** This generally means `null` and is better expressed as
207 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
209 /// **Known problems:** None.
215 /// let a = 0 as *const u32;
218 /// let a = std::ptr::null::<u32>();
222 "using `0 as *{const, mut} T`"
225 declare_clippy_lint! {
226 /// **What it does:** Checks for (in-)equality comparisons on floating-point
227 /// value and constant, except in functions called `*eq*` (which probably
228 /// implement equality for a type involving floats).
230 /// **Why is this bad?** Floating point calculations are usually imprecise, so
231 /// asking if two values are *exactly* equal is asking for trouble. For a good
232 /// guide on what to do, see [the floating point
233 /// guide](http://www.floating-point-gui.de/errors/comparison).
235 /// **Known problems:** None.
239 /// let x: f64 = 1.0;
240 /// const ONE: f64 = 1.00;
243 /// if x == ONE { } // where both are floats
246 /// let error_margin = f64::EPSILON; // Use an epsilon for comparison
247 /// // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
248 /// // let error_margin = std::f64::EPSILON;
249 /// if (x - ONE).abs() < error_margin { }
253 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
256 declare_lint_pass!(MiscLints => [
262 USED_UNDERSCORE_BINDING,
263 SHORT_CIRCUIT_STATEMENT,
268 impl<'tcx> LateLintPass<'tcx> for MiscLints {
271 cx: &LateContext<'tcx>,
273 decl: &'tcx FnDecl<'_>,
274 body: &'tcx Body<'_>,
278 if let FnKind::Closure(_) = k {
279 // Does not apply to closures
282 if in_external_macro(cx.tcx.sess, span) {
285 for arg in iter_input_pats(decl, body) {
286 if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = arg.pat.kind {
291 "`ref` directly on a function argument is ignored. \
292 Consider using a reference type instead.",
298 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
300 if !in_external_macro(cx.tcx.sess, stmt.span);
301 if let StmtKind::Local(ref local) = stmt.kind;
302 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
303 if let Some(ref init) = local.init;
304 if !higher::is_from_for_desugar(local);
306 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
307 // use the macro callsite when the init span (but not the whole local span)
308 // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
309 let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
310 Sugg::hir_with_macro_callsite(cx, init, "..")
312 Sugg::hir(cx, init, "..")
314 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
315 ("mut ", sugg_init.mut_addr())
317 ("", sugg_init.addr())
319 let tyopt = if let Some(ref ty) = local.ty {
320 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, ".."))
324 span_lint_hir_and_then(
329 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
331 diag.span_suggestion(
335 "let {name}{tyopt} = {initref};",
336 name=snippet(cx, name.span, ".."),
340 Applicability::MachineApplicable,
348 if let StmtKind::Semi(ref expr) = stmt.kind;
349 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.kind;
350 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
351 if let Some(sugg) = Sugg::hir_opt(cx, a);
353 span_lint_and_then(cx,
354 SHORT_CIRCUIT_STATEMENT,
356 "boolean short circuit operator in statement may be clearer using an explicit test",
358 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
359 diag.span_suggestion(
365 &snippet(cx, b.span, ".."),
367 Applicability::MachineApplicable, // snippet
374 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
376 ExprKind::Cast(ref e, ref ty) => {
377 check_cast(cx, expr.span, e, ty);
380 ExprKind::Binary(ref cmp, ref left, ref right) => {
382 if op.is_comparison() {
383 check_nan(cx, left, expr);
384 check_nan(cx, right, expr);
385 check_to_owned(cx, left, right, true);
386 check_to_owned(cx, right, left, false);
388 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
389 if is_allowed(cx, left) || is_allowed(cx, right) {
393 // Allow comparing the results of signum()
394 if is_signum(cx, left) && is_signum(cx, right) {
398 if let Some(name) = get_item_name(cx, expr) {
399 let name = name.as_str();
403 || name.starts_with("eq_")
404 || name.ends_with("_eq")
409 let is_comparing_arrays = is_array(cx, left) || is_array(cx, right);
410 let (lint, msg) = get_lint_and_message(
411 is_named_constant(cx, left) || is_named_constant(cx, right),
414 span_lint_and_then(cx, lint, expr.span, msg, |diag| {
415 let lhs = Sugg::hir(cx, left, "..");
416 let rhs = Sugg::hir(cx, right, "..");
418 if !is_comparing_arrays {
419 diag.span_suggestion(
421 "consider comparing them within some margin of error",
423 "({}).abs() {} error_margin",
425 if op == BinOpKind::Eq { '<' } else { '>' }
427 Applicability::HasPlaceholders, // snippet
430 diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error_margin`");
432 } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) {
433 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
438 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
439 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
442 let binding = match expr.kind {
443 ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
444 let binding = last_path_segment(qpath).ident.as_str();
445 if binding.starts_with('_') &&
446 !binding.starts_with("__") &&
447 binding != "_result" && // FIXME: #944
449 // don't lint if the declaration is in a macro
450 non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
457 ExprKind::Field(_, ident) => {
458 let name = ident.as_str();
459 if name.starts_with('_') && !name.starts_with("__") {
467 if let Some(binding) = binding {
470 USED_UNDERSCORE_BINDING,
473 "used binding `{}` which is prefixed with an underscore. A leading \
474 underscore signals that a binding will not be used.",
482 fn get_lint_and_message(
483 is_comparing_constants: bool,
484 is_comparing_arrays: bool,
485 ) -> (&'static rustc_lint::Lint, &'static str) {
486 if is_comparing_constants {
489 if is_comparing_arrays {
490 "strict comparison of `f32` or `f64` constant arrays"
492 "strict comparison of `f32` or `f64` constant"
498 if is_comparing_arrays {
499 "strict comparison of `f32` or `f64` arrays"
501 "strict comparison of `f32` or `f64`"
507 fn check_nan(cx: &LateContext<'_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) {
509 if !in_constant(cx, cmp_expr.hir_id);
510 if let Some((value, _)) = constant(cx, cx.typeck_results(), expr);
512 let needs_lint = match value {
513 Constant::F32(num) => num.is_nan(),
514 Constant::F64(num) => num.is_nan(),
523 "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead",
530 fn is_named_constant<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
531 if let Some((_, res)) = constant(cx, cx.typeck_results(), expr) {
538 fn is_allowed<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
539 match constant(cx, cx.typeck_results(), expr) {
540 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
541 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
542 Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f {
543 Constant::F32(f) => *f == 0.0 || (*f).is_infinite(),
544 Constant::F64(f) => *f == 0.0 || (*f).is_infinite(),
551 // Return true if `expr` is the result of `signum()` invoked on a float value.
552 fn is_signum(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
553 // The negation of a signum is still a signum
554 if let ExprKind::Unary(UnOp::UnNeg, ref child_expr) = expr.kind {
555 return is_signum(cx, &child_expr);
559 if let ExprKind::MethodCall(ref method_name, _, ref expressions, _) = expr.kind;
560 if sym!(signum) == method_name.ident.name;
561 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
564 return is_float(cx, &expressions[0]);
570 fn is_float(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
571 let value = &cx.typeck_results().expr_ty(expr).peel_refs().kind();
573 if let ty::Array(arr_ty, _) = value {
574 return matches!(arr_ty.kind(), ty::Float(_));
577 matches!(value, ty::Float(_))
580 fn is_array(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
581 matches!(&cx.typeck_results().expr_ty(expr).peel_refs().kind(), ty::Array(_, _))
584 fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) {
592 fn is_implemented(&self) -> bool {
593 self.ty_eq_other || self.other_eq_ty
597 fn symmetric_partial_eq<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, other: Ty<'tcx>) -> Option<EqImpl> {
598 cx.tcx.lang_items().eq_trait().map(|def_id| EqImpl {
599 ty_eq_other: implements_trait(cx, ty, def_id, &[other.into()]),
600 other_eq_ty: implements_trait(cx, other, def_id, &[ty.into()]),
604 let (arg_ty, snip) = match expr.kind {
605 ExprKind::MethodCall(.., ref args, _) if args.len() == 1 => {
606 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
607 (cx.typeck_results().expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
612 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
613 if let ExprKind::Path(ref path) = path.kind {
614 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
615 (cx.typeck_results().expr_ty(&v[0]), snippet(cx, v[0].span, ".."))
626 let other_ty = cx.typeck_results().expr_ty(other);
628 let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default();
629 let with_deref = arg_ty
631 .and_then(|tam| symmetric_partial_eq(cx, tam.ty, other_ty))
632 .unwrap_or_default();
634 if !with_deref.is_implemented() && !without_deref.is_implemented() {
638 let other_gets_derefed = matches!(other.kind, ExprKind::Unary(UnOp::UnDeref, _));
640 let lint_span = if other_gets_derefed {
641 expr.span.to(other.span)
650 "this creates an owned instance just for comparison",
652 // This also catches `PartialEq` implementations that call `to_owned`.
653 if other_gets_derefed {
654 diag.span_label(lint_span, "try implementing the comparison without allocating");
660 if with_deref.is_implemented() {
661 expr_snip = format!("*{}", snip);
662 eq_impl = with_deref;
664 expr_snip = snip.to_string();
665 eq_impl = without_deref;
670 if (eq_impl.ty_eq_other && left) || (eq_impl.other_eq_ty && !left) {
674 span = expr.span.to(other.span);
675 if eq_impl.ty_eq_other {
676 hint = format!("{} == {}", expr_snip, snippet(cx, other.span, ".."));
678 hint = format!("{} == {}", snippet(cx, other.span, ".."), expr_snip);
682 diag.span_suggestion(
686 Applicability::MachineApplicable, // snippet
692 /// Heuristic to see if an expression is used. Should be compatible with
693 /// `unused_variables`'s idea
694 /// of what it means for an expression to be "used".
695 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
696 get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
697 ExprKind::Assign(_, ref rhs, _) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
698 _ => is_used(cx, parent),
702 /// Tests whether an expression is in a macro expansion (e.g., something
703 /// generated by `#[derive(...)]` or the like).
704 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
705 use rustc_span::hygiene::MacroKind;
706 if expr.span.from_expansion() {
707 let data = expr.span.ctxt().outer_expn_data();
708 matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _))
714 /// Tests whether `res` is a variable defined outside a macro.
715 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
716 if let def::Res::Local(id) = res {
717 !cx.tcx.hir().span(id).from_expansion()
723 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
725 if let TyKind::Ptr(ref mut_ty) = ty.kind;
726 if let ExprKind::Lit(ref lit) = e.kind;
727 if let LitKind::Int(0, _) = lit.node;
728 if !in_constant(cx, e.hir_id);
730 let (msg, sugg_fn) = match mut_ty.mutbl {
731 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
732 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
735 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
736 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
737 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
738 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
740 // `MaybeIncorrect` as type inference may not work with the suggested code
741 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
743 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);