1 use if_chain::if_chain;
3 use rustc::declare_lint_pass;
4 use rustc::hir::intravisit::FnKind;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
8 use rustc_errors::Applicability;
9 use rustc_session::declare_tool_lint;
10 use syntax::ast::LitKind;
11 use syntax::source_map::{ExpnKind, Span};
13 use crate::consts::{constant, Constant};
14 use crate::utils::sugg::Sugg;
16 get_item_name, get_parent_expr, implements_trait, in_constant, is_integer_const, iter_input_pats,
17 last_path_segment, match_qpath, match_trait_method, paths, snippet, snippet_opt, span_lint, span_lint_and_sugg,
18 span_lint_and_then, span_lint_hir_and_then, walk_ptrs_ty, SpanlessEq,
21 declare_clippy_lint! {
22 /// **What it does:** Checks for function arguments and let bindings denoted as
25 /// **Why is this bad?** The `ref` declaration makes the function take an owned
26 /// value, but turns the argument into a reference (which means that the value
27 /// is destroyed when exiting the function). This adds not much value: either
28 /// take a reference type, or take an owned value and create references in the
31 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
32 /// type of `x` is more obvious with the former.
34 /// **Known problems:** If the argument is dereferenced within the function,
35 /// removing the `ref` will lead to errors. This can be fixed by removing the
36 /// dereferences, e.g., changing `*x` to `x` within the function.
40 /// fn foo(ref x: u8) -> bool {
46 "an entire binding declared as `ref`, in a function argument or a `let` statement"
49 declare_clippy_lint! {
50 /// **What it does:** Checks for comparisons to NaN.
52 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
53 /// even itself – so those comparisons are simply wrong.
55 /// **Known problems:** None.
59 /// # use core::f32::NAN;
66 "comparisons to NAN, which will always return false, probably not intended"
69 declare_clippy_lint! {
70 /// **What it does:** Checks for (in-)equality comparisons on floating-point
71 /// values (apart from zero), except in functions called `*eq*` (which probably
72 /// implement equality for a type involving floats).
74 /// **Why is this bad?** Floating point calculations are usually imprecise, so
75 /// asking if two values are *exactly* equal is asking for trouble. For a good
76 /// guide on what to do, see [the floating point
77 /// guide](http://www.floating-point-gui.de/errors/comparison).
79 /// **Known problems:** None.
83 /// let x = 1.2331f64;
84 /// let y = 1.2332f64;
85 /// if y == 1.23f64 { }
86 /// if y != x {} // where both are floats
90 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
93 declare_clippy_lint! {
94 /// **What it does:** Checks for conversions to owned values just for the sake
97 /// **Why is this bad?** The comparison can operate on a reference, so creating
98 /// an owned value effectively throws it away directly afterwards, which is
99 /// needlessly consuming code and heap space.
101 /// **Known problems:** None.
106 /// # let y = String::from("foo");
107 /// if x.to_owned() == y {}
109 /// Could be written as
112 /// # let y = String::from("foo");
117 "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
120 declare_clippy_lint! {
121 /// **What it does:** Checks for getting the remainder of a division by one.
123 /// **Why is this bad?** The result can only ever be zero. No one will write
124 /// such code deliberately, unless trying to win an Underhanded Rust
125 /// Contest. Even for that contest, it's probably a bad idea. Use something more
128 /// **Known problems:** None.
137 "taking a number modulo 1, which always returns 0"
140 declare_clippy_lint! {
141 /// **What it does:** Checks for the use of bindings with a single leading
144 /// **Why is this bad?** A single leading underscore is usually used to indicate
145 /// that a binding will not be used. Using such a binding breaks this
148 /// **Known problems:** The lint does not work properly with desugaring and
149 /// macro, it has been allowed in the mean time.
154 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
155 /// // underscore. We should rename `_x` to `x`
157 pub USED_UNDERSCORE_BINDING,
159 "using a binding which is prefixed with an underscore"
162 declare_clippy_lint! {
163 /// **What it does:** Checks for the use of short circuit boolean conditions as
167 /// **Why is this bad?** Using a short circuit boolean condition as a statement
168 /// may hide the fact that the second part is executed or not depending on the
169 /// outcome of the first part.
171 /// **Known problems:** None.
175 /// f() && g(); // We should write `if f() { g(); }`.
177 pub SHORT_CIRCUIT_STATEMENT,
179 "using a short circuit boolean condition as a statement"
182 declare_clippy_lint! {
183 /// **What it does:** Catch casts from `0` to some pointer type
185 /// **Why is this bad?** This generally means `null` and is better expressed as
186 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
188 /// **Known problems:** None.
193 /// let a = 0 as *const u32;
197 "using 0 as *{const, mut} T"
200 declare_clippy_lint! {
201 /// **What it does:** Checks for (in-)equality comparisons on floating-point
202 /// value and constant, except in functions called `*eq*` (which probably
203 /// implement equality for a type involving floats).
205 /// **Why is this bad?** Floating point calculations are usually imprecise, so
206 /// asking if two values are *exactly* equal is asking for trouble. For a good
207 /// guide on what to do, see [the floating point
208 /// guide](http://www.floating-point-gui.de/errors/comparison).
210 /// **Known problems:** None.
214 /// let x: f64 = 1.0;
215 /// const ONE: f64 = 1.00;
216 /// x == ONE; // where both are floats
220 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
223 declare_lint_pass!(MiscLints => [
229 USED_UNDERSCORE_BINDING,
230 SHORT_CIRCUIT_STATEMENT,
235 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints {
238 cx: &LateContext<'a, 'tcx>,
245 if let FnKind::Closure(_) = k {
246 // Does not apply to closures
249 for arg in iter_input_pats(decl, body) {
251 PatKind::Binding(BindingAnnotation::Ref, ..) | PatKind::Binding(BindingAnnotation::RefMut, ..) => {
256 "`ref` directly on a function argument is ignored. Consider using a reference type \
265 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
267 if let StmtKind::Local(ref local) = stmt.kind;
268 if let PatKind::Binding(an, .., name, None) = local.pat.kind;
269 if let Some(ref init) = local.init;
271 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
272 let sugg_init = if init.span.from_expansion() {
273 Sugg::hir_with_macro_callsite(cx, init, "..")
275 Sugg::hir(cx, init, "..")
277 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
278 ("mut ", sugg_init.mut_addr())
280 ("", sugg_init.addr())
282 let tyopt = if let Some(ref ty) = local.ty {
283 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
287 span_lint_hir_and_then(
292 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
298 "let {name}{tyopt} = {initref};",
299 name=snippet(cx, name.span, "_"),
303 Applicability::MachineApplicable,
311 if let StmtKind::Semi(ref expr) = stmt.kind;
312 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.kind;
313 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
314 if let Some(sugg) = Sugg::hir_opt(cx, a);
316 span_lint_and_then(cx,
317 SHORT_CIRCUIT_STATEMENT,
319 "boolean short circuit operator in statement may be clearer using an explicit test",
321 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
328 &snippet(cx, b.span, ".."),
330 Applicability::MachineApplicable, // snippet
337 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
339 ExprKind::Cast(ref e, ref ty) => {
340 check_cast(cx, expr.span, e, ty);
343 ExprKind::Binary(ref cmp, ref left, ref right) => {
345 if op.is_comparison() {
346 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.kind {
347 check_nan(cx, path, expr);
349 if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.kind {
350 check_nan(cx, path, expr);
352 check_to_owned(cx, left, right);
353 check_to_owned(cx, right, left);
355 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
356 if is_allowed(cx, left) || is_allowed(cx, right) {
360 // Allow comparing the results of signum()
361 if is_signum(cx, left) && is_signum(cx, right) {
365 if let Some(name) = get_item_name(cx, expr) {
366 let name = name.as_str();
370 || name.starts_with("eq_")
371 || name.ends_with("_eq")
376 let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
377 (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
379 (FLOAT_CMP, "strict comparison of f32 or f64")
381 span_lint_and_then(cx, lint, expr.span, msg, |db| {
382 let lhs = Sugg::hir(cx, left, "..");
383 let rhs = Sugg::hir(cx, right, "..");
387 "consider comparing them within some error",
389 "({}).abs() {} error",
391 if op == BinOpKind::Eq { '<' } else { '>' }
393 Applicability::HasPlaceholders, // snippet
395 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
397 } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) {
398 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
403 if in_attributes_expansion(expr) {
404 // Don't lint things expanded by #[derive(...)], etc
407 let binding = match expr.kind {
408 ExprKind::Path(ref qpath) => {
409 let binding = last_path_segment(qpath).ident.as_str();
410 if binding.starts_with('_') &&
411 !binding.starts_with("__") &&
412 binding != "_result" && // FIXME: #944
414 // don't lint if the declaration is in a macro
415 non_macro_local(cx, cx.tables.qpath_res(qpath, expr.hir_id))
422 ExprKind::Field(_, ident) => {
423 let name = ident.as_str();
424 if name.starts_with('_') && !name.starts_with("__") {
432 if let Some(binding) = binding {
435 USED_UNDERSCORE_BINDING,
438 "used binding `{}` which is prefixed with an underscore. A leading \
439 underscore signals that a binding will not be used.",
447 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
448 if !in_constant(cx, expr.hir_id) {
449 if let Some(seg) = path.segments.last() {
450 if seg.ident.name == sym!(NAN) {
455 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
462 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
463 if let Some((_, res)) = constant(cx, cx.tables, expr) {
470 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
471 match constant(cx, cx.tables, expr) {
472 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
473 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
478 // Return true if `expr` is the result of `signum()` invoked on a float value.
479 fn is_signum(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
480 // The negation of a signum is still a signum
481 if let ExprKind::Unary(UnNeg, ref child_expr) = expr.kind {
482 return is_signum(cx, &child_expr);
486 if let ExprKind::MethodCall(ref method_name, _, ref expressions) = expr.kind;
487 if sym!(signum) == method_name.ident.name;
488 // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
491 return is_float(cx, &expressions[0]);
497 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
498 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).kind, ty::Float(_))
501 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
502 let (arg_ty, snip) = match expr.kind {
503 ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
504 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
505 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
510 ExprKind::Call(ref path, ref v) if v.len() == 1 => {
511 if let ExprKind::Path(ref path) = path.kind {
512 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
513 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
524 let other_ty = cx.tables.expr_ty_adjusted(other);
525 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
530 let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
531 implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
533 let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
534 implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
536 let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
538 if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
542 let other_gets_derefed = match other.kind {
543 ExprKind::Unary(UnDeref, _) => true,
547 let lint_span = if other_gets_derefed {
548 expr.span.to(other.span)
557 "this creates an owned instance just for comparison",
559 // This also catches `PartialEq` implementations that call `to_owned`.
560 if other_gets_derefed {
561 db.span_label(lint_span, "try implementing the comparison without allocating");
565 let try_hint = if deref_arg_impl_partial_eq_other {
566 // suggest deref on the left
569 // suggest dropping the to_owned on the left
577 Applicability::MachineApplicable, // snippet
583 /// Heuristic to see if an expression is used. Should be compatible with
584 /// `unused_variables`'s idea
585 /// of what it means for an expression to be "used".
586 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
587 if let Some(parent) = get_parent_expr(cx, expr) {
589 ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
590 _ => is_used(cx, parent),
597 /// Tests whether an expression is in a macro expansion (e.g., something
598 /// generated by `#[derive(...)]` or the like).
599 fn in_attributes_expansion(expr: &Expr) -> bool {
600 use syntax_pos::hygiene::MacroKind;
601 if expr.span.from_expansion() {
602 let data = expr.span.ctxt().outer_expn_data();
604 if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind {
614 /// Tests whether `res` is a variable defined outside a macro.
615 fn non_macro_local(cx: &LateContext<'_, '_>, res: def::Res) -> bool {
616 if let def::Res::Local(id) = res {
617 !cx.tcx.hir().span(id).from_expansion()
623 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
625 if let TyKind::Ptr(ref mut_ty) = ty.kind;
626 if let ExprKind::Lit(ref lit) = e.kind;
627 if let LitKind::Int(0, _) = lit.node;
628 if !in_constant(cx, e.hir_id);
630 let (msg, sugg_fn) = match mut_ty.mutbl {
631 Mutability::Mutable => ("`0 as *mut _` detected", "std::ptr::null_mut"),
632 Mutability::Immutable => ("`0 as *const _` detected", "std::ptr::null"),
635 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
636 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
637 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
638 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
640 // `MaybeIncorrect` as type inference may not work with the suggested code
641 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
643 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);