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