1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::reexport::*;
13 use crate::rustc::hir::*;
14 use crate::rustc::hir::intravisit::FnKind;
15 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
16 use crate::rustc::{declare_tool_lint, lint_array};
17 use if_chain::if_chain;
19 use crate::syntax::source_map::{ExpnFormat, Span};
20 use crate::utils::{get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal,
21 iter_input_pats, last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint,
22 span_lint_and_then, walk_ptrs_ty, SpanlessEq};
23 use crate::utils::sugg::Sugg;
24 use crate::syntax::ast::{LitKind, CRATE_NODE_ID};
25 use crate::consts::{constant, Constant};
26 use crate::rustc_errors::Applicability;
28 /// **What it does:** Checks for function arguments and let bindings denoted as
31 /// **Why is this bad?** The `ref` declaration makes the function take an owned
32 /// value, but turns the argument into a reference (which means that the value
33 /// is destroyed when exiting the function). This adds not much value: either
34 /// take a reference type, or take an owned value and create references in the
37 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
38 /// type of `x` is more obvious with the former.
40 /// **Known problems:** If the argument is dereferenced within the function,
41 /// removing the `ref` will lead to errors. This can be fixed by removing the
42 /// dereferences, e.g. changing `*x` to `x` within the function.
46 /// fn foo(ref x: u8) -> bool { .. }
48 declare_clippy_lint! {
51 "an entire binding declared as `ref`, in a function argument or a `let` statement"
54 /// **What it does:** Checks for comparisons to NaN.
56 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
57 /// even itself – so those comparisons are simply wrong.
59 /// **Known problems:** None.
65 declare_clippy_lint! {
68 "comparisons to NAN, which will always return false, probably not intended"
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.
85 /// y != x // where both are floats
87 declare_clippy_lint! {
90 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
93 /// **What it does:** Checks for conversions to owned values just for the sake
96 /// **Why is this bad?** The comparison can operate on a reference, so creating
97 /// an owned value effectively throws it away directly afterwards, which is
98 /// needlessly consuming code and heap space.
100 /// **Known problems:** None.
104 /// x.to_owned() == y
106 declare_clippy_lint! {
109 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
112 /// **What it does:** Checks for getting the remainder of a division by one.
114 /// **Why is this bad?** The result can only ever be zero. No one will write
115 /// such code deliberately, unless trying to win an Underhanded Rust
116 /// Contest. Even for that contest, it's probably a bad idea. Use something more
119 /// **Known problems:** None.
125 declare_clippy_lint! {
128 "taking a number modulo 1, which always returns 0"
131 /// **What it does:** Checks for patterns in the form `name @ _`.
133 /// **Why is this bad?** It's almost always more readable to just use direct
136 /// **Known problems:** None.
142 /// y @ _ => (), // easier written as `y`,
145 declare_clippy_lint! {
146 pub REDUNDANT_PATTERN,
148 "using `name @ _` in a pattern"
151 /// **What it does:** Checks for the use of bindings with a single leading
154 /// **Why is this bad?** A single leading underscore is usually used to indicate
155 /// that a binding will not be used. Using such a binding breaks this
158 /// **Known problems:** The lint does not work properly with desugaring and
159 /// macro, it has been allowed in the mean time.
164 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
165 /// // underscore. We should rename `_x` to `x`
167 declare_clippy_lint! {
168 pub USED_UNDERSCORE_BINDING,
170 "using a binding which is prefixed with an underscore"
173 /// **What it does:** Checks for the use of short circuit boolean conditions as
177 /// **Why is this bad?** Using a short circuit boolean condition as a statement
178 /// may hide the fact that the second part is executed or not depending on the
179 /// outcome of the first part.
181 /// **Known problems:** None.
185 /// f() && g(); // We should write `if f() { g(); }`.
187 declare_clippy_lint! {
188 pub SHORT_CIRCUIT_STATEMENT,
190 "using a short circuit boolean condition as a statement"
193 /// **What it does:** Catch casts from `0` to some pointer type
195 /// **Why is this bad?** This generally means `null` and is better expressed as
196 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
198 /// **Known problems:** None.
205 declare_clippy_lint! {
208 "using 0 as *{const, mut} T"
211 /// **What it does:** Checks for (in-)equality comparisons on floating-point
212 /// value and constant, except in functions called `*eq*` (which probably
213 /// implement equality for a type involving floats).
215 /// **Why is this bad?** Floating point calculations are usually imprecise, so
216 /// asking if two values are *exactly* equal is asking for trouble. For a good
217 /// guide on what to do, see [the floating point
218 /// guide](http://www.floating-point-gui.de/errors/comparison).
220 /// **Known problems:** None.
224 /// const ONE == 1.00f64
225 /// x == ONE // where both are floats
227 declare_clippy_lint! {
230 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
233 #[derive(Copy, Clone)]
236 impl LintPass for Pass {
237 fn get_lints(&self) -> LintArray {
245 USED_UNDERSCORE_BINDING,
246 SHORT_CIRCUIT_STATEMENT,
253 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
256 cx: &LateContext<'a, 'tcx>,
263 if let FnKind::Closure(_) = k {
264 // Does not apply to closures
267 for arg in iter_input_pats(decl, body) {
269 PatKind::Binding(BindingAnnotation::Ref, _, _, _) |
270 PatKind::Binding(BindingAnnotation::RefMut, _, _, _) => {
275 "`ref` directly on a function argument is ignored. Consider using a reference type \
284 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
286 if let StmtKind::Decl(ref d, _) = s.node;
287 if let DeclKind::Local(ref l) = d.node;
288 if let PatKind::Binding(an, _, i, None) = l.pat.node;
289 if let Some(ref init) = l.init;
291 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
292 let init = Sugg::hir(cx, init, "..");
293 let (mutopt,initref) = if an == BindingAnnotation::RefMut {
294 ("mut ", init.mut_addr())
298 let tyopt = if let Some(ref ty) = l.ty {
299 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
303 span_lint_and_then(cx,
306 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
308 db.span_suggestion_with_applicability(
312 "let {name}{tyopt} = {initref};",
313 name=snippet(cx, i.span, "_"),
317 Applicability::MachineApplicable, // snippet
325 if let StmtKind::Semi(ref expr, _) = s.node;
326 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.node;
327 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
328 if let Some(sugg) = Sugg::hir_opt(cx, a);
330 span_lint_and_then(cx,
331 SHORT_CIRCUIT_STATEMENT,
333 "boolean short circuit operator in statement may be clearer using an explicit test",
335 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
336 db.span_suggestion_with_applicability(
342 &snippet(cx, b.span, ".."),
344 Applicability::MachineApplicable, // snippet
351 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
353 ExprKind::Cast(ref e, ref ty) => {
354 check_cast(cx, expr.span, e, ty);
357 ExprKind::Binary(ref cmp, ref left, ref right) => {
359 if op.is_comparison() {
360 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node {
361 check_nan(cx, path, expr);
363 if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.node {
364 check_nan(cx, path, expr);
366 check_to_owned(cx, left, right);
367 check_to_owned(cx, right, left);
369 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
370 if is_allowed(cx, left) || is_allowed(cx, right) {
373 if let Some(name) = get_item_name(cx, expr) {
374 let name = name.as_str();
375 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_")
376 || name.ends_with("_eq")
381 let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
382 (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
384 (FLOAT_CMP, "strict comparison of f32 or f64")
386 span_lint_and_then(cx, lint, expr.span, msg, |db| {
387 let lhs = Sugg::hir(cx, left, "..");
388 let rhs = Sugg::hir(cx, right, "..");
390 db.span_suggestion_with_applicability(
392 "consider comparing them within some error",
393 format!("({}).abs() < error", lhs - rhs),
394 Applicability::MachineApplicable, // snippet
396 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
398 } else if op == BinOpKind::Rem && is_integer_literal(right, 1) {
399 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
404 if in_attributes_expansion(expr) {
405 // Don't lint things expanded by #[derive(...)], etc
408 let binding = match expr.node {
409 ExprKind::Path(ref qpath) => {
410 let binding = last_path_segment(qpath).ident.as_str();
411 if binding.starts_with('_') &&
412 !binding.starts_with("__") &&
413 binding != "_result" && // FIXME: #944
415 // don't lint if the declaration is in a macro
416 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
423 ExprKind::Field(_, ident) => {
424 let name = ident.as_str();
425 if name.starts_with('_') && !name.starts_with("__") {
433 if let Some(binding) = binding {
436 USED_UNDERSCORE_BINDING,
439 "used binding `{}` which is prefixed with an underscore. A leading \
440 underscore signals that a binding will not be used.",
447 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
448 if let PatKind::Binding(_, _, ident, Some(ref right)) = pat.node {
449 if let PatKind::Wild = right.node {
454 &format!("the `{} @ _` pattern can be written as just `{}`", ident.name, ident.name),
461 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
462 if !in_constant(cx, expr.id) {
463 if let Some(seg) = path.segments.last() {
464 if seg.ident.name == "NAN" {
469 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
476 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
477 if let Some((_, res)) = constant(cx, cx.tables, expr) {
484 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
485 match constant(cx, cx.tables, expr) {
486 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
487 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
492 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
493 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::Float(_))
496 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
497 let (arg_ty, snip) = match expr.node {
498 ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
499 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
500 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
505 ExprKind::Call(ref path, ref v) if v.len() == 1 => 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, ".."))
517 let other_ty = cx.tables.expr_ty_adjusted(other);
518 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
523 let deref_arg_impl_partial_eq_other = arg_ty
525 .map_or(false, |tam| implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()]));
526 let arg_impl_partial_eq_deref_other = other_ty
528 .map_or(false, |tam| implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()]));
529 let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
531 if !deref_arg_impl_partial_eq_other
532 && !arg_impl_partial_eq_deref_other
533 && !arg_impl_partial_eq_other
538 let other_gets_derefed = match other.node {
539 ExprKind::Unary(UnDeref, _) => true,
543 let (lint_span, try_hint) = if deref_arg_impl_partial_eq_other {
544 // suggest deref on the left
545 (expr.span, format!("*{}", snip))
546 } else if other_gets_derefed {
547 // suggest dropping the to_owned on the left and the deref on the right
548 let other_snippet = snippet(cx, other.span, "..").into_owned();
549 let other_without_deref = other_snippet.replacen('*', "", 1);
551 (expr.span.to(other.span), format!("{} == {}", snip.to_string(), other_without_deref))
553 // suggest dropping the to_owned on the left
554 (expr.span, snip.to_string())
561 "this creates an owned instance just for comparison",
563 // this is as good as our recursion check can get, we can't prove that the
564 // current function is
566 // PartialEq::eq, but we can at least ensure that this code is not part of it
567 let parent_fn = cx.tcx.hir.get_parent(expr.id);
568 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
569 if parent_impl != CRATE_NODE_ID {
570 if let Node::Item(item) = cx.tcx.hir.get(parent_impl) {
571 if let ItemKind::Impl(.., Some(ref trait_ref), _, _) = item.node {
572 if trait_ref.path.def.def_id() == partial_eq_trait_id {
573 // we are implementing PartialEq, don't suggest not doing `to_owned`, otherwise
576 db.span_label(lint_span, "try implementing the comparison without allocating");
582 if other_gets_derefed {
583 db.span_label(lint_span, "try implementing the comparison without allocating");
586 db.span_suggestion_with_applicability(
590 Applicability::MachineApplicable, // snippet
596 /// Heuristic to see if an expression is used. Should be compatible with
597 /// `unused_variables`'s idea
598 /// of what it means for an expression to be "used".
599 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
600 if let Some(parent) = get_parent_expr(cx, expr) {
602 ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
603 _ => is_used(cx, parent),
610 /// Test whether an expression is in a macro expansion (e.g. something
612 /// `#[derive(...)`] or the like).
613 fn in_attributes_expansion(expr: &Expr) -> bool {
618 .map_or(false, |info| matches!(info.format, ExpnFormat::MacroAttribute(_)))
621 /// Test whether `def` is a variable defined outside a macro.
622 fn non_macro_local(cx: &LateContext<'_, '_>, def: &def::Def) -> bool {
624 def::Def::Local(id) | def::Def::Upvar(id, _, _) => !in_macro(cx.tcx.hir.span(id)),
629 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
631 if let TyKind::Ptr(MutTy { mutbl, .. }) = ty.node;
632 if let ExprKind::Lit(ref lit) = e.node;
633 if let LitKind::Int(value, ..) = lit.node;
635 if !in_constant(cx, e.id);
637 let msg = match mutbl {
638 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
639 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
641 span_lint(cx, ZERO_PTR, span, msg);