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::path_res;
4 use clippy_utils::source::snippet_with_context;
5 use clippy_utils::ty::{implements_trait, is_copy, is_type_diagnostic_item};
6 use clippy_utils::usage::local_used_after_expr;
7 use rustc_errors::Applicability;
8 use rustc_hir::def::Res;
9 use rustc_hir::{Expr, ExprKind};
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::ty::{self, Ty};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 declare_clippy_lint! {
17 /// Checks for `assert!(r.is_ok())` or `assert!(r.is_err())` calls.
19 /// ### Why is this bad?
20 /// An assertion failure cannot output an useful message of the error.
24 /// # let r = Ok::<_, ()>(());
25 /// assert!(r.is_ok());
26 /// # let r = Err::<_, ()>(());
27 /// assert!(r.is_err());
29 #[clippy::version = "1.64.0"]
30 pub ASSERTIONS_ON_RESULT_STATES,
32 "`assert!(r.is_ok())`/`assert!(r.is_err())` gives worse error message than directly calling `r.unwrap()`/`r.unwrap_err()`"
35 declare_lint_pass!(AssertionsOnResultStates => [ASSERTIONS_ON_RESULT_STATES]);
37 impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates {
38 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
39 if let Some(macro_call) = root_macro_call_first_node(cx, e)
40 && matches!(cx.tcx.get_diagnostic_name(macro_call.def_id), Some(sym::assert_macro))
41 && let Some((condition, panic_expn)) = find_assert_args(cx, e, macro_call.expn)
42 && matches!(panic_expn, PanicExpn::Empty)
43 && let ExprKind::MethodCall(method_segment, [recv], _) = condition.kind
44 && let result_type_with_refs = cx.typeck_results().expr_ty(recv)
45 && let result_type = result_type_with_refs.peel_refs()
46 && is_type_diagnostic_item(cx, result_type, sym::Result)
47 && let ty::Adt(_, substs) = result_type.kind()
49 if !is_copy(cx, result_type) {
50 if result_type_with_refs != result_type {
52 } else if let Res::Local(binding_id) = path_res(cx, recv)
53 && local_used_after_expr(cx, binding_id, recv) {
57 let mut app = Applicability::MachineApplicable;
58 match method_segment.ident.as_str() {
59 "is_ok" if has_debug_impl(cx, substs.type_at(1)) => {
62 ASSERTIONS_ON_RESULT_STATES,
64 "called `assert!` with `Result::is_ok`",
68 snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
73 "is_err" if has_debug_impl(cx, substs.type_at(0)) => {
76 ASSERTIONS_ON_RESULT_STATES,
78 "called `assert!` with `Result::is_err`",
82 snippet_with_context(cx, recv.span, condition.span.ctxt(), "..", &mut app).0
93 /// This checks whether a given type is known to implement Debug.
94 fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
96 .get_diagnostic_item(sym::Debug)
97 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))