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