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