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