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