|
5 | 5 | import ast |
6 | 6 | from typing import TYPE_CHECKING, Any, cast |
7 | 7 |
|
8 | | -from .flake8asyncvisitor import Flake8AsyncVisitor |
9 | | -from .helpers import disabled_by_default, error_class, get_matching_call, has_decorator |
| 8 | +import libcst as cst |
| 9 | + |
| 10 | +from .flake8asyncvisitor import Flake8AsyncVisitor, Flake8AsyncVisitor_cst |
| 11 | +from .helpers import ( |
| 12 | + disabled_by_default, |
| 13 | + error_class, |
| 14 | + error_class_cst, |
| 15 | + get_matching_call, |
| 16 | + has_decorator, |
| 17 | + identifier_to_string, |
| 18 | +) |
10 | 19 |
|
11 | 20 | if TYPE_CHECKING: |
12 | 21 | from collections.abc import Mapping |
@@ -332,6 +341,53 @@ def visit_Yield(self, node: ast.Yield): |
332 | 341 | visit_Lambda = visit_AsyncFunctionDef |
333 | 342 |
|
334 | 343 |
|
| 344 | +@error_class_cst |
| 345 | +class Visitor300(Flake8AsyncVisitor_cst): |
| 346 | + error_codes: Mapping[str, str] = { |
| 347 | + "ASYNC300": "asyncio.create_task() called without saving the result" |
| 348 | + } |
| 349 | + |
| 350 | + def __init__(self, *args: Any, **kwargs: Any): |
| 351 | + super().__init__(*args, **kwargs) |
| 352 | + self.safe_to_create_task: bool = False |
| 353 | + |
| 354 | + def visit_Assign(self, node: cst.CSTNode): |
| 355 | + self.save_state(node, "safe_to_create_task") |
| 356 | + self.safe_to_create_task = True |
| 357 | + |
| 358 | + def visit_CompIf(self, node: cst.CSTNode): |
| 359 | + self.save_state(node, "safe_to_create_task") |
| 360 | + self.safe_to_create_task = False |
| 361 | + |
| 362 | + def visit_Call(self, node: cst.Call): |
| 363 | + if ( |
| 364 | + isinstance(node.func, (cst.Name, cst.Attribute)) |
| 365 | + and identifier_to_string(node.func) == "asyncio.create_task" |
| 366 | + and not self.safe_to_create_task |
| 367 | + ): |
| 368 | + self.error(node) |
| 369 | + self.visit_Assign(node) |
| 370 | + |
| 371 | + visit_NamedExpr = visit_Assign |
| 372 | + visit_AugAssign = visit_Assign |
| 373 | + visit_IfExp_test = visit_CompIf |
| 374 | + |
| 375 | + # because this is a Flake8AsyncVisitor_cst, we need to manually call restore_state |
| 376 | + def leave_Assign( |
| 377 | + self, original_node: cst.CSTNode, updated_node: cst.CSTNode |
| 378 | + ) -> Any: |
| 379 | + self.restore_state(original_node) |
| 380 | + return updated_node |
| 381 | + |
| 382 | + leave_Call = leave_Assign |
| 383 | + leave_CompIf = leave_Assign |
| 384 | + leave_NamedExpr = leave_Assign |
| 385 | + leave_AugAssign = leave_Assign |
| 386 | + |
| 387 | + def leave_IfExp_test(self, node: cst.IfExp): |
| 388 | + self.restore_state(node) |
| 389 | + |
| 390 | + |
335 | 391 | @error_class |
336 | 392 | @disabled_by_default |
337 | 393 | class Visitor900(Flake8AsyncVisitor): |
|
0 commit comments