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