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