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