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::{ExpnKind, Span};
12 use crate::consts::{constant, Constant};
13 use crate::utils::sugg::Sugg;
15 get_item_name, get_parent_expr, implements_trait, in_constant, is_integer_const, iter_input_pats,
16 last_path_segment, match_qpath, match_trait_method, paths, snippet, snippet_opt, span_lint, span_lint_and_sugg,
17 span_lint_and_then, 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.
105 /// # let y = String::from("foo");
106 /// if x.to_owned() == y {}
108 /// Could be written as
111 /// # let y = String::from("foo");
116 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
119 declare_clippy_lint! {
120 /// **What it does:** Checks for getting the remainder of a division by one.
122 /// **Why is this bad?** The result can only ever be zero. No one will write
123 /// such code deliberately, unless trying to win an Underhanded Rust
124 /// Contest. Even for that contest, it's probably a bad idea. Use something more
127 /// **Known problems:** None.
136 "taking a number modulo 1, which always returns 0"
139 declare_clippy_lint! {
140 /// **What it does:** Checks for the use of bindings with a single leading
143 /// **Why is this bad?** A single leading underscore is usually used to indicate
144 /// that a binding will not be used. Using such a binding breaks this
147 /// **Known problems:** The lint does not work properly with desugaring and
148 /// macro, it has been allowed in the mean time.
153 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
154 /// // underscore. We should rename `_x` to `x`
156 pub USED_UNDERSCORE_BINDING,
158 "using a binding which is prefixed with an underscore"
161 declare_clippy_lint! {
162 /// **What it does:** Checks for the use of short circuit boolean conditions as
166 /// **Why is this bad?** Using a short circuit boolean condition as a statement
167 /// may hide the fact that the second part is executed or not depending on the
168 /// outcome of the first part.
170 /// **Known problems:** None.
174 /// f() && g(); // We should write `if f() { g(); }`.
176 pub SHORT_CIRCUIT_STATEMENT,
178 "using a short circuit boolean condition as a statement"
181 declare_clippy_lint! {
182 /// **What it does:** Catch casts from `0` to some pointer type
184 /// **Why is this bad?** This generally means `null` and is better expressed as
185 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
187 /// **Known problems:** None.
192 /// let a = 0 as *const u32;
196 "using 0 as *{const, mut} T"
199 declare_clippy_lint! {
200 /// **What it does:** Checks for (in-)equality comparisons on floating-point
201 /// value and constant, except in functions called `*eq*` (which probably
202 /// implement equality for a type involving floats).
204 /// **Why is this bad?** Floating point calculations are usually imprecise, so
205 /// asking if two values are *exactly* equal is asking for trouble. For a good
206 /// guide on what to do, see [the floating point
207 /// guide](http://www.floating-point-gui.de/errors/comparison).
209 /// **Known problems:** None.
213 /// let x: f64 = 1.0;
214 /// const ONE: f64 = 1.00;
215 /// x == ONE; // where both are floats
219 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
222 declare_lint_pass!(MiscLints => [
228 USED_UNDERSCORE_BINDING,
229 SHORT_CIRCUIT_STATEMENT,
234 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints {
237 cx: &LateContext<'a, 'tcx>,
244 if let FnKind::Closure(_) = k {
245 // Does not apply to closures
248 for arg in iter_input_pats(decl, body) {
250 PatKind::Binding(BindingAnnotation::Ref, ..) | PatKind::Binding(BindingAnnotation::RefMut, ..) => {
255 "`ref` directly on a function argument is ignored. Consider using a reference type \
264 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
266 if let StmtKind::Local(ref local) = stmt.kind;
267 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
268 if let Some(ref init) = local.init;
270 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
271 let sugg_init = if init.span.from_expansion() {
272 Sugg::hir_with_macro_callsite(cx, init, "..")
274 Sugg::hir(cx, init, "..")
276 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
277 ("mut ", sugg_init.mut_addr())
279 ("", sugg_init.addr())
281 let tyopt = if let Some(ref ty) = local.ty {
282 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
286 span_lint_hir_and_then(
291 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
297 "let {name}{tyopt} = {initref};",
298 name=snippet(cx, name.span, "_"),
302 Applicability::MachineApplicable,
310 if let StmtKind::Semi(ref expr) = stmt.kind;
311 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.kind;
312 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
313 if let Some(sugg) = Sugg::hir_opt(cx, a);
315 span_lint_and_then(cx,
316 SHORT_CIRCUIT_STATEMENT,
318 "boolean short circuit operator in statement may be clearer using an explicit test",
320 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
327 &snippet(cx, b.span, ".."),
329 Applicability::MachineApplicable, // snippet
336 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
338 ExprKind::Cast(ref e, ref ty) => {
339 check_cast(cx, expr.span, e, ty);
342 ExprKind::Binary(ref cmp, ref left, ref right) => {
344 if op.is_comparison() {
345 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.kind {
346 check_nan(cx, path, expr);
348 if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.kind {
349 check_nan(cx, path, expr);
351 check_to_owned(cx, left, right);
352 check_to_owned(cx, right, left);
354 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
355 if is_allowed(cx, left) || is_allowed(cx, right) {
359 // Allow comparing the results of signum()
360 if is_signum(cx, left) && is_signum(cx, right) {
364 if let Some(name) = get_item_name(cx, expr) {
365 let name = name.as_str();
369 || name.starts_with("eq_")
370 || name.ends_with("_eq")
375 let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
376 (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
378 (FLOAT_CMP, "strict comparison of f32 or f64")
380 span_lint_and_then(cx, lint, expr.span, msg, |db| {
381 let lhs = Sugg::hir(cx, left, "..");
382 let rhs = Sugg::hir(cx, right, "..");
386 "consider comparing them within some error",
388 "({}).abs() {} error",
390 if op == BinOpKind::Eq { '<' } else { '>' }
392 Applicability::HasPlaceholders, // snippet
394 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
396 } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) {
397 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
402 if in_attributes_expansion(expr) {
403 // Don't lint things expanded by #[derive(...)], etc
406 let binding = match expr.kind {
407 ExprKind::Path(ref qpath) => {
408 let binding = last_path_segment(qpath).ident.as_str();
409 if binding.starts_with('_') &&
410 !binding.starts_with("__") &&
411 binding != "_result" && // FIXME: #944
413 // don't lint if the declaration is in a macro
414 non_macro_local(cx, cx.tables.qpath_res(qpath, expr.hir_id))
421 ExprKind::Field(_, ident) => {
422 let name = ident.as_str();
423 if name.starts_with('_') && !name.starts_with("__") {
431 if let Some(binding) = binding {
434 USED_UNDERSCORE_BINDING,
437 "used binding `{}` which is prefixed with an underscore. A leading \
438 underscore signals that a binding will not be used.",
446 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
447 if !in_constant(cx, expr.hir_id) {
448 if let Some(seg) = path.segments.last() {
449 if seg.ident.name == sym!(NAN) {
454 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
461 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
462 if let Some((_, res)) = constant(cx, cx.tables, expr) {
469 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
470 match constant(cx, cx.tables, expr) {
471 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
472 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
477 // Return true if `expr` is the result of `signum()` invoked on a float value.
478 fn is_signum(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
479 // The negation of a signum is still a signum
480 if let ExprKind::Unary(UnNeg, ref child_expr) = expr.kind {
481 return is_signum(cx, &child_expr);
485 if let ExprKind::MethodCall(ref method_name, _, ref expressions) = expr.kind;
486 if sym!(signum) == method_name.ident.name;
487 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
490 return is_float(cx, &expressions[0]);
496 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
497 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).kind, ty::Float(_))
500 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
501 let (arg_ty, snip) = match expr.kind {
502 ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
503 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
504 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
509 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
510 if let ExprKind::Path(ref path) = path.kind {
511 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
512 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
523 let other_ty = cx.tables.expr_ty_adjusted(other);
524 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
529 let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
530 implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
532 let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
533 implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
535 let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
537 if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
541 let other_gets_derefed = match other.kind {
542 ExprKind::Unary(UnDeref, _) => true,
546 let lint_span = if other_gets_derefed {
547 expr.span.to(other.span)
556 "this creates an owned instance just for comparison",
558 // This also catches `PartialEq` implementations that call `to_owned`.
559 if other_gets_derefed {
560 db.span_label(lint_span, "try implementing the comparison without allocating");
564 let try_hint = if deref_arg_impl_partial_eq_other {
565 // suggest deref on the left
568 // suggest dropping the to_owned on the left
576 Applicability::MachineApplicable, // snippet
582 /// Heuristic to see if an expression is used. Should be compatible with
583 /// `unused_variables`'s idea
584 /// of what it means for an expression to be "used".
585 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
586 if let Some(parent) = get_parent_expr(cx, expr) {
588 ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
589 _ => is_used(cx, parent),
596 /// Tests whether an expression is in a macro expansion (e.g., something
597 /// generated by `#[derive(...)]` or the like).
598 fn in_attributes_expansion(expr: &Expr) -> bool {
599 use syntax_pos::hygiene::MacroKind;
600 if expr.span.from_expansion() {
601 let data = expr.span.ctxt().outer_expn_data();
603 if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind {
613 /// Tests whether `res` is a variable defined outside a macro.
614 fn non_macro_local(cx: &LateContext<'_, '_>, res: def::Res) -> bool {
615 if let def::Res::Local(id) = res {
616 !cx.tcx.hir().span(id).from_expansion()
622 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
624 if let TyKind::Ptr(ref mut_ty) = ty.kind;
625 if let ExprKind::Lit(ref lit) = e.kind;
626 if let LitKind::Int(0, _) = lit.node;
627 if !in_constant(cx, e.hir_id);
629 let (msg, sugg_fn) = match mut_ty.mutbl {
630 Mutability::Mutable => ("`0 as *mut _` detected", "std::ptr::null_mut"),
631 Mutability::Immutable => ("`0 as *const _` detected", "std::ptr::null"),
634 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
635 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
636 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
637 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
639 // `MaybeIncorrect` as type inference may not work with the suggested code
640 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
642 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);