]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/fallible_impl_from.rs
Rollup merge of #91562 - dtolnay:asyncspace, r=Mark-Simulacrum
[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::ty::is_type_diagnostic_item;
3 use clippy_utils::{is_expn_of, match_panic_def_id, method_chain_args};
4 use if_chain::if_chain;
5 use rustc_hir as hir;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::hir::map::Map;
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     /// use std::convert::TryFrom;
36     /// impl TryFrom<String> for Foo {
37     ///     type Error = ();
38     ///     fn try_from(s: String) -> Result<Self, Self::Error> {
39     ///         if let Ok(parsed) = s.parse() {
40     ///             Ok(Foo(parsed))
41     ///         } else {
42     ///             Err(())
43     ///         }
44     ///     }
45     /// }
46     /// ```
47     #[clippy::version = "pre 1.29.0"]
48     pub FALLIBLE_IMPL_FROM,
49     nursery,
50     "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
51 }
52
53 declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
54
55 impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
56     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
57         // check for `impl From<???> for ..`
58         if_chain! {
59             if let hir::ItemKind::Impl(impl_) = &item.kind;
60             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
61             if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id);
62             then {
63                 lint_impl_body(cx, item.span, impl_.items);
64             }
65         }
66     }
67 }
68
69 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) {
70     use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
71     use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
72
73     struct FindPanicUnwrap<'a, 'tcx> {
74         lcx: &'a LateContext<'tcx>,
75         typeck_results: &'tcx ty::TypeckResults<'tcx>,
76         result: Vec<Span>,
77     }
78
79     impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
80         type Map = Map<'tcx>;
81
82         fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
83             // check for `begin_panic`
84             if_chain! {
85                 if let ExprKind::Call(func_expr, _) = expr.kind;
86                 if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
87                 if let Some(path_def_id) = path.res.opt_def_id();
88                 if match_panic_def_id(self.lcx, path_def_id);
89                 if is_expn_of(expr.span, "unreachable").is_none();
90                 then {
91                     self.result.push(expr.span);
92                 }
93             }
94
95             // check for `unwrap`
96             if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
97                 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
98                 if is_type_diagnostic_item(self.lcx, reciever_ty, sym::Option)
99                     || is_type_diagnostic_item(self.lcx, reciever_ty, sym::Result)
100                 {
101                     self.result.push(expr.span);
102                 }
103             }
104
105             // and check sub-expressions
106             intravisit::walk_expr(self, expr);
107         }
108
109         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
110             NestedVisitorMap::None
111         }
112     }
113
114     for impl_item in impl_items {
115         if_chain! {
116             if impl_item.ident.name == sym::from;
117             if let ImplItemKind::Fn(_, body_id) =
118                 cx.tcx.hir().impl_item(impl_item.id).kind;
119             then {
120                 // check the body for `begin_panic` or `unwrap`
121                 let body = cx.tcx.hir().body(body_id);
122                 let mut fpu = FindPanicUnwrap {
123                     lcx: cx,
124                     typeck_results: cx.tcx.typeck(impl_item.id.def_id),
125                     result: Vec::new(),
126                 };
127                 fpu.visit_expr(&body.value);
128
129                 // if we've found one, lint
130                 if !fpu.result.is_empty() {
131                     span_lint_and_then(
132                         cx,
133                         FALLIBLE_IMPL_FROM,
134                         impl_span,
135                         "consider implementing `TryFrom` instead",
136                         move |diag| {
137                             diag.help(
138                                 "`From` is intended for infallible conversions only. \
139                                 Use `TryFrom` if there's a possibility for the conversion to fail");
140                             diag.span_note(fpu.result, "potential failure(s)");
141                         });
142                 }
143             }
144         }
145     }
146 }