]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc.rs
Auto merge of #3558 - russelltg:new_without_default_merge, r=flip1995
[rust.git] / clippy_lints / src / misc.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::consts::{constant, Constant};
11 use crate::reexport::*;
12 use crate::utils::sugg::Sugg;
13 use crate::utils::{
14     get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal, iter_input_pats,
15     last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint, span_lint_and_then, walk_ptrs_ty,
16     SpanlessEq,
17 };
18 use if_chain::if_chain;
19 use matches::matches;
20 use rustc::hir::intravisit::FnKind;
21 use rustc::hir::*;
22 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
23 use rustc::ty;
24 use rustc::{declare_tool_lint, lint_array};
25 use rustc_errors::Applicability;
26 use syntax::ast::LitKind;
27 use syntax::source_map::{ExpnFormat, Span};
28
29 /// **What it does:** Checks for function arguments and let bindings denoted as
30 /// `ref`.
31 ///
32 /// **Why is this bad?** The `ref` declaration makes the function take an owned
33 /// value, but turns the argument into a reference (which means that the value
34 /// is destroyed when exiting the function). This adds not much value: either
35 /// take a reference type, or take an owned value and create references in the
36 /// body.
37 ///
38 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
39 /// type of `x` is more obvious with the former.
40 ///
41 /// **Known problems:** If the argument is dereferenced within the function,
42 /// removing the `ref` will lead to errors. This can be fixed by removing the
43 /// dereferences, e.g. changing `*x` to `x` within the function.
44 ///
45 /// **Example:**
46 /// ```rust
47 /// fn foo(ref x: u8) -> bool {
48 ///     ..
49 /// }
50 /// ```
51 declare_clippy_lint! {
52     pub TOPLEVEL_REF_ARG,
53     style,
54     "an entire binding declared as `ref`, in a function argument or a `let` statement"
55 }
56
57 /// **What it does:** Checks for comparisons to NaN.
58 ///
59 /// **Why is this bad?** NaN does not compare meaningfully to anything – not
60 /// even itself – so those comparisons are simply wrong.
61 ///
62 /// **Known problems:** None.
63 ///
64 /// **Example:**
65 /// ```rust
66 /// x == NAN
67 /// ```
68 declare_clippy_lint! {
69     pub CMP_NAN,
70     correctness,
71     "comparisons to NAN, which will always return false, probably not intended"
72 }
73
74 /// **What it does:** Checks for (in-)equality comparisons on floating-point
75 /// values (apart from zero), except in functions called `*eq*` (which probably
76 /// implement equality for a type involving floats).
77 ///
78 /// **Why is this bad?** Floating point calculations are usually imprecise, so
79 /// asking if two values are *exactly* equal is asking for trouble. For a good
80 /// guide on what to do, see [the floating point
81 /// guide](http://www.floating-point-gui.de/errors/comparison).
82 ///
83 /// **Known problems:** None.
84 ///
85 /// **Example:**
86 /// ```rust
87 /// y == 1.23f64
88 /// y != x  // where both are floats
89 /// ```
90 declare_clippy_lint! {
91     pub FLOAT_CMP,
92     correctness,
93     "using `==` or `!=` on float values instead of comparing difference with an epsilon"
94 }
95
96 /// **What it does:** Checks for conversions to owned values just for the sake
97 /// of a comparison.
98 ///
99 /// **Why is this bad?** The comparison can operate on a reference, so creating
100 /// an owned value effectively throws it away directly afterwards, which is
101 /// needlessly consuming code and heap space.
102 ///
103 /// **Known problems:** None.
104 ///
105 /// **Example:**
106 /// ```rust
107 /// x.to_owned() == y
108 /// ```
109 declare_clippy_lint! {
110     pub CMP_OWNED,
111     perf,
112     "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
113 }
114
115 /// **What it does:** Checks for getting the remainder of a division by one.
116 ///
117 /// **Why is this bad?** The result can only ever be zero. No one will write
118 /// such code deliberately, unless trying to win an Underhanded Rust
119 /// Contest. Even for that contest, it's probably a bad idea. Use something more
120 /// underhanded.
121 ///
122 /// **Known problems:** None.
123 ///
124 /// **Example:**
125 /// ```rust
126 /// x % 1
127 /// ```
128 declare_clippy_lint! {
129     pub MODULO_ONE,
130     correctness,
131     "taking a number modulo 1, which always returns 0"
132 }
133
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 /// match v {
144 ///     Some(x) => (),
145 ///     y @ _ => (), // easier written as `y`,
146 /// }
147 /// ```
148 declare_clippy_lint! {
149     pub REDUNDANT_PATTERN,
150     style,
151     "using `name @ _` in a pattern"
152 }
153
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 declare_clippy_lint! {
171     pub USED_UNDERSCORE_BINDING,
172     pedantic,
173     "using a binding which is prefixed with an underscore"
174 }
175
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
188 /// f() && g(); // We should write `if f() { g(); }`.
189 /// ```
190 declare_clippy_lint! {
191     pub SHORT_CIRCUIT_STATEMENT,
192     complexity,
193     "using a short circuit boolean condition as a statement"
194 }
195
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 /// 0 as *const u32
207 /// ```
208 declare_clippy_lint! {
209     pub ZERO_PTR,
210     style,
211     "using 0 as *{const, mut} T"
212 }
213
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 declare_clippy_lint! {
231     pub FLOAT_CMP_CONST,
232     restriction,
233     "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
234 }
235
236 #[derive(Copy, Clone)]
237 pub struct Pass;
238
239 impl LintPass for Pass {
240     fn get_lints(&self) -> LintArray {
241         lint_array!(
242             TOPLEVEL_REF_ARG,
243             CMP_NAN,
244             FLOAT_CMP,
245             CMP_OWNED,
246             MODULO_ONE,
247             REDUNDANT_PATTERN,
248             USED_UNDERSCORE_BINDING,
249             SHORT_CIRCUIT_STATEMENT,
250             ZERO_PTR,
251             FLOAT_CMP_CONST
252         )
253     }
254 }
255
256 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
257     fn check_fn(
258         &mut self,
259         cx: &LateContext<'a, 'tcx>,
260         k: FnKind<'tcx>,
261         decl: &'tcx FnDecl,
262         body: &'tcx Body,
263         _: Span,
264         _: NodeId,
265     ) {
266         if let FnKind::Closure(_) = k {
267             // Does not apply to closures
268             return;
269         }
270         for arg in iter_input_pats(decl, body) {
271             match arg.pat.node {
272                 PatKind::Binding(BindingAnnotation::Ref, _, _, _)
273                 | 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::Decl(ref d, _) = s.node;
290             if let DeclKind::Local(ref l) = d.node;
291             if let PatKind::Binding(an, _, i, None) = l.pat.node;
292             if let Some(ref init) = l.init;
293             then {
294                 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
295                     let init = Sugg::hir(cx, init, "..");
296                     let (mutopt,initref) = if an == BindingAnnotation::RefMut {
297                         ("mut ", init.mut_addr())
298                     } else {
299                         ("", init.addr())
300                     };
301                     let tyopt = if let Some(ref ty) = l.ty {
302                         format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
303                     } else {
304                         String::new()
305                     };
306                     span_lint_and_then(cx,
307                         TOPLEVEL_REF_ARG,
308                         l.pat.span,
309                         "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
310                         |db| {
311                             db.span_suggestion_with_applicability(
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_with_applicability(
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                     if let Some(name) = get_item_name(cx, expr) {
377                         let name = name.as_str();
378                         if name == "eq"
379                             || name == "ne"
380                             || name == "is_nan"
381                             || name.starts_with("eq_")
382                             || name.ends_with("_eq")
383                         {
384                             return;
385                         }
386                     }
387                     let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
388                         (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
389                     } else {
390                         (FLOAT_CMP, "strict comparison of f32 or f64")
391                     };
392                     span_lint_and_then(cx, lint, expr.span, msg, |db| {
393                         let lhs = Sugg::hir(cx, left, "..");
394                         let rhs = Sugg::hir(cx, right, "..");
395
396                         db.span_suggestion_with_applicability(
397                             expr.span,
398                             "consider comparing them within some error",
399                             format!("({}).abs() < error", lhs - rhs),
400                             Applicability::MachineApplicable, // snippet
401                         );
402                         db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
403                     });
404                 } else if op == BinOpKind::Rem && is_integer_literal(right, 1) {
405                     span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
406                 }
407             },
408             _ => {},
409         }
410         if in_attributes_expansion(expr) {
411             // Don't lint things expanded by #[derive(...)], etc
412             return;
413         }
414         let binding = match expr.node {
415             ExprKind::Path(ref qpath) => {
416                 let binding = last_path_segment(qpath).ident.as_str();
417                 if binding.starts_with('_') &&
418                     !binding.starts_with("__") &&
419                     binding != "_result" && // FIXME: #944
420                     is_used(cx, expr) &&
421                     // don't lint if the declaration is in a macro
422                     non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
423                 {
424                     Some(binding)
425                 } else {
426                     None
427                 }
428             },
429             ExprKind::Field(_, ident) => {
430                 let name = ident.as_str();
431                 if name.starts_with('_') && !name.starts_with("__") {
432                     Some(name)
433                 } else {
434                     None
435                 }
436             },
437             _ => None,
438         };
439         if let Some(binding) = binding {
440             span_lint(
441                 cx,
442                 USED_UNDERSCORE_BINDING,
443                 expr.span,
444                 &format!(
445                     "used binding `{}` which is prefixed with an underscore. A leading \
446                      underscore signals that a binding will not be used.",
447                     binding
448                 ),
449             );
450         }
451     }
452
453     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
454         if let PatKind::Binding(_, _, ident, Some(ref right)) = pat.node {
455             if let PatKind::Wild = right.node {
456                 span_lint(
457                     cx,
458                     REDUNDANT_PATTERN,
459                     pat.span,
460                     &format!(
461                         "the `{} @ _` pattern can be written as just `{}`",
462                         ident.name, ident.name
463                     ),
464                 );
465             }
466         }
467     }
468 }
469
470 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
471     if !in_constant(cx, expr.id) {
472         if let Some(seg) = path.segments.last() {
473             if seg.ident.name == "NAN" {
474                 span_lint(
475                     cx,
476                     CMP_NAN,
477                     expr.span,
478                     "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
479                 );
480             }
481         }
482     }
483 }
484
485 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
486     if let Some((_, res)) = constant(cx, cx.tables, expr) {
487         res
488     } else {
489         false
490     }
491 }
492
493 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
494     match constant(cx, cx.tables, expr) {
495         Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
496         Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
497         _ => false,
498     }
499 }
500
501 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
502     matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::Float(_))
503 }
504
505 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
506     let (arg_ty, snip) = match expr.node {
507         ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
508             if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
509                 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
510             } else {
511                 return;
512             }
513         },
514         ExprKind::Call(ref path, ref v) if v.len() == 1 => {
515             if let ExprKind::Path(ref path) = path.node {
516                 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
517                     (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
518                 } else {
519                     return;
520                 }
521             } else {
522                 return;
523             }
524         },
525         _ => return,
526     };
527
528     let other_ty = cx.tables.expr_ty_adjusted(other);
529     let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
530         Some(id) => id,
531         None => return,
532     };
533
534     let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
535         implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
536     });
537     let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
538         implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
539     });
540     let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
541
542     if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
543         return;
544     }
545
546     let other_gets_derefed = match other.node {
547         ExprKind::Unary(UnDeref, _) => true,
548         _ => false,
549     };
550
551     let lint_span = if other_gets_derefed {
552         expr.span.to(other.span)
553     } else {
554         expr.span
555     };
556
557     span_lint_and_then(
558         cx,
559         CMP_OWNED,
560         lint_span,
561         "this creates an owned instance just for comparison",
562         |db| {
563             // this also catches PartialEq implementations that call to_owned
564             if other_gets_derefed {
565                 db.span_label(lint_span, "try implementing the comparison without allocating");
566                 return;
567             }
568
569             let try_hint = if deref_arg_impl_partial_eq_other {
570                 // suggest deref on the left
571                 format!("*{}", snip)
572             } else {
573                 // suggest dropping the to_owned on the left
574                 snip.to_string()
575             };
576
577             db.span_suggestion_with_applicability(
578                 lint_span,
579                 "try",
580                 try_hint,
581                 Applicability::MachineApplicable, // snippet
582             );
583         },
584     );
585 }
586
587 /// Heuristic to see if an expression is used. Should be compatible with
588 /// `unused_variables`'s idea
589 /// of what it means for an expression to be "used".
590 fn is_used(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
591     if let Some(parent) = get_parent_expr(cx, expr) {
592         match parent.node {
593             ExprKind::Assign(_, ref rhs) | ExprKind::AssignOp(_, _, ref rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
594             _ => is_used(cx, parent),
595         }
596     } else {
597         true
598     }
599 }
600
601 /// Test whether an expression is in a macro expansion (e.g. something
602 /// generated by
603 /// `#[derive(...)`] or the like).
604 fn in_attributes_expansion(expr: &Expr) -> bool {
605     expr.span
606         .ctxt()
607         .outer()
608         .expn_info()
609         .map_or(false, |info| matches!(info.format, ExpnFormat::MacroAttribute(_)))
610 }
611
612 /// Test whether `def` is a variable defined outside a macro.
613 fn non_macro_local(cx: &LateContext<'_, '_>, def: &def::Def) -> bool {
614     match *def {
615         def::Def::Local(id) | def::Def::Upvar(id, _, _) => !in_macro(cx.tcx.hir().span(id)),
616         _ => false,
617     }
618 }
619
620 fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr, ty: &Ty) {
621     if_chain! {
622         if let TyKind::Ptr(MutTy { mutbl, .. }) = ty.node;
623         if let ExprKind::Lit(ref lit) = e.node;
624         if let LitKind::Int(value, ..) = lit.node;
625         if value == 0;
626         if !in_constant(cx, e.id);
627         then {
628             let msg = match mutbl {
629                 Mutability::MutMutable => "`0 as *mut _` detected. Consider using `ptr::null_mut()`",
630                 Mutability::MutImmutable => "`0 as *const _` detected. Consider using `ptr::null()`",
631             };
632             span_lint(cx, ZERO_PTR, span, msg);
633         }
634     }
635 }