Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[flake8-async] Update ASYNC115 to match upstream #12262

Merged
merged 3 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,72 @@ async def main() -> None:
sleep = 10

trio.run(main)


async def func():
import anyio
from anyio import sleep

await anyio.sleep(0) # ASYNC115
await anyio.sleep(1) # OK
await anyio.sleep(0, 1) # OK
await anyio.sleep(...) # OK
await anyio.sleep() # OK

anyio.sleep(0) # ASYNC115
foo = 0
anyio.sleep(foo) # OK
anyio.sleep(1) # OK
time.sleep(0) # OK

sleep(0) # ASYNC115

bar = "bar"
anyio.sleep(bar)

x, y = 0, 2000
anyio.sleep(x) # OK
anyio.sleep(y) # OK

(a, b, [c, (d, e)]) = (1, 2, (0, [4, 0]))
anyio.sleep(c) # OK
anyio.sleep(d) # OK
anyio.sleep(e) # OK

m_x, m_y = 0
anyio.sleep(m_y) # OK
anyio.sleep(m_x) # OK

m_a = m_b = 0
anyio.sleep(m_a) # OK
anyio.sleep(m_b) # OK

m_c = (m_d, m_e) = (0, 0)
anyio.sleep(m_c) # OK
anyio.sleep(m_d) # OK
anyio.sleep(m_e) # OK


def func():
import anyio

anyio.run(anyio.sleep(0)) # ASYNC115


def func():
import anyio

if (walrus := 0) == 0:
anyio.sleep(walrus) # OK


def func():
import anyio

async def main() -> None:
sleep = 0
for _ in range(2):
await anyio.sleep(sleep) # OK
sleep = 10

