-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add initial flake8-trio rule (#8439)
## Summary This pull request adds [flake8-trio](https://github.com/Zac-HD/flake8-trio) support to ruff, which is a very useful plugin for trio users to avoid very common mistakes. Part of #8451. ## Test Plan Traditional rule testing, as [described in the documentation](https://docs.astral.sh/ruff/contributing/#rule-testing-fixtures-and-snapshots).
- Loading branch information
1 parent
7fa6ac9
commit 2ff1afb
Showing
13 changed files
with
242 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
crates/ruff_linter/resources/test/fixtures/flake8_trio/TRIO100.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import trio | ||
|
||
|
||
async def foo(): | ||
with trio.fail_after(): | ||
... | ||
|
||
async def foo(): | ||
with trio.fail_at(): | ||
await ... | ||
|
||
async def foo(): | ||
with trio.move_on_after(): | ||
... | ||
|
||
async def foo(): | ||
with trio.move_at(): | ||
await ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
//! Rules from [flake8-trio](https://pypi.org/project/flake8-trio/). | ||
pub(crate) mod rules; | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::path::Path; | ||
|
||
use anyhow::Result; | ||
use test_case::test_case; | ||
|
||
use crate::assert_messages; | ||
use crate::registry::Rule; | ||
use crate::settings::LinterSettings; | ||
use crate::test::test_path; | ||
|
||
#[test_case(Rule::TrioTimeoutWithoutAwait, Path::new("TRIO100.py"))] | ||
fn rules(rule_code: Rule, path: &Path) -> Result<()> { | ||
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy()); | ||
let diagnostics = test_path( | ||
Path::new("flake8_trio").join(path).as_path(), | ||
&LinterSettings::for_rule(rule_code), | ||
)?; | ||
assert_messages!(snapshot, diagnostics); | ||
Ok(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
pub(crate) use timeout_without_await::*; | ||
|
||
mod timeout_without_await; |
125 changes: 125 additions & 0 deletions
125
crates/ruff_linter/src/rules/flake8_trio/rules/timeout_without_await.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
use ruff_diagnostics::{Diagnostic, Violation}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::call_path::CallPath; | ||
use ruff_python_ast::visitor::{walk_expr, walk_stmt, Visitor}; | ||
use ruff_python_ast::{Expr, ExprAwait, Stmt, StmtWith, WithItem}; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for trio functions that should contain await but don't. | ||
/// | ||
/// ## Why is this bad? | ||
/// Some trio context managers, such as `trio.fail_after` and | ||
/// `trio.move_on_after`, have no effect unless they contain an `await` | ||
/// statement. The use of such functions without an `await` statement is | ||
/// likely a mistake. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// async def func(): | ||
/// with trio.move_on_after(2): | ||
/// do_something() | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// async def func(): | ||
/// with trio.move_on_after(2): | ||
/// do_something() | ||
/// await awaitable() | ||
/// ``` | ||
#[violation] | ||
pub struct TrioTimeoutWithoutAwait { | ||
method_name: MethodName, | ||
} | ||
|
||
impl Violation for TrioTimeoutWithoutAwait { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
let Self { method_name } = self; | ||
format!("A `with {method_name}(...):` context does not contain any `await` statements. This makes it pointless, as the timeout can only be triggered by a checkpoint.") | ||
} | ||
} | ||
|
||
/// TRIO100 | ||
pub(crate) fn timeout_without_await( | ||
checker: &mut Checker, | ||
with_stmt: &StmtWith, | ||
with_items: &[WithItem], | ||
) { | ||
let Some(method_name) = with_items.iter().find_map(|item| { | ||
let call = item.context_expr.as_call_expr()?; | ||
let call_path = checker.semantic().resolve_call_path(call.func.as_ref())?; | ||
MethodName::try_from(&call_path) | ||
}) else { | ||
return; | ||
}; | ||
|
||
let mut visitor = AwaitVisitor::default(); | ||
visitor.visit_body(&with_stmt.body); | ||
if visitor.seen_await { | ||
return; | ||
} | ||
|
||
checker.diagnostics.push(Diagnostic::new( | ||
TrioTimeoutWithoutAwait { method_name }, | ||
with_stmt.range, | ||
)); | ||
} | ||
|
||
#[derive(Debug, Copy, Clone, PartialEq, Eq)] | ||
enum MethodName { | ||
MoveOnAfter, | ||
MoveOnAt, | ||
FailAfter, | ||
FailAt, | ||
CancelScope, | ||
} | ||
|
||
impl MethodName { | ||
fn try_from(call_path: &CallPath<'_>) -> Option<Self> { | ||
match call_path.as_slice() { | ||
["trio", "move_on_after"] => Some(Self::MoveOnAfter), | ||
["trio", "move_on_at"] => Some(Self::MoveOnAt), | ||
["trio", "fail_after"] => Some(Self::FailAfter), | ||
["trio", "fail_at"] => Some(Self::FailAt), | ||
["trio", "CancelScope"] => Some(Self::CancelScope), | ||
_ => None, | ||
} | ||
} | ||
} | ||
|
||
impl std::fmt::Display for MethodName { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
match self { | ||
MethodName::MoveOnAfter => write!(f, "trio.move_on_after"), | ||
MethodName::MoveOnAt => write!(f, "trio.move_on_at"), | ||
MethodName::FailAfter => write!(f, "trio.fail_after"), | ||
MethodName::FailAt => write!(f, "trio.fail_at"), | ||
MethodName::CancelScope => write!(f, "trio.CancelScope"), | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug, Default)] | ||
struct AwaitVisitor { | ||
seen_await: bool, | ||
} | ||
|
||
impl Visitor<'_> for AwaitVisitor { | ||
fn visit_stmt(&mut self, stmt: &Stmt) { | ||
match stmt { | ||
Stmt::FunctionDef(_) | Stmt::ClassDef(_) => (), | ||
_ => walk_stmt(self, stmt), | ||
} | ||
} | ||
|
||
fn visit_expr(&mut self, expr: &Expr) { | ||
if let Expr::Await(ExprAwait { .. }) = expr { | ||
self.seen_await = true; | ||
} else { | ||
walk_expr(self, expr); | ||
} | ||
} | ||
} |
26 changes: 26 additions & 0 deletions
26
...les/flake8_trio/snapshots/ruff_linter__rules__flake8_trio__tests__TRIO100_TRIO100.py.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/flake8_trio/mod.rs | ||
--- | ||
TRIO100.py:5:5: TRIO100 A `with trio.fail_after(...):` context does not contain any `await` statements. This makes it pointless, as the timeout can only be triggered by a checkpoint. | ||
| | ||
4 | async def foo(): | ||
5 | with trio.fail_after(): | ||
| _____^ | ||
6 | | ... | ||
| |___________^ TRIO100 | ||
7 | | ||
8 | async def foo(): | ||
| | ||
|
||
TRIO100.py:13:5: TRIO100 A `with trio.move_on_after(...):` context does not contain any `await` statements. This makes it pointless, as the timeout can only be triggered by a checkpoint. | ||
| | ||
12 | async def foo(): | ||
13 | with trio.move_on_after(): | ||
| _____^ | ||
14 | | ... | ||
| |___________^ TRIO100 | ||
15 | | ||
16 | async def foo(): | ||
| | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.