|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::macros::{find_assert_args, root_macro_call_first_node, PanicExpn}; |
| 3 | +use clippy_utils::source::snippet_opt; |
| 4 | +use if_chain::if_chain; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir::{Expr, ExprKind}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 9 | +use rustc_span::sym; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// Checks for `assert!(r.is_ok())` calls. |
| 14 | + /// |
| 15 | + /// ### Why is this bad? |
| 16 | + /// An assertion failure cannot output a useful message of the error. |
| 17 | + /// |
| 18 | + /// ### Known problems |
| 19 | + /// The error type needs to implement `Debug`. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// ```rust,ignore |
| 23 | + /// # let r = Ok::<_, ()>(()); |
| 24 | + /// assert!(r.is_ok()); |
| 25 | + /// ``` |
| 26 | + #[clippy::version = "1.64.0"] |
| 27 | + pub ASSERT_OK, |
| 28 | + style, |
| 29 | + "`assert!(r.is_ok())` gives worse error message than directly calling `r.unwrap()`" |
| 30 | +} |
| 31 | + |
| 32 | +declare_lint_pass!(AssertOk => [ASSERT_OK]); |
| 33 | + |
| 34 | +impl<'tcx> LateLintPass<'tcx> for AssertOk { |
| 35 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { |
| 36 | + if_chain! { |
| 37 | + if let Some(macro_call) = root_macro_call_first_node(cx, e); |
| 38 | + if matches!(cx.tcx.get_diagnostic_name(macro_call.def_id), Some(sym::assert_macro)); |
| 39 | + if let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn); |
| 40 | + if matches!(panic_expn, PanicExpn::Empty); |
| 41 | + if let ExprKind::MethodCall(method_segment, args, _) = condition.kind; |
| 42 | + if method_segment.ident.name == sym!(is_ok); |
| 43 | + let method_receiver = &args[0]; |
| 44 | + if let Some(method_receiver_snippet) = snippet_opt(cx, method_receiver.span); |
| 45 | + then { |
| 46 | + span_lint_and_sugg( |
| 47 | + cx, |
| 48 | + ASSERT_OK, |
| 49 | + macro_call.span, |
| 50 | + &format!( |
| 51 | + "`assert!({}.is_ok())` gives bad error message", |
| 52 | + method_receiver_snippet |
| 53 | + ), |
| 54 | + "replace with", |
| 55 | + format!( |
| 56 | + "{}.unwrap()", |
| 57 | + method_receiver_snippet |
| 58 | + ), |
| 59 | + Applicability::Unspecified, |
| 60 | + ); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments