/
use_contextlib_suppress.rs
42 lines (40 loc) · 1.69 KB
/
use_contextlib_suppress.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use rustpython_ast::{Excepthandler, ExcepthandlerKind, ExprKind};
use crate::ast::helpers;
use crate::ast::types::Range;
use crate::checkers::ast::Checker;
use crate::registry::{Check, CheckKind};
pub fn use_contextlib_suppress(checker: &mut Checker, handlers: &[Excepthandler]) {
for handler in handlers {
let ExcepthandlerKind::ExceptHandler { type_, body, .. } = &handler.node;
if body.len() == 1 {
let node = &body[0].node;
if matches!(node, rustpython_ast::StmtKind::Pass) {
let exception = match type_ {
Some(type_) => match &type_.node {
ExprKind::Attribute { .. } | ExprKind::Name { .. } => {
let call_path = helpers::collect_call_paths(type_);
Some(call_path[0].to_string())
}
ExprKind::Tuple { elts, .. } => {
let mut excs = Vec::new();
for expr in elts {
let call_path = helpers::collect_call_paths(expr);
excs.extend(call_path);
}
Some(excs.join(", "))
}
_ => None,
},
None => None,
};
let check = Check::new(
CheckKind::UseContextlibSuppress(
exception.unwrap_or_else(|| "Exception".to_string()),
),
Range::from_located(handler),
);
checker.add_check(check);
}
}
}
}