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