]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/misc.rs
Rollup merge of #89090 - cjgillot:bare-dyn, r=jackh726
[rust.git] / src / tools / clippy / 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, in_constant, is_diag_trait_item, is_integer_const, iter_input_pats,
24     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 an == BindingAnnotation::Ref || an == BindingAnnotation::RefMut;
325             then {
326                 // use the macro callsite when the init span (but not the whole local span)
327                 // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
328                 let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
329                     Sugg::hir_with_macro_callsite(cx, init, "..")
330                 } else {
331                     Sugg::hir(cx, init, "..")
332                 };
333                 let (mutopt, initref) = if an == BindingAnnotation::RefMut {
334                     ("mut ", sugg_init.mut_addr())
335                 } else {
336                     ("", sugg_init.addr())
337                 };
338                 let tyopt = if let Some(ty) = local.ty {
339                     format!(": &{mutopt}{ty}", mutopt=mutopt, ty=snippet(cx, ty.span, ".."))
340                 } else {
341                     String::new()
342                 };
343                 span_lint_hir_and_then(
344                     cx,
345                     TOPLEVEL_REF_ARG,
346                     init.hir_id,
347                     local.pat.span,
348                     "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
349                     |diag| {
350                         diag.span_suggestion(
351                             stmt.span,
352                             "try",
353                             format!(
354                                 "let {name}{tyopt} = {initref};",
355                                 name=snippet(cx, name.span, ".."),
356                                 tyopt=tyopt,
357                                 initref=initref,
358                             ),
359                             Applicability::MachineApplicable,
360                         );
361                     }
362                 );
363             }
364         };
365         if_chain! {
366             if let StmtKind::Semi(expr) = stmt.kind;
367             if let ExprKind::Binary(ref binop, a, b) = expr.kind;
368             if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
369             if let Some(sugg) = Sugg::hir_opt(cx, a);
370             then {
371                 span_lint_hir_and_then(
372                     cx,
373                     SHORT_CIRCUIT_STATEMENT,
374                     expr.hir_id,
375                     stmt.span,
376                     "boolean short circuit operator in statement may be clearer using an explicit test",
377                     |diag| {
378                         let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
379                         diag.span_suggestion(
380                             stmt.span,
381                             "replace it with",
382                             format!(
383                                 "if {} {{ {}; }}",
384                                 sugg,
385                                 &snippet(cx, b.span, ".."),
386                             ),
387                             Applicability::MachineApplicable, // snippet
388                         );
389                     });
390             }
391         };
392     }
393
394     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
395         match expr.kind {
396             ExprKind::Cast(e, ty) => {
397                 check_cast(cx, expr.span, e, ty);
398                 return;
399             },
400             ExprKind::Binary(ref cmp, left, right) => {
401                 check_binary(cx, expr, cmp, left, right);
402                 return;
403             },
404             _ => {},
405         }
406         if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
407             // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
408             return;
409         }
410         let binding = match expr.kind {
411             ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
412                 let binding = last_path_segment(qpath).ident.as_str();
413                 if binding.starts_with('_') &&
414                     !binding.starts_with("__") &&
415                     binding != "_result" && // FIXME: #944
416                     is_used(cx, expr) &&
417                     // don't lint if the declaration is in a macro
418                     non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
419                 {
420                     Some(binding)
421                 } else {
422                     None
423                 }
424             },
425             ExprKind::Field(_, ident) => {
426                 let name = ident.as_str();
427                 if name.starts_with('_') && !name.starts_with("__") {
428                     Some(name)
429                 } else {
430                     None
431                 }
432             },
433             _ => None,
434         };
435         if let Some(binding) = binding {
436             span_lint(
437                 cx,
438                 USED_UNDERSCORE_BINDING,
439                 expr.span,
440                 &format!(
441                     "used binding `{}` which is prefixed with an underscore. A leading \
442                      underscore signals that a binding will not be used",
443                     binding
444                 ),
445             );
446         }
447     }
448 }
449
450 fn get_lint_and_message(
451     is_comparing_constants: bool,
452     is_comparing_arrays: bool,
453 ) -> (&'static rustc_lint::Lint, &'static str) {
454     if is_comparing_constants {
455         (
456             FLOAT_CMP_CONST,
457             if is_comparing_arrays {
458                 "strict comparison of `f32` or `f64` constant arrays"
459             } else {
460                 "strict comparison of `f32` or `f64` constant"
461             },
462         )
463     } else {
464         (
465             FLOAT_CMP,
466             if is_comparing_arrays {
467                 "strict comparison of `f32` or `f64` arrays"
468             } else {
469                 "strict comparison of `f32` or `f64`"
470             },
471         )
472     }
473 }
474
475 fn check_nan(cx: &LateContext<'_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) {
476     if_chain! {
477         if !in_constant(cx, cmp_expr.hir_id);
478         if let Some((value, _)) = constant(cx, cx.typeck_results(), expr);
479         if match value {
480             Constant::F32(num) => num.is_nan(),
481             Constant::F64(num) => num.is_nan(),
482             _ => false,
483         };
484         then {
485             span_lint(
486                 cx,
487                 CMP_NAN,
488                 cmp_expr.span,
489                 "doomed comparison with `NAN`, use `{f32,f64}::is_nan()` instead",
490             );
491         }
492     }
493 }
494
495 fn is_named_constant<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
496     if let Some((_, res)) = constant(cx, cx.typeck_results(), expr) {
497         res
498     } else {
499         false
500     }
501 }
502
503 fn is_allowed<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
504     match constant(cx, cx.typeck_results(), expr) {
505         Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(),
506         Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(),
507         Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f {
508             Constant::F32(f) => *f == 0.0 || (*f).is_infinite(),
509             Constant::F64(f) => *f == 0.0 || (*f).is_infinite(),
510             _ => false,
511         }),
512         _ => false,
513     }
514 }
515
516 // Return true if `expr` is the result of `signum()` invoked on a float value.
517 fn is_signum(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
518     // The negation of a signum is still a signum
519     if let ExprKind::Unary(UnOp::Neg, child_expr) = expr.kind {
520         return is_signum(cx, child_expr);
521     }
522
523     if_chain! {
524         if let ExprKind::MethodCall(method_name, _, [ref self_arg, ..], _) = expr.kind;
525         if sym!(signum) == method_name.ident.name;
526         // Check that the receiver of the signum() is a float (expressions[0] is the receiver of
527         // the method call)
528         then {
529             return is_float(cx, self_arg);
530         }
531     }
532     false
533 }
534
535 fn is_float(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
536     let value = &cx.typeck_results().expr_ty(expr).peel_refs().kind();
537
538     if let ty::Array(arr_ty, _) = value {
539         return matches!(arr_ty.kind(), ty::Float(_));
540     };
541
542     matches!(value, ty::Float(_))
543 }
544
545 fn is_array(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
546     matches!(&cx.typeck_results().expr_ty(expr).peel_refs().kind(), ty::Array(_, _))
547 }
548
549 fn check_to_owned(cx: &LateContext<'_>, expr: &Expr<'_>, other: &Expr<'_>, left: bool) {
550     #[derive(Default)]
551     struct EqImpl {
552         ty_eq_other: bool,
553         other_eq_ty: bool,
554     }
555
556     impl EqImpl {
557         fn is_implemented(&self) -> bool {
558             self.ty_eq_other || self.other_eq_ty
559         }
560     }
561
562     fn symmetric_partial_eq<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, other: Ty<'tcx>) -> Option<EqImpl> {
563         cx.tcx.lang_items().eq_trait().map(|def_id| EqImpl {
564             ty_eq_other: implements_trait(cx, ty, def_id, &[other.into()]),
565             other_eq_ty: implements_trait(cx, other, def_id, &[ty.into()]),
566         })
567     }
568
569     let (arg_ty, snip) = match expr.kind {
570         ExprKind::MethodCall(.., args, _) if args.len() == 1 => {
571             if_chain!(
572                 if let Some(expr_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id);
573                 if is_diag_trait_item(cx, expr_def_id, sym::ToString)
574                     || is_diag_trait_item(cx, expr_def_id, sym::ToOwned);
575                 then {
576                     (cx.typeck_results().expr_ty(&args[0]), snippet(cx, args[0].span, ".."))
577                 } else {
578                     return;
579                 }
580             )
581         },
582         ExprKind::Call(path, [arg]) => {
583             if expr_path_res(cx, path)
584                 .opt_def_id()
585                 .and_then(|id| match_any_def_paths(cx, id, &[&paths::FROM_STR_METHOD, &paths::FROM_FROM]))
586                 .is_some()
587             {
588                 (cx.typeck_results().expr_ty(arg), snippet(cx, arg.span, ".."))
589             } else {
590                 return;
591             }
592         },
593         _ => return,
594     };
595
596     let other_ty = cx.typeck_results().expr_ty(other);
597
598     let without_deref = symmetric_partial_eq(cx, arg_ty, other_ty).unwrap_or_default();
599     let with_deref = arg_ty
600         .builtin_deref(true)
601         .and_then(|tam| symmetric_partial_eq(cx, tam.ty, other_ty))
602         .unwrap_or_default();
603
604     if !with_deref.is_implemented() && !without_deref.is_implemented() {
605         return;
606     }
607
608     let other_gets_derefed = matches!(other.kind, ExprKind::Unary(UnOp::Deref, _));
609
610     let lint_span = if other_gets_derefed {
611         expr.span.to(other.span)
612     } else {
613         expr.span
614     };
615
616     span_lint_and_then(
617         cx,
618         CMP_OWNED,
619         lint_span,
620         "this creates an owned instance just for comparison",
621         |diag| {
622             // This also catches `PartialEq` implementations that call `to_owned`.
623             if other_gets_derefed {
624                 diag.span_label(lint_span, "try implementing the comparison without allocating");
625                 return;
626             }
627
628             let expr_snip;
629             let eq_impl;
630             if with_deref.is_implemented() {
631                 expr_snip = format!("*{}", snip);
632                 eq_impl = with_deref;
633             } else {
634                 expr_snip = snip.to_string();
635                 eq_impl = without_deref;
636             };
637
638             let span;
639             let hint;
640             if (eq_impl.ty_eq_other && left) || (eq_impl.other_eq_ty && !left) {
641                 span = expr.span;
642                 hint = expr_snip;
643             } else {
644                 span = expr.span.to(other.span);
645                 if eq_impl.ty_eq_other {
646                     hint = format!("{} == {}", expr_snip, snippet(cx, other.span, ".."));
647                 } else {
648                     hint = format!("{} == {}", snippet(cx, other.span, ".."), expr_snip);
649                 }
650             }
651
652             diag.span_suggestion(
653                 span,
654                 "try",
655                 hint,
656                 Applicability::MachineApplicable, // snippet
657             );
658         },
659     );
660 }
661
662 /// Heuristic to see if an expression is used. Should be compatible with
663 /// `unused_variables`'s idea
664 /// of what it means for an expression to be "used".
665 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
666     get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
667         ExprKind::Assign(_, rhs, _) | ExprKind::AssignOp(_, _, rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
668         _ => is_used(cx, parent),
669     })
670 }
671
672 /// Tests whether an expression is in a macro expansion (e.g., something
673 /// generated by `#[derive(...)]` or the like).
674 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
675     use rustc_span::hygiene::MacroKind;
676     if expr.span.from_expansion() {
677         let data = expr.span.ctxt().outer_expn_data();
678         matches!(data.kind, ExpnKind::Macro(MacroKind::Attr, _))
679     } else {
680         false
681     }
682 }
683
684 /// Tests whether `res` is a variable defined outside a macro.
685 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
686     if let def::Res::Local(id) = res {
687         !cx.tcx.hir().span(id).from_expansion()
688     } else {
689         false
690     }
691 }
692
693 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
694     if_chain! {
695         if let TyKind::Ptr(ref mut_ty) = ty.kind;
696         if let ExprKind::Lit(ref lit) = e.kind;
697         if let LitKind::Int(0, _) = lit.node;
698         if !in_constant(cx, e.hir_id);
699         then {
700             let (msg, sugg_fn) = match mut_ty.mutbl {
701                 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
702                 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
703             };
704
705             let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
706                 (format!("{}()", sugg_fn), Applicability::MachineApplicable)
707             } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
708                 (format!("{}::<{}>()", sugg_fn, mut_ty_snip), Applicability::MachineApplicable)
709             } else {
710                 // `MaybeIncorrect` as type inference may not work with the suggested code
711                 (format!("{}()", sugg_fn), Applicability::MaybeIncorrect)
712             };
713             span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);
714         }
715     }
716 }
717
718 fn check_binary(
719     cx: &LateContext<'a>,
720     expr: &Expr<'_>,
721     cmp: &rustc_span::source_map::Spanned<rustc_hir::BinOpKind>,
722     left: &'a Expr<'_>,
723     right: &'a Expr<'_>,
724 ) {
725     let op = cmp.node;
726     if op.is_comparison() {
727         check_nan(cx, left, expr);
728         check_nan(cx, right, expr);
729         check_to_owned(cx, left, right, true);
730         check_to_owned(cx, right, left, false);
731     }
732     if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) {
733         if is_allowed(cx, left) || is_allowed(cx, right) {
734             return;
735         }
736
737         // Allow comparing the results of signum()
738         if is_signum(cx, left) && is_signum(cx, right) {
739             return;
740         }
741
742         if let Some(name) = get_item_name(cx, expr) {
743             let name = name.as_str();
744             if name == "eq" || name == "ne" || name == "is_nan" || name.starts_with("eq_") || name.ends_with("_eq") {
745                 return;
746             }
747         }
748         let is_comparing_arrays = is_array(cx, left) || is_array(cx, right);
749         let (lint, msg) = get_lint_and_message(
750             is_named_constant(cx, left) || is_named_constant(cx, right),
751             is_comparing_arrays,
752         );
753         span_lint_and_then(cx, lint, expr.span, msg, |diag| {
754             let lhs = Sugg::hir(cx, left, "..");
755             let rhs = Sugg::hir(cx, right, "..");
756
757             if !is_comparing_arrays {
758                 diag.span_suggestion(
759                     expr.span,
760                     "consider comparing them within some margin of error",
761                     format!(
762                         "({}).abs() {} error_margin",
763                         lhs - rhs,
764                         if op == BinOpKind::Eq { '<' } else { '>' }
765                     ),
766                     Applicability::HasPlaceholders, // snippet
767                 );
768             }
769             diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error_margin`");
770         });
771     } else if op == BinOpKind::Rem {
772         if is_integer_const(cx, right, 1) {
773             span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0");
774         }
775
776         if let ty::Int(ity) = cx.typeck_results().expr_ty(right).kind() {
777             if is_integer_const(cx, right, unsext(cx.tcx, -1, *ity)) {
778                 span_lint(
779                     cx,
780                     MODULO_ONE,
781                     expr.span,
782                     "any number modulo -1 will panic/overflow or result in 0",
783                 );
784             }
785         };
786     }
787 }