Skip to content

Commit

Permalink
Refine complexity rules for try-except-else-finally (#3519)
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Mar 14, 2023
1 parent 432059d commit 344daeb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
42 changes: 35 additions & 7 deletions crates/ruff/src/rules/mccabe/rules.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use rustpython_parser::ast::{ExcepthandlerKind, ExprKind, Stmt, StmtKind};
use rustpython_parser::ast::{ExcepthandlerKind, Stmt, StmtKind};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
Expand Down Expand Up @@ -74,13 +74,10 @@ fn get_complexity_number(stmts: &[Stmt]) -> usize {
complexity += get_complexity_number(body);
complexity += get_complexity_number(orelse);
}
StmtKind::While { test, body, orelse } => {
StmtKind::While { body, orelse, .. } => {
complexity += 1;
complexity += get_complexity_number(body);
complexity += get_complexity_number(orelse);
if let ExprKind::BoolOp { .. } = &test.node {
complexity += 1;
}
}
StmtKind::Match { cases, .. } => {
complexity += 1;
Expand All @@ -100,8 +97,10 @@ fn get_complexity_number(stmts: &[Stmt]) -> usize {
orelse,
finalbody,
} => {
complexity += 1;
complexity += get_complexity_number(body);
if !orelse.is_empty() {
complexity += 1;
}
complexity += get_complexity_number(orelse);
complexity += get_complexity_number(finalbody);
for handler in handlers {
Expand Down Expand Up @@ -307,7 +306,7 @@ def nested_try_finally():
print(3)
"#;
let stmts = parser::parse_program(source, "<filename>")?;
assert_eq!(get_complexity_number(&stmts), 3);
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}

Expand Down Expand Up @@ -374,4 +373,33 @@ class Class:
assert_eq!(get_complexity_number(&stmts), 9);
Ok(())
}

#[test]
fn finally() -> Result<()> {
let source = r#"
def process_detect_lines():
try:
pass
finally:
pass
"#;
let stmts = parser::parse_program(source, "<filename>")?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}

#[test]
fn if_in_finally() -> Result<()> {
let source = r#"
def process_detect_lines():
try:
pass
finally:
if res:
errors.append(f"Non-zero exit code {res}")
"#;
let stmts = parser::parse_program(source, "<filename>")?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ expression: diagnostics
parent: ~
- kind:
name: ComplexStructure
body: "`nested_try_finally` is too complex (3)"
body: "`nested_try_finally` is too complex (1)"
suggestion: ~
fixable: false
location:
Expand Down

0 comments on commit 344daeb

Please sign in to comment.