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