]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/misc.rs
Auto merge of #3845 - euclio:unused-comments, r=phansch
[rust.git] / clippy_lints / src / misc.rs
1 use crate::consts::{constant, Constant};
2 use crate::utils::sugg::Sugg;
3 use crate::utils::{
4     get_item_name, get_parent_expr, implements_trait, in_constant, in_macro, is_integer_literal, iter_input_pats,
5     last_path_segment, match_qpath, match_trait_method, paths, snippet, span_lint, span_lint_and_then, walk_ptrs_ty,
6     SpanlessEq,
7 };
8 use if_chain::if_chain;
9 use matches::matches;
10 use rustc::hir::intravisit::FnKind;
11 use rustc::hir::*;
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::ty;
14 use rustc::{declare_tool_lint, lint_array};
15 use rustc_errors::Applicability;
16 use syntax::ast::LitKind;
17 use syntax::source_map::{ExpnFormat, Span};
18
19 declare_clippy_lint! {
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     /// ```ignore
38     /// fn foo(ref x: u8) -> bool {
39     ///     ..
40     /// }
41     /// ```
42     pub TOPLEVEL_REF_ARG,
43     style,
44     "an entire binding declared as `ref`, in a function argument or a `let` statement"
45 }
46
47 declare_clippy_lint! {
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     /// ```ignore
57     /// x == NAN
58     /// ```
59     pub CMP_NAN,
60     correctness,
61     "comparisons to NAN, which will always return false, probably not intended"
62 }
63
64 declare_clippy_lint! {
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     /// ```ignore
78     /// y == 1.23f64
79     /// y != x  // where both are floats
80     /// ```
81     pub FLOAT_CMP,
82     correctness,
83     "using `==` or `!=` on float values instead of comparing difference with an epsilon"
84 }
85
86 declare_clippy_lint! {
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     pub CMP_OWNED,
101     perf,
102     "creating owned instances for comparing with others, e.g. `x == \"foo\".to_string()`"
103 }
104
105 declare_clippy_lint! {
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     /// ```ignore
117     /// x % 1
118     /// ```
119     pub MODULO_ONE,
120     correctness,
121     "taking a number modulo 1, which always returns 0"
122 }
123
124 declare_clippy_lint! {
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     /// ```ignore
134     /// match v {
135     ///     Some(x) => (),
136     ///     y @ _ => (), // easier written as `y`,
137     /// }
138     /// ```
139     pub REDUNDANT_PATTERN,
140     style,
141     "using `name @ _` in a pattern"
142 }
143
144 declare_clippy_lint! {
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     pub USED_UNDERSCORE_BINDING,
162     pedantic,
163     "using a binding which is prefixed with an underscore"
164 }
165
166 declare_clippy_lint! {
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     pub SHORT_CIRCUIT_STATEMENT,
182     complexity,
183     "using a short circuit boolean condition as a statement"
184 }
185
186 declare_clippy_lint! {
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     /// ```ignore
197     /// 0 as *const u32
198     /// ```
199     pub ZERO_PTR,
200     style,
201     "using 0 as *{const, mut} T"
202 }
203
204 declare_clippy_lint! {
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     pub FLOAT_CMP_CONST,
222     restriction,
223     "using `==` or `!=` on float constants instead of comparing difference with an epsilon"
224 }
225
226 #[derive(Copy, Clone)]
227 pub struct Pass;
228
229 impl LintPass for Pass {
230     fn get_lints(&self) -> LintArray {
231         lint_array!(
232             TOPLEVEL_REF_ARG,
233             CMP_NAN,
234             FLOAT_CMP,
235             CMP_OWNED,
236             MODULO_ONE,
237             REDUNDANT_PATTERN,
238             USED_UNDERSCORE_BINDING,
239             SHORT_CIRCUIT_STATEMENT,
240             ZERO_PTR,
241             FLOAT_CMP_CONST
242         )
243     }
244
245     fn name(&self) -> &'static str {
246         "MiscLints"
247     }
248 }
249
250 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
251     fn check_fn(
252         &mut self,
253         cx: &LateContext<'a, 'tcx>,
254         k: FnKind<'tcx>,
255         decl: &'tcx FnDecl,
256         body: &'tcx Body,
257         _: Span,
258         _: HirId,
259     ) {
260         if let FnKind::Closure(_) = k {
261             // Does not apply to closures
262             return;
263         }
264         for arg in iter_input_pats(decl, body) {
265             match arg.pat.node {
266                 PatKind::Binding(BindingAnnotation::Ref, ..) | PatKind::Binding(BindingAnnotation::RefMut, ..) => {
267                     span_lint(
268                         cx,
269                         TOPLEVEL_REF_ARG,
270                         arg.pat.span,
271                         "`ref` directly on a function argument is ignored. Consider using a reference type \
272                          instead.",
273                     );
274                 },
275                 _ => {},
276             }
277         }
278     }
279
280     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, s: &'tcx Stmt) {
281         if_chain! {
282             if let StmtKind::Local(ref l) = s.node;
283             if let PatKind::Binding(an, .., i, None) = l.pat.node;
284             if let Some(ref init) = l.init;
285             then {
286                 if an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut {
287                     let init = Sugg::hir(cx, init, "..");
288                     let (mutopt,initref) = if an == BindingAnnotation::RefMut {
289                         ("mut ", init.mut_addr())
290                     } else {
291                         ("", init.addr())
292                     };
293                     let tyopt = if let Some(ref ty) = l.ty {
294                         format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, "_"))
295                     } else {
296                         String::new()
297                     };
298                     span_lint_and_then(cx,
299                         TOPLEVEL_REF_ARG,
300                         l.pat.span,
301                         "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
302                         |db| {
303                             db.span_suggestion(
304                                 s.span,
305                                 "try",
306                                 format!(
307                                     "let {name}{tyopt} = {initref};",
308                                     name=snippet(cx, i.span, "_"),
309                                     tyopt=tyopt,
310                                     initref=initref,
311                                 ),
312                                 Applicability::MachineApplicable, // snippet
313                             );
314                         }
315                     );
316                 }
317             }
318         };
319         if_chain! {
320             if let StmtKind::Semi(ref expr) = s.node;
321             if let ExprKind::Binary(ref binop, ref a, ref b) = expr.node;
322             if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
323             if let Some(sugg) = Sugg::hir_opt(cx, a);
324             then {
325                 span_lint_and_then(cx,
326                     SHORT_CIRCUIT_STATEMENT,
327                     s.span,
328                     "boolean short circuit operator in statement may be clearer using an explicit test",
329                     |db| {
330                         let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
331                         db.span_suggestion(
332                             s.span,
333                             "replace it with",
334                             format!(
335                                 "if {} {{ {}; }}",
336                                 sugg,
337                                 &snippet(cx, b.span, ".."),
338                             ),
339                             Applicability::MachineApplicable, // snippet
340                         );
341                     });
342             }
343         };
344     }
345
346     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
347         match expr.node {
348             ExprKind::Cast(ref e, ref ty) => {
349                 check_cast(cx, expr.span, e, ty);
350                 return;
351             },
352             ExprKind::Binary(ref cmp, ref left, ref right) => {
353                 let op = cmp.node;
354                 if op.is_comparison() {
355                     if let ExprKind::Path(QPath::Resolved(_, ref path)) = left.node {
356                         check_nan(cx, path, expr);
357                     }
358                     if let ExprKind::Path(QPath::Resolved(_, ref path)) = right.node {
359                         check_nan(cx, path, expr);
360                     }
361                     check_to_owned(cx, left, right);
362                     check_to_owned(cx, right, left);
363                 }
364                 if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
365                     if is_allowed(cx, left) || is_allowed(cx, right) {
366                         return;
367                     }
368                     if let Some(name) = get_item_name(cx, expr) {
369                         let name = name.as_str();
370                         if name == "eq"
371                             || name == "ne"
372                             || name == "is_nan"
373                             || name.starts_with("eq_")
374                             || name.ends_with("_eq")
375                         {
376                             return;
377                         }
378                     }
379                     let (lint, msg) = if is_named_constant(cx, left) || is_named_constant(cx, right) {
380                         (FLOAT_CMP_CONST, "strict comparison of f32 or f64 constant")
381                     } else {
382                         (FLOAT_CMP, "strict comparison of f32 or f64")
383                     };
384                     span_lint_and_then(cx, lint, expr.span, msg, |db| {
385                         let lhs = Sugg::hir(cx, left, "..");
386                         let rhs = Sugg::hir(cx, right, "..");
387
388                         db.span_suggestion(
389                             expr.span,
390                             "consider comparing them within some error",
391                             format!("({}).abs() < error", lhs - rhs),
392                             Applicability::MachineApplicable, // snippet
393                         );
394                         db.span_note(expr.span, "std::f32::EPSILON and std::f64::EPSILON are available.");
395                     });
396                 } else if op == BinOpKind::Rem && is_integer_literal(right, 1) {
397                     span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
398                 }
399             },
400             _ => {},
401         }
402         if in_attributes_expansion(expr) {
403             // Don't lint things expanded by #[derive(...)], etc
404             return;
405         }
406         let binding = match expr.node {
407             ExprKind::Path(ref qpath) => {
408                 let binding = last_path_segment(qpath).ident.as_str();
409                 if binding.starts_with('_') &&
410                     !binding.starts_with("__") &&
411                     binding != "_result" && // FIXME: #944
412                     is_used(cx, expr) &&
413                     // don't lint if the declaration is in a macro
414                     non_macro_local(cx, &cx.tables.qpath_def(qpath, expr.hir_id))
415                 {
416                     Some(binding)
417                 } else {
418                     None
419                 }
420             },
421             ExprKind::Field(_, ident) => {
422                 let name = ident.as_str();
423                 if name.starts_with('_') && !name.starts_with("__") {
424                     Some(name)
425                 } else {
426                     None
427                 }
428             },
429             _ => None,
430         };
431         if let Some(binding) = binding {
432             span_lint(
433                 cx,
434                 USED_UNDERSCORE_BINDING,
435                 expr.span,
436                 &format!(
437                     "used binding `{}` which is prefixed with an underscore. A leading \
438                      underscore signals that a binding will not be used.",
439                     binding
440                 ),
441             );
442         }
443     }
444
445     fn check_pat(&mut self, cx: &LateContext<'a, 'tcx>, pat: &'tcx Pat) {
446         if let PatKind::Binding(.., ident, Some(ref right)) = pat.node {
447             if let PatKind::Wild = right.node {
448                 span_lint(
449                     cx,
450                     REDUNDANT_PATTERN,
451                     pat.span,
452                     &format!(
453                         "the `{} @ _` pattern can be written as just `{}`",
454                         ident.name, ident.name
455                     ),
456                 );
457             }
458         }
459     }
460 }
461
462 fn check_nan(cx: &LateContext<'_, '_>, path: &Path, expr: &Expr) {
463     if !in_constant(cx, expr.hir_id) {
464         if let Some(seg) = path.segments.last() {
465             if seg.ident.name == "NAN" {
466                 span_lint(
467                     cx,
468                     CMP_NAN,
469                     expr.span,
470                     "doomed comparison with NAN, use `std::{f32,f64}::is_nan()` instead",
471                 );
472             }
473         }
474     }
475 }
476
477 fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
478     if let Some((_, res)) = constant(cx, cx.tables, expr) {
479         res
480     } else {
481         false
482     }
483 }
484
485 fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> bool {
486     match constant(cx, cx.tables, expr) {
487         Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
488         Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
489         _ => false,
490     }
491 }
492
493 fn is_float(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
494     matches!(walk_ptrs_ty(cx.tables.expr_ty(expr)).sty, ty::Float(_))
495 }
496
497 fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr, other: &Expr) {
498     let (arg_ty, snip) = match expr.node {
499         ExprKind::MethodCall(.., ref args) if args.len() == 1 => {
500             if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) {
501                 (cx.tables.expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, ".."))
502             } else {
503                 return;
504             }
505         },
506         ExprKind::Call(ref path, ref v) if v.len() == 1 => {
507             if let ExprKind::Path(ref path) = path.node {
508                 if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) {
509                     (cx.tables.expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, ".."))
510                 } else {
511                     return;
512                 }
513             } else {
514                 return;
515             }
516         },
517         _ => return,
518     };
519
520     let other_ty = cx.tables.expr_ty_adjusted(other);
521     let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() {
522         Some(id) => id,
523         None => return,
524     };
525
526     let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| {
527         implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])
528     });
529     let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| {
530         implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])
531     });
532     let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]);
533
534     if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other {
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(
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.hir_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 }