1 use crate::consts::{constant, Constant};
2 use crate::reexport::*;
3 use crate::utils::sugg::Sugg;
5 get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal, iter_input_pats,
6 last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint, span_lint_and_then, walk_ptrs_ty,
9 use if_chain::if_chain;
11 use rustc::hir::intravisit::FnKind;
13 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::{declare_tool_lint, lint_array};
16 use rustc_errors::Applicability;
17 use syntax::ast::LitKind;
18 use syntax::source_map::{ExpnFormat, Span};
20 /// **What it does:** Checks for function arguments and let bindings denoted as
23 /// **Why is this bad?** The `ref` declaration makes the function take an owned
24 /// value, but turns the argument into a reference (which means that the value
25 /// is destroyed when exiting the function). This adds not much value: either
26 /// take a reference type, or take an owned value and create references in the
29 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
30 /// type of `x` is more obvious with the former.
32 /// **Known problems:** If the argument is dereferenced within the function,
33 /// removing the `ref` will lead to errors. This can be fixed by removing the
34 /// dereferences, e.g. changing `*x` to `x` within the function.
38 /// fn foo(ref x: u8) -> bool {
42 declare_clippy_lint! {
45 "an entire binding declared as `ref`, in a function argument or a `let` statement"
48 /// **What it does:** Checks for comparisons to NaN.
50 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
51 /// even itself – so those comparisons are simply wrong.
53 /// **Known problems:** None.
59 declare_clippy_lint! {
62 "comparisons to NAN, which will always return false, probably not intended"
65 /// **What it does:** Checks for (in-)equality comparisons on floating-point
66 /// values (apart from zero), except in functions called `*eq*` (which probably
67 /// implement equality for a type involving floats).
69 /// **Why is this bad?** Floating point calculations are usually imprecise, so
70 /// asking if two values are *exactly* equal is asking for trouble. For a good
71 /// guide on what to do, see [the floating point
72 /// guide](http://www.floating-point-gui.de/errors/comparison).
74 /// **Known problems:** None.
79 /// y != x // where both are floats
81 declare_clippy_lint! {
84 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
87 /// **What it does:** Checks for conversions to owned values just for the sake
90 /// **Why is this bad?** The comparison can operate on a reference, so creating
91 /// an owned value effectively throws it away directly afterwards, which is
92 /// needlessly consuming code and heap space.
94 /// **Known problems:** None.
100 declare_clippy_lint! {
103 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
106 /// **What it does:** Checks for getting the remainder of a division by one.
108 /// **Why is this bad?** The result can only ever be zero. No one will write
109 /// such code deliberately, unless trying to win an Underhanded Rust
110 /// Contest. Even for that contest, it's probably a bad idea. Use something more
113 /// **Known problems:** None.
119 declare_clippy_lint! {
122 "taking a number modulo 1, which always returns 0"
125 /// **What it does:** Checks for patterns in the form `name @ _`.
127 /// **Why is this bad?** It's almost always more readable to just use direct
130 /// **Known problems:** None.
136 /// y @ _ => (), // easier written as `y`,
139 declare_clippy_lint! {
140 pub REDUNDANT_PATTERN,
142 "using `name @ _` in a pattern"
145 /// **What it does:** Checks for the use of bindings with a single leading
148 /// **Why is this bad?** A single leading underscore is usually used to indicate
149 /// that a binding will not be used. Using such a binding breaks this
152 /// **Known problems:** The lint does not work properly with desugaring and
153 /// macro, it has been allowed in the mean time.
158 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
159 /// // underscore. We should rename `_x` to `x`
161 declare_clippy_lint! {
162 pub USED_UNDERSCORE_BINDING,
164 "using a binding which is prefixed with an underscore"
167 /// **What it does:** Checks for the use of short circuit boolean conditions as
171 /// **Why is this bad?** Using a short circuit boolean condition as a statement
172 /// may hide the fact that the second part is executed or not depending on the
173 /// outcome of the first part.
175 /// **Known problems:** None.
179 /// f() && g(); // We should write `if f() { g(); }`.
181 declare_clippy_lint! {
182 pub SHORT_CIRCUIT_STATEMENT,
184 "using a short circuit boolean condition as a statement"
187 /// **What it does:** Catch casts from `0` to some pointer type
189 /// **Why is this bad?** This generally means `null` and is better expressed as
190 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
192 /// **Known problems:** None.
199 declare_clippy_lint! {
202 "using 0 as *{const, mut} T"
205 /// **What it does:** Checks for (in-)equality comparisons on floating-point
206 /// value and constant, except in functions called `*eq*` (which probably
207 /// implement equality for a type involving floats).
209 /// **Why is this bad?** Floating point calculations are usually imprecise, so
210 /// asking if two values are *exactly* equal is asking for trouble. For a good
211 /// guide on what to do, see [the floating point
212 /// guide](http://www.floating-point-gui.de/errors/comparison).
214 /// **Known problems:** None.
218 /// const ONE == 1.00f64
219 /// x == ONE // where both are floats
221 declare_clippy_lint! {
224 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
227 #[derive(Copy, Clone)]
230 impl LintPass for Pass {
231 fn get_lints(&self) -> LintArray {
239 USED_UNDERSCORE_BINDING,
240 SHORT_CIRCUIT_STATEMENT,
247 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
250 cx: &LateContext<'a, 'tcx>,
257 if let FnKind::Closure(_) = k {
258 // Does not apply to closures
261 for arg in iter_input_pats(decl, body) {
263 PatKind::Binding(BindingAnnotation::Ref, _, _, _)
264 | PatKind::Binding(BindingAnnotation::RefMut, _, _, _) => {
269 "`ref` directly on a function argument is ignored. Consider using a reference type \
278 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
280 if let StmtKind::Local(ref l) = s.node;
281 if let PatKind::Binding(an, _, i, None) = l.pat.node;
282 if let Some(ref init) = l.init;
284 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
285 let init = Sugg::hir(cx, init, "..");
286 let (mutopt,initref) = if an == BindingAnnotation::RefMut {
287 ("mut ", init.mut_addr())
291 let tyopt = if let Some(ref ty) = l.ty {
292 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
296 span_lint_and_then(cx,
299 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
301 db.span_suggestion_with_applicability(
305 "let {name}{tyopt} = {initref};",
306 name=snippet(cx, i.span, "_"),
310 Applicability::MachineApplicable, // snippet
318 if let StmtKind::Semi(ref expr) = s.node;
319 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.node;
320 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
321 if let Some(sugg) = Sugg::hir_opt(cx, a);
323 span_lint_and_then(cx,
324 SHORT_CIRCUIT_STATEMENT,
326 "boolean short circuit operator in statement may be clearer using an explicit test",
328 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
329 db.span_suggestion_with_applicability(
335 &snippet(cx, b.span, ".."),
337 Applicability::MachineApplicable, // snippet
344 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
346 ExprKind::Cast(ref e, ref ty) => {
347 check_cast(cx, expr.span, e, ty);
350 ExprKind::Binary(ref cmp, ref left, ref right) => {
352 if op.is_comparison() {
353 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node {
354 check_nan(cx, path, expr);
356 if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.node {
357 check_nan(cx, path, expr);
359 check_to_owned(cx, left, right);
360 check_to_owned(cx, right, left);
362 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
363 if is_allowed(cx, left) || is_allowed(cx, right) {
366 if let Some(name) = get_item_name(cx, expr) {
367 let name = name.as_str();
371 || name.starts_with("eq_")
372 || name.ends_with("_eq")
377 let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
378 (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
380 (FLOAT_CMP, "strict comparison of f32 or f64")
382 span_lint_and_then(cx, lint, expr.span, msg, |db| {
383 let lhs = Sugg::hir(cx, left, "..");
384 let rhs = Sugg::hir(cx, right, "..");
386 db.span_suggestion_with_applicability(
388 "consider comparing them within some error",
389 format!("({}).abs() < error", lhs - rhs),
390 Applicability::MachineApplicable, // snippet
392 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
394 } else if op == BinOpKind::Rem && is_integer_literal(right, 1) {
395 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
400 if in_attributes_expansion(expr) {
401 // Don't lint things expanded by #[derive(...)], etc
404 let binding = match expr.node {
405 ExprKind::Path(ref qpath) => {
406 let binding = last_path_segment(qpath).ident.as_str();
407 if binding.starts_with('_') &&
408 !binding.starts_with("__") &&
409 binding != "_result" && // FIXME: #944
411 // don't lint if the declaration is in a macro
412 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
419 ExprKind::Field(_, ident) => {
420 let name = ident.as_str();
421 if name.starts_with('_') && !name.starts_with("__") {
429 if let Some(binding) = binding {
432 USED_UNDERSCORE_BINDING,
435 "used binding `{}` which is prefixed with an underscore. A leading \
436 underscore signals that a binding will not be used.",
443 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
444 if let PatKind::Binding(_, _, ident, Some(ref right)) = pat.node {
445 if let PatKind::Wild = right.node {
451 "the `{} @ _` pattern can be written as just `{}`",
452 ident.name, ident.name
460 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
461 if !in_constant(cx, expr.id) {
462 if let Some(seg) = path.segments.last() {
463 if seg.ident.name == "NAN" {
468 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
475 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
476 if let Some((_, res)) = constant(cx, cx.tables, expr) {
483 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
484 match constant(cx, cx.tables, expr) {
485 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
486 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
491 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
492 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::Float(_))
495 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
496 let (arg_ty, snip) = match expr.node {
497 ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
498 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
499 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
504 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
505 if let ExprKind::Path(ref path) = path.node {
506 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
507 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
518 let other_ty = cx.tables.expr_ty_adjusted(other);
519 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
524 let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
525 implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
527 let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
528 implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
530 let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
532 if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
536 let other_gets_derefed = match other.node {
537 ExprKind::Unary(UnDeref, _) => true,
541 let lint_span = if other_gets_derefed {
542 expr.span.to(other.span)
551 "this creates an owned instance just for comparison",
553 // this also catches PartialEq implementations that call to_owned
554 if other_gets_derefed {
555 db.span_label(lint_span, "try implementing the comparison without allocating");
559 let try_hint = if deref_arg_impl_partial_eq_other {
560 // suggest deref on the left
563 // suggest dropping the to_owned on the left
567 db.span_suggestion_with_applicability(
571 Applicability::MachineApplicable, // snippet
577 /// Heuristic to see if an expression is used. Should be compatible with
578 /// `unused_variables`'s idea
579 /// of what it means for an expression to be "used".
580 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
581 if let Some(parent) = get_parent_expr(cx, expr) {
583 ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
584 _ => is_used(cx, parent),
591 /// Test whether an expression is in a macro expansion (e.g. something
593 /// `#[derive(...)`] or the like).
594 fn in_attributes_expansion(expr: &Expr) -> bool {
599 .map_or(false, |info| matches!(info.format, ExpnFormat::MacroAttribute(_)))
602 /// Test whether `def` is a variable defined outside a macro.
603 fn non_macro_local(cx: &LateContext<'_, '_>, def: &def::Def) -> bool {
605 def::Def::Local(id) | def::Def::Upvar(id, _, _) => !in_macro(cx.tcx.hir().span(id)),
610 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
612 if let TyKind::Ptr(MutTy { mutbl, .. }) = ty.node;
613 if let ExprKind::Lit(ref lit) = e.node;
614 if let LitKind::Int(value, ..) = lit.node;
616 if !in_constant(cx, e.id);
618 let msg = match mutbl {
619 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
620 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
622 span_lint(cx, ZERO_PTR, span, msg);