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