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