anyio.run(main)
4 changes: 2 additions & 2 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -975,8 +975,8 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
if checker.enabled(Rule::TrioSyncCall) {
flake8_async::rules::sync_call(checker, call);
}
if checker.enabled(Rule::TrioZeroSleepCall) {
flake8_async::rules::zero_sleep_call(checker, call);
if checker.enabled(Rule::AsyncZeroSleep) {
flake8_async::rules::async_zero_sleep(checker, call);
}
if checker.enabled(Rule::UnnecessaryDunderCall) {
pylint::rules::unnecessary_dunder_call(checker, call);
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8Async, "105") => (RuleGroup::Stable, rules::flake8_async::rules::TrioSyncCall),
(Flake8Async, "109") => (RuleGroup::Stable, rules::flake8_async::rules::AsyncFunctionWithTimeout),
(Flake8Async, "110") => (RuleGroup::Stable, rules::flake8_async::rules::AsyncBusyWait),
(Flake8Async, "115") => (RuleGroup::Stable, rules::flake8_async::rules::TrioZeroSleepCall),
(Flake8Async, "115") => (RuleGroup::Stable, rules::flake8_async::rules::AsyncZeroSleep),
(Flake8Async, "116") => (RuleGroup::Preview, rules::flake8_async::rules::SleepForeverCall),
(Flake8Async, "210") => (RuleGroup::Stable, rules::flake8_async::rules::BlockingHttpCallInAsyncFunction),
(Flake8Async, "220") => (RuleGroup::Stable, rules::flake8_async::rules::CreateSubprocessInAsyncFunction),
Expand Down
3 changes: 2 additions & 1 deletion crates/ruff_linter/src/rules/flake8_async/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ mod tests {
#[test_case(Rule::AsyncFunctionWithTimeout, Path::new("ASYNC109_0.py"))]
#[test_case(Rule::AsyncFunctionWithTimeout, Path::new("ASYNC109_1.py"))]
#[test_case(Rule::AsyncBusyWait, Path::new("ASYNC110.py"))]
#[test_case(Rule::TrioZeroSleepCall, Path::new("ASYNC115.py"))]
#[test_case(Rule::AsyncZeroSleep, Path::new("ASYNC115.py"))]
#[test_case(Rule::SleepForeverCall, Path::new("ASYNC116.py"))]
#[test_case(Rule::BlockingHttpCallInAsyncFunction, Path::new("ASYNC210.py"))]
#[test_case(Rule::CreateSubprocessInAsyncFunction, Path::new("ASYNC22x.py"))]
Expand All @@ -42,6 +42,7 @@ mod tests {
#[test_case(Rule::AsyncFunctionWithTimeout, Path::new("ASYNC109_0.py"))]
#[test_case(Rule::AsyncFunctionWithTimeout, Path::new("ASYNC109_1.py"))]
#[test_case(Rule::AsyncBusyWait, Path::new("ASYNC110.py"))]
#[test_case(Rule::AsyncZeroSleep, Path::new("ASYNC115.py"))]
fn preview_rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"preview__{}_{}",
Expand Down
112 changes: 112 additions & 0 deletions crates/ruff_linter/src/rules/flake8_async/rules/async_zero_sleep.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr, ExprCall, Int, Number};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::rules::flake8_async::helpers::AsyncModule;

/// ## What it does
/// Checks for uses of `trio.sleep(0)` or `anyio.sleep(0)`.
///
/// ## Why is this bad?
/// `trio.sleep(0)` is equivalent to calling `trio.lowlevel.checkpoint()`.
/// However, the latter better conveys the intent of the code.
///
/// ## Example
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.sleep(0)
/// ```
///
/// Use instead:
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.lowlevel.checkpoint()
/// ```
#[violation]
pub struct AsyncZeroSleep {
module: AsyncModule,
}

impl AlwaysFixableViolation for AsyncZeroSleep {
#[derive_message_formats]
fn message(&self) -> String {
let Self { module } = self;
format!("Use `{module}.lowlevel.checkpoint()` instead of `{module}.sleep(0)`")
}

fn fix_title(&self) -> String {
let Self { module } = self;
format!("Replace with `{module}.lowlevel.checkpoint()`")
}
}

/// ASYNC115
pub(crate) fn async_zero_sleep(checker: &mut Checker, call: &ExprCall) {
if !(checker.semantic().seen_module(Modules::TRIO)
|| checker.semantic().seen_module(Modules::ANYIO))
{
return;
}

if call.arguments.len() != 1 {
return;
}

let Some(arg) = call.arguments.find_argument("seconds", 0) else {
return;
};

match arg {
Expr::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => {
if !matches!(value, Number::Int(Int::ZERO)) {
return;
}
}
_ => return,
}

let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};

if let Some(module) = AsyncModule::try_from(&qualified_name) {
let is_relevant_module = if checker.settings.preview.is_enabled() {
matches!(module, AsyncModule::Trio | AsyncModule::AnyIo)
} else {
matches!(module, AsyncModule::Trio)
};

let is_sleep = is_relevant_module && matches!(qualified_name.segments(), [_, "sleep"]);

if !is_sleep {
return;
}

let mut diagnostic = Diagnostic::new(AsyncZeroSleep { module }, call.range());
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from(&module.to_string(), "lowlevel"),
call.func.start(),
checker.semantic(),
)?;
let reference_edit =
Edit::range_replacement(format!("{binding}.checkpoint"), call.func.range());
let arg_edit = Edit::range_replacement("()".to_string(), call.arguments.range());
Ok(Fix::safe_edits(import_edit, [reference_edit, arg_edit]))
});
checker.diagnostics.push(diagnostic);
}
}
4 changes: 2 additions & 2 deletions crates/ruff_linter/src/rules/flake8_async/rules/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
pub(crate) use async_busy_wait::*;
pub(crate) use async_function_with_timeout::*;
pub(crate) use async_zero_sleep::*;
pub(crate) use blocking_http_call::*;
pub(crate) use blocking_open_call::*;
pub(crate) use blocking_process_invocation::*;
pub(crate) use blocking_sleep::*;
pub(crate) use cancel_scope_no_checkpoint::*;
pub(crate) use sleep_forever_call::*;
pub(crate) use sync_call::*;
pub(crate) use zero_sleep_call::*;

mod async_busy_wait;
mod async_function_with_timeout;
mod async_zero_sleep;
mod blocking_http_call;
mod blocking_open_call;
mod blocking_process_invocation;
mod blocking_sleep;
mod cancel_scope_no_checkpoint;
mod sleep_forever_call;
mod sync_call;
mod zero_sleep_call;
92 changes: 0 additions & 92 deletions crates/ruff_linter/src/rules/flake8_async/rules/zero_sleep_call.rs

This file was deleted.

Loading
Loading