1 use if_chain::if_chain;
3 use rustc::hir::intravisit::FnKind;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_lint_pass, declare_tool_lint};
8 use rustc_errors::Applicability;
9 use syntax::ast::LitKind;
10 use syntax::source_map::{ExpnFormat, Span};
12 use crate::consts::{constant, Constant};
13 use crate::utils::sugg::Sugg;
15 get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal, iter_input_pats,
16 last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint, span_lint_and_then,
17 span_lint_hir_and_then, walk_ptrs_ty, SpanlessEq,
20 declare_clippy_lint! {
21 /// **What it does:** Checks for function arguments and let bindings denoted as
24 /// **Why is this bad?** The `ref` declaration makes the function take an owned
25 /// value, but turns the argument into a reference (which means that the value
26 /// is destroyed when exiting the function). This adds not much value: either
27 /// take a reference type, or take an owned value and create references in the
30 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
31 /// type of `x` is more obvious with the former.
33 /// **Known problems:** If the argument is dereferenced within the function,
34 /// removing the `ref` will lead to errors. This can be fixed by removing the
35 /// dereferences, e.g., changing `*x` to `x` within the function.
39 /// fn foo(ref x: u8) -> bool {
45 "an entire binding declared as `ref`, in a function argument or a `let` statement"
48 declare_clippy_lint! {
49 /// **What it does:** Checks for comparisons to NaN.
51 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
52 /// even itself – so those comparisons are simply wrong.
54 /// **Known problems:** None.
58 /// # use core::f32::NAN;
65 "comparisons to NAN, which will always return false, probably not intended"
68 declare_clippy_lint! {
69 /// **What it does:** Checks for (in-)equality comparisons on floating-point
70 /// values (apart from zero), except in functions called `*eq*` (which probably
71 /// implement equality for a type involving floats).
73 /// **Why is this bad?** Floating point calculations are usually imprecise, so
74 /// asking if two values are *exactly* equal is asking for trouble. For a good
75 /// guide on what to do, see [the floating point
76 /// guide](http://www.floating-point-gui.de/errors/comparison).
78 /// **Known problems:** None.
82 /// let x = 1.2331f64;
83 /// let y = 1.2332f64;
84 /// if y == 1.23f64 { }
85 /// if y != x {} // where both are floats
89 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
92 declare_clippy_lint! {
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
108 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
111 declare_clippy_lint! {
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.
128 "taking a number modulo 1, which always returns 0"
131 declare_clippy_lint! {
132 /// **What it does:** Checks for patterns in the form `name @ _`.
134 /// **Why is this bad?** It's almost always more readable to just use direct
137 /// **Known problems:** None.
141 /// # let v = Some("abc");
145 /// y @ _ => (), // easier written as `y`,
148 pub REDUNDANT_PATTERN,
150 "using `name @ _` in a pattern"
153 declare_clippy_lint! {
154 /// **What it does:** Checks for the use of bindings with a single leading
157 /// **Why is this bad?** A single leading underscore is usually used to indicate
158 /// that a binding will not be used. Using such a binding breaks this
161 /// **Known problems:** The lint does not work properly with desugaring and
162 /// macro, it has been allowed in the mean time.
167 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
168 /// // underscore. We should rename `_x` to `x`
170 pub USED_UNDERSCORE_BINDING,
172 "using a binding which is prefixed with an underscore"
175 declare_clippy_lint! {
176 /// **What it does:** Checks for the use of short circuit boolean conditions as
180 /// **Why is this bad?** Using a short circuit boolean condition as a statement
181 /// may hide the fact that the second part is executed or not depending on the
182 /// outcome of the first part.
184 /// **Known problems:** None.
188 /// f() && g(); // We should write `if f() { g(); }`.
190 pub SHORT_CIRCUIT_STATEMENT,
192 "using a short circuit boolean condition as a statement"
195 declare_clippy_lint! {
196 /// **What it does:** Catch casts from `0` to some pointer type
198 /// **Why is this bad?** This generally means `null` and is better expressed as
199 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
201 /// **Known problems:** None.
206 /// let a = 0 as *const u32;
210 "using 0 as *{const, mut} T"
213 declare_clippy_lint! {
214 /// **What it does:** Checks for (in-)equality comparisons on floating-point
215 /// value and constant, except in functions called `*eq*` (which probably
216 /// implement equality for a type involving floats).
218 /// **Why is this bad?** Floating point calculations are usually imprecise, so
219 /// asking if two values are *exactly* equal is asking for trouble. For a good
220 /// guide on what to do, see [the floating point
221 /// guide](http://www.floating-point-gui.de/errors/comparison).
223 /// **Known problems:** None.
227 /// const ONE = 1.00f64;
228 /// x == ONE // where both are floats
232 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
235 declare_lint_pass!(MiscLints => [
242 USED_UNDERSCORE_BINDING,
243 SHORT_CIRCUIT_STATEMENT,
248 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints {
251 cx: &LateContext<'a, 'tcx>,
258 if let FnKind::Closure(_) = k {
259 // Does not apply to closures
262 for arg in iter_input_pats(decl, body) {
264 PatKind::Binding(BindingAnnotation::Ref, ..) | 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 sugg_init = Sugg::hir(cx, init, "..");
286 let (mutopt,initref) = if an == BindingAnnotation::RefMut {
287 ("mut ", sugg_init.mut_addr())
289 ("", sugg_init.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_hir_and_then(cx,
300 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
306 "let {name}{tyopt} = {initref};",
307 name=snippet(cx, i.span, "_"),
311 Applicability::MachineApplicable, // snippet
319 if let StmtKind::Semi(ref expr) = s.node;
320 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.node;
321 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
322 if let Some(sugg) = Sugg::hir_opt(cx, a);
324 span_lint_and_then(cx,
325 SHORT_CIRCUIT_STATEMENT,
327 "boolean short circuit operator in statement may be clearer using an explicit test",
329 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
336 &snippet(cx, b.span, ".."),
338 Applicability::MachineApplicable, // snippet
345 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
347 ExprKind::Cast(ref e, ref ty) => {
348 check_cast(cx, expr.span, e, ty);
351 ExprKind::Binary(ref cmp, ref left, ref right) => {
353 if op.is_comparison() {
354 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node {
355 check_nan(cx, path, expr);
357 if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.node {
358 check_nan(cx, path, expr);
360 check_to_owned(cx, left, right);
361 check_to_owned(cx, right, left);
363 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
364 if is_allowed(cx, left) || is_allowed(cx, right) {
367 if let Some(name) = get_item_name(cx, expr) {
368 let name = name.as_str();
372 || name.starts_with("eq_")
373 || name.ends_with("_eq")
378 let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
379 (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
381 (FLOAT_CMP, "strict comparison of f32 or f64")
383 span_lint_and_then(cx, lint, expr.span, msg, |db| {
384 let lhs = Sugg::hir(cx, left, "..");
385 let rhs = Sugg::hir(cx, right, "..");
389 "consider comparing them within some error",
390 format!("({}).abs() < error", lhs - rhs),
391 Applicability::MachineApplicable, // snippet
393 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
395 } else if op == BinOpKind::Rem && is_integer_literal(right, 1) {
396 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
401 if in_attributes_expansion(expr) {
402 // Don't lint things expanded by #[derive(...)], etc
405 let binding = match expr.node {
406 ExprKind::Path(ref qpath) => {
407 let binding = last_path_segment(qpath).ident.as_str();
408 if binding.starts_with('_') &&
409 !binding.starts_with("__") &&
410 binding != "_result" && // FIXME: #944
412 // don't lint if the declaration is in a macro
413 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
420 ExprKind::Field(_, ident) => {
421 let name = ident.as_str();
422 if name.starts_with('_') && !name.starts_with("__") {
430 if let Some(binding) = binding {
433 USED_UNDERSCORE_BINDING,
436 "used binding `{}` which is prefixed with an underscore. A leading \
437 underscore signals that a binding will not be used.",
444 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
445 if let PatKind::Binding(.., ident, Some(ref right)) = pat.node {
446 if let PatKind::Wild = right.node {
452 "the `{} @ _` pattern can be written as just `{}`",
453 ident.name, ident.name
461 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
462 if !in_constant(cx, expr.hir_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 => {
506 if let ExprKind::Path(ref path) = path.node {
507 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
508 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
519 let other_ty = cx.tables.expr_ty_adjusted(other);
520 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
525 let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
526 implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
528 let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
529 implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
531 let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
533 if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
537 let other_gets_derefed = match other.node {
538 ExprKind::Unary(UnDeref, _) => true,
542 let lint_span = if other_gets_derefed {
543 expr.span.to(other.span)
552 "this creates an owned instance just for comparison",
554 // This also catches `PartialEq` implementations that call `to_owned`.
555 if other_gets_derefed {
556 db.span_label(lint_span, "try implementing the comparison without allocating");
560 let try_hint = if deref_arg_impl_partial_eq_other {
561 // suggest deref on the left
564 // suggest dropping the to_owned on the left
572 Applicability::MachineApplicable, // snippet
578 /// Heuristic to see if an expression is used. Should be compatible with
579 /// `unused_variables`'s idea
580 /// of what it means for an expression to be "used".
581 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
582 if let Some(parent) = get_parent_expr(cx, expr) {
584 ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
585 _ => is_used(cx, parent),
592 /// Tests whether an expression is in a macro expansion (e.g., something
593 /// generated by `#[derive(...)]` or the like).
594 fn in_attributes_expansion(expr: &Expr) -> bool {
599 .map_or(false, |info| matches!(info.format, ExpnFormat::MacroAttribute(_)))
602 /// Tests 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_by_hir_id(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.hir_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);