]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/fallible_impl_from.rs
Auto merge of #6828 - mgacek8:issue_6758_enhance_wrong_self_convention, r=flip1995
[rust.git] / clippy_lints / src / fallible_impl_from.rs
1 use crate::utils::{is_expn_of, match_panic_def_id, method_chain_args, span_lint_and_then};
2 use clippy_utils::ty::is_type_diagnostic_item;
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::{sym, 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         if_chain! {
57             if let hir::ItemKind::Impl(impl_) = &item.kind;
58             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.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 mut fpu = FindPanicUnwrap {
121                     lcx: cx,
122                     typeck_results: cx.tcx.typeck(impl_item.id.def_id),
123                     result: Vec::new(),
124                 };
125                 fpu.visit_expr(&body.value);
126
127                 // if we've found one, lint
128                 if !fpu.result.is_empty() {
129                     span_lint_and_then(
130                         cx,
131                         FALLIBLE_IMPL_FROM,
132                         impl_span,
133                         "consider implementing `TryFrom` instead",
134                         move |diag| {
135                             diag.help(
136                                 "`From` is intended for infallible conversions only. \
137                                 Use `TryFrom` if there's a possibility for the conversion to fail");
138                             diag.span_note(fpu.result, "potential failure(s)");
139                         });
140                 }
141             }
142         }
143     }
144 }