|
| 1 | +use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet}; |
| 2 | +use rustc_ast::ast::*; |
| 3 | +use rustc_ast::visit::Visitor as AstVisitor; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 6 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// Checks for `async` block that only returns `await` on a future. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// It is simpler and more efficient to use the future directly. |
| 14 | + /// |
| 15 | + /// ### Example |
| 16 | + /// ```rust |
| 17 | + /// async fn f() -> i32 { |
| 18 | + /// 1 + 2 |
| 19 | + /// } |
| 20 | + /// |
| 21 | + /// let fut = async { |
| 22 | + /// f().await |
| 23 | + /// }; |
| 24 | + /// ``` |
| 25 | + /// Use instead: |
| 26 | + /// ```rust |
| 27 | + /// async fn f() -> i32 { |
| 28 | + /// 1 + 2 |
| 29 | + /// } |
| 30 | + /// |
| 31 | + /// let fut = f(); |
| 32 | + /// ``` |
| 33 | + #[clippy::version = "1.69.0"] |
| 34 | + pub REDUNDANT_ASYNC_BLOCK, |
| 35 | + complexity, |
| 36 | + "`async { future.await }` can be replaced by `future`" |
| 37 | +} |
| 38 | +declare_lint_pass!(RedundantAsyncBlock => [REDUNDANT_ASYNC_BLOCK]); |
| 39 | + |
| 40 | +impl EarlyLintPass for RedundantAsyncBlock { |
| 41 | + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { |
| 42 | + if expr.span.from_expansion() { |
| 43 | + return; |
| 44 | + } |
| 45 | + if let ExprKind::Async(_, _, block) = &expr.kind && block.stmts.len() == 1 && |
| 46 | + let Some(Stmt { kind: StmtKind::Expr(last), .. }) = block.stmts.last() && |
| 47 | + let ExprKind::Await(future) = &last.kind && |
| 48 | + !future.span.from_expansion() && |
| 49 | + !await_in_expr(future) |
| 50 | + { |
| 51 | + span_lint_and_sugg( |
| 52 | + cx, |
| 53 | + REDUNDANT_ASYNC_BLOCK, |
| 54 | + expr.span, |
| 55 | + "this async expression only awaits a single future", |
| 56 | + "you can reduce it to", |
| 57 | + snippet(cx, future.span, "..").into_owned(), |
| 58 | + Applicability::MachineApplicable, |
| 59 | + ); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/// Check whether an expression contains `.await` |
| 65 | +fn await_in_expr(expr: &Expr) -> bool { |
| 66 | + let mut detector = AwaitDetector::default(); |
| 67 | + detector.visit_expr(expr); |
| 68 | + detector.await_found |
| 69 | +} |
| 70 | + |
| 71 | +#[derive(Default)] |
| 72 | +struct AwaitDetector { |
| 73 | + await_found: bool, |
| 74 | +} |
| 75 | + |
| 76 | +impl<'ast> AstVisitor<'ast> for AwaitDetector { |
| 77 | + fn visit_expr(&mut self, ex: &'ast Expr) { |
| 78 | + match (&ex.kind, self.await_found) { |
| 79 | + (ExprKind::Await(_), _) => self.await_found = true, |
| 80 | + (_, false) => rustc_ast::visit::walk_expr(self, ex), |
| 81 | + _ => (), |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments