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