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