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