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