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