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