1 use crate::utils::{is_expn_of, is_type_diagnostic_item, match_panic_def_id, method_chain_args, span_lint_and_then};
2 use if_chain::if_chain;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::hir::map::Map;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::{sym, Span};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
13 /// **Why is this bad?** `TryFrom` should be used if there's a possibility of failure.
15 /// **Known problems:** None.
22 /// impl From<String> for Foo {
23 /// fn from(s: String) -> Self {
24 /// Foo(s.parse().unwrap())
33 /// use std::convert::TryFrom;
34 /// impl TryFrom<String> for Foo {
36 /// fn try_from(s: String) -> Result<Self, Self::Error> {
37 /// if let Ok(parsed) = s.parse() {
45 pub FALLIBLE_IMPL_FROM,
47 "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
50 declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
52 impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
53 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
54 // check for `impl From<???> for ..`
55 let impl_def_id = cx.tcx.hir().local_def_id(item.hir_id);
57 if let hir::ItemKind::Impl(impl_) = &item.kind;
58 if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(impl_def_id);
59 if cx.tcx.is_diagnostic_item(sym::from_trait, impl_trait_ref.def_id);
61 lint_impl_body(cx, item.span, impl_.items);
67 fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef<'_>]) {
68 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
69 use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
71 struct FindPanicUnwrap<'a, 'tcx> {
72 lcx: &'a LateContext<'tcx>,
73 typeck_results: &'tcx ty::TypeckResults<'tcx>,
77 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
80 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
81 // check for `begin_panic`
83 if let ExprKind::Call(ref func_expr, _) = expr.kind;
84 if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
85 if let Some(path_def_id) = path.res.opt_def_id();
86 if match_panic_def_id(self.lcx, path_def_id);
87 if is_expn_of(expr.span, "unreachable").is_none();
89 self.result.push(expr.span);
94 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
95 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
96 if is_type_diagnostic_item(self.lcx, reciever_ty, sym::option_type)
97 || is_type_diagnostic_item(self.lcx, reciever_ty, sym::result_type)
99 self.result.push(expr.span);
103 // and check sub-expressions
104 intravisit::walk_expr(self, expr);
107 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
108 NestedVisitorMap::None
112 for impl_item in impl_items {
114 if impl_item.ident.name == sym::from;
115 if let ImplItemKind::Fn(_, body_id) =
116 cx.tcx.hir().impl_item(impl_item.id).kind;
118 // check the body for `begin_panic` or `unwrap`
119 let body = cx.tcx.hir().body(body_id);
120 let impl_item_def_id = cx.tcx.hir().local_def_id(impl_item.id.hir_id);
121 let mut fpu = FindPanicUnwrap {
123 typeck_results: cx.tcx.typeck(impl_item_def_id),
126 fpu.visit_expr(&body.value);
128 // if we've found one, lint
129 if !fpu.result.is_empty() {
134 "consider implementing `TryFrom` instead",
137 "`From` is intended for infallible conversions only. \
138 Use `TryFrom` if there's a possibility for the conversion to fail.");
139 diag.span_note(fpu.result, "potential failure(s)");