]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc.rs
Auto merge of #4910 - krishna-veerareddy:issue-1205-cmp-nan-against-consts, r=phansch
[rust.git] / clippy_lints / src / misc.rs
1 use if_chain::if_chain;
2 use matches::matches;
3 use rustc::declare_lint_pass;
4 use rustc::hir::intravisit::FnKind;
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::ty;
8 use rustc_errors::Applicability;
9 use rustc_session::declare_tool_lint;
10 use syntax::ast::LitKind;
11 use syntax::source_map::{ExpnKind, Span};
12
13 use crate::consts::{constant, Constant};
14 use crate::utils::sugg::Sugg;
15 use crate::utils::{
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,
19 };
20
21 declare_clippy_lint! {
22     /// **What it does:** Checks for function arguments and let bindings denoted as
23     /// `ref`.
24     ///
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
29     /// body.
30     ///
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.
33     ///
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.
37     ///
38     /// **Example:**
39     /// ```rust
40     /// fn foo(ref x: u8) -> bool {
41     ///     true
42     /// }
43     /// ```
44     pub TOPLEVEL_REF_ARG,
45     style,
46     "an entire binding declared as `ref`, in a function argument or a `let` statement"
47 }
48
49 declare_clippy_lint! {
50     /// **What it does:** Checks for comparisons to NaN.
51     ///
52     /// **Why is this bad?** NaN does not compare meaningfully to anything – not
53     /// even itself – so those comparisons are simply wrong.
54     ///
55     /// **Known problems:** None.
56     ///
57     /// **Example:**
58     /// ```rust
59     /// # use core::f32::NAN;
60     /// # let x = 1.0;
61     ///
62     /// if x == NAN { }
63     /// ```
64     pub CMP_NAN,
65     correctness,
66     "comparisons to NAN, which will always return false, probably not intended"
67 }
68
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).
73     ///
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).
78     ///
79     /// **Known problems:** None.
80     ///
81     /// **Example:**
82     /// ```rust
83     /// let x = 1.2331f64;
84     /// let y = 1.2332f64;
85     /// if y == 1.23f64 { }
86     /// if y != x {} // where both are floats
87     /// ```
88     pub FLOAT_CMP,
89     correctness,
90     "using `==` or `!=` on float values instead of comparing difference with an epsilon"
91 }
92
93 declare_clippy_lint! {
94     /// **What it does:** Checks for conversions to owned values just for the sake
95     /// of a comparison.
96     ///
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.
100     ///
101     /// **Known problems:** None.
102     ///
103     /// **Example:**
104     /// ```rust
105     /// # let x = "foo";
106     /// # let y = String::from("foo");
107     /// if x.to_owned() == y {}
108     /// ```
109     /// Could be written as
110     /// ```rust
111     /// # let x = "foo";
112     /// # let y = String::from("foo");
113     /// if x == y {}
114     /// ```
115     pub CMP_OWNED,
116     perf,
117     "creating owned instances for comparing with others, e.g., `x == \"foo\".to_string()`"
118 }
119
120 declare_clippy_lint! {
121     /// **What it does:** Checks for getting the remainder of a division by one.
122     ///
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
126     /// underhanded.
127     ///
128     /// **Known problems:** None.
129     ///
130     /// **Example:**
131     /// ```rust
132     /// # let x = 1;
133     /// let a = x % 1;
134     /// ```
135     pub MODULO_ONE,
136     correctness,
137     "taking a number modulo 1, which always returns 0"
138 }
139
140 declare_clippy_lint! {
141     /// **What it does:** Checks for the use of bindings with a single leading
142     /// underscore.
143     ///
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
146     /// expectation.
147     ///
148     /// **Known problems:** The lint does not work properly with desugaring and
149     /// macro, it has been allowed in the mean time.
150     ///
151     /// **Example:**
152     /// ```rust
153     /// let _x = 0;
154     /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
155     ///                 // underscore. We should rename `_x` to `x`
156     /// ```
157     pub USED_UNDERSCORE_BINDING,
158     pedantic,
159     "using a binding which is prefixed with an underscore"
160 }
161
162 declare_clippy_lint! {
163     /// **What it does:** Checks for the use of short circuit boolean conditions as
164     /// a
165     /// statement.
166     ///
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.
170     ///
171     /// **Known problems:** None.
172     ///
173     /// **Example:**
174     /// ```rust,ignore
175     /// f() && g(); // We should write `if f() { g(); }`.
176     /// ```
177     pub SHORT_CIRCUIT_STATEMENT,
178     complexity,
179     "using a short circuit boolean condition as a statement"
180 }
181
182 declare_clippy_lint! {
183     /// **What it does:** Catch casts from `0` to some pointer type
184     ///
185     /// **Why is this bad?** This generally means `null` and is better expressed as
186     /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
187     ///
188     /// **Known problems:** None.
189     ///
190     /// **Example:**
191     ///
192     /// ```rust
193     /// let a = 0 as *const u32;
194     /// ```
195     pub ZERO_PTR,
196     style,
197     "using 0 as *{const, mut} T"
198 }
199
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).
204     ///
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).
209     ///
210     /// **Known problems:** None.
211     ///
212     /// **Example:**
213     /// ```rust
214     /// let x: f64 = 1.0;
215     /// const ONE: f64 = 1.00;
216     /// x == ONE;  // where both are floats
217     /// ```
218     pub FLOAT_CMP_CONST,
219     restriction,
220     "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
221 }
222
223 declare_lint_pass!(MiscLints => [
224     TOPLEVEL_REF_ARG,
225     CMP_NAN,
226     FLOAT_CMP,
227     CMP_OWNED,
228     MODULO_ONE,
229     USED_UNDERSCORE_BINDING,
230     SHORT_CIRCUIT_STATEMENT,
231     ZERO_PTR,
232     FLOAT_CMP_CONST
233 ]);
234
235 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints {
236     fn check_fn(
237         &mut self,
238         cx: &LateContext<'a, 'tcx>,
239         k: FnKind<'tcx>,
240         decl: &'tcx FnDecl,
241         body: &'tcx Body,
242         _: Span,
243         _: HirId,
244     ) {
245         if let FnKind::Closure(_) = k {
246             // Does not apply to closures
247             return;
248         }
249         for arg in iter_input_pats(decl, body) {
250             match arg.pat.kind {
251                 PatKind::Binding(BindingAnnotation::Ref, ..) | PatKind::Binding(BindingAnnotation::RefMut, ..) => {
252                     span_lint(
253                         cx,
254                         TOPLEVEL_REF_ARG,
255                         arg.pat.span,
256                         "`ref` directly on a function argument is ignored. Consider using a reference type \
257                          instead.",
258                     );
259                 },
260                 _ => {},
261             }
262         }
263     }
264
265     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
266         if_chain! {
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;
270             then {
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, "..")
274                     } else {
275                         Sugg::hir(cx, init, "..")
276                     };
277                     let (mutopt, initref) = if an == BindingAnnotation::RefMut {
278                         ("mut ", sugg_init.mut_addr())
279                     } else {
280                         ("", sugg_init.addr())
281                     };
282                     let tyopt = if let Some(ref ty) = local.ty {
283                         format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
284                     } else {
285                         String::new()
286                     };
287                     span_lint_hir_and_then(
288                         cx,
289                         TOPLEVEL_REF_ARG,
290                         init.hir_id,
291                         local.pat.span,
292                         "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
293                         |db| {
294                             db.span_suggestion(
295                                 stmt.span,
296                                 "try",
297                                 format!(
298                                     "let {name}{tyopt} = {initref};",
299                                     name=snippet(cx, name.span, "_"),
300                                     tyopt=tyopt,
301                                     initref=initref,
302                                 ),
303                                 Applicability::MachineApplicable,
304                             );
305                         }
306                     );
307                 }
308             }
309         };
310         if_chain! {
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);
315             then {
316                 span_lint_and_then(cx,
317                     SHORT_CIRCUIT_STATEMENT,
318                     stmt.span,
319                     "boolean short circuit operator in statement may be clearer using an explicit test",
320                     |db| {
321                         let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
322                         db.span_suggestion(
323                             stmt.span,
324                             "replace it with",
325                             format!(
326                                 "if {} {{ {}; }}",
327                                 sugg,
328                                 &snippet(cx, b.span, ".."),
329                             ),
330                             Applicability::MachineApplicable, // snippet
331                         );
332                     });
333             }
334         };
335     }
336
337     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
338         match expr.kind {
339             ExprKind::Cast(ref e, ref ty) => {
340                 check_cast(cx, expr.span, e, ty);
341                 return;
342             },
343             ExprKind::Binary(ref cmp, ref left, ref right) => {
344                 let op = cmp.node;
345                 if op.is_comparison() {
346                     check_nan(cx, left, expr);
347                     check_nan(cx, right, expr);
348                     check_to_owned(cx, left, right);
349                     check_to_owned(cx, right, left);
350                 }
351                 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
352                     if is_allowed(cx, left) || is_allowed(cx, right) {
353                         return;
354                     }
355
356                     // Allow comparing the results of signum()
357                     if is_signum(cx, left) && is_signum(cx, right) {
358                         return;
359                     }
360
361                     if let Some(name) = get_item_name(cx, expr) {
362                         let name = name.as_str();
363                         if name == "eq"
364                             || name == "ne"
365                             || name == "is_nan"
366                             || name.starts_with("eq_")
367                             || name.ends_with("_eq")
368                         {
369                             return;
370                         }
371                     }
372                     let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
373                         (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
374                     } else {
375                         (FLOAT_CMP, "strict comparison of f32 or f64")
376                     };
377                     span_lint_and_then(cx, lint, expr.span, msg, |db| {
378                         let lhs = Sugg::hir(cx, left, "..");
379                         let rhs = Sugg::hir(cx, right, "..");
380
381                         db.span_suggestion(
382                             expr.span,
383                             "consider comparing them within some error",
384                             format!(
385                                 "({}).abs() {} error",
386                                 lhs - rhs,
387                                 if op == BinOpKind::Eq { '<' } else { '>' }
388                             ),
389                             Applicability::HasPlaceholders, // snippet
390                         );
391                         db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
392                     });
393                 } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) {
394                     span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
395                 }
396             },
397             _ => {},
398         }
399         if in_attributes_expansion(expr) {
400             // Don't lint things expanded by #[derive(...)], etc
401             return;
402         }
403         let binding = match expr.kind {
404             ExprKind::Path(ref qpath) => {
405                 let binding = last_path_segment(qpath).ident.as_str();
406                 if binding.starts_with('_') &&
407                     !binding.starts_with("__") &&
408                     binding != "_result" && // FIXME: #944
409                     is_used(cx, expr) &&
410                     // don't lint if the declaration is in a macro
411                     non_macro_local(cx, cx.tables.qpath_res(qpath, expr.hir_id))
412                 {
413                     Some(binding)
414                 } else {
415                     None
416                 }
417             },
418             ExprKind::Field(_, ident) => {
419                 let name = ident.as_str();
420                 if name.starts_with('_') && !name.starts_with("__") {
421                     Some(name)
422                 } else {
423                     None
424                 }
425             },
426             _ => None,
427         };
428         if let Some(binding) = binding {
429             span_lint(
430                 cx,
431                 USED_UNDERSCORE_BINDING,
432                 expr.span,
433                 &format!(
434                     "used binding `{}` which is prefixed with an underscore. A leading \
435                      underscore signals that a binding will not be used.",
436                     binding
437                 ),
438             );
439         }
440     }
441 }
442
443 fn check_nan(cx: &LateContext<'_, '_>, expr: &Expr, cmp_expr: &Expr) {
444     if_chain! {
445         if !in_constant(cx, cmp_expr.hir_id);
446         if let Some((value, _)) = constant(cx, cx.tables, expr);
447         then {
448             let needs_lint = match value {
449                 Constant::F32(num) => num.is_nan(),
450                 Constant::F64(num) => num.is_nan(),
451                 _ => false,
452             };
453
454             if needs_lint {
455                 span_lint(
456                     cx,
457                     CMP_NAN,
458                     cmp_expr.span,
459                     "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
460                 );
461             }
462         }
463     }
464 }
465
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) {
468         res
469     } else {
470         false
471     }
472 }
473
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(),
478         _ => false,
479     }
480 }
481
482 // Return true if `expr` is the result of `signum()` invoked on a float value.
483 fn is_signum(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
484     // The negation of a signum is still a signum
485     if let ExprKind::Unary(UnNeg, ref child_expr) = expr.kind {
486         return is_signum(cx, &child_expr);
487     }
488
489     if_chain! {
490         if let ExprKind::MethodCall(ref method_name, _, ref expressions) = expr.kind;
491         if sym!(signum) == method_name.ident.name;
492         // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
493         // the method call)
494         then {
495             return is_float(cx, &expressions[0]);
496         }
497     }
498     false
499 }
500
501 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
502     matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).kind, ty::Float(_))
503 }
504
505 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
506     let (arg_ty, snip) = match expr.kind {
507         ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
508             if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
509                 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
510             } else {
511                 return;
512             }
513         },
514         ExprKind::Call(ref path, ref v) if v.len() == 1 => {
515             if let ExprKind::Path(ref path) = path.kind {
516                 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
517                     (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
518                 } else {
519                     return;
520                 }
521             } else {
522                 return;
523             }
524         },
525         _ => return,
526     };
527
528     let other_ty = cx.tables.expr_ty_adjusted(other);
529     let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
530         Some(id) => id,
531         None => return,
532     };
533
534     let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
535         implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
536     });
537     let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
538         implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
539     });
540     let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
541
542     if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
543         return;
544     }
545
546     let other_gets_derefed = match other.kind {
547         ExprKind::Unary(UnDeref, _) => true,
548         _ => false,
549     };
550
551     let lint_span = if other_gets_derefed {
552         expr.span.to(other.span)
553     } else {
554         expr.span
555     };
556
557     span_lint_and_then(
558         cx,
559         CMP_OWNED,
560         lint_span,
561         "this creates an owned instance just for comparison",
562         |db| {
563             // This also catches `PartialEq` implementations that call `to_owned`.
564             if other_gets_derefed {
565                 db.span_label(lint_span, "try implementing the comparison without allocating");
566                 return;
567             }
568
569             let try_hint = if deref_arg_impl_partial_eq_other {
570                 // suggest deref on the left
571                 format!("*{}", snip)
572             } else {
573                 // suggest dropping the to_owned on the left
574                 snip.to_string()
575             };
576
577             db.span_suggestion(
578                 lint_span,
579                 "try",
580                 try_hint,
581                 Applicability::MachineApplicable, // snippet
582             );
583         },
584     );
585 }
586
587 /// Heuristic to see if an expression is used. Should be compatible with
588 /// `unused_variables`'s idea
589 /// of what it means for an expression to be "used".
590 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
591     if let Some(parent) = get_parent_expr(cx, expr) {
592         match parent.kind {
593             ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
594             _ => is_used(cx, parent),
595         }
596     } else {
597         true
598     }
599 }
600
601 /// Tests whether an expression is in a macro expansion (e.g., something
602 /// generated by `#[derive(...)]` or the like).
603 fn in_attributes_expansion(expr: &Expr) -> bool {
604     use syntax_pos::hygiene::MacroKind;
605     if expr.span.from_expansion() {
606         let data = expr.span.ctxt().outer_expn_data();
607
608         if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind {
609             true
610         } else {
611             false
612         }
613     } else {
614         false
615     }
616 }
617
618 /// Tests whether `res` is a variable defined outside a macro.
619 fn non_macro_local(cx: &LateContext<'_, '_>, res: def::Res) -> bool {
620     if let def::Res::Local(id) = res {
621         !cx.tcx.hir().span(id).from_expansion()
622     } else {
623         false
624     }
625 }
626
627 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
628     if_chain! {
629         if let TyKind::Ptr(ref mut_ty) = ty.kind;
630         if let ExprKind::Lit(ref lit) = e.kind;
631         if let LitKind::Int(0, _) = lit.node;
632         if !in_constant(cx, e.hir_id);
633         then {
634             let (msg, sugg_fn) = match mut_ty.mutbl {
635                 Mutability::Mutable => ("`0 as *mut _` detected", "std::ptr::null_mut"),
636                 Mutability::Immutable => ("`0 as *const _` detected", "std::ptr::null"),
637             };
638
639             let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
640                 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
641             } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
642                 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
643             } else {
644                 // `MaybeIncorrect` as type inference may not work with the suggested code
645                 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
646             };
647             span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);
648         }
649     }
650 }