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