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