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