]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/fallible_impl_from.rs
Auto merge of #97121 - pvdrz:do-subdiagnostics-later, r=davidtwco
[rust.git] / src / tools / clippy / clippy_lints / src / fallible_impl_from.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::macros::{is_panic, root_macro_call_first_node};
3 use clippy_utils::method_chain_args;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use if_chain::if_chain;
6 use rustc_hir as hir;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::ty;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::{sym, Span};
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
15     ///
16     /// ### Why is this bad?
17     /// `TryFrom` should be used if there's a possibility of failure.
18     ///
19     /// ### Example
20     /// ```rust
21     /// struct Foo(i32);
22     ///
23     /// // Bad
24     /// impl From<String> for Foo {
25     ///     fn from(s: String) -> Self {
26     ///         Foo(s.parse().unwrap())
27     ///     }
28     /// }
29     /// ```
30     ///
31     /// ```rust
32     /// // Good
33     /// struct Foo(i32);
34     ///
35     /// impl TryFrom<String> for Foo {
36     ///     type Error = ();
37     ///     fn try_from(s: String) -> Result<Self, Self::Error> {
38     ///         if let Ok(parsed) = s.parse() {
39     ///             Ok(Foo(parsed))
40     ///         } else {
41     ///             Err(())
42     ///         }
43     ///     }
44     /// }
45     /// ```
46     #[clippy::version = "pre 1.29.0"]
47     pub FALLIBLE_IMPL_FROM,
48     nursery,
49     "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
50 }
51
52 declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
53
54 impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
55     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
56         // check for `impl From<???> for ..`
57         if_chain! {
58             if let hir::ItemKind::Impl(impl_) = &item.kind;
59             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
60             if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id);
61             then {
62                 lint_impl_body(cx, item.span, impl_.items);
63             }
64         }
65     }
66 }
67
68 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) {
69     use rustc_hir::intravisit::{self, Visitor};
70     use rustc_hir::{Expr, ImplItemKind};
71
72     struct FindPanicUnwrap<'a, 'tcx> {
73         lcx: &'a LateContext<'tcx>,
74         typeck_results: &'tcx ty::TypeckResults<'tcx>,
75         result: Vec<Span>,
76     }
77
78     impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
79         fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
80             if let Some(macro_call) = root_macro_call_first_node(self.lcx, expr) {
81                 if is_panic(self.lcx, macro_call.def_id) {
82                     self.result.push(expr.span);
83                 }
84             }
85
86             // check for `unwrap`
87             if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
88                 let receiver_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
89                 if is_type_diagnostic_item(self.lcx, receiver_ty, sym::Option)
90                     || is_type_diagnostic_item(self.lcx, receiver_ty, sym::Result)
91                 {
92                     self.result.push(expr.span);
93                 }
94             }
95
96             // and check sub-expressions
97             intravisit::walk_expr(self, expr);
98         }
99     }
100
101     for impl_item in impl_items {
102         if_chain! {
103             if impl_item.ident.name == sym::from;
104             if let ImplItemKind::Fn(_, body_id) =
105                 cx.tcx.hir().impl_item(impl_item.id).kind;
106             then {
107                 // check the body for `begin_panic` or `unwrap`
108                 let body = cx.tcx.hir().body(body_id);
109                 let mut fpu = FindPanicUnwrap {
110                     lcx: cx,
111                     typeck_results: cx.tcx.typeck(impl_item.id.def_id),
112                     result: Vec::new(),
113                 };
114                 fpu.visit_expr(&body.value);
115
116                 // if we've found one, lint
117                 if !fpu.result.is_empty() {
118                     span_lint_and_then(
119                         cx,
120                         FALLIBLE_IMPL_FROM,
121                         impl_span,
122                         "consider implementing `TryFrom` instead",
123                         move |diag| {
124                             diag.help(
125                                 "`From` is intended for infallible conversions only. \
126                                 Use `TryFrom` if there's a possibility for the conversion to fail");
127                             diag.span_note(fpu.result, "potential failure(s)");
128                         });
129                 }
130             }
131         }
132     }
133 }