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