|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet_with_context; |
| 3 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::{ExprKind, Stmt, StmtKind}; |
| 6 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 7 | +use rustc_middle::lint::in_external_macro; |
| 8 | +use rustc_session::declare_lint_pass; |
| 9 | +use rustc_span::sym; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// Checks for calls to `Result::ok()` without using the returned `Option`. |
| 14 | + /// |
| 15 | + /// ### Why is this bad? |
| 16 | + /// Using `Result::ok()` may look like the result is checked like `unwrap` or `expect` would do |
| 17 | + /// but it only silences the warning caused by `#[must_use]` on the `Result`. |
| 18 | + /// |
| 19 | + /// ### Example |
| 20 | + /// ```no_run |
| 21 | + /// # fn some_function() -> Result<(), ()> { Ok(()) } |
| 22 | + /// some_function().ok(); |
| 23 | + /// ``` |
| 24 | + /// Use instead: |
| 25 | + /// ```no_run |
| 26 | + /// # fn some_function() -> Result<(), ()> { Ok(()) } |
| 27 | + /// let _ = some_function(); |
| 28 | + /// ``` |
| 29 | + #[clippy::version = "1.70.0"] |
| 30 | + pub UNUSED_RESULT_OK, |
| 31 | + restriction, |
| 32 | + "Use of `.ok()` to silence `Result`'s `#[must_use]` is misleading. Use `let _ =` instead." |
| 33 | +} |
| 34 | +declare_lint_pass!(UnusedResultOk => [UNUSED_RESULT_OK]); |
| 35 | + |
| 36 | +impl LateLintPass<'_> for UnusedResultOk { |
| 37 | + fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &Stmt<'_>) { |
| 38 | + if let StmtKind::Semi(expr) = stmt.kind |
| 39 | + && let ExprKind::MethodCall(ok_path, recv, [], ..) = expr.kind //check is expr.ok() has type Result<T,E>.ok(, _) |
| 40 | + && ok_path.ident.as_str() == "ok" |
| 41 | + && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv), sym::Result) |
| 42 | + && !in_external_macro(cx.sess(), stmt.span) |
| 43 | + { |
| 44 | + let ctxt = expr.span.ctxt(); |
| 45 | + let mut applicability = Applicability::MaybeIncorrect; |
| 46 | + let snippet = snippet_with_context(cx, recv.span, ctxt, "", &mut applicability).0; |
| 47 | + let sugg = format!("let _ = {snippet}"); |
| 48 | + span_lint_and_sugg( |
| 49 | + cx, |
| 50 | + UNUSED_RESULT_OK, |
| 51 | + expr.span, |
| 52 | + "ignoring a result with `.ok()` is misleading", |
| 53 | + "consider using `let _ =` and removing the call to `.ok()` instead", |
| 54 | + sugg, |
| 55 | + applicability, |
| 56 | + ); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments