]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/fallible_impl_from.rs
Rollup merge of #74394 - bjorn3:remove_emscripten_leftover, r=spastorino
[rust.git] / src / tools / clippy / clippy_lints / src / fallible_impl_from.rs
1 use crate::utils::paths::{BEGIN_PANIC, BEGIN_PANIC_FMT, FROM_TRAIT};
2 use crate::utils::{
3     is_expn_of, is_type_diagnostic_item, match_def_path, method_chain_args, span_lint_and_then, walk_ptrs_ty,
4 };
5 use if_chain::if_chain;
6 use rustc_hir as hir;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_middle::hir::map::Map;
9 use rustc_middle::ty;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::Span;
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
15     ///
16     /// **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// struct Foo(i32);
23     ///
24     /// // Bad
25     /// impl From<String> for Foo {
26     ///     fn from(s: String) -> Self {
27     ///         Foo(s.parse().unwrap())
28     ///     }
29     /// }
30     /// ```
31     ///
32     /// ```rust
33     /// // Good
34     /// struct Foo(i32);
35     ///
36     /// use std::convert::TryFrom;
37     /// impl TryFrom<String> for Foo {
38     ///     type Error = ();
39     ///     fn try_from(s: String) -> Result<Self, Self::Error> {
40     ///         if let Ok(parsed) = s.parse() {
41     ///             Ok(Foo(parsed))
42     ///         } else {
43     ///             Err(())
44     ///         }
45     ///     }
46     /// }
47     /// ```
48     pub FALLIBLE_IMPL_FROM,
49     nursery,
50     "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
51 }
52
53 declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
54
55 impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
56     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
57         // check for `impl From<???> for ..`
58         let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
59         if_chain! {
60             if let hir::ItemKind::Impl{ items: impl_items, .. } = item.kind;
61             if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id);
62             if match_def_path(cx, impl_trait_ref.def_id, &FROM_TRAIT);
63             then {
64                 lint_impl_body(cx, item.span, impl_items);
65             }
66         }
67     }
68 }
69
70 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef<'_>]) {
71     use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
72     use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
73
74     struct FindPanicUnwrap<'a, 'tcx> {
75         lcx: &'a LateContext<'tcx>,
76         typeck_results: &'tcx ty::TypeckResults<'tcx>,
77         result: Vec<Span>,
78     }
79
80     impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
81         type Map = Map<'tcx>;
82
83         fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
84             // check for `begin_panic`
85             if_chain! {
86                 if let ExprKind::Call(ref func_expr, _) = expr.kind;
87                 if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
88                 if let Some(path_def_id) = path.res.opt_def_id();
89                 if match_def_path(self.lcx, path_def_id, &BEGIN_PANIC) ||
90                     match_def_path(self.lcx, path_def_id, &BEGIN_PANIC_FMT);
91                 if is_expn_of(expr.span, "unreachable").is_none();
92                 then {
93                     self.result.push(expr.span);
94                 }
95             }
96
97             // check for `unwrap`
98             if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
99                 let reciever_ty = walk_ptrs_ty(self.typeck_results.expr_ty(&arglists[0][0]));
100                 if is_type_diagnostic_item(self.lcx, reciever_ty, sym!(option_type))
101                     || is_type_diagnostic_item(self.lcx, reciever_ty, sym!(result_type))
102                 {
103                     self.result.push(expr.span);
104                 }
105             }
106
107             // and check sub-expressions
108             intravisit::walk_expr(self, expr);
109         }
110
111         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
112             NestedVisitorMap::None
113         }
114     }
115
116     for impl_item in impl_items {
117         if_chain! {
118             if impl_item.ident.name == sym!(from);
119             if let ImplItemKind::Fn(_, body_id) =
120                 cx.tcx.hir().impl_item(impl_item.id).kind;
121             then {
122                 // check the body for `begin_panic` or `unwrap`
123                 let body = cx.tcx.hir().body(body_id);
124                 let impl_item_def_id = cx.tcx.hir().local_def_id(impl_item.id.hir_id);
125                 let mut fpu = FindPanicUnwrap {
126                     lcx: cx,
127                     typeck_results: cx.tcx.typeck(impl_item_def_id),
128                     result: Vec::new(),
129                 };
130                 fpu.visit_expr(&body.value);
131
132                 // if we've found one, lint
133                 if !fpu.result.is_empty() {
134                     span_lint_and_then(
135                         cx,
136                         FALLIBLE_IMPL_FROM,
137                         impl_span,
138                         "consider implementing `TryFrom` instead",
139                         move |diag| {
140                             diag.help(
141                                 "`From` is intended for infallible conversions only. \
142                                 Use `TryFrom` if there's a possibility for the conversion to fail.");
143                             diag.span_note(fpu.result, "potential failure(s)");
144                         });
145                 }
146             }
147         }
148     }
149 }