|
| 1 | +use ruff_diagnostics::{Diagnostic, Violation}; |
| 2 | +use ruff_macros::{derive_message_formats, violation}; |
| 3 | +use ruff_python_ast::{self as ast, Expr, Stmt}; |
| 4 | +use ruff_text_size::Ranged; |
| 5 | + |
| 6 | +use crate::checkers::ast::Checker; |
| 7 | + |
| 8 | +/// ## What it does |
| 9 | +/// Checks for the use of `trio.sleep` in a `while` loop. |
| 10 | +/// |
| 11 | +/// ## Why is this bad? |
| 12 | +/// Instead of sleeping in a `while` loop, and waiting for a condition |
| 13 | +/// to become true, it's preferable to `wait()` on a `trio.Event`. |
| 14 | +/// |
| 15 | +/// ## Example |
| 16 | +/// ```python |
| 17 | +/// DONE = False |
| 18 | +/// |
| 19 | +/// |
| 20 | +/// async def func(): |
| 21 | +/// while not DONE: |
| 22 | +/// await trio.sleep(1) |
| 23 | +/// ``` |
| 24 | +/// |
| 25 | +/// Use instead: |
| 26 | +/// ```python |
| 27 | +/// DONE = trio.Event() |
| 28 | +/// |
| 29 | +/// |
| 30 | +/// async def func(): |
| 31 | +/// await DONE.wait() |
| 32 | +/// ``` |
| 33 | +#[violation] |
| 34 | +pub struct TrioUnneededSleep; |
| 35 | + |
| 36 | +impl Violation for TrioUnneededSleep { |
| 37 | + #[derive_message_formats] |
| 38 | + fn message(&self) -> String { |
| 39 | + format!("Use `trio.Event` instead of awaiting `trio.sleep` in a `while` loop") |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +/// TRIO110 |
| 44 | +pub(crate) fn unneeded_sleep(checker: &mut Checker, while_stmt: &ast::StmtWhile) { |
| 45 | + // The body should be a single `await` call. |
| 46 | + let [stmt] = while_stmt.body.as_slice() else { |
| 47 | + return; |
| 48 | + }; |
| 49 | + let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else { |
| 50 | + return; |
| 51 | + }; |
| 52 | + let Expr::Await(ast::ExprAwait { value, .. }) = value.as_ref() else { |
| 53 | + return; |
| 54 | + }; |
| 55 | + let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else { |
| 56 | + return; |
| 57 | + }; |
| 58 | + |
| 59 | + if checker |
| 60 | + .semantic() |
| 61 | + .resolve_call_path(func.as_ref()) |
| 62 | + .is_some_and(|path| matches!(path.as_slice(), ["trio", "sleep" | "sleep_until"])) |
| 63 | + { |
| 64 | + checker |
| 65 | + .diagnostics |
| 66 | + .push(Diagnostic::new(TrioUnneededSleep, while_stmt.range())); |
| 67 | + } |
| 68 | +} |
0 commit comments