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