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

Add suggested fix for TRY201 #6008

Merged
merged 5 commits into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
50 changes: 34 additions & 16 deletions crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use ruff_text_size::TextRange;
use rustpython_parser::ast::{self, ExceptHandler, Expr, Ranged, Stmt};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::statement_visitor::{walk_stmt, StatementVisitor};

use crate::checkers::ast::Checker;
use crate::registry::AsRule;

/// ## What it does
/// Checks for needless exception names in `raise` statements.
Expand Down Expand Up @@ -33,16 +35,20 @@ use crate::checkers::ast::Checker;
#[violation]
pub struct VerboseRaise;

impl Violation for VerboseRaise {
impl AlwaysAutofixableViolation for VerboseRaise {
#[derive_message_formats]
fn message(&self) -> String {
format!("Use `raise` without specifying exception name")
}

fn autofix_title(&self) -> String {
format!("Remove exception name")
}
}

#[derive(Default)]
struct RaiseStatementVisitor<'a> {
raises: Vec<(Option<&'a Expr>, Option<&'a Expr>)>,
raises: Vec<&'a ast::StmtRaise>,
}

impl<'a, 'b> StatementVisitor<'b> for RaiseStatementVisitor<'a>
Expand All @@ -51,12 +57,8 @@ where
{
fn visit_stmt(&mut self, stmt: &'b Stmt) {
match stmt {
Stmt::Raise(ast::StmtRaise {
exc,
cause,
range: _,
}) => {
self.raises.push((exc.as_deref(), cause.as_deref()));
Stmt::Raise(raise @ ast::StmtRaise { .. }) => {
self.raises.push(raise);
}
Stmt::Try(ast::StmtTry {
body, finalbody, ..
Expand All @@ -78,6 +80,7 @@ pub(crate) fn verbose_raise(checker: &mut Checker, handlers: &[ExceptHandler]) {
for handler in handlers {
// If the handler assigned a name to the exception...
if let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
type_: Some(expr),
name: Some(exception_name),
body,
..
Expand All @@ -88,17 +91,32 @@ pub(crate) fn verbose_raise(checker: &mut Checker, handlers: &[ExceptHandler]) {
visitor.visit_body(body);
visitor.raises
};
for (exc, cause) in raises {
if cause.is_some() {
for raise in raises {
if raise.cause.is_some() {
continue;
}
if let Some(exc) = exc {
if let Some(exc) = raise.exc.as_ref() {
// ...and the raised object is bound to the same name...
if let Expr::Name(ast::ExprName { id, .. }) = exc {
if let Expr::Name(ast::ExprName { id, .. }) = exc.as_ref() {
if id == exception_name.as_str() {
checker
.diagnostics
.push(Diagnostic::new(VerboseRaise, exc.range()));
let mut diagnostic = Diagnostic::new(VerboseRaise, exc.range());
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(Fix::automatic_edits(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be simplified to: Edit::range_replacement("raise".to_string(), raise.range())?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should be "suggested" because this rule can have some false positives. I assume it gets this wrong:

except Foo as e:
  e = 1
  raise e

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yes, I had that case in mind and it does gets it wrong. I was wondering if our semantic model can resolve such references (I can't find anything on that). I'll make this a suggested fix.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we change to Edit::range_replacement("raise".to_string(), raise.range()) too, or does that not work?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh we need to delete as e too, I see. Does this rule verify that e isn't used in the exception body? Like:

except Foo as e:
  print(e)
  raise e

In that case, we can change raise e to raise, but we can't remove as e.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, we don't really check that case. I don't think we can use the semantic model to verify such instances so I'll probably have to check either using a StatementVisitor or any_over_stmt.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this fix should only remove e in raise e. If the variable is unused, it'll get marked in the next pass as an unused variable and removed via the unused variable autofix.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right, that makes sense. I'll just add a test case for it then and remove the first edit.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good. Eventually we can improve this rule to handle it properly in the first place.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this is interesting: Ruff is detecting that the variable e is unused in the last test case which seems incorrect:

def bad_that_needs_recursion_2():
    try:
        process()
    except MyException as e:  # F841: Local variable `e` is assigned to but never used
        logger.exception("process failed")
        if True:

            def foo():
                raise e  # F821: Undefined name `e`

Edit::deletion(
expr.range().end(),
exception_name.range().end(),
),
[Edit::range_replacement(
checker.generator().stmt(&Stmt::Raise(ast::StmtRaise {
range: TextRange::default(),
exc: None,
cause: None,
})),
raise.range(),
)],
));
}
checker.diagnostics.push(diagnostic);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,70 @@
---
source: crates/ruff/src/rules/tryceratops/mod.rs
---
TRY201.py:20:15: TRY201 Use `raise` without specifying exception name
TRY201.py:20:15: TRY201 [*] Use `raise` without specifying exception name
|
18 | except MyException as e:
19 | logger.exception("process failed")
20 | raise e
| ^ TRY201
|
= help: Remove exception name

TRY201.py:63:19: TRY201 Use `raise` without specifying exception name
ℹ Fix
15 15 | def bad():
16 16 | try:
17 17 | process()
18 |- except MyException as e:
18 |+ except MyException:
19 19 | logger.exception("process failed")
20 |- raise e
20 |+ raise
21 21 |
22 22 |
23 23 | def good():

TRY201.py:63:19: TRY201 [*] Use `raise` without specifying exception name
|
61 | logger.exception("process failed")
62 | if True:
63 | raise e
| ^ TRY201
|
= help: Remove exception name

ℹ Fix
57 57 | def bad_that_needs_recursion():
58 58 | try:
59 59 | process()
60 |- except MyException as e:
60 |+ except MyException:
61 61 | logger.exception("process failed")
62 62 | if True:
63 |- raise e
63 |+ raise
64 64 |
65 65 |
66 66 | def bad_that_needs_recursion_2():

TRY201.py:74:23: TRY201 Use `raise` without specifying exception name
TRY201.py:74:23: TRY201 [*] Use `raise` without specifying exception name
|
73 | def foo():
74 | raise e
| ^ TRY201
|
= help: Remove exception name

ℹ Fix
66 66 | def bad_that_needs_recursion_2():
67 67 | try:
68 68 | process()
69 |- except MyException as e:
69 |+ except MyException:
70 70 | logger.exception("process failed")
71 71 | if True:
72 72 |
73 73 | def foo():
74 |- raise e
74 |+ raise


Loading