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