]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/fallible_impl_from.rs
19a122594cb7b6955c1ada925d9720f4b46f7f42
[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, span_lint_and_then, walk_ptrs_ty};
3 use if_chain::if_chain;
4 use rustc::hir::map::Map;
5 use rustc::ty::{self, Ty};
6 use rustc_hir as hir;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::Span;
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
13     ///
14     /// **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// struct Foo(i32);
21     /// impl From<String> for Foo {
22     ///     fn from(s: String) -> Self {
23     ///         Foo(s.parse().unwrap())
24     ///     }
25     /// }
26     /// ```
27     pub FALLIBLE_IMPL_FROM,
28     nursery,
29     "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
30 }
31
32 declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
33
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FallibleImplFrom {
35     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
36         // check for `impl From<???> for ..`
37         let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
38         if_chain! {
39             if let hir::ItemKind::Impl{ items: impl_items, .. } = item.kind;
40             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id);
41             if match_def_path(cx, impl_trait_ref.def_id, &FROM_TRAIT);
42             then {
43                 lint_impl_body(cx, item.span, impl_items);
44             }
45         }
46     }
47 }
48
49 fn lint_impl_body<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef<'_>]) {
50     use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
51     use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
52
53     struct FindPanicUnwrap<'a, 'tcx> {
54         lcx: &'a LateContext<'a, 'tcx>,
55         tables: &'tcx ty::TypeckTables<'tcx>,
56         result: Vec<Span>,
57     }
58
59     impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
60         type Map = Map<'tcx>;
61
62         fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
63             // check for `begin_panic`
64             if_chain! {
65                 if let ExprKind::Call(ref func_expr, _) = expr.kind;
66                 if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
67                 if let Some(path_def_id) = path.res.opt_def_id();
68                 if match_def_path(self.lcx, path_def_id, &BEGIN_PANIC) ||
69                     match_def_path(self.lcx, path_def_id, &BEGIN_PANIC_FMT);
70                 if is_expn_of(expr.span, "unreachable").is_none();
71                 then {
72                     self.result.push(expr.span);
73                 }
74             }
75
76             // check for `unwrap`
77             if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
78                 let reciever_ty = walk_ptrs_ty(self.tables.expr_ty(&arglists[0][0]));
79                 if match_type(self.lcx, reciever_ty, &OPTION) || match_type(self.lcx, reciever_ty, &RESULT) {
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(&mut self) -> NestedVisitorMap<'_, Self::Map> {
89             NestedVisitorMap::None
90         }
91     }
92
93     for impl_item in impl_items {
94         if_chain! {
95             if impl_item.ident.name == sym!(from);
96             if let ImplItemKind::Method(_, body_id) =
97                 cx.tcx.hir().impl_item(impl_item.id).kind;
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.hir_id);
102                 let mut fpu = FindPanicUnwrap {
103                     lcx: cx,
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(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
129     match ty.kind {
130         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
131         _ => false,
132     }
133 }