1 use crate::reexport::*;
3 use crate::rustc::hir::*;
4 use crate::rustc::hir::intravisit::FnKind;
5 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use crate::rustc::{declare_tool_lint, lint_array};
7 use if_chain::if_chain;
9 use crate::syntax::source_map::{ExpnFormat, Span};
10 use crate::utils::{get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal,
11 iter_input_pats, last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint,
12 span_lint_and_then, walk_ptrs_ty, SpanlessEq};
13 use crate::utils::sugg::Sugg;
14 use crate::syntax::ast::{LitKind, CRATE_NODE_ID};
15 use crate::consts::{constant, Constant};
16 use crate::rustc_errors::Applicability;
18 /// **What it does:** Checks for function arguments and let bindings denoted as
21 /// **Why is this bad?** The `ref` declaration makes the function take an owned
22 /// value, but turns the argument into a reference (which means that the value
23 /// is destroyed when exiting the function). This adds not much value: either
24 /// take a reference type, or take an owned value and create references in the
27 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
28 /// type of `x` is more obvious with the former.
30 /// **Known problems:** If the argument is dereferenced within the function,
31 /// removing the `ref` will lead to errors. This can be fixed by removing the
32 /// dereferences, e.g. changing `*x` to `x` within the function.
36 /// fn foo(ref x: u8) -> bool { .. }
38 declare_clippy_lint! {
41 "an entire binding declared as `ref`, in a function argument or a `let` statement"
44 /// **What it does:** Checks for comparisons to NaN.
46 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
47 /// even itself – so those comparisons are simply wrong.
49 /// **Known problems:** None.
55 declare_clippy_lint! {
58 "comparisons to NAN, which will always return false, probably not intended"
61 /// **What it does:** Checks for (in-)equality comparisons on floating-point
62 /// values (apart from zero), except in functions called `*eq*` (which probably
63 /// implement equality for a type involving floats).
65 /// **Why is this bad?** Floating point calculations are usually imprecise, so
66 /// asking if two values are *exactly* equal is asking for trouble. For a good
67 /// guide on what to do, see [the floating point
68 /// guide](http://www.floating-point-gui.de/errors/comparison).
70 /// **Known problems:** None.
75 /// y != x // where both are floats
77 declare_clippy_lint! {
80 "using `==` or `!=` on float values instead of comparing difference with an epsilon"
83 /// **What it does:** Checks for conversions to owned values just for the sake
86 /// **Why is this bad?** The comparison can operate on a reference, so creating
87 /// an owned value effectively throws it away directly afterwards, which is
88 /// needlessly consuming code and heap space.
90 /// **Known problems:** None.
96 declare_clippy_lint! {
99 "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
102 /// **What it does:** Checks for getting the remainder of a division by one.
104 /// **Why is this bad?** The result can only ever be zero. No one will write
105 /// such code deliberately, unless trying to win an Underhanded Rust
106 /// Contest. Even for that contest, it's probably a bad idea. Use something more
109 /// **Known problems:** None.
115 declare_clippy_lint! {
118 "taking a number modulo 1, which always returns 0"
121 /// **What it does:** Checks for patterns in the form `name @ _`.
123 /// **Why is this bad?** It's almost always more readable to just use direct
126 /// **Known problems:** None.
132 /// y @ _ => (), // easier written as `y`,
135 declare_clippy_lint! {
136 pub REDUNDANT_PATTERN,
138 "using `name @ _` in a pattern"
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 declare_clippy_lint! {
158 pub USED_UNDERSCORE_BINDING,
160 "using a binding which is prefixed with an underscore"
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 declare_clippy_lint! {
178 pub SHORT_CIRCUIT_STATEMENT,
180 "using a short circuit boolean condition as a statement"
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.
195 declare_clippy_lint! {
198 "using 0 as *{const, mut} T"
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 /// const ONE == 1.00f64
215 /// x == ONE // where both are floats
217 declare_clippy_lint! {
220 "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
223 #[derive(Copy, Clone)]
226 impl LintPass for Pass {
227 fn get_lints(&self) -> LintArray {
235 USED_UNDERSCORE_BINDING,
236 SHORT_CIRCUIT_STATEMENT,
243 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
246 cx: &LateContext<'a, 'tcx>,
253 if let FnKind::Closure(_) = k {
254 // Does not apply to closures
257 for arg in iter_input_pats(decl, body) {
259 PatKind::Binding(BindingAnnotation::Ref, _, _, _) |
260 PatKind::Binding(BindingAnnotation::RefMut, _, _, _) => {
265 "`ref` directly on a function argument is ignored. Consider using a reference type \
274 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
276 if let StmtKind::Decl(ref d, _) = s.node;
277 if let DeclKind::Local(ref l) = d.node;
278 if let PatKind::Binding(an, _, i, None) = l.pat.node;
279 if let Some(ref init) = l.init;
281 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
282 let init = Sugg::hir(cx, init, "..");
283 let (mutopt,initref) = if an == BindingAnnotation::RefMut {
284 ("mut ", init.mut_addr())
288 let tyopt = if let Some(ref ty) = l.ty {
289 format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
293 span_lint_and_then(cx,
296 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
298 db.span_suggestion_with_applicability(
302 "let {name}{tyopt} = {initref};",
303 name=snippet(cx, i.span, "_"),
307 Applicability::MachineApplicable, // snippet
315 if let StmtKind::Semi(ref expr, _) = s.node;
316 if let ExprKind::Binary(ref binop, ref a, ref b) = expr.node;
317 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
318 if let Some(sugg) = Sugg::hir_opt(cx, a);
320 span_lint_and_then(cx,
321 SHORT_CIRCUIT_STATEMENT,
323 "boolean short circuit operator in statement may be clearer using an explicit test",
325 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
326 db.span_suggestion_with_applicability(
332 &snippet(cx, b.span, ".."),
334 Applicability::MachineApplicable, // snippet
341 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
343 ExprKind::Cast(ref e, ref ty) => {
344 check_cast(cx, expr.span, e, ty);
347 ExprKind::Binary(ref cmp, ref left, ref right) => {
349 if op.is_comparison() {
350 if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node {
351 check_nan(cx, path, expr);
353 if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.node {
354 check_nan(cx, path, expr);
356 check_to_owned(cx, left, right);
357 check_to_owned(cx, right, left);
359 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
360 if is_allowed(cx, left) || is_allowed(cx, right) {
363 if let Some(name) = get_item_name(cx, expr) {
364 let name = name.as_str();
365 if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_")
366 || name.ends_with("_eq")
371 let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
372 (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
374 (FLOAT_CMP, "strict comparison of f32 or f64")
376 span_lint_and_then(cx, lint, expr.span, msg, |db| {
377 let lhs = Sugg::hir(cx, left, "..");
378 let rhs = Sugg::hir(cx, right, "..");
380 db.span_suggestion_with_applicability(
382 "consider comparing them within some error",
383 format!("({}).abs() < error", lhs - rhs),
384 Applicability::MachineApplicable, // snippet
386 db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
388 } else if op == BinOpKind::Rem && is_integer_literal(right, 1) {
389 span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
394 if in_attributes_expansion(expr) {
395 // Don't lint things expanded by #[derive(...)], etc
398 let binding = match expr.node {
399 ExprKind::Path(ref qpath) => {
400 let binding = last_path_segment(qpath).ident.as_str();
401 if binding.starts_with('_') &&
402 !binding.starts_with("__") &&
403 binding != "_result" && // FIXME: #944
405 // don't lint if the declaration is in a macro
406 non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
413 ExprKind::Field(_, ident) => {
414 let name = ident.as_str();
415 if name.starts_with('_') && !name.starts_with("__") {
423 if let Some(binding) = binding {
426 USED_UNDERSCORE_BINDING,
429 "used binding `{}` which is prefixed with an underscore. A leading \
430 underscore signals that a binding will not be used.",
437 fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
438 if let PatKind::Binding(_, _, ident, Some(ref right)) = pat.node {
439 if let PatKind::Wild = right.node {
444 &format!("the `{} @ _` pattern can be written as just `{}`", ident.name, ident.name),
451 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
452 if !in_constant(cx, expr.id) {
453 if let Some(seg) = path.segments.last() {
454 if seg.ident.name == "NAN" {
459 "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
466 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
467 if let Some((_, res)) = constant(cx, cx.tables, expr) {
474 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
475 match constant(cx, cx.tables, expr) {
476 Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
477 Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
482 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
483 matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::Float(_))
486 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
487 let (arg_ty, snip) = match expr.node {
488 ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
489 if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
490 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
495 ExprKind::Call(ref path, ref v) if v.len() == 1 => if let ExprKind::Path(ref path) = path.node {
496 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
497 (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
507 let other_ty = cx.tables.expr_ty_adjusted(other);
508 let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
513 // *arg impls PartialEq<other>
516 .map_or(false, |tam| implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()]))
517 // arg impls PartialEq<*other>
520 .map_or(false, |tam| implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()]))
521 // arg impls PartialEq<other>
522 && !implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()])
531 "this creates an owned instance just for comparison",
533 // this is as good as our recursion check can get, we can't prove that the
534 // current function is
536 // PartialEq::eq, but we can at least ensure that this code is not part of it
537 let parent_fn = cx.tcx.hir.get_parent(expr.id);
538 let parent_impl = cx.tcx.hir.get_parent(parent_fn);
539 if parent_impl != CRATE_NODE_ID {
540 if let Node::Item(item) = cx.tcx.hir.get(parent_impl) {
541 if let ItemKind::Impl(.., Some(ref trait_ref), _, _) = item.node {
542 if trait_ref.path.def.def_id() == partial_eq_trait_id {
543 // we are implementing PartialEq, don't suggest not doing `to_owned`, otherwise
546 db.span_label(expr.span, "try calling implementing the comparison without allocating");
552 db.span_suggestion_with_applicability(
556 Applicability::MachineApplicable, // snippet
562 /// Heuristic to see if an expression is used. Should be compatible with
563 /// `unused_variables`'s idea
564 /// of what it means for an expression to be "used".
565 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
566 if let Some(parent) = get_parent_expr(cx, expr) {
568 ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
569 _ => is_used(cx, parent),
576 /// Test whether an expression is in a macro expansion (e.g. something
578 /// `#[derive(...)`] or the like).
579 fn in_attributes_expansion(expr: &Expr) -> bool {
584 .map_or(false, |info| matches!(info.format, ExpnFormat::MacroAttribute(_)))
587 /// Test whether `def` is a variable defined outside a macro.
588 fn non_macro_local(cx: &LateContext<'_, '_>, def: &def::Def) -> bool {
590 def::Def::Local(id) | def::Def::Upvar(id, _, _) => !in_macro(cx.tcx.hir.span(id)),
595 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
597 if let TyKind::Ptr(MutTy { mutbl, .. }) = ty.node;
598 if let ExprKind::Lit(ref lit) = e.node;
599 if let LitKind::Int(value, ..) = lit.node;
601 if !in_constant(cx, e.id);
603 let msg = match mutbl {
604 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
605 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
607 span_lint(cx, ZERO_PTR, span, msg);