]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/fallible_impl_from.rs
Merge pull request #2849 from mikerite/issue_2741
[rust.git] / clippy_lints / src / fallible_impl_from.rs
1 use rustc::lint::*;
2 use rustc::hir;
3 use rustc::ty;
4 use syntax_pos::Span;
5 use crate::utils::{match_def_path, method_chain_args, span_lint_and_then, walk_ptrs_ty, is_expn_of, opt_def_id};
6 use crate::utils::paths::{BEGIN_PANIC, BEGIN_PANIC_FMT, FROM_TRAIT, OPTION, RESULT};
7
8 /// **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
9 ///
10 /// **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust
16 /// struct Foo(i32);
17 /// impl From<String> for Foo {
18 ///     fn from(s: String) -> Self {
19 ///         Foo(s.parse().unwrap())
20 ///     }
21 /// }
22 /// ```
23 declare_clippy_lint! {
24     pub FALLIBLE_IMPL_FROM,
25     nursery,
26     "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
27 }
28
29 pub struct FallibleImplFrom;
30
31 impl LintPass for FallibleImplFrom {
32     fn get_lints(&self) -> LintArray {
33         lint_array!(FALLIBLE_IMPL_FROM)
34     }
35 }
36
37 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FallibleImplFrom {
38     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
39         // check for `impl From<???> for ..`
40         let impl_def_id = cx.tcx.hir.local_def_id(item.id);
41         if_chain! {
42             if let hir::ItemImpl(.., ref impl_items) = item.node;
43             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id);
44             if match_def_path(cx.tcx, impl_trait_ref.def_id, &FROM_TRAIT);
45             then {
46                 lint_impl_body(cx, item.span, impl_items);
47             }
48         }
49     }
50 }
51
52 fn lint_impl_body<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, impl_span: Span, impl_items: &hir::HirVec<hir::ImplItemRef>) {
53     use rustc::hir::*;
54     use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
55
56     struct FindPanicUnwrap<'a, 'tcx: 'a> {
57         tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
58         tables: &'tcx ty::TypeckTables<'tcx>,
59         result: Vec<Span>,
60     }
61
62     impl<'a, 'tcx: 'a> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
63         fn visit_expr(&mut self, expr: &'tcx Expr) {
64             // check for `begin_panic`
65             if_chain! {
66                 if let ExprCall(ref func_expr, _) = expr.node;
67                 if let ExprPath(QPath::Resolved(_, ref path)) = func_expr.node;
68                 if let Some(path_def_id) = opt_def_id(path.def);
69                 if match_def_path(self.tcx, path_def_id, &BEGIN_PANIC) ||
70                     match_def_path(self.tcx, path_def_id, &BEGIN_PANIC_FMT);
71                 if is_expn_of(expr.span, "unreachable").is_none();
72                 then {
73                     self.result.push(expr.span);
74                 }
75             }
76
77             // check for `unwrap`
78             if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
79                 let reciever_ty = walk_ptrs_ty(self.tables.expr_ty(&arglists[0][0]));
80                 if match_type(self.tcx, reciever_ty, &OPTION) || match_type(self.tcx, reciever_ty, &RESULT) {
81                     self.result.push(expr.span);
82                 }
83             }
84
85             // and check sub-expressions
86             intravisit::walk_expr(self, expr);
87         }
88
89         fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
90             NestedVisitorMap::None
91         }
92     }
93
94     for impl_item in impl_items {
95         if_chain! {
96             if impl_item.name == "from";
97             if let ImplItemKind::Method(_, body_id) =
98                 cx.tcx.hir.impl_item(impl_item.id).node;
99             then {
100                 // check the body for `begin_panic` or `unwrap`
101                 let body = cx.tcx.hir.body(body_id);
102                 let impl_item_def_id = cx.tcx.hir.local_def_id(impl_item.id.node_id);
103                 let mut fpu = FindPanicUnwrap {
104                     tcx: cx.tcx,
105                     tables: cx.tcx.typeck_tables_of(impl_item_def_id),
106                     result: Vec::new(),
107                 };
108                 fpu.visit_expr(&body.value);
109
110                 // if we've found one, lint
111                 if !fpu.result.is_empty() {
112                     span_lint_and_then(
113                         cx,
114                         FALLIBLE_IMPL_FROM,
115                         impl_span,
116                         "consider implementing `TryFrom` instead",
117                         move |db| {
118                             db.help(
119                                 "`From` is intended for infallible conversions only. \
120                                  Use `TryFrom` if there's a possibility for the conversion to fail.");
121                             db.span_note(fpu.result, "potential failure(s)");
122                         });
123                 }
124             }
125         }
126     }
127 }
128
129 fn match_type(tcx: ty::TyCtxt, ty: ty::Ty, path: &[&str]) -> bool {
130     match ty.sty {
131         ty::TyAdt(adt, _) => match_def_path(tcx, adt.did, path),
132         _ => false,
133     }
134 }