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