repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_length_return.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_length_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::terminal::Terminal; use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `__len__` implementations that return values that are not non-negative /// integers. /// /// ## Why is this bad? /// The `__len__` method should return a non-negative integer. Returning a different /// value may cause unexpected behavior. /// /// Note: `bool` is a subclass of `int`, so it's technically valid for `__len__` to /// return `True` or `False`. However, for consistency with other rules, Ruff will /// still emit a diagnostic when `__len__` returns a `bool`. /// /// ## Example /// ```python /// class Foo: /// def __len__(self): /// return "2" /// ``` /// /// Use instead: /// ```python /// class Foo: /// def __len__(self): /// return 2 /// ``` /// /// ## References /// - [Python documentation: The `__len__` method](https://docs.python.org/3/reference/datamodel.html#object.__len__) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.6.0")] pub(crate) struct InvalidLengthReturnType; impl Violation for InvalidLengthReturnType { #[derive_message_formats] fn message(&self) -> String { "`__len__` does not return a non-negative integer".to_string() } } /// PLE0303 pub(crate) fn invalid_length_return(checker: &Checker, function_def: &ast::StmtFunctionDef) { if function_def.name.as_str() != "__len__" { return; } if !checker.semantic().current_scope().kind.is_class() { return; } if is_stub(function_def, checker.semantic()) { return; } // Determine the terminal behavior (i.e., implicit return, no return, etc.). let terminal = Terminal::from_function(function_def); // If every control flow path raises an exception, ignore the function. if terminal == Terminal::Raise { return; } // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { checker.report_diagnostic(InvalidLengthReturnType, function_def.identifier()); return; } let returns = { let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(&function_def.body); visitor.returns }; for stmt in returns { if let Some(value) = stmt.value.as_deref() { if is_negative_integer(value) || !matches!( ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ) { checker.report_diagnostic(InvalidLengthReturnType, value.range()); } } else { // Disallow implicit `None`. checker.report_diagnostic(InvalidLengthReturnType, stmt.range()); } } } /// Returns `true` if the given expression is a negative integer. fn is_negative_integer(value: &Expr) -> bool { matches!( value, Expr::UnaryOp(ast::ExprUnaryOp { op: ast::UnaryOp::USub, .. }) ) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/magic_value_comparison.rs
crates/ruff_linter/src/rules/pylint/rules/magic_value_comparison.rs
use itertools::Itertools; use ruff_python_ast::{self as ast, Expr, Int, LiteralExpressionRef, UnaryOp}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::settings::ConstantType; /// ## What it does /// Checks for the use of unnamed numerical constants ("magic") values in /// comparisons. /// /// ## Why is this bad? /// The use of "magic" values can make code harder to read and maintain, as /// readers will have to infer the meaning of the value from the context. /// Such values are discouraged by [PEP 8]. /// /// For convenience, this rule excludes a variety of common values from the /// "magic" value definition, such as `0`, `1`, `""`, and `"__main__"`. /// /// ## Example /// ```python /// def apply_discount(price: float) -> float: /// if price <= 100: /// return price / 2 /// else: /// return price /// ``` /// /// Use instead: /// ```python /// MAX_DISCOUNT = 100 /// /// /// def apply_discount(price: float) -> float: /// if price <= MAX_DISCOUNT: /// return price / 2 /// else: /// return price /// ``` /// /// ## Options /// - `lint.pylint.allow-magic-value-types` /// /// [PEP 8]: https://peps.python.org/pep-0008/#constants #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.221")] pub(crate) struct MagicValueComparison { value: String, } impl Violation for MagicValueComparison { #[derive_message_formats] fn message(&self) -> String { let MagicValueComparison { value } = self; format!( "Magic value used in comparison, consider replacing `{value}` with a constant variable" ) } } /// If an [`Expr`] is a literal (or unary operation on a literal), return the [`LiteralExpressionRef`]. fn as_literal(expr: &Expr) -> Option<LiteralExpressionRef<'_>> { match expr { Expr::UnaryOp(ast::ExprUnaryOp { op: UnaryOp::UAdd | UnaryOp::USub | UnaryOp::Invert, operand, .. }) => operand.as_literal_expr(), _ => expr.as_literal_expr(), } } fn is_magic_value(literal_expr: LiteralExpressionRef, allowed_types: &[ConstantType]) -> bool { if let Some(constant_type) = ConstantType::try_from_literal_expr(literal_expr) { if allowed_types.contains(&constant_type) { return false; } } match literal_expr { // Ignore `None`, `Bool`, and `Ellipsis` constants. LiteralExpressionRef::NoneLiteral(_) | LiteralExpressionRef::BooleanLiteral(_) | LiteralExpressionRef::EllipsisLiteral(_) => false, // Special-case some common string and integer types. LiteralExpressionRef::StringLiteral(ast::ExprStringLiteral { value, .. }) => { !matches!(value.to_str(), "" | "__main__") } LiteralExpressionRef::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => match value { #[expect(clippy::float_cmp)] ast::Number::Float(value) => !(*value == 0.0 || *value == 1.0), ast::Number::Int(value) => !matches!(*value, Int::ZERO | Int::ONE), ast::Number::Complex { .. } => true, }, LiteralExpressionRef::BytesLiteral(_) => true, } } /// PLR2004 pub(crate) fn magic_value_comparison(checker: &Checker, left: &Expr, comparators: &[Expr]) { for (left, right) in std::iter::once(left).chain(comparators).tuple_windows() { // If both of the comparators are literals, skip rule for the whole expression. // R0133: comparison-of-constants if as_literal(left).is_some() && as_literal(right).is_some() { return; } } for comparison_expr in std::iter::once(left).chain(comparators) { if let Some(value) = as_literal(comparison_expr) { if is_magic_value(value, &checker.settings().pylint.allow_magic_value_types) { checker.report_diagnostic( MagicValueComparison { value: checker.locator().slice(comparison_expr).to_string(), }, comparison_expr.range(), ); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/useless_else_on_loop.rs
crates/ruff_linter/src/rules/pylint/rules/useless_else_on_loop.rs
use anyhow::Result; use ast::whitespace::indentation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier; use ruff_python_ast::{self as ast, ExceptHandler, MatchCase, Stmt}; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextRange}; use crate::Locator; use crate::checkers::ast::Checker; use crate::fix::edits::adjust_indentation; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for `else` clauses on loops without a `break` statement. /// /// ## Why is this bad? /// When a loop includes an `else` statement, the code inside the `else` clause /// will be executed if the loop terminates "normally" (i.e., without a /// `break`). /// /// If a loop _always_ terminates "normally" (i.e., does _not_ contain a /// `break`), then the `else` clause is redundant, as the code inside the /// `else` clause will always be executed. /// /// In such cases, the code inside the `else` clause can be moved outside the /// loop entirely, and the `else` clause can be removed. /// /// ## Example /// ```python /// for item in items: /// print(item) /// else: /// print("All items printed") /// ``` /// /// Use instead: /// ```python /// for item in items: /// print(item) /// print("All items printed") /// ``` /// /// ## References /// - [Python documentation: `break` and `continue` Statements, and `else` Clauses on Loops](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.156")] pub(crate) struct UselessElseOnLoop; impl Violation for UselessElseOnLoop { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "`else` clause on loop without a `break` statement; remove the `else` and dedent its contents".to_string() } fn fix_title(&self) -> Option<String> { Some("Remove `else`".to_string()) } } /// PLW0120 pub(crate) fn useless_else_on_loop(checker: &Checker, stmt: &Stmt, body: &[Stmt], orelse: &[Stmt]) { if orelse.is_empty() || loop_exits_early(body) { return; } let else_range = identifier::else_(stmt, checker.locator().contents()).expect("else clause"); let mut diagnostic = checker.report_diagnostic(UselessElseOnLoop, else_range); diagnostic.try_set_fix(|| { remove_else( stmt, orelse, else_range, checker.locator(), checker.indexer(), checker.stylist(), ) }); } /// Returns `true` if the given body contains a `break` statement. fn loop_exits_early(body: &[Stmt]) -> bool { body.iter().any(|stmt| match stmt { Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { loop_exits_early(body) || elif_else_clauses .iter() .any(|clause| loop_exits_early(&clause.body)) } Stmt::With(ast::StmtWith { body, .. }) => loop_exits_early(body), Stmt::Match(ast::StmtMatch { cases, .. }) => cases .iter() .any(|MatchCase { body, .. }| loop_exits_early(body)), Stmt::Try(ast::StmtTry { body, handlers, orelse, finalbody, .. }) => { loop_exits_early(body) || loop_exits_early(orelse) || loop_exits_early(finalbody) || handlers.iter().any(|handler| match handler { ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) => loop_exits_early(body), }) } Stmt::For(ast::StmtFor { orelse, .. }) | Stmt::While(ast::StmtWhile { orelse, .. }) => { loop_exits_early(orelse) } Stmt::Break(_) => true, _ => false, }) } /// Generate a [`Fix`] to remove the `else` clause from the given statement. fn remove_else( stmt: &Stmt, orelse: &[Stmt], else_range: TextRange, locator: &Locator, indexer: &Indexer, stylist: &Stylist, ) -> Result<Fix> { let Some(start) = orelse.first() else { return Err(anyhow::anyhow!("Empty `else` clause")); }; let Some(end) = orelse.last() else { return Err(anyhow::anyhow!("Empty `else` clause")); }; let start_indentation = indentation(locator.contents(), start); if start_indentation.is_none() { // Inline `else` block (e.g., `else: x = 1`). Ok(Fix::safe_edit(Edit::deletion( else_range.start(), start.start(), ))) } else { // Identify the indentation of the loop itself (e.g., the `while` or `for`). let Some(desired_indentation) = indentation(locator.contents(), stmt) else { return Err(anyhow::anyhow!("Compound statement cannot be inlined")); }; // Dedent the content from the end of the `else` to the end of the loop. let indented = adjust_indentation( TextRange::new( locator.full_line_end(else_range.start()), locator.full_line_end(end.end()), ), desired_indentation, locator, indexer, stylist, )?; // Replace the content from the start of the `else` to the end of the loop. Ok(Fix::safe_edit(Edit::replacement( indented, locator.line_start(else_range.start()), locator.full_line_end(end.end()), ))) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs
crates/ruff_linter/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs
use ruff_python_ast::Expr; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for unnecessary direct calls to lambda expressions. /// /// ## Why is this bad? /// Calling a lambda expression directly is unnecessary. The expression can be /// executed inline instead to improve readability. /// /// ## Example /// ```python /// area = (lambda r: 3.14 * r**2)(radius) /// ``` /// /// Use instead: /// ```python /// area = 3.14 * radius**2 /// ``` /// /// ## References /// - [Python documentation: Lambdas](https://docs.python.org/3/reference/expressions.html#lambda) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.153")] pub(crate) struct UnnecessaryDirectLambdaCall; impl Violation for UnnecessaryDirectLambdaCall { #[derive_message_formats] fn message(&self) -> String { "Lambda expression called directly. Execute the expression inline instead.".to_string() } } /// PLC3002 pub(crate) fn unnecessary_direct_lambda_call(checker: &Checker, expr: &Expr, func: &Expr) { if let Expr::Lambda(_) = func { checker.report_diagnostic(UnnecessaryDirectLambdaCall, expr.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_hash_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast}; use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::terminal::Terminal; use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `__hash__` implementations that return non-integer values. /// /// ## Why is this bad? /// The `__hash__` method should return an integer. Returning a different /// type may cause unexpected behavior. /// /// Note: `bool` is a subclass of `int`, so it's technically valid for `__hash__` to /// return `True` or `False`. However, for consistency with other rules, Ruff will /// still emit a diagnostic when `__hash__` returns a `bool`. /// /// ## Example /// ```python /// class Foo: /// def __hash__(self): /// return "2" /// ``` /// /// Use instead: /// ```python /// class Foo: /// def __hash__(self): /// return 2 /// ``` /// /// ## References /// - [Python documentation: The `__hash__` method](https://docs.python.org/3/reference/datamodel.html#object.__hash__) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.6.0")] pub(crate) struct InvalidHashReturnType; impl Violation for InvalidHashReturnType { #[derive_message_formats] fn message(&self) -> String { "`__hash__` does not return an integer".to_string() } } /// PLE0309 pub(crate) fn invalid_hash_return(checker: &Checker, function_def: &ast::StmtFunctionDef) { if function_def.name.as_str() != "__hash__" { return; } if !checker.semantic().current_scope().kind.is_class() { return; } if is_stub(function_def, checker.semantic()) { return; } // Determine the terminal behavior (i.e., implicit return, no return, etc.). let terminal = Terminal::from_function(function_def); // If every control flow path raises an exception, ignore the function. if terminal == Terminal::Raise { return; } // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { checker.report_diagnostic(InvalidHashReturnType, function_def.identifier()); return; } let returns = { let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(&function_def.body); visitor.returns }; for stmt in returns { if let Some(value) = stmt.value.as_deref() { if !matches!( ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ) { checker.report_diagnostic(InvalidHashReturnType, value.range()); } } else { // Disallow implicit `None`. checker.report_diagnostic(InvalidHashReturnType, stmt.range()); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for functions or methods with too many branches, including (nested) /// `if`, `elif`, and `else` branches, `for` loops, `try`-`except` clauses, and /// `match` and `case` statements. /// /// By default, this rule allows up to 12 branches. This can be configured /// using the [`lint.pylint.max-branches`] option. /// /// ## Why is this bad? /// Functions or methods with many branches are harder to understand /// and maintain than functions or methods with fewer branches. /// /// ## Example /// Given: /// ```python /// def capital(country): /// if country == "Australia": /// return "Canberra" /// elif country == "Brazil": /// return "Brasilia" /// elif country == "Canada": /// return "Ottawa" /// elif country == "England": /// return "London" /// elif country == "France": /// return "Paris" /// elif country == "Germany": /// return "Berlin" /// elif country == "Poland": /// return "Warsaw" /// elif country == "Romania": /// return "Bucharest" /// elif country == "Spain": /// return "Madrid" /// elif country == "Thailand": /// return "Bangkok" /// elif country == "Turkey": /// return "Ankara" /// elif country == "United States": /// return "Washington" /// else: /// return "Unknown" # 13th branch /// ``` /// /// Use instead: /// ```python /// def capital(country): /// capitals = { /// "Australia": "Canberra", /// "Brazil": "Brasilia", /// "Canada": "Ottawa", /// "England": "London", /// "France": "Paris", /// "Germany": "Berlin", /// "Poland": "Warsaw", /// "Romania": "Bucharest", /// "Spain": "Madrid", /// "Thailand": "Bangkok", /// "Turkey": "Ankara", /// "United States": "Washington", /// } /// city = capitals.get(country, "Unknown") /// return city /// ``` /// /// Given: /// ```python /// def grades_to_average_number(grades): /// numbers = [] /// for grade in grades: # 1st branch /// if len(grade) not in {1, 2}: /// raise ValueError(f"Invalid grade: {grade}") /// /// if len(grade) == 2 and grade[1] not in {"+", "-"}: /// raise ValueError(f"Invalid grade: {grade}") /// /// letter = grade[0] /// /// if letter in {"F", "E"}: /// number = 0.0 /// elif letter == "D": /// number = 1.0 /// elif letter == "C": /// number = 2.0 /// elif letter == "B": /// number = 3.0 /// elif letter == "A": /// number = 4.0 /// else: /// raise ValueError(f"Invalid grade: {grade}") /// /// modifier = 0.0 /// if letter != "F" and grade[-1] == "+": /// modifier = 0.3 /// elif letter != "F" and grade[-1] == "-": /// modifier = -0.3 /// /// numbers.append(max(0.0, min(number + modifier, 4.0))) /// /// try: /// return sum(numbers) / len(numbers) /// except ZeroDivisionError: # 13th branch /// return 0 /// ``` /// /// Use instead: /// ```python /// def grades_to_average_number(grades): /// grade_values = {"F": 0.0, "E": 0.0, "D": 1.0, "C": 2.0, "B": 3.0, "A": 4.0} /// modifier_values = {"+": 0.3, "-": -0.3} /// /// numbers = [] /// for grade in grades: /// if len(grade) not in {1, 2}: /// raise ValueError(f"Invalid grade: {grade}") /// /// letter = grade[0] /// if letter not in grade_values: /// raise ValueError(f"Invalid grade: {grade}") /// number = grade_values[letter] /// /// if len(grade) == 2 and grade[1] not in modifier_values: /// raise ValueError(f"Invalid grade: {grade}") /// modifier = modifier_values.get(grade[-1], 0.0) /// /// if letter == "F": /// numbers.append(0.0) /// else: /// numbers.append(max(0.0, min(number + modifier, 4.0))) /// /// try: /// return sum(numbers) / len(numbers) /// except ZeroDivisionError: /// return 0 /// ``` /// /// ## Options /// - `lint.pylint.max-branches` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.242")] pub(crate) struct TooManyBranches { branches: usize, max_branches: usize, } impl Violation for TooManyBranches { #[derive_message_formats] fn message(&self) -> String { let TooManyBranches { branches, max_branches, } = self; format!("Too many branches ({branches} > {max_branches})") } } fn num_branches(stmts: &[Stmt]) -> usize { stmts .iter() .map(|stmt| match stmt { Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { 1 + num_branches(body) + elif_else_clauses.len() + elif_else_clauses .iter() .map(|clause| num_branches(&clause.body)) .sum::<usize>() } Stmt::Match(ast::StmtMatch { cases, .. }) => { cases.len() + cases .iter() .map(|case| num_branches(&case.body)) .sum::<usize>() } // The `with` statement is not considered a branch but the statements inside the `with` should be counted. Stmt::With(ast::StmtWith { body, .. }) => num_branches(body), Stmt::For(ast::StmtFor { body, orelse, .. }) | Stmt::While(ast::StmtWhile { body, orelse, .. }) => { 1 + num_branches(body) + (if orelse.is_empty() { 0 } else { 1 + num_branches(orelse) }) } Stmt::Try(ast::StmtTry { body, handlers, orelse, finalbody, .. }) => { // Count each `except` clause as a branch; the `else` and `finally` clauses also // count, but the `try` clause itself does not. num_branches(body) + (if orelse.is_empty() { 0 } else { 1 + num_branches(orelse) }) + (if finalbody.is_empty() { 0 } else { 1 + num_branches(finalbody) }) + handlers .iter() .map(|handler| { 1 + { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler; num_branches(body) } }) .sum::<usize>() } _ => 0, }) .sum() } /// PLR0912 pub(crate) fn too_many_branches( checker: &Checker, stmt: &Stmt, body: &[Stmt], max_branches: usize, ) { let branches = num_branches(body); if branches > max_branches { checker.report_diagnostic( TooManyBranches { branches, max_branches, }, stmt.identifier(), ); } } #[cfg(test)] mod tests { use anyhow::Result; use ruff_python_parser::parse_module; use super::num_branches; fn test_helper(source: &str, expected_num_branches: usize) -> Result<()> { let parsed = parse_module(source)?; assert_eq!(num_branches(parsed.suite()), expected_num_branches); Ok(()) } #[test] fn if_else_nested_if_else() -> Result<()> { let source: &str = r" if x == 0: # 3 return else: if x == 1: pass else: pass "; test_helper(source, 4)?; Ok(()) } #[test] fn match_case() -> Result<()> { let source: &str = r" match x: # 2 case 0: pass case 1: pass "; test_helper(source, 2)?; Ok(()) } #[test] fn for_else() -> Result<()> { let source: &str = r" for _ in range(x): # 2 pass else: pass "; test_helper(source, 2)?; Ok(()) } #[test] fn while_if_else_if() -> Result<()> { let source: &str = r" while x < 1: # 4 if x: pass else: if x: pass "; test_helper(source, 4)?; Ok(()) } #[test] fn nested_def() -> Result<()> { let source: &str = r" if x: # 2 pass else: pass def g(x): if x: pass return 1 "; test_helper(source, 2)?; Ok(()) } #[test] fn try_except() -> Result<()> { let source: &str = r" try: pass except: pass "; test_helper(source, 1)?; Ok(()) } #[test] fn try_except_else() -> Result<()> { let source: &str = r" try: pass except: pass else: pass "; test_helper(source, 2)?; Ok(()) } #[test] fn try_finally() -> Result<()> { let source: &str = r" try: pass finally: pass "; test_helper(source, 1)?; Ok(()) } #[test] fn try_except_except_else_finally() -> Result<()> { let source: &str = r" try: pass except: pass except: pass else: pass finally: pass "; test_helper(source, 4)?; Ok(()) } #[test] fn with_statement() -> Result<()> { let source: &str = r" with suppress(Exception): if x == 0: # 2 return else: return "; test_helper(source, 2)?; Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_string_characters.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_string_characters.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::token::{Token, TokenKind}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use crate::Locator; use crate::checkers::ast::LintContext; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for strings that contain the control character `BS`. /// /// ## Why is this bad? /// Control characters are displayed differently by different text editors and /// terminals. /// /// By using the `\b` sequence in lieu of the `BS` control character, the /// string will contain the same value, but will render visibly in all editors. /// /// ## Example /// ```python /// x = "" /// ``` /// /// Use instead: /// ```python /// x = "\b" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct InvalidCharacterBackspace; impl Violation for InvalidCharacterBackspace { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Invalid unescaped character backspace, use \"\\b\" instead".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with escape sequence".to_string()) } } /// ## What it does /// Checks for strings that contain the raw control character `SUB`. /// /// ## Why is this bad? /// Control characters are displayed differently by different text editors and /// terminals. /// /// By using the `\x1a` sequence in lieu of the `SUB` control character, the /// string will contain the same value, but will render visibly in all editors. /// /// ## Example /// ```python /// x = "" /// ``` /// /// Use instead: /// ```python /// x = "\x1a" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct InvalidCharacterSub; impl Violation for InvalidCharacterSub { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Invalid unescaped character SUB, use \"\\x1a\" instead".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with escape sequence".to_string()) } } /// ## What it does /// Checks for strings that contain the raw control character `ESC`. /// /// ## Why is this bad? /// Control characters are displayed differently by different text editors and /// terminals. /// /// By using the `\x1b` sequence in lieu of the `ESC` control character, the /// string will contain the same value, but will render visibly in all editors. /// /// ## Example /// ```python /// x = "" /// ``` /// /// Use instead: /// ```python /// x = "\x1b" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct InvalidCharacterEsc; impl Violation for InvalidCharacterEsc { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Invalid unescaped character ESC, use \"\\x1b\" instead".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with escape sequence".to_string()) } } /// ## What it does /// Checks for strings that contain the raw control character `NUL` (0 byte). /// /// ## Why is this bad? /// Control characters are displayed differently by different text editors and /// terminals. /// /// By using the `\0` sequence in lieu of the `NUL` control character, the /// string will contain the same value, but will render visibly in all editors. /// /// ## Example /// ```python /// x = "" /// ``` /// /// Use instead: /// ```python /// x = "\0" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct InvalidCharacterNul; impl Violation for InvalidCharacterNul { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Invalid unescaped character NUL, use \"\\0\" instead".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with escape sequence".to_string()) } } /// ## What it does /// Checks for strings that contain the zero width space character. /// /// ## Why is this bad? /// This character is rendered invisibly in some text editors and terminals. /// /// By using the `\u200B` sequence, the string will contain the same value, /// but will render visibly in all editors. /// /// ## Example /// ```python /// x = "Dear Sir/Madam" /// ``` /// /// Use instead: /// ```python /// x = "Dear Sir\u200b/\u200bMadam" # zero width space /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct InvalidCharacterZeroWidthSpace; impl Violation for InvalidCharacterZeroWidthSpace { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Invalid unescaped character zero-width-space, use \"\\u200B\" instead".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with escape sequence".to_string()) } } /// PLE2510, PLE2512, PLE2513, PLE2514, PLE2515 pub(crate) fn invalid_string_characters(context: &LintContext, token: &Token, locator: &Locator) { let text = match token.kind() { // We can't use the `value` field since it's decoded and e.g. for f-strings removed a curly // brace that escaped another curly brace, which would gives us wrong column information. TokenKind::String | TokenKind::FStringMiddle | TokenKind::TStringMiddle => { locator.slice(token) } _ => return, }; for (column, match_) in text.match_indices(&['\x08', '\x1a', '\x1b', '\0', '\u{200b}']) { let location = token.start() + TextSize::try_from(column).unwrap(); let c = match_.chars().next().unwrap(); let range = TextRange::at(location, c.text_len()); let is_escaped = &text[..column] .chars() .rev() .take_while(|c| *c == '\\') .count() % 2 == 1; let (replacement, diagnostic) = match c { '\x08' => ( "\\b", context.report_diagnostic_if_enabled(InvalidCharacterBackspace, range), ), '\x1a' => ( "\\x1a", context.report_diagnostic_if_enabled(InvalidCharacterSub, range), ), '\x1b' => ( "\\x1b", context.report_diagnostic_if_enabled(InvalidCharacterEsc, range), ), '\0' => ( "\\0", context.report_diagnostic_if_enabled(InvalidCharacterNul, range), ), '\u{200b}' => ( "\\u200b", context.report_diagnostic_if_enabled(InvalidCharacterZeroWidthSpace, range), ), _ => { continue; } }; let Some(mut diagnostic) = diagnostic else { continue; }; if !token.unwrap_string_flags().is_raw_string() && !is_escaped { let edit = Edit::range_replacement(replacement.to_string(), range); diagnostic.set_fix(Fix::safe_edit(edit)); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_nested_blocks.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_nested_blocks.rs
use ast::ExceptHandler; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Stmt}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for functions or methods with too many nested blocks. /// /// By default, this rule allows up to five nested blocks. /// This can be configured using the [`lint.pylint.max-nested-blocks`] option. /// /// ## Why is this bad? /// Functions or methods with too many nested blocks are harder to understand /// and maintain. /// /// ## Options /// - `lint.pylint.max-nested-blocks` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.15")] pub(crate) struct TooManyNestedBlocks { nested_blocks: usize, max_nested_blocks: usize, } impl Violation for TooManyNestedBlocks { #[derive_message_formats] fn message(&self) -> String { let TooManyNestedBlocks { nested_blocks, max_nested_blocks, } = self; format!("Too many nested blocks ({nested_blocks} > {max_nested_blocks})") } } /// PLR1702 pub(crate) fn too_many_nested_blocks(checker: &Checker, stmt: &Stmt) { // Only enforce nesting within functions or methods. if !checker.semantic().current_scope().kind.is_function() { return; } // If the statement isn't a leaf node, we don't want to emit a diagnostic, since the diagnostic // will be emitted on the leaves. if has_nested_block(stmt) { return; } let max_nested_blocks = checker.settings().pylint.max_nested_blocks; // Traverse up the hierarchy, identifying the root node and counting the number of nested // blocks between the root and this leaf. let (count, root_id) = checker .semantic() .current_statement_ids() .fold((0, None), |(count, ancestor_id), id| { let stmt = checker.semantic().statement(id); if is_nested_block(stmt) { (count + 1, Some(id)) } else { (count, ancestor_id) } }); let Some(root_id) = root_id else { return; }; // If the number of nested blocks is less than the maximum, we don't want to emit a diagnostic. if count <= max_nested_blocks { return; } checker.report_diagnostic( TooManyNestedBlocks { nested_blocks: count, max_nested_blocks, }, checker.semantic().statement(root_id).range(), ); } /// Returns `true` if the given statement is a nested block. fn is_nested_block(stmt: &Stmt) -> bool { matches!( stmt, Stmt::If(_) | Stmt::While(_) | Stmt::For(_) | Stmt::Try(_) | Stmt::With(_) ) } /// Returns `true` if the given statement is a leaf node. fn has_nested_block(stmt: &Stmt) -> bool { match stmt { Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { body.iter().any(is_nested_block) || elif_else_clauses .iter() .any(|elif_else| elif_else.body.iter().any(is_nested_block)) } Stmt::While(ast::StmtWhile { body, orelse, .. }) => { body.iter().any(is_nested_block) || orelse.iter().any(is_nested_block) } Stmt::For(ast::StmtFor { body, orelse, .. }) => { body.iter().any(is_nested_block) || orelse.iter().any(is_nested_block) } Stmt::Try(ast::StmtTry { body, handlers, orelse, finalbody, .. }) => { body.iter().any(is_nested_block) || handlers.iter().any(|handler| match handler { ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) => body.iter().any(is_nested_block), }) || orelse.iter().any(is_nested_block) || finalbody.iter().any(is_nested_block) } Stmt::With(ast::StmtWith { body, .. }) => body.iter().any(is_nested_block), _ => false, } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/stop_iteration_return.rs
crates/ruff_linter/src/rules/pylint/rules/stop_iteration_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ self as ast, helpers::map_callable, visitor::{Visitor, walk_expr, walk_stmt}, }; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for explicit `raise StopIteration` in generator functions. /// /// ## Why is this bad? /// Raising `StopIteration` in a generator function causes a `RuntimeError` /// when the generator is iterated over. /// /// Instead of `raise StopIteration`, use `return` in generator functions. /// /// ## Example /// ```python /// def my_generator(): /// yield 1 /// yield 2 /// raise StopIteration # This causes RuntimeError at runtime /// ``` /// /// Use instead: /// ```python /// def my_generator(): /// yield 1 /// yield 2 /// return # Use return instead /// ``` /// /// ## References /// - [PEP 479](https://peps.python.org/pep-0479/) /// - [Python documentation](https://docs.python.org/3/library/exceptions.html#StopIteration) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.14.3")] pub(crate) struct StopIterationReturn; impl Violation for StopIterationReturn { #[derive_message_formats] fn message(&self) -> String { "Explicit `raise StopIteration` in generator".to_string() } fn fix_title(&self) -> Option<String> { Some("Use `return` instead".to_string()) } } /// PLR1708 pub(crate) fn stop_iteration_return(checker: &Checker, function_def: &ast::StmtFunctionDef) { let mut analyzer = GeneratorAnalyzer { checker, has_yield: false, stop_iteration_raises: Vec::new(), }; analyzer.visit_body(&function_def.body); if analyzer.has_yield { for raise_stmt in analyzer.stop_iteration_raises { checker.report_diagnostic(StopIterationReturn, raise_stmt.range()); } } } struct GeneratorAnalyzer<'a, 'b> { checker: &'a Checker<'b>, has_yield: bool, stop_iteration_raises: Vec<&'a ast::StmtRaise>, } impl<'a> Visitor<'a> for GeneratorAnalyzer<'a, '_> { fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { match stmt { ast::Stmt::FunctionDef(_) => {} ast::Stmt::Raise(raise @ ast::StmtRaise { exc: Some(exc), .. }) => { if self .checker .semantic() .match_builtin_expr(map_callable(exc), "StopIteration") { self.stop_iteration_raises.push(raise); } walk_stmt(self, stmt); } _ => walk_stmt(self, stmt), } } fn visit_expr(&mut self, expr: &'a ast::Expr) { match expr { ast::Expr::Lambda(_) => {} ast::Expr::Yield(_) | ast::Expr::YieldFrom(_) => { self.has_yield = true; walk_expr(self, expr); } _ => walk_expr(self, expr), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs
crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::is_known_dunder_method; /// ## What it does /// Checks for dunder methods that have no special meaning in Python 3. /// /// ## Why is this bad? /// Misspelled or no longer supported dunder name methods may cause your code to not function /// as expected. /// /// Since dunder methods are associated with customizing the behavior /// of a class in Python, introducing a dunder method such as `__foo__` /// that diverges from standard Python dunder methods could potentially /// confuse someone reading the code. /// /// This rule will detect all methods starting and ending with at least /// one underscore (e.g., `_str_`), but ignores known dunder methods (like /// `__init__`), as well as methods that are marked with [`@override`][override]. /// /// Additional dunder methods names can be allowed via the /// [`lint.pylint.allow-dunder-method-names`] setting. /// /// ## Example /// /// ```python /// class Foo: /// def __init_(self): ... /// ``` /// /// Use instead: /// /// ```python /// class Foo: /// def __init__(self): ... /// ``` /// /// ## Options /// - `lint.pylint.allow-dunder-method-names` /// /// [override]: https://docs.python.org/3/library/typing.html#typing.override #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.0.285")] pub(crate) struct BadDunderMethodName { name: String, } impl Violation for BadDunderMethodName { #[derive_message_formats] fn message(&self) -> String { let BadDunderMethodName { name } = self; format!("Dunder method `{name}` has no special meaning in Python 3") } } /// PLW3201 pub(crate) fn bad_dunder_method_name(checker: &Checker, method: &ast::StmtFunctionDef) { // https://github.com/astral-sh/ruff/issues/14535 if checker.source_type.is_stub() { return; } // If the name isn't a dunder, skip it. if !method.name.starts_with('_') || !method.name.ends_with('_') { return; } // If the name is explicitly allowed, skip it. if is_known_dunder_method(&method.name) || checker .settings() .pylint .allow_dunder_method_names .contains(method.name.as_str()) || matches!(method.name.as_str(), "_") { return; } if visibility::is_override(&method.decorator_list, checker.semantic()) { return; } checker.report_diagnostic( BadDunderMethodName { name: method.name.to_string(), }, method.identifier(), ); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_statements.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::{self as ast, ExceptHandler, Stmt}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for functions or methods with too many statements. /// /// By default, this rule allows up to 50 statements, as configured by the /// [`lint.pylint.max-statements`] option. /// /// ## Why is this bad? /// Functions or methods with many statements are harder to understand /// and maintain. /// /// Instead, consider refactoring the function or method into smaller /// functions or methods, or identifying generalizable patterns and /// replacing them with generic logic or abstractions. /// /// ## Example /// ```python /// def is_even(number: int) -> bool: /// if number == 0: /// return True /// elif number == 1: /// return False /// elif number == 2: /// return True /// elif number == 3: /// return False /// elif number == 4: /// return True /// elif number == 5: /// return False /// else: /// ... /// ``` /// /// Use instead: /// ```python /// def is_even(number: int) -> bool: /// return number % 2 == 0 /// ``` /// /// ## Options /// - `lint.pylint.max-statements` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.240")] pub(crate) struct TooManyStatements { statements: usize, max_statements: usize, } impl Violation for TooManyStatements { #[derive_message_formats] fn message(&self) -> String { let TooManyStatements { statements, max_statements, } = self; format!("Too many statements ({statements} > {max_statements})") } } fn num_statements(stmts: &[Stmt]) -> usize { let mut count = 0; for stmt in stmts { match stmt { Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { count += 1; count += num_statements(body); for clause in elif_else_clauses { count += 1; count += num_statements(&clause.body); } } Stmt::For(ast::StmtFor { body, orelse, .. }) => { count += num_statements(body); count += num_statements(orelse); } Stmt::While(ast::StmtWhile { body, orelse, .. }) => { count += 1; count += num_statements(body); count += num_statements(orelse); } Stmt::Match(ast::StmtMatch { cases, .. }) => { count += 1; for case in cases { count += 1; count += num_statements(&case.body); } } Stmt::Try(ast::StmtTry { body, handlers, orelse, finalbody, .. }) => { count += 1; count += num_statements(body); if !orelse.is_empty() { count += 1 + num_statements(orelse); } if !finalbody.is_empty() { // Unclear why, but follow Pylint's convention. count += 2 + num_statements(finalbody); } if handlers.len() > 1 { count += 1; } for handler in handlers { count += 1; let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler; count += num_statements(body); } } Stmt::FunctionDef(ast::StmtFunctionDef { body, .. }) | Stmt::With(ast::StmtWith { body, .. }) => { count += 1; count += num_statements(body); } Stmt::Return(_) => {} _ => { count += 1; } } } count } /// PLR0915 pub(crate) fn too_many_statements( checker: &Checker, stmt: &Stmt, body: &[Stmt], max_statements: usize, ) { let statements = num_statements(body); if statements > max_statements { checker.report_diagnostic( TooManyStatements { statements, max_statements, }, stmt.identifier(), ); } } #[cfg(test)] mod tests { use anyhow::Result; use ruff_python_ast::Suite; use ruff_python_parser::parse_module; use super::num_statements; fn parse_suite(source: &str) -> Result<Suite> { Ok(parse_module(source)?.into_suite()) } #[test] fn pass() -> Result<()> { let source: &str = r" def f(): pass "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 2); Ok(()) } #[test] fn if_else() -> Result<()> { let source: &str = r" def f(): if a: print() else: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 5); Ok(()) } #[test] fn if_else_if_corner() -> Result<()> { let source: &str = r" def f(): if a: print() else: if a: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 6); Ok(()) } #[test] fn if_elif() -> Result<()> { let source: &str = r" def f(): if a: print() elif a: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 5); Ok(()) } #[test] fn if_elif_else() -> Result<()> { let source: &str = r" def f(): if a: print() elif a == 2: print() elif a == 3: print() else: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 9); Ok(()) } #[test] fn match_case() -> Result<()> { let source: &str = r" def f(): match x: case 3: pass case _: pass "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 6); Ok(()) } #[test] fn many_statements() -> Result<()> { let source: &str = r" async def f(): a = 1 b = 2 c = 3 await some_other_func() if a == 1: print('hello') else: other_func() count = 1 while True: count += 1 if count > 20: break; with open(f): with open(e): a -= 1 import time pass "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 19); Ok(()) } #[test] fn for_() -> Result<()> { let source: &str = r" def f(): for i in range(10): pass "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 2); Ok(()) } #[test] fn for_else() -> Result<()> { let source: &str = r" def f(): for i in range(10): print() else: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 3); Ok(()) } #[test] fn nested_def() -> Result<()> { let source: &str = r" def f(): def g(): print() print() print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 5); Ok(()) } #[test] fn nested_class() -> Result<()> { let source: &str = r" def f(): class A: def __init__(self): pass def f(self): pass print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 3); Ok(()) } #[test] fn return_not_counted() -> Result<()> { let source: &str = r" def f(): return "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 1); Ok(()) } #[test] fn with() -> Result<()> { let source: &str = r" def f(): with a: if a: print() else: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 6); Ok(()) } #[test] fn try_except() -> Result<()> { let source: &str = r" def f(): try: print() except Exception: raise "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 5); Ok(()) } #[test] fn try_except_else() -> Result<()> { let source: &str = r" def f(): try: print() except ValueError: pass else: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 7); Ok(()) } #[test] fn try_except_else_finally() -> Result<()> { let source: &str = r" def f(): try: print() except ValueError: pass else: print() finally: pass "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 10); Ok(()) } #[test] fn try_except_except() -> Result<()> { let source: &str = r" def f(): try: print() except ValueError: pass except Exception: raise "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 8); Ok(()) } #[test] fn try_except_except_finally() -> Result<()> { let source: &str = r" def f(): try: print() except: pass except: pass finally: print() "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 11); Ok(()) } #[test] fn yield_() -> Result<()> { let source: &str = r" def f(): for i in range(10): yield i "; let stmts = parse_suite(source)?; assert_eq!(num_statements(&stmts), 2); Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/useless_with_lock.rs
crates/ruff_linter/src/rules/pylint/rules/useless_with_lock.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for lock objects that are created and immediately discarded in /// `with` statements. /// /// ## Why is this bad? /// Creating a lock (via `threading.Lock` or similar) in a `with` statement /// has no effect, as locks are only relevant when shared between threads. /// /// Instead, assign the lock to a variable outside the `with` statement, /// and share that variable between threads. /// /// ## Example /// ```python /// import threading /// /// counter = 0 /// /// /// def increment(): /// global counter /// /// with threading.Lock(): /// counter += 1 /// ``` /// /// Use instead: /// ```python /// import threading /// /// counter = 0 /// lock = threading.Lock() /// /// /// def increment(): /// global counter /// /// with lock: /// counter += 1 /// ``` /// /// ## References /// - [Python documentation: `Lock Objects`](https://docs.python.org/3/library/threading.html#lock-objects) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct UselessWithLock; impl Violation for UselessWithLock { #[derive_message_formats] fn message(&self) -> String { "Threading lock directly created in `with` statement has no effect".to_string() } } /// PLW2101 pub(crate) fn useless_with_lock(checker: &Checker, with: &ast::StmtWith) { for item in &with.items { let Some(call) = item.context_expr.as_call_expr() else { continue; }; if !checker .semantic() .resolve_qualified_name(call.func.as_ref()) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), [ "threading", "Lock" | "RLock" | "Condition" | "Semaphore" | "BoundedSemaphore" ] ) }) { return; } checker.report_diagnostic(UselessWithLock, call.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dunder_call.rs
crates/ruff_linter/src/rules/pylint/rules/unnecessary_dunder_call.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, OperatorPrecedence, Stmt}; use ruff_python_semantic::SemanticModel; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits; use crate::rules::pylint::helpers::is_known_dunder_method; use crate::{Edit, Fix, FixAvailability, Violation}; use ruff_python_ast::PythonVersion; /// ## What it does /// Checks for explicit use of dunder methods, like `__str__` and `__add__`. /// /// ## Why is this bad? /// Dunder names are not meant to be called explicitly and, in most cases, can /// be replaced with builtins or operators. /// /// ## Fix safety /// This fix is always unsafe. When replacing dunder method calls with operators /// or builtins, the behavior can change in the following ways: /// /// 1. Types may implement only a subset of related dunder methods. Calling a /// missing dunder method directly returns `NotImplemented`, but using the /// equivalent operator raises a `TypeError`. /// ```python /// class C: pass /// c = C() /// c.__gt__(1) # before fix: NotImplemented /// c > 1 # after fix: raises TypeError /// ``` /// 2. Instance-assigned dunder methods are ignored by operators and builtins. /// ```python /// class C: pass /// c = C() /// c.__bool__ = lambda: False /// c.__bool__() # before fix: False /// bool(c) # after fix: True /// ``` /// /// 3. Even with built-in types, behavior can differ. /// ```python /// (1).__gt__(1.0) # before fix: NotImplemented /// 1 > 1.0 # after fix: False /// ``` /// /// ## Example /// ```python /// three = (3.0).__str__() /// twelve = "1".__add__("2") /// /// /// def is_greater_than_two(x: int) -> bool: /// return x.__gt__(2) /// ``` /// /// Use instead: /// ```python /// three = str(3.0) /// twelve = "1" + "2" /// /// /// def is_greater_than_two(x: int) -> bool: /// return x > 2 /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct UnnecessaryDunderCall { method: String, replacement: Option<String>, } impl Violation for UnnecessaryDunderCall { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { let UnnecessaryDunderCall { method, replacement, } = self; if let Some(replacement) = replacement { format!("Unnecessary dunder call to `{method}`. {replacement}.") } else { format!("Unnecessary dunder call to `{method}`") } } fn fix_title(&self) -> Option<String> { let UnnecessaryDunderCall { replacement, .. } = self; replacement.clone() } } /// PLC2801 pub(crate) fn unnecessary_dunder_call(checker: &Checker, call: &ast::ExprCall) { let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = call.func.as_ref() else { return; }; // If this isn't a known dunder method, abort. if !is_known_dunder_method(attr) { return; } // If this is an allowed dunder method, abort. if allowed_dunder_constants(attr, checker.target_version()) { return; } // Ignore certain dunder method calls in lambda expressions. These methods would require // rewriting as a statement, which is not possible in a lambda expression. if allow_nested_expression(attr, checker.semantic()) { return; } // Ignore dunder method calls within dunder methods definitions. if in_dunder_method_definition(checker.semantic()) { return; } // Ignore dunder methods used on `super`. if let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() { if checker.semantic().has_builtin_binding("super") { if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() { if id == "super" { return; } } } } // If the call has keywords, abort. if !call.arguments.keywords.is_empty() { return; } // If a fix is available, we'll store the text of the fixed expression here // along with the precedence of the resulting expression. let mut fixed: Option<(String, OperatorPrecedence)> = None; let mut title: Option<String> = None; if let Some(dunder) = DunderReplacement::from_method(attr) { match (&*call.arguments.args, dunder) { ([], DunderReplacement::Builtin(replacement, message)) => { if !checker.semantic().has_builtin_binding(replacement) { return; } fixed = Some(( format!( "{}({})", replacement, checker.locator().slice(value.as_ref()), ), OperatorPrecedence::CallAttribute, )); title = Some(message.to_string()); } ([arg], DunderReplacement::Operator(replacement, message, precedence)) => { let value_slice = checker.locator().slice(value.as_ref()); let arg_slice = checker.locator().slice(arg); if OperatorPrecedence::from_expr(arg) > precedence { // if it's something that can reasonably be removed from parentheses, // we'll do that. fixed = Some(( format!("{value_slice} {replacement} {arg_slice}"), precedence, )); } else { fixed = Some(( format!("{value_slice} {replacement} ({arg_slice})"), precedence, )); } title = Some(message.to_string()); } ([arg], DunderReplacement::ROperator(replacement, message, precedence)) => { let value_slice = checker.locator().slice(value.as_ref()); let arg_slice = checker.locator().slice(arg); if OperatorPrecedence::from_expr(arg) > precedence { // if it's something that can reasonably be removed from parentheses, // we'll do that. fixed = Some(( format!("{arg_slice} {replacement} {value_slice}"), precedence, )); } else { fixed = Some(( format!("({arg_slice}) {replacement} {value_slice}"), precedence, )); } title = Some(message.to_string()); } (_, DunderReplacement::MessageOnly(message)) => { title = Some(message.to_string()); } _ => {} } } let mut diagnostic = checker.report_diagnostic( UnnecessaryDunderCall { method: attr.to_string(), replacement: title, }, call.range(), ); if let Some((mut fixed, precedence)) = fixed { let dunder = DunderReplacement::from_method(attr); // We never need to wrap builtin functions in extra parens // since function calls have high precedence let wrap_in_paren = (!matches!(dunder, Some(DunderReplacement::Builtin(_,_)))) // If parent expression has higher precedence then the new replacement, // it would associate with either the left operand (e.g. naive change from `a * b.__add__(c)` // becomes `a * b + c` which is incorrect) or the right operand (e.g. naive change from // `a.__add__(b).attr` becomes `a + b.attr` which is also incorrect). // This rule doesn't apply to function calls despite them having higher // precedence than any of our replacement, since they already wrap around // our expression e.g. `print(a.__add__(3))` -> `print(a + 3)` && checker .semantic() .current_expression_parent() .is_some_and(|parent| !parent.is_call_expr() && OperatorPrecedence::from_expr(parent) > precedence); if wrap_in_paren { fixed = format!("({fixed})"); } diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( edits::pad(fixed, call.range(), checker.locator()), call.range(), ))); } } /// Return `true` if this is a dunder method that is allowed to be called explicitly. fn allowed_dunder_constants(dunder_method: &str, target_version: PythonVersion) -> bool { if matches!( dunder_method, "__aexit__" | "__await__" | "__class__" | "__class_getitem__" | "__delete__" | "__dict__" | "__doc__" | "__exit__" | "__get__" | "__getnewargs__" | "__getnewargs_ex__" | "__getstate__" | "__index__" | "__init_subclass__" | "__missing__" | "__module__" | "__new__" | "__post_init__" | "__reduce__" | "__reduce_ex__" | "__set__" | "__set_name__" | "__setstate__" | "__sizeof__" | "__subclasses__" | "__subclasshook__" | "__weakref__" ) { return true; } if target_version < PythonVersion::PY310 && matches!(dunder_method, "__aiter__" | "__anext__") { return true; } false } #[derive(Debug, Copy, Clone)] enum DunderReplacement { /// A dunder method that is an operator. Operator(&'static str, &'static str, OperatorPrecedence), /// A dunder method that is a right-side operator. ROperator(&'static str, &'static str, OperatorPrecedence), /// A dunder method that is a builtin. Builtin(&'static str, &'static str), /// A dunder method that is a message only. MessageOnly(&'static str), } impl DunderReplacement { fn from_method(dunder_method: &str) -> Option<Self> { match dunder_method { "__add__" => Some(Self::Operator( "+", "Use `+` operator", OperatorPrecedence::AddSub, )), "__and__" => Some(Self::Operator( "&", "Use `&` operator", OperatorPrecedence::BitAnd, )), "__contains__" => Some(Self::ROperator( "in", "Use `in` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__eq__" => Some(Self::Operator( "==", "Use `==` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__floordiv__" => Some(Self::Operator( "//", "Use `//` operator", OperatorPrecedence::MulDivRemain, )), "__ge__" => Some(Self::Operator( ">=", "Use `>=` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__gt__" => Some(Self::Operator( ">", "Use `>` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__iadd__" => Some(Self::Operator( "+=", "Use `+=` operator", OperatorPrecedence::Assign, )), "__iand__" => Some(Self::Operator( "&=", "Use `&=` operator", OperatorPrecedence::Assign, )), "__ifloordiv__" => Some(Self::Operator( "//=", "Use `//=` operator", OperatorPrecedence::Assign, )), "__ilshift__" => Some(Self::Operator( "<<=", "Use `<<=` operator", OperatorPrecedence::Assign, )), "__imod__" => Some(Self::Operator( "%=", "Use `%=` operator", OperatorPrecedence::Assign, )), "__imul__" => Some(Self::Operator( "*=", "Use `*=` operator", OperatorPrecedence::Assign, )), "__ior__" => Some(Self::Operator( "|=", "Use `|=` operator", OperatorPrecedence::Assign, )), "__ipow__" => Some(Self::Operator( "**=", "Use `**=` operator", OperatorPrecedence::Assign, )), "__irshift__" => Some(Self::Operator( ">>=", "Use `>>=` operator", OperatorPrecedence::Assign, )), "__isub__" => Some(Self::Operator( "-=", "Use `-=` operator", OperatorPrecedence::Assign, )), "__itruediv__" => Some(Self::Operator( "/=", "Use `/=` operator", OperatorPrecedence::Assign, )), "__ixor__" => Some(Self::Operator( "^=", "Use `^=` operator", OperatorPrecedence::Assign, )), "__le__" => Some(Self::Operator( "<=", "Use `<=` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__lshift__" => Some(Self::Operator( "<<", "Use `<<` operator", OperatorPrecedence::LeftRightShift, )), "__lt__" => Some(Self::Operator( "<", "Use `<` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__mod__" => Some(Self::Operator( "%", "Use `%` operator", OperatorPrecedence::MulDivRemain, )), "__mul__" => Some(Self::Operator( "*", "Use `*` operator", OperatorPrecedence::MulDivRemain, )), "__ne__" => Some(Self::Operator( "!=", "Use `!=` operator", OperatorPrecedence::ComparisonsMembershipIdentity, )), "__or__" => Some(Self::Operator( "|", "Use `|` operator", OperatorPrecedence::BitOr, )), "__rshift__" => Some(Self::Operator( ">>", "Use `>>` operator", OperatorPrecedence::LeftRightShift, )), "__sub__" => Some(Self::Operator( "-", "Use `-` operator", OperatorPrecedence::AddSub, )), "__truediv__" => Some(Self::Operator( "/", "Use `/` operator", OperatorPrecedence::MulDivRemain, )), "__xor__" => Some(Self::Operator( "^", "Use `^` operator", OperatorPrecedence::BitXor, )), "__radd__" => Some(Self::ROperator( "+", "Use `+` operator", OperatorPrecedence::AddSub, )), "__rand__" => Some(Self::ROperator( "&", "Use `&` operator", OperatorPrecedence::BitAnd, )), "__rfloordiv__" => Some(Self::ROperator( "//", "Use `//` operator", OperatorPrecedence::MulDivRemain, )), "__rlshift__" => Some(Self::ROperator( "<<", "Use `<<` operator", OperatorPrecedence::LeftRightShift, )), "__rmod__" => Some(Self::ROperator( "%", "Use `%` operator", OperatorPrecedence::MulDivRemain, )), "__rmul__" => Some(Self::ROperator( "*", "Use `*` operator", OperatorPrecedence::MulDivRemain, )), "__ror__" => Some(Self::ROperator( "|", "Use `|` operator", OperatorPrecedence::BitOr, )), "__rrshift__" => Some(Self::ROperator( ">>", "Use `>>` operator", OperatorPrecedence::LeftRightShift, )), "__rsub__" => Some(Self::ROperator( "-", "Use `-` operator", OperatorPrecedence::AddSub, )), "__rtruediv__" => Some(Self::ROperator( "/", "Use `/` operator", OperatorPrecedence::MulDivRemain, )), "__rxor__" => Some(Self::ROperator( "^", "Use `^` operator", OperatorPrecedence::BitXor, )), "__aiter__" => Some(Self::Builtin("aiter", "Use `aiter()` builtin")), "__anext__" => Some(Self::Builtin("anext", "Use `anext()` builtin")), "__abs__" => Some(Self::Builtin("abs", "Use `abs()` builtin")), "__bool__" => Some(Self::Builtin("bool", "Use `bool()` builtin")), "__bytes__" => Some(Self::Builtin("bytes", "Use `bytes()` builtin")), "__complex__" => Some(Self::Builtin("complex", "Use `complex()` builtin")), "__dir__" => Some(Self::Builtin("dir", "Use `dir()` builtin")), "__float__" => Some(Self::Builtin("float", "Use `float()` builtin")), "__hash__" => Some(Self::Builtin("hash", "Use `hash()` builtin")), "__int__" => Some(Self::Builtin("int", "Use `int()` builtin")), "__iter__" => Some(Self::Builtin("iter", "Use `iter()` builtin")), "__len__" => Some(Self::Builtin("len", "Use `len()` builtin")), "__next__" => Some(Self::Builtin("next", "Use `next()` builtin")), "__repr__" => Some(Self::Builtin("repr", "Use `repr()` builtin")), "__reversed__" => Some(Self::Builtin("reversed", "Use `reversed()` builtin")), "__round__" => Some(Self::Builtin("round", "Use `round()` builtin")), "__str__" => Some(Self::Builtin("str", "Use `str()` builtin")), "__subclasscheck__" => Some(Self::Builtin("issubclass", "Use `issubclass()` builtin")), "__aenter__" => Some(Self::MessageOnly("Invoke context manager directly")), "__ceil__" => Some(Self::MessageOnly("Use `math.ceil()` function")), "__copy__" => Some(Self::MessageOnly("Use `copy.copy()` function")), "__deepcopy__" => Some(Self::MessageOnly("Use `copy.deepcopy()` function")), "__del__" => Some(Self::MessageOnly("Use `del` statement")), "__delattr__" => Some(Self::MessageOnly("Use `del` statement")), "__delitem__" => Some(Self::MessageOnly("Use `del` statement")), "__divmod__" => Some(Self::MessageOnly("Use `divmod()` builtin")), "__format__" => Some(Self::MessageOnly( "Use `format` builtin, format string method, or f-string", )), "__fspath__" => Some(Self::MessageOnly("Use `os.fspath` function")), "__getattr__" => Some(Self::MessageOnly( "Access attribute directly or use getattr built-in function", )), "__getattribute__" => Some(Self::MessageOnly( "Access attribute directly or use getattr built-in function", )), "__getitem__" => Some(Self::MessageOnly("Access item via subscript")), "__init__" => Some(Self::MessageOnly("Instantiate class directly")), "__instancecheck__" => Some(Self::MessageOnly("Use `isinstance()` builtin")), "__invert__" => Some(Self::MessageOnly("Use `~` operator")), "__neg__" => Some(Self::MessageOnly("Multiply by -1 instead")), "__pos__" => Some(Self::MessageOnly("Multiply by +1 instead")), "__pow__" => Some(Self::MessageOnly("Use ** operator or `pow()` builtin")), "__rdivmod__" => Some(Self::MessageOnly("Use `divmod()` builtin")), "__rpow__" => Some(Self::MessageOnly("Use ** operator or `pow()` builtin")), "__setattr__" => Some(Self::MessageOnly( "Mutate attribute directly or use setattr built-in function", )), "__setitem__" => Some(Self::MessageOnly("Use subscript assignment")), "__truncate__" => Some(Self::MessageOnly("Use `math.trunc()` function")), _ => None, } } } /// Returns `true` if this is a dunder method that is excusable in a nested expression. Some /// methods are otherwise unusable in lambda expressions and elsewhere, as they can only be /// represented as /// statements. fn allow_nested_expression(dunder_name: &str, semantic: &SemanticModel) -> bool { semantic.current_expression_parent().is_some() && matches!( dunder_name, "__init__" | "__del__" | "__delattr__" | "__setitem__" | "__delitem__" | "__iadd__" | "__isub__" | "__imul__" | "__imatmul__" | "__itruediv__" | "__ifloordiv__" | "__imod__" | "__ipow__" | "__ilshift__" | "__irshift__" | "__iand__" | "__ixor__" | "__ior__" ) } /// Returns `true` if the [`SemanticModel`] is currently in a dunder method definition. fn in_dunder_method_definition(semantic: &SemanticModel) -> bool { semantic.current_statements().any(|statement| { let Stmt::FunctionDef(func_def) = statement else { return false; }; func_def.name.starts_with("__") && func_def.name.ends_with("__") }) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/import_self.rs
crates/ruff_linter/src/rules/pylint/rules/import_self.rs
use ruff_python_ast::Alias; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::resolve_imported_module_path; use ruff_text_size::Ranged; use crate::{Violation, checkers::ast::Checker}; /// ## What it does /// Checks for import statements that import the current module. /// /// ## Why is this bad? /// Importing a module from itself is a circular dependency and results /// in an `ImportError` exception. /// /// ## Example /// /// ```python /// # file: this_file.py /// from this_file import foo /// /// /// def foo(): ... /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.265")] pub(crate) struct ImportSelf { name: String, } impl Violation for ImportSelf { #[derive_message_formats] fn message(&self) -> String { let Self { name } = self; format!("Module `{name}` imports itself") } } /// PLW0406 pub(crate) fn import_self(checker: &Checker, alias: &Alias, module_path: Option<&[String]>) { let Some(module_path) = module_path else { return; }; if alias.name.split('.').eq(module_path) { checker.report_diagnostic( ImportSelf { name: alias.name.to_string(), }, alias.range(), ); } } /// PLW0406 pub(crate) fn import_from_self( checker: &Checker, level: u32, module: Option<&str>, names: &[Alias], module_path: Option<&[String]>, ) { let Some(module_path) = module_path else { return; }; let Some(imported_module_path) = resolve_imported_module_path(level, module, Some(module_path)) else { return; }; if imported_module_path .split('.') .eq(&module_path[..module_path.len() - 1]) { if let Some(alias) = names .iter() .find(|alias| alias.name == module_path[module_path.len() - 1]) { checker.report_diagnostic( ImportSelf { name: format!("{}.{}", imported_module_path, alias.name), }, alias.range(), ); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs
crates/ruff_linter/src/rules/pylint/rules/bad_string_format_type.rs
use std::str::FromStr; use ruff_python_ast::{self as ast, Expr, StringFlags, StringLiteral}; use ruff_python_literal::cformat::{CFormatPart, CFormatSpec, CFormatStrOrBytes, CFormatString}; use ruff_text_size::Ranged; use rustc_hash::FxHashMap; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for mismatched argument types in "old-style" format strings. /// /// ## Why is this bad? /// The format string is not checked at compile time, so it is easy to /// introduce bugs by mistyping the format string. /// /// ## Example /// ```python /// print("%d" % "1") /// ``` /// /// Use instead: /// ```python /// print("%d" % 1) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.245")] pub(crate) struct BadStringFormatType; impl Violation for BadStringFormatType { #[derive_message_formats] fn message(&self) -> String { "Format type does not match argument type".to_string() } } #[derive(Debug, Copy, Clone)] enum FormatType { Repr, String, Integer, Float, Number, Unknown, } impl FormatType { fn is_compatible_with(self, data_type: PythonType) -> bool { match data_type { PythonType::String | PythonType::Bytes | PythonType::List | PythonType::Dict | PythonType::Set | PythonType::Tuple | PythonType::Generator | PythonType::Ellipsis | PythonType::None => matches!( self, FormatType::Unknown | FormatType::String | FormatType::Repr ), PythonType::Number(NumberLike::Complex | NumberLike::Bool) => matches!( self, FormatType::Unknown | FormatType::String | FormatType::Repr ), PythonType::Number(NumberLike::Integer) => matches!( self, FormatType::Unknown | FormatType::String | FormatType::Repr | FormatType::Integer | FormatType::Float | FormatType::Number ), PythonType::Number(NumberLike::Float) => matches!( self, FormatType::Unknown | FormatType::String | FormatType::Repr | FormatType::Float | FormatType::Number ), } } } impl From<char> for FormatType { fn from(format: char) -> Self { match format { 'r' => FormatType::Repr, 's' => FormatType::String, // The python documentation says "d" only works for integers, but it works for floats as // well: https://docs.python.org/3/library/string.html#formatstrings // I checked the rest of the integer codes, and none of them work with floats 'n' | 'd' => FormatType::Number, 'b' | 'c' | 'o' | 'x' | 'X' => FormatType::Integer, 'e' | 'E' | 'f' | 'F' | 'g' | 'G' | '%' => FormatType::Float, _ => FormatType::Unknown, } } } fn collect_specs(formats: &[CFormatStrOrBytes<String>]) -> Vec<&CFormatSpec> { let mut specs = vec![]; for format in formats { for (_, item) in format.iter() { if let CFormatPart::Spec(spec) = item { specs.push(spec); } } } specs } /// Return `true` if the format string is equivalent to the constant type fn equivalent(format: &CFormatSpec, value: &Expr) -> bool { let format_type = FormatType::from(format.format_char); match ResolvedPythonType::from(value) { ResolvedPythonType::Atom(atom) => { // Special case where `%c` allows single character strings to be formatted if format.format_char == 'c' { if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = value { let mut chars = value.chars(); if chars.next().is_some() && chars.next().is_none() { return true; } } } format_type.is_compatible_with(atom) } ResolvedPythonType::Union(atoms) => atoms .iter() .all(|atom| format_type.is_compatible_with(*atom)), ResolvedPythonType::Unknown => true, ResolvedPythonType::TypeError => true, } } /// Return `true` if the [`Constant`] aligns with the format type. fn is_valid_constant(formats: &[CFormatStrOrBytes<String>], value: &Expr) -> bool { let formats = collect_specs(formats); // If there is more than one format, this is not valid Python and we should // return true so that no error is reported. let [format] = formats.as_slice() else { return true; }; equivalent(format, value) } /// Return `true` if the tuple elements align with the format types. fn is_valid_tuple(formats: &[CFormatStrOrBytes<String>], elts: &[Expr]) -> bool { let formats = collect_specs(formats); // If there are more formats that values, the statement is invalid. Avoid // checking the values. if formats.len() > elts.len() { return true; } for (format, elt) in formats.iter().zip(elts) { if !equivalent(format, elt) { return false; } } true } /// Return `true` if the dictionary values align with the format types. fn is_valid_dict(formats: &[CFormatStrOrBytes<String>], items: &[ast::DictItem]) -> bool { let formats = collect_specs(formats); // If there are more formats that values, the statement is invalid. Avoid // checking the values. if formats.len() > items.len() { return true; } let formats_hash: FxHashMap<&str, &&CFormatSpec> = formats .iter() .filter_map(|format| { format .mapping_key .as_ref() .map(|mapping_key| (mapping_key.as_str(), format)) }) .collect(); for ast::DictItem { key, value } in items { let Some(key) = key else { return true; }; if let Expr::StringLiteral(ast::ExprStringLiteral { value: mapping_key, .. }) = key { let Some(format) = formats_hash.get(mapping_key.to_str()) else { return true; }; if !equivalent(format, value) { return false; } } else { // We can't check non-string keys. return true; } } true } /// PLE1307 pub(crate) fn bad_string_format_type( checker: &Checker, bin_op: &ast::ExprBinOp, format_string: &ast::ExprStringLiteral, ) { // Parse each string segment. let mut format_strings = vec![]; for StringLiteral { value: _, node_index: _, range, flags, } in &format_string.value { let string = checker.locator().slice(range); let string = &string [usize::from(flags.opener_len())..(string.len() - usize::from(flags.closer_len()))]; // Parse the format string (e.g. `"%s"`) into a list of `PercentFormat`. if let Ok(format_string) = CFormatString::from_str(string) { format_strings.push(format_string); } } // Parse the parameters. let is_valid = match &*bin_op.right { Expr::Tuple(ast::ExprTuple { elts, .. }) => is_valid_tuple(&format_strings, elts), Expr::Dict(ast::ExprDict { items, range: _, node_index: _, }) => is_valid_dict(&format_strings, items), _ => is_valid_constant(&format_strings, &bin_op.right), }; if !is_valid { checker.report_diagnostic(BadStringFormatType, bin_op.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/misplaced_bare_raise.rs
crates/ruff_linter/src/rules/pylint/rules/misplaced_bare_raise.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::in_dunder_method; /// ## What it does /// Checks for bare `raise` statements outside of exception handlers. /// /// ## Why is this bad? /// A bare `raise` statement without an exception object will re-raise the last /// exception that was active in the current scope, and is typically used /// within an exception handler to re-raise the caught exception. /// /// If a bare `raise` is used outside of an exception handler, it will generate /// an error due to the lack of an active exception. /// /// Note that a bare `raise` within a `finally` block will work in some cases /// (namely, when the exception is raised within the `try` block), but should /// be avoided as it can lead to confusing behavior. /// /// ## Example /// ```python /// from typing import Any /// /// /// def is_some(obj: Any) -> bool: /// if obj is None: /// raise /// ``` /// /// Use instead: /// ```python /// from typing import Any /// /// /// def is_some(obj: Any) -> bool: /// if obj is None: /// raise ValueError("`obj` cannot be `None`") /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct MisplacedBareRaise; impl Violation for MisplacedBareRaise { #[derive_message_formats] fn message(&self) -> String { "Bare `raise` statement is not inside an exception handler".to_string() } } /// PLE0704 pub(crate) fn misplaced_bare_raise(checker: &Checker, raise: &ast::StmtRaise) { if raise.exc.is_some() { return; } if checker.semantic().in_exception_handler() { return; } if in_dunder_method("__exit__", checker.semantic(), checker.settings()) { return; } checker.report_diagnostic(MisplacedBareRaise, raise.range()); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/subprocess_run_without_check.rs
crates/ruff_linter/src/rules/pylint/rules/subprocess_run_without_check.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits::add_argument; use crate::{AlwaysFixableViolation, Applicability, Fix}; /// ## What it does /// Checks for uses of `subprocess.run` without an explicit `check` argument. /// /// ## Why is this bad? /// By default, `subprocess.run` does not check the return code of the process /// it runs. This can lead to silent failures. /// /// Instead, consider using `check=True` to raise an exception if the process /// fails, or set `check=False` explicitly to mark the behavior as intentional. /// /// ## Example /// ```python /// import subprocess /// /// subprocess.run(["ls", "nonexistent"]) # No exception raised. /// ``` /// /// Use instead: /// ```python /// import subprocess /// /// subprocess.run(["ls", "nonexistent"], check=True) # Raises exception. /// ``` /// /// Or: /// ```python /// import subprocess /// /// subprocess.run(["ls", "nonexistent"], check=False) # Explicitly no check. /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe for function calls that contain /// `**kwargs`, as adding a `check` keyword argument to such a call may lead /// to a duplicate keyword argument error. /// /// ## References /// - [Python documentation: `subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.285")] pub(crate) struct SubprocessRunWithoutCheck; impl AlwaysFixableViolation for SubprocessRunWithoutCheck { #[derive_message_formats] fn message(&self) -> String { "`subprocess.run` without explicit `check` argument".to_string() } fn fix_title(&self) -> String { "Add explicit `check=False`".to_string() } } /// PLW1510 pub(crate) fn subprocess_run_without_check(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::SUBPROCESS) { return; } if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["subprocess", "run"])) { if call.arguments.find_keyword("check").is_none() { let mut diagnostic = checker.report_diagnostic(SubprocessRunWithoutCheck, call.func.range()); diagnostic.set_fix(Fix::applicable_edit( add_argument("check=False", &call.arguments, checker.tokens()), // If the function call contains `**kwargs`, mark the fix as unsafe. if call .arguments .keywords .iter() .any(|keyword| keyword.arg.is_none()) { Applicability::Unsafe } else { Applicability::Safe }, )); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/self_or_cls_assignment.rs
crates/ruff_linter/src/rules/pylint/rules/self_or_cls_assignment.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::ScopeKind; use ruff_python_semantic::analyze::function_type::{self as function_type, FunctionType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for assignment of `self` and `cls` in instance and class methods respectively. /// /// This check also applies to `__new__` even though this is technically /// a static method. /// /// ## Why is this bad? /// The identifiers `self` and `cls` are conventional in Python for the first parameter of instance /// methods and class methods, respectively. Assigning new values to these variables can be /// confusing for others reading your code; using a different variable name can lead to clearer /// code. /// /// ## Example /// /// ```python /// class Version: /// def add(self, other): /// self = self + other /// return self /// /// @classmethod /// def superclass(cls): /// cls = cls.__mro__[-1] /// return cls /// ``` /// /// Use instead: /// ```python /// class Version: /// def add(self, other): /// new_version = self + other /// return new_version /// /// @classmethod /// def superclass(cls): /// supercls = cls.__mro__[-1] /// return supercls /// ``` /// /// ## Options /// /// - `lint.pep8-naming.classmethod-decorators` /// - `lint.pep8-naming.staticmethod-decorators` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.6.0")] pub(crate) struct SelfOrClsAssignment { method_type: MethodType, } impl Violation for SelfOrClsAssignment { #[derive_message_formats] fn message(&self) -> String { let SelfOrClsAssignment { method_type } = self; format!( "Reassigned `{}` variable in {method_type} method", method_type.arg_name(), ) } fn fix_title(&self) -> Option<String> { Some("Consider using a different variable name".to_string()) } } /// PLW0642 pub(crate) fn self_or_cls_assignment(checker: &Checker, target: &Expr) { let ScopeKind::Function(ast::StmtFunctionDef { name, decorator_list, parameters, .. }) = checker.semantic().current_scope().kind else { return; }; let Some(parent) = &checker .semantic() .first_non_type_parent_scope(checker.semantic().current_scope()) else { return; }; let Some(self_or_cls) = parameters .posonlyargs .first() .or_else(|| parameters.args.first()) else { return; }; let function_type = function_type::classify( name, decorator_list, parent, checker.semantic(), &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ); let method_type = match (function_type, self_or_cls.name().as_str()) { (FunctionType::Method, "self") => MethodType::Instance, (FunctionType::ClassMethod, "cls") => MethodType::Class, (FunctionType::NewMethod, "cls") => MethodType::New, _ => return, }; check_expr(checker, target, method_type); } fn check_expr(checker: &Checker, target: &Expr, method_type: MethodType) { match target { Expr::Name(_) => { if let Expr::Name(ast::ExprName { id, .. }) = target { if id.as_str() == method_type.arg_name() { checker.report_diagnostic(SelfOrClsAssignment { method_type }, target.range()); } } } Expr::Tuple(ast::ExprTuple { elts, .. }) | Expr::List(ast::ExprList { elts, .. }) => { for element in elts { check_expr(checker, element, method_type); } } Expr::Starred(ast::ExprStarred { value, .. }) => check_expr(checker, value, method_type), _ => {} } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum MethodType { Instance, Class, New, } impl MethodType { const fn arg_name(self) -> &'static str { match self { MethodType::Instance => "self", MethodType::Class => "cls", MethodType::New => "cls", } } } impl std::fmt::Display for MethodType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { MethodType::Instance => f.write_str("instance"), MethodType::Class => f.write_str("class"), MethodType::New => f.write_str("`__new__`"), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unnecessary_lambda.rs
crates/ruff_linter/src/rules/pylint/rules/unnecessary_lambda.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, ExprLambda, Parameter, ParameterWithDefault, visitor}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for `lambda` definitions that consist of a single function call /// with the same arguments as the `lambda` itself. /// /// ## Why is this bad? /// When a `lambda` is used to wrap a function call, and merely propagates /// the `lambda` arguments to that function, it can typically be replaced with /// the function itself, removing a level of indirection. /// /// ## Example /// ```python /// df.apply(lambda x: str(x)) /// ``` /// /// Use instead: /// ```python /// df.apply(str) /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe for two primary reasons. /// /// First, the lambda body itself could contain an effect. /// /// For example, replacing `lambda x, y: (func()(x, y))` with `func()` would /// lead to a change in behavior, as `func()` would be evaluated eagerly when /// defining the lambda, rather than when the lambda is called. /// /// However, even when the lambda body itself is pure, the lambda may /// change the argument names, which can lead to a change in behavior when /// callers pass arguments by name. /// /// For example, replacing `foo = lambda x, y: func(x, y)` with `foo = func`, /// where `func` is defined as `def func(a, b): return a + b`, would be a /// breaking change for callers that execute the lambda by passing arguments by /// name, as in: `foo(x=1, y=2)`. Since `func` does not define the arguments /// `x` and `y`, unlike the lambda, the call would raise a `TypeError`. #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.2")] pub(crate) struct UnnecessaryLambda; impl Violation for UnnecessaryLambda { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Lambda may be unnecessary; consider inlining inner function".to_string() } fn fix_title(&self) -> Option<String> { Some("Inline function call".to_string()) } } /// PLW0108 pub(crate) fn unnecessary_lambda(checker: &Checker, lambda: &ExprLambda) { let ExprLambda { parameters, body, range: _, node_index: _, } = lambda; // The lambda should consist of a single function call. let Expr::Call(ast::ExprCall { arguments, func, .. }) = body.as_ref() else { return; }; // Ignore call chains. if let Expr::Attribute(ast::ExprAttribute { value, .. }) = func.as_ref() { if value.is_call_expr() { return; } } // If at least one of the lambda parameters has a default value, abort. We can't know if the // defaults provided by the lambda are the same as the defaults provided by the inner // function. if parameters.as_ref().is_some_and(|parameters| { parameters .args .iter() .any(|ParameterWithDefault { default, .. }| default.is_some()) }) { return; } match parameters.as_ref() { None => { if !arguments.is_empty() { return; } } Some(parameters) => { // Collect all starred arguments (e.g., `lambda *args: func(*args)`). let call_varargs: Vec<&Expr> = arguments .args .iter() .filter_map(|arg| { if let Expr::Starred(ast::ExprStarred { value, .. }) = arg { Some(value.as_ref()) } else { None } }) .collect::<Vec<_>>(); // Collect all keyword arguments (e.g., `lambda x, y: func(x=x, y=y)`). let call_kwargs: Vec<&Expr> = arguments .keywords .iter() .map(|kw| &kw.value) .collect::<Vec<_>>(); // Collect all positional arguments (e.g., `lambda x, y: func(x, y)`). let call_posargs: Vec<&Expr> = arguments .args .iter() .filter(|arg| !arg.is_starred_expr()) .collect::<Vec<_>>(); // Ex) `lambda **kwargs: func(**kwargs)` match parameters.kwarg.as_ref() { None => { if !call_kwargs.is_empty() { return; } } Some(kwarg) => { let [call_kwarg] = &call_kwargs[..] else { return; }; let Expr::Name(ast::ExprName { id, .. }) = call_kwarg else { return; }; if id.as_str() != kwarg.name.as_str() { return; } } } // Ex) `lambda *args: func(*args)` match parameters.vararg.as_ref() { None => { if !call_varargs.is_empty() { return; } } Some(vararg) => { let [call_vararg] = &call_varargs[..] else { return; }; let Expr::Name(ast::ExprName { id, .. }) = call_vararg else { return; }; if id.as_str() != vararg.name.as_str() { return; } } } // Ex) `lambda x, y: func(x, y)` let lambda_posargs: Vec<&Parameter> = parameters .args .iter() .map(|ParameterWithDefault { parameter, .. }| parameter) .collect::<Vec<_>>(); if call_posargs.len() != lambda_posargs.len() { return; } for (param, arg) in lambda_posargs.iter().zip(call_posargs) { let Expr::Name(ast::ExprName { id, .. }) = arg else { return; }; if id.as_str() != param.name.as_str() { return; } } } } // The lambda is necessary if it uses one of its parameters _as_ the function call. // Ex) `lambda x, y: x(y)` let names = { let mut finder = NameFinder::default(); finder.visit_expr(func); finder.names }; for name in &names { if let Some(binding_id) = checker.semantic().resolve_name(name) { let binding = checker.semantic().binding(binding_id); if checker.semantic().is_current_scope(binding.scope) { return; } } } let mut diagnostic = checker.report_diagnostic(UnnecessaryLambda, lambda.range()); // Suppress the fix if the assignment expression target shadows one of the lambda's parameters. // This is necessary to avoid introducing a change in the behavior of the program. for name in names { if let Some(binding_id) = checker.semantic().lookup_symbol(name.id()) { let binding = checker.semantic().binding(binding_id); if checker .semantic() .current_scope() .shadowed_binding(binding_id) .is_some() && binding .expression(checker.semantic()) .is_some_and(Expr::is_named_expr) { return; } } } diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( if func.is_named_expr() { format!("({})", checker.locator().slice(func.as_ref())) } else { checker.locator().slice(func.as_ref()).to_string() }, lambda.range(), ))); } /// Identify all `Expr::Name` nodes in an AST. #[derive(Debug, Default)] struct NameFinder<'a> { /// A map from identifier to defining expression. names: Vec<&'a ast::ExprName>, } impl<'a> Visitor<'a> for NameFinder<'a> { fn visit_expr(&mut self, expr: &'a Expr) { if let Expr::Name(expr_name) = expr { self.names.push(expr_name); } visitor::walk_expr(self, expr); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/redeclared_assigned_name.rs
crates/ruff_linter/src/rules/pylint/rules/redeclared_assigned_name.rs
use ruff_python_ast::{self as ast, Expr}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for declared assignments to the same variable multiple times /// in the same assignment. /// /// ## Why is this bad? /// Assigning a variable multiple times in the same assignment is redundant, /// as the final assignment to the variable is what the value will be. /// /// ## Example /// ```python /// a, b, a = (1, 2, 3) /// print(a) # 3 /// ``` /// /// Use instead: /// ```python /// # this is assuming you want to assign 3 to `a` /// _, b, a = (1, 2, 3) /// print(a) # 3 /// ``` /// /// ## Options /// /// The rule ignores assignments to dummy variables, as specified by: /// /// - `lint.dummy-variable-rgx` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct RedeclaredAssignedName { name: String, } impl Violation for RedeclaredAssignedName { #[derive_message_formats] fn message(&self) -> String { let RedeclaredAssignedName { name } = self; format!("Redeclared variable `{name}` in assignment") } } /// PLW0128 pub(crate) fn redeclared_assigned_name(checker: &Checker, targets: &Vec<Expr>) { let mut names: Vec<Name> = Vec::new(); for target in targets { check_expr(checker, target, &mut names); } } fn check_expr(checker: &Checker, expr: &Expr, names: &mut Vec<Name>) { match expr { Expr::Tuple(tuple) => { for target in tuple { check_expr(checker, target, names); } } Expr::List(list) => { for target in list { check_expr(checker, target, names); } } Expr::Starred(starred) => { check_expr(checker, &starred.value, names); } Expr::Name(ast::ExprName { id, .. }) => { if checker.settings().dummy_variable_rgx.is_match(id) { // Ignore dummy variable assignments return; } if names.contains(id) { checker.report_diagnostic( RedeclaredAssignedName { name: id.to_string(), }, expr.range(), ); } names.push(id.clone()); } _ => {} } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/global_at_module_level.rs
crates/ruff_linter/src/rules/pylint/rules/global_at_module_level.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of the `global` keyword at the module level. /// /// ## Why is this bad? /// The `global` keyword is used within functions to indicate that a name /// refers to a global variable, rather than a local variable. /// /// At the module level, all names are global by default, so the `global` /// keyword is redundant. #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct GlobalAtModuleLevel; impl Violation for GlobalAtModuleLevel { #[derive_message_formats] fn message(&self) -> String { "`global` at module level is redundant".to_string() } } /// PLW0604 pub(crate) fn global_at_module_level(checker: &Checker, stmt: &Stmt) { if checker.semantic().current_scope().kind.is_module() { checker.report_diagnostic(GlobalAtModuleLevel, stmt.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/global_statement.rs
crates/ruff_linter/src/rules/pylint/rules/global_statement.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for the use of `global` statements to update identifiers. /// /// ## Why is this bad? /// Pylint discourages the use of `global` variables as global mutable /// state is a common source of bugs and confusing behavior. /// /// ## Example /// ```python /// var = 1 /// /// /// def foo(): /// global var # [global-statement] /// var = 10 /// print(var) /// /// /// foo() /// print(var) /// ``` /// /// Use instead: /// ```python /// var = 1 /// /// /// def foo(): /// var = 10 /// print(var) /// return var /// /// /// var = foo() /// print(var) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.253")] pub(crate) struct GlobalStatement { name: String, } impl Violation for GlobalStatement { #[derive_message_formats] fn message(&self) -> String { let GlobalStatement { name } = self; format!("Using the global statement to update `{name}` is discouraged") } } /// PLW0603 pub(crate) fn global_statement(checker: &Checker, name: &str) { if let Some(range) = checker.semantic().global(name) { checker.report_diagnostic( GlobalStatement { name: name.to_string(), }, // Match Pylint's behavior by reporting on the `global` statement`, rather // than the variable usage. range, ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs
crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs
use rustc_hash::{FxBuildHasher, FxHashSet}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_ast::comparable::HashableExpr; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for iteration over a `set` literal where each element in the set is /// itself a literal value. /// /// ## Why is this bad? /// Iterating over a `set` is less efficient than iterating over a sequence /// type, like `list` or `tuple`. /// /// ## Example /// ```python /// for number in {1, 2, 3}: /// ... /// ``` /// /// Use instead: /// ```python /// for number in (1, 2, 3): /// ... /// ``` /// /// ## References /// - [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.271")] pub(crate) struct IterationOverSet; impl AlwaysFixableViolation for IterationOverSet { #[derive_message_formats] fn message(&self) -> String { "Use a sequence type instead of a `set` when iterating over values".to_string() } fn fix_title(&self) -> String { "Convert to `tuple`".to_string() } } /// PLC0208 pub(crate) fn iteration_over_set(checker: &Checker, expr: &Expr) { let Expr::Set(set) = expr else { return; }; if set.iter().any(|value| !value.is_literal_expr()) { return; } let mut seen_values = FxHashSet::with_capacity_and_hasher(set.len(), FxBuildHasher); for value in set { if !seen_values.insert(HashableExpr::from(value)) { // if the set contains a duplicate literal value, early exit. // rule `B033` can catch that. return; } } let mut diagnostic = checker.report_diagnostic(IterationOverSet, expr.range()); let tuple = if let [elt] = set.elts.as_slice() { let elt = checker.locator().slice(elt); format!("({elt},)") } else { let set = checker.locator().slice(expr); format!("({})", &set[1..set.len() - 1]) }; diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(tuple, expr.range()))); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_arguments.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_arguments.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::function_type::is_subject_to_liskov_substitution_principle; use ruff_python_semantic::analyze::{function_type, visibility}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for function definitions that include too many arguments. /// /// By default, this rule allows up to five arguments, as configured by the /// [`lint.pylint.max-args`] option. /// /// This rule exempts methods decorated with [`@typing.override`][override]. /// Changing the signature of a subclass method may cause type checkers to /// complain about a violation of the Liskov Substitution Principle if it /// means that the method now incompatibly overrides a method defined on a /// superclass. Explicitly decorating an overriding method with `@override` /// signals to Ruff that the method is intended to override a superclass /// method and that a type checker will enforce that it does so; Ruff /// therefore knows that it should not enforce rules about methods having /// too many arguments. /// /// ## Why is this bad? /// Functions with many arguments are harder to understand, maintain, and call. /// Consider refactoring functions with many arguments into smaller functions /// with fewer arguments, or using objects to group related arguments. /// /// ## Example /// ```python /// def calculate_position(x_pos, y_pos, z_pos, x_vel, y_vel, z_vel, time): /// new_x = x_pos + x_vel * time /// new_y = y_pos + y_vel * time /// new_z = z_pos + z_vel * time /// return new_x, new_y, new_z /// ``` /// /// Use instead: /// ```python /// from typing import NamedTuple /// /// /// class Vector(NamedTuple): /// x: float /// y: float /// z: float /// /// /// def calculate_position(pos: Vector, vel: Vector, time: float) -> Vector: /// return Vector(*(p + v * time for p, v in zip(pos, vel))) /// ``` /// /// ## Options /// - `lint.pylint.max-args` /// /// [override]: https://docs.python.org/3/library/typing.html#typing.override #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.238")] pub(crate) struct TooManyArguments { c_args: usize, max_args: usize, } impl Violation for TooManyArguments { #[derive_message_formats] fn message(&self) -> String { let TooManyArguments { c_args, max_args } = self; format!("Too many arguments in function definition ({c_args} > {max_args})") } } /// PLR0913 pub(crate) fn too_many_arguments(checker: &Checker, function_def: &ast::StmtFunctionDef) { // https://github.com/astral-sh/ruff/issues/14535 if checker.source_type.is_stub() { return; } let semantic = checker.semantic(); let num_arguments = function_def .parameters .iter_non_variadic_params() .filter(|param| !checker.settings().dummy_variable_rgx.is_match(param.name())) .count(); if num_arguments <= checker.settings().pylint.max_args { return; } // Allow excessive arguments in `@override` or `@overload` methods, since they're required // to adhere to the parent signature. if visibility::is_override(&function_def.decorator_list, checker.semantic()) || visibility::is_overload(&function_def.decorator_list, checker.semantic()) { return; } // Check if the function is a method or class method. let num_arguments = if matches!( function_type::classify( &function_def.name, &function_def.decorator_list, semantic.current_scope(), semantic, &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ), function_type::FunctionType::Method | function_type::FunctionType::ClassMethod | function_type::FunctionType::NewMethod ) { // If so, we need to subtract one from the number of positional arguments, since the first // argument is always `self` or `cls`. num_arguments.saturating_sub(1) } else { num_arguments }; if num_arguments <= checker.settings().pylint.max_args { return; } let mut diagnostic = checker.report_diagnostic( TooManyArguments { c_args: num_arguments, max_args: checker.settings().pylint.max_args, }, function_def.identifier(), ); if is_subject_to_liskov_substitution_principle( &function_def.name, &function_def.decorator_list, semantic.current_scope(), semantic, &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ) { diagnostic.help( "Consider adding `@typing.override` if changing the function signature \ would violate the Liskov Substitution Principle", ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bad_str_strip_call.rs
crates/ruff_linter/src/rules/pylint/rules/bad_str_strip_call.rs
use std::fmt; use ruff_python_ast::{self as ast, Expr}; use rustc_hash::FxHashSet; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::typing; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use ruff_python_ast::PythonVersion; /// ## What it does /// Checks duplicate characters in `str.strip` calls. /// /// ## Why is this bad? /// All characters in `str.strip` calls are removed from both the leading and /// trailing ends of the string. Including duplicate characters in the call /// is redundant and often indicative of a mistake. /// /// In Python 3.9 and later, you can use `str.removeprefix` and /// `str.removesuffix` to remove an exact prefix or suffix from a string, /// respectively, which should be preferred when possible. /// /// ## Example /// ```python /// # Evaluates to "foo". /// "bar foo baz".strip("bar baz ") /// ``` /// /// Use instead: /// ```python /// # Evaluates to "foo". /// "bar foo baz".strip("abrz ") # "foo" /// ``` /// /// Or: /// ```python /// # Evaluates to "foo". /// "bar foo baz".removeprefix("bar ").removesuffix(" baz") /// ``` /// /// ## Options /// - `target-version` /// /// ## References /// - [Python documentation: `str.strip`](https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.242")] pub(crate) struct BadStrStripCall { strip: StripKind, removal: Option<RemovalKind>, } impl Violation for BadStrStripCall { #[derive_message_formats] fn message(&self) -> String { let Self { strip, removal } = self; if let Some(removal) = removal { format!( "String `{strip}` call contains duplicate characters (did you mean `{removal}`?)", ) } else { format!("String `{strip}` call contains duplicate characters") } } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub(crate) enum ValueKind { String, Bytes, } impl ValueKind { fn from(expr: &Expr, semantic: &SemanticModel) -> Option<Self> { match expr { Expr::StringLiteral(_) => Some(Self::String), Expr::BytesLiteral(_) => Some(Self::Bytes), Expr::Name(name) => { let binding_id = semantic.only_binding(name)?; let binding = semantic.binding(binding_id); if typing::is_string(binding, semantic) { Some(Self::String) } else if typing::is_bytes(binding, semantic) { Some(Self::Bytes) } else { None } } _ => None, } } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub(crate) enum StripKind { Strip, LStrip, RStrip, } impl StripKind { pub(crate) fn from_str(s: &str) -> Option<Self> { match s { "strip" => Some(Self::Strip), "lstrip" => Some(Self::LStrip), "rstrip" => Some(Self::RStrip), _ => None, } } } impl fmt::Display for StripKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let representation = match self { Self::Strip => "strip", Self::LStrip => "lstrip", Self::RStrip => "rstrip", }; write!(f, "{representation}") } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub(crate) enum RemovalKind { RemovePrefix, RemoveSuffix, } impl RemovalKind { pub(crate) fn for_strip(s: StripKind) -> Option<Self> { match s { StripKind::Strip => None, StripKind::LStrip => Some(Self::RemovePrefix), StripKind::RStrip => Some(Self::RemoveSuffix), } } } impl fmt::Display for RemovalKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let representation = match self { Self::RemovePrefix => "removeprefix", Self::RemoveSuffix => "removesuffix", }; write!(f, "{representation}") } } fn string_has_duplicate_char(string: &ast::StringLiteralValue) -> bool { has_duplicate(string.chars()) } fn bytes_has_duplicate_char(bytes: &ast::BytesLiteralValue) -> bool { has_duplicate(bytes.bytes().map(char::from)) } /// Return true if a string or byte sequence has a duplicate. fn has_duplicate(mut chars: impl Iterator<Item = char>) -> bool { let mut seen = FxHashSet::default(); chars.any(|char| !seen.insert(char)) } /// PLE1310 pub(crate) fn bad_str_strip_call(checker: &Checker, call: &ast::ExprCall) { let (func, arguments) = (&call.func, &call.arguments); let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else { return; }; let Some(strip) = StripKind::from_str(attr.as_str()) else { return; }; if !arguments.keywords.is_empty() { return; } let [arg] = arguments.args.as_ref() else { return; }; let value = &**value; let Some(value_kind) = ValueKind::from(value, checker.semantic()) else { return; }; let duplicated = match arg { Expr::StringLiteral(string) if value_kind == ValueKind::String => { string_has_duplicate_char(&string.value) } Expr::BytesLiteral(bytes) if value_kind == ValueKind::Bytes => { bytes_has_duplicate_char(&bytes.value) } _ => return, }; if !duplicated { return; } let removal = if checker.target_version() >= PythonVersion::PY39 { RemovalKind::for_strip(strip) } else { None }; checker.report_diagnostic(BadStrStripCall { strip, removal }, arg.range()); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bidirectional_unicode.rs
crates/ruff_linter/src/rules/pylint/rules/bidirectional_unicode.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::Line; use crate::{Violation, checkers::ast::LintContext}; const BIDI_UNICODE: [char; 11] = [ '\u{202A}', //{LEFT-TO-RIGHT EMBEDDING} '\u{202B}', //{RIGHT-TO-LEFT EMBEDDING} '\u{202C}', //{POP DIRECTIONAL FORMATTING} '\u{202D}', //{LEFT-TO-RIGHT OVERRIDE} '\u{202E}', //{RIGHT-TO-LEFT OVERRIDE} '\u{2066}', //{LEFT-TO-RIGHT ISOLATE} '\u{2067}', //{RIGHT-TO-LEFT ISOLATE} '\u{2068}', //{FIRST STRONG ISOLATE} '\u{2069}', //{POP DIRECTIONAL ISOLATE} // The following was part of PEP 672: // https://peps.python.org/pep-0672/ // so the list above might not be complete '\u{200F}', //{RIGHT-TO-LEFT MARK} '\u{061C}', //{ARABIC LETTER MARK} // We don't use // "\u200E" # \n{LEFT-TO-RIGHT MARK} // as this is the default for latin files and can't be used // to hide code ]; /// ## What it does /// Checks for bidirectional formatting characters. /// /// ## Why is this bad? /// The interaction between bidirectional formatting characters and the /// surrounding code can be surprising to those that are unfamiliar /// with right-to-left writing systems. /// /// In some cases, bidirectional formatting characters can also be used to /// obfuscate code and introduce or mask security vulnerabilities. /// /// ## Example /// ```python /// example = "x‏" * 100 # "‏x" is assigned /// ``` /// /// The example uses two `RIGHT-TO-LEFT MARK`s to make the `100 * ` appear inside the comment. /// Without the `RIGHT-TO-LEFT MARK`s, the code looks like this: /// /// ```py /// example = "x" * 100 # "x" is assigned /// ``` /// /// ## References /// - [PEP 672: Bidirectional Marks, Embeddings, Overrides and Isolates](https://peps.python.org/pep-0672/#bidirectional-marks-embeddings-overrides-and-isolates) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.244")] pub(crate) struct BidirectionalUnicode; impl Violation for BidirectionalUnicode { #[derive_message_formats] fn message(&self) -> String { "Contains control characters that can permit obfuscated code".to_string() } } /// PLE2502 pub(crate) fn bidirectional_unicode(line: &Line, context: &LintContext) { if line.contains(BIDI_UNICODE) { context.report_diagnostic(BidirectionalUnicode, line.full_range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/await_outside_async.rs
crates/ruff_linter/src/rules/pylint/rules/await_outside_async.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; /// ## What it does /// Checks for uses of `await` outside `async` functions. /// /// ## Why is this bad? /// Using `await` outside an `async` function is a syntax error. /// /// ## Example /// ```python /// import asyncio /// /// /// def foo(): /// await asyncio.sleep(1) /// ``` /// /// Use instead: /// ```python /// import asyncio /// /// /// async def foo(): /// await asyncio.sleep(1) /// ``` /// /// ## Notebook behavior /// As an exception, `await` is allowed at the top level of a Jupyter notebook /// (see: [autoawait]). /// /// ## References /// - [Python documentation: Await expression](https://docs.python.org/3/reference/expressions.html#await) /// - [PEP 492: Await Expression](https://peps.python.org/pep-0492/#await-expression) /// /// [autoawait]: https://ipython.readthedocs.io/en/stable/interactive/autoawait.html #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.150")] pub(crate) struct AwaitOutsideAsync; impl Violation for AwaitOutsideAsync { #[derive_message_formats] fn message(&self) -> String { "`await` should be used within an async function".to_string() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/dict_iter_missing_items.rs
crates/ruff_linter/src/rules/pylint/rules/dict_iter_missing_items.rs
use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::analyze::typing::is_dict; use ruff_python_semantic::{Binding, SemanticModel}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for dictionary unpacking in a for loop without calling `.items()`. /// /// ## Why is this bad? /// When iterating over a dictionary in a for loop, if a dictionary is unpacked /// without calling `.items()`, it could lead to a runtime error if the keys are not /// a tuple of two elements. /// /// It is likely that you're looking for an iteration over (key, value) pairs which /// can only be achieved when calling `.items()`. /// /// ## Example /// ```python /// data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129} /// /// for city, population in data: /// print(f"{city} has population {population}.") /// ``` /// /// Use instead: /// ```python /// data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129} /// /// for city, population in data.items(): /// print(f"{city} has population {population}.") /// ``` /// /// ## Known problems /// If the dictionary key is a tuple, e.g.: /// /// ```python /// d = {(1, 2): 3, (3, 4): 5} /// for x, y in d: /// print(x, y) /// ``` /// /// The tuple key is unpacked into `x` and `y` instead of the key and values. This means that /// the suggested fix of using `d.items()` would result in different runtime behavior. Ruff /// cannot consistently infer the type of a dictionary's keys. /// /// ## Fix safety /// Due to the known problem with tuple keys, this fix is unsafe. #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.3.0")] pub(crate) struct DictIterMissingItems; impl AlwaysFixableViolation for DictIterMissingItems { #[derive_message_formats] fn message(&self) -> String { "Unpacking a dictionary in iteration without calling `.items()`".to_string() } fn fix_title(&self) -> String { "Add a call to `.items()`".to_string() } } /// PLE1141 pub(crate) fn dict_iter_missing_items(checker: &Checker, target: &Expr, iter: &Expr) { let Expr::Tuple(tuple) = target else { return; }; if tuple.len() != 2 { return; } let Expr::Name(name) = iter else { return; }; let Some(binding) = checker .semantic() .only_binding(name) .map(|id| checker.semantic().binding(id)) else { return; }; if !is_dict(binding, checker.semantic()) { return; } // If we can reliably determine that a dictionary has keys that are tuples of two we don't warn if is_dict_key_tuple_with_two_elements(binding, checker.semantic()) { return; } let mut diagnostic = checker.report_diagnostic(DictIterMissingItems, iter.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("{}.items()", name.id), iter.range(), ))); } /// Returns true if the binding is a dictionary where each key is a tuple with two elements. fn is_dict_key_tuple_with_two_elements(binding: &Binding, semantic: &SemanticModel) -> bool { let Some(statement) = binding.statement(semantic) else { return false; }; let (value, annotation) = match statement { Stmt::Assign(assign_stmt) => (assign_stmt.value.as_ref(), None), Stmt::AnnAssign(ast::StmtAnnAssign { value: Some(value), annotation, .. }) => (value.as_ref(), Some(annotation.as_ref())), _ => return false, }; let Expr::Dict(dict_expr) = value else { return false; }; // Check if dict is empty let is_empty = dict_expr.is_empty(); if is_empty { // For empty dicts, check type annotation return annotation .is_some_and(|annotation| is_annotation_dict_with_tuple_keys(annotation, semantic)); } // For non-empty dicts, check if all keys are 2-tuples dict_expr .iter_keys() .all(|key| matches!(key, Some(Expr::Tuple(tuple)) if tuple.len() == 2)) } /// Returns true if the annotation is `dict[tuple[T1, T2], ...]` where tuple has exactly 2 elements. fn is_annotation_dict_with_tuple_keys(annotation: &Expr, semantic: &SemanticModel) -> bool { // Check if it's a subscript: dict[...] let Expr::Subscript(subscript) = annotation else { return false; }; // Check if it's dict or typing.Dict if !semantic.match_builtin_expr(subscript.value.as_ref(), "dict") && !semantic.match_typing_expr(subscript.value.as_ref(), "Dict") { return false; } // Extract the slice (should be a tuple: (key_type, value_type)) let Expr::Tuple(tuple) = subscript.slice.as_ref() else { return false; }; // dict[K, V] format - check if K is tuple with 2 elements if let [key, _value] = tuple.elts.as_slice() { return is_tuple_type_with_two_elements(key, semantic); } false } /// Returns true if the expression represents a tuple type with exactly 2 elements. fn is_tuple_type_with_two_elements(expr: &Expr, semantic: &SemanticModel) -> bool { // Handle tuple[...] subscript if let Expr::Subscript(subscript) = expr { // Check if it's tuple or typing.Tuple if semantic.match_builtin_expr(subscript.value.as_ref(), "tuple") || semantic.match_typing_expr(subscript.value.as_ref(), "Tuple") { // Check the slice - tuple[T1, T2] if let Expr::Tuple(tuple_slice) = subscript.slice.as_ref() { return tuple_slice.elts.len() == 2; } return false; } } false }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bad_staticmethod_argument.rs
crates/ruff_linter/src/rules/pylint/rules/bad_staticmethod_argument.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::ParameterWithDefault; use ruff_python_semantic::Scope; use ruff_python_semantic::analyze::function_type; use ruff_python_semantic::analyze::function_type::FunctionType; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for static methods that use `self` or `cls` as their first argument. /// This rule also applies to `__new__` methods, which are implicitly static. /// /// ## Why is this bad? /// [PEP 8] recommends the use of `self` and `cls` as the first arguments for /// instance methods and class methods, respectively. Naming the first argument /// of a static method as `self` or `cls` can be misleading, as static methods /// do not receive an instance or class reference as their first argument. /// /// ## Example /// ```python /// class Wolf: /// @staticmethod /// def eat(self): /// pass /// ``` /// /// Use instead: /// ```python /// class Wolf: /// @staticmethod /// def eat(sheep): /// pass /// ``` /// /// ## Options /// /// - `lint.pep8-naming.classmethod-decorators` /// - `lint.pep8-naming.staticmethod-decorators` /// /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.6.0")] pub(crate) struct BadStaticmethodArgument { argument_name: String, } impl Violation for BadStaticmethodArgument { #[derive_message_formats] fn message(&self) -> String { let Self { argument_name } = self; format!("First argument of a static method should not be named `{argument_name}`") } } /// PLW0211 pub(crate) fn bad_staticmethod_argument(checker: &Checker, scope: &Scope) { let Some(func) = scope.kind.as_function() else { return; }; let ast::StmtFunctionDef { name, decorator_list, parameters, .. } = func; let Some(parent) = checker.semantic().first_non_type_parent_scope(scope) else { return; }; let type_ = function_type::classify( name, decorator_list, parent, checker.semantic(), &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ); match type_ { FunctionType::StaticMethod | FunctionType::NewMethod => {} FunctionType::Function | FunctionType::Method | FunctionType::ClassMethod => { return; } } let Some(ParameterWithDefault { parameter: self_or_cls, .. }) = parameters .posonlyargs .first() .or_else(|| parameters.args.first()) else { return; }; match (name.as_str(), self_or_cls.name.as_str()) { ("__new__", "cls") => { return; } (_, "self" | "cls") => {} _ => return, } checker.report_diagnostic( BadStaticmethodArgument { argument_name: self_or_cls.name.to_string(), }, self_or_cls.range(), ); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/len_test.rs
crates/ruff_linter/src/rules/pylint/rules/len_test.rs
use ruff_diagnostics::Applicability; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall}; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType}; use ruff_python_semantic::analyze::typing::find_binding_value; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits; use crate::fix::snippet::SourceCodeSnippet; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for `len` calls on sequences in a boolean test context. /// /// ## Why is this bad? /// Empty sequences are considered false in a boolean context. /// You can either remove the call to `len` /// or compare the length against a scalar. /// /// ## Example /// ```python /// fruits = ["orange", "apple"] /// vegetables = [] /// /// if len(fruits): /// print(fruits) /// /// if not len(vegetables): /// print(vegetables) /// ``` /// /// Use instead: /// ```python /// fruits = ["orange", "apple"] /// vegetables = [] /// /// if fruits: /// print(fruits) /// /// if not vegetables: /// print(vegetables) /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe when the `len` call includes a comment, /// as the comment would be removed. /// /// For example, the fix would be marked as unsafe in the following case: /// ```python /// fruits = [] /// if len( /// fruits # comment /// ): /// ... /// ``` /// /// ## References /// [PEP 8: Programming Recommendations](https://peps.python.org/pep-0008/#programming-recommendations) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.10.0")] pub(crate) struct LenTest { expression: SourceCodeSnippet, } impl AlwaysFixableViolation for LenTest { #[derive_message_formats] fn message(&self) -> String { if let Some(expression) = self.expression.full_display() { format!("`len({expression})` used as condition without comparison") } else { "`len(SEQUENCE)` used as condition without comparison".to_string() } } fn fix_title(&self) -> String { "Remove `len`".to_string() } } /// PLC1802 pub(crate) fn len_test(checker: &Checker, call: &ExprCall) { let ExprCall { func, arguments, .. } = call; let semantic = checker.semantic(); if !semantic.in_boolean_test() { return; } if !semantic.match_builtin_expr(func, "len") { return; } // Single argument and no keyword arguments let [argument] = &*arguments.args else { return }; if !arguments.keywords.is_empty() { return; } // Simple inferred sequence type (e.g., list, set, dict, tuple, string, bytes, varargs, kwargs). if !is_sequence(argument, semantic) && !is_indirect_sequence(argument, semantic) { return; } let replacement = checker.locator().slice(argument.range()).to_string(); checker .report_diagnostic( LenTest { expression: SourceCodeSnippet::new(replacement.clone()), }, call.range(), ) .set_fix(Fix::applicable_edit( Edit::range_replacement( edits::pad(replacement, call.range(), checker.locator()), call.range(), ), if checker.comment_ranges().intersects(call.range()) { Applicability::Unsafe } else { Applicability::Safe }, )); } fn is_indirect_sequence(expr: &Expr, semantic: &SemanticModel) -> bool { let Expr::Name(ast::ExprName { id: name, .. }) = expr else { return false; }; let scope = semantic.current_scope(); let Some(binding_id) = scope.get(name) else { return false; }; let binding = semantic.binding(binding_id); // Attempt to find the binding's value let Some(binding_value) = find_binding_value(binding, semantic) else { // If the binding is not an argument, return false if !binding.kind.is_argument() { return false; } // Attempt to retrieve the function definition statement let Some(function) = binding .statement(semantic) .and_then(|statement| statement.as_function_def_stmt()) else { return false; }; // If not find in non-default params, it must be varargs or kwargs return function.parameters.find(name).is_none(); }; // If `binding_value` is found, check if it is a sequence is_sequence(binding_value, semantic) } fn is_sequence(expr: &Expr, semantic: &SemanticModel) -> bool { // Check if the expression type is a direct sequence match (dict, list, set, tuple, string or bytes) if matches!( ResolvedPythonType::from(expr), ResolvedPythonType::Atom( PythonType::Dict | PythonType::List | PythonType::Set | PythonType::Tuple | PythonType::String | PythonType::Bytes ) ) { return true; } // Check if the expression is a function call to a built-in sequence constructor let Some(ExprCall { func, .. }) = expr.as_call_expr() else { return false; }; // Match against specific built-in constructors that return sequences semantic.resolve_builtin_symbol(func).is_some_and(|func| { matches!( func, "chr" | "format" | "input" | "repr" | "str" | "list" | "dir" | "locals" | "globals" | "vars" | "dict" | "set" | "frozenset" | "tuple" | "range" | "bin" | "bytes" | "bytearray" | "hex" | "memoryview" | "oct" | "ascii" | "sorted" ) }) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/yield_from_in_async_function.rs
crates/ruff_linter/src/rules/pylint/rules/yield_from_in_async_function.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; /// ## What it does /// Checks for uses of `yield from` in async functions. /// /// ## Why is this bad? /// Python doesn't support the use of `yield from` in async functions, and will /// raise a `SyntaxError` in such cases. /// /// Instead, considering refactoring the code to use an `async for` loop instead. /// /// ## Example /// ```python /// async def numbers(): /// yield from [1, 2, 3, 4, 5] /// ``` /// /// Use instead: /// ```python /// async def numbers(): /// async for number in [1, 2, 3, 4, 5]: /// yield number /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.271")] pub(crate) struct YieldFromInAsyncFunction; impl Violation for YieldFromInAsyncFunction { #[derive_message_formats] fn message(&self) -> String { "`yield from` statement in async function; use `async for` instead".to_string() } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/modified_iterating_set.rs
crates/ruff_linter/src/rules/pylint/rules/modified_iterating_set.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::any_over_body; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr, StmtFor}; use ruff_python_semantic::analyze::typing::is_set; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for loops in which a `set` is modified during iteration. /// /// ## Why is this bad? /// If a `set` is modified during iteration, it will cause a `RuntimeError`. /// /// If you need to modify a `set` within a loop, consider iterating over a copy /// of the `set` instead. /// /// ## Known problems /// This rule favors false negatives over false positives. Specifically, it /// will only detect variables that can be inferred to be a `set` type based on /// local type inference, and will only detect modifications that are made /// directly on the variable itself (e.g., `set.add()`), as opposed to /// modifications within other function calls (e.g., `some_function(set)`). /// /// ## Example /// ```python /// nums = {1, 2, 3} /// for num in nums: /// nums.add(num + 5) /// ``` /// /// Use instead: /// ```python /// nums = {1, 2, 3} /// for num in nums.copy(): /// nums.add(num + 5) /// ``` /// /// ## Fix safety /// This fix is always unsafe because it changes the program’s behavior. Replacing the /// original set with a copy during iteration allows code that would previously raise a /// `RuntimeError` to run without error. /// /// ## References /// - [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.3.5")] pub(crate) struct ModifiedIteratingSet { name: Name, } impl AlwaysFixableViolation for ModifiedIteratingSet { #[derive_message_formats] fn message(&self) -> String { let ModifiedIteratingSet { name } = self; format!("Iterated set `{name}` is modified within the `for` loop",) } fn fix_title(&self) -> String { let ModifiedIteratingSet { name } = self; format!("Iterate over a copy of `{name}`") } } /// PLE4703 pub(crate) fn modified_iterating_set(checker: &Checker, for_stmt: &StmtFor) { let Some(name) = for_stmt.iter.as_name_expr() else { return; }; let Some(binding_id) = checker.semantic().only_binding(name) else { return; }; if !is_set(checker.semantic().binding(binding_id), checker.semantic()) { return; } let is_modified = any_over_body(&for_stmt.body, &|expr| { let Some(func) = expr.as_call_expr().map(|call| &call.func) else { return false; }; let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else { return false; }; let Some(value) = value.as_name_expr() else { return false; }; let Some(value_id) = checker.semantic().only_binding(value) else { return false; }; binding_id == value_id && modifies_set(attr.as_str()) }); if is_modified { let mut diagnostic = checker.report_diagnostic( ModifiedIteratingSet { name: name.id.clone(), }, for_stmt.range(), ); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("{}.copy()", checker.locator().slice(name)), name.range(), ))); } } /// Returns `true` if the method modifies the set. fn modifies_set(identifier: &str) -> bool { matches!(identifier, "add" | "clear" | "discard" | "pop" | "remove") }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/no_self_use.rs
crates/ruff_linter/src/rules/pylint/rules/no_self_use.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::{ Scope, ScopeId, ScopeKind, analyze::{function_type, visibility}, }; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_unused_arguments::rules::is_not_implemented_stub_with_variable; /// ## What it does /// Checks for the presence of unused `self` parameter in methods definitions. /// /// ## Why is this bad? /// Unused `self` parameters are usually a sign of a method that could be /// replaced by a function, class method, or static method. /// /// This rule exempts methods decorated with [`@typing.override`][override]. /// Converting an instance method into a static method or class method may /// cause type checkers to complain about a violation of the Liskov /// Substitution Principle if it means that the method now incompatibly /// overrides a method defined on a superclass. Explicitly decorating an /// overriding method with `@override` signals to Ruff that the method is /// intended to override a superclass method and that a type checker will /// enforce that it does so; Ruff therefore knows that it should not enforce /// rules about unused `self` parameters on such methods. /// /// ## Example /// ```python /// class Person: /// def greeting(self): /// print("Greetings friend!") /// ``` /// /// Use instead: /// ```python /// def greeting(): /// print("Greetings friend!") /// ``` /// /// or /// /// ```python /// class Person: /// @staticmethod /// def greeting(): /// print("Greetings friend!") /// ``` /// /// ## Options /// /// The rule will not trigger on methods that are already marked as static or class methods. /// /// - `lint.pep8-naming.classmethod-decorators` /// - `lint.pep8-naming.staticmethod-decorators` /// /// [override]: https://docs.python.org/3/library/typing.html#typing.override #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.0.286")] pub(crate) struct NoSelfUse { method_name: String, } impl Violation for NoSelfUse { #[derive_message_formats] fn message(&self) -> String { let NoSelfUse { method_name } = self; format!("Method `{method_name}` could be a function, class method, or static method") } } /// PLR6301 pub(crate) fn no_self_use(checker: &Checker, scope_id: ScopeId, scope: &Scope) { let semantic = checker.semantic(); let Some(parent) = semantic.first_non_type_parent_scope(scope) else { return; }; let ScopeKind::Function(func) = scope.kind else { return; }; let ast::StmtFunctionDef { name, parameters, decorator_list, .. } = func; if !matches!( function_type::classify( name, decorator_list, parent, semantic, &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ), function_type::FunctionType::Method ) { return; } let extra_property_decorators = checker.settings().pydocstyle.property_decorators(); if function_type::is_stub(func, semantic) || visibility::is_magic(name) || visibility::is_abstract(decorator_list, semantic) || visibility::is_override(decorator_list, semantic) || visibility::is_overload(decorator_list, semantic) || visibility::is_property(decorator_list, extra_property_decorators, semantic) || visibility::is_validator(decorator_list, semantic) || is_not_implemented_stub_with_variable(func, semantic) { return; } // Identify the `self` parameter. let Some(parameter) = parameters.posonlyargs.iter().chain(&parameters.args).next() else { return; }; if parameter.name() != "self" { return; } // If the method contains a `super` reference, then it should be considered to use self // implicitly. if let Some(binding_id) = semantic.global_scope().get("super") { let binding = semantic.binding(binding_id); if binding.kind.is_builtin() { if binding .references() .any(|id| semantic.reference(id).scope_id() == scope_id) { return; } } } if scope .get("self") .map(|binding_id| semantic.binding(binding_id)) .is_some_and(|binding| binding.kind.is_argument() && binding.is_unused()) { let mut diagnostic = checker.report_diagnostic( NoSelfUse { method_name: name.to_string(), }, func.identifier(), ); diagnostic.help( "Consider adding `@typing.override` if this method overrides \ a method from a superclass", ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_str_return.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_str_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast}; use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::terminal::Terminal; use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `__str__` implementations that return a type other than `str`. /// /// ## Why is this bad? /// The `__str__` method should return a `str` object. Returning a different /// type may cause unexpected behavior. /// /// ## Example /// ```python /// class Foo: /// def __str__(self): /// return True /// ``` /// /// Use instead: /// ```python /// class Foo: /// def __str__(self): /// return "Foo" /// ``` /// /// ## References /// - [Python documentation: The `__str__` method](https://docs.python.org/3/reference/datamodel.html#object.__str__) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.271")] pub(crate) struct InvalidStrReturnType; impl Violation for InvalidStrReturnType { #[derive_message_formats] fn message(&self) -> String { "`__str__` does not return `str`".to_string() } } /// PLE0307 pub(crate) fn invalid_str_return(checker: &Checker, function_def: &ast::StmtFunctionDef) { if function_def.name.as_str() != "__str__" { return; } if !checker.semantic().current_scope().kind.is_class() { return; } if is_stub(function_def, checker.semantic()) { return; } // Determine the terminal behavior (i.e., implicit return, no return, etc.). let terminal = Terminal::from_function(function_def); // If every control flow path raises an exception, ignore the function. if terminal == Terminal::Raise { return; } // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { checker.report_diagnostic(InvalidStrReturnType, function_def.identifier()); return; } let returns = { let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(&function_def.body); visitor.returns }; for stmt in returns { if let Some(value) = stmt.value.as_deref() { if !matches!( ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::String) ) { checker.report_diagnostic(InvalidStrReturnType, value.range()); } } else { // Disallow implicit `None`. checker.report_diagnostic(InvalidStrReturnType, stmt.range()); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/repeated_keyword_argument.rs
crates/ruff_linter/src/rules/pylint/rules/repeated_keyword_argument.rs
use rustc_hash::{FxBuildHasher, FxHashSet}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprCall, ExprStringLiteral}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for repeated keyword arguments in function calls. /// /// ## Why is this bad? /// Python does not allow repeated keyword arguments in function calls. If a /// function is called with the same keyword argument multiple times, the /// interpreter will raise an exception. /// /// ## Example /// ```python /// func(1, 2, c=3, **{"c": 4}) /// ``` /// /// ## References /// - [Python documentation: Argument](https://docs.python.org/3/glossary.html#term-argument) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct RepeatedKeywordArgument { duplicate_keyword: String, } impl Violation for RepeatedKeywordArgument { #[derive_message_formats] fn message(&self) -> String { let Self { duplicate_keyword } = self; format!("Repeated keyword argument: `{duplicate_keyword}`") } } /// PLE1132 pub(crate) fn repeated_keyword_argument(checker: &Checker, call: &ExprCall) { let ExprCall { arguments, .. } = call; let mut seen = FxHashSet::with_capacity_and_hasher(arguments.keywords.len(), FxBuildHasher); for keyword in &*arguments.keywords { if let Some(id) = &keyword.arg { // Ex) `func(a=1, a=2)` if !seen.insert(id.as_str()) { checker.report_diagnostic( RepeatedKeywordArgument { duplicate_keyword: id.to_string(), }, keyword.range(), ); } } else if let Expr::Dict(dict) = &keyword.value { // Ex) `func(**{"a": 1, "a": 2})` for key in dict.iter_keys().flatten() { if let Expr::StringLiteral(ExprStringLiteral { value, .. }) = key { if !seen.insert(value.to_str()) { checker.report_diagnostic( RepeatedKeywordArgument { duplicate_keyword: value.to_string(), }, key.range(), ); } } } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/global_variable_not_assigned.rs
crates/ruff_linter/src/rules/pylint/rules/global_variable_not_assigned.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{ResolvedReference, Scope}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `global` variables that are not assigned a value in the current /// scope. /// /// ## Why is this bad? /// The `global` keyword allows an inner scope to modify a variable declared /// in the outer scope. If the variable is not modified within the inner scope, /// there is no need to use `global`. /// /// ## Example /// ```python /// DEBUG = True /// /// /// def foo(): /// global DEBUG /// if DEBUG: /// print("foo() called") /// ... /// ``` /// /// Use instead: /// ```python /// DEBUG = True /// /// /// def foo(): /// if DEBUG: /// print("foo() called") /// ... /// ``` /// /// ## References /// - [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.174")] pub(crate) struct GlobalVariableNotAssigned { name: String, } impl Violation for GlobalVariableNotAssigned { #[derive_message_formats] fn message(&self) -> String { let GlobalVariableNotAssigned { name } = self; format!("Using global for `{name}` but no assignment is done") } } /// PLW0602 pub(crate) fn global_variable_not_assigned(checker: &Checker, scope: &Scope) { for (name, binding_id) in scope.bindings() { let binding = checker.semantic().binding(binding_id); // If the binding is a `global`, then it's a top-level `global` that was never // assigned in the current scope. If it were assigned, the `global` would be // shadowed by the assignment. if binding.kind.is_global() { // If the binding was conditionally deleted, it will include a reference within // a `Del` context, but won't be shadowed by a `BindingKind::Deletion`, as in: // ```python // if condition: // del var // ``` if binding .references .iter() .map(|id| checker.semantic().reference(*id)) .all(ResolvedReference::is_load) { checker.report_diagnostic( GlobalVariableNotAssigned { name: (*name).to_string(), }, binding.range(), ); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unnecessary_dict_index_lookup.rs
crates/ruff_linter/src/rules/pylint/rules/unnecessary_dict_index_lookup.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, StmtFor}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::SequenceIndexVisitor; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for key-based dict accesses during `.items()` iterations. /// /// ## Why is this bad? /// When iterating over a dict via `.items()`, the current value is already /// available alongside its key. Using the key to look up the value is /// unnecessary. /// /// ## Example /// ```python /// FRUITS = {"apple": 1, "orange": 10, "berry": 22} /// /// for fruit_name, fruit_count in FRUITS.items(): /// print(FRUITS[fruit_name]) /// ``` /// /// Use instead: /// ```python /// FRUITS = {"apple": 1, "orange": 10, "berry": 22} /// /// for fruit_name, fruit_count in FRUITS.items(): /// print(fruit_count) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.12.0")] pub(crate) struct UnnecessaryDictIndexLookup; impl AlwaysFixableViolation for UnnecessaryDictIndexLookup { #[derive_message_formats] fn message(&self) -> String { "Unnecessary lookup of dictionary value by key".to_string() } fn fix_title(&self) -> String { "Use existing variable".to_string() } } /// PLR1733 pub(crate) fn unnecessary_dict_index_lookup(checker: &Checker, stmt_for: &StmtFor) { let Some((dict_name, index_name, value_name)) = dict_items(&stmt_for.iter, &stmt_for.target) else { return; }; let ranges = { let mut visitor = SequenceIndexVisitor::new(&dict_name.id, &index_name.id, &value_name.id); visitor.visit_body(&stmt_for.body); visitor.visit_body(&stmt_for.orelse); visitor.into_accesses() }; for range in ranges { let mut diagnostic = checker.report_diagnostic(UnnecessaryDictIndexLookup, range); diagnostic.set_fix(Fix::safe_edits( Edit::range_replacement(value_name.id.to_string(), range), [noop(index_name), noop(value_name)], )); } } /// PLR1733 pub(crate) fn unnecessary_dict_index_lookup_comprehension(checker: &Checker, expr: &Expr) { let (Expr::Generator(ast::ExprGenerator { elt, generators, .. }) | Expr::DictComp(ast::ExprDictComp { value: elt, generators, .. }) | Expr::SetComp(ast::ExprSetComp { elt, generators, .. }) | Expr::ListComp(ast::ExprListComp { elt, generators, .. })) = expr else { return; }; for comp in generators { let Some((dict_name, index_name, value_name)) = dict_items(&comp.iter, &comp.target) else { continue; }; let ranges = { let mut visitor = SequenceIndexVisitor::new(&dict_name.id, &index_name.id, &value_name.id); visitor.visit_expr(elt.as_ref()); for expr in &comp.ifs { visitor.visit_expr(expr); } visitor.into_accesses() }; for range in ranges { let mut diagnostic = checker.report_diagnostic(UnnecessaryDictIndexLookup, range); diagnostic.set_fix(Fix::safe_edits( Edit::range_replacement(value_name.id.to_string(), range), [noop(index_name), noop(value_name)], )); } } } fn dict_items<'a>( call_expr: &'a Expr, tuple_expr: &'a Expr, ) -> Option<(&'a ast::ExprName, &'a ast::ExprName, &'a ast::ExprName)> { let ast::ExprCall { func, arguments, .. } = call_expr.as_call_expr()?; if !arguments.is_empty() { return None; } let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else { return None; }; if attr != "items" { return None; } let Expr::Name(dict_name) = value.as_ref() else { return None; }; let Expr::Tuple(ast::ExprTuple { elts, .. }) = tuple_expr else { return None; }; let [index, value] = elts.as_slice() else { return None; }; // Grab the variable names. let Expr::Name(index_name) = index else { return None; }; let Expr::Name(value_name) = value else { return None; }; // If either of the variable names are intentionally ignored by naming them `_`, then don't // emit. if index_name.id == "_" || value_name.id == "_" { return None; } Some((dict_name, index_name, value_name)) } /// Return a no-op edit for the given name. fn noop(name: &ast::ExprName) -> Edit { Edit::range_replacement(name.id.to_string(), name.range()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/non_ascii_name.rs
crates/ruff_linter/src/rules/pylint/rules/non_ascii_name.rs
use std::fmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Binding, BindingKind}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for the use of non-ASCII characters in variable names. /// /// ## Why is this bad? /// The use of non-ASCII characters in variable names can cause confusion /// and compatibility issues (see: [PEP 672]). /// /// ## Example /// ```python /// ápple_count: int /// ``` /// /// Use instead: /// ```python /// apple_count: int /// ``` /// /// [PEP 672]: https://peps.python.org/pep-0672/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct NonAsciiName { name: String, kind: Kind, } impl Violation for NonAsciiName { #[derive_message_formats] fn message(&self) -> String { let Self { name, kind } = self; format!("{kind} name `{name}` contains a non-ASCII character") } fn fix_title(&self) -> Option<String> { Some("Rename the variable using ASCII characters".to_string()) } } /// PLC2401 pub(crate) fn non_ascii_name(checker: &Checker, binding: &Binding) { let locator = checker.locator(); let name = binding.name(locator.contents()); if name.is_ascii() { return; } let kind = match binding.kind { BindingKind::Annotation => Kind::Annotation, BindingKind::Argument => Kind::Argument, BindingKind::NamedExprAssignment => Kind::NamedExprAssignment, BindingKind::Assignment => Kind::Assignment, BindingKind::TypeParam => Kind::TypeParam, BindingKind::LoopVar => Kind::LoopVar, BindingKind::WithItemVar => Kind::WithItemVar, BindingKind::Global(_) => Kind::Global, BindingKind::Nonlocal(_, _) => Kind::Nonlocal, BindingKind::ClassDefinition(_) => Kind::ClassDefinition, BindingKind::FunctionDefinition(_) => Kind::FunctionDefinition, BindingKind::BoundException => Kind::BoundException, BindingKind::Builtin | BindingKind::Export(_) | BindingKind::FutureImport | BindingKind::Import(_) | BindingKind::FromImport(_) | BindingKind::SubmoduleImport(_) | BindingKind::Deletion | BindingKind::ConditionalDeletion(_) | BindingKind::UnboundException(_) | BindingKind::DunderClassCell => { return; } }; checker.report_diagnostic( NonAsciiName { name: name.to_string(), kind, }, binding.range(), ); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum Kind { Annotation, Argument, NamedExprAssignment, Assignment, TypeParam, LoopVar, WithItemVar, Global, Nonlocal, ClassDefinition, FunctionDefinition, BoundException, } impl fmt::Display for Kind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Kind::Annotation => f.write_str("Annotation"), Kind::Argument => f.write_str("Argument"), Kind::NamedExprAssignment => f.write_str("Variable"), Kind::Assignment => f.write_str("Variable"), Kind::TypeParam => f.write_str("Type parameter"), Kind::LoopVar => f.write_str("Variable"), Kind::WithItemVar => f.write_str("Variable"), Kind::Global => f.write_str("Global"), Kind::Nonlocal => f.write_str("Nonlocal"), Kind::ClassDefinition => f.write_str("Class"), Kind::FunctionDefinition => f.write_str("Function"), Kind::BoundException => f.write_str("Exception"), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_return_statements.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_return_statements.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; use crate::{Violation, checkers::ast::Checker}; /// ## What it does /// Checks for functions or methods with too many return statements. /// /// By default, this rule allows up to six return statements, as configured by /// the [`lint.pylint.max-returns`] option. /// /// ## Why is this bad? /// Functions or methods with many return statements are harder to understand /// and maintain, and often indicative of complex logic. /// /// ## Example /// ```python /// def capital(country: str) -> str | None: /// if country == "England": /// return "London" /// elif country == "France": /// return "Paris" /// elif country == "Poland": /// return "Warsaw" /// elif country == "Romania": /// return "Bucharest" /// elif country == "Spain": /// return "Madrid" /// elif country == "Thailand": /// return "Bangkok" /// else: /// return None /// ``` /// /// Use instead: /// ```python /// def capital(country: str) -> str | None: /// capitals = { /// "England": "London", /// "France": "Paris", /// "Poland": "Warsaw", /// "Romania": "Bucharest", /// "Spain": "Madrid", /// "Thailand": "Bangkok", /// } /// return capitals.get(country) /// ``` /// /// ## Options /// - `lint.pylint.max-returns` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.242")] pub(crate) struct TooManyReturnStatements { returns: usize, max_returns: usize, } impl Violation for TooManyReturnStatements { #[derive_message_formats] fn message(&self) -> String { let TooManyReturnStatements { returns, max_returns, } = self; format!("Too many return statements ({returns} > {max_returns})") } } /// Count the number of return statements in a function or method body. fn num_returns(body: &[Stmt]) -> usize { let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(body); visitor.returns.len() } /// PLR0911 pub(crate) fn too_many_return_statements( checker: &Checker, stmt: &Stmt, body: &[Stmt], max_returns: usize, ) { let returns = num_returns(body); if returns > max_returns { checker.report_diagnostic( TooManyReturnStatements { returns, max_returns, }, stmt.identifier(), ); } } #[cfg(test)] mod tests { use anyhow::Result; use ruff_python_parser::parse_module; use super::num_returns; fn test_helper(source: &str, expected: usize) -> Result<()> { let parsed = parse_module(source)?; assert_eq!(num_returns(parsed.suite()), expected); Ok(()) } #[test] fn if_() -> Result<()> { let source = r" x = 1 if x == 1: # 9 return if x == 2: return if x == 3: return if x == 4: return if x == 5: return if x == 6: return if x == 7: return if x == 8: return if x == 9: return "; test_helper(source, 9)?; Ok(()) } #[test] fn for_else() -> Result<()> { let source = r" for _i in range(10): return else: return "; test_helper(source, 2)?; Ok(()) } #[test] fn async_for_else() -> Result<()> { let source = r" async for _i in range(10): return else: return "; test_helper(source, 2)?; Ok(()) } #[test] fn nested_def_ignored() -> Result<()> { let source = r" def f(): return x = 1 if x == 1: print() else: print() "; test_helper(source, 0)?; Ok(()) } #[test] fn while_nested_if() -> Result<()> { let source = r" x = 1 while x < 10: print() if x == 3: return x += 1 return "; test_helper(source, 2)?; Ok(()) } #[test] fn with_if() -> Result<()> { let source = r" with a as f: return if f == 1: return "; test_helper(source, 2)?; Ok(()) } #[test] fn async_with_if() -> Result<()> { let source = r" async with a as f: return if f == 1: return "; test_helper(source, 2)?; Ok(()) } #[test] fn try_except_except_else_finally() -> Result<()> { let source = r" try: print() return except ValueError: return except Exception: return else: return finally: return "; test_helper(source, 5)?; Ok(()) } #[test] fn class_def_ignored() -> Result<()> { let source = r" class A: def f(self): return def g(self): return "; test_helper(source, 0)?; Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/nonlocal_without_binding.rs
crates/ruff_linter/src/rules/pylint/rules/nonlocal_without_binding.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; /// ## What it does /// Checks for `nonlocal` names without bindings. /// /// ## Why is this bad? /// `nonlocal` names must be bound to a name in an outer scope. /// Violating this rule leads to a `SyntaxError` at runtime. /// /// ## Example /// ```python /// def foo(): /// def get_bar(self): /// nonlocal bar /// ... /// ``` /// /// Use instead: /// ```python /// def foo(): /// bar = 1 /// /// def get_bar(self): /// nonlocal bar /// ... /// ``` /// /// ## References /// - [Python documentation: The `nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) /// - [PEP 3104 – Access to Names in Outer Scopes](https://peps.python.org/pep-3104/) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.174")] pub(crate) struct NonlocalWithoutBinding { pub(crate) name: String, } impl Violation for NonlocalWithoutBinding { #[derive_message_formats] fn message(&self) -> String { let NonlocalWithoutBinding { name } = self; format!("Nonlocal name `{name}` found without binding") } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs
crates/ruff_linter/src/rules/pylint/rules/nan_comparison.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::linter::float::as_nan_float_string_literal; /// ## What it does /// Checks for comparisons against NaN values. /// /// ## Why is this bad? /// Comparing against a NaN value can lead to unexpected results. For example, /// `float("NaN") == float("NaN")` will return `False` and, in general, /// `x == float("NaN")` will always return `False`, even if `x` is `NaN`. /// /// To determine whether a value is `NaN`, use `math.isnan` or `np.isnan` /// instead of comparing against `NaN` directly. /// /// ## Example /// ```python /// if x == float("NaN"): /// pass /// ``` /// /// Use instead: /// ```python /// import math /// /// if math.isnan(x): /// pass /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.12.0")] pub(crate) struct NanComparison { nan: Nan, } impl Violation for NanComparison { #[derive_message_formats] fn message(&self) -> String { match self.nan { Nan::Math => "Comparing against a NaN value; use `math.isnan` instead".to_string(), Nan::NumPy => "Comparing against a NaN value; use `np.isnan` instead".to_string(), } } } /// PLW0177 pub(crate) fn nan_comparison(checker: &Checker, left: &Expr, comparators: &[Expr]) { nan_comparison_impl(checker, std::iter::once(left).chain(comparators)); } /// PLW0177 pub(crate) fn nan_comparison_match(checker: &Checker, cases: &[ast::MatchCase]) { nan_comparison_impl( checker, cases .iter() .filter_map(|case| case.pattern.as_match_value().map(|pattern| &*pattern.value)), ); } fn nan_comparison_impl<'a>(checker: &Checker, comparators: impl Iterator<Item = &'a Expr>) { for expr in comparators { if let Some(qualified_name) = checker.semantic().resolve_qualified_name(expr) { match qualified_name.segments() { ["numpy", "nan" | "NAN" | "NaN"] => { checker.report_diagnostic(NanComparison { nan: Nan::NumPy }, expr.range()); } ["math", "nan"] => { checker.report_diagnostic(NanComparison { nan: Nan::Math }, expr.range()); } _ => continue, } } if is_nan_float(expr, checker.semantic()) { checker.report_diagnostic(NanComparison { nan: Nan::Math }, expr.range()); } } } #[derive(Debug, PartialEq, Eq)] enum Nan { /// `math.isnan` Math, /// `np.isnan` NumPy, } impl std::fmt::Display for Nan { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Nan::Math => fmt.write_str("math"), Nan::NumPy => fmt.write_str("numpy"), } } } /// Returns `true` if the expression is a call to `float("NaN")`. fn is_nan_float(expr: &Expr, semantic: &SemanticModel) -> bool { let Expr::Call(ast::ExprCall { func, arguments: ast::Arguments { args, keywords, .. }, .. }) = expr else { return false; }; if !keywords.is_empty() { return false; } let [expr] = &**args else { return false; }; if as_nan_float_string_literal(expr).is_none() { return false; } semantic.match_builtin_expr(func, "float") }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/shallow_copy_environ.rs
crates/ruff_linter/src/rules/pylint/rules/shallow_copy_environ.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Check for shallow `os.environ` copies. /// /// ## Why is this bad? /// `os.environ` is not a `dict` object, but rather, a proxy object. As such, mutating a shallow /// copy of `os.environ` will also mutate the original object. /// /// See [BPO 15373] for more information. /// /// ## Example /// ```python /// import copy /// import os /// /// env = copy.copy(os.environ) /// ``` /// /// Use instead: /// ```python /// import os /// /// env = os.environ.copy() /// ``` /// /// ## Fix safety /// /// This rule's fix is marked as unsafe because replacing a shallow copy with a deep copy can lead /// to unintended side effects. If the program modifies the shallow copy at some point, changing it /// to a deep copy may prevent those modifications from affecting the original data, potentially /// altering the program's behavior. /// /// ## References /// - [Python documentation: `copy` — Shallow and deep copy operations](https://docs.python.org/3/library/copy.html) /// - [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ) /// /// [BPO 15373]: https://bugs.python.org/issue15373 #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.10.0")] pub(crate) struct ShallowCopyEnviron; impl AlwaysFixableViolation for ShallowCopyEnviron { #[derive_message_formats] fn message(&self) -> String { "Shallow copy of `os.environ` via `copy.copy(os.environ)`".to_string() } fn fix_title(&self) -> String { "Replace with `os.environ.copy()`".to_string() } } /// PLW1507 pub(crate) fn shallow_copy_environ(checker: &Checker, call: &ast::ExprCall) { if !(checker.semantic().seen_module(Modules::OS) && checker.semantic().seen_module(Modules::COPY)) { return; } if !checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["copy", "copy"])) { return; } if !call.arguments.keywords.is_empty() { return; } let [arg] = call.arguments.args.as_ref() else { return; }; if !checker .semantic() .resolve_qualified_name(arg) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["os", "environ"])) { return; } let mut diagnostic = checker.report_diagnostic(ShallowCopyEnviron, call.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( format!("{}.copy()", checker.locator().slice(arg)), call.range(), ))); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/and_or_ternary.rs
crates/ruff_linter/src/rules/pylint/rules/and_or_ternary.rs
use ruff_macros::ViolationMetadata; use crate::Violation; /// ## Removal /// This rule was removed from Ruff because it was common for it to introduce behavioral changes. /// See [#9007](https://github.com/astral-sh/ruff/issues/9007) for more information. /// /// ## What it does /// Checks for uses of the known pre-Python 2.5 ternary syntax. /// /// ## Why is this bad? /// Prior to the introduction of the if-expression (ternary) operator in Python /// 2.5, the only way to express a conditional expression was to use the `and` /// and `or` operators. /// /// The if-expression construct is clearer and more explicit, and should be /// preferred over the use of `and` and `or` for ternary expressions. /// /// ## Example /// ```python /// x, y = 1, 2 /// maximum = x >= y and x or y /// ``` /// /// Use instead: /// ```python /// x, y = 1, 2 /// maximum = x if x >= y else y /// ``` #[derive(ViolationMetadata)] #[violation_metadata(removed_since = "v0.2.0")] pub(crate) struct AndOrTernary; /// PLR1706 impl Violation for AndOrTernary { fn message(&self) -> String { unreachable!("PLR1706 has been removed"); } fn message_formats() -> &'static [&'static str] { &["Consider using if-else expression"] } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/non_slot_assignment.rs
crates/ruff_linter/src/rules/pylint/rules/non_slot_assignment.rs
use rustc_hash::FxHashSet; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::{Ranged, TextRange}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for assignments to attributes that are not defined in `__slots__`. /// /// ## Why is this bad? /// When using `__slots__`, only the specified attributes are allowed. /// Attempting to assign to an attribute that is not defined in `__slots__` /// will result in an `AttributeError` at runtime. /// /// ## Known problems /// This rule can't detect `__slots__` implementations in superclasses, and /// so limits its analysis to classes that inherit from (at most) `object`. /// /// ## Example /// ```python /// class Student: /// __slots__ = ("name",) /// /// def __init__(self, name, surname): /// self.name = name /// self.surname = surname # [assigning-non-slot] /// self.setup() /// /// def setup(self): /// pass /// ``` /// /// Use instead: /// ```python /// class Student: /// __slots__ = ("name", "surname") /// /// def __init__(self, name, surname): /// self.name = name /// self.surname = surname /// self.setup() /// /// def setup(self): /// pass /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.1.15")] pub(crate) struct NonSlotAssignment { name: String, } impl Violation for NonSlotAssignment { #[derive_message_formats] fn message(&self) -> String { let NonSlotAssignment { name } = self; format!("Attribute `{name}` is not defined in class's `__slots__`") } } /// PLE0237 pub(crate) fn non_slot_assignment(checker: &Checker, class_def: &ast::StmtClassDef) { let semantic = checker.semantic(); // If the class inherits from another class (aside from `object`), then it's possible that // the parent class defines the relevant `__slots__`. if !class_def .bases() .iter() .all(|base| semantic.match_builtin_expr(base, "object")) { return; } for attribute in is_attributes_not_in_slots(&class_def.body) { checker.report_diagnostic( NonSlotAssignment { name: attribute.name.to_string(), }, attribute.range(), ); } } #[derive(Debug)] struct AttributeAssignment<'a> { /// The name of the attribute that is assigned to. name: &'a str, /// The range of the attribute that is assigned to. range: TextRange, } impl Ranged for AttributeAssignment<'_> { fn range(&self) -> TextRange { self.range } } /// Return a list of attributes that are assigned to but not included in `__slots__`. /// /// If the `__slots__` attribute cannot be statically determined, returns an empty vector. fn is_attributes_not_in_slots(body: &[Stmt]) -> Vec<AttributeAssignment<'_>> { // First, collect all the attributes that are assigned to `__slots__`. let mut slots = FxHashSet::default(); for statement in body { match statement { // Ex) `__slots__ = ("name",)` Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { let [Expr::Name(ast::ExprName { id, .. })] = targets.as_slice() else { continue; }; if id == "__slots__" { for attribute in slots_attributes(value) { if let Some(attribute) = attribute { slots.insert(attribute); } else { return vec![]; } } } } // Ex) `__slots__: Tuple[str, ...] = ("name",)` Stmt::AnnAssign(ast::StmtAnnAssign { target, value: Some(value), .. }) => { let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() else { continue; }; if id == "__slots__" { for attribute in slots_attributes(value) { if let Some(attribute) = attribute { slots.insert(attribute); } else { return vec![]; } } } } // Ex) `__slots__ += ("name",)` Stmt::AugAssign(ast::StmtAugAssign { target, value, .. }) => { let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() else { continue; }; if id == "__slots__" { for attribute in slots_attributes(value) { if let Some(attribute) = attribute { slots.insert(attribute); } else { return vec![]; } } } } _ => {} } } if slots.is_empty() || slots.contains("__dict__") { return vec![]; } // And, collect all the property name with setter. for statement in body { let Stmt::FunctionDef(ast::StmtFunctionDef { decorator_list, .. }) = statement else { continue; }; for decorator in decorator_list { let Some(ast::ExprAttribute { value, attr, .. }) = decorator.expression.as_attribute_expr() else { continue; }; if attr == "setter" { let Some(ast::ExprName { id, .. }) = value.as_name_expr() else { continue; }; slots.insert(id.as_str()); } } } // Second, find any assignments that aren't included in `__slots__`. let mut assignments = vec![]; for statement in body { let Stmt::FunctionDef(ast::StmtFunctionDef { name, body, .. }) = statement else { continue; }; if name == "__init__" { for statement in body { match statement { // Ex) `self.name = name` Stmt::Assign(ast::StmtAssign { targets, .. }) => { let [Expr::Attribute(attribute)] = targets.as_slice() else { continue; }; let Expr::Name(ast::ExprName { id, .. }) = attribute.value.as_ref() else { continue; }; if id == "self" && !slots.contains(attribute.attr.as_str()) { assignments.push(AttributeAssignment { name: &attribute.attr, range: attribute.range(), }); } } // Ex) `self.name: str = name` Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => { let Expr::Attribute(attribute) = target.as_ref() else { continue; }; let Expr::Name(ast::ExprName { id, .. }) = attribute.value.as_ref() else { continue; }; if id == "self" && !slots.contains(attribute.attr.as_str()) { assignments.push(AttributeAssignment { name: &attribute.attr, range: attribute.range(), }); } } // Ex) `self.name += name` Stmt::AugAssign(ast::StmtAugAssign { target, .. }) => { let Expr::Attribute(attribute) = target.as_ref() else { continue; }; let Expr::Name(ast::ExprName { id, .. }) = attribute.value.as_ref() else { continue; }; if id == "self" && !slots.contains(attribute.attr.as_str()) { assignments.push(AttributeAssignment { name: &attribute.attr, range: attribute.range(), }); } } _ => {} } } } } assignments } /// Return an iterator over the attributes enumerated in the given `__slots__` value. /// /// If an attribute can't be statically determined, it will be `None`. fn slots_attributes(expr: &Expr) -> impl Iterator<Item = Option<&str>> { // Ex) `__slots__ = ("name",)` let elts_iter = match expr { Expr::Tuple(ast::ExprTuple { elts, .. }) | Expr::List(ast::ExprList { elts, .. }) | Expr::Set(ast::ExprSet { elts, .. }) => Some(elts.iter().map(|elt| match elt { Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => Some(value.to_str()), _ => None, })), _ => None, }; // Ex) `__slots__ = {"name": ...}` let keys_iter = match expr { Expr::Dict(dict) => Some(dict.iter_keys().map(|key| match key { Some(Expr::StringLiteral(ast::ExprStringLiteral { value, .. })) => Some(value.to_str()), _ => None, })), _ => None, }; elts_iter .into_iter() .flatten() .chain(keys_iter.into_iter().flatten()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/redefined_slots_in_subclass.rs
crates/ruff_linter/src/rules/pylint/rules/redefined_slots_in_subclass.rs
use std::hash::Hash; use ruff_python_semantic::analyze::class::iter_super_class; use rustc_hash::FxHashSet; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::{Ranged, TextRange}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for a re-defined slot in a subclass. /// /// ## Why is this bad? /// If a class defines a slot also defined in a base class, the /// instance variable defined by the base class slot is inaccessible /// (except by retrieving its descriptor directly from the base class). /// /// ## Example /// ```python /// class Base: /// __slots__ = ("a", "b") /// /// /// class Subclass(Base): /// __slots__ = ("a", "d") # slot "a" redefined /// ``` /// /// Use instead: /// ```python /// class Base: /// __slots__ = ("a", "b") /// /// /// class Subclass(Base): /// __slots__ = "d" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.9.3")] pub(crate) struct RedefinedSlotsInSubclass { base: String, slot_name: String, } impl Violation for RedefinedSlotsInSubclass { #[derive_message_formats] fn message(&self) -> String { let RedefinedSlotsInSubclass { base, slot_name } = self; format!("Slot `{slot_name}` redefined from base class `{base}`") } } // PLW0244 pub(crate) fn redefined_slots_in_subclass(checker: &Checker, class_def: &ast::StmtClassDef) { // Early return if this is not a subclass if class_def.bases().is_empty() { return; } let ast::StmtClassDef { body, .. } = class_def; let class_slots = slots_members(body); // If there are no slots, we're safe if class_slots.is_empty() { return; } for slot in class_slots { check_super_slots(checker, class_def, &slot); } } #[derive(Clone, Debug)] struct Slot<'a> { name: &'a str, range: TextRange, } impl std::cmp::PartialEq for Slot<'_> { // We will only ever be comparing slots // within a class and with the slots of // a super class. In that context, we // want to compare names and not ranges. fn eq(&self, other: &Self) -> bool { self.name == other.name } } impl std::cmp::Eq for Slot<'_> {} impl Hash for Slot<'_> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.name.hash(state); } } impl Ranged for Slot<'_> { fn range(&self) -> TextRange { self.range } } fn check_super_slots(checker: &Checker, class_def: &ast::StmtClassDef, slot: &Slot) { for super_class in iter_super_class(class_def, checker.semantic()).skip(1) { if slots_members(&super_class.body).contains(slot) { checker.report_diagnostic( RedefinedSlotsInSubclass { base: super_class.name.to_string(), slot_name: slot.name.to_string(), }, slot.range(), ); } } } fn slots_members(body: &[Stmt]) -> FxHashSet<Slot<'_>> { let mut members = FxHashSet::default(); for stmt in body { match stmt { // Ex) `__slots__ = ("name",)` Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { let [Expr::Name(ast::ExprName { id, .. })] = targets.as_slice() else { continue; }; if id == "__slots__" { members.extend(slots_attributes(value)); } } // Ex) `__slots__: Tuple[str, ...] = ("name",)` Stmt::AnnAssign(ast::StmtAnnAssign { target, value: Some(value), .. }) => { let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() else { continue; }; if id == "__slots__" { members.extend(slots_attributes(value)); } } // Ex) `__slots__ += ("name",)` Stmt::AugAssign(ast::StmtAugAssign { target, value, .. }) => { let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() else { continue; }; if id == "__slots__" { members.extend(slots_attributes(value)); } } _ => {} } } members } fn slots_attributes(expr: &Expr) -> impl Iterator<Item = Slot<'_>> { // Ex) `__slots__ = ("name",)` let elts_iter = match expr { Expr::Tuple(ast::ExprTuple { elts, .. }) | Expr::List(ast::ExprList { elts, .. }) | Expr::Set(ast::ExprSet { elts, .. }) => Some(elts.iter().filter_map(|elt| match elt { Expr::StringLiteral(ast::ExprStringLiteral { value, range, node_index: _, }) => Some(Slot { name: value.to_str(), range: *range, }), _ => None, })), _ => None, }; // Ex) `__slots__ = {"name": ...}` let keys_iter = match expr { Expr::Dict(ast::ExprDict { .. }) => Some( expr.as_dict_expr() .unwrap() .iter_keys() .filter_map(|key| match key { Some(Expr::StringLiteral(ast::ExprStringLiteral { value, range, node_index: _, })) => Some(Slot { name: value.to_str(), range: *range, }), _ => None, }), ), _ => None, }; elts_iter .into_iter() .flatten() .chain(keys_iter.into_iter().flatten()) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/named_expr_without_context.rs
crates/ruff_linter/src/rules/pylint/rules/named_expr_without_context.rs
use ruff_python_ast::{self as ast, Expr}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of named expressions (e.g., `a := 42`) that can be /// replaced by regular assignment statements (e.g., `a = 42`). /// /// ## Why is this bad? /// While a top-level named expression is syntactically and semantically valid, /// it's less clear than a regular assignment statement. Named expressions are /// intended to be used in comprehensions and generator expressions, where /// assignment statements are not allowed. /// /// ## Example /// ```python /// (a := 42) /// ``` /// /// Use instead: /// ```python /// a = 42 /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.270")] pub(crate) struct NamedExprWithoutContext; impl Violation for NamedExprWithoutContext { #[derive_message_formats] fn message(&self) -> String { "Named expression used without context".to_string() } } /// PLW0131 pub(crate) fn named_expr_without_context(checker: &Checker, value: &Expr) { if let Expr::Named(ast::ExprNamed { range, .. }) = value { checker.report_diagnostic(NamedExprWithoutContext, *range); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/duplicate_bases.rs
crates/ruff_linter/src/rules/pylint/rules/duplicate_bases.rs
use ruff_diagnostics::Applicability; use ruff_python_ast::{self as ast, Arguments, Expr}; use rustc_hash::{FxBuildHasher, FxHashSet}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits::{Parentheses, remove_argument}; use crate::{Fix, FixAvailability, Violation}; /// ## What it does /// Checks for duplicate base classes in class definitions. /// /// ## Why is this bad? /// Including duplicate base classes will raise a `TypeError` at runtime. /// /// ## Example /// ```python /// class Foo: /// pass /// /// /// class Bar(Foo, Foo): /// pass /// ``` /// /// Use instead: /// ```python /// class Foo: /// pass /// /// /// class Bar(Foo): /// pass /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe if there's comments in the /// base classes, as comments may be removed. /// /// For example, the fix would be marked as unsafe in the following case: /// ```python /// class Foo: /// pass /// /// /// class Bar( /// Foo, # comment /// Foo, /// ): /// pass /// ``` /// /// ## References /// - [Python documentation: Class definitions](https://docs.python.org/3/reference/compound_stmts.html#class-definitions) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.269")] pub(crate) struct DuplicateBases { base: String, class: String, } impl Violation for DuplicateBases { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { let DuplicateBases { base, class } = self; format!("Duplicate base `{base}` for class `{class}`") } fn fix_title(&self) -> Option<String> { Some("Remove duplicate base".to_string()) } } /// PLE0241 pub(crate) fn duplicate_bases(checker: &Checker, name: &str, arguments: Option<&Arguments>) { let Some(arguments) = arguments else { return; }; let bases = &arguments.args; let mut seen: FxHashSet<&str> = FxHashSet::with_capacity_and_hasher(bases.len(), FxBuildHasher); for base in bases { if let Expr::Name(ast::ExprName { id, .. }) = base { if !seen.insert(id) { let mut diagnostic = checker.report_diagnostic( DuplicateBases { base: id.to_string(), class: name.to_string(), }, base.range(), ); diagnostic.try_set_fix(|| { remove_argument( base, arguments, Parentheses::Remove, checker.locator().contents(), checker.tokens(), ) .map(|edit| { Fix::applicable_edit( edit, if checker.comment_ranges().intersects(arguments.range()) { Applicability::Unsafe } else { Applicability::Safe }, ) }) }); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unspecified_encoding.rs
crates/ruff_linter/src/rules/pylint/rules/unspecified_encoding.rs
use std::fmt::{Display, Formatter}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, name::QualifiedName}; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::typing; use ruff_text_size::{Ranged, TextRange}; use crate::checkers::ast::Checker; use crate::fix::edits::add_argument; use crate::{AlwaysFixableViolation, Fix}; /// ## What it does /// Checks for uses of `open` and related calls without an explicit `encoding` /// argument. /// /// ## Why is this bad? /// Using `open` in text mode without an explicit encoding can lead to /// non-portable code, with differing behavior across platforms. While readers /// may assume that UTF-8 is the default encoding, in reality, the default /// is locale-specific. /// /// Instead, consider using the `encoding` parameter to enforce a specific /// encoding. [PEP 597] recommends the use of `encoding="utf-8"` as a default, /// and suggests that it may become the default in future versions of Python. /// /// If a locale-specific encoding is intended, use `encoding="locale"` on /// Python 3.10 and later, or `locale.getpreferredencoding()` on earlier versions, /// to make the encoding explicit. /// /// ## Fix safety /// This fix is always unsafe and may change the program's behavior. It forces /// `encoding="utf-8"` as the default, regardless of the platform’s actual default /// encoding, which may cause `UnicodeDecodeError` on non-UTF-8 systems. /// ```python /// with open("test.txt") as f: /// print(f.read()) # before fix (on UTF-8 systems): 你好,世界! /// with open("test.txt", encoding="utf-8") as f: /// print(f.read()) # after fix (on Windows): UnicodeDecodeError /// ``` /// /// ## Example /// ```python /// open("file.txt") /// ``` /// /// Use instead: /// ```python /// open("file.txt", encoding="utf-8") /// ``` /// /// ## References /// - [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open) /// /// [PEP 597]: https://peps.python.org/pep-0597/ #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.1")] pub(crate) struct UnspecifiedEncoding { function_name: String, mode: ModeArgument, } impl AlwaysFixableViolation for UnspecifiedEncoding { #[derive_message_formats] fn message(&self) -> String { let UnspecifiedEncoding { function_name, mode, } = self; match mode { ModeArgument::Supported => { format!("`{function_name}` in text mode without explicit `encoding` argument") } ModeArgument::Unsupported => { format!("`{function_name}` without explicit `encoding` argument") } } } fn fix_title(&self) -> String { "Add explicit `encoding` argument".to_string() } } /// PLW1514 pub(crate) fn unspecified_encoding(checker: &Checker, call: &ast::ExprCall) { let Some((function_name, mode)) = Callee::try_from_call_expression(call, checker.semantic()) .filter(|segments| is_violation(call, segments)) .map(|segments| (segments.to_string(), segments.mode_argument())) else { return; }; let mut diagnostic = checker.report_diagnostic( UnspecifiedEncoding { function_name, mode, }, call.func.range(), ); diagnostic.set_fix(generate_keyword_fix(checker, call)); } /// Represents the path of the function or method being called. enum Callee<'a> { /// Fully-qualified symbol name of the callee. Qualified(QualifiedName<'a>), /// Attribute value for the `pathlib.Path(...)` call e.g., `open` in /// `pathlib.Path(...).open(...)`. Pathlib(&'a str), } impl<'a> Callee<'a> { fn is_pathlib_path_call(expr: &Expr, semantic: &SemanticModel) -> bool { if let Expr::Call(ast::ExprCall { func, .. }) = expr { semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["pathlib", "Path"]) }) } else { false } } fn try_from_call_expression( call: &'a ast::ExprCall, semantic: &'a SemanticModel, ) -> Option<Self> { if let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = call.func.as_ref() { // Direct: Path(...).open() if Self::is_pathlib_path_call(value, semantic) { return Some(Callee::Pathlib(attr)); } // Indirect: x.open() where x = Path(...) else if let Expr::Name(name) = value.as_ref() { if let Some(binding_id) = semantic.only_binding(name) { let binding = semantic.binding(binding_id); if typing::is_pathlib_path(binding, semantic) { return Some(Callee::Pathlib(attr)); } } } } if let Some(qualified_name) = semantic.resolve_qualified_name(&call.func) { return Some(Callee::Qualified(qualified_name)); } None } fn mode_argument(&self) -> ModeArgument { match self { Callee::Qualified(qualified_name) => match qualified_name.segments() { ["" | "codecs" | "_io", "open"] => ModeArgument::Supported, [ "tempfile", "TemporaryFile" | "NamedTemporaryFile" | "SpooledTemporaryFile", ] => ModeArgument::Supported, ["io" | "_io", "TextIOWrapper"] => ModeArgument::Unsupported, _ => ModeArgument::Unsupported, }, Callee::Pathlib(attr) => match *attr { "open" => ModeArgument::Supported, _ => ModeArgument::Unsupported, }, } } } impl Display for Callee<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Callee::Qualified(qualified_name) => f.write_str(&qualified_name.to_string()), Callee::Pathlib(attr) => f.write_str(&format!("pathlib.Path(...).{attr}")), } } } /// Generate an [`Edit`] to set `encoding="utf-8"`. fn generate_keyword_fix(checker: &Checker, call: &ast::ExprCall) -> Fix { Fix::unsafe_edit(add_argument( &format!( "encoding={}", checker.generator().expr(&Expr::from(ast::StringLiteral { value: Box::from("utf-8"), flags: checker.default_string_flags(), range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, })) ), &call.arguments, checker.tokens(), )) } /// Returns `true` if the given expression is a string literal containing a `b` character. fn is_binary_mode(expr: &Expr) -> Option<bool> { Some( expr.as_string_literal_expr()? .value .chars() .any(|c| c == 'b'), ) } /// Returns `true` if the given call lacks an explicit `encoding`. fn is_violation(call: &ast::ExprCall, qualified_name: &Callee) -> bool { // If we have something like `*args`, which might contain the encoding argument, abort. if call.arguments.args.iter().any(Expr::is_starred_expr) { return false; } // If we have something like `**kwargs`, which might contain the encoding argument, abort. if call .arguments .keywords .iter() .any(|keyword| keyword.arg.is_none()) { return false; } match qualified_name { Callee::Qualified(qualified_name) => match qualified_name.segments() { ["" | "codecs" | "_io", "open"] => { if let Some(mode_arg) = call.arguments.find_argument_value("mode", 1) { if is_binary_mode(mode_arg).unwrap_or(true) { // binary mode or unknown mode is no violation return false; } } let encoding_param_pos = match qualified_name.segments() { // The `encoding` parameter position for `codecs.open` ["codecs", _] => 2, // The `encoding` parameter position for `_io.open` and the builtin `open` _ => 3, }; // else mode not specified, defaults to text mode call.arguments .find_argument_value("encoding", encoding_param_pos) .is_none() } [ "tempfile", tempfile_class @ ("TemporaryFile" | "NamedTemporaryFile" | "SpooledTemporaryFile"), ] => { let mode_pos = usize::from(*tempfile_class == "SpooledTemporaryFile"); if let Some(mode_arg) = call.arguments.find_argument_value("mode", mode_pos) { if is_binary_mode(mode_arg).unwrap_or(true) { // binary mode or unknown mode is no violation return false; } } else { // defaults to binary mode return false; } call.arguments .find_argument_value("encoding", mode_pos + 2) .is_none() } ["io" | "_io", "TextIOWrapper"] => { call.arguments.find_argument_value("encoding", 1).is_none() } _ => false, }, Callee::Pathlib(attr) => match *attr { "open" => { if let Some(mode_arg) = call.arguments.find_argument_value("mode", 0) { if is_binary_mode(mode_arg).unwrap_or(true) { // binary mode or unknown mode is no violation return false; } } // else mode not specified, defaults to text mode call.arguments.find_argument_value("encoding", 2).is_none() } "read_text" => call.arguments.find_argument_value("encoding", 0).is_none(), "write_text" => call.arguments.find_argument_value("encoding", 1).is_none(), _ => false, }, } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ModeArgument { /// The call supports a `mode` argument. Supported, /// The call does not support a `mode` argument. Unsupported, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/mod.rs
crates/ruff_linter/src/rules/pylint/rules/mod.rs
pub(crate) use and_or_ternary::*; pub(crate) use assert_on_string_literal::*; pub(crate) use await_outside_async::*; pub(crate) use bad_dunder_method_name::*; pub(crate) use bad_open_mode::*; pub(crate) use bad_staticmethod_argument::*; pub(crate) use bad_str_strip_call::*; pub(crate) use bad_string_format_character::BadStringFormatCharacter; pub(crate) use bad_string_format_type::*; pub(crate) use bidirectional_unicode::*; pub(crate) use binary_op_exception::*; pub(crate) use boolean_chained_comparison::*; pub(crate) use collapsible_else_if::*; pub(crate) use compare_to_empty_string::*; pub(crate) use comparison_of_constant::*; pub(crate) use comparison_with_itself::*; pub(crate) use continue_in_finally::*; pub(crate) use dict_index_missing_items::*; pub(crate) use dict_iter_missing_items::*; pub(crate) use duplicate_bases::*; pub(crate) use empty_comment::*; pub(crate) use eq_without_hash::*; pub(crate) use global_at_module_level::*; pub(crate) use global_statement::*; pub(crate) use global_variable_not_assigned::*; pub(crate) use if_stmt_min_max::*; pub(crate) use import_outside_top_level::*; pub(crate) use import_private_name::*; pub(crate) use import_self::*; pub(crate) use invalid_all_format::*; pub(crate) use invalid_all_object::*; pub(crate) use invalid_bool_return::*; pub(crate) use invalid_bytes_return::*; pub(crate) use invalid_envvar_default::*; pub(crate) use invalid_envvar_value::*; pub(crate) use invalid_hash_return::*; pub(crate) use invalid_index_return::*; pub(crate) use invalid_length_return::*; pub(crate) use invalid_str_return::*; pub(crate) use invalid_string_characters::*; pub(crate) use iteration_over_set::*; pub(crate) use len_test::*; pub(crate) use literal_membership::*; pub(crate) use load_before_global_declaration::*; pub(crate) use logging::*; pub(crate) use magic_value_comparison::*; pub(crate) use manual_import_from::*; pub(crate) use misplaced_bare_raise::*; pub(crate) use missing_maxsplit_arg::*; pub(crate) use modified_iterating_set::*; pub(crate) use named_expr_without_context::*; pub(crate) use nan_comparison::*; pub(crate) use nested_min_max::*; pub(crate) use no_method_decorator::*; pub(crate) use no_self_use::*; pub(crate) use non_ascii_module_import::*; pub(crate) use non_ascii_name::*; pub(crate) use non_augmented_assignment::*; pub(crate) use non_slot_assignment::*; pub(crate) use nonlocal_and_global::*; pub(crate) use nonlocal_without_binding::*; pub(crate) use potential_index_error::*; pub(crate) use property_with_parameters::*; pub(crate) use redeclared_assigned_name::*; pub(crate) use redefined_argument_from_local::*; pub(crate) use redefined_loop_name::*; pub(crate) use redefined_slots_in_subclass::*; pub(crate) use repeated_equality_comparison::*; pub(crate) use repeated_isinstance_calls::*; pub(crate) use repeated_keyword_argument::*; pub(crate) use return_in_init::*; pub(crate) use self_assigning_variable::*; pub(crate) use self_or_cls_assignment::*; pub(crate) use shallow_copy_environ::*; pub(crate) use single_string_slots::*; pub(crate) use singledispatch_method::*; pub(crate) use singledispatchmethod_function::*; pub(crate) use stop_iteration_return::*; pub(crate) use subprocess_popen_preexec_fn::*; pub(crate) use subprocess_run_without_check::*; pub(crate) use super_without_brackets::*; pub(crate) use sys_exit_alias::*; pub(crate) use too_many_arguments::*; pub(crate) use too_many_boolean_expressions::*; pub(crate) use too_many_branches::*; pub(crate) use too_many_locals::*; pub(crate) use too_many_nested_blocks::*; pub(crate) use too_many_positional_arguments::*; pub(crate) use too_many_public_methods::*; pub(crate) use too_many_return_statements::*; pub(crate) use too_many_statements::*; pub(crate) use type_bivariance::*; pub(crate) use type_name_incorrect_variance::*; pub(crate) use type_param_name_mismatch::*; pub(crate) use unexpected_special_method_signature::*; pub(crate) use unnecessary_dict_index_lookup::*; pub(crate) use unnecessary_direct_lambda_call::*; pub(crate) use unnecessary_dunder_call::*; pub(crate) use unnecessary_lambda::*; pub(crate) use unnecessary_list_index_lookup::*; #[cfg(any(feature = "test-rules", test))] pub(crate) use unreachable::*; pub(crate) use unspecified_encoding::*; pub(crate) use useless_else_on_loop::*; pub(crate) use useless_exception_statement::*; pub(crate) use useless_import_alias::*; pub(crate) use useless_return::*; pub(crate) use useless_with_lock::*; pub(crate) use yield_from_in_async_function::*; pub(crate) use yield_in_init::*; mod and_or_ternary; mod assert_on_string_literal; mod await_outside_async; mod bad_dunder_method_name; mod bad_open_mode; mod bad_staticmethod_argument; mod bad_str_strip_call; pub(crate) mod bad_string_format_character; mod bad_string_format_type; mod bidirectional_unicode; mod binary_op_exception; mod boolean_chained_comparison; mod collapsible_else_if; mod compare_to_empty_string; mod comparison_of_constant; mod comparison_with_itself; mod continue_in_finally; mod dict_index_missing_items; mod dict_iter_missing_items; mod duplicate_bases; mod empty_comment; mod eq_without_hash; mod global_at_module_level; mod global_statement; mod global_variable_not_assigned; mod if_stmt_min_max; mod import_outside_top_level; mod import_private_name; mod import_self; mod invalid_all_format; mod invalid_all_object; mod invalid_bool_return; mod invalid_bytes_return; mod invalid_envvar_default; mod invalid_envvar_value; mod invalid_hash_return; mod invalid_index_return; mod invalid_length_return; mod invalid_str_return; mod invalid_string_characters; mod iteration_over_set; mod len_test; mod literal_membership; mod load_before_global_declaration; mod logging; mod magic_value_comparison; mod manual_import_from; mod misplaced_bare_raise; mod missing_maxsplit_arg; mod modified_iterating_set; mod named_expr_without_context; mod nan_comparison; mod nested_min_max; mod no_method_decorator; mod no_self_use; mod non_ascii_module_import; mod non_ascii_name; mod non_augmented_assignment; mod non_slot_assignment; mod nonlocal_and_global; mod nonlocal_without_binding; mod potential_index_error; mod property_with_parameters; mod redeclared_assigned_name; mod redefined_argument_from_local; mod redefined_loop_name; mod redefined_slots_in_subclass; mod repeated_equality_comparison; mod repeated_isinstance_calls; mod repeated_keyword_argument; mod return_in_init; mod self_assigning_variable; mod self_or_cls_assignment; mod shallow_copy_environ; mod single_string_slots; mod singledispatch_method; mod singledispatchmethod_function; mod stop_iteration_return; mod subprocess_popen_preexec_fn; mod subprocess_run_without_check; mod super_without_brackets; mod sys_exit_alias; mod too_many_arguments; mod too_many_boolean_expressions; mod too_many_branches; mod too_many_locals; mod too_many_nested_blocks; mod too_many_positional_arguments; mod too_many_public_methods; mod too_many_return_statements; mod too_many_statements; mod type_bivariance; mod type_name_incorrect_variance; mod type_param_name_mismatch; mod unexpected_special_method_signature; mod unnecessary_dict_index_lookup; mod unnecessary_direct_lambda_call; mod unnecessary_dunder_call; mod unnecessary_lambda; mod unnecessary_list_index_lookup; #[cfg(any(feature = "test-rules", test))] mod unreachable; mod unspecified_encoding; mod useless_else_on_loop; mod useless_exception_statement; mod useless_import_alias; mod useless_return; mod useless_with_lock; mod yield_from_in_async_function; mod yield_in_init;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/compare_to_empty_string.rs
crates/ruff_linter/src/rules/pylint/rules/compare_to_empty_string.rs
use anyhow::bail; use itertools::Itertools; use ruff_python_ast::{self as ast, CmpOp, Expr}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for comparisons to empty strings. /// /// ## Why is this bad? /// An empty string is falsy, so it is unnecessary to compare it to `""`. If /// the value can be something else Python considers falsy, such as `None`, /// `0`, or another empty container, then the code is not equivalent. /// /// ## Known problems /// High false positive rate, as the check is context-insensitive and does not /// consider the type of the variable being compared ([#4282]). /// /// ## Example /// ```python /// x: str = ... /// /// if x == "": /// print("x is empty") /// ``` /// /// Use instead: /// ```python /// x: str = ... /// /// if not x: /// print("x is empty") /// ``` /// /// ## References /// - [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) /// /// [#4282]: https://github.com/astral-sh/ruff/issues/4282 #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.0.255")] pub(crate) struct CompareToEmptyString { existing: String, replacement: String, } impl Violation for CompareToEmptyString { #[derive_message_formats] fn message(&self) -> String { let CompareToEmptyString { existing, replacement, } = self; format!("`{existing}` can be simplified to `{replacement}` as an empty string is falsey",) } } /// PLC1901 pub(crate) fn compare_to_empty_string( checker: &Checker, left: &Expr, ops: &[CmpOp], comparators: &[Expr], ) { // Omit string comparison rules within subscripts. This is mostly commonly used within // DataFrame and np.ndarray indexing. if checker .semantic() .current_expressions() .any(Expr::is_subscript_expr) { return; } let mut first = true; for ((lhs, rhs), op) in std::iter::once(left) .chain(comparators) .tuple_windows::<(&Expr, &Expr)>() .zip(ops) { if let Ok(op) = EmptyStringCmpOp::try_from(op) { if std::mem::take(&mut first) { // Check the left-most expression. if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &lhs { if value.is_empty() { let literal = checker.generator().expr(lhs); let expr = checker.generator().expr(rhs); let existing = format!("{literal} {op} {expr}"); let replacement = format!("{}{expr}", op.into_unary()); checker.report_diagnostic( CompareToEmptyString { existing, replacement, }, lhs.range(), ); } } } // Check all right-hand expressions. if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &rhs { if value.is_empty() { let expr = checker.generator().expr(lhs); let literal = checker.generator().expr(rhs); let existing = format!("{expr} {op} {literal}"); let replacement = format!("{}{expr}", op.into_unary()); checker.report_diagnostic( CompareToEmptyString { existing, replacement, }, rhs.range(), ); } } } } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum EmptyStringCmpOp { Is, IsNot, Eq, NotEq, } impl TryFrom<&CmpOp> for EmptyStringCmpOp { type Error = anyhow::Error; fn try_from(value: &CmpOp) -> Result<Self, Self::Error> { match value { CmpOp::Is => Ok(Self::Is), CmpOp::IsNot => Ok(Self::IsNot), CmpOp::Eq => Ok(Self::Eq), CmpOp::NotEq => Ok(Self::NotEq), _ => bail!("{value:?} cannot be converted to EmptyStringCmpOp"), } } } impl EmptyStringCmpOp { fn into_unary(self) -> &'static str { match self { Self::Is | Self::Eq => "not ", Self::IsNot | Self::NotEq => "", } } } impl std::fmt::Display for EmptyStringCmpOp { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let repr = match self { Self::Is => "is", Self::IsNot => "is not", Self::Eq => "==", Self::NotEq => "!=", }; write!(f, "{repr}") } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/assert_on_string_literal.rs
crates/ruff_linter/src/rules/pylint/rules/assert_on_string_literal.rs
use ruff_python_ast::{self as ast, Expr}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum Kind { Empty, NonEmpty, Unknown, } /// ## What it does /// Checks for `assert` statements that use a string literal as the first /// argument. /// /// ## Why is this bad? /// An `assert` on a non-empty string literal will always pass, while an /// `assert` on an empty string literal will always fail. /// /// ## Example /// ```python /// assert "always true" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.258")] pub(crate) struct AssertOnStringLiteral { kind: Kind, } impl Violation for AssertOnStringLiteral { #[derive_message_formats] fn message(&self) -> String { match self.kind { Kind::Empty => "Asserting on an empty string literal will never pass".to_string(), Kind::NonEmpty => { "Asserting on a non-empty string literal will always pass".to_string() } Kind::Unknown => { "Asserting on a string literal may have unintended results".to_string() } } } } /// PLW0129 pub(crate) fn assert_on_string_literal(checker: &Checker, test: &Expr) { match test { Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => { checker.report_diagnostic( AssertOnStringLiteral { kind: if value.is_empty() { Kind::Empty } else { Kind::NonEmpty }, }, test.range(), ); } Expr::BytesLiteral(ast::ExprBytesLiteral { value, .. }) => { checker.report_diagnostic( AssertOnStringLiteral { kind: if value.is_empty() { Kind::Empty } else { Kind::NonEmpty }, }, test.range(), ); } Expr::FString(ast::ExprFString { value, .. }) => { let kind = if value.iter().all(|f_string_part| match f_string_part { ast::FStringPart::Literal(literal) => literal.is_empty(), ast::FStringPart::FString(f_string) => { f_string.elements.iter().all(|element| match element { ast::InterpolatedStringElement::Literal( ast::InterpolatedStringLiteralElement { value, .. }, ) => value.is_empty(), ast::InterpolatedStringElement::Interpolation(_) => false, }) } }) { Kind::Empty } else if value.iter().any(|f_string_part| match f_string_part { ast::FStringPart::Literal(literal) => !literal.is_empty(), ast::FStringPart::FString(f_string) => { f_string.elements.iter().any(|element| match element { ast::InterpolatedStringElement::Literal( ast::InterpolatedStringLiteralElement { value, .. }, ) => !value.is_empty(), ast::InterpolatedStringElement::Interpolation(_) => false, }) } }) { Kind::NonEmpty } else { Kind::Unknown }; checker.report_diagnostic(AssertOnStringLiteral { kind }, test.range()); } _ => {} } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/single_string_slots.rs
crates/ruff_linter/src/rules/pylint/rules/single_string_slots.rs
use ruff_python_ast::{self as ast, Expr, Stmt, StmtClassDef}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for single strings assigned to `__slots__`. /// /// ## Why is this bad? /// In Python, the `__slots__` attribute allows you to explicitly define the /// attributes (instance variables) that a class can have. By default, Python /// uses a dictionary to store an object's attributes, which incurs some memory /// overhead. However, when `__slots__` is defined, Python uses a more compact /// internal structure to store the object's attributes, resulting in memory /// savings. /// /// Any string iterable may be assigned to `__slots__` (most commonly, a /// `tuple` of strings). If a string is assigned to `__slots__`, it is /// interpreted as a single attribute name, rather than an iterable of attribute /// names. This can cause confusion, as users that iterate over the `__slots__` /// value may expect to iterate over a sequence of attributes, but would instead /// iterate over the characters of the string. /// /// To use a single string attribute in `__slots__`, wrap the string in an /// iterable container type, like a `tuple`. /// /// ## Example /// ```python /// class Person: /// __slots__: str = "name" /// /// def __init__(self, name: str) -> None: /// self.name = name /// ``` /// /// Use instead: /// ```python /// class Person: /// __slots__: tuple[str, ...] = ("name",) /// /// def __init__(self, name: str) -> None: /// self.name = name /// ``` /// /// ## References /// - [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.276")] pub(crate) struct SingleStringSlots; impl Violation for SingleStringSlots { #[derive_message_formats] fn message(&self) -> String { "Class `__slots__` should be a non-string iterable".to_string() } } /// PLC0205 pub(crate) fn single_string_slots(checker: &Checker, class: &StmtClassDef) { for stmt in &class.body { match stmt { Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { for target in targets { if let Expr::Name(ast::ExprName { id, .. }) = target { if id.as_str() == "__slots__" { if matches!(value.as_ref(), Expr::StringLiteral(_) | Expr::FString(_)) { checker.report_diagnostic(SingleStringSlots, stmt.identifier()); } } } } } Stmt::AnnAssign(ast::StmtAnnAssign { target, value: Some(value), .. }) => { if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() { if id.as_str() == "__slots__" { if matches!(value.as_ref(), Expr::StringLiteral(_) | Expr::FString(_)) { checker.report_diagnostic(SingleStringSlots, stmt.identifier()); } } } } _ => {} } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unexpected_special_method_signature.rs
crates/ruff_linter/src/rules/pylint/rules/unexpected_special_method_signature.rs
use std::cmp::Ordering; use ruff_python_ast::{Decorator, Parameters, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility::is_staticmethod; use crate::Violation; use crate::checkers::ast::Checker; #[derive(Debug, Eq, PartialEq)] pub(crate) enum ExpectedParams { Fixed(usize), Range(usize, usize), } impl ExpectedParams { fn from_method(name: &str, is_staticmethod: bool) -> Option<ExpectedParams> { let expected_params = match name { "__del__" | "__repr__" | "__str__" | "__bytes__" | "__hash__" | "__bool__" | "__dir__" | "__len__" | "__length_hint__" | "__iter__" | "__reversed__" | "__neg__" | "__pos__" | "__abs__" | "__invert__" | "__complex__" | "__int__" | "__float__" | "__index__" | "__trunc__" | "__floor__" | "__ceil__" | "__enter__" | "__aenter__" | "__getnewargs_ex__" | "__getnewargs__" | "__getstate__" | "__reduce__" | "__copy__" | "__await__" | "__aiter__" | "__anext__" | "__fspath__" | "__subclasses__" | "__next__" => Some(ExpectedParams::Fixed(0)), "__format__" | "__lt__" | "__le__" | "__eq__" | "__ne__" | "__gt__" | "__ge__" | "__getattr__" | "__getattribute__" | "__delattr__" | "__delete__" | "__instancecheck__" | "__subclasscheck__" | "__getitem__" | "__missing__" | "__delitem__" | "__contains__" | "__add__" | "__sub__" | "__mul__" | "__truediv__" | "__floordiv__" | "__rfloordiv__" | "__mod__" | "__divmod__" | "__lshift__" | "__rshift__" | "__and__" | "__xor__" | "__or__" | "__radd__" | "__rsub__" | "__rmul__" | "__rtruediv__" | "__rmod__" | "__rdivmod__" | "__rpow__" | "__rlshift__" | "__rrshift__" | "__rand__" | "__rxor__" | "__ror__" | "__iadd__" | "__isub__" | "__imul__" | "__itruediv__" | "__ifloordiv__" | "__imod__" | "__ilshift__" | "__irshift__" | "__iand__" | "__ixor__" | "__ior__" | "__ipow__" | "__setstate__" | "__reduce_ex__" | "__deepcopy__" | "__matmul__" | "__rmatmul__" | "__imatmul__" | "__buffer__" | "__class_getitem__" | "__mro_entries__" | "__release_buffer__" | "__subclasshook__" => { Some(ExpectedParams::Fixed(1)) } "__setattr__" | "__get__" | "__set__" | "__setitem__" | "__set_name__" => { Some(ExpectedParams::Fixed(2)) } "__exit__" | "__aexit__" => Some(ExpectedParams::Fixed(3)), "__round__" => Some(ExpectedParams::Range(0, 1)), "__pow__" => Some(ExpectedParams::Range(1, 2)), _ => None, }?; Some(if is_staticmethod { expected_params } else { match expected_params { ExpectedParams::Fixed(n) => ExpectedParams::Fixed(n + 1), ExpectedParams::Range(min, max) => ExpectedParams::Range(min + 1, max + 1), } }) } fn message(&self) -> String { match self { ExpectedParams::Fixed(n) if *n == 1 => "1 parameter".to_string(), ExpectedParams::Fixed(n) => { format!("{} parameters", *n) } ExpectedParams::Range(min, max) => { format!("between {} and {} parameters", *min, *max) } } } } /// ## What it does /// Checks for "special" methods that have an unexpected method signature. /// /// ## Why is this bad? /// "Special" methods, like `__len__`, are expected to adhere to a specific, /// standard function signature. Implementing a "special" method using a /// non-standard function signature can lead to unexpected and surprising /// behavior for users of a given class. /// /// ## Example /// ```python /// class Bookshelf: /// def __init__(self): /// self._books = ["Foo", "Bar", "Baz"] /// /// def __len__(self, index): # __len__ does not except an index parameter /// return len(self._books) /// /// def __getitem__(self, index): /// return self._books[index] /// ``` /// /// Use instead: /// ```python /// class Bookshelf: /// def __init__(self): /// self._books = ["Foo", "Bar", "Baz"] /// /// def __len__(self): /// return len(self._books) /// /// def __getitem__(self, index): /// return self._books[index] /// ``` /// /// ## References /// - [Python documentation: Data model](https://docs.python.org/3/reference/datamodel.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.263")] pub(crate) struct UnexpectedSpecialMethodSignature { method_name: String, expected_params: ExpectedParams, actual_params: usize, } impl Violation for UnexpectedSpecialMethodSignature { #[derive_message_formats] fn message(&self) -> String { let verb = if self.actual_params > 1 { "were" } else { "was" }; format!( "The special method `{}` expects {}, {} {} given", self.method_name, self.expected_params.message(), self.actual_params, verb ) } } /// PLE0302 pub(crate) fn unexpected_special_method_signature( checker: &Checker, stmt: &Stmt, name: &str, decorator_list: &[Decorator], parameters: &Parameters, ) { if !checker.semantic().current_scope().kind.is_class() { return; } // Ignore methods with keyword-only parameters or variadic parameters. if !parameters.kwonlyargs.is_empty() || parameters.kwarg.is_some() { return; } // Method has no parameter, will be caught by no-method-argument (E0211/N805). if parameters.args.is_empty() && parameters.vararg.is_none() { return; } let actual_params = parameters.args.len() + parameters.posonlyargs.len(); let mandatory_params = parameters .args .iter() .chain(parameters.posonlyargs.iter()) .filter(|arg| arg.default.is_none()) .count(); let Some(expected_params) = ExpectedParams::from_method(name, is_staticmethod(decorator_list, checker.semantic())) else { return; }; let valid_signature = match expected_params { ExpectedParams::Range(min, max) => { if mandatory_params >= min { mandatory_params <= max } else { parameters.vararg.is_some() || actual_params <= max } } ExpectedParams::Fixed(expected) => match expected.cmp(&mandatory_params) { Ordering::Less => false, Ordering::Greater => parameters.vararg.is_some() || actual_params >= expected, Ordering::Equal => true, }, }; if !valid_signature { checker.report_diagnostic( UnexpectedSpecialMethodSignature { method_name: name.to_owned(), expected_params, actual_params, }, stmt.identifier(), ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/return_in_init.rs
crates/ruff_linter/src/rules/pylint/rules/return_in_init.rs
use ruff_python_ast::{self as ast, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::in_dunder_method; /// ## What it does /// Checks for `__init__` methods that return values. /// /// ## Why is this bad? /// The `__init__` method is the constructor for a given Python class, /// responsible for initializing, rather than creating, new objects. /// /// The `__init__` method has to return `None`. Returning any value from /// an `__init__` method will result in a runtime error. /// /// ## Example /// ```python /// class Example: /// def __init__(self): /// return [] /// ``` /// /// Use instead: /// ```python /// class Example: /// def __init__(self): /// self.value = [] /// ``` /// /// ## References /// - [CodeQL: `py-explicit-return-in-init`](https://codeql.github.com/codeql-query-help/python/py-explicit-return-in-init/) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.248")] pub(crate) struct ReturnInInit; impl Violation for ReturnInInit { #[derive_message_formats] fn message(&self) -> String { "Explicit return in `__init__`".to_string() } } /// PLE0101 pub(crate) fn return_in_init(checker: &Checker, stmt: &Stmt) { if let Stmt::Return(ast::StmtReturn { value, range: _, node_index: _, }) = stmt { if let Some(expr) = value { if expr.is_none_literal_expr() { // Explicit `return None`. return; } } else { // Implicit `return`. return; } } if in_dunder_method("__init__", checker.semantic(), checker.settings()) { checker.report_diagnostic(ReturnInInit, stmt.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/subprocess_popen_preexec_fn.rs
crates/ruff_linter/src/rules/pylint/rules/subprocess_popen_preexec_fn.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of `subprocess.Popen` with a `preexec_fn` argument. /// /// ## Why is this bad? /// The `preexec_fn` argument is unsafe within threads as it can lead to /// deadlocks. Furthermore, `preexec_fn` is [targeted for deprecation]. /// /// Instead, consider using task-specific arguments such as `env`, /// `start_new_session`, and `process_group`. These are not prone to deadlocks /// and are more explicit. /// /// ## Example /// ```python /// import os, subprocess /// /// subprocess.Popen(foo, preexec_fn=os.setsid) /// subprocess.Popen(bar, preexec_fn=os.setpgid(0, 0)) /// ``` /// /// Use instead: /// ```python /// import subprocess /// /// subprocess.Popen(foo, start_new_session=True) /// subprocess.Popen(bar, process_group=0) # Introduced in Python 3.11 /// ``` /// /// ## References /// - [Python documentation: `subprocess.Popen`](https://docs.python.org/3/library/subprocess.html#popen-constructor) /// - [Why `preexec_fn` in `subprocess.Popen` may lead to deadlock?](https://discuss.python.org/t/why-preexec-fn-in-subprocess-popen-may-lead-to-deadlock/16908/2) /// /// [targeted for deprecation]: https://github.com/python/cpython/issues/82616 #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.281")] pub(crate) struct SubprocessPopenPreexecFn; impl Violation for SubprocessPopenPreexecFn { #[derive_message_formats] fn message(&self) -> String { "`preexec_fn` argument is unsafe when using threads".to_string() } } /// PLW1509 pub(crate) fn subprocess_popen_preexec_fn(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::SUBPROCESS) { return; } if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["subprocess", "Popen"])) { if let Some(keyword) = call .arguments .find_keyword("preexec_fn") .filter(|keyword| !keyword.value.is_none_literal_expr()) { checker.report_diagnostic(SubprocessPopenPreexecFn, keyword.range()); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs
crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs
use std::collections::HashMap; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_python_trivia::indentation_at_offset; use ruff_text_size::{Ranged, TextRange}; use crate::checkers::ast::Checker; use crate::fix; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for the use of a classmethod being made without the decorator. /// /// ## Why is this bad? /// When it comes to consistency and readability, it's preferred to use the decorator. /// /// ## Example /// /// ```python /// class Foo: /// def bar(cls): ... /// /// bar = classmethod(bar) /// ``` /// /// Use instead: /// /// ```python /// class Foo: /// @classmethod /// def bar(cls): ... /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.7")] pub(crate) struct NoClassmethodDecorator; impl AlwaysFixableViolation for NoClassmethodDecorator { #[derive_message_formats] fn message(&self) -> String { "Class method defined without decorator".to_string() } fn fix_title(&self) -> String { "Add @classmethod decorator".to_string() } } /// ## What it does /// Checks for the use of a staticmethod being made without the decorator. /// /// ## Why is this bad? /// When it comes to consistency and readability, it's preferred to use the decorator. /// /// ## Example /// /// ```python /// class Foo: /// def bar(arg1, arg2): ... /// /// bar = staticmethod(bar) /// ``` /// /// Use instead: /// /// ```python /// class Foo: /// @staticmethod /// def bar(arg1, arg2): ... /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.7")] pub(crate) struct NoStaticmethodDecorator; impl AlwaysFixableViolation for NoStaticmethodDecorator { #[derive_message_formats] fn message(&self) -> String { "Static method defined without decorator".to_string() } fn fix_title(&self) -> String { "Add @staticmethod decorator".to_string() } } enum MethodType { Classmethod, Staticmethod, } /// PLR0202 pub(crate) fn no_classmethod_decorator(checker: &Checker, stmt: &Stmt) { get_undecorated_methods(checker, stmt, &MethodType::Classmethod); } /// PLR0203 pub(crate) fn no_staticmethod_decorator(checker: &Checker, stmt: &Stmt) { get_undecorated_methods(checker, stmt, &MethodType::Staticmethod); } fn get_undecorated_methods(checker: &Checker, class_stmt: &Stmt, method_type: &MethodType) { let Stmt::ClassDef(class_def) = class_stmt else { return; }; let mut explicit_decorator_calls: HashMap<Name, &Stmt> = HashMap::default(); let method_name = match method_type { MethodType::Classmethod => "classmethod", MethodType::Staticmethod => "staticmethod", }; // gather all explicit *method calls for stmt in &class_def.body { if let Stmt::Assign(ast::StmtAssign { targets, value, .. }) = stmt { if let Expr::Call(ast::ExprCall { func, arguments, .. }) = value.as_ref() { if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() { if id == method_name && checker.semantic().has_builtin_binding(method_name) { if arguments.args.len() != 1 { continue; } if targets.len() != 1 { continue; } let target_name = match targets.first() { Some(Expr::Name(ast::ExprName { id, .. })) => id.to_string(), _ => continue, }; if let Expr::Name(ast::ExprName { id, .. }) = &arguments.args[0] { if target_name == *id { explicit_decorator_calls.insert(id.clone(), stmt); } } } } } } } if explicit_decorator_calls.is_empty() { return; } for stmt in &class_def.body { if let Stmt::FunctionDef(ast::StmtFunctionDef { name, decorator_list, .. }) = stmt { let Some(decorator_call_statement) = explicit_decorator_calls.get(name.id()) else { continue; }; // if we find the decorator we're looking for, skip if decorator_list.iter().any(|decorator| { if let Expr::Name(ast::ExprName { id, .. }) = &decorator.expression { if id == method_name && checker.semantic().has_builtin_binding(method_name) { return true; } } false }) { continue; } let range = TextRange::new(stmt.range().start(), stmt.range().start()); let mut diagnostic = match method_type { MethodType::Classmethod => checker.report_diagnostic(NoClassmethodDecorator, range), MethodType::Staticmethod => { checker.report_diagnostic(NoStaticmethodDecorator, range) } }; let indentation = indentation_at_offset(stmt.range().start(), checker.source()); match indentation { Some(indentation) => { diagnostic.set_fix(Fix::safe_edits( Edit::insertion( format!("@{method_name}\n{indentation}"), stmt.range().start(), ), [fix::edits::delete_stmt( decorator_call_statement, Some(class_stmt), checker.locator(), checker.indexer(), )], )); } None => { continue; } } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/super_without_brackets.rs
crates/ruff_linter/src/rules/pylint/rules/super_without_brackets.rs
use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::{ScopeKind, analyze::function_type}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Detects attempts to use `super` without parentheses. /// /// ## Why is this bad? /// The [`super()` callable](https://docs.python.org/3/library/functions.html#super) /// can be used inside method definitions to create a proxy object that /// delegates attribute access to a superclass of the current class. Attempting /// to access attributes on `super` itself, however, instead of the object /// returned by a call to `super()`, will raise `AttributeError`. /// /// ## Example /// ```python /// class Animal: /// @staticmethod /// def speak(): /// return "This animal says something." /// /// /// class Dog(Animal): /// @staticmethod /// def speak(): /// original_speak = super.speak() # ERROR: `super.speak()` /// return f"{original_speak} But as a dog, it barks!" /// ``` /// /// Use instead: /// ```python /// class Animal: /// @staticmethod /// def speak(): /// return "This animal says something." /// /// /// class Dog(Animal): /// @staticmethod /// def speak(): /// original_speak = super().speak() # Correct: `super().speak()` /// return f"{original_speak} But as a dog, it barks!" /// ``` /// /// ## Options /// /// This rule applies to regular, static, and class methods. You can customize how Ruff categorizes /// methods with the following options: /// /// - `lint.pep8-naming.classmethod-decorators` /// - `lint.pep8-naming.staticmethod-decorators` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct SuperWithoutBrackets; impl AlwaysFixableViolation for SuperWithoutBrackets { #[derive_message_formats] fn message(&self) -> String { "`super` call is missing parentheses".to_string() } fn fix_title(&self) -> String { "Add parentheses to `super` call".to_string() } } /// PLW0245 pub(crate) fn super_without_brackets(checker: &Checker, func: &Expr) { // The call must be to `super` (without parentheses). let Expr::Attribute(ast::ExprAttribute { value, .. }) = func else { return; }; let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else { return; }; if id.as_str() != "super" { return; } if !checker.semantic().has_builtin_binding(id.as_str()) { return; } let scope = checker.semantic().current_scope(); // The current scope _must_ be a function. let ScopeKind::Function(function_def) = scope.kind else { return; }; let Some(parent) = checker.semantic().first_non_type_parent_scope(scope) else { return; }; // The function must be a method, class method, or static method. let classification = function_type::classify( &function_def.name, &function_def.decorator_list, parent, checker.semantic(), &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ); if !matches!( classification, function_type::FunctionType::Method | function_type::FunctionType::ClassMethod | function_type::FunctionType::StaticMethod ) { return; } let mut diagnostic = checker.report_diagnostic(SuperWithoutBrackets, value.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( "super()".to_string(), value.range(), ))); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/comparison_of_constant.rs
crates/ruff_linter/src/rules/pylint/rules/comparison_of_constant.rs
use itertools::Itertools; use ruff_python_ast::{CmpOp, Expr}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for comparisons between constants. /// /// ## Why is this bad? /// Comparing two constants will always resolve to the same value, so the /// comparison is redundant. Instead, the expression should be replaced /// with the result of the comparison. /// /// ## Example /// ```python /// foo = 1 == 1 /// ``` /// /// Use instead: /// ```python /// foo = True /// ``` /// /// ## References /// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.221")] pub(crate) struct ComparisonOfConstant { left_constant: String, op: CmpOp, right_constant: String, } impl Violation for ComparisonOfConstant { #[derive_message_formats] fn message(&self) -> String { let ComparisonOfConstant { left_constant, op, right_constant, } = self; format!( "Two constants compared in a comparison, consider replacing `{left_constant} {op} {right_constant}`", ) } } /// PLR0133 pub(crate) fn comparison_of_constant( checker: &Checker, left: &Expr, ops: &[CmpOp], comparators: &[Expr], ) { for ((left, right), op) in std::iter::once(left) .chain(comparators) .tuple_windows() .zip(ops) { if left.is_literal_expr() && right.is_literal_expr() { checker.report_diagnostic( ComparisonOfConstant { left_constant: checker.generator().expr(left), op: *op, right_constant: checker.generator().expr(right), }, left.range(), ); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/non_ascii_module_import.rs
crates/ruff_linter/src/rules/pylint/rules/non_ascii_module_import.rs
use ruff_python_ast::Alias; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for the use of non-ASCII characters in import statements. /// /// ## Why is this bad? /// The use of non-ASCII characters in import statements can cause confusion /// and compatibility issues (see: [PEP 672]). /// /// ## Example /// ```python /// import bár /// ``` /// /// Use instead: /// ```python /// import bar /// ``` /// /// If the module is third-party, use an ASCII-only alias: /// ```python /// import bár as bar /// ``` /// /// [PEP 672]: https://peps.python.org/pep-0672/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct NonAsciiImportName { name: String, kind: Kind, } impl Violation for NonAsciiImportName { #[derive_message_formats] fn message(&self) -> String { let Self { name, kind } = self; match kind { Kind::Aliased => { format!("Module alias `{name}` contains a non-ASCII character") } Kind::Unaliased => { format!("Module name `{name}` contains a non-ASCII character") } } } fn fix_title(&self) -> Option<String> { Some("Use an ASCII-only alias".to_string()) } } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum Kind { /// The import uses a non-ASCII alias (e.g., `import foo as bár`). Aliased, /// The imported module is non-ASCII, and could be given an ASCII alias (e.g., `import bár`). Unaliased, } /// PLC2403 pub(crate) fn non_ascii_module_import(checker: &Checker, alias: &Alias) { if let Some(asname) = &alias.asname { if asname.as_str().is_ascii() { return; } checker.report_diagnostic( NonAsciiImportName { name: asname.to_string(), kind: Kind::Aliased, }, asname.range(), ); } else { if alias.name.as_str().is_ascii() { return; } checker.report_diagnostic( NonAsciiImportName { name: alias.name.to_string(), kind: Kind::Unaliased, }, alias.name.range(), ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/redefined_argument_from_local.rs
crates/ruff_linter/src/rules/pylint/rules/redefined_argument_from_local.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{BindingKind, Scope, ScopeId}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for variables defined in `for`, `try`, `with` statements /// that redefine function parameters. /// /// ## Why is this bad? /// Redefined variables can cause unexpected behavior because of overridden function parameters. /// If nested functions are declared, an inner function's body can override an outer function's parameters. /// /// ## Example /// ```python /// def show(host_id=10.11): /// for host_id, host in [[12.13, "Venus"], [14.15, "Mars"]]: /// print(host_id, host) /// ``` /// /// Use instead: /// ```python /// def show(host_id=10.11): /// for inner_host_id, host in [[12.13, "Venus"], [14.15, "Mars"]]: /// print(host_id, inner_host_id, host) /// ``` /// /// ## Options /// - `lint.dummy-variable-rgx` /// /// ## References /// - [Pylint documentation](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/redefined-argument-from-local.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct RedefinedArgumentFromLocal { pub(crate) name: String, } impl Violation for RedefinedArgumentFromLocal { #[derive_message_formats] fn message(&self) -> String { let RedefinedArgumentFromLocal { name } = self; format!("Redefining argument with the local name `{name}`") } } /// PLR1704 pub(crate) fn redefined_argument_from_local(checker: &Checker, scope_id: ScopeId, scope: &Scope) { for (name, binding_id) in scope.bindings() { for shadow in checker.semantic().shadowed_bindings(scope_id, binding_id) { let binding = &checker.semantic().bindings[shadow.binding_id()]; if !matches!( binding.kind, BindingKind::LoopVar | BindingKind::BoundException | BindingKind::WithItemVar ) { continue; } let shadowed = &checker.semantic().bindings[shadow.shadowed_id()]; if !shadowed.kind.is_argument() { continue; } if checker.settings().dummy_variable_rgx.is_match(name) { continue; } let scope = &checker.semantic().scopes[binding.scope]; if scope.kind.is_generator() { continue; } checker.report_diagnostic( RedefinedArgumentFromLocal { name: name.to_string(), }, binding.range(), ); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/useless_return.rs
crates/ruff_linter/src/rules/pylint/rules/useless_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix; use crate::{AlwaysFixableViolation, Fix}; /// ## What it does /// Checks for functions that end with an unnecessary `return` or /// `return None`, and contain no other `return` statements. /// /// ## Why is this bad? /// Python implicitly assumes a `None` return at the end of a function, making /// it unnecessary to explicitly write `return None`. /// /// ## Example /// ```python /// def f(): /// print(5) /// return None /// ``` /// /// Use instead: /// ```python /// def f(): /// print(5) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct UselessReturn; impl AlwaysFixableViolation for UselessReturn { #[derive_message_formats] fn message(&self) -> String { "Useless `return` statement at end of function".to_string() } fn fix_title(&self) -> String { "Remove useless `return` statement".to_string() } } /// PLR1711 pub(crate) fn useless_return( checker: &Checker, stmt: &Stmt, body: &[Stmt], returns: Option<&Expr>, ) { // Skip functions that have a return annotation that is not `None`. if !returns.is_none_or(Expr::is_none_literal_expr) { return; } // Find the last statement in the function. let Some(last_stmt) = body.last() else { // Skip empty functions. return; }; // Verify that the last statement is a return statement. let Stmt::Return(ast::StmtReturn { value, range: _, node_index: _, }) = &last_stmt else { return; }; // Skip functions that consist of a single return statement. if body.len() == 1 { return; } // Skip functions that consist of a docstring and a return statement. if body.len() == 2 { if let Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) = &body[0] { if value.is_string_literal_expr() { return; } } } // Verify that the return statement is either bare or returns `None`. if !value .as_ref() .is_none_or(|expr| expr.is_none_literal_expr()) { return; } // Finally: verify that there are no _other_ return statements in the function. let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(body); if visitor.returns.len() > 1 { return; } let mut diagnostic = checker.report_diagnostic(UselessReturn, last_stmt.range()); let edit = fix::edits::delete_stmt(last_stmt, Some(stmt), checker.locator(), checker.indexer()); diagnostic.set_fix(Fix::safe_edit(edit).isolate(Checker::isolation( checker.semantic().current_statement_id(), ))); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_default.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_default.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `os.getenv` calls with invalid default values. /// /// ## Why is this bad? /// If an environment variable is set, `os.getenv` will return its value as /// a string. If the environment variable is _not_ set, `os.getenv` will /// return `None`, or the default value if one is provided. /// /// If the default value is not a string or `None`, then it will be /// inconsistent with the return type of `os.getenv`, which can lead to /// confusing behavior. /// /// ## Example /// ```python /// import os /// /// int(os.getenv("FOO", 1)) /// ``` /// /// Use instead: /// ```python /// import os /// /// int(os.getenv("FOO", "1")) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.255")] pub(crate) struct InvalidEnvvarDefault; impl Violation for InvalidEnvvarDefault { #[derive_message_formats] fn message(&self) -> String { "Invalid type for environment variable default; expected `str` or `None`".to_string() } } /// PLW1508 pub(crate) fn invalid_envvar_default(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::OS) { return; } if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["os", "getenv"] | ["os", "environ", "get"] ) }) { // Find the `default` argument, if it exists. let Some(expr) = call.arguments.find_argument_value("default", 1) else { return; }; if matches!( ResolvedPythonType::from(expr), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::String | PythonType::None) ) { return; } checker.report_diagnostic(InvalidEnvvarDefault, expr.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/load_before_global_declaration.rs
crates/ruff_linter/src/rules/pylint/rules/load_before_global_declaration.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_source_file::SourceRow; use crate::Violation; /// ## What it does /// Checks for uses of names that are declared as `global` prior to the /// relevant `global` declaration. /// /// ## Why is this bad? /// The `global` declaration applies to the entire scope. Using a name that's /// declared as `global` in a given scope prior to the relevant `global` /// declaration is a `SyntaxError`. /// /// ## Example /// ```python /// counter = 1 /// /// /// def increment(): /// print(f"Adding 1 to {counter}") /// global counter /// counter += 1 /// ``` /// /// Use instead: /// ```python /// counter = 1 /// /// /// def increment(): /// global counter /// print(f"Adding 1 to {counter}") /// counter += 1 /// ``` /// /// ## References /// - [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.174")] pub(crate) struct LoadBeforeGlobalDeclaration { pub(crate) name: String, pub(crate) row: SourceRow, } impl Violation for LoadBeforeGlobalDeclaration { #[derive_message_formats] fn message(&self) -> String { let LoadBeforeGlobalDeclaration { name, row } = self; format!("Name `{name}` is used prior to global declaration on {row}") } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_boolean_expressions.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_boolean_expressions.rs
use ast::{Expr, StmtIf}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for too many Boolean expressions in an `if` statement. /// /// By default, this rule allows up to 5 expressions. This can be configured /// using the [`lint.pylint.max-bool-expr`] option. /// /// ## Why is this bad? /// `if` statements with many Boolean expressions are harder to understand /// and maintain. Consider assigning the result of the Boolean expression, /// or any of its sub-expressions, to a variable. /// /// ## Example /// ```python /// if a and b and c and d and e and f and g and h: /// ... /// ``` /// /// ## Options /// - `lint.pylint.max-bool-expr` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.1")] pub(crate) struct TooManyBooleanExpressions { expressions: usize, max_expressions: usize, } impl Violation for TooManyBooleanExpressions { #[derive_message_formats] fn message(&self) -> String { let TooManyBooleanExpressions { expressions, max_expressions, } = self; format!("Too many Boolean expressions ({expressions} > {max_expressions})") } } /// PLR0916 pub(crate) fn too_many_boolean_expressions(checker: &Checker, stmt: &StmtIf) { if let Some(bool_op) = stmt.test.as_bool_op_expr() { let expressions = count_bools(bool_op); if expressions > checker.settings().pylint.max_bool_expr { checker.report_diagnostic( TooManyBooleanExpressions { expressions, max_expressions: checker.settings().pylint.max_bool_expr, }, bool_op.range(), ); } } for elif in &stmt.elif_else_clauses { if let Some(bool_op) = elif.test.as_ref().and_then(Expr::as_bool_op_expr) { let expressions = count_bools(bool_op); if expressions > checker.settings().pylint.max_bool_expr { checker.report_diagnostic( TooManyBooleanExpressions { expressions, max_expressions: checker.settings().pylint.max_bool_expr, }, bool_op.range(), ); } } } } /// Count the number of Boolean expressions in a `bool_op` expression. fn count_bools(bool_op: &ast::ExprBoolOp) -> usize { bool_op .values .iter() .map(|expr| { if let Expr::BoolOp(bool_op) = expr { count_bools(bool_op) } else { 1 } }) .sum::<usize>() }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/manual_import_from.rs
crates/ruff_linter/src/rules/pylint/rules/manual_import_from.rs
use ruff_python_ast::{self as ast, Alias, Identifier, Stmt}; use ruff_text_size::{Ranged, TextRange}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::checkers::ast::Checker; use crate::rules::pyupgrade::rules::is_import_required_by_isort; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for submodule imports that are aliased to the submodule name. /// /// ## Why is this bad? /// Using the `from` keyword to import the submodule is more concise and /// readable. /// /// ## Example /// ```python /// import concurrent.futures as futures /// ``` /// /// Use instead: /// ```python /// from concurrent import futures /// ``` /// /// ## Options /// /// This rule will not trigger on imports required by the `isort` configuration. /// /// - `lint.isort.required-imports` /// /// ## References /// - [Python documentation: Submodules](https://docs.python.org/3/reference/import.html#submodules) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.155")] pub(crate) struct ManualFromImport { module: String, name: String, } impl Violation for ManualFromImport { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { let ManualFromImport { module, name } = self; format!("Use `from {module} import {name}` in lieu of alias") } fn fix_title(&self) -> Option<String> { let ManualFromImport { module, name } = self; Some(format!("Replace with `from {module} import {name}`")) } } /// PLR0402 pub(crate) fn manual_from_import(checker: &Checker, stmt: &Stmt, alias: &Alias, names: &[Alias]) { let Some(asname) = &alias.asname else { return; }; let Some((module, name)) = alias.name.rsplit_once('.') else { return; }; if asname != name { return; } // Skip if this import is required by isort to prevent infinite loops with I002 if is_import_required_by_isort( &checker.settings().isort.required_imports, stmt.into(), alias, ) { return; } let mut diagnostic = checker.report_diagnostic( ManualFromImport { module: module.to_string(), name: name.to_string(), }, alias.range(), ); if names.len() == 1 { let node = ast::StmtImportFrom { module: Some(Identifier::new(module.to_string(), TextRange::default())), names: vec![Alias { name: asname.clone(), asname: None, range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, }], level: 0, range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, }; diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( checker.generator().stmt(&node.into()), stmt.range(), ))); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/collapsible_else_if.rs
crates/ruff_linter/src/rules/pylint/rules/collapsible_else_if.rs
use anyhow::Result; use ast::whitespace::indentation; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, ElifElseClause, Stmt}; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextRange}; use crate::Locator; use crate::checkers::ast::Checker; use crate::fix::edits::adjust_indentation; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for `else` blocks that consist of a single `if` statement. /// /// ## Why is this bad? /// If an `else` block contains a single `if` statement, it can be collapsed /// into an `elif`, thus reducing the indentation level. /// /// ## Example /// ```python /// def check_sign(value: int) -> None: /// if value > 0: /// print("Number is positive.") /// else: /// if value < 0: /// print("Number is negative.") /// else: /// print("Number is zero.") /// ``` /// /// Use instead: /// ```python /// def check_sign(value: int) -> None: /// if value > 0: /// print("Number is positive.") /// elif value < 0: /// print("Number is negative.") /// else: /// print("Number is zero.") /// ``` /// /// ## References /// - [Python documentation: `if` Statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.253")] pub(crate) struct CollapsibleElseIf; impl Violation for CollapsibleElseIf { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Use `elif` instead of `else` then `if`, to reduce indentation".to_string() } fn fix_title(&self) -> Option<String> { Some("Convert to `elif`".to_string()) } } /// PLR5501 pub(crate) fn collapsible_else_if(checker: &Checker, stmt: &Stmt) { let Stmt::If(ast::StmtIf { elif_else_clauses, .. }) = stmt else { return; }; let Some( else_clause @ ElifElseClause { body, test: None, .. }, ) = elif_else_clauses.last() else { return; }; let [first @ Stmt::If(ast::StmtIf { .. })] = body.as_slice() else { return; }; let mut diagnostic = checker.report_diagnostic( CollapsibleElseIf, TextRange::new(else_clause.start(), first.start()), ); diagnostic.try_set_fix(|| { convert_to_elif( first, else_clause, checker.locator(), checker.indexer(), checker.stylist(), ) }); } /// Generate [`Fix`] to convert an `else` block to an `elif` block. fn convert_to_elif( first: &Stmt, else_clause: &ElifElseClause, locator: &Locator, indexer: &Indexer, stylist: &Stylist, ) -> Result<Fix> { let inner_if_line_start = locator.line_start(first.start()); let inner_if_line_end = locator.line_end(first.end()); // Capture the trivia between the `else` and the `if`. let else_line_end = locator.full_line_end(else_clause.start()); let trivia_range = TextRange::new(else_line_end, inner_if_line_start); // Identify the indentation of the outer clause let Some(indentation) = indentation(locator.contents(), else_clause) else { return Err(anyhow::anyhow!("`else` is expected to be on its own line")); }; // Dedent the content from the end of the `else` to the end of the `if`. let indented = adjust_indentation( TextRange::new(inner_if_line_start, inner_if_line_end), indentation, locator, indexer, stylist, )?; // If there's trivia, restore it let trivia = if trivia_range.is_empty() { None } else { let indented_trivia = adjust_indentation(trivia_range, indentation, locator, indexer, stylist)?; Some(Edit::insertion( indented_trivia, locator.line_start(else_clause.start()), )) }; // Strip the indent from the first line of the `if` statement, and add `el` to the start. let Some(unindented) = indented.strip_prefix(indentation) else { return Err(anyhow::anyhow!("indented block to start with indentation")); }; let indented = format!("{indentation}el{unindented}"); Ok(Fix::safe_edits( Edit::replacement( indented, locator.line_start(else_clause.start()), inner_if_line_end, ), trivia, )) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/type_param_name_mismatch.rs
crates/ruff_linter/src/rules/pylint/rules/type_param_name_mismatch.rs
use std::fmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::type_param_name; /// ## What it does /// Checks for `TypeVar`, `TypeVarTuple`, `ParamSpec`, and `NewType` /// definitions in which the name of the type parameter does not match the name /// of the variable to which it is assigned. /// /// ## Why is this bad? /// When defining a `TypeVar` or a related type parameter, Python allows you to /// provide a name for the type parameter. According to [PEP 484], the name /// provided to the `TypeVar` constructor must be equal to the name of the /// variable to which it is assigned. /// /// ## Example /// ```python /// from typing import TypeVar /// /// T = TypeVar("U") /// ``` /// /// Use instead: /// ```python /// from typing import TypeVar /// /// T = TypeVar("T") /// ``` /// /// ## References /// - [Python documentation: `typing` — Support for type hints](https://docs.python.org/3/library/typing.html) /// - [PEP 484 – Type Hints: Generics](https://peps.python.org/pep-0484/#generics) /// /// [PEP 484]:https://peps.python.org/pep-0484/#generics #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.277")] pub(crate) struct TypeParamNameMismatch { kind: VarKind, var_name: String, param_name: String, } impl Violation for TypeParamNameMismatch { #[derive_message_formats] fn message(&self) -> String { let TypeParamNameMismatch { kind, var_name, param_name, } = self; format!("`{kind}` name `{param_name}` does not match assigned variable name `{var_name}`") } } /// PLC0132 pub(crate) fn type_param_name_mismatch(checker: &Checker, value: &Expr, targets: &[Expr]) { // If the typing modules were never imported, we'll never match below. if !checker.semantic().seen_typing() { return; } let [target] = targets else { return; }; let Expr::Name(ast::ExprName { id: var_name, .. }) = &target else { return; }; let Expr::Call(ast::ExprCall { func, arguments, .. }) = value else { return; }; let Some(param_name) = type_param_name(arguments) else { return; }; if var_name == param_name { return; } let Some(kind) = checker .semantic() .resolve_qualified_name(func) .and_then(|qualified_name| { if checker .semantic() .match_typing_qualified_name(&qualified_name, "ParamSpec") { Some(VarKind::ParamSpec) } else if checker .semantic() .match_typing_qualified_name(&qualified_name, "TypeVar") { Some(VarKind::TypeVar) } else if checker .semantic() .match_typing_qualified_name(&qualified_name, "TypeVarTuple") { Some(VarKind::TypeVarTuple) } else if checker .semantic() .match_typing_qualified_name(&qualified_name, "NewType") { Some(VarKind::NewType) } else { None } }) else { return; }; checker.report_diagnostic( TypeParamNameMismatch { kind, var_name: var_name.to_string(), param_name: param_name.to_string(), }, value.range(), ); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum VarKind { TypeVar, ParamSpec, TypeVarTuple, NewType, } impl fmt::Display for VarKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { VarKind::TypeVar => fmt.write_str("TypeVar"), VarKind::ParamSpec => fmt.write_str("ParamSpec"), VarKind::TypeVarTuple => fmt.write_str("TypeVarTuple"), VarKind::NewType => fmt.write_str("NewType"), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/logging.rs
crates/ruff_linter/src/rules/pylint/rules/logging.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::analyze::logging; use ruff_python_stdlib::logging::LoggingLevel; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::registry::Rule; use crate::rules::pyflakes::cformat::CFormatSummary; /// ## What it does /// Checks for too few positional arguments for a `logging` format string. /// /// ## Why is this bad? /// A `TypeError` will be raised if the statement is run. /// /// ## Example /// ```python /// import logging /// /// try: /// function() /// except Exception as e: /// logging.error("%s error occurred: %s", e) /// raise /// ``` /// /// Use instead: /// ```python /// import logging /// /// try: /// function() /// except Exception as e: /// logging.error("%s error occurred: %s", type(e), e) /// raise /// ``` /// /// ## Options /// /// - `lint.logger-objects` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.252")] pub(crate) struct LoggingTooFewArgs; impl Violation for LoggingTooFewArgs { #[derive_message_formats] fn message(&self) -> String { "Not enough arguments for `logging` format string".to_string() } } /// ## What it does /// Checks for too many positional arguments for a `logging` format string. /// /// ## Why is this bad? /// A `TypeError` will be raised if the statement is run. /// /// ## Example /// ```python /// import logging /// /// try: /// function() /// except Exception as e: /// logging.error("Error occurred: %s", type(e), e) /// raise /// ``` /// /// Use instead: /// ```python /// import logging /// /// try: /// function() /// except Exception as e: /// logging.error("%s error occurred: %s", type(e), e) /// raise /// ``` /// /// ## Options /// /// - `lint.logger-objects` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.252")] pub(crate) struct LoggingTooManyArgs; impl Violation for LoggingTooManyArgs { #[derive_message_formats] fn message(&self) -> String { "Too many arguments for `logging` format string".to_string() } } /// PLE1205 /// PLE1206 pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { // If there are any starred arguments, abort. if call.arguments.args.iter().any(Expr::is_starred_expr) { return; } // If there are any starred keyword arguments, abort. if call .arguments .keywords .iter() .any(|keyword| keyword.arg.is_none()) { return; } match call.func.as_ref() { Expr::Attribute(ast::ExprAttribute { attr, .. }) => { if LoggingLevel::from_attribute(attr).is_none() { return; } if !logging::is_logger_candidate( &call.func, checker.semantic(), &checker.settings().logger_objects, ) { return; } } Expr::Name(_) => { let Some(qualified_name) = checker .semantic() .resolve_qualified_name(call.func.as_ref()) else { return; }; let ["logging", attribute] = qualified_name.segments() else { return; }; if LoggingLevel::from_attribute(attribute).is_none() { return; } } _ => return, } let Some(Expr::StringLiteral(ast::ExprStringLiteral { value, .. })) = call.arguments.find_positional(0) else { return; }; let Ok(summary) = CFormatSummary::try_from(value.to_str()) else { return; }; if summary.starred { return; } if !summary.keywords.is_empty() { return; } let num_message_args = call.arguments.args.len() - 1; let num_keywords = call.arguments.keywords.len(); if checker.is_rule_enabled(Rule::LoggingTooManyArgs) { if summary.num_positional < num_message_args { checker.report_diagnostic(LoggingTooManyArgs, call.func.range()); } } if checker.is_rule_enabled(Rule::LoggingTooFewArgs) { if num_message_args > 0 && num_keywords == 0 && summary.num_positional > num_message_args { checker.report_diagnostic(LoggingTooFewArgs, call.func.range()); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/unreachable.rs
crates/ruff_linter/src/rules/pylint/rules/unreachable.rs
use std::collections::HashSet; use itertools::Itertools; use ruff_python_ast::{Identifier, Stmt}; use ruff_python_semantic::cfg::graph::{BlockId, Condition, ControlFlowGraph, build_cfg}; use ruff_text_size::TextRange; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for unreachable code. /// /// ## Why is this bad? /// Unreachable code can be a maintenance burden without ever being used. /// /// ## Example /// ```python /// def function(): /// if False: /// return "unreachable" /// return "reachable" /// ``` /// /// Use instead: /// ```python /// def function(): /// return "reachable" /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.0.0")] pub(crate) struct UnreachableCode { name: String, } impl Violation for UnreachableCode { #[derive_message_formats] fn message(&self) -> String { let UnreachableCode { name } = self; format!("Unreachable code in `{name}`") } } pub(crate) fn in_function(checker: &Checker, name: &Identifier, body: &[Stmt]) { let cfg = build_cfg(body); let reachable = reachable(&cfg); let mut blocks = (0..cfg.num_blocks()) .map(BlockId::from_usize) .filter(|block| !cfg.stmts(*block).is_empty()) .sorted_by_key(|block| cfg.range(*block).start()) .peekable(); // Advance past leading reachable blocks while blocks.next_if(|block| reachable.contains(block)).is_some() {} while let Some(start_block) = blocks.next() { // Advance to next reachable block let mut end_block = start_block; while let Some(next_block) = blocks.next_if(|block| !reachable.contains(block)) { end_block = next_block; } let start = cfg.range(start_block).start(); let end = cfg.range(end_block).end(); checker.report_diagnostic( UnreachableCode { name: name.to_string(), }, TextRange::new(start, end), ); } } /// Returns set of block indices reachable from entry block fn reachable(cfg: &ControlFlowGraph) -> HashSet<BlockId> { let mut reachable = HashSet::with_capacity(cfg.num_blocks()); let mut stack = Vec::new(); stack.push(cfg.initial()); while let Some(block) = stack.pop() { if reachable.insert(block) { stack.extend( cfg.outgoing(block) // Traverse edges that are statically known to be possible to cross. .filter_targets_by_conditions(|cond| matches!(taken(cond), Some(true) | None)), ); } } reachable } /// Determines if `condition` is taken. /// /// Returns `Some(true)` if the condition is always true, e.g. `if True`, same /// with `Some(false)` if it's never taken. If it can't be determined it returns /// `None`, e.g. `if i == 100`. #[expect(clippy::unnecessary_wraps)] fn taken(condition: &Condition) -> Option<bool> { match condition { Condition::Always => Some(true), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/useless_import_alias.rs
crates/ruff_linter/src/rules/pylint/rules/useless_import_alias.rs
use ruff_python_ast::Alias; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for import aliases that do not rename the original package. /// This rule does not apply in `__init__.py` files. /// /// ## Why is this bad? /// The import alias is redundant and should be removed to avoid confusion. /// /// ## Fix safety /// This fix is marked as always unsafe because the user may be intentionally /// re-exporting the import. While statements like `import numpy as numpy` /// appear redundant, they can have semantic meaning in certain contexts. /// /// ## Example /// ```python /// import numpy as numpy /// ``` /// /// Use instead: /// ```python /// import numpy as np /// ``` /// /// or /// /// ```python /// import numpy /// ``` /// /// ## Options /// /// The rule will emit a diagnostic but not a fix if the import is required by the `isort` /// configuration option: /// /// - `lint.isort.required-imports` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.156")] pub(crate) struct UselessImportAlias { required_import_conflict: bool, } impl Violation for UselessImportAlias { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { if !self.required_import_conflict { "Import alias does not rename original package".to_string() } else { "Required import does not rename original package.".to_string() } } fn fix_title(&self) -> Option<String> { if self.required_import_conflict { Some("Change required import or disable rule.".to_string()) } else { Some("Remove import alias".to_string()) } } } /// PLC0414 pub(crate) fn useless_import_alias(checker: &Checker, alias: &Alias) { let Some(asname) = &alias.asname else { return; }; if alias.name.as_str() != asname.as_str() { return; } // A re-export in __init__.py is probably intentional. if checker.in_init_module() { return; } // A required import with a useless alias causes an infinite loop. // See https://github.com/astral-sh/ruff/issues/14283 let required_import_conflict = checker .settings() .isort .requires_module_import(alias.name.to_string(), Some(asname.to_string())); let mut diagnostic = checker.report_diagnostic( UselessImportAlias { required_import_conflict, }, alias.range(), ); if !required_import_conflict { diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( asname.to_string(), alias.range(), ))); } } /// PLC0414 pub(crate) fn useless_import_from_alias( checker: &Checker, alias: &Alias, module: Option<&str>, level: u32, ) { let Some(asname) = &alias.asname else { return; }; if alias.name.as_str() != asname.as_str() { return; } // A re-export in __init__.py is probably intentional. if checker.in_init_module() { return; } // A required import with a useless alias causes an infinite loop. // See https://github.com/astral-sh/ruff/issues/14283 let required_import_conflict = checker.settings().isort.requires_member_import( module.map(str::to_string), alias.name.to_string(), Some(asname.to_string()), level, ); let mut diagnostic = checker.report_diagnostic( UselessImportAlias { required_import_conflict, }, alias.range(), ); if !required_import_conflict { diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( asname.to_string(), alias.range(), ))); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/eq_without_hash.rs
crates/ruff_linter/src/rules/pylint/rules/eq_without_hash.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ Expr, ExprName, Identifier, StmtAnnAssign, StmtAssign, StmtClassDef, StmtFunctionDef, }; use ruff_python_semantic::analyze::class::{ ClassMemberBoundness, ClassMemberKind, any_member_declaration, }; use ruff_text_size::Ranged; use std::ops::BitOr; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for classes that implement `__eq__` but not `__hash__`. /// /// ## Why is this bad? /// A class that implements `__eq__` but not `__hash__` will have its hash /// method implicitly set to `None`, regardless of if a superclass defines /// `__hash__`. This will cause the class to be unhashable, which will in turn /// cause issues when using instances of the class as keys in a dictionary or /// members of a set. /// /// ## Example /// /// ```python /// class Person: /// def __init__(self): /// self.name = "monty" /// /// def __eq__(self, other): /// return isinstance(other, Person) and other.name == self.name /// ``` /// /// Use instead: /// /// ```python /// class Person: /// def __init__(self): /// self.name = "monty" /// /// def __eq__(self, other): /// return isinstance(other, Person) and other.name == self.name /// /// def __hash__(self): /// return hash(self.name) /// ``` /// /// In general, it is unsound to inherit a `__hash__` implementation from a parent class while /// overriding the `__eq__` implementation because the two must be kept in sync. However, an easy /// way to resolve this error in cases where it _is_ sound is to explicitly set `__hash__` to the /// parent class's implementation: /// /// ```python /// class Developer(Person): /// def __init__(self): ... /// /// def __eq__(self, other): ... /// /// __hash__ = Person.__hash__ /// ``` /// /// ## References /// - [Python documentation: `object.__hash__`](https://docs.python.org/3/reference/datamodel.html#object.__hash__) /// - [Python glossary: hashable](https://docs.python.org/3/glossary.html#term-hashable) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.12.0")] pub(crate) struct EqWithoutHash; impl Violation for EqWithoutHash { #[derive_message_formats] fn message(&self) -> String { "Object does not implement `__hash__` method".to_string() } } /// PLW1641 pub(crate) fn object_without_hash_method(checker: &Checker, class: &StmtClassDef) { if checker.source_type.is_stub() { return; } let eq_hash = EqHash::from_class(class); if matches!( eq_hash, EqHash { eq: HasMethod::Yes | HasMethod::Maybe, hash: HasMethod::No } ) { checker.report_diagnostic(EqWithoutHash, class.name.range()); } } #[derive(Debug)] struct EqHash { hash: HasMethod, eq: HasMethod, } impl EqHash { fn from_class(class: &StmtClassDef) -> Self { let (mut has_eq, mut has_hash) = (HasMethod::No, HasMethod::No); any_member_declaration(class, &mut |declaration| { let id = match declaration.kind() { ClassMemberKind::Assign(StmtAssign { targets, .. }) => { let [Expr::Name(ExprName { id, .. })] = &targets[..] else { return false; }; id } ClassMemberKind::AnnAssign(StmtAnnAssign { target, .. }) => { let Expr::Name(ExprName { id, .. }) = target.as_ref() else { return false; }; id } ClassMemberKind::FunctionDef(StmtFunctionDef { name: Identifier { id, .. }, .. }) => id.as_str(), }; match id { "__eq__" => has_eq = has_eq | declaration.boundness().into(), "__hash__" => has_hash = has_hash | declaration.boundness().into(), _ => {} } !has_eq.is_no() && !has_hash.is_no() }); Self { eq: has_eq, hash: has_hash, } } } #[derive(Debug, Copy, Clone, Eq, PartialEq, is_macro::Is, Default)] enum HasMethod { /// There is no assignment or declaration. #[default] No, /// The assignment or declaration is placed directly within the class body. Yes, /// The assignment or declaration is placed within an intermediate block /// (`if`/`elif`/`else`, `for`/`else`, `while`/`else`, `with`, `case`, `try`/`except`). Maybe, } impl From<ClassMemberBoundness> for HasMethod { fn from(value: ClassMemberBoundness) -> Self { match value { ClassMemberBoundness::PossiblyUnbound => Self::Maybe, ClassMemberBoundness::Bound => Self::Yes, } } } impl BitOr<HasMethod> for HasMethod { type Output = Self; fn bitor(self, rhs: Self) -> Self::Output { match (self, rhs) { (HasMethod::No, _) => rhs, (_, _) => self, } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_value.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_envvar_value.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Modules; use ruff_python_semantic::analyze::type_inference::{PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `os.getenv` calls with an invalid `key` argument. /// /// ## Why is this bad? /// `os.getenv` only supports strings as the first argument (`key`). /// /// If the provided argument is not a string, `os.getenv` will throw a /// `TypeError` at runtime. /// /// ## Example /// ```python /// import os /// /// os.getenv(1) /// ``` /// /// Use instead: /// ```python /// import os /// /// os.getenv("1") /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.255")] pub(crate) struct InvalidEnvvarValue; impl Violation for InvalidEnvvarValue { #[derive_message_formats] fn message(&self) -> String { "Invalid type for initial `os.getenv` argument; expected `str`".to_string() } } /// PLE1507 pub(crate) fn invalid_envvar_value(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::OS) { return; } if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["os", "getenv"])) { // Find the `key` argument, if it exists. let Some(expr) = call.arguments.find_argument_value("key", 0) else { return; }; if matches!( ResolvedPythonType::from(expr), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::String) ) { return; } checker.report_diagnostic(InvalidEnvvarValue, expr.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_public_methods.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_public_methods.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::analyze::visibility::{self, Visibility::Public}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for classes with too many public methods /// /// By default, this rule allows up to 20 public methods, as configured by /// the [`lint.pylint.max-public-methods`] option. /// /// ## Why is this bad? /// Classes with many public methods are harder to understand /// and maintain. /// /// Instead, consider refactoring the class into separate classes. /// /// ## Example /// Assuming that `lint.pylint.max-public-methods` is set to 5: /// ```python /// class Linter: /// def __init__(self): /// pass /// /// def pylint(self): /// pass /// /// def pylint_settings(self): /// pass /// /// def flake8(self): /// pass /// /// def flake8_settings(self): /// pass /// /// def pydocstyle(self): /// pass /// /// def pydocstyle_settings(self): /// pass /// ``` /// /// Use instead: /// ```python /// class Linter: /// def __init__(self): /// self.pylint = Pylint() /// self.flake8 = Flake8() /// self.pydocstyle = Pydocstyle() /// /// def lint(self): /// pass /// /// /// class Pylint: /// def lint(self): /// pass /// /// def settings(self): /// pass /// /// /// class Flake8: /// def lint(self): /// pass /// /// def settings(self): /// pass /// /// /// class Pydocstyle: /// def lint(self): /// pass /// /// def settings(self): /// pass /// ``` /// /// ## Options /// - `lint.pylint.max-public-methods` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.0.290")] pub(crate) struct TooManyPublicMethods { methods: usize, max_methods: usize, } impl Violation for TooManyPublicMethods { #[derive_message_formats] fn message(&self) -> String { let TooManyPublicMethods { methods, max_methods, } = self; format!("Too many public methods ({methods} > {max_methods})") } } /// PLR0904 pub(crate) fn too_many_public_methods( checker: &Checker, class_def: &ast::StmtClassDef, max_methods: usize, ) { // https://github.com/astral-sh/ruff/issues/14535 if checker.source_type.is_stub() { return; } let methods = class_def .body .iter() .filter(|stmt| { stmt.as_function_def_stmt().is_some_and(|node| { matches!(visibility::method_visibility(node), Public) && !visibility::is_overload(&node.decorator_list, checker.semantic()) }) }) .count(); if methods > max_methods { checker.report_diagnostic( TooManyPublicMethods { methods, max_methods, }, class_def.range(), ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/boolean_chained_comparison.rs
crates/ruff_linter/src/rules/pylint/rules/boolean_chained_comparison.rs
use itertools::Itertools; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ BoolOp, CmpOp, Expr, ExprBoolOp, ExprCompare, token::{parentheses_iterator, parenthesized_range}, }; use ruff_text_size::{Ranged, TextRange}; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Check for chained boolean operations that can be simplified. /// /// ## Why is this bad? /// Refactoring the code will improve readability for these cases. /// /// ## Example /// /// ```python /// a = int(input()) /// b = int(input()) /// c = int(input()) /// if a < b and b < c: /// pass /// ``` /// /// Use instead: /// /// ```python /// a = int(input()) /// b = int(input()) /// c = int(input()) /// if a < b < c: /// pass /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.9.0")] pub(crate) struct BooleanChainedComparison; impl AlwaysFixableViolation for BooleanChainedComparison { #[derive_message_formats] fn message(&self) -> String { "Contains chained boolean comparison that can be simplified".to_string() } fn fix_title(&self) -> String { "Use a single compare expression".to_string() } } /// PLR1716 pub(crate) fn boolean_chained_comparison(checker: &Checker, expr_bool_op: &ExprBoolOp) { // early exit for non `and` boolean operations if expr_bool_op.op != BoolOp::And { return; } // early exit when not all expressions are compare expressions if !expr_bool_op.values.iter().all(Expr::is_compare_expr) { return; } let locator = checker.locator(); let tokens = checker.tokens(); // retrieve all compare expressions from boolean expression let compare_expressions = expr_bool_op .values .iter() .map(|expr| expr.as_compare_expr().unwrap()); for (left_compare, right_compare) in compare_expressions .tuple_windows() .filter(|(left_compare, right_compare)| { are_compare_expr_simplifiable(left_compare, right_compare) }) { let Some(Expr::Name(left_compare_right)) = left_compare.comparators.last() else { continue; }; let Expr::Name(right_compare_left) = &*right_compare.left else { continue; }; if left_compare_right.id() != right_compare_left.id() { continue; } let left_paren_count = parentheses_iterator(left_compare.into(), Some(expr_bool_op.into()), tokens).count(); let right_paren_count = parentheses_iterator(right_compare.into(), Some(expr_bool_op.into()), tokens).count(); // Create the edit that removes the comparison operator // In `a<(b) and ((b))<c`, we need to handle the // parentheses when specifying the fix range. let left_compare_right_range = parenthesized_range(left_compare_right.into(), left_compare.into(), tokens) .unwrap_or(left_compare_right.range()); let right_compare_left_range = parenthesized_range(right_compare_left.into(), right_compare.into(), tokens) .unwrap_or(right_compare_left.range()); let edit = Edit::range_replacement( locator.slice(left_compare_right_range).to_string(), TextRange::new( left_compare_right_range.start(), right_compare_left_range.end(), ), ); // Balance left and right parentheses let fix = match left_paren_count.cmp(&right_paren_count) { std::cmp::Ordering::Less => { let balance_parens_edit = Edit::insertion( "(".repeat(right_paren_count - left_paren_count), left_compare.start(), ); Fix::safe_edits(edit, [balance_parens_edit]) } std::cmp::Ordering::Equal => Fix::safe_edit(edit), std::cmp::Ordering::Greater => { let balance_parens_edit = Edit::insertion( ")".repeat(left_paren_count - right_paren_count), right_compare.end(), ); Fix::safe_edits(edit, [balance_parens_edit]) } }; let mut diagnostic = checker.report_diagnostic( BooleanChainedComparison, TextRange::new(left_compare.start(), right_compare.end()), ); diagnostic.set_fix(fix); } } /// Checks whether two compare expressions are simplifiable fn are_compare_expr_simplifiable(left: &ExprCompare, right: &ExprCompare) -> bool { left.ops .iter() .chain(right.ops.iter()) .tuple_windows::<(_, _)>() .all(|(left_operator, right_operator)| { matches!( (left_operator, right_operator), (CmpOp::Lt | CmpOp::LtE, CmpOp::Lt | CmpOp::LtE) | (CmpOp::Gt | CmpOp::GtE, CmpOp::Gt | CmpOp::GtE) ) }) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/repeated_equality_comparison.rs
crates/ruff_linter/src/rules/pylint/rules/repeated_equality_comparison.rs
use itertools::Itertools; use rustc_hash::{FxBuildHasher, FxHashMap}; use ast::ExprContext; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::helpers::{any_over_expr, contains_effect}; use ruff_python_ast::{self as ast, AtomicNodeIndex, BoolOp, CmpOp, Expr}; use ruff_python_semantic::SemanticModel; use ruff_text_size::{Ranged, TextRange}; use crate::Locator; use crate::checkers::ast::Checker; use crate::fix::snippet::SourceCodeSnippet; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for repeated equality comparisons that can be rewritten as a membership /// test. /// /// This rule will try to determine if the values are hashable /// and the fix will use a `set` if they are. If unable to determine, the fix /// will use a `tuple` and suggest the use of a `set`. /// /// ## Why is this bad? /// To check if a variable is equal to one of many values, it is common to /// write a series of equality comparisons (e.g., /// `foo == "bar" or foo == "baz"`). /// /// Instead, prefer to combine the values into a collection and use the `in` /// operator to check for membership, which is more performant and succinct. /// If the items are hashable, use a `set` for efficiency; otherwise, use a /// `tuple`. /// /// ## Fix safety /// This rule is always unsafe since literal sets and tuples /// evaluate their members eagerly whereas `or` comparisons /// are short-circuited. It is therefore possible that a fix /// will change behavior in the presence of side-effects. /// /// ## Example /// ```python /// foo == "bar" or foo == "baz" or foo == "qux" /// ``` /// /// Use instead: /// ```python /// foo in {"bar", "baz", "qux"} /// ``` /// /// ## References /// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons) /// - [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations) /// - [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.279")] pub(crate) struct RepeatedEqualityComparison { expression: SourceCodeSnippet, all_hashable: bool, } impl AlwaysFixableViolation for RepeatedEqualityComparison { #[derive_message_formats] fn message(&self) -> String { match (self.expression.full_display(), self.all_hashable) { (Some(expression), false) => { format!( "Consider merging multiple comparisons: `{expression}`. Use a `set` if the elements are hashable." ) } (Some(expression), true) => { format!("Consider merging multiple comparisons: `{expression}`.") } (None, false) => { "Consider merging multiple comparisons. Use a `set` if the elements are hashable." .to_string() } (None, true) => "Consider merging multiple comparisons.".to_string(), } } fn fix_title(&self) -> String { "Merge multiple comparisons".to_string() } } /// PLR1714 pub(crate) fn repeated_equality_comparison(checker: &Checker, bool_op: &ast::ExprBoolOp) { // Map from expression hash to (starting offset, number of comparisons, list let mut value_to_comparators: FxHashMap<ComparableExpr, (&Expr, Vec<&Expr>, Vec<usize>)> = FxHashMap::with_capacity_and_hasher(bool_op.values.len() * 2, FxBuildHasher); for (i, value) in bool_op.values.iter().enumerate() { let Some((left, right)) = to_allowed_value(bool_op.op, value, checker.semantic()) else { continue; }; if matches!(left, Expr::Name(_) | Expr::Attribute(_)) { let (_, left_matches, index_matches) = value_to_comparators .entry(left.into()) .or_insert_with(|| (left, Vec::new(), Vec::new())); left_matches.push(right); index_matches.push(i); } if matches!(right, Expr::Name(_) | Expr::Attribute(_)) { let (_, right_matches, index_matches) = value_to_comparators .entry(right.into()) .or_insert_with(|| (right, Vec::new(), Vec::new())); right_matches.push(left); index_matches.push(i); } } for (expr, comparators, indices) in value_to_comparators .into_values() .sorted_by_key(|(expr, _, _)| expr.start()) { // If there's only one comparison, there's nothing to merge. if comparators.len() == 1 { continue; } // Break into sequences of consecutive comparisons. let mut sequences: Vec<(Vec<usize>, Vec<&Expr>)> = Vec::new(); let mut last = None; for (index, comparator) in indices.iter().zip(comparators) { if last.is_some_and(|last| last + 1 == *index) { let (indices, comparators) = sequences.last_mut().unwrap(); indices.push(*index); comparators.push(comparator); } else { sequences.push((vec![*index], vec![comparator])); } last = Some(*index); } for (indices, comparators) in sequences { if indices.len() == 1 { continue; } if let Some((&first, rest)) = comparators.split_first() { let first_comparable = ComparableExpr::from(first); if rest .iter() .all(|&c| ComparableExpr::from(c) == first_comparable) { // Do not flag if all members are identical continue; } } // if we can determine that all the values are hashable, we can use a set // TODO: improve with type inference let all_hashable = comparators .iter() .all(|comparator| comparator.is_literal_expr()); let mut diagnostic = checker.report_diagnostic( RepeatedEqualityComparison { expression: SourceCodeSnippet::new(merged_membership_test( expr, bool_op.op, &comparators, checker.locator(), all_hashable, )), all_hashable, }, bool_op.range(), ); // Grab the remaining comparisons. let [first, .., last] = indices.as_slice() else { unreachable!("Indices should have at least two elements") }; let before = bool_op.values.iter().take(*first).cloned(); let after = bool_op.values.iter().skip(last + 1).cloned(); let comparator = if all_hashable { Expr::Set(ast::ExprSet { elts: comparators.iter().copied().cloned().collect(), range: TextRange::default(), node_index: AtomicNodeIndex::NONE, }) } else { Expr::Tuple(ast::ExprTuple { elts: comparators.iter().copied().cloned().collect(), range: TextRange::default(), node_index: AtomicNodeIndex::NONE, ctx: ExprContext::Load, parenthesized: true, }) }; diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( checker.generator().expr(&Expr::BoolOp(ast::ExprBoolOp { op: bool_op.op, values: before .chain(std::iter::once(Expr::Compare(ast::ExprCompare { left: Box::new(expr.clone()), ops: match bool_op.op { BoolOp::Or => Box::from([CmpOp::In]), BoolOp::And => Box::from([CmpOp::NotIn]), }, comparators: Box::from([comparator]), range: bool_op.range(), node_index: AtomicNodeIndex::NONE, }))) .chain(after) .collect(), range: bool_op.range(), node_index: AtomicNodeIndex::NONE, })), bool_op.range(), ))); } } } /// Return `true` if the given expression is compatible with a membership test. /// E.g., `==` operators can be joined with `or` and `!=` operators can be /// joined with `and`. fn to_allowed_value<'a>( bool_op: BoolOp, value: &'a Expr, semantic: &SemanticModel, ) -> Option<(&'a Expr, &'a Expr)> { let Expr::Compare(ast::ExprCompare { left, ops, comparators, .. }) = value else { return None; }; // Ignore, e.g., `foo == bar == baz`. let [op] = &**ops else { return None; }; if match bool_op { BoolOp::Or => !matches!(op, CmpOp::Eq), BoolOp::And => !matches!(op, CmpOp::NotEq), } { return None; } // Ignore self-comparisons, e.g., `foo == foo`. let [right] = &**comparators else { return None; }; if ComparableExpr::from(left) == ComparableExpr::from(right) { return None; } if contains_effect(value, |id| semantic.has_builtin_binding(id)) { return None; } // Ignore `sys.version_info` and `sys.platform` comparisons, which are only // respected by type checkers when enforced via equality. if any_over_expr(value, &|expr| { semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["sys", "version_info" | "platform"] ) }) }) { return None; } Some((left, right)) } /// Generate a string like `obj in (a, b, c)` or `obj not in (a, b, c)`. /// If `all_hashable` is `true`, the string will use a set instead of a tuple. fn merged_membership_test( left: &Expr, op: BoolOp, comparators: &[&Expr], locator: &Locator, all_hashable: bool, ) -> String { let op = match op { BoolOp::Or => "in", BoolOp::And => "not in", }; let left = locator.slice(left); let members = comparators .iter() .map(|comparator| locator.slice(comparator)) .join(", "); if all_hashable { return format!("{left} {op} {{{members}}}",); } format!("{left} {op} ({members})",) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/property_with_parameters.rs
crates/ruff_linter/src/rules/pylint/rules/property_with_parameters.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Decorator, Parameters, Stmt, identifier::Identifier}; use ruff_python_semantic::analyze::visibility::is_property; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for property definitions that accept function parameters. /// /// ## Why is this bad? /// Properties cannot be called with parameters. /// /// If you need to pass parameters to a property, create a method with the /// desired parameters and call that method instead. /// /// ## Example /// /// ```python /// class Cat: /// @property /// def purr(self, volume): ... /// ``` /// /// Use instead: /// /// ```python /// class Cat: /// @property /// def purr(self): ... /// /// def purr_volume(self, volume): ... /// ``` /// /// ## Options /// /// - `lint.pydocstyle.property-decorators` /// /// ## References /// - [Python documentation: `property`](https://docs.python.org/3/library/functions.html#property) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.153")] pub(crate) struct PropertyWithParameters; impl Violation for PropertyWithParameters { #[derive_message_formats] fn message(&self) -> String { "Cannot have defined parameters for properties".to_string() } } /// PLR0206 pub(crate) fn property_with_parameters( checker: &Checker, stmt: &Stmt, decorator_list: &[Decorator], parameters: &Parameters, ) { if parameters.len() <= 1 { return; } let semantic = checker.semantic(); let extra_property_decorators = checker.settings().pydocstyle.property_decorators(); if is_property(decorator_list, extra_property_decorators, semantic) { checker.report_diagnostic(PropertyWithParameters, stmt.identifier()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_positional_arguments.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_positional_arguments.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, identifier::Identifier}; use ruff_python_semantic::analyze::function_type::is_subject_to_liskov_substitution_principle; use ruff_python_semantic::analyze::{function_type, visibility}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for function definitions that include too many positional arguments. /// /// By default, this rule allows up to five arguments, as configured by the /// [`lint.pylint.max-positional-args`] option. /// /// ## Why is this bad? /// Functions with many arguments are harder to understand, maintain, and call. /// This is especially true for functions with many positional arguments, as /// providing arguments positionally is more error-prone and less clear to /// readers than providing arguments by name. /// /// Consider refactoring functions with many arguments into smaller functions /// with fewer arguments, using objects to group related arguments, or migrating to /// [keyword-only arguments](https://docs.python.org/3/tutorial/controlflow.html#special-parameters). /// /// This rule exempts methods decorated with [`@typing.override`][override]. /// Changing the signature of a subclass method may cause type checkers to /// complain about a violation of the Liskov Substitution Principle if it /// means that the method now incompatibly overrides a method defined on a /// superclass. Explicitly decorating an overriding method with `@override` /// signals to Ruff that the method is intended to override a superclass /// method and that a type checker will enforce that it does so; Ruff /// therefore knows that it should not enforce rules about methods having /// too many arguments. /// /// ## Example /// /// ```python /// def plot(x, y, z, color, mark, add_trendline): ... /// /// /// plot(1, 2, 3, "r", "*", True) /// ``` /// /// Use instead: /// /// ```python /// def plot(x, y, z, *, color, mark, add_trendline): ... /// /// /// plot(1, 2, 3, color="r", mark="*", add_trendline=True) /// ``` /// /// ## Options /// - `lint.pylint.max-positional-args` /// /// [override]: https://docs.python.org/3/library/typing.html#typing.override #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.7")] pub(crate) struct TooManyPositionalArguments { c_pos: usize, max_pos: usize, } impl Violation for TooManyPositionalArguments { #[derive_message_formats] fn message(&self) -> String { let TooManyPositionalArguments { c_pos, max_pos } = self; format!("Too many positional arguments ({c_pos}/{max_pos})") } } /// PLR0917 pub(crate) fn too_many_positional_arguments( checker: &Checker, function_def: &ast::StmtFunctionDef, ) { // https://github.com/astral-sh/ruff/issues/14535 if checker.source_type.is_stub() { return; } let semantic = checker.semantic(); // Count the number of positional arguments. let num_positional_args = function_def .parameters .posonlyargs .iter() .chain(&function_def.parameters.args) .filter(|param| !checker.settings().dummy_variable_rgx.is_match(param.name())) .count(); if num_positional_args <= checker.settings().pylint.max_positional_args { return; } // Allow excessive arguments in `@override` or `@overload` methods, since they're required // to adhere to the parent signature. if visibility::is_override(&function_def.decorator_list, semantic) || visibility::is_overload(&function_def.decorator_list, semantic) { return; } // Check if the function is a method or class method. let num_positional_args = if matches!( function_type::classify( &function_def.name, &function_def.decorator_list, semantic.current_scope(), semantic, &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ), function_type::FunctionType::Method | function_type::FunctionType::ClassMethod | function_type::FunctionType::NewMethod ) { // If so, we need to subtract one from the number of positional arguments, since the first // argument is always `self` or `cls`. num_positional_args.saturating_sub(1) } else { num_positional_args }; if num_positional_args <= checker.settings().pylint.max_positional_args { return; } let mut diagnostic = checker.report_diagnostic( TooManyPositionalArguments { c_pos: num_positional_args, max_pos: checker.settings().pylint.max_positional_args, }, function_def.identifier(), ); if is_subject_to_liskov_substitution_principle( &function_def.name, &function_def.decorator_list, semantic.current_scope(), semantic, &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ) { diagnostic.help( "Consider adding `@typing.override` if changing the function signature \ would violate the Liskov Substitution Principle", ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_index_return.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_index_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast}; use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::terminal::Terminal; use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `__index__` implementations that return non-integer values. /// /// ## Why is this bad? /// The `__index__` method should return an integer. Returning a different /// type may cause unexpected behavior. /// /// Note: `bool` is a subclass of `int`, so it's technically valid for `__index__` to /// return `True` or `False`. However, a `DeprecationWarning` (`DeprecationWarning: /// __index__ returned non-int (type bool)`) for such cases was already introduced, /// thus this is a conscious difference between the original pylint rule and the /// current ruff implementation. /// /// ## Example /// ```python /// class Foo: /// def __index__(self): /// return "2" /// ``` /// /// Use instead: /// ```python /// class Foo: /// def __index__(self): /// return 2 /// ``` /// /// ## References /// - [Python documentation: The `__index__` method](https://docs.python.org/3/reference/datamodel.html#object.__index__) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.6.0")] pub(crate) struct InvalidIndexReturnType; impl Violation for InvalidIndexReturnType { #[derive_message_formats] fn message(&self) -> String { "`__index__` does not return an integer".to_string() } } /// PLE0305 pub(crate) fn invalid_index_return(checker: &Checker, function_def: &ast::StmtFunctionDef) { if function_def.name.as_str() != "__index__" { return; } if !checker.semantic().current_scope().kind.is_class() { return; } if is_stub(function_def, checker.semantic()) { return; } // Determine the terminal behavior (i.e., implicit return, no return, etc.). let terminal = Terminal::from_function(function_def); // If every control flow path raises an exception, ignore the function. if terminal == Terminal::Raise { return; } // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { checker.report_diagnostic(InvalidIndexReturnType, function_def.identifier()); return; } let returns = { let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(&function_def.body); visitor.returns }; for stmt in returns { if let Some(value) = stmt.value.as_deref() { if !matches!( ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) ) { checker.report_diagnostic(InvalidIndexReturnType, value.range()); } } else { // Disallow implicit `None`. checker.report_diagnostic(InvalidIndexReturnType, stmt.range()); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs
crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for hard-coded sequence accesses that are known to be out of bounds. /// /// ## Why is this bad? /// Attempting to access a sequence with an out-of-bounds index will cause an /// `IndexError` to be raised at runtime. When the sequence and index are /// defined statically (e.g., subscripts on `list` and `tuple` literals, with /// integer indexes), such errors can be detected ahead of time. /// /// ## Example /// ```python /// print([0, 1, 2][3]) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct PotentialIndexError; impl Violation for PotentialIndexError { #[derive_message_formats] fn message(&self) -> String { "Expression is likely to raise `IndexError`".to_string() } } /// PLE0643 pub(crate) fn potential_index_error(checker: &Checker, value: &Expr, slice: &Expr) { // Determine the length of the sequence. let length = match value { Expr::Tuple(ast::ExprTuple { elts, .. }) | Expr::List(ast::ExprList { elts, .. }) => { match i64::try_from(elts.len()) { Ok(length) => length, Err(_) => return, } } _ => { return; } }; // Determine the index value. let index = match slice { Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(number_value), .. }) => number_value.as_i64(), Expr::UnaryOp(ast::ExprUnaryOp { op: ast::UnaryOp::USub, operand, .. }) => match operand.as_ref() { Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(number_value), .. }) => number_value.as_i64().map(|number| -number), _ => return, }, _ => return, }; // Emit a diagnostic if the index is out of bounds. If the index can't be represented as an // `i64`, but the length _can_, then the index is definitely out of bounds. if index.is_none_or(|index| index >= length || index < -length) { checker.report_diagnostic(PotentialIndexError, slice.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/too_many_locals.rs
crates/ruff_linter/src/rules/pylint/rules/too_many_locals.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::{Scope, ScopeKind}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for functions that include too many local variables. /// /// By default, this rule allows up to fifteen locals, as configured by the /// [`lint.pylint.max-locals`] option. /// /// ## Why is this bad? /// Functions with many local variables are harder to understand and maintain. /// /// Consider refactoring functions with many local variables into smaller /// functions with fewer assignments. /// /// ## Options /// - `lint.pylint.max-locals` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.9")] pub(crate) struct TooManyLocals { current_amount: usize, max_amount: usize, } impl Violation for TooManyLocals { #[derive_message_formats] fn message(&self) -> String { let TooManyLocals { current_amount, max_amount, } = self; format!("Too many local variables ({current_amount}/{max_amount})") } } /// PLR0914 pub(crate) fn too_many_locals(checker: &Checker, scope: &Scope) { let num_locals = scope .binding_ids() .filter(|id| { let binding = checker.semantic().binding(*id); binding.kind.is_assignment() }) .count(); if num_locals > checker.settings().pylint.max_locals { if let ScopeKind::Function(func) = scope.kind { checker.report_diagnostic( TooManyLocals { current_amount: num_locals, max_amount: checker.settings().pylint.max_locals, }, func.identifier(), ); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs
crates/ruff_linter/src/rules/pylint/rules/import_private_name.rs
use std::borrow::Cow; use itertools::Itertools; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_semantic::{FromImport, Import, Imported, ResolvedReference, Scope}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::package::PackageRoot; /// ## What it does /// Checks for import statements that import a private name (a name starting /// with an underscore `_`) from another module. /// /// ## Why is this bad? /// [PEP 8] states that names starting with an underscore are private. Thus, /// they are not intended to be used outside of the module in which they are /// defined. /// /// Further, as private imports are not considered part of the public API, they /// are prone to unexpected changes, especially outside of semantic versioning. /// /// Instead, consider using the public API of the module. /// /// This rule ignores private name imports that are exclusively used in type /// annotations. Ideally, types would be public; however, this is not always /// possible when using third-party libraries. /// /// ## Known problems /// Does not ignore private name imports from within the module that defines /// the private name if the module is defined with [PEP 420] namespace packages /// (i.e., directories that omit the `__init__.py` file). Namespace packages /// must be configured via the [`namespace-packages`] setting. /// /// ## Example /// ```python /// from foo import _bar /// ``` /// /// ## Options /// - `namespace-packages` /// /// ## References /// - [PEP 8: Naming Conventions](https://peps.python.org/pep-0008/#naming-conventions) /// - [Semantic Versioning](https://semver.org/) /// /// [PEP 8]: https://peps.python.org/pep-0008/ /// [PEP 420]: https://peps.python.org/pep-0420/ #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.14")] pub(crate) struct ImportPrivateName { name: String, module: Option<String>, } impl Violation for ImportPrivateName { #[derive_message_formats] fn message(&self) -> String { let ImportPrivateName { name, module } = self; match module { Some(module) => { format!("Private name import `{name}` from external module `{module}`") } None => format!("Private name import `{name}`"), } } } /// PLC2701 pub(crate) fn import_private_name(checker: &Checker, scope: &Scope) { for binding_id in scope.binding_ids() { let binding = checker.semantic().binding(binding_id); let Some(import) = binding.as_any_import() else { continue; }; let import_info = match import { import if import.is_import() => ImportInfo::from(import.import().unwrap()), import if import.is_from_import() => ImportInfo::from(import.from_import().unwrap()), _ => continue, }; let Some(root_module) = import_info.module_name.first() else { continue; }; // Relative imports are not a public API. // Ex) `from . import foo` if import_info.module_name.starts_with(&["."]) { continue; } // We can also ignore dunder names. // Ex) `from __future__ import annotations` // Ex) `from foo import __version__` if root_module.starts_with("__") || import_info.member_name.starts_with("__") { continue; } // Ignore private imports from the same module. // Ex) `from foo import _bar` within `foo/baz.py` if checker .package() .map(PackageRoot::path) .is_some_and(|path| path.ends_with(root_module)) { continue; } // Ignore public imports; require at least one private name. // Ex) `from foo import bar` let Some((index, private_name)) = import_info .qualified_name .segments() .iter() .find_position(|name| name.starts_with('_')) else { continue; }; // Ignore private imports used exclusively for typing. if !binding.references.is_empty() && binding .references() .map(|reference_id| checker.semantic().reference(reference_id)) .all(is_typing) { continue; } let name = (*private_name).to_string(); let module = if index > 0 { Some(import_info.qualified_name.segments()[..index].join(".")) } else { None }; checker.report_diagnostic(ImportPrivateName { name, module }, binding.range()); } } /// Returns `true` if the [`ResolvedReference`] is in a typing context. fn is_typing(reference: &ResolvedReference) -> bool { reference.in_type_checking_block() || reference.in_typing_only_annotation() || reference.in_string_type_definition() || reference.in_runtime_evaluated_annotation() } #[expect(clippy::struct_field_names)] struct ImportInfo<'a> { module_name: &'a [&'a str], member_name: Cow<'a, str>, qualified_name: &'a QualifiedName<'a>, } impl<'a> From<&'a FromImport<'_>> for ImportInfo<'a> { fn from(import: &'a FromImport) -> Self { let module_name = import.module_name(); let member_name = import.member_name(); let qualified_name = import.qualified_name(); Self { module_name, member_name, qualified_name, } } } impl<'a> From<&'a Import<'_>> for ImportInfo<'a> { fn from(import: &'a Import) -> Self { let module_name = import.module_name(); let member_name = import.member_name(); let qualified_name = import.qualified_name(); Self { module_name, member_name, qualified_name, } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/nonlocal_and_global.rs
crates/ruff_linter/src/rules/pylint/rules/nonlocal_and_global.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for variables which are both declared as both `nonlocal` and /// `global`. /// /// ## Why is this bad? /// A `nonlocal` variable is a variable that is defined in the nearest /// enclosing scope, but not in the global scope, while a `global` variable is /// a variable that is defined in the global scope. /// /// Declaring a variable as both `nonlocal` and `global` is contradictory and /// will raise a `SyntaxError`. /// /// ## Example /// ```python /// counter = 0 /// /// /// def increment(): /// global counter /// nonlocal counter /// counter += 1 /// ``` /// /// Use instead: /// ```python /// counter = 0 /// /// /// def increment(): /// global counter /// counter += 1 /// ``` /// /// ## References /// - [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement) /// - [Python documentation: The `nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct NonlocalAndGlobal { pub(crate) name: String, } impl Violation for NonlocalAndGlobal { #[derive_message_formats] fn message(&self) -> String { let NonlocalAndGlobal { name } = self; format!("Name `{name}` is both `nonlocal` and `global`") } } /// PLE0115 pub(crate) fn nonlocal_and_global(checker: &Checker, nonlocal: &ast::StmtNonlocal) { // Determine whether any of the newly declared `nonlocal` variables are already declared as // `global`. for name in &nonlocal.names { if let Some(global) = checker.semantic().global(name) { checker.report_diagnostic( NonlocalAndGlobal { name: name.to_string(), }, global, ); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bad_open_mode.rs
crates/ruff_linter/src/rules/pylint/rules/bad_open_mode.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::SemanticModel; use ruff_python_stdlib::open_mode::OpenMode; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Check for an invalid `mode` argument in `open` calls. /// /// ## Why is this bad? /// The `open` function accepts a `mode` argument that specifies how the file /// should be opened (e.g., read-only, write-only, append-only, etc.). /// /// Python supports a variety of open modes: `r`, `w`, `a`, and `x`, to control /// reading, writing, appending, and creating, respectively, along with /// `b` (binary mode), `+` (read and write), and `U` (universal newlines), /// the latter of which is only valid alongside `r`. This rule detects both /// invalid combinations of modes and invalid characters in the mode string /// itself. /// /// ## Example /// ```python /// with open("file", "rwx") as f: /// content = f.read() /// ``` /// /// Use instead: /// /// ```python /// with open("file", "r") as f: /// content = f.read() /// ``` /// /// ## References /// - [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct BadOpenMode { mode: String, } impl Violation for BadOpenMode { #[derive_message_formats] fn message(&self) -> String { let BadOpenMode { mode } = self; format!("`{mode}` is not a valid mode for `open`") } } /// PLW1501 pub(crate) fn bad_open_mode(checker: &Checker, call: &ast::ExprCall) { let Some(kind) = is_open(call.func.as_ref(), checker.semantic()) else { return; }; let Some(mode) = extract_mode(call, kind) else { return; }; let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = mode else { return; }; if OpenMode::from_chars(value.chars()).is_ok() { return; } checker.report_diagnostic( BadOpenMode { mode: value.to_string(), }, mode.range(), ); } #[derive(Debug, Copy, Clone)] enum Kind { /// A call to the builtin `open(...)`. Builtin, /// A call to `pathlib.Path(...).open(...)`. Pathlib, } /// If a function is a call to `open`, returns the kind of `open` call. fn is_open(func: &Expr, semantic: &SemanticModel) -> Option<Kind> { // Ex) `open(...)` if semantic.match_builtin_expr(func, "open") { return Some(Kind::Builtin); } // Ex) `pathlib.Path(...).open(...)` let ast::ExprAttribute { attr, value, .. } = func.as_attribute_expr()?; if attr != "open" { return None; } let ast::ExprCall { func: value_func, .. } = value.as_call_expr()?; let qualified_name = semantic.resolve_qualified_name(value_func)?; match qualified_name.segments() { ["pathlib", "Path"] => Some(Kind::Pathlib), _ => None, } } /// Returns the mode argument, if present. fn extract_mode(call: &ast::ExprCall, kind: Kind) -> Option<&Expr> { match kind { Kind::Builtin => call.arguments.find_argument_value("mode", 1), Kind::Pathlib => call.arguments.find_argument_value("mode", 0), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/singledispatchmethod_function.rs
crates/ruff_linter/src/rules/pylint/rules/singledispatchmethod_function.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_semantic::Scope; use ruff_python_semantic::analyze::function_type; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::importer::ImportRequest; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for non-method functions decorated with `@singledispatchmethod`. /// /// ## Why is this bad? /// The `@singledispatchmethod` decorator is intended for use with methods, not /// functions. /// /// Instead, use the `@singledispatch` decorator. /// /// ## Example /// /// ```python /// from functools import singledispatchmethod /// /// /// @singledispatchmethod /// def func(arg): ... /// ``` /// /// Use instead: /// /// ```python /// from functools import singledispatch /// /// /// @singledispatch /// def func(arg): ... /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe, as migrating from `@singledispatchmethod` to /// `@singledispatch` may change the behavior of the code. #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.6.0")] pub(crate) struct SingledispatchmethodFunction; impl Violation for SingledispatchmethodFunction { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "`@singledispatchmethod` decorator should not be used on non-method functions".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with `@singledispatch`".to_string()) } } /// PLE1520 pub(crate) fn singledispatchmethod_function(checker: &Checker, scope: &Scope) { let Some(func) = scope.kind.as_function() else { return; }; let ast::StmtFunctionDef { name, decorator_list, .. } = func; let Some(parent) = checker.semantic().first_non_type_parent_scope(scope) else { return; }; let type_ = function_type::classify( name, decorator_list, parent, checker.semantic(), &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ); if !matches!(type_, function_type::FunctionType::Function) { return; } for decorator in decorator_list { if checker .semantic() .resolve_qualified_name(&decorator.expression) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["functools", "singledispatchmethod"] ) }) { let mut diagnostic = checker.report_diagnostic(SingledispatchmethodFunction, decorator.range()); diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_symbol( &ImportRequest::import("functools", "singledispatch"), decorator.start(), checker.semantic(), )?; Ok(Fix::unsafe_edits( Edit::range_replacement(binding, decorator.expression.range()), [import_edit], )) }); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_all_format.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_all_format.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Binding; use ruff_text_size::Ranged; use crate::{Violation, checkers::ast::Checker}; /// ## What it does /// Checks for invalid assignments to `__all__`. /// /// ## Why is this bad? /// In Python, `__all__` should contain a sequence of strings that represent /// the names of all "public" symbols exported by a module. /// /// Assigning anything other than a `tuple` or `list` of strings to `__all__` /// is invalid. /// /// ## Example /// ```python /// __all__ = "Foo" /// ``` /// /// Use instead: /// ```python /// __all__ = ("Foo",) /// ``` /// /// ## References /// - [Python documentation: The `import` statement](https://docs.python.org/3/reference/simple_stmts.html#the-import-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.237")] pub(crate) struct InvalidAllFormat; impl Violation for InvalidAllFormat { #[derive_message_formats] fn message(&self) -> String { "Invalid format for `__all__`, must be `tuple` or `list`".to_string() } } /// PLE0605 pub(crate) fn invalid_all_format(checker: &Checker, binding: &Binding) { if binding.is_invalid_all_format() { checker.report_diagnostic(InvalidAllFormat, binding.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/repeated_isinstance_calls.rs
crates/ruff_linter/src/rules/pylint/rules/repeated_isinstance_calls.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::AlwaysFixableViolation; use crate::fix::snippet::SourceCodeSnippet; /// ## Removed /// This rule is identical to [SIM101] which should be used instead. /// /// ## What it does /// Checks for repeated `isinstance` calls on the same object. /// /// ## Why is this bad? /// Repeated `isinstance` calls on the same object can be merged into a /// single call. /// /// ## Fix safety /// This rule's fix is marked as unsafe on Python 3.10 and later, as combining /// multiple `isinstance` calls with a binary operator (`|`) will fail at /// runtime if any of the operands are themselves tuples. /// /// For example, given `TYPES = (dict, list)`, then /// `isinstance(None, TYPES | set | float)` will raise a `TypeError` at runtime, /// while `isinstance(None, set | float)` will not. /// /// ## Example /// ```python /// def is_number(x): /// return isinstance(x, int) or isinstance(x, float) or isinstance(x, complex) /// ``` /// /// Use instead: /// ```python /// def is_number(x): /// return isinstance(x, (int, float, complex)) /// ``` /// /// Or, for Python 3.10 and later: /// /// ```python /// def is_number(x): /// return isinstance(x, int | float | complex) /// ``` /// /// ## Options /// - `target-version` /// /// ## References /// - [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance) /// /// [SIM101]: https://docs.astral.sh/ruff/rules/duplicate-isinstance-call/ #[derive(ViolationMetadata)] #[violation_metadata(removed_since = "0.5.0")] pub(crate) struct RepeatedIsinstanceCalls { expression: SourceCodeSnippet, } /// PLR1701 impl AlwaysFixableViolation for RepeatedIsinstanceCalls { #[derive_message_formats] fn message(&self) -> String { if let Some(expression) = self.expression.full_display() { format!("Merge `isinstance` calls: `{expression}`") } else { "Merge `isinstance` calls".to_string() } } fn fix_title(&self) -> String { if let Some(expression) = self.expression.full_display() { format!("Replace with `{expression}`") } else { "Replace with merged `isinstance` call".to_string() } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/yield_in_init.rs
crates/ruff_linter/src/rules/pylint/rules/yield_in_init.rs
use ruff_python_ast::Expr; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::in_dunder_method; /// ## What it does /// Checks for `__init__` methods that are turned into generators by the /// inclusion of `yield` or `yield from` expressions. /// /// ## Why is this bad? /// The `__init__` method is the constructor for a given Python class, /// responsible for initializing, rather than creating, new objects. /// /// The `__init__` method has to return `None`. By including a `yield` or /// `yield from` expression in an `__init__`, the method will return a /// generator object when called at runtime, resulting in a runtime error. /// /// ## Example /// ```python /// class InitIsGenerator: /// def __init__(self, i): /// yield i /// ``` /// /// ## References /// - [CodeQL: `py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.245")] pub(crate) struct YieldInInit; impl Violation for YieldInInit { #[derive_message_formats] fn message(&self) -> String { "`__init__` method is a generator".to_string() } } /// PLE0100 pub(crate) fn yield_in_init(checker: &Checker, expr: &Expr) { if in_dunder_method("__init__", checker.semantic(), checker.settings()) { checker.report_diagnostic(YieldInInit, expr.range()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/continue_in_finally.rs
crates/ruff_linter/src/rules/pylint/rules/continue_in_finally.rs
use ruff_python_ast::{self as ast, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `continue` statements inside `finally` /// /// ## Why is this bad? /// `continue` statements were not allowed within `finally` clauses prior to /// Python 3.8. Using a `continue` statement within a `finally` clause can /// cause a `SyntaxError`. /// /// ## Example /// ```python /// while True: /// try: /// pass /// finally: /// continue /// ``` /// /// Use instead: /// ```python /// while True: /// try: /// pass /// except Exception: /// pass /// else: /// continue /// ``` /// /// ## Options /// - `target-version` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct ContinueInFinally; impl Violation for ContinueInFinally { #[derive_message_formats] fn message(&self) -> String { "`continue` not supported inside `finally` clause".to_string() } } fn traverse_body(checker: &Checker, body: &[Stmt]) { for stmt in body { if stmt.is_continue_stmt() { checker.report_diagnostic(ContinueInFinally, stmt.range()); } match stmt { Stmt::If(ast::StmtIf { body, elif_else_clauses, .. }) => { traverse_body(checker, body); for clause in elif_else_clauses { traverse_body(checker, &clause.body); } } Stmt::Try(ast::StmtTry { body, orelse, .. }) => { traverse_body(checker, body); traverse_body(checker, orelse); } Stmt::For(ast::StmtFor { orelse, .. }) | Stmt::While(ast::StmtWhile { orelse, .. }) => { traverse_body(checker, orelse); } Stmt::With(ast::StmtWith { body, .. }) => { traverse_body(checker, body); } Stmt::Match(ast::StmtMatch { cases, .. }) => { for case in cases { traverse_body(checker, &case.body); } } _ => {} } } } /// PLE0116 pub(crate) fn continue_in_finally(checker: &Checker, body: &[Stmt]) { traverse_body(checker, body); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/bad_string_format_character.rs
crates/ruff_linter/src/rules/pylint/rules/bad_string_format_character.rs
use std::str::FromStr; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, ExprStringLiteral, StringFlags, StringLiteral}; use ruff_python_literal::{ cformat::{CFormatErrorType, CFormatString}, format::FormatPart, format::FromTemplate, format::{FormatSpec, FormatSpecError, FormatString}, }; use ruff_text_size::{Ranged, TextRange}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for unsupported format types in format strings. /// /// ## Why is this bad? /// An invalid format string character will result in an error at runtime. /// /// ## Example /// ```python /// # `z` is not a valid format type. /// print("%z" % "1") /// /// print("{:z}".format("1")) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.283")] pub(crate) struct BadStringFormatCharacter { format_char: char, } impl Violation for BadStringFormatCharacter { #[derive_message_formats] fn message(&self) -> String { let BadStringFormatCharacter { format_char } = self; format!("Unsupported format character '{format_char}'") } } /// PLE1300 /// Ex) `"{:z}".format("1")` pub(crate) fn call(checker: &Checker, string: &str, range: TextRange) { if let Ok(format_string) = FormatString::from_str(string) { for part in &format_string.format_parts { let FormatPart::Field { format_spec, .. } = part else { continue; }; match FormatSpec::parse(format_spec) { Err(FormatSpecError::InvalidFormatType) => { checker.report_diagnostic( BadStringFormatCharacter { // The format type character is always the last one. // More info in the official spec: // https://docs.python.org/3/library/string.html#format-specification-mini-language format_char: format_spec.chars().last().unwrap(), }, range, ); } Err(_) => {} Ok(FormatSpec::Static(_)) => {} Ok(FormatSpec::Dynamic(format_spec)) => { for placeholder in format_spec.placeholders { let FormatPart::Field { format_spec, .. } = placeholder else { continue; }; if let Err(FormatSpecError::InvalidFormatType) = FormatSpec::parse(&format_spec) { checker.report_diagnostic( BadStringFormatCharacter { // The format type character is always the last one. // More info in the official spec: // https://docs.python.org/3/library/string.html#format-specification-mini-language format_char: format_spec.chars().last().unwrap(), }, range, ); } } } } } } } /// PLE1300 /// Ex) `"%z" % "1"` pub(crate) fn percent(checker: &Checker, expr: &Expr, format_string: &ExprStringLiteral) { for StringLiteral { value: _, node_index: _, range, flags, } in &format_string.value { let string = checker.locator().slice(range); let string = &string [usize::from(flags.opener_len())..(string.len() - usize::from(flags.closer_len()))]; // Parse the format string (e.g. `"%s"`) into a list of `PercentFormat`. if let Err(format_error) = CFormatString::from_str(string) { if let CFormatErrorType::UnsupportedFormatChar(format_char) = format_error.typ { checker.report_diagnostic(BadStringFormatCharacter { format_char }, expr.range()); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/import_outside_top_level.rs
crates/ruff_linter/src/rules/pylint/rules/import_outside_top_level.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; use crate::Violation; use crate::rules::flake8_tidy_imports::rules::BannedModuleImportPolicies; use crate::{ checkers::ast::Checker, codes::Rule, rules::flake8_tidy_imports::matchers::NameMatchPolicy, }; /// ## What it does /// Checks for `import` statements outside of a module's top-level scope, such /// as within a function or class definition. /// /// ## Why is this bad? /// [PEP 8] recommends placing imports not only at the top-level of a module, /// but at the very top of the file, "just after any module comments and /// docstrings, and before module globals and constants." /// /// `import` statements have effects that are global in scope; defining them at /// the top level has a number of benefits. For example, it makes it easier to /// identify the dependencies of a module, and ensures that any invalid imports /// are caught regardless of whether a specific function is called or class is /// instantiated. /// /// An import statement would typically be placed within a function only to /// avoid a circular dependency, to defer a costly module load, or to avoid /// loading a dependency altogether in a certain runtime environment. /// /// ## Example /// ```python /// def print_python_version(): /// import platform /// /// print(platform.python_version()) /// ``` /// /// Use instead: /// ```python /// import platform /// /// /// def print_python_version(): /// print(platform.python_version()) /// ``` /// /// ## See also /// This rule will ignore import statements configured in /// [`lint.flake8-tidy-imports.banned-module-level-imports`][banned-module-level-imports] /// if the rule [`banned-module-level-imports`][TID253] is enabled. /// /// [banned-module-level-imports]: https://docs.astral.sh/ruff/settings/#lint_flake8-tidy-imports_banned-module-level-imports /// [TID253]: https://docs.astral.sh/ruff/rules/banned-module-level-imports/ /// [PEP 8]: https://peps.python.org/pep-0008/#imports #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.12.0")] pub(crate) struct ImportOutsideTopLevel; impl Violation for ImportOutsideTopLevel { #[derive_message_formats] fn message(&self) -> String { "`import` should be at the top-level of a file".to_string() } } /// PLC0415 pub(crate) fn import_outside_top_level(checker: &Checker, stmt: &Stmt) { if checker.semantic().current_scope().kind.is_module() { // "Top-level" imports are allowed return; } // Check if any of the non-top-level imports are banned by TID253 // before emitting the diagnostic to avoid conflicts. if checker.is_rule_enabled(Rule::BannedModuleLevelImports) { let mut all_aliases_banned = true; let mut has_alias = false; for (policy, node) in &BannedModuleImportPolicies::new(stmt, checker) { if node.is_alias() { has_alias = true; all_aliases_banned &= is_banned_module_level_import(&policy, checker); } // If the entire import is banned else if is_banned_module_level_import(&policy, checker) { return; } } if has_alias && all_aliases_banned { return; } } // Emit the diagnostic checker.report_diagnostic(ImportOutsideTopLevel, stmt.range()); } fn is_banned_module_level_import(policy: &NameMatchPolicy, checker: &Checker) -> bool { policy .find( checker .settings() .flake8_tidy_imports .banned_module_level_imports(), ) .is_some() }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/redefined_loop_name.rs
crates/ruff_linter/src/rules/pylint/rules/redefined_loop_name.rs
use std::{fmt, iter}; use regex::Regex; use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Stmt, WithItem}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt}; use ruff_python_semantic::SemanticModel; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for variables defined in `for` loops and `with` statements that /// get overwritten within the body, for example by another `for` loop or /// `with` statement or by direct assignment. /// /// ## Why is this bad? /// Redefinition of a loop variable inside the loop's body causes its value /// to differ from the original loop iteration for the remainder of the /// block, in a way that will likely cause bugs. /// /// In Python, unlike many other languages, `for` loops and `with` /// statements don't define their own scopes. Therefore, a nested loop that /// uses the same target variable name as an outer loop will reuse the same /// actual variable, and the value from the last iteration will "leak out" /// into the remainder of the enclosing loop. /// /// While this mistake is easy to spot in small examples, it can be hidden /// in larger blocks of code, where the definition and redefinition of the /// variable may not be visible at the same time. /// /// ## Example /// ```python /// for i in range(10): /// i = 9 /// print(i) # prints 9 every iteration /// /// for i in range(10): /// for i in range(10): # original value overwritten /// pass /// print(i) # also prints 9 every iteration /// /// with path1.open() as f: /// with path2.open() as f: /// f = path2.open() /// print(f.readline()) # prints a line from path2 /// ``` /// /// ## Options /// /// The rule ignores assignments to dummy variables, as specified by: /// /// - `lint.dummy-variable-rgx` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.252")] pub(crate) struct RedefinedLoopName { name: String, outer_kind: OuterBindingKind, inner_kind: InnerBindingKind, } impl Violation for RedefinedLoopName { #[derive_message_formats] fn message(&self) -> String { let RedefinedLoopName { name, outer_kind, inner_kind, } = self; // Prefix the nouns describing the outer and inner kinds with "outer" and "inner" // to better distinguish them, but to avoid confusion, only do so if the outer and inner // kinds are equal. For example, instead of: // // "Outer `for` loop variable `i` overwritten by inner assignment target." // // We have: // // "`for` loop variable `i` overwritten by assignment target." // // While at the same time, we have: // // "Outer `for` loop variable `i` overwritten by inner `for` loop target." // "Outer `with` statement variable `f` overwritten by inner `with` statement target." if outer_kind == inner_kind { format!("Outer {outer_kind} variable `{name}` overwritten by inner {inner_kind} target") } else { format!("{outer_kind} variable `{name}` overwritten by {inner_kind} target") } } } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum OuterBindingKind { For, With, } impl fmt::Display for OuterBindingKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { OuterBindingKind::For => fmt.write_str("`for` loop"), OuterBindingKind::With => fmt.write_str("`with` statement"), } } } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum InnerBindingKind { For, With, Assignment, } impl fmt::Display for InnerBindingKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { InnerBindingKind::For => fmt.write_str("`for` loop"), InnerBindingKind::With => fmt.write_str("`with` statement"), InnerBindingKind::Assignment => fmt.write_str("assignment"), } } } impl PartialEq<InnerBindingKind> for OuterBindingKind { fn eq(&self, other: &InnerBindingKind) -> bool { matches!( (self, other), (OuterBindingKind::For, InnerBindingKind::For) | (OuterBindingKind::With, InnerBindingKind::With) ) } } struct ExprWithOuterBindingKind<'a> { expr: &'a Expr, binding_kind: OuterBindingKind, } struct ExprWithInnerBindingKind<'a> { expr: &'a Expr, binding_kind: InnerBindingKind, } struct InnerForWithAssignTargetsVisitor<'a, 'b> { context: &'a SemanticModel<'b>, dummy_variable_rgx: &'a Regex, assignment_targets: Vec<ExprWithInnerBindingKind<'a>>, } impl<'b> StatementVisitor<'b> for InnerForWithAssignTargetsVisitor<'_, 'b> { fn visit_stmt(&mut self, stmt: &'b Stmt) { // Collect target expressions. match stmt { Stmt::For(ast::StmtFor { target, .. }) => { self.assignment_targets.extend( assignment_targets_from_expr(target, self.dummy_variable_rgx).map(|expr| { ExprWithInnerBindingKind { expr, binding_kind: InnerBindingKind::For, } }), ); } Stmt::With(ast::StmtWith { items, .. }) => { self.assignment_targets.extend( assignment_targets_from_with_items(items, self.dummy_variable_rgx).map( |expr| ExprWithInnerBindingKind { expr, binding_kind: InnerBindingKind::With, }, ), ); } Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { // Check for single-target assignments which are of the // form `x = cast(..., x)`. if targets .first() .is_some_and(|target| assignment_is_cast_expr(value, target, self.context)) { return; } self.assignment_targets.extend( assignment_targets_from_assign_targets(targets, self.dummy_variable_rgx).map( |expr| ExprWithInnerBindingKind { expr, binding_kind: InnerBindingKind::Assignment, }, ), ); } Stmt::AugAssign(ast::StmtAugAssign { target, .. }) => { self.assignment_targets.extend( assignment_targets_from_expr(target, self.dummy_variable_rgx).map(|expr| { ExprWithInnerBindingKind { expr, binding_kind: InnerBindingKind::Assignment, } }), ); } Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => { if value.is_none() { return; } self.assignment_targets.extend( assignment_targets_from_expr(target, self.dummy_variable_rgx).map(|expr| { ExprWithInnerBindingKind { expr, binding_kind: InnerBindingKind::Assignment, } }), ); } _ => {} } // Decide whether to recurse. match stmt { // Don't recurse into blocks that create a new scope. Stmt::ClassDef(_) | Stmt::FunctionDef(_) => {} // Otherwise, do recurse. _ => { walk_stmt(self, stmt); } } } } /// Checks whether the given assignment value is a `typing.cast` expression /// and that the target name is the same as the argument name. /// /// Example: /// ```python /// from typing import cast /// /// x = cast(int, x) /// ``` fn assignment_is_cast_expr(value: &Expr, target: &Expr, semantic: &SemanticModel) -> bool { if !semantic.seen_typing() { return false; } let Expr::Call(ast::ExprCall { func, arguments: Arguments { args, .. }, .. }) = value else { return false; }; let Expr::Name(ast::ExprName { id: target_id, .. }) = target else { return false; }; if args.len() != 2 { return false; } let Expr::Name(ast::ExprName { id: arg_id, .. }) = &args[1] else { return false; }; if arg_id != target_id { return false; } semantic.match_typing_expr(func, "cast") } fn assignment_targets_from_expr<'a>( expr: &'a Expr, dummy_variable_rgx: &'a Regex, ) -> Box<dyn Iterator<Item = &'a Expr> + 'a> { // The Box is necessary to ensure the match arms have the same return type - we can't use // a cast to "impl Iterator", since at the time of writing that is only allowed for // return types and argument types. match expr { Expr::Attribute(ast::ExprAttribute { ctx: ExprContext::Store, .. }) => Box::new(iter::once(expr)), Expr::Subscript(ast::ExprSubscript { ctx: ExprContext::Store, .. }) => Box::new(iter::once(expr)), Expr::Starred(ast::ExprStarred { ctx: ExprContext::Store, value, range: _, node_index: _, }) => Box::new(iter::once(value.as_ref())), Expr::Name(ast::ExprName { ctx: ExprContext::Store, id, range: _, node_index: _, }) => { // Ignore dummy variables. if dummy_variable_rgx.is_match(id) { Box::new(iter::empty()) } else { Box::new(iter::once(expr)) } } Expr::List(ast::ExprList { ctx: ExprContext::Store, elts, range: _, node_index: _, }) => Box::new( elts.iter() .flat_map(|elt| assignment_targets_from_expr(elt, dummy_variable_rgx)), ), Expr::Tuple(ast::ExprTuple { ctx: ExprContext::Store, elts, range: _, node_index: _, parenthesized: _, }) => Box::new( elts.iter() .flat_map(|elt| assignment_targets_from_expr(elt, dummy_variable_rgx)), ), _ => Box::new(iter::empty()), } } fn assignment_targets_from_with_items<'a>( items: &'a [WithItem], dummy_variable_rgx: &'a Regex, ) -> impl Iterator<Item = &'a Expr> + 'a { items .iter() .filter_map(|item| { item.optional_vars .as_ref() .map(|expr| assignment_targets_from_expr(expr, dummy_variable_rgx)) }) .flatten() } fn assignment_targets_from_assign_targets<'a>( targets: &'a [Expr], dummy_variable_rgx: &'a Regex, ) -> impl Iterator<Item = &'a Expr> + 'a { targets .iter() .flat_map(|target| assignment_targets_from_expr(target, dummy_variable_rgx)) } /// PLW2901 pub(crate) fn redefined_loop_name(checker: &Checker, stmt: &Stmt) { let (outer_assignment_targets, inner_assignment_targets) = match stmt { Stmt::With(ast::StmtWith { items, body, .. }) => { let outer_assignment_targets: Vec<ExprWithOuterBindingKind> = assignment_targets_from_with_items(items, &checker.settings().dummy_variable_rgx) .map(|expr| ExprWithOuterBindingKind { expr, binding_kind: OuterBindingKind::With, }) .collect(); let mut visitor = InnerForWithAssignTargetsVisitor { context: checker.semantic(), dummy_variable_rgx: &checker.settings().dummy_variable_rgx, assignment_targets: vec![], }; for stmt in body { visitor.visit_stmt(stmt); } (outer_assignment_targets, visitor.assignment_targets) } Stmt::For(ast::StmtFor { target, body, .. }) => { let outer_assignment_targets: Vec<ExprWithOuterBindingKind> = assignment_targets_from_expr(target, &checker.settings().dummy_variable_rgx) .map(|expr| ExprWithOuterBindingKind { expr, binding_kind: OuterBindingKind::For, }) .collect(); let mut visitor = InnerForWithAssignTargetsVisitor { context: checker.semantic(), dummy_variable_rgx: &checker.settings().dummy_variable_rgx, assignment_targets: vec![], }; for stmt in body { visitor.visit_stmt(stmt); } (outer_assignment_targets, visitor.assignment_targets) } _ => panic!("redefined_loop_name called on Statement that is not a `With` or `For`"), }; for outer_assignment_target in &outer_assignment_targets { for inner_assignment_target in &inner_assignment_targets { // Compare the targets structurally. if ComparableExpr::from(outer_assignment_target.expr) .eq(&(ComparableExpr::from(inner_assignment_target.expr))) { checker.report_diagnostic( RedefinedLoopName { name: checker.generator().expr(outer_assignment_target.expr), outer_kind: outer_assignment_target.binding_kind, inner_kind: inner_assignment_target.binding_kind, }, inner_assignment_target.expr.range(), ); } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/type_name_incorrect_variance.rs
crates/ruff_linter/src/rules/pylint/rules/type_name_incorrect_variance.rs
use std::fmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::type_param_name; /// ## What it does /// Checks for type names that do not match the variance of their associated /// type parameter. /// /// ## Why is this bad? /// [PEP 484] recommends the use of the `_co` and `_contra` suffixes for /// covariant and contravariant type parameters, respectively (while invariant /// type parameters should not have any such suffix). /// /// ## Example /// ```python /// from typing import TypeVar /// /// T = TypeVar("T", covariant=True) /// U = TypeVar("U", contravariant=True) /// V_co = TypeVar("V_co") /// ``` /// /// Use instead: /// ```python /// from typing import TypeVar /// /// T_co = TypeVar("T_co", covariant=True) /// U_contra = TypeVar("U_contra", contravariant=True) /// V = TypeVar("V") /// ``` /// /// ## References /// - [Python documentation: `typing` — Support for type hints](https://docs.python.org/3/library/typing.html) /// - [PEP 483 – The Theory of Type Hints: Covariance and Contravariance](https://peps.python.org/pep-0483/#covariance-and-contravariance) /// - [PEP 484 – Type Hints: Covariance and contravariance](https://peps.python.org/pep-0484/#covariance-and-contravariance) /// /// [PEP 484]: https://peps.python.org/pep-0484/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.278")] pub(crate) struct TypeNameIncorrectVariance { kind: VarKind, param_name: String, variance: VarVariance, replacement_name: String, } impl Violation for TypeNameIncorrectVariance { #[derive_message_formats] fn message(&self) -> String { let TypeNameIncorrectVariance { kind, param_name, variance, replacement_name, } = self; format!( "`{kind}` name \"{param_name}\" does not reflect its {variance}; consider renaming it to \"{replacement_name}\"" ) } } /// PLC0105 pub(crate) fn type_name_incorrect_variance(checker: &Checker, value: &Expr) { // If the typing modules were never imported, we'll never match below. if !checker.semantic().seen_typing() { return; } let Expr::Call(ast::ExprCall { func, arguments, .. }) = value else { return; }; let Some(param_name) = type_param_name(arguments) else { return; }; let covariant = arguments .find_keyword("covariant") .map(|keyword| &keyword.value); let contravariant = arguments .find_keyword("contravariant") .map(|keyword| &keyword.value); if !mismatch(param_name, covariant, contravariant) { return; } let Some(kind) = checker .semantic() .resolve_qualified_name(func) .and_then(|qualified_name| { if checker .semantic() .match_typing_qualified_name(&qualified_name, "ParamSpec") { Some(VarKind::ParamSpec) } else if checker .semantic() .match_typing_qualified_name(&qualified_name, "TypeVar") { Some(VarKind::TypeVar) } else { None } }) else { return; }; let variance = variance(covariant, contravariant); let name_root = param_name .trim_end_matches("_co") .trim_end_matches("_contra"); let replacement_name: String = match variance { VarVariance::Bivariance => return, // Bivariate types are invalid, so ignore them for this rule. VarVariance::Covariance => format!("{name_root}_co"), VarVariance::Contravariance => format!("{name_root}_contra"), VarVariance::Invariance => name_root.to_string(), }; checker.report_diagnostic( TypeNameIncorrectVariance { kind, param_name: param_name.to_string(), variance, replacement_name, }, func.range(), ); } /// Returns `true` if the parameter name does not match its type variance. fn mismatch(param_name: &str, covariant: Option<&Expr>, contravariant: Option<&Expr>) -> bool { if param_name.ends_with("_co") { covariant.is_none_or(|covariant| !is_const_true(covariant)) } else if param_name.ends_with("_contra") { contravariant.is_none_or(|contravariant| !is_const_true(contravariant)) } else { covariant.is_some_and(is_const_true) || contravariant.is_some_and(is_const_true) } } /// Return the variance of the type parameter. fn variance(covariant: Option<&Expr>, contravariant: Option<&Expr>) -> VarVariance { match ( covariant.map(is_const_true), contravariant.map(is_const_true), ) { (Some(true), Some(true)) => VarVariance::Bivariance, (Some(true), _) => VarVariance::Covariance, (_, Some(true)) => VarVariance::Contravariance, _ => VarVariance::Invariance, } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum VarKind { TypeVar, ParamSpec, } impl fmt::Display for VarKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { VarKind::TypeVar => fmt.write_str("TypeVar"), VarKind::ParamSpec => fmt.write_str("ParamSpec"), } } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum VarVariance { Bivariance, Covariance, Contravariance, Invariance, } impl fmt::Display for VarVariance { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { VarVariance::Bivariance => fmt.write_str("bivariance"), VarVariance::Covariance => fmt.write_str("covariance"), VarVariance::Contravariance => fmt.write_str("contravariance"), VarVariance::Invariance => fmt.write_str("invariance"), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/invalid_bool_return.rs
crates/ruff_linter/src/rules/pylint/rules/invalid_bool_return.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::ReturnStatementVisitor; use ruff_python_ast::identifier::Identifier; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast}; use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::terminal::Terminal; use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `__bool__` implementations that return a type other than `bool`. /// /// ## Why is this bad? /// The `__bool__` method should return a `bool` object. Returning a different /// type may cause unexpected behavior. /// /// ## Example /// ```python /// class Foo: /// def __bool__(self): /// return 2 /// ``` /// /// Use instead: /// ```python /// class Foo: /// def __bool__(self): /// return True /// ``` /// /// ## References /// - [Python documentation: The `__bool__` method](https://docs.python.org/3/reference/datamodel.html#object.__bool__) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.3.3")] pub(crate) struct InvalidBoolReturnType; impl Violation for InvalidBoolReturnType { #[derive_message_formats] fn message(&self) -> String { "`__bool__` does not return `bool`".to_string() } } /// PLE0304 pub(crate) fn invalid_bool_return(checker: &Checker, function_def: &ast::StmtFunctionDef) { if function_def.name.as_str() != "__bool__" { return; } if !checker.semantic().current_scope().kind.is_class() { return; } if is_stub(function_def, checker.semantic()) { return; } // Determine the terminal behavior (i.e., implicit return, no return, etc.). let terminal = Terminal::from_function(function_def); // If every control flow path raises an exception, ignore the function. if terminal == Terminal::Raise { return; } // If there are no return statements, add a diagnostic. if terminal == Terminal::Implicit { checker.report_diagnostic(InvalidBoolReturnType, function_def.identifier()); return; } let returns = { let mut visitor = ReturnStatementVisitor::default(); visitor.visit_body(&function_def.body); visitor.returns }; for stmt in returns { if let Some(value) = stmt.value.as_deref() { if !matches!( ResolvedPythonType::from(value), ResolvedPythonType::Unknown | ResolvedPythonType::Atom(PythonType::Number(NumberLike::Bool)) ) { checker.report_diagnostic(InvalidBoolReturnType, value.range()); } } else { // Disallow implicit `None`. checker.report_diagnostic(InvalidBoolReturnType, stmt.range()); } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pylint/rules/useless_exception_statement.rs
crates/ruff_linter/src/rules/pylint/rules/useless_exception_statement.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::{SemanticModel, analyze}; use ruff_python_stdlib::builtins; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::preview::is_custom_exception_checking_enabled; use crate::{Edit, Fix, FixAvailability, Violation}; use ruff_python_ast::PythonVersion; /// ## What it does /// Checks for an exception that is not raised. /// /// ## Why is this bad? /// It's unnecessary to create an exception without raising it. For example, /// `ValueError("...")` on its own will have no effect (unlike /// `raise ValueError("...")`) and is likely a mistake. /// /// ## Known problems /// This rule only detects built-in exceptions, like `ValueError`, and does /// not catch user-defined exceptions. /// /// In [preview], this rule will also detect user-defined exceptions, but only /// the ones defined in the file being checked. /// /// ## Example /// ```python /// ValueError("...") /// ``` /// /// Use instead: /// ```python /// raise ValueError("...") /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe, as converting a useless exception /// statement to a `raise` statement will change the program's behavior. /// /// [preview]: https://docs.astral.sh/ruff/preview/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct UselessExceptionStatement; impl Violation for UselessExceptionStatement { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Missing `raise` statement on exception".to_string() } fn fix_title(&self) -> Option<String> { Some("Add `raise` keyword".to_string()) } } /// PLW0133 pub(crate) fn useless_exception_statement(checker: &Checker, expr: &ast::StmtExpr) { let Expr::Call(ast::ExprCall { func, .. }) = expr.value.as_ref() else { return; }; if is_builtin_exception(func, checker.semantic(), checker.target_version()) || (is_custom_exception_checking_enabled(checker.settings()) && is_custom_exception(func, checker.semantic(), checker.target_version())) { let mut diagnostic = checker.report_diagnostic(UselessExceptionStatement, expr.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion( "raise ".to_string(), expr.start(), ))); } } /// Returns `true` if the given expression is a builtin exception. fn is_builtin_exception( expr: &Expr, semantic: &SemanticModel, target_version: PythonVersion, ) -> bool { semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["" | "builtins", name] if builtins::is_exception(name, target_version.minor)) }) } /// Returns `true` if the given expression is a custom exception. fn is_custom_exception( expr: &Expr, semantic: &SemanticModel, target_version: PythonVersion, ) -> bool { let Some(qualified_name) = semantic.resolve_qualified_name(expr) else { return false; }; let Some(symbol) = qualified_name.segments().last() else { return false; }; let Some(binding_id) = semantic.lookup_symbol(symbol) else { return false; }; let binding = semantic.binding(binding_id); let Some(source) = binding.source else { return false; }; let statement = semantic.statement(source); if let ast::Stmt::ClassDef(class_def) = statement { return analyze::class::any_qualified_base_class(class_def, semantic, &|qualified_name| { if let ["" | "builtins", name] = qualified_name.segments() { return builtins::is_exception(name, target_version.minor); } false }); } false }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pydoclint/settings.rs
crates/ruff_linter/src/rules/pydoclint/settings.rs
//! Settings for the `pydoclint` plugin. use crate::display_settings; use ruff_macros::CacheKey; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, Default, CacheKey)] pub struct Settings { pub ignore_one_line_docstrings: bool, } impl Display for Settings { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { display_settings! { formatter = f, namespace = "linter.pydoclint", fields = [self.ignore_one_line_docstrings] } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pydoclint/mod.rs
crates/ruff_linter/src/rules/pydoclint/mod.rs
//! Rules from [pydoclint](https://pypi.org/project/pydoclint/). pub(crate) mod rules; pub mod settings; #[cfg(test)] mod tests { use std::path::Path; use anyhow::Result; use test_case::test_case; use crate::registry::Rule; use crate::rules::pydocstyle; use crate::rules::pydocstyle::settings::Convention; use crate::test::test_path; use crate::{assert_diagnostics, settings}; use super::settings::Settings; #[test_case(Rule::DocstringMissingException, Path::new("DOC501.py"))] fn rules(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!("{}_{}", rule_code.name(), path.to_string_lossy()); let diagnostics = test_path( Path::new("pydoclint").join(path).as_path(), &settings::LinterSettings::for_rule(rule_code), )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test_case(Rule::DocstringExtraneousParameter, Path::new("DOC102_google.py"))] #[test_case(Rule::DocstringMissingReturns, Path::new("DOC201_google.py"))] #[test_case(Rule::DocstringExtraneousReturns, Path::new("DOC202_google.py"))] #[test_case(Rule::DocstringMissingYields, Path::new("DOC402_google.py"))] #[test_case(Rule::DocstringExtraneousYields, Path::new("DOC403_google.py"))] #[test_case(Rule::DocstringMissingException, Path::new("DOC501_google.py"))] #[test_case(Rule::DocstringExtraneousException, Path::new("DOC502_google.py"))] fn rules_google_style(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!("{}_{}", rule_code.name(), path.to_string_lossy()); let diagnostics = test_path( Path::new("pydoclint").join(path).as_path(), &settings::LinterSettings { pydocstyle: pydocstyle::settings::Settings { convention: Some(Convention::Google), ..pydocstyle::settings::Settings::default() }, ..settings::LinterSettings::for_rule(rule_code) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test_case(Rule::DocstringExtraneousParameter, Path::new("DOC102_numpy.py"))] #[test_case(Rule::DocstringMissingReturns, Path::new("DOC201_numpy.py"))] #[test_case(Rule::DocstringExtraneousReturns, Path::new("DOC202_numpy.py"))] #[test_case(Rule::DocstringMissingYields, Path::new("DOC402_numpy.py"))] #[test_case(Rule::DocstringExtraneousYields, Path::new("DOC403_numpy.py"))] #[test_case(Rule::DocstringMissingException, Path::new("DOC501_numpy.py"))] #[test_case(Rule::DocstringExtraneousException, Path::new("DOC502_numpy.py"))] fn rules_numpy_style(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!("{}_{}", rule_code.name(), path.to_string_lossy()); let diagnostics = test_path( Path::new("pydoclint").join(path).as_path(), &settings::LinterSettings { pydocstyle: pydocstyle::settings::Settings { convention: Some(Convention::Numpy), ..pydocstyle::settings::Settings::default() }, ..settings::LinterSettings::for_rule(rule_code) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test_case(Rule::DocstringMissingReturns, Path::new("DOC201_google.py"))] #[test_case(Rule::DocstringMissingYields, Path::new("DOC402_google.py"))] #[test_case(Rule::DocstringMissingException, Path::new("DOC501_google.py"))] fn rules_google_style_ignore_one_line(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!( "{}_{}_ignore_one_line", rule_code.name(), path.to_string_lossy() ); let diagnostics = test_path( Path::new("pydoclint").join(path).as_path(), &settings::LinterSettings { pydoclint: Settings { ignore_one_line_docstrings: true, }, pydocstyle: pydocstyle::settings::Settings { convention: Some(Convention::Google), ..pydocstyle::settings::Settings::default() }, ..settings::LinterSettings::for_rule(rule_code) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs
crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs
use itertools::Itertools; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::{map_callable, map_subscript}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, Stmt, visitor}; use ruff_python_semantic::analyze::{function_type, visibility}; use ruff_python_semantic::{Definition, SemanticModel}; use ruff_python_stdlib::identifiers::is_identifier; use ruff_source_file::{LineRanges, NewlineWithTrailingNewline}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use rustc_hash::FxHashMap; use crate::Violation; use crate::checkers::ast::Checker; use crate::docstrings::Docstring; use crate::docstrings::sections::{SectionContext, SectionContexts, SectionKind}; use crate::docstrings::styles::SectionStyle; use crate::registry::Rule; use crate::rules::pydocstyle::settings::Convention; /// ## What it does /// Checks for function docstrings that include parameters which are not /// in the function signature. /// /// ## Why is this bad? /// If a docstring documents a parameter which is not in the function signature, /// it can be misleading to users and/or a sign of incomplete documentation or /// refactors. /// /// ## Example /// ```python /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// acceleration: Rate of change of speed. /// /// Returns: /// Speed as distance divided by time. /// """ /// return distance / time /// ``` /// /// Use instead: /// ```python /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// /// Returns: /// Speed as distance divided by time. /// """ /// return distance / time /// ``` /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.14.1")] pub(crate) struct DocstringExtraneousParameter { id: String, } impl Violation for DocstringExtraneousParameter { #[derive_message_formats] fn message(&self) -> String { let DocstringExtraneousParameter { id } = self; format!("Documented parameter `{id}` is not in the function's signature") } fn fix_title(&self) -> Option<String> { Some("Remove the extraneous parameter from the docstring".to_string()) } } /// ## What it does /// Checks for functions with `return` statements that do not have "Returns" /// sections in their docstrings. /// /// ## Why is this bad? /// A missing "Returns" section is a sign of incomplete documentation. /// /// This rule is not enforced for abstract methods or functions that only return /// `None`. It is also ignored for "stub functions": functions where the body only /// consists of `pass`, `...`, `raise NotImplementedError`, or similar. /// /// ## Example /// ```python /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// """ /// return distance / time /// ``` /// /// Use instead: /// ```python /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// /// Returns: /// Speed as distance divided by time. /// """ /// return distance / time /// ``` /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` /// - `lint.pydocstyle.property-decorators` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.5.6")] pub(crate) struct DocstringMissingReturns; impl Violation for DocstringMissingReturns { #[derive_message_formats] fn message(&self) -> String { "`return` is not documented in docstring".to_string() } fn fix_title(&self) -> Option<String> { Some("Add a \"Returns\" section to the docstring".to_string()) } } /// ## What it does /// Checks for function docstrings with unnecessary "Returns" sections. /// /// ## Why is this bad? /// A function without an explicit `return` statement should not have a /// "Returns" section in its docstring. /// /// This rule is not enforced for abstract methods. It is also ignored for /// "stub functions": functions where the body only consists of `pass`, `...`, /// `raise NotImplementedError`, or similar. /// /// ## Example /// ```python /// def say_hello(n: int) -> None: /// """Says hello to the user. /// /// Args: /// n: Number of times to say hello. /// /// Returns: /// Doesn't return anything. /// """ /// for _ in range(n): /// print("Hello!") /// ``` /// /// Use instead: /// ```python /// def say_hello(n: int) -> None: /// """Says hello to the user. /// /// Args: /// n: Number of times to say hello. /// """ /// for _ in range(n): /// print("Hello!") /// ``` /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.5.6")] pub(crate) struct DocstringExtraneousReturns; impl Violation for DocstringExtraneousReturns { #[derive_message_formats] fn message(&self) -> String { "Docstring should not have a returns section because the function doesn't return anything" .to_string() } fn fix_title(&self) -> Option<String> { Some("Remove the \"Returns\" section".to_string()) } } /// ## What it does /// Checks for functions with `yield` statements that do not have "Yields" sections in /// their docstrings. /// /// ## Why is this bad? /// A missing "Yields" section is a sign of incomplete documentation. /// /// This rule is not enforced for abstract methods or functions that only yield `None`. /// It is also ignored for "stub functions": functions where the body only consists /// of `pass`, `...`, `raise NotImplementedError`, or similar. /// /// ## Example /// ```python /// def count_to_n(n: int) -> int: /// """Generate integers up to *n*. /// /// Args: /// n: The number at which to stop counting. /// """ /// for i in range(1, n + 1): /// yield i /// ``` /// /// Use instead: /// ```python /// def count_to_n(n: int) -> int: /// """Generate integers up to *n*. /// /// Args: /// n: The number at which to stop counting. /// /// Yields: /// int: The number we're at in the count. /// """ /// for i in range(1, n + 1): /// yield i /// ``` /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.5.7")] pub(crate) struct DocstringMissingYields; impl Violation for DocstringMissingYields { #[derive_message_formats] fn message(&self) -> String { "`yield` is not documented in docstring".to_string() } fn fix_title(&self) -> Option<String> { Some("Add a \"Yields\" section to the docstring".to_string()) } } /// ## What it does /// Checks for function docstrings with unnecessary "Yields" sections. /// /// ## Why is this bad? /// A function that doesn't yield anything should not have a "Yields" section /// in its docstring. /// /// This rule is not enforced for abstract methods. It is also ignored for /// "stub functions": functions where the body only consists of `pass`, `...`, /// `raise NotImplementedError`, or similar. /// /// ## Example /// ```python /// def say_hello(n: int) -> None: /// """Says hello to the user. /// /// Args: /// n: Number of times to say hello. /// /// Yields: /// Doesn't yield anything. /// """ /// for _ in range(n): /// print("Hello!") /// ``` /// /// Use instead: /// ```python /// def say_hello(n: int) -> None: /// """Says hello to the user. /// /// Args: /// n: Number of times to say hello. /// """ /// for _ in range(n): /// print("Hello!") /// ``` /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.5.7")] pub(crate) struct DocstringExtraneousYields; impl Violation for DocstringExtraneousYields { #[derive_message_formats] fn message(&self) -> String { "Docstring has a \"Yields\" section but the function doesn't yield anything".to_string() } fn fix_title(&self) -> Option<String> { Some("Remove the \"Yields\" section".to_string()) } } /// ## What it does /// Checks for function docstrings that do not document all explicitly raised /// exceptions. /// /// ## Why is this bad? /// A function should document all exceptions that are directly raised in some /// circumstances. Failing to document an exception that could be raised /// can be misleading to users and/or a sign of incomplete documentation. /// /// This rule is not enforced for abstract methods. It is also ignored for /// "stub functions": functions where the body only consists of `pass`, `...`, /// `raise NotImplementedError`, or similar. /// /// ## Example /// ```python /// class FasterThanLightError(ArithmeticError): ... /// /// /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// /// Returns: /// Speed as distance divided by time. /// """ /// try: /// return distance / time /// except ZeroDivisionError as exc: /// raise FasterThanLightError from exc /// ``` /// /// Use instead: /// ```python /// class FasterThanLightError(ArithmeticError): ... /// /// /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// /// Returns: /// Speed as distance divided by time. /// /// Raises: /// FasterThanLightError: If speed is greater than the speed of light. /// """ /// try: /// return distance / time /// except ZeroDivisionError as exc: /// raise FasterThanLightError from exc /// ``` /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.5.5")] pub(crate) struct DocstringMissingException { id: String, } impl Violation for DocstringMissingException { #[derive_message_formats] fn message(&self) -> String { let DocstringMissingException { id } = self; format!("Raised exception `{id}` missing from docstring") } fn fix_title(&self) -> Option<String> { let DocstringMissingException { id } = self; Some(format!("Add `{id}` to the docstring")) } } /// ## What it does /// Checks for function docstrings that state that exceptions could be raised /// even though they are not directly raised in the function body. /// /// ## Why is this bad? /// Some conventions prefer non-explicit exceptions be omitted from the /// docstring. /// /// This rule is not enforced for abstract methods. It is also ignored for /// "stub functions": functions where the body only consists of `pass`, `...`, /// `raise NotImplementedError`, or similar. /// /// ## Example /// ```python /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// /// Returns: /// Speed as distance divided by time. /// /// Raises: /// ZeroDivisionError: Divided by zero. /// """ /// return distance / time /// ``` /// /// Use instead: /// ```python /// def calculate_speed(distance: float, time: float) -> float: /// """Calculate speed as distance divided by time. /// /// Args: /// distance: Distance traveled. /// time: Time spent traveling. /// /// Returns: /// Speed as distance divided by time. /// """ /// return distance / time /// ``` /// /// ## Known issues /// It may often be desirable to document *all* exceptions that a function /// could possibly raise, even those which are not explicitly raised using /// `raise` statements in the function body. /// /// ## Options /// /// - `lint.pydoclint.ignore-one-line-docstrings` /// - `lint.pydocstyle.convention` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.5.5")] pub(crate) struct DocstringExtraneousException { ids: Vec<String>, } impl Violation for DocstringExtraneousException { #[derive_message_formats] fn message(&self) -> String { let DocstringExtraneousException { ids } = self; if let [id] = ids.as_slice() { format!("Raised exception is not explicitly raised: `{id}`") } else { format!( "Raised exceptions are not explicitly raised: {}", ids.iter().map(|id| format!("`{id}`")).join(", ") ) } } fn fix_title(&self) -> Option<String> { let DocstringExtraneousException { ids } = self; Some(format!( "Remove {} from the docstring", ids.iter().map(|id| format!("`{id}`")).join(", ") )) } } /// A generic docstring section. #[derive(Debug)] struct GenericSection { range: TextRange, } impl Ranged for GenericSection { fn range(&self) -> TextRange { self.range } } impl GenericSection { fn from_section(section: &SectionContext) -> Self { Self { range: section.range(), } } } /// A parameter in a docstring with its text range. #[derive(Debug, Clone)] struct ParameterEntry<'a> { name: &'a str, range: TextRange, } impl Ranged for ParameterEntry<'_> { fn range(&self) -> TextRange { self.range } } /// A "Raises" section in a docstring. #[derive(Debug)] struct RaisesSection<'a> { raised_exceptions: Vec<QualifiedName<'a>>, range: TextRange, } impl Ranged for RaisesSection<'_> { fn range(&self) -> TextRange { self.range } } impl<'a> RaisesSection<'a> { /// Return the raised exceptions for the docstring, or `None` if the docstring does not contain /// a "Raises" section. fn from_section(section: &SectionContext<'a>, style: Option<SectionStyle>) -> Self { Self { raised_exceptions: parse_raises(section.following_lines_str(), style), range: section.range(), } } } /// An "Args" or "Parameters" section in a docstring. #[derive(Debug)] struct ParametersSection<'a> { parameters: Vec<ParameterEntry<'a>>, range: TextRange, } impl Ranged for ParametersSection<'_> { fn range(&self) -> TextRange { self.range } } impl<'a> ParametersSection<'a> { /// Return the parameters for the docstring, or `None` if the docstring does not contain /// an "Args" or "Parameters" section. fn from_section(section: &SectionContext<'a>, style: Option<SectionStyle>) -> Self { Self { parameters: parse_parameters( section.following_lines_str(), section.following_range().start(), style, ), range: section.section_name_range(), } } } #[derive(Debug, Default)] struct DocstringSections<'a> { returns: Option<GenericSection>, yields: Option<GenericSection>, raises: Option<RaisesSection<'a>>, parameters: Option<ParametersSection<'a>>, } impl<'a> DocstringSections<'a> { fn from_sections(sections: &'a SectionContexts, style: Option<SectionStyle>) -> Self { let mut docstring_sections = Self::default(); for section in sections { match section.kind() { SectionKind::Args | SectionKind::Arguments | SectionKind::Parameters => { docstring_sections.parameters = Some(ParametersSection::from_section(&section, style)); } SectionKind::Raises => { docstring_sections.raises = Some(RaisesSection::from_section(&section, style)); } SectionKind::Returns => { docstring_sections.returns = Some(GenericSection::from_section(&section)); } SectionKind::Yields => { docstring_sections.yields = Some(GenericSection::from_section(&section)); } _ => continue, } } docstring_sections } } /// Parse the entries in a "Parameters" section of a docstring. /// /// Attempts to parse using the specified [`SectionStyle`], falling back to the other style if no /// entries are found. fn parse_parameters( content: &str, content_start: TextSize, style: Option<SectionStyle>, ) -> Vec<ParameterEntry<'_>> { match style { Some(SectionStyle::Google) => parse_parameters_google(content, content_start), Some(SectionStyle::Numpy) => parse_parameters_numpy(content, content_start), None => { let entries = parse_parameters_google(content, content_start); if entries.is_empty() { parse_parameters_numpy(content, content_start) } else { entries } } } } /// Parses Google-style "Args" sections of the form: /// /// ```python /// Args: /// a (int): The first number to add. /// b (int): The second number to add. /// ``` fn parse_parameters_google(content: &str, content_start: TextSize) -> Vec<ParameterEntry<'_>> { let mut entries: Vec<ParameterEntry> = Vec::new(); // Find first entry to determine indentation let Some(first_arg) = content.lines().next() else { return entries; }; let indentation = &first_arg[..first_arg.len() - first_arg.trim_start().len()]; let mut current_pos = TextSize::ZERO; for line in content.lines() { let line_start = current_pos; current_pos = content.full_line_end(line_start); if let Some(entry) = line.strip_prefix(indentation) { if entry .chars() .next() .is_some_and(|first_char| !first_char.is_whitespace()) { let Some((before_colon, _)) = entry.split_once(':') else { continue; }; if let Some(param) = before_colon.split_whitespace().next() { let param_name = param.trim_start_matches('*'); if is_identifier(param_name) { let param_start = line_start + indentation.text_len(); let param_end = param_start + param.text_len(); entries.push(ParameterEntry { name: param_name, range: TextRange::new( content_start + param_start, content_start + param_end, ), }); } } } } } entries } /// Parses NumPy-style "Parameters" sections of the form: /// /// ```python /// Parameters /// ---------- /// a : int /// The first number to add. /// b : int /// The second number to add. /// ``` fn parse_parameters_numpy(content: &str, content_start: TextSize) -> Vec<ParameterEntry<'_>> { let mut entries: Vec<ParameterEntry> = Vec::new(); let mut lines = content.lines(); let Some(dashes) = lines.next() else { return entries; }; let indentation = &dashes[..dashes.len() - dashes.trim_start().len()]; let mut current_pos = content.full_line_end(dashes.text_len()); for potential in lines { let line_start = current_pos; current_pos = content.full_line_end(line_start); if let Some(entry) = potential.strip_prefix(indentation) { if entry .chars() .next() .is_some_and(|first_char| !first_char.is_whitespace()) { if let Some(before_colon) = entry.split(':').next() { let param_line = before_colon.trim_end(); // Split on commas to handle comma-separated parameters let mut current_offset = TextSize::from(0); for param_part in param_line.split(',') { let param_part_trimmed = param_part.trim(); let param_name = param_part_trimmed.trim_start_matches('*'); if is_identifier(param_name) { // Calculate the position of this specific parameter part within the line // Account for leading whitespace that gets trimmed let param_start_in_line = current_offset + (param_part.text_len() - param_part_trimmed.text_len()); let param_start = line_start + indentation.text_len() + param_start_in_line; entries.push(ParameterEntry { name: param_name, range: TextRange::at( content_start + param_start, param_part_trimmed.text_len(), ), }); } // Update offset for next iteration: add the part length plus comma length current_offset = current_offset + param_part.text_len() + ','.text_len(); } } } } } entries } /// Parse the entries in a "Raises" section of a docstring. /// /// Attempts to parse using the specified [`SectionStyle`], falling back to the other style if no /// entries are found. fn parse_raises(content: &str, style: Option<SectionStyle>) -> Vec<QualifiedName<'_>> { match style { Some(SectionStyle::Google) => parse_raises_google(content), Some(SectionStyle::Numpy) => parse_raises_numpy(content), None => { let entries = parse_raises_google(content); if entries.is_empty() { parse_raises_numpy(content) } else { entries } } } } /// Parses Google-style "Raises" section of the form: /// /// ```python /// Raises: /// FasterThanLightError: If speed is greater than the speed of light. /// DivisionByZero: If attempting to divide by zero. /// ``` fn parse_raises_google(content: &str) -> Vec<QualifiedName<'_>> { let mut entries: Vec<QualifiedName> = Vec::new(); let mut lines = content.lines().peekable(); let Some(first) = lines.peek() else { return entries; }; let indentation = &first[..first.len() - first.trim_start().len()]; for potential in lines { if let Some(entry) = potential.strip_prefix(indentation) { if let Some(first_char) = entry.chars().next() { if !first_char.is_whitespace() { if let Some(colon_idx) = entry.find(':') { let entry = entry[..colon_idx].trim(); if !entry.is_empty() { entries.push(QualifiedName::user_defined(entry)); } } } } } else { // If we can't strip the expected indentation, check if this is a dedented line // (not blank) - if so, break early as we've reached the end of this section if !potential.trim().is_empty() { break; } } } entries } /// Parses NumPy-style "Raises" section of the form: /// /// ```python /// Raises /// ------ /// FasterThanLightError /// If speed is greater than the speed of light. /// DivisionByZero /// If attempting to divide by zero. /// ``` fn parse_raises_numpy(content: &str) -> Vec<QualifiedName<'_>> { let mut entries: Vec<QualifiedName> = Vec::new(); let mut lines = content.lines(); let Some(dashes) = lines.next() else { return entries; }; let indentation = &dashes[..dashes.len() - dashes.trim_start().len()]; for potential in lines { if let Some(entry) = potential.strip_prefix(indentation) { // Check for Sphinx directives (lines starting with ..) - these indicate the end of the // section. In numpy-style, exceptions are dedented to the same level as sphinx // directives. if entry.starts_with("..") { break; } if let Some(first_char) = entry.chars().next() { if !first_char.is_whitespace() { entries.push(QualifiedName::user_defined(entry.trim_end())); } } } } entries } /// An individual `yield` expression in a function body. #[derive(Debug)] struct YieldEntry { range: TextRange, is_none_yield: bool, } impl Ranged for YieldEntry { fn range(&self) -> TextRange { self.range } } #[expect(clippy::enum_variant_names)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ReturnEntryKind { NotNone, ImplicitNone, ExplicitNone, } /// An individual `return` statement in a function body. #[derive(Debug)] struct ReturnEntry { range: TextRange, kind: ReturnEntryKind, } impl ReturnEntry { const fn is_none_return(&self) -> bool { matches!( &self.kind, ReturnEntryKind::ExplicitNone | ReturnEntryKind::ImplicitNone ) } const fn is_implicit(&self) -> bool { matches!(&self.kind, ReturnEntryKind::ImplicitNone) } } impl Ranged for ReturnEntry { fn range(&self) -> TextRange { self.range } } /// An individual exception raised in a function body. #[derive(Debug)] struct ExceptionEntry<'a> { qualified_name: QualifiedName<'a>, range: TextRange, } impl Ranged for ExceptionEntry<'_> { fn range(&self) -> TextRange { self.range } } /// A summary of documentable statements from the function body #[derive(Debug)] struct BodyEntries<'a> { returns: Vec<ReturnEntry>, yields: Vec<YieldEntry>, raised_exceptions: Vec<ExceptionEntry<'a>>, } /// An AST visitor to extract a summary of documentable statements from a function body. struct BodyVisitor<'a> { returns: Vec<ReturnEntry>, yields: Vec<YieldEntry>, currently_suspended_exceptions: Option<&'a ast::Expr>, raised_exceptions: Vec<ExceptionEntry<'a>>, semantic: &'a SemanticModel<'a>, /// Maps exception variable names to their exception expressions in the current except clause exception_variables: FxHashMap<&'a str, &'a ast::Expr>, } impl<'a> BodyVisitor<'a> { fn new(semantic: &'a SemanticModel) -> Self { Self { returns: Vec::new(), yields: Vec::new(), currently_suspended_exceptions: None, raised_exceptions: Vec::new(), semantic, exception_variables: FxHashMap::default(), } } fn finish(self) -> BodyEntries<'a> { let BodyVisitor { returns, yields, mut raised_exceptions, .. } = self; // Deduplicate exceptions collected: // no need to complain twice about `raise TypeError` not being documented // just because there are two separate `raise TypeError` statements in the function raised_exceptions.sort_unstable_by(|left, right| { left.qualified_name .segments() .cmp(right.qualified_name.segments()) .then_with(|| left.start().cmp(&right.start())) .then_with(|| left.end().cmp(&right.end())) }); raised_exceptions.dedup_by(|left, right| { left.qualified_name.segments() == right.qualified_name.segments() }); BodyEntries { returns, yields, raised_exceptions, } } /// Store `exception` if its qualified name does not correspond to one of the exempt types. fn maybe_store_exception(&mut self, exception: &'a Expr, range: TextRange) { let Some(qualified_name) = self.semantic.resolve_qualified_name(exception) else { return; }; if is_exception_or_base_exception(&qualified_name) { return; } self.raised_exceptions.push(ExceptionEntry { qualified_name, range, }); } } impl<'a> Visitor<'a> for BodyVisitor<'a> { fn visit_except_handler(&mut self, handler: &'a ast::ExceptHandler) { let ast::ExceptHandler::ExceptHandler(handler_inner) = handler; self.currently_suspended_exceptions = handler_inner.type_.as_deref(); // Track exception variable bindings if let Some(name) = handler_inner.name.as_ref() { if let Some(exceptions) = self.currently_suspended_exceptions { // Store the exception expression(s) for later resolution self.exception_variables .insert(name.id.as_str(), exceptions); } } visitor::walk_except_handler(self, handler); self.currently_suspended_exceptions = None; // Clear exception variables when leaving the except handler self.exception_variables.clear(); } fn visit_stmt(&mut self, stmt: &'a Stmt) { match stmt { Stmt::Raise(ast::StmtRaise { exc, .. }) => { if let Some(exc) = exc.as_ref() { // First try to resolve the exception directly if let Some(qualified_name) = self.semantic.resolve_qualified_name(map_callable(exc)) { self.raised_exceptions.push(ExceptionEntry { qualified_name, range: exc.range(), }); } else if let ast::Expr::Name(name) = exc.as_ref() { // If it's a variable name, check if it's bound to an exception in the // current except clause if let Some(exception_expr) = self.exception_variables.get(name.id.as_str()) { if let ast::Expr::Tuple(tuple) = exception_expr { for exception in tuple { self.maybe_store_exception(exception, stmt.range()); } } else { self.maybe_store_exception(exception_expr, stmt.range()); } } } } else if let Some(exceptions) = self.currently_suspended_exceptions { if let ast::Expr::Tuple(tuple) = exceptions { for exception in tuple { self.maybe_store_exception(exception, stmt.range()); } } else { self.maybe_store_exception(exceptions, stmt.range()); } } } Stmt::Return(ast::StmtReturn { range, node_index: _, value: Some(value), }) => { self.returns.push(ReturnEntry { range: *range, kind: if value.is_none_literal_expr() { ReturnEntryKind::ExplicitNone } else { ReturnEntryKind::NotNone }, }); } Stmt::Return(ast::StmtReturn { range, node_index: _,
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/pydoclint/rules/mod.rs
crates/ruff_linter/src/rules/pydoclint/rules/mod.rs
pub(crate) use check_docstring::*; mod check_docstring;
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_commas/mod.rs
crates/ruff_linter/src/rules/flake8_commas/mod.rs
//! Rules from [flake8-commas](https://pypi.org/project/flake8-commas/). pub(crate) mod rules; #[cfg(test)] mod tests { use std::path::Path; use anyhow::Result; use test_case::test_case; use crate::registry::Rule; use crate::test::test_path; use crate::{assert_diagnostics, settings}; #[test_case(Path::new("COM81.py"))] #[test_case(Path::new("COM81_syntax_error.py"))] fn rules(path: &Path) -> Result<()> { let snapshot = path.to_string_lossy().into_owned(); let diagnostics = test_path( Path::new("flake8_commas").join(path).as_path(), &settings::LinterSettings::for_rules(vec![ Rule::MissingTrailingComma, Rule::TrailingCommaOnBareTuple, Rule::ProhibitedTrailingComma, ]), )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_commas/rules/trailing_commas.rs
crates/ruff_linter/src/rules/flake8_commas/rules/trailing_commas.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::token::{TokenKind, Tokens}; use ruff_python_index::Indexer; use ruff_text_size::{Ranged, TextRange}; use crate::Locator; use crate::checkers::ast::LintContext; use crate::{AlwaysFixableViolation, Violation}; use crate::{Edit, Fix}; /// Simplified token type. #[derive(Copy, Clone, PartialEq, Eq)] enum TokenType { Named, String, Newline, NonLogicalNewline, OpeningBracket, ClosingBracket, OpeningSquareBracket, Colon, Comma, OpeningCurlyBracket, Def, For, Lambda, Class, Type, Irrelevant, } /// Simplified token specialized for the task. #[derive(Copy, Clone)] struct SimpleToken { ty: TokenType, range: TextRange, } impl Ranged for SimpleToken { fn range(&self) -> TextRange { self.range } } impl SimpleToken { fn new(ty: TokenType, range: TextRange) -> Self { Self { ty, range } } fn irrelevant() -> SimpleToken { SimpleToken { ty: TokenType::Irrelevant, range: TextRange::default(), } } } impl From<(TokenKind, TextRange)> for SimpleToken { fn from((tok, range): (TokenKind, TextRange)) -> Self { let ty = match tok { TokenKind::Name => TokenType::Named, TokenKind::String => TokenType::String, TokenKind::Newline => TokenType::Newline, TokenKind::NonLogicalNewline => TokenType::NonLogicalNewline, TokenKind::Lpar => TokenType::OpeningBracket, TokenKind::Rpar => TokenType::ClosingBracket, TokenKind::Lsqb => TokenType::OpeningSquareBracket, TokenKind::Rsqb => TokenType::ClosingBracket, TokenKind::Colon => TokenType::Colon, TokenKind::Comma => TokenType::Comma, TokenKind::Lbrace => TokenType::OpeningCurlyBracket, TokenKind::Rbrace => TokenType::ClosingBracket, TokenKind::Def => TokenType::Def, TokenKind::Class => TokenType::Class, TokenKind::Type => TokenType::Type, TokenKind::For => TokenType::For, TokenKind::Lambda => TokenType::Lambda, // Import treated like a function. TokenKind::Import => TokenType::Named, _ => TokenType::Irrelevant, }; #[expect(clippy::inconsistent_struct_constructor)] Self { range, ty } } } /// Comma context type - types of comma-delimited Python constructs. #[derive(Copy, Clone, PartialEq, Eq)] enum ContextType { No, /// Function definition parameter list, e.g. `def foo(a,b,c)`. FunctionParameters, /// Call argument-like item list, e.g. `f(1,2,3)`, `foo()(1,2,3)`. CallArguments, /// Tuple-like item list, e.g. `(1,2,3)`. Tuple, /// Subscript item list, e.g. `x[1,2,3]`, `foo()[1,2,3]`. Subscript, /// List-like item list, e.g. `[1,2,3]`. List, /// Dict-/set-like item list, e.g. `{1,2,3}`. Dict, /// Lambda parameter list, e.g. `lambda a, b`. LambdaParameters, /// Type parameter list, e.g. `def foo[T, U](): ...` TypeParameters, } /// Comma context - described a comma-delimited "situation". #[derive(Copy, Clone)] struct Context { ty: ContextType, num_commas: u32, } impl Context { const fn new(ty: ContextType) -> Self { Self { ty, num_commas: 0 } } fn inc(&mut self) { self.num_commas += 1; } } /// ## What it does /// Checks for the absence of trailing commas. /// /// ## Why is this bad? /// The presence of a trailing comma can reduce diff size when parameters or /// elements are added or removed from function calls, function definitions, /// literals, etc. /// /// ## Example /// ```python /// foo = { /// "bar": 1, /// "baz": 2 /// } /// ``` /// /// Use instead: /// ```python /// foo = { /// "bar": 1, /// "baz": 2, /// } /// ``` /// /// ## Formatter compatibility /// We recommend against using this rule alongside the [formatter]. The /// formatter enforces consistent use of trailing commas, making the rule redundant. /// /// [formatter]:https://docs.astral.sh/ruff/formatter/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.223")] pub(crate) struct MissingTrailingComma; impl AlwaysFixableViolation for MissingTrailingComma { #[derive_message_formats] fn message(&self) -> String { "Trailing comma missing".to_string() } fn fix_title(&self) -> String { "Add trailing comma".to_string() } } /// ## What it does /// Checks for the presence of trailing commas on bare (i.e., unparenthesized) /// tuples. /// /// ## Why is this bad? /// The presence of a misplaced comma will cause Python to interpret the value /// as a tuple, which can lead to unexpected behaviour. /// /// ## Example /// ```python /// import json /// /// /// foo = json.dumps({"bar": 1}), /// ``` /// /// Use instead: /// ```python /// import json /// /// /// foo = json.dumps({"bar": 1}) /// ``` /// /// In the event that a tuple is intended, then use instead: /// ```python /// import json /// /// /// foo = (json.dumps({"bar": 1}),) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.223")] pub(crate) struct TrailingCommaOnBareTuple; impl Violation for TrailingCommaOnBareTuple { #[derive_message_formats] fn message(&self) -> String { "Trailing comma on bare tuple prohibited".to_string() } } /// ## What it does /// Checks for the presence of prohibited trailing commas. /// /// ## Why is this bad? /// Trailing commas are not essential in some cases and can therefore be viewed /// as unnecessary. /// /// ## Example /// ```python /// foo = (1, 2, 3,) /// ``` /// /// Use instead: /// ```python /// foo = (1, 2, 3) /// ``` /// /// ## Formatter compatibility /// We recommend against using this rule alongside the [formatter]. The /// formatter enforces consistent use of trailing commas, making the rule redundant. /// /// [formatter]:https://docs.astral.sh/ruff/formatter/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.223")] pub(crate) struct ProhibitedTrailingComma; impl AlwaysFixableViolation for ProhibitedTrailingComma { #[derive_message_formats] fn message(&self) -> String { "Trailing comma prohibited".to_string() } fn fix_title(&self) -> String { "Remove trailing comma".to_string() } } /// COM812, COM818, COM819 pub(crate) fn trailing_commas( lint_context: &LintContext, tokens: &Tokens, locator: &Locator, indexer: &Indexer, ) { let mut interpolated_strings = 0u32; let simple_tokens = tokens.iter().filter_map(|token| { match token.kind() { // Completely ignore comments -- they just interfere with the logic. TokenKind::Comment => None, // F-strings and t-strings are handled as `String` token type with the complete range // of the outermost interpolated string. This means that the expression inside the // interpolated string is not checked for trailing commas. TokenKind::FStringStart | TokenKind::TStringStart => { interpolated_strings = interpolated_strings.saturating_add(1); None } TokenKind::FStringEnd | TokenKind::TStringEnd => { interpolated_strings = interpolated_strings.saturating_sub(1); if interpolated_strings == 0 { indexer .interpolated_string_ranges() .outermost(token.start()) .map(|range| SimpleToken::new(TokenType::String, range)) } else { None } } _ => { if interpolated_strings == 0 { Some(SimpleToken::from(token.as_tuple())) } else { None } } } }); let mut prev = SimpleToken::irrelevant(); let mut prev_prev = SimpleToken::irrelevant(); let mut stack = vec![Context::new(ContextType::No)]; for token in simple_tokens { if prev.ty == TokenType::NonLogicalNewline && token.ty == TokenType::NonLogicalNewline { // Collapse consecutive newlines to the first one -- trailing commas are // added before the first newline. continue; } // Update the comma context stack. let context = update_context(token, prev, prev_prev, &mut stack); check_token(token, prev, prev_prev, context, locator, lint_context); // Pop the current context if the current token ended it. // The top context is never popped (if unbalanced closing brackets). let pop_context = match context.ty { // Lambda terminated by `:`. ContextType::LambdaParameters => token.ty == TokenType::Colon, // All others terminated by a closing bracket. // flake8-commas doesn't verify that it matches the opening... _ => token.ty == TokenType::ClosingBracket, }; if pop_context && stack.len() > 1 { stack.pop(); } prev_prev = prev; prev = token; } } fn check_token( token: SimpleToken, prev: SimpleToken, prev_prev: SimpleToken, context: Context, locator: &Locator, lint_context: &LintContext, ) { // Is it allowed to have a trailing comma before this token? let comma_allowed = token.ty == TokenType::ClosingBracket && match context.ty { ContextType::No => false, ContextType::FunctionParameters => true, ContextType::CallArguments => true, ContextType::TypeParameters => true, // `(1)` is not equivalent to `(1,)`. ContextType::Tuple => context.num_commas != 0, // `x[1]` is not equivalent to `x[1,]`. ContextType::Subscript => context.num_commas != 0, ContextType::List => true, ContextType::Dict => true, // Lambdas are required to be a single line, trailing comma never makes sense. ContextType::LambdaParameters => false, }; // Is prev a prohibited trailing comma? let comma_prohibited = prev.ty == TokenType::Comma && { // Is `(1,)` or `x[1,]`? let is_singleton_tuplish = matches!(context.ty, ContextType::Subscript | ContextType::Tuple) && context.num_commas <= 1; // There was no non-logical newline, so prohibit (except in `(1,)` or `x[1,]`). if comma_allowed && !is_singleton_tuplish { true // Lambdas not handled by comma_allowed so handle it specially. } else { context.ty == ContextType::LambdaParameters && token.ty == TokenType::Colon } }; if comma_prohibited { if let Some(mut diagnostic) = lint_context.report_diagnostic_if_enabled(ProhibitedTrailingComma, prev.range()) { diagnostic.set_fix(Fix::safe_edit(Edit::range_deletion(prev.range))); return; } } // Is prev a prohibited trailing comma on a bare tuple? // Approximation: any comma followed by a statement-ending newline. let bare_comma_prohibited = prev.ty == TokenType::Comma && token.ty == TokenType::Newline; if bare_comma_prohibited { lint_context.report_diagnostic_if_enabled(TrailingCommaOnBareTuple, prev.range()); return; } if !comma_allowed { return; } // Comma is required if: // - It is allowed, // - Followed by a newline, // - Not already present, // - Not on an empty (), {}, []. let comma_required = prev.ty == TokenType::NonLogicalNewline && !matches!( prev_prev.ty, TokenType::Comma | TokenType::OpeningBracket | TokenType::OpeningSquareBracket | TokenType::OpeningCurlyBracket ); if comma_required { if let Some(mut diagnostic) = lint_context .report_diagnostic_if_enabled(MissingTrailingComma, TextRange::empty(prev_prev.end())) { // Create a replacement that includes the final bracket (or other token), // rather than just inserting a comma at the end. This prevents the UP034 fix // removing any brackets in the same linter pass - doing both at the same time could // lead to a syntax error. let contents = locator.slice(prev_prev.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( format!("{contents},"), prev_prev.range(), ))); } } } fn update_context( token: SimpleToken, prev: SimpleToken, prev_prev: SimpleToken, stack: &mut Vec<Context>, ) -> Context { let new_context = match token.ty { TokenType::OpeningBracket => match (prev.ty, prev_prev.ty) { (TokenType::Named, TokenType::Def) => Context::new(ContextType::FunctionParameters), (TokenType::Named | TokenType::ClosingBracket, _) => { Context::new(ContextType::CallArguments) } _ => Context::new(ContextType::Tuple), }, TokenType::OpeningSquareBracket => match (prev.ty, prev_prev.ty) { (TokenType::Named, TokenType::Def | TokenType::Class | TokenType::Type) => { Context::new(ContextType::TypeParameters) } (TokenType::ClosingBracket | TokenType::Named | TokenType::String, _) => { Context::new(ContextType::Subscript) } _ => Context::new(ContextType::List), }, TokenType::OpeningCurlyBracket => Context::new(ContextType::Dict), TokenType::Lambda => Context::new(ContextType::LambdaParameters), TokenType::For => { let last = stack.last_mut().expect("Stack to never be empty"); *last = Context::new(ContextType::No); return *last; } TokenType::Comma => { let last = stack.last_mut().expect("Stack to never be empty"); last.inc(); return *last; } _ => return stack.last().copied().expect("Stack to never be empty"), }; stack.push(new_context); new_context }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false