|
| 1 | +use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext}; |
| 2 | +use ruff_text_size::{Ranged, TextRange}; |
| 3 | + |
| 4 | +use crate::fix::edits::pad; |
| 5 | +use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; |
| 6 | +use ruff_macros::{derive_message_formats, violation}; |
| 7 | +use ruff_python_ast::call_path::compose_call_path; |
| 8 | +use ruff_python_semantic::SemanticModel; |
| 9 | + |
| 10 | +use crate::checkers::ast::Checker; |
| 11 | +use crate::settings::types::PythonVersion; |
| 12 | + |
| 13 | +/// ## What it does |
| 14 | +/// Checks for uses of exceptions that alias `TimeoutError`. |
| 15 | +/// |
| 16 | +/// ## Why is this bad? |
| 17 | +/// `TimeoutError` is the builtin error type used for exceptions when a system |
| 18 | +/// function timed out at the system level. |
| 19 | +/// |
| 20 | +/// In Python 3.10, `socket.timeout` was aliased to `TimeoutError`. In Python |
| 21 | +/// 3.11, `asyncio.TimeoutError` was aliased to `TimeoutError`. |
| 22 | +/// |
| 23 | +/// These aliases remain in place for compatibility with older versions of |
| 24 | +/// Python, but may be removed in future versions. |
| 25 | +/// |
| 26 | +/// Prefer using `TimeoutError` directly, as it is more idiomatic and future-proof. |
| 27 | +/// |
| 28 | +/// ## Example |
| 29 | +/// ```python |
| 30 | +/// raise asyncio.TimeoutError |
| 31 | +/// ``` |
| 32 | +/// |
| 33 | +/// Use instead: |
| 34 | +/// ```python |
| 35 | +/// raise TimeoutError |
| 36 | +/// ``` |
| 37 | +/// |
| 38 | +/// ## References |
| 39 | +/// - [Python documentation: `TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError) |
| 40 | +#[violation] |
| 41 | +pub struct TimeoutErrorAlias { |
| 42 | + name: Option<String>, |
| 43 | +} |
| 44 | + |
| 45 | +impl AlwaysFixableViolation for TimeoutErrorAlias { |
| 46 | + #[derive_message_formats] |
| 47 | + fn message(&self) -> String { |
| 48 | + format!("Replace aliased errors with `TimeoutError`") |
| 49 | + } |
| 50 | + |
| 51 | + fn fix_title(&self) -> String { |
| 52 | + let TimeoutErrorAlias { name } = self; |
| 53 | + match name { |
| 54 | + None => "Replace with builtin `TimeoutError`".to_string(), |
| 55 | + Some(name) => format!("Replace `{name}` with builtin `TimeoutError`"), |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/// Return `true` if an [`Expr`] is an alias of `TimeoutError`. |
| 61 | +fn is_alias(expr: &Expr, semantic: &SemanticModel, target_version: PythonVersion) -> bool { |
| 62 | + semantic.resolve_call_path(expr).is_some_and(|call_path| { |
| 63 | + if target_version >= PythonVersion::Py311 { |
| 64 | + matches!(call_path.as_slice(), [""] | ["asyncio", "TimeoutError"]) |
| 65 | + } else { |
| 66 | + matches!( |
| 67 | + call_path.as_slice(), |
| 68 | + [""] | ["asyncio", "TimeoutError"] | ["socket", "timeout"] |
| 69 | + ) |
| 70 | + } |
| 71 | + }) |
| 72 | +} |
| 73 | + |
| 74 | +/// Return `true` if an [`Expr`] is `TimeoutError`. |
| 75 | +fn is_timeout_error(expr: &Expr, semantic: &SemanticModel) -> bool { |
| 76 | + semantic |
| 77 | + .resolve_call_path(expr) |
| 78 | + .is_some_and(|call_path| matches!(call_path.as_slice(), ["", "TimeoutError"])) |
| 79 | +} |
| 80 | + |
| 81 | +/// Create a [`Diagnostic`] for a single target, like an [`Expr::Name`]. |
| 82 | +fn atom_diagnostic(checker: &mut Checker, target: &Expr) { |
| 83 | + let mut diagnostic = Diagnostic::new( |
| 84 | + TimeoutErrorAlias { |
| 85 | + name: compose_call_path(target), |
| 86 | + }, |
| 87 | + target.range(), |
| 88 | + ); |
| 89 | + if checker.semantic().is_builtin("TimeoutError") { |
| 90 | + diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( |
| 91 | + "TimeoutError".to_string(), |
| 92 | + target.range(), |
| 93 | + ))); |
| 94 | + } |
| 95 | + checker.diagnostics.push(diagnostic); |
| 96 | +} |
| 97 | + |
| 98 | +/// Create a [`Diagnostic`] for a tuple of expressions. |
| 99 | +fn tuple_diagnostic(checker: &mut Checker, tuple: &ast::ExprTuple, aliases: &[&Expr]) { |
| 100 | + let mut diagnostic = Diagnostic::new(TimeoutErrorAlias { name: None }, tuple.range()); |
| 101 | + if checker.semantic().is_builtin("TimeoutError") { |
| 102 | + // Filter out any `TimeoutErrors` aliases. |
| 103 | + let mut remaining: Vec<Expr> = tuple |
| 104 | + .elts |
| 105 | + .iter() |
| 106 | + .filter_map(|elt| { |
| 107 | + if aliases.contains(&elt) { |
| 108 | + None |
| 109 | + } else { |
| 110 | + Some(elt.clone()) |
| 111 | + } |
| 112 | + }) |
| 113 | + .collect(); |
| 114 | + |
| 115 | + // If `TimeoutError` itself isn't already in the tuple, add it. |
| 116 | + if tuple |
| 117 | + .elts |
| 118 | + .iter() |
| 119 | + .all(|elt| !is_timeout_error(elt, checker.semantic())) |
| 120 | + { |
| 121 | + let node = ast::ExprName { |
| 122 | + id: "TimeoutError".into(), |
| 123 | + ctx: ExprContext::Load, |
| 124 | + range: TextRange::default(), |
| 125 | + }; |
| 126 | + remaining.insert(0, node.into()); |
| 127 | + } |
| 128 | + |
| 129 | + let content = if remaining.len() == 1 { |
| 130 | + "TimeoutError".to_string() |
| 131 | + } else { |
| 132 | + let node = ast::ExprTuple { |
| 133 | + elts: remaining, |
| 134 | + ctx: ExprContext::Load, |
| 135 | + range: TextRange::default(), |
| 136 | + }; |
| 137 | + format!("({})", checker.generator().expr(&node.into())) |
| 138 | + }; |
| 139 | + |
| 140 | + diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( |
| 141 | + pad(content, tuple.range(), checker.locator()), |
| 142 | + tuple.range(), |
| 143 | + ))); |
| 144 | + } |
| 145 | + checker.diagnostics.push(diagnostic); |
| 146 | +} |
| 147 | + |
| 148 | +/// UP041 |
| 149 | +pub(crate) fn timeout_error_alias_handlers(checker: &mut Checker, handlers: &[ExceptHandler]) { |
| 150 | + for handler in handlers { |
| 151 | + let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_, .. }) = handler; |
| 152 | + let Some(expr) = type_.as_ref() else { |
| 153 | + continue; |
| 154 | + }; |
| 155 | + match expr.as_ref() { |
| 156 | + Expr::Name(_) | Expr::Attribute(_) => { |
| 157 | + if is_alias(expr, checker.semantic(), checker.settings.target_version) { |
| 158 | + atom_diagnostic(checker, expr); |
| 159 | + } |
| 160 | + } |
| 161 | + Expr::Tuple(tuple) => { |
| 162 | + // List of aliases to replace with `TimeoutError`. |
| 163 | + let mut aliases: Vec<&Expr> = vec![]; |
| 164 | + for elt in &tuple.elts { |
| 165 | + if is_alias(elt, checker.semantic(), checker.settings.target_version) { |
| 166 | + aliases.push(elt); |
| 167 | + } |
| 168 | + } |
| 169 | + if !aliases.is_empty() { |
| 170 | + tuple_diagnostic(checker, tuple, &aliases); |
| 171 | + } |
| 172 | + } |
| 173 | + _ => {} |
| 174 | + } |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +/// UP041 |
| 179 | +pub(crate) fn timeout_error_alias_call(checker: &mut Checker, func: &Expr) { |
| 180 | + if is_alias(func, checker.semantic(), checker.settings.target_version) { |
| 181 | + atom_diagnostic(checker, func); |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +/// UP041 |
| 186 | +pub(crate) fn timeout_error_alias_raise(checker: &mut Checker, expr: &Expr) { |
| 187 | + if matches!(expr, Expr::Name(_) | Expr::Attribute(_)) { |
| 188 | + if is_alias(expr, checker.semantic(), checker.settings.target_version) { |
| 189 | + atom_diagnostic(checker, expr); |
| 190 | + } |
| 191 | + } |
| 192 | +} |
0 commit comments