]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/fallible_impl_from.rs
a9e05fddbe7625dc7dc98d74dd39679c034982bf
[rust.git] / src / tools / clippy / clippy_lints / src / fallible_impl_from.rs
1 use crate::utils::paths::{BEGIN_PANIC, BEGIN_PANIC_FMT, FROM_TRAIT};
2 use crate::utils::{is_expn_of, is_type_diagnostic_item, match_def_path, method_chain_args, span_lint_and_then};
3 use if_chain::if_chain;
4 use rustc_hir as hir;
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::hir::map::Map;
7 use rustc_middle::ty;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::Span;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
13     ///
14     /// **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// struct Foo(i32);
21     ///
22     /// // Bad
23     /// impl From<String> for Foo {
24     ///     fn from(s: String) -> Self {
25     ///         Foo(s.parse().unwrap())
26     ///     }
27     /// }
28     /// ```
29     ///
30     /// ```rust
31     /// // Good
32     /// struct Foo(i32);
33     ///
34     /// use std::convert::TryFrom;
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     pub FALLIBLE_IMPL_FROM,
47     nursery,
48     "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
49 }
50
51 declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
52
53 impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
54     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
55         // check for `impl From<???> for ..`
56         let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
57         if_chain! {
58             if let hir::ItemKind::Impl{ items: impl_items, .. } = item.kind;
59             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id);
60             if match_def_path(cx, impl_trait_ref.def_id, &FROM_TRAIT);
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, NestedVisitorMap, Visitor};
70     use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
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         type Map = Map<'tcx>;
80
81         fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
82             // check for `begin_panic`
83             if_chain! {
84                 if let ExprKind::Call(ref func_expr, _) = expr.kind;
85                 if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
86                 if let Some(path_def_id) = path.res.opt_def_id();
87                 if match_def_path(self.lcx, path_def_id, &BEGIN_PANIC) ||
88                     match_def_path(self.lcx, path_def_id, &BEGIN_PANIC_FMT);
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_type))
99                     || is_type_diagnostic_item(self.lcx, reciever_ty, sym!(result_type))
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 impl_item_def_id = cx.tcx.hir().local_def_id(impl_item.id.hir_id);
123                 let mut fpu = FindPanicUnwrap {
124                     lcx: cx,
125                     typeck_results: cx.tcx.typeck(impl_item_def_id),
126                     result: Vec::new(),
127                 };
128                 fpu.visit_expr(&body.value);
129
130                 // if we've found one, lint
131                 if !fpu.result.is_empty() {
132                     span_lint_and_then(
133                         cx,
134                         FALLIBLE_IMPL_FROM,
135                         impl_span,
136                         "consider implementing `TryFrom` instead",
137                         move |diag| {
138                             diag.help(
139                                 "`From` is intended for infallible conversions only. \
140                                 Use `TryFrom` if there's a possibility for the conversion to fail.");
141                             diag.span_note(fpu.result, "potential failure(s)");
142                         });
143                 }
144             }
145         }
146     }
147 }