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/flake8_bandit/rules/ssl_insecure_version.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_insecure_version.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprCall}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for function calls with parameters that indicate the use of insecure /// SSL and TLS protocol versions. /// /// ## Why is this bad? /// Several highly publicized exploitable flaws have been discovered in all /// versions of SSL and early versions of TLS. The following versions are /// considered insecure, and should be avoided: /// - SSL v2 /// - SSL v3 /// - TLS v1 /// - TLS v1.1 /// /// This method supports detection on the Python's built-in `ssl` module and /// the `pyOpenSSL` module. /// /// ## Example /// ```python /// import ssl /// /// ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) /// ``` /// /// Use instead: /// ```python /// import ssl /// /// ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct SslInsecureVersion { protocol: String, } impl Violation for SslInsecureVersion { #[derive_message_formats] fn message(&self) -> String { let SslInsecureVersion { protocol } = self; format!("Call made with insecure SSL protocol: `{protocol}`") } } /// S502 pub(crate) fn ssl_insecure_version(checker: &Checker, call: &ExprCall) { let Some(keyword) = checker .semantic() .resolve_qualified_name(call.func.as_ref()) .and_then(|qualified_name| match qualified_name.segments() { ["ssl", "wrap_socket"] => Some("ssl_version"), ["OpenSSL", "SSL", "Context"] => Some("method"), _ => None, }) else { return; }; let Some(keyword) = call.arguments.find_keyword(keyword) else { return; }; match &keyword.value { Expr::Name(ast::ExprName { id, .. }) => { if is_insecure_protocol(id) { checker.report_diagnostic( SslInsecureVersion { protocol: id.to_string(), }, keyword.range(), ); } } Expr::Attribute(ast::ExprAttribute { attr, .. }) => { if is_insecure_protocol(attr) { checker.report_diagnostic( SslInsecureVersion { protocol: attr.to_string(), }, keyword.range(), ); } } _ => {} } } /// Returns `true` if the given protocol name is insecure. fn is_insecure_protocol(name: &str) -> bool { matches!( name, "PROTOCOL_SSLv2" | "PROTOCOL_SSLv3" | "PROTOCOL_TLSv1" | "PROTOCOL_TLSv1_1" | "SSLv2_METHOD" | "SSLv23_METHOD" | "SSLv3_METHOD" | "TLSv1_METHOD" | "TLSv1_1_METHOD" ) }
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_bandit/rules/weak_cryptographic_key.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/weak_cryptographic_key.rs
use std::fmt::{Display, Formatter}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprAttribute, ExprCall}; use ruff_text_size::{Ranged, TextRange}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of cryptographic keys with vulnerable key sizes. /// /// ## Why is this bad? /// Small keys are easily breakable. For DSA and RSA, keys should be at least /// 2048 bits long. For EC, keys should be at least 224 bits long. /// /// ## Example /// ```python /// from cryptography.hazmat.primitives.asymmetric import dsa, ec /// /// dsa.generate_private_key(key_size=512) /// ec.generate_private_key(curve=ec.SECT163K1()) /// ``` /// /// Use instead: /// ```python /// from cryptography.hazmat.primitives.asymmetric import dsa, ec /// /// dsa.generate_private_key(key_size=4096) /// ec.generate_private_key(curve=ec.SECP384R1()) /// ``` /// /// ## References /// - [CSRC: Transitioning the Use of Cryptographic Algorithms and Key Lengths](https://csrc.nist.gov/pubs/sp/800/131/a/r2/final) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct WeakCryptographicKey { cryptographic_key: CryptographicKey, } impl Violation for WeakCryptographicKey { #[derive_message_formats] fn message(&self) -> String { let WeakCryptographicKey { cryptographic_key } = self; let minimum_key_size = cryptographic_key.minimum_key_size(); format!( "{cryptographic_key} key sizes below {minimum_key_size} bits are considered breakable" ) } } /// S505 pub(crate) fn weak_cryptographic_key(checker: &Checker, call: &ExprCall) { let Some((cryptographic_key, range)) = extract_cryptographic_key(checker, call) else { return; }; if cryptographic_key.is_vulnerable() { checker.report_diagnostic(WeakCryptographicKey { cryptographic_key }, range); } } #[derive(Debug, PartialEq, Eq)] enum CryptographicKey { Dsa { key_size: u16 }, Ec { algorithm: String }, Rsa { key_size: u16 }, } impl CryptographicKey { const fn minimum_key_size(&self) -> u16 { match self { Self::Dsa { .. } | Self::Rsa { .. } => 2048, Self::Ec { .. } => 224, } } fn is_vulnerable(&self) -> bool { match self { Self::Dsa { key_size } | Self::Rsa { key_size } => key_size < &self.minimum_key_size(), Self::Ec { algorithm } => { matches!(algorithm.as_str(), "SECP192R1" | "SECT163K1" | "SECT163R2") } } } } impl Display for CryptographicKey { fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result { match self { CryptographicKey::Dsa { .. } => fmt.write_str("DSA"), CryptographicKey::Ec { .. } => fmt.write_str("EC"), CryptographicKey::Rsa { .. } => fmt.write_str("RSA"), } } } fn extract_cryptographic_key( checker: &Checker, call: &ExprCall, ) -> Option<(CryptographicKey, TextRange)> { let qualified_name = checker.semantic().resolve_qualified_name(&call.func)?; match qualified_name.segments() { [ "cryptography", "hazmat", "primitives", "asymmetric", function, "generate_private_key", ] => match *function { "dsa" => { let (key_size, range) = extract_int_argument(call, "key_size", 0)?; Some((CryptographicKey::Dsa { key_size }, range)) } "rsa" => { let (key_size, range) = extract_int_argument(call, "key_size", 1)?; Some((CryptographicKey::Rsa { key_size }, range)) } "ec" => { let argument = call.arguments.find_argument_value("curve", 0)?; let ExprAttribute { attr, value, .. } = argument.as_attribute_expr()?; let qualified_name = checker.semantic().resolve_qualified_name(value)?; if matches!( qualified_name.segments(), ["cryptography", "hazmat", "primitives", "asymmetric", "ec"] ) { Some(( CryptographicKey::Ec { algorithm: attr.to_string(), }, argument.range(), )) } else { None } } _ => None, }, ["Crypto" | "Cryptodome", "PublicKey", function, "generate"] => match *function { "DSA" => { let (key_size, range) = extract_int_argument(call, "bits", 0)?; Some((CryptographicKey::Dsa { key_size }, range)) } "RSA" => { let (key_size, range) = extract_int_argument(call, "bits", 0)?; Some((CryptographicKey::Dsa { key_size }, range)) } _ => None, }, _ => None, } } fn extract_int_argument(call: &ExprCall, name: &str, position: usize) -> Option<(u16, TextRange)> { let argument = call.arguments.find_argument_value(name, position)?; let Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(i), .. }) = argument else { return None; }; Some((i.as_u16()?, argument.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/flake8_bandit/rules/unsafe_markup_use.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_markup_use.rs
use ruff_python_ast::{Expr, ExprCall}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_semantic::{Modules, SemanticModel}; use ruff_text_size::Ranged; use crate::Violation; use crate::{checkers::ast::Checker, settings::LinterSettings}; /// ## What it does /// Checks for non-literal strings being passed to [`markupsafe.Markup`][markupsafe-markup]. /// /// ## Why is this bad? /// [`markupsafe.Markup`][markupsafe-markup] does not perform any escaping, so passing dynamic /// content, like f-strings, variables or interpolated strings will potentially /// lead to XSS vulnerabilities. /// /// Instead you should interpolate the `Markup` object. /// /// Using [`lint.flake8-bandit.extend-markup-names`] additional objects can be /// treated like `Markup`. /// /// This rule was originally inspired by [flake8-markupsafe] but doesn't carve /// out any exceptions for i18n related calls by default. /// /// You can use [`lint.flake8-bandit.allowed-markup-calls`] to specify exceptions. /// /// ## Example /// Given: /// ```python /// from markupsafe import Markup /// /// content = "<script>alert('Hello, world!')</script>" /// html = Markup(f"<b>{content}</b>") # XSS /// ``` /// /// Use instead: /// ```python /// from markupsafe import Markup /// /// content = "<script>alert('Hello, world!')</script>" /// html = Markup("<b>{}</b>").format(content) # Safe /// ``` /// /// Given: /// ```python /// from markupsafe import Markup /// /// lines = [ /// Markup("<b>heading</b>"), /// "<script>alert('XSS attempt')</script>", /// ] /// html = Markup("<br>".join(lines)) # XSS /// ``` /// /// Use instead: /// ```python /// from markupsafe import Markup /// /// lines = [ /// Markup("<b>heading</b>"), /// "<script>alert('XSS attempt')</script>", /// ] /// html = Markup("<br>").join(lines) # Safe /// ``` /// ## Options /// - `lint.flake8-bandit.extend-markup-names` /// - `lint.flake8-bandit.allowed-markup-calls` /// /// ## References /// - [MarkupSafe on PyPI](https://pypi.org/project/MarkupSafe/) /// - [`markupsafe.Markup` API documentation](https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup) /// /// [markupsafe-markup]: https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup /// [flake8-markupsafe]: https://github.com/vmagamedov/flake8-markupsafe #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.10.0")] pub(crate) struct UnsafeMarkupUse { name: String, } impl Violation for UnsafeMarkupUse { #[derive_message_formats] fn message(&self) -> String { let UnsafeMarkupUse { name } = self; format!("Unsafe use of `{name}` detected") } } /// S704 pub(crate) fn unsafe_markup_call(checker: &Checker, call: &ExprCall) { if checker .settings() .flake8_bandit .extend_markup_names .is_empty() && !(checker.semantic().seen_module(Modules::MARKUPSAFE) || checker.semantic().seen_module(Modules::FLASK)) { return; } if !is_unsafe_call(call, checker.semantic(), checker.settings()) { return; } let Some(qualified_name) = checker.semantic().resolve_qualified_name(&call.func) else { return; }; if !is_markup_call(&qualified_name, checker.settings()) { return; } checker.report_diagnostic( UnsafeMarkupUse { name: qualified_name.to_string(), }, call.range(), ); } fn is_markup_call(qualified_name: &QualifiedName, settings: &LinterSettings) -> bool { matches!( qualified_name.segments(), ["markupsafe" | "flask", "Markup"] ) || settings .flake8_bandit .extend_markup_names .iter() .map(|target| QualifiedName::from_dotted_name(target)) .any(|target| *qualified_name == target) } fn is_unsafe_call(call: &ExprCall, semantic: &SemanticModel, settings: &LinterSettings) -> bool { // technically this could be circumvented by using a keyword argument // but without type-inference we can't really know which keyword argument // corresponds to the first positional argument and either way it is // unlikely that someone will actually use a keyword argument here // TODO: Eventually we may want to allow dynamic values, as long as they // have a __html__ attribute, since that is part of the API matches!(&*call.arguments.args, [first] if !first.is_string_literal_expr() && !first.is_bytes_literal_expr() && !is_whitelisted_call(first, semantic, settings)) } fn is_whitelisted_call(expr: &Expr, semantic: &SemanticModel, settings: &LinterSettings) -> bool { let Expr::Call(ExprCall { func, .. }) = expr else { return false; }; let Some(qualified_name) = semantic.resolve_qualified_name(func) else { return false; }; settings .flake8_bandit .allowed_markup_calls .iter() .map(|target| QualifiedName::from_dotted_name(target)) .any(|target| qualified_name == target) }
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_bandit/rules/hardcoded_password_func_arg.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs
use ruff_python_ast::Keyword; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bandit::helpers::{matches_password_name, string_literal}; /// ## What it does /// Checks for potential uses of hardcoded passwords in function calls. /// /// ## Why is this bad? /// Including a hardcoded password in source code is a security risk, as an /// attacker could discover the password and use it to gain unauthorized /// access. /// /// Instead, store passwords and other secrets in configuration files, /// environment variables, or other sources that are excluded from version /// control. /// /// ## Example /// ```python /// connect_to_server(password="hunter2") /// ``` /// /// Use instead: /// ```python /// import os /// /// connect_to_server(password=os.environ["PASSWORD"]) /// ``` /// /// ## References /// - [Common Weakness Enumeration: CWE-259](https://cwe.mitre.org/data/definitions/259.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct HardcodedPasswordFuncArg { name: String, } impl Violation for HardcodedPasswordFuncArg { #[derive_message_formats] fn message(&self) -> String { let HardcodedPasswordFuncArg { name } = self; format!( "Possible hardcoded password assigned to argument: \"{}\"", name.escape_debug() ) } } /// S106 pub(crate) fn hardcoded_password_func_arg(checker: &Checker, keywords: &[Keyword]) { for keyword in keywords { if string_literal(&keyword.value).is_none_or(str::is_empty) { continue; } let Some(arg) = &keyword.arg else { continue; }; if !matches_password_name(arg) { continue; } checker.report_diagnostic( HardcodedPasswordFuncArg { name: arg.to_string(), }, 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/flake8_bandit/rules/assert_used.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/assert_used.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; use ruff_text_size::{TextLen, TextRange}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of the `assert` keyword. /// /// ## Why is this bad? /// Assertions are removed when Python is run with optimization requested /// (i.e., when the `-O` flag is present), which is a common practice in /// production environments. As such, assertions should not be used for runtime /// validation of user input or to enforce interface constraints. /// /// Consider raising a meaningful error instead of using `assert`. /// /// ## Example /// ```python /// assert x > 0, "Expected positive value." /// ``` /// /// Use instead: /// ```python /// if not x > 0: /// raise ValueError("Expected positive value.") /// /// # or even better: /// if x <= 0: /// raise ValueError("Expected positive value.") /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct Assert; impl Violation for Assert { #[derive_message_formats] fn message(&self) -> String { "Use of `assert` detected".to_string() } } /// S101 pub(crate) fn assert_used(checker: &Checker, stmt: &Stmt) { checker.report_diagnostic(Assert, TextRange::at(stmt.start(), "assert".text_len())); }
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_bandit/rules/django_raw_sql.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/django_raw_sql.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; 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 Django's `RawSQL` function. /// /// ## Why is this bad? /// Django's `RawSQL` function can be used to execute arbitrary SQL queries, /// which can in turn lead to SQL injection vulnerabilities. /// /// ## Example /// ```python /// from django.db.models.expressions import RawSQL /// from django.contrib.auth.models import User /// /// User.objects.annotate(val=RawSQL("%s" % input_param, [])) /// ``` /// /// ## References /// - [Django documentation: SQL injection protection](https://docs.djangoproject.com/en/dev/topics/security/#sql-injection-protection) /// - [Common Weakness Enumeration: CWE-89](https://cwe.mitre.org/data/definitions/89.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct DjangoRawSql; impl Violation for DjangoRawSql { #[derive_message_formats] fn message(&self) -> String { "Use of `RawSQL` can lead to SQL injection vulnerabilities".to_string() } } /// S611 pub(crate) fn django_raw_sql(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::DJANGO) { return; } if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["django", "db", "models", "expressions", "RawSQL"] ) }) { if !call .arguments .find_argument_value("sql", 0) .is_some_and(Expr::is_string_literal_expr) { checker.report_diagnostic(DjangoRawSql, 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/flake8_bandit/rules/logging_config_insecure_listen.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/logging_config_insecure_listen.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 insecure `logging.config.listen` calls. /// /// ## Why is this bad? /// `logging.config.listen` starts a server that listens for logging /// configuration requests. This is insecure, as parts of the configuration are /// passed to the built-in `eval` function, which can be used to execute /// arbitrary code. /// /// ## Example /// ```python /// import logging /// /// logging.config.listen(9999) /// ``` /// /// ## References /// - [Python documentation: `logging.config.listen()`](https://docs.python.org/3/library/logging.config.html#logging.config.listen) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.231")] pub(crate) struct LoggingConfigInsecureListen; impl Violation for LoggingConfigInsecureListen { #[derive_message_formats] fn message(&self) -> String { "Use of insecure `logging.config.listen` detected".to_string() } } /// S612 pub(crate) fn logging_config_insecure_listen(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::LOGGING) { return; } if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["logging", "config", "listen"]) }) { if call.arguments.find_keyword("verify").is_some() { return; } checker.report_diagnostic(LoggingConfigInsecureListen, 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/flake8_bandit/rules/request_with_no_cert_validation.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::helpers::is_const_false; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for HTTPS requests that disable SSL certificate checks. /// /// ## Why is this bad? /// If SSL certificates are not verified, an attacker could perform a "man in /// the middle" attack by intercepting and modifying traffic between the client /// and server. /// /// ## Example /// ```python /// import requests /// /// requests.get("https://www.example.com", verify=False) /// ``` /// /// Use instead: /// ```python /// import requests /// /// requests.get("https://www.example.com") # By default, `verify=True`. /// ``` /// /// ## References /// - [Common Weakness Enumeration: CWE-295](https://cwe.mitre.org/data/definitions/295.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.213")] pub(crate) struct RequestWithNoCertValidation { string: String, } impl Violation for RequestWithNoCertValidation { #[derive_message_formats] fn message(&self) -> String { let RequestWithNoCertValidation { string } = self; format!( "Probable use of `{string}` call with `verify=False` disabling SSL certificate checks" ) } } /// S501 pub(crate) fn request_with_no_cert_validation(checker: &Checker, call: &ast::ExprCall) { if let Some(target) = checker .semantic() .resolve_qualified_name(&call.func) .and_then(|qualified_name| match qualified_name.segments() { [ "requests", "get" | "options" | "head" | "post" | "put" | "patch" | "delete", ] => Some("requests"), [ "httpx", "get" | "options" | "head" | "post" | "put" | "patch" | "delete" | "request" | "stream" | "Client" | "AsyncClient", ] => Some("httpx"), _ => None, }) { if let Some(keyword) = call.arguments.find_keyword("verify") { if is_const_false(&keyword.value) { checker.report_diagnostic( RequestWithNoCertValidation { string: target.to_string(), }, 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/flake8_bandit/rules/suspicious_imports.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_imports.rs
//! Check for imports of or from suspicious modules. //! //! See: <https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html> 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 imports of the `telnetlib` module. /// /// ## Why is this bad? /// Telnet is considered insecure. It is deprecated since version 3.11, and /// was removed in version 3.13. Instead, use SSH or another encrypted /// protocol. /// /// ## Example /// ```python /// import telnetlib /// ``` /// /// ## References /// - [Python documentation: `telnetlib` - Telnet client](https://docs.python.org/3.12/library/telnetlib.html#module-telnetlib) /// - [PEP 594: `telnetlib`](https://peps.python.org/pep-0594/#telnetlib) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousTelnetlibImport; impl Violation for SuspiciousTelnetlibImport { #[derive_message_formats] fn message(&self) -> String { "`telnetlib` and related modules are considered insecure. Use SSH or another encrypted protocol.".to_string() } } /// ## What it does /// Checks for imports of the `ftplib` module. /// /// ## Why is this bad? /// FTP is considered insecure. Instead, use SSH, SFTP, SCP, or another /// encrypted protocol. /// /// ## Example /// ```python /// import ftplib /// ``` /// /// ## References /// - [Python documentation: `ftplib` - FTP protocol client](https://docs.python.org/3/library/ftplib.html) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousFtplibImport; impl Violation for SuspiciousFtplibImport { #[derive_message_formats] fn message(&self) -> String { "`ftplib` and related modules are considered insecure. Use SSH, SFTP, SCP, or another encrypted protocol.".to_string() } } /// ## What it does /// Checks for imports of the `pickle`, `cPickle`, `dill`, and `shelve` modules. /// /// ## Why is this bad? /// It is possible to construct malicious pickle data which will execute /// arbitrary code during unpickling. Consider possible security implications /// associated with these modules. /// /// ## Example /// ```python /// import pickle /// ``` /// /// ## References /// - [Python documentation: `pickle` — Python object serialization](https://docs.python.org/3/library/pickle.html) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousPickleImport; impl Violation for SuspiciousPickleImport { #[derive_message_formats] fn message(&self) -> String { "`pickle`, `cPickle`, `dill`, and `shelve` modules are possibly insecure".to_string() } } /// ## What it does /// Checks for imports of the `subprocess` module. /// /// ## Why is this bad? /// It is possible to inject malicious commands into subprocess calls. Consider /// possible security implications associated with this module. /// /// ## Example /// ```python /// import subprocess /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousSubprocessImport; impl Violation for SuspiciousSubprocessImport { #[derive_message_formats] fn message(&self) -> String { "`subprocess` module is possibly insecure".to_string() } } /// ## What it does /// Checks for imports of the `xml.etree.cElementTree` and `xml.etree.ElementTree` modules /// /// ## Why is this bad? /// Using various methods from these modules to parse untrusted XML data is /// known to be vulnerable to XML attacks. Replace vulnerable imports with the /// equivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is /// called before parsing XML data. /// /// ## Example /// ```python /// import xml.etree.cElementTree /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousXmlEtreeImport; impl Violation for SuspiciousXmlEtreeImport { #[derive_message_formats] fn message(&self) -> String { "`xml.etree` methods are vulnerable to XML attacks".to_string() } } /// ## What it does /// Checks for imports of the `xml.sax` module. /// /// ## Why is this bad? /// Using various methods from these modules to parse untrusted XML data is /// known to be vulnerable to XML attacks. Replace vulnerable imports with the /// equivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is /// called before parsing XML data. /// /// ## Example /// ```python /// import xml.sax /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousXmlSaxImport; impl Violation for SuspiciousXmlSaxImport { #[derive_message_formats] fn message(&self) -> String { "`xml.sax` methods are vulnerable to XML attacks".to_string() } } /// ## What it does /// Checks for imports of the `xml.dom.expatbuilder` module. /// /// ## Why is this bad? /// Using various methods from these modules to parse untrusted XML data is /// known to be vulnerable to XML attacks. Replace vulnerable imports with the /// equivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is /// called before parsing XML data. /// /// ## Example /// ```python /// import xml.dom.expatbuilder /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousXmlExpatImport; impl Violation for SuspiciousXmlExpatImport { #[derive_message_formats] fn message(&self) -> String { "`xml.dom.expatbuilder` is vulnerable to XML attacks".to_string() } } /// ## What it does /// Checks for imports of the `xml.dom.minidom` module. /// /// ## Why is this bad? /// Using various methods from these modules to parse untrusted XML data is /// known to be vulnerable to XML attacks. Replace vulnerable imports with the /// equivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is /// called before parsing XML data. /// /// ## Example /// ```python /// import xml.dom.minidom /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousXmlMinidomImport; impl Violation for SuspiciousXmlMinidomImport { #[derive_message_formats] fn message(&self) -> String { "`xml.dom.minidom` is vulnerable to XML attacks".to_string() } } /// ## What it does /// Checks for imports of the `xml.dom.pulldom` module. /// /// ## Why is this bad? /// Using various methods from these modules to parse untrusted XML data is /// known to be vulnerable to XML attacks. Replace vulnerable imports with the /// equivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is /// called before parsing XML data. /// /// ## Example /// ```python /// import xml.dom.pulldom /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousXmlPulldomImport; impl Violation for SuspiciousXmlPulldomImport { #[derive_message_formats] fn message(&self) -> String { "`xml.dom.pulldom` is vulnerable to XML attacks".to_string() } } /// ## Removed /// This rule was removed as the `lxml` library has been modified to address /// known vulnerabilities and unsafe defaults. As such, the `defusedxml` /// library is no longer necessary, `defusedxml` has [deprecated] its `lxml` /// module. /// /// ## What it does /// Checks for imports of the `lxml` module. /// /// ## Why is this bad? /// Using various methods from the `lxml` module to parse untrusted XML data is /// known to be vulnerable to XML attacks. Replace vulnerable imports with the /// equivalent `defusedxml` package. /// /// ## Example /// ```python /// import lxml /// ``` /// /// [deprecated]: https://github.com/tiran/defusedxml/blob/c7445887f5e1bcea470a16f61369d29870cfcfe1/README.md#defusedxmllxml #[derive(ViolationMetadata)] #[violation_metadata(removed_since = "v0.3.0")] pub(crate) struct SuspiciousLxmlImport; impl Violation for SuspiciousLxmlImport { #[derive_message_formats] fn message(&self) -> String { "`lxml` is vulnerable to XML attacks".to_string() } } /// ## What it does /// Checks for imports of the `xmlrpc` module. /// /// ## Why is this bad? /// XMLRPC is a particularly dangerous XML module, as it is also concerned with /// communicating data over a network. Use the `defused.xmlrpc.monkey_patch()` /// function to monkey-patch the `xmlrpclib` module and mitigate remote XML /// attacks. /// /// ## Example /// ```python /// import xmlrpc /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousXmlrpcImport; impl Violation for SuspiciousXmlrpcImport { #[derive_message_formats] fn message(&self) -> String { "XMLRPC is vulnerable to remote XML attacks".to_string() } } /// ## What it does /// Checks for imports of `wsgiref.handlers.CGIHandler` and /// `twisted.web.twcgi.CGIScript`. /// /// ## Why is this bad? /// httpoxy is a set of vulnerabilities that affect application code running in /// CGI or CGI-like environments. The use of CGI for web applications should be /// avoided to prevent this class of attack. /// /// ## Example /// ```python /// from wsgiref.handlers import CGIHandler /// ``` /// /// ## References /// - [httpoxy website](https://httpoxy.org/) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousHttpoxyImport; impl Violation for SuspiciousHttpoxyImport { #[derive_message_formats] fn message(&self) -> String { "`httpoxy` is a set of vulnerabilities that affect application code running inCGI, or CGI-like environments. The use of CGI for web applications should be avoided".to_string() } } /// ## What it does /// Checks for imports of several unsafe cryptography modules. /// /// ## Why is this bad? /// The `pycrypto` library is known to have a publicly disclosed buffer /// overflow vulnerability. It is no longer actively maintained and has been /// deprecated in favor of the `pyca/cryptography` library. /// /// ## Example /// ```python /// import Crypto.Random /// ``` /// /// ## References /// - [Buffer Overflow Issue](https://github.com/pycrypto/pycrypto/issues/176) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousPycryptoImport; impl Violation for SuspiciousPycryptoImport { #[derive_message_formats] fn message(&self) -> String { "`pycrypto` library is known to have publicly disclosed buffer overflow vulnerability" .to_string() } } /// ## What it does /// Checks for imports of the `pyghmi` module. /// /// ## Why is this bad? /// `pyghmi` is an IPMI-related module, but IPMI is considered insecure. /// Instead, use an encrypted protocol. /// /// ## Example /// ```python /// import pyghmi /// ``` /// /// ## References /// - [Buffer Overflow Issue](https://github.com/pycrypto/pycrypto/issues/176) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.1.12")] pub(crate) struct SuspiciousPyghmiImport; impl Violation for SuspiciousPyghmiImport { #[derive_message_formats] fn message(&self) -> String { "An IPMI-related module is being imported. Prefer an encrypted protocol over IPMI." .to_string() } } /// S401, S402, S403, S404, S405, S406, S407, S408, S409, S410, S411, S412, S413, S415 pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) { // Skip stub files. if checker.source_type.is_stub() { return; } match stmt { Stmt::Import(ast::StmtImport { names, .. }) => { for name in names { match name.name.as_str() { "telnetlib" => { checker.report_diagnostic_if_enabled(SuspiciousTelnetlibImport, name.range); } "ftplib" => { checker.report_diagnostic_if_enabled(SuspiciousFtplibImport, name.range); } "pickle" | "cPickle" | "dill" | "shelve" => { checker.report_diagnostic_if_enabled(SuspiciousPickleImport, name.range); } "subprocess" => { checker .report_diagnostic_if_enabled(SuspiciousSubprocessImport, name.range); } "xml.etree.cElementTree" | "xml.etree.ElementTree" => { checker.report_diagnostic_if_enabled(SuspiciousXmlEtreeImport, name.range); } "xml.sax" => { checker.report_diagnostic_if_enabled(SuspiciousXmlSaxImport, name.range); } "xml.dom.expatbuilder" => { checker.report_diagnostic_if_enabled(SuspiciousXmlExpatImport, name.range); } "xml.dom.minidom" => { checker .report_diagnostic_if_enabled(SuspiciousXmlMinidomImport, name.range); } "xml.dom.pulldom" => { checker .report_diagnostic_if_enabled(SuspiciousXmlPulldomImport, name.range); } "lxml" => { checker.report_diagnostic_if_enabled(SuspiciousLxmlImport, name.range); } "xmlrpc" => { checker.report_diagnostic_if_enabled(SuspiciousXmlrpcImport, name.range); } "Crypto.Cipher" | "Crypto.Hash" | "Crypto.IO" | "Crypto.Protocol" | "Crypto.PublicKey" | "Crypto.Random" | "Crypto.Signature" | "Crypto.Util" => { checker.report_diagnostic_if_enabled(SuspiciousPycryptoImport, name.range); } "pyghmi" => { checker.report_diagnostic_if_enabled(SuspiciousPyghmiImport, name.range); } _ => {} } } } Stmt::ImportFrom(ast::StmtImportFrom { module, names, .. }) => { let Some(identifier) = module else { return }; match identifier.as_str() { "telnetlib" => { checker.report_diagnostic_if_enabled( SuspiciousTelnetlibImport, identifier.range(), ); } "ftplib" => { checker .report_diagnostic_if_enabled(SuspiciousFtplibImport, identifier.range()); } "pickle" | "cPickle" | "dill" | "shelve" => { checker .report_diagnostic_if_enabled(SuspiciousPickleImport, identifier.range()); } "subprocess" => { checker.report_diagnostic_if_enabled( SuspiciousSubprocessImport, identifier.range(), ); } "xml.etree" => { for name in names { if matches!(name.name.as_str(), "cElementTree" | "ElementTree") { checker.report_diagnostic_if_enabled( SuspiciousXmlEtreeImport, identifier.range(), ); } } } "xml.etree.cElementTree" | "xml.etree.ElementTree" => { checker .report_diagnostic_if_enabled(SuspiciousXmlEtreeImport, identifier.range()); } "xml" => { for name in names { if name.name.as_str() == "sax" { checker.report_diagnostic_if_enabled( SuspiciousXmlSaxImport, identifier.range(), ); } } } "xml.sax" => { checker .report_diagnostic_if_enabled(SuspiciousXmlSaxImport, identifier.range()); } "xml.dom" => { for name in names { match name.name.as_str() { "expatbuilder" => { checker.report_diagnostic_if_enabled( SuspiciousXmlExpatImport, identifier.range(), ); } "minidom" => { checker.report_diagnostic_if_enabled( SuspiciousXmlMinidomImport, identifier.range(), ); } "pulldom" => { checker.report_diagnostic_if_enabled( SuspiciousXmlPulldomImport, identifier.range(), ); } _ => {} } } } "xml.dom.expatbuilder" => { checker .report_diagnostic_if_enabled(SuspiciousXmlExpatImport, identifier.range()); } "xml.dom.minidom" => { checker.report_diagnostic_if_enabled( SuspiciousXmlMinidomImport, identifier.range(), ); } "xml.dom.pulldom" => { checker.report_diagnostic_if_enabled( SuspiciousXmlPulldomImport, identifier.range(), ); } "lxml" => { checker.report_diagnostic_if_enabled(SuspiciousLxmlImport, identifier.range()); } "xmlrpc" => { checker .report_diagnostic_if_enabled(SuspiciousXmlrpcImport, identifier.range()); } "wsgiref.handlers" => { for name in names { if name.name.as_str() == "CGIHandler" { checker.report_diagnostic_if_enabled( SuspiciousHttpoxyImport, identifier.range(), ); } } } "twisted.web.twcgi" => { for name in names { if name.name.as_str() == "CGIScript" { checker.report_diagnostic_if_enabled( SuspiciousHttpoxyImport, identifier.range(), ); } } } "Crypto" => { for name in names { if matches!( name.name.as_str(), "Cipher" | "Hash" | "IO" | "Protocol" | "PublicKey" | "Random" | "Signature" | "Util" ) { checker.report_diagnostic_if_enabled( SuspiciousPycryptoImport, identifier.range(), ); } } } "Crypto.Cipher" | "Crypto.Hash" | "Crypto.IO" | "Crypto.Protocol" | "Crypto.PublicKey" | "Crypto.Random" | "Crypto.Signature" | "Crypto.Util" => { checker .report_diagnostic_if_enabled(SuspiciousPycryptoImport, identifier.range()); } "pyghmi" => { checker .report_diagnostic_if_enabled(SuspiciousPyghmiImport, identifier.range()); } _ => {} } } _ => panic!("Expected Stmt::Import | Stmt::ImportFrom"), } }
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_bandit/rules/ssh_no_host_key_verification.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/ssh_no_host_key_verification.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; use ruff_python_semantic::analyze::typing; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of policies disabling SSH verification in Paramiko. /// /// ## Why is this bad? /// By default, Paramiko checks the identity of the remote host when establishing /// an SSH connection. Disabling the verification might lead to the client /// connecting to a malicious host, without the client knowing. /// /// ## Example /// ```python /// from paramiko import client /// /// ssh_client = client.SSHClient() /// ssh_client.set_missing_host_key_policy(client.AutoAddPolicy) /// ``` /// /// Use instead: /// ```python /// from paramiko import client /// /// ssh_client = client.SSHClient() /// ssh_client.set_missing_host_key_policy(client.RejectPolicy) /// ``` /// /// ## References /// - [Paramiko documentation: set_missing_host_key_policy](https://docs.paramiko.org/en/latest/api/client.html#paramiko.client.SSHClient.set_missing_host_key_policy) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct SSHNoHostKeyVerification; impl Violation for SSHNoHostKeyVerification { #[derive_message_formats] fn message(&self) -> String { "Paramiko call with policy set to automatically trust the unknown host key".to_string() } } /// S507 pub(crate) fn ssh_no_host_key_verification(checker: &Checker, call: &ExprCall) { let Expr::Attribute(ExprAttribute { attr, value, .. }) = call.func.as_ref() else { return; }; if attr.as_str() != "set_missing_host_key_policy" { return; } let Some(policy_argument) = call.arguments.find_argument_value("policy", 0) else { return; }; // Detect either, e.g., `paramiko.client.AutoAddPolicy` or `paramiko.client.AutoAddPolicy()`. if !checker .semantic() .resolve_qualified_name(map_callable(policy_argument)) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["paramiko", "client", "AutoAddPolicy" | "WarningPolicy"] | ["paramiko", "AutoAddPolicy" | "WarningPolicy"] ) }) { return; } if typing::resolve_assignment(value, checker.semantic()).is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["paramiko", "client", "SSHClient"] | ["paramiko", "SSHClient"] ) }) { checker.report_diagnostic(SSHNoHostKeyVerification, policy_argument.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/flake8_bandit/rules/exec_used.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/exec_used.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 uses of the builtin `exec` function. /// /// ## Why is this bad? /// The `exec()` function is insecure as it allows for arbitrary code /// execution. /// /// ## Example /// ```python /// exec("print('Hello World')") /// ``` /// /// ## References /// - [Python documentation: `exec`](https://docs.python.org/3/library/functions.html#exec) /// - [Common Weakness Enumeration: CWE-78](https://cwe.mitre.org/data/definitions/78.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct ExecBuiltin; impl Violation for ExecBuiltin { #[derive_message_formats] fn message(&self) -> String { "Use of `exec` detected".to_string() } } /// S102 pub(crate) fn exec_used(checker: &Checker, func: &Expr) { if checker.semantic().match_builtin_expr(func, "exec") { checker.report_diagnostic(ExecBuiltin, 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/flake8_bandit/rules/mod.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/mod.rs
pub(crate) use assert_used::*; pub(crate) use bad_file_permissions::*; pub(crate) use django_extra::*; pub(crate) use django_raw_sql::*; pub(crate) use exec_used::*; pub(crate) use flask_debug_true::*; pub(crate) use hardcoded_bind_all_interfaces::*; pub(crate) use hardcoded_password_default::*; pub(crate) use hardcoded_password_func_arg::*; pub(crate) use hardcoded_password_string::*; pub(crate) use hardcoded_sql_expression::*; pub(crate) use hardcoded_tmp_directory::*; pub(crate) use hashlib_insecure_hash_functions::*; pub(crate) use jinja2_autoescape_false::*; pub(crate) use logging_config_insecure_listen::*; pub(crate) use mako_templates::*; pub(crate) use paramiko_calls::*; pub(crate) use request_with_no_cert_validation::*; pub(crate) use request_without_timeout::*; pub(crate) use shell_injection::*; pub(crate) use snmp_insecure_version::*; pub(crate) use snmp_weak_cryptography::*; pub(crate) use ssh_no_host_key_verification::*; pub(crate) use ssl_insecure_version::*; pub(crate) use ssl_with_bad_defaults::*; pub(crate) use ssl_with_no_version::*; pub(crate) use suspicious_function_call::*; pub(crate) use suspicious_imports::*; pub(crate) use tarfile_unsafe_members::*; pub(crate) use try_except_continue::*; pub(crate) use try_except_pass::*; pub(crate) use unsafe_markup_use::*; pub(crate) use unsafe_yaml_load::*; pub(crate) use weak_cryptographic_key::*; mod assert_used; mod bad_file_permissions; mod django_extra; mod django_raw_sql; mod exec_used; mod flask_debug_true; mod hardcoded_bind_all_interfaces; mod hardcoded_password_default; mod hardcoded_password_func_arg; mod hardcoded_password_string; mod hardcoded_sql_expression; mod hardcoded_tmp_directory; mod hashlib_insecure_hash_functions; mod jinja2_autoescape_false; mod logging_config_insecure_listen; mod mako_templates; mod paramiko_calls; mod request_with_no_cert_validation; mod request_without_timeout; mod shell_injection; mod snmp_insecure_version; mod snmp_weak_cryptography; mod ssh_no_host_key_verification; mod ssl_insecure_version; mod ssl_with_bad_defaults; mod ssl_with_no_version; mod suspicious_function_call; mod suspicious_imports; mod tarfile_unsafe_members; mod try_except_continue; mod try_except_pass; mod unsafe_markup_use; mod unsafe_yaml_load; mod weak_cryptographic_key;
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_bandit/rules/mako_templates.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/mako_templates.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 uses of the `mako` templates. /// /// ## Why is this bad? /// Mako templates allow HTML and JavaScript rendering by default, and are /// inherently open to XSS attacks. Ensure variables in all templates are /// properly sanitized via the `n`, `h` or `x` flags (depending on context). /// For example, to HTML escape the variable `data`, use `${ data |h }`. /// /// ## Example /// ```python /// from mako.template import Template /// /// Template("hello") /// ``` /// /// Use instead: /// ```python /// from mako.template import Template /// /// Template("hello |h") /// ``` /// /// ## References /// - [Mako documentation](https://www.makotemplates.org/) /// - [OpenStack security: Cross site scripting XSS](https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html) /// - [Common Weakness Enumeration: CWE-80](https://cwe.mitre.org/data/definitions/80.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct MakoTemplates; impl Violation for MakoTemplates { #[derive_message_formats] fn message(&self) -> String { "Mako templates allow HTML and JavaScript rendering by default and are inherently open to XSS attacks".to_string() } } /// S702 pub(crate) fn mako_templates(checker: &Checker, call: &ast::ExprCall) { if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["mako", "template", "Template"]) }) { checker.report_diagnostic(MakoTemplates, 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/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, StringLike}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for hardcoded bindings to all network interfaces (`0.0.0.0`). /// /// ## Why is this bad? /// Binding to all network interfaces is insecure as it allows access from /// unintended interfaces, which may be poorly secured or unauthorized. /// /// Instead, bind to specific interfaces. /// /// ## Example /// ```python /// ALLOWED_HOSTS = ["0.0.0.0"] /// ``` /// /// Use instead: /// ```python /// ALLOWED_HOSTS = ["127.0.0.1", "localhost"] /// ``` /// /// ## References /// - [Common Weakness Enumeration: CWE-200](https://cwe.mitre.org/data/definitions/200.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct HardcodedBindAllInterfaces; impl Violation for HardcodedBindAllInterfaces { #[derive_message_formats] fn message(&self) -> String { "Possible binding to all interfaces".to_string() } } /// S104 pub(crate) fn hardcoded_bind_all_interfaces(checker: &Checker, string: StringLike) { match string { StringLike::String(ast::ExprStringLiteral { value, .. }) => { if value == "0.0.0.0" { checker.report_diagnostic(HardcodedBindAllInterfaces, string.range()); } } StringLike::FString(ast::ExprFString { value, .. }) => { for part in value { match part { ast::FStringPart::Literal(literal) => { if &**literal == "0.0.0.0" { checker.report_diagnostic(HardcodedBindAllInterfaces, literal.range()); } } ast::FStringPart::FString(f_string) => { for literal in f_string.elements.literals() { if &**literal == "0.0.0.0" { checker .report_diagnostic(HardcodedBindAllInterfaces, literal.range()); } } } } } } StringLike::Bytes(_) => (), // TODO(dylan): decide whether to trigger here StringLike::TString(_) => (), } }
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_bandit/rules/unsafe_yaml_load.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.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 uses of the `yaml.load` function. /// /// ## Why is this bad? /// Running the `yaml.load` function over untrusted YAML files is insecure, as /// `yaml.load` allows for the creation of arbitrary Python objects, which can /// then be used to execute arbitrary code. /// /// Instead, consider using `yaml.safe_load`, which allows for the creation of /// simple Python objects like integers and lists, but prohibits the creation of /// more complex objects like functions and classes. /// /// ## Example /// ```python /// import yaml /// /// yaml.load(untrusted_yaml) /// ``` /// /// Use instead: /// ```python /// import yaml /// /// yaml.safe_load(untrusted_yaml) /// ``` /// /// ## References /// - [PyYAML documentation: Loading YAML](https://pyyaml.org/wiki/PyYAMLDocumentation) /// - [Common Weakness Enumeration: CWE-20](https://cwe.mitre.org/data/definitions/20.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.212")] pub(crate) struct UnsafeYAMLLoad { pub loader: Option<String>, } impl Violation for UnsafeYAMLLoad { #[derive_message_formats] fn message(&self) -> String { match &self.loader { Some(name) => { format!( "Probable use of unsafe loader `{name}` with `yaml.load`. Allows \ instantiation of arbitrary objects. Consider `yaml.safe_load`." ) } None => { "Probable use of unsafe `yaml.load`. Allows instantiation of arbitrary objects. \ Consider `yaml.safe_load`." .to_string() } } } } /// S506 pub(crate) fn unsafe_yaml_load(checker: &Checker, call: &ast::ExprCall) { if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["yaml", "load"])) { if let Some(loader_arg) = call.arguments.find_argument_value("Loader", 1) { if !checker .semantic() .resolve_qualified_name(loader_arg) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["yaml", "SafeLoader" | "CSafeLoader"] | ["yaml", "loader", "SafeLoader" | "CSafeLoader"] | ["yaml", "cyaml", "CSafeLoader"] ) }) { let loader = match loader_arg { Expr::Attribute(ast::ExprAttribute { attr, .. }) => Some(attr.to_string()), Expr::Name(ast::ExprName { id, .. }) => Some(id.to_string()), _ => None, }; checker.report_diagnostic(UnsafeYAMLLoad { loader }, loader_arg.range()); } } else { checker.report_diagnostic(UnsafeYAMLLoad { loader: None }, 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/flake8_bandit/rules/hardcoded_password_default.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_default.rs
use ruff_python_ast::{Expr, Parameter, Parameters}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bandit::helpers::{matches_password_name, string_literal}; /// ## What it does /// Checks for potential uses of hardcoded passwords in function argument /// defaults. /// /// ## Why is this bad? /// Including a hardcoded password in source code is a security risk, as an /// attacker could discover the password and use it to gain unauthorized /// access. /// /// Instead, store passwords and other secrets in configuration files, /// environment variables, or other sources that are excluded from version /// control. /// /// ## Example /// /// ```python /// def connect_to_server(password="hunter2"): ... /// ``` /// /// Use instead: /// /// ```python /// import os /// /// /// def connect_to_server(password=os.environ["PASSWORD"]): ... /// ``` /// /// ## References /// - [Common Weakness Enumeration: CWE-259](https://cwe.mitre.org/data/definitions/259.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct HardcodedPasswordDefault { name: String, } impl Violation for HardcodedPasswordDefault { #[derive_message_formats] fn message(&self) -> String { let HardcodedPasswordDefault { name } = self; format!( "Possible hardcoded password assigned to function default: \"{}\"", name.escape_debug() ) } } fn check_password_kwarg(checker: &Checker, parameter: &Parameter, default: &Expr) { if string_literal(default).is_none_or(str::is_empty) { return; } let kwarg_name = &parameter.name; if !matches_password_name(kwarg_name) { return; } checker.report_diagnostic( HardcodedPasswordDefault { name: kwarg_name.to_string(), }, default.range(), ); } /// S107 pub(crate) fn hardcoded_password_default(checker: &Checker, parameters: &Parameters) { for parameter in parameters.iter_non_variadic_params() { let Some(default) = parameter.default() else { continue; }; check_password_kwarg(checker, &parameter.parameter, default); } }
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_bandit/rules/request_without_timeout.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/request_without_timeout.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; /// ## What it does /// Checks for uses of the Python `requests` or `httpx` module that omit the /// `timeout` parameter. /// /// ## Why is this bad? /// The `timeout` parameter is used to set the maximum time to wait for a /// response from the server. By omitting the `timeout` parameter, the program /// may hang indefinitely while awaiting a response. /// /// ## Example /// ```python /// import requests /// /// requests.get("https://www.example.com/") /// ``` /// /// Use instead: /// ```python /// import requests /// /// requests.get("https://www.example.com/", timeout=10) /// ``` /// /// ## References /// - [Requests documentation: Timeouts](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts) /// - [httpx documentation: Timeouts](https://www.python-httpx.org/advanced/timeouts/) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.213")] pub(crate) struct RequestWithoutTimeout { implicit: bool, module: String, } impl Violation for RequestWithoutTimeout { #[derive_message_formats] fn message(&self) -> String { let RequestWithoutTimeout { implicit, module } = self; if *implicit { format!("Probable use of `{module}` call without timeout") } else { format!("Probable use of `{module}` call with timeout set to `None`") } } } /// S113 pub(crate) fn request_without_timeout(checker: &Checker, call: &ast::ExprCall) { if let Some(module) = checker .semantic() .resolve_qualified_name(&call.func) .and_then(|qualified_name| match qualified_name.segments() { [ "requests", "get" | "options" | "head" | "post" | "put" | "patch" | "delete" | "request", ] => Some("requests"), [ "httpx", "get" | "options" | "head" | "post" | "put" | "patch" | "delete" | "request" | "stream" | "Client" | "AsyncClient", ] => Some("httpx"), _ => None, }) { if let Some(keyword) = call.arguments.find_keyword("timeout") { if keyword.value.is_none_literal_expr() { checker.report_diagnostic( RequestWithoutTimeout { implicit: false, module: module.to_string(), }, keyword.range(), ); } } else if module == "requests" { checker.report_diagnostic( RequestWithoutTimeout { implicit: true, module: module.to_string(), }, 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/flake8_bandit/rules/try_except_continue.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_continue.rs
use ruff_python_ast::{ExceptHandler, Expr, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bandit::helpers::is_untyped_exception; /// ## What it does /// Checks for uses of the `try`-`except`-`continue` pattern. /// /// ## Why is this bad? /// The `try`-`except`-`continue` pattern suppresses all exceptions. /// Suppressing exceptions may hide errors that could otherwise reveal /// unexpected behavior, security vulnerabilities, or malicious activity. /// Instead, consider logging the exception. /// /// ## Example /// ```python /// import logging /// /// while predicate: /// try: /// ... /// except Exception: /// continue /// ``` /// /// Use instead: /// ```python /// import logging /// /// while predicate: /// try: /// ... /// except Exception as exc: /// logging.exception("Error occurred") /// ``` /// /// ## Options /// - `lint.flake8-bandit.check-typed-exception` /// /// ## References /// - [Common Weakness Enumeration: CWE-703](https://cwe.mitre.org/data/definitions/703.html) /// - [Python documentation: `logging`](https://docs.python.org/3/library/logging.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.245")] pub(crate) struct TryExceptContinue; impl Violation for TryExceptContinue { #[derive_message_formats] fn message(&self) -> String { "`try`-`except`-`continue` detected, consider logging the exception".to_string() } } /// S112 pub(crate) fn try_except_continue( checker: &Checker, except_handler: &ExceptHandler, type_: Option<&Expr>, body: &[Stmt], check_typed_exception: bool, ) { if matches!(body, [Stmt::Continue(_)]) { if check_typed_exception || is_untyped_exception(type_, checker.semantic()) { checker.report_diagnostic(TryExceptContinue, except_handler.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/flake8_bandit/rules/django_extra.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/django_extra.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, ExprAttribute}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of Django's `extra` function where one or more arguments /// passed are not literal expressions. /// /// ## Why is this bad? /// Django's `extra` function can be used to execute arbitrary SQL queries, /// which can in turn lead to SQL injection vulnerabilities. /// /// ## Example /// ```python /// from django.contrib.auth.models import User /// /// # String interpolation creates a security loophole that could be used /// # for SQL injection: /// User.objects.all().extra(select={"test": "%secure" % "nos"}) /// ``` /// /// Use instead: /// ```python /// from django.contrib.auth.models import User /// /// # SQL injection is impossible if all arguments are literal expressions: /// User.objects.all().extra(select={"test": "secure"}) /// ``` /// /// ## References /// - [Django documentation: SQL injection protection](https://docs.djangoproject.com/en/dev/topics/security/#sql-injection-protection) /// - [Common Weakness Enumeration: CWE-89](https://cwe.mitre.org/data/definitions/89.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.5.0")] pub(crate) struct DjangoExtra; impl Violation for DjangoExtra { #[derive_message_formats] fn message(&self) -> String { "Use of Django `extra` can lead to SQL injection vulnerabilities".to_string() } } /// S610 pub(crate) fn django_extra(checker: &Checker, call: &ast::ExprCall) { let Expr::Attribute(ExprAttribute { attr, .. }) = call.func.as_ref() else { return; }; if attr.as_str() != "extra" { return; } if is_call_insecure(call) { checker.report_diagnostic(DjangoExtra, call.arguments.range()); } } fn is_call_insecure(call: &ast::ExprCall) -> bool { for (argument_name, position) in [("select", 0), ("where", 1), ("tables", 3)] { if let Some(argument) = call.arguments.find_argument_value(argument_name, position) { match argument_name { "select" => match argument { Expr::Dict(dict) => { if dict.iter().any(|ast::DictItem { key, value }| { key.as_ref() .is_some_and(|key| !key.is_string_literal_expr()) || !value.is_string_literal_expr() }) { return true; } } _ => return true, }, "where" | "tables" => match argument { Expr::List(list) => { if !list.iter().all(Expr::is_string_literal_expr) { return true; } } _ => return true, }, _ => (), } } } 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/flake8_bandit/rules/jinja2_autoescape_false.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/jinja2_autoescape_false.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 `jinja2` templates that use `autoescape=False`. /// /// ## Why is this bad? /// `jinja2` templates that use `autoescape=False` are vulnerable to cross-site /// scripting (XSS) attacks that allow attackers to execute arbitrary /// JavaScript. /// /// By default, `jinja2` sets `autoescape` to `False`, so it is important to /// set `autoescape=True` or use the `select_autoescape` function to mitigate /// XSS vulnerabilities. /// /// ## Example /// ```python /// import jinja2 /// /// jinja2.Environment(loader=jinja2.FileSystemLoader(".")) /// ``` /// /// Use instead: /// ```python /// import jinja2 /// /// jinja2.Environment(loader=jinja2.FileSystemLoader("."), autoescape=True) /// ``` /// /// ## References /// - [Jinja documentation: API](https://jinja.palletsprojects.com/en/latest/api/#autoescaping) /// - [Common Weakness Enumeration: CWE-94](https://cwe.mitre.org/data/definitions/94.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.220")] pub(crate) struct Jinja2AutoescapeFalse { value: bool, } impl Violation for Jinja2AutoescapeFalse { #[derive_message_formats] fn message(&self) -> String { if self.value { "Using jinja2 templates with `autoescape=False` is dangerous and can lead to XSS. \ Ensure `autoescape=True` or use the `select_autoescape` function." .to_string() } else { "By default, jinja2 sets `autoescape` to `False`. Consider using \ `autoescape=True` or the `select_autoescape` function to mitigate XSS \ vulnerabilities." .to_string() } } } /// S701 pub(crate) fn jinja2_autoescape_false(checker: &Checker, call: &ast::ExprCall) { if checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["jinja2", "Environment"]) }) { if let Some(keyword) = call.arguments.find_keyword("autoescape") { match &keyword.value { Expr::BooleanLiteral(ast::ExprBooleanLiteral { value: true, .. }) => (), Expr::Call(ast::ExprCall { func, .. }) => { if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() { if id != "select_autoescape" { checker.report_diagnostic( Jinja2AutoescapeFalse { value: true }, keyword.range(), ); } } } _ => { checker .report_diagnostic(Jinja2AutoescapeFalse { value: true }, keyword.range()); } } } else { checker.report_diagnostic(Jinja2AutoescapeFalse { value: false }, 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/flake8_bandit/rules/bad_file_permissions.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/bad_file_permissions.rs
use anyhow::Result; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Expr, Operator}; use ruff_python_semantic::{Modules, SemanticModel}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for files with overly permissive permissions. /// /// ## Why is this bad? /// Overly permissive file permissions may allow unintended access and /// arbitrary code execution. /// /// ## Example /// ```python /// import os /// /// os.chmod("/etc/secrets.txt", 0o666) # rw-rw-rw- /// ``` /// /// Use instead: /// ```python /// import os /// /// os.chmod("/etc/secrets.txt", 0o600) # rw------- /// ``` /// /// ## References /// - [Python documentation: `os.chmod`](https://docs.python.org/3/library/os.html#os.chmod) /// - [Python documentation: `stat`](https://docs.python.org/3/library/stat.html) /// - [Common Weakness Enumeration: CWE-732](https://cwe.mitre.org/data/definitions/732.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.211")] pub(crate) struct BadFilePermissions { reason: Reason, } impl Violation for BadFilePermissions { #[derive_message_formats] fn message(&self) -> String { let BadFilePermissions { reason } = self; match reason { Reason::Permissive(mask) => { format!("`os.chmod` setting a permissive mask `{mask:#o}` on file or directory") } Reason::Invalid => { "`os.chmod` setting an invalid mask on file or directory".to_string() } } } } #[derive(Debug, PartialEq, Eq)] enum Reason { Permissive(u16), Invalid, } /// S103 pub(crate) fn bad_file_permissions(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", "chmod"])) { if let Some(mode_arg) = call.arguments.find_argument_value("mode", 1) { match parse_mask(mode_arg, checker.semantic()) { // The mask couldn't be determined (e.g., it's dynamic). Ok(None) => {} // The mask is a valid integer value -- check for overly permissive permissions. Ok(Some(mask)) => { if (mask & WRITE_WORLD > 0) || (mask & EXECUTE_GROUP > 0) { checker.report_diagnostic( BadFilePermissions { reason: Reason::Permissive(mask), }, mode_arg.range(), ); } } // The mask is an invalid integer value (i.e., it's out of range). Err(_) => { checker.report_diagnostic( BadFilePermissions { reason: Reason::Invalid, }, mode_arg.range(), ); } } } } } const WRITE_WORLD: u16 = 0o2; const EXECUTE_GROUP: u16 = 0o10; fn py_stat(qualified_name: &QualifiedName) -> Option<u16> { match qualified_name.segments() { ["stat", "ST_MODE"] => Some(0o0), ["stat", "S_IFDOOR"] => Some(0o0), ["stat", "S_IFPORT"] => Some(0o0), ["stat", "ST_INO"] => Some(0o1), ["stat", "S_IXOTH"] => Some(0o1), ["stat", "UF_NODUMP"] => Some(0o1), ["stat", "ST_DEV"] => Some(0o2), ["stat", "S_IWOTH"] => Some(0o2), ["stat", "UF_IMMUTABLE"] => Some(0o2), ["stat", "ST_NLINK"] => Some(0o3), ["stat", "ST_UID"] => Some(0o4), ["stat", "S_IROTH"] => Some(0o4), ["stat", "UF_APPEND"] => Some(0o4), ["stat", "ST_GID"] => Some(0o5), ["stat", "ST_SIZE"] => Some(0o6), ["stat", "ST_ATIME"] => Some(0o7), ["stat", "S_IRWXO"] => Some(0o7), ["stat", "ST_MTIME"] => Some(0o10), ["stat", "S_IXGRP"] => Some(0o10), ["stat", "UF_OPAQUE"] => Some(0o10), ["stat", "ST_CTIME"] => Some(0o11), ["stat", "S_IWGRP"] => Some(0o20), ["stat", "UF_NOUNLINK"] => Some(0o20), ["stat", "S_IRGRP"] => Some(0o40), ["stat", "UF_COMPRESSED"] => Some(0o40), ["stat", "S_IRWXG"] => Some(0o70), ["stat", "S_IEXEC"] => Some(0o100), ["stat", "S_IXUSR"] => Some(0o100), ["stat", "S_IWRITE"] => Some(0o200), ["stat", "S_IWUSR"] => Some(0o200), ["stat", "S_IREAD"] => Some(0o400), ["stat", "S_IRUSR"] => Some(0o400), ["stat", "S_IRWXU"] => Some(0o700), ["stat", "S_ISVTX"] => Some(0o1000), ["stat", "S_ISGID"] => Some(0o2000), ["stat", "S_ENFMT"] => Some(0o2000), ["stat", "S_ISUID"] => Some(0o4000), _ => None, } } /// Return the mask value as a `u16`, if it can be determined. Returns an error if the mask is /// an integer value, but that value is out of range. fn parse_mask(expr: &Expr, semantic: &SemanticModel) -> Result<Option<u16>> { match expr { Expr::NumberLiteral(ast::ExprNumberLiteral { value: ast::Number::Int(int), .. }) => match int.as_u16() { Some(value) => Ok(Some(value)), None => anyhow::bail!("int value out of range"), }, Expr::Attribute(_) => Ok(semantic .resolve_qualified_name(expr) .as_ref() .and_then(py_stat)), Expr::BinOp(ast::ExprBinOp { left, op, right, range: _, node_index: _, }) => { let Some(left_value) = parse_mask(left, semantic)? else { return Ok(None); }; let Some(right_value) = parse_mask(right, semantic)? else { return Ok(None); }; Ok(match op { Operator::BitAnd => Some(left_value & right_value), Operator::BitOr => Some(left_value | right_value), Operator::BitXor => Some(left_value ^ right_value), _ => None, }) } _ => Ok(None), } }
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_bandit/rules/try_except_pass.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/try_except_pass.rs
use ruff_python_ast::{ExceptHandler, Expr, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bandit::helpers::is_untyped_exception; /// ## What it does /// Checks for uses of the `try`-`except`-`pass` pattern. /// /// ## Why is this bad? /// The `try`-`except`-`pass` pattern suppresses all exceptions. Suppressing /// exceptions may hide errors that could otherwise reveal unexpected behavior, /// security vulnerabilities, or malicious activity. Instead, consider logging /// the exception. /// /// ## Example /// ```python /// try: /// ... /// except Exception: /// pass /// ``` /// /// Use instead: /// ```python /// import logging /// /// try: /// ... /// except Exception as exc: /// logging.exception("Exception occurred") /// ``` /// /// ## Options /// - `lint.flake8-bandit.check-typed-exception` /// /// ## References /// - [Common Weakness Enumeration: CWE-703](https://cwe.mitre.org/data/definitions/703.html) /// - [Python documentation: `logging`](https://docs.python.org/3/library/logging.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.237")] pub(crate) struct TryExceptPass; impl Violation for TryExceptPass { #[derive_message_formats] fn message(&self) -> String { "`try`-`except`-`pass` detected, consider logging the exception".to_string() } } /// S110 pub(crate) fn try_except_pass( checker: &Checker, except_handler: &ExceptHandler, type_: Option<&Expr>, body: &[Stmt], check_typed_exception: bool, ) { if matches!(body, [Stmt::Pass(_)]) { if check_typed_exception || is_untyped_exception(type_, checker.semantic()) { checker.report_diagnostic(TryExceptPass, except_handler.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/flake8_bandit/rules/hardcoded_tmp_directory.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs
use ruff_python_ast::{self as ast, Expr, StringLike}; use ruff_text_size::{Ranged, TextRange}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for the use of hardcoded temporary file or directory paths. /// /// ## Why is this bad? /// The use of hardcoded paths for temporary files can be insecure. If an /// attacker discovers the location of a hardcoded path, they can replace the /// contents of the file or directory with a malicious payload. /// /// Other programs may also read or write contents to these hardcoded paths, /// causing unexpected behavior. /// /// ## Example /// ```python /// with open("/tmp/foo.txt", "w") as file: /// ... /// ``` /// /// Use instead: /// ```python /// import tempfile /// /// with tempfile.NamedTemporaryFile() as file: /// ... /// ``` /// /// ## Options /// - `lint.flake8-bandit.hardcoded-tmp-directory` /// - `lint.flake8-bandit.hardcoded-tmp-directory-extend` /// /// ## References /// - [Common Weakness Enumeration: CWE-377](https://cwe.mitre.org/data/definitions/377.html) /// - [Common Weakness Enumeration: CWE-379](https://cwe.mitre.org/data/definitions/379.html) /// - [Python documentation: `tempfile`](https://docs.python.org/3/library/tempfile.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.211")] pub(crate) struct HardcodedTempFile { string: String, } impl Violation for HardcodedTempFile { #[derive_message_formats] fn message(&self) -> String { let HardcodedTempFile { string } = self; format!( "Probable insecure usage of temporary file or directory: \"{}\"", string.escape_debug() ) } } /// S108 pub(crate) fn hardcoded_tmp_directory(checker: &Checker, string: StringLike) { match string { StringLike::String(ast::ExprStringLiteral { value, .. }) => { check(checker, value.to_str(), string.range()); } StringLike::FString(ast::ExprFString { value, .. }) => { for part in value { match part { ast::FStringPart::Literal(literal) => { check(checker, literal, literal.range()); } ast::FStringPart::FString(f_string) => { for literal in f_string.elements.literals() { check(checker, literal, literal.range()); } } } } } // These are not actually strings StringLike::Bytes(_) => (), // TODO(dylan) - verify that we should skip these StringLike::TString(_) => (), } } fn check(checker: &Checker, value: &str, range: TextRange) { if !checker .settings() .flake8_bandit .hardcoded_tmp_directory .iter() .any(|prefix| value.starts_with(prefix)) { return; } if let Some(Expr::Call(ast::ExprCall { func, .. })) = checker.semantic().current_expression_parent() { if checker .semantic() .resolve_qualified_name(func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["tempfile", ..])) { return; } } checker.report_diagnostic( HardcodedTempFile { string: value.to_string(), }, 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/flake8_bandit/rules/ssl_with_bad_defaults.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_bad_defaults.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, StmtFunctionDef}; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for function definitions with default arguments set to insecure SSL /// and TLS protocol versions. /// /// ## Why is this bad? /// Several highly publicized exploitable flaws have been discovered in all /// versions of SSL and early versions of TLS. The following versions are /// considered insecure, and should be avoided: /// - SSL v2 /// - SSL v3 /// - TLS v1 /// - TLS v1.1 /// /// ## Example /// /// ```python /// import ssl /// /// /// def func(version=ssl.PROTOCOL_TLSv1): ... /// ``` /// /// Use instead: /// /// ```python /// import ssl /// /// /// def func(version=ssl.PROTOCOL_TLSv1_2): ... /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct SslWithBadDefaults { protocol: String, } impl Violation for SslWithBadDefaults { #[derive_message_formats] fn message(&self) -> String { let SslWithBadDefaults { protocol } = self; format!("Argument default set to insecure SSL protocol: `{protocol}`") } } /// S503 pub(crate) fn ssl_with_bad_defaults(checker: &Checker, function_def: &StmtFunctionDef) { for default in function_def .parameters .iter_non_variadic_params() .filter_map(|param| param.default.as_deref()) { match default { Expr::Name(ast::ExprName { id, range, .. }) => { if is_insecure_protocol(id.as_str()) { checker.report_diagnostic( SslWithBadDefaults { protocol: id.to_string(), }, *range, ); } } Expr::Attribute(ast::ExprAttribute { attr, range, .. }) => { if is_insecure_protocol(attr.as_str()) { checker.report_diagnostic( SslWithBadDefaults { protocol: attr.to_string(), }, *range, ); } } _ => {} } } } /// Returns `true` if the given protocol name is insecure. fn is_insecure_protocol(name: &str) -> bool { matches!( name, "PROTOCOL_SSLv2" | "PROTOCOL_SSLv3" | "PROTOCOL_TLSv1" | "PROTOCOL_TLSv1_1" | "SSLv2_METHOD" | "SSLv23_METHOD" | "SSLv3_METHOD" | "TLSv1_METHOD" | "TLSv1_1_METHOD" ) }
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_bandit/rules/hardcoded_password_string.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_password_string.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; use crate::rules::flake8_bandit::helpers::{matches_password_name, string_literal}; /// ## What it does /// Checks for potential uses of hardcoded passwords in strings. /// /// ## Why is this bad? /// Including a hardcoded password in source code is a security risk, as an /// attacker could discover the password and use it to gain unauthorized /// access. /// /// Instead, store passwords and other secrets in configuration files, /// environment variables, or other sources that are excluded from version /// control. /// /// ## Example /// ```python /// SECRET_KEY = "hunter2" /// ``` /// /// Use instead: /// ```python /// import os /// /// SECRET_KEY = os.environ["SECRET_KEY"] /// ``` /// /// ## References /// - [Common Weakness Enumeration: CWE-259](https://cwe.mitre.org/data/definitions/259.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct HardcodedPasswordString { name: String, } impl Violation for HardcodedPasswordString { #[derive_message_formats] fn message(&self) -> String { let HardcodedPasswordString { name } = self; format!( "Possible hardcoded password assigned to: \"{}\"", name.escape_debug() ) } } fn password_target(target: &Expr) -> Option<&str> { let target_name = match target { // variable = "s3cr3t" Expr::Name(ast::ExprName { id, .. }) => id.as_str(), // d["password"] = "s3cr3t" Expr::Subscript(ast::ExprSubscript { slice, .. }) => match slice.as_ref() { Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => value.to_str(), _ => return None, }, // obj.password = "s3cr3t" Expr::Attribute(ast::ExprAttribute { attr, .. }) => attr, _ => return None, }; if matches_password_name(target_name) { Some(target_name) } else { None } } /// S105 pub(crate) fn compare_to_hardcoded_password_string( checker: &Checker, left: &Expr, comparators: &[Expr], ) { for comp in comparators { if string_literal(comp).is_none_or(str::is_empty) { continue; } let Some(name) = password_target(left) else { continue; }; checker.report_diagnostic( HardcodedPasswordString { name: name.to_string(), }, comp.range(), ); } } /// S105 pub(crate) fn assign_hardcoded_password_string(checker: &Checker, value: &Expr, targets: &[Expr]) { if string_literal(value) .filter(|string| !string.is_empty()) .is_some() { for target in targets { if let Some(name) = password_target(target) { checker.report_diagnostic( HardcodedPasswordString { name: name.to_string(), }, value.range(), ); return; } } } }
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_bandit/rules/flask_debug_true.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/flask_debug_true.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_true; use ruff_python_ast::{Expr, ExprAttribute, ExprCall}; use ruff_python_semantic::analyze::typing; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of `debug=True` in Flask. /// /// ## Why is this bad? /// Enabling debug mode shows an interactive debugger in the browser if an /// error occurs, and allows running arbitrary Python code from the browser. /// This could leak sensitive information, or allow an attacker to run /// arbitrary code. /// /// ## Example /// ```python /// from flask import Flask /// /// app = Flask() /// /// app.run(debug=True) /// ``` /// /// Use instead: /// ```python /// import os /// /// from flask import Flask /// /// app = Flask() /// /// app.run(debug=os.environ["ENV"] == "dev") /// ``` /// /// ## References /// - [Flask documentation: Debug Mode](https://flask.palletsprojects.com/en/latest/quickstart/#debug-mode) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct FlaskDebugTrue; impl Violation for FlaskDebugTrue { #[derive_message_formats] fn message(&self) -> String { "Use of `debug=True` in Flask app detected".to_string() } } /// S201 pub(crate) fn flask_debug_true(checker: &Checker, call: &ExprCall) { let Expr::Attribute(ExprAttribute { attr, value, .. }) = call.func.as_ref() else { return; }; if attr.as_str() != "run" { return; } let Some(debug_argument) = call.arguments.find_keyword("debug") else { return; }; if !is_const_true(&debug_argument.value) { return; } if typing::resolve_assignment(value, checker.semantic()) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["flask", "Flask"])) { checker.report_diagnostic(FlaskDebugTrue, debug_argument.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/flake8_bandit/rules/hashlib_insecure_hash_functions.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_false; use ruff_python_ast::{self as ast, Arguments}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bandit::helpers::string_literal; /// ## What it does /// Checks for uses of weak or broken cryptographic hash functions in /// `hashlib` and `crypt` libraries. /// /// ## Why is this bad? /// Weak or broken cryptographic hash functions may be susceptible to /// collision attacks (where two different inputs produce the same hash) or /// pre-image attacks (where an attacker can find an input that produces a /// given hash). This can lead to security vulnerabilities in applications /// that rely on these hash functions. /// /// Avoid using weak or broken cryptographic hash functions in security /// contexts. Instead, use a known secure hash function such as SHA256. /// /// Note: This rule targets the following weak algorithm names in `hashlib`: /// `md4`, `md5`, `sha`, and `sha1`. It also flags uses of `crypt.crypt` and /// `crypt.mksalt` when configured with `METHOD_CRYPT`, `METHOD_MD5`, or /// `METHOD_BLOWFISH`. /// /// It does not attempt to lint OpenSSL- or platform-specific aliases and OIDs /// (for example: `"sha-1"`, `"ssl3-sha1"`, `"ssl3-md5"`, or /// `"1.3.14.3.2.26"`), nor variations with trailing spaces, as the set of /// accepted aliases depends on the underlying OpenSSL version and varies across /// platforms and Python builds. /// /// ## Example /// ```python /// import hashlib /// /// /// def certificate_is_valid(certificate: bytes, known_hash: str) -> bool: /// hash = hashlib.md5(certificate).hexdigest() /// return hash == known_hash /// ``` /// /// Use instead: /// ```python /// import hashlib /// /// /// def certificate_is_valid(certificate: bytes, known_hash: str) -> bool: /// hash = hashlib.sha256(certificate).hexdigest() /// return hash == known_hash /// ``` /// /// or add `usedforsecurity=False` if the hashing algorithm is not used in a security context, e.g. /// as a non-cryptographic one-way compression function: /// ```python /// import hashlib /// /// /// def certificate_is_valid(certificate: bytes, known_hash: str) -> bool: /// hash = hashlib.md5(certificate, usedforsecurity=False).hexdigest() /// return hash == known_hash /// ``` /// /// /// ## References /// - [Python documentation: `hashlib` — Secure hashes and message digests](https://docs.python.org/3/library/hashlib.html) /// - [Python documentation: `crypt` — Function to check Unix passwords](https://docs.python.org/3/library/crypt.html) /// - [Python documentation: `FIPS` - FIPS compliant hashlib implementation](https://docs.python.org/3/library/hashlib.html#hashlib.algorithms_guaranteed) /// - [Common Weakness Enumeration: CWE-327](https://cwe.mitre.org/data/definitions/327.html) /// - [Common Weakness Enumeration: CWE-328](https://cwe.mitre.org/data/definitions/328.html) /// - [Common Weakness Enumeration: CWE-916](https://cwe.mitre.org/data/definitions/916.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.212")] pub(crate) struct HashlibInsecureHashFunction { library: String, string: String, } impl Violation for HashlibInsecureHashFunction { #[derive_message_formats] fn message(&self) -> String { let HashlibInsecureHashFunction { library, string } = self; format!("Probable use of insecure hash functions in `{library}`: `{string}`") } } /// S324 pub(crate) fn hashlib_insecure_hash_functions(checker: &Checker, call: &ast::ExprCall) { if !checker .semantic() .seen_module(Modules::HASHLIB | Modules::CRYPT) { return; } if let Some(weak_hash_call) = checker .semantic() .resolve_qualified_name(&call.func) .and_then(|qualified_name| match qualified_name.segments() { ["hashlib", "new"] => Some(WeakHashCall::Hashlib { call: HashlibCall::New, }), ["hashlib", "md4"] => Some(WeakHashCall::Hashlib { call: HashlibCall::WeakHash("md4"), }), ["hashlib", "md5"] => Some(WeakHashCall::Hashlib { call: HashlibCall::WeakHash("md5"), }), ["hashlib", "sha"] => Some(WeakHashCall::Hashlib { call: HashlibCall::WeakHash("sha"), }), ["hashlib", "sha1"] => Some(WeakHashCall::Hashlib { call: HashlibCall::WeakHash("sha1"), }), ["crypt", "crypt" | "mksalt"] => Some(WeakHashCall::Crypt), _ => None, }) { match weak_hash_call { WeakHashCall::Hashlib { call: hashlib_call } => { detect_insecure_hashlib_calls(checker, call, hashlib_call); } WeakHashCall::Crypt => detect_insecure_crypt_calls(checker, call), } } } fn detect_insecure_hashlib_calls( checker: &Checker, call: &ast::ExprCall, hashlib_call: HashlibCall, ) { if !is_used_for_security(&call.arguments) { return; } match hashlib_call { HashlibCall::New => { let Some(name_arg) = call.arguments.find_argument_value("name", 0) else { return; }; let Some(hash_func_name) = string_literal(name_arg) else { return; }; // `hashlib.new` accepts mixed lowercase and uppercase names for hash // functions. if matches!( hash_func_name.to_ascii_lowercase().as_str(), "md4" | "md5" | "sha" | "sha1" ) { checker.report_diagnostic( HashlibInsecureHashFunction { library: "hashlib".to_string(), string: hash_func_name.to_string(), }, name_arg.range(), ); } } HashlibCall::WeakHash(func_name) => { checker.report_diagnostic( HashlibInsecureHashFunction { library: "hashlib".to_string(), string: (*func_name).to_string(), }, call.func.range(), ); } } } fn detect_insecure_crypt_calls(checker: &Checker, call: &ast::ExprCall) { let Some(method) = checker .semantic() .resolve_qualified_name(&call.func) .and_then(|qualified_name| match qualified_name.segments() { ["crypt", "crypt"] => Some(("salt", 1)), ["crypt", "mksalt"] => Some(("method", 0)), _ => None, }) .and_then(|(argument_name, position)| { call.arguments.find_argument_value(argument_name, position) }) else { return; }; let Some(qualified_name) = checker.semantic().resolve_qualified_name(method) else { return; }; if matches!( qualified_name.segments(), ["crypt", "METHOD_CRYPT" | "METHOD_MD5" | "METHOD_BLOWFISH"] ) { checker.report_diagnostic( HashlibInsecureHashFunction { library: "crypt".to_string(), string: qualified_name.to_string(), }, method.range(), ); } } fn is_used_for_security(arguments: &Arguments) -> bool { arguments .find_keyword("usedforsecurity") .is_none_or(|keyword| !is_const_false(&keyword.value)) } #[derive(Debug, Copy, Clone)] enum WeakHashCall { Hashlib { call: HashlibCall }, Crypt, } #[derive(Debug, Copy, Clone)] enum HashlibCall { New, WeakHash(&'static str), }
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_bandit/rules/paramiko_calls.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/paramiko_calls.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 `paramiko` calls. /// /// ## Why is this bad? /// `paramiko` calls allow users to execute arbitrary shell commands on a /// remote machine. If the inputs to these calls are not properly sanitized, /// they can be vulnerable to shell injection attacks. /// /// ## Example /// ```python /// import paramiko /// /// client = paramiko.SSHClient() /// client.exec_command("echo $HOME") /// ``` /// /// ## References /// - [Common Weakness Enumeration: CWE-78](https://cwe.mitre.org/data/definitions/78.html) /// - [Paramiko documentation: `SSHClient.exec_command()`](https://docs.paramiko.org/en/stable/api/client.html#paramiko.client.SSHClient.exec_command) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.270")] pub(crate) struct ParamikoCall; impl Violation for ParamikoCall { #[derive_message_formats] fn message(&self) -> String { "Possible shell injection via Paramiko call; check inputs are properly sanitized" .to_string() } } /// S601 pub(crate) fn paramiko_call(checker: &Checker, func: &Expr) { if checker .semantic() .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["paramiko", "exec_command"]) }) { checker.report_diagnostic(ParamikoCall, 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/flake8_bandit/rules/ssl_with_no_version.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/ssl_with_no_version.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprCall; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for calls to `ssl.wrap_socket()` without an `ssl_version`. /// /// ## Why is this bad? /// This method is known to provide a default value that maximizes /// compatibility, but permits use of insecure protocols. /// /// ## Example /// ```python /// import ssl /// /// ssl.wrap_socket() /// ``` /// /// Use instead: /// ```python /// import ssl /// /// ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct SslWithNoVersion; impl Violation for SslWithNoVersion { #[derive_message_formats] fn message(&self) -> String { "`ssl.wrap_socket` called without an `ssl_version``".to_string() } } /// S504 pub(crate) fn ssl_with_no_version(checker: &Checker, call: &ExprCall) { if checker .semantic() .resolve_qualified_name(call.func.as_ref()) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["ssl", "wrap_socket"])) { if call.arguments.find_keyword("ssl_version").is_none() { checker.report_diagnostic(SslWithNoVersion, 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/flake8_bandit/rules/hardcoded_sql_expression.rs
crates/ruff_linter/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs
use std::sync::LazyLock; use regex::Regex; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::str::raw_contents; use ruff_python_ast::{self as ast, Expr, Operator}; use ruff_text_size::Ranged; use crate::Locator; use crate::Violation; use crate::checkers::ast::Checker; static SQL_REGEX: LazyLock<Regex> = LazyLock::new(|| { Regex::new( r"(?isx) \b (select\s+.*\s+from\s |delete\s+from\s |(insert|replace)\s+.*\s+values\s |update\s+.*\s+set\s ) ", ) .unwrap() }); /// ## What it does /// Checks for strings that resemble SQL statements involved in some form /// string building operation. /// /// ## Why is this bad? /// SQL injection is a common attack vector for web applications. Directly /// interpolating user input into SQL statements should always be avoided. /// Instead, favor parameterized queries, in which the SQL statement is /// provided separately from its parameters, as supported by `psycopg3` /// and other database drivers and ORMs. /// /// ## Example /// ```python /// query = "DELETE FROM foo WHERE id = '%s'" % identifier /// ``` /// /// ## References /// - [B608: Test for SQL injection](https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html) /// - [psycopg3: Server-side binding](https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#server-side-binding) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.245")] pub(crate) struct HardcodedSQLExpression; impl Violation for HardcodedSQLExpression { #[derive_message_formats] fn message(&self) -> String { "Possible SQL injection vector through string-based query construction".to_string() } } /// S608 pub(crate) fn hardcoded_sql_expression(checker: &Checker, expr: &Expr) { let content = match expr { // "select * from table where val = " + "str" + ... Expr::BinOp(ast::ExprBinOp { op: Operator::Add, .. }) => { // Only evaluate the full BinOp, not the nested components. if checker .semantic() .current_expression_parent() .is_some_and(ruff_python_ast::Expr::is_bin_op_expr) { return; } if is_explicit_concatenation(expr) != Some(true) { return; } checker.generator().expr(expr) } // "select * from table where val = %s" % ... Expr::BinOp(ast::ExprBinOp { left, op: Operator::Mod, .. }) => { let Some(string) = left.as_string_literal_expr() else { return; }; string.value.to_str().escape_default().to_string() } Expr::Call(ast::ExprCall { func, .. }) => { let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func.as_ref() else { return; }; // "select * from table where val = {}".format(...) if attr != "format" { return; } let Some(string) = value.as_string_literal_expr() else { return; }; string.value.to_str().escape_default().to_string() } // f"select * from table where val = {val}" Expr::FString(f_string) if f_string.value.f_strings().any(|fs| { fs.elements .iter() .any(ast::InterpolatedStringElement::is_interpolation) }) => { concatenated_f_string(f_string, checker.locator()) } _ => return, }; if SQL_REGEX.is_match(&content) { checker.report_diagnostic(HardcodedSQLExpression, expr.range()); } } /// Concatenates the contents of an f-string, without the prefix and quotes, /// and escapes any special characters. /// /// ## Example /// /// ```python /// "foo" f"bar {x}" "baz" /// ``` /// /// becomes `foobar {x}baz`. fn concatenated_f_string(expr: &ast::ExprFString, locator: &Locator) -> String { expr.value .iter() .filter_map(|part| raw_contents(locator.slice(part))) .collect() } /// Returns `Some(true)` if an expression appears to be an explicit string concatenation, /// `Some(false)` if it's _not_ an explicit concatenation, and `None` if it's ambiguous. fn is_explicit_concatenation(expr: &Expr) -> Option<bool> { match expr { Expr::BinOp(ast::ExprBinOp { left, right, .. }) => { let left = is_explicit_concatenation(left); let right = is_explicit_concatenation(right); match (left, right) { // If either side is definitively _not_ a string, neither is the expression. (Some(false), _) | (_, Some(false)) => Some(false), // If either side is definitively a string, the expression is a string. (Some(true), _) | (_, Some(true)) => Some(true), _ => None, } } // Ambiguous (e.g., `x + y`). Expr::Call(_) => None, Expr::Subscript(_) => None, Expr::Attribute(_) => None, Expr::Name(_) => None, // Non-strings. Expr::Lambda(_) => Some(false), Expr::List(_) => Some(false), Expr::Tuple(_) => Some(false), Expr::Dict(_) => Some(false), Expr::Set(_) => Some(false), Expr::Generator(_) => Some(false), Expr::Yield(_) => Some(false), Expr::YieldFrom(_) => Some(false), Expr::Await(_) => Some(false), Expr::Starred(_) => Some(false), Expr::Slice(_) => Some(false), Expr::BooleanLiteral(_) => Some(false), Expr::EllipsisLiteral(_) => Some(false), Expr::NumberLiteral(_) => Some(false), Expr::ListComp(_) => Some(false), Expr::SetComp(_) => Some(false), Expr::DictComp(_) => Some(false), Expr::Compare(_) => Some(false), Expr::FString(_) => Some(true), // TODO(dylan): decide whether to trigger here Expr::TString(_) => Some(false), Expr::StringLiteral(_) => Some(true), Expr::BytesLiteral(_) => Some(false), Expr::NoneLiteral(_) => Some(false), Expr::IpyEscapeCommand(_) => Some(false), // Conditionally strings. Expr::Named(ast::ExprNamed { value, .. }) => is_explicit_concatenation(value), Expr::If(ast::ExprIf { body, orelse, .. }) => { let body = is_explicit_concatenation(body); let orelse = is_explicit_concatenation(orelse); match (body, orelse) { // If either side is definitively a string, the expression could be a string. (Some(true), _) | (_, Some(true)) => Some(true), // If both sides are definitively _not_ a string, neither is the expression. (Some(false), Some(false)) => Some(false), _ => None, } } Expr::BoolOp(ast::ExprBoolOp { values, .. }) => { let values = values .iter() .map(is_explicit_concatenation) .collect::<Vec<_>>(); if values.contains(&Some(true)) { Some(true) } else if values.iter().all(|v| *v == Some(false)) { Some(false) } else { None } } Expr::UnaryOp(ast::ExprUnaryOp { operand, .. }) => is_explicit_concatenation(operand), } }
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_self/settings.rs
crates/ruff_linter/src/rules/flake8_self/settings.rs
//! Settings for the `flake8-self` plugin. use crate::display_settings; use ruff_macros::CacheKey; use ruff_python_ast::name::Name; use std::fmt::{Display, Formatter}; // By default, ignore the `namedtuple` methods and attributes, as well as the // _sunder_ names in Enum, which are underscore-prefixed to prevent conflicts // with field names. pub const IGNORE_NAMES: [&str; 7] = [ "_make", "_asdict", "_replace", "_fields", "_field_defaults", "_name_", "_value_", ]; #[derive(Debug, Clone, CacheKey)] pub struct Settings { pub ignore_names: Vec<Name>, } impl Default for Settings { fn default() -> Self { Self { ignore_names: IGNORE_NAMES.map(Name::new_static).to_vec(), } } } impl Display for Settings { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { display_settings! { formatter = f, namespace = "linter.flake8_self", fields = [ self.ignore_names | array ] } 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_self/mod.rs
crates/ruff_linter/src/rules/flake8_self/mod.rs
//! Rules from [flake8-self](https://pypi.org/project/flake8-self/). pub(crate) mod rules; pub mod settings; #[cfg(test)] mod tests { use std::path::Path; use crate::registry::Rule; use crate::rules::flake8_self; use crate::test::test_path; use crate::{assert_diagnostics, settings}; use anyhow::Result; use ruff_python_ast::name::Name; use test_case::test_case; #[test_case(Rule::PrivateMemberAccess, Path::new("SLF001.py"))] #[test_case(Rule::PrivateMemberAccess, Path::new("SLF001_1.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("flake8_self").join(path).as_path(), &settings::LinterSettings::for_rule(rule_code), )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test] fn ignore_names() -> Result<()> { let diagnostics = test_path( Path::new("flake8_self/SLF001_extended.py"), &settings::LinterSettings { flake8_self: flake8_self::settings::Settings { ignore_names: vec![Name::new_static("_meta")], }, ..settings::LinterSettings::for_rule(Rule::PrivateMemberAccess) }, )?; assert_diagnostics!(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_self/rules/private_member_access.rs
crates/ruff_linter/src/rules/flake8_self/rules/private_member_access.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::{is_dunder, is_sunder}; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::analyze::typing; use ruff_python_semantic::analyze::typing::TypeChecker; use ruff_python_semantic::{BindingKind, ScopeKind, SemanticModel}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pylint::helpers::is_dunder_operator_method; /// ## What it does /// Checks for accesses on "private" class members. /// /// ## Why is this bad? /// In Python, the convention is such that class members that are prefixed /// with a single underscore, or prefixed but not suffixed with a double /// underscore, are considered private and intended for internal use. /// /// Using such "private" members is considered a misuse of the class, as /// there are no guarantees that the member will be present in future /// versions, that it will have the same type, or that it will have the same /// behavior. Instead, use the class's public interface. /// /// This rule ignores accesses on dunder methods (e.g., `__init__`) and sunder /// methods (e.g., `_missing_`). /// /// ## Example /// ```python /// class Class: /// def __init__(self): /// self._private_member = "..." /// /// /// var = Class() /// print(var._private_member) /// ``` /// /// Use instead: /// ```python /// class Class: /// def __init__(self): /// self.public_member = "..." /// /// /// var = Class() /// print(var.public_member) /// ``` /// /// ## Options /// - `lint.flake8-self.ignore-names` /// /// ## References /// - [_What is the meaning of single or double underscores before an object name?_](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.240")] pub(crate) struct PrivateMemberAccess { access: String, } impl Violation for PrivateMemberAccess { #[derive_message_formats] fn message(&self) -> String { let PrivateMemberAccess { access } = self; format!("Private member accessed: `{access}`") } } /// SLF001 pub(crate) fn private_member_access(checker: &Checker, expr: &Expr) { let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = expr else { return; }; let semantic = checker.semantic(); let current_scope = semantic.current_scope(); if semantic.in_annotation() { return; } if !attr.starts_with('_') || is_dunder(attr) || is_sunder(attr) { return; } if checker .settings() .flake8_self .ignore_names .contains(attr.id()) { return; } // Ignore accesses on instances within special methods (e.g., `__eq__`). if let ScopeKind::Function(ast::StmtFunctionDef { name, .. }) = current_scope.kind { if is_dunder_operator_method(name) { return; } } // Allow some documented private methods, like `os._exit()`. if let Some(qualified_name) = semantic.resolve_qualified_name(expr) { if matches!(qualified_name.segments(), ["os", "_exit"]) { return; } } if let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() { // Ignore `super()` calls. if let Some(name) = UnqualifiedName::from_expr(func) { if matches!(name.segments(), ["super"]) { return; } } } if let Some(name) = UnqualifiedName::from_expr(value) { // Ignore `self` and `cls` accesses. if matches!(name.segments(), ["self" | "cls" | "mcs"]) { return; } } if let Expr::Name(name) = value.as_ref() { // Ignore accesses on class members from _within_ the class. if semantic .resolve_name(name) .and_then(|id| { if let BindingKind::ClassDefinition(scope) = semantic.binding(id).kind { Some(scope) } else { None } }) .is_some_and(|scope| semantic.current_scope_ids().any(|parent| scope == parent)) { return; } if is_same_class_instance(name, semantic) { return; } } checker.report_diagnostic( PrivateMemberAccess { access: attr.to_string(), }, expr.range(), ); } /// Check for the following cases: /// /// * Parameter annotation: /// /// ```python /// class C[T]: /// def f(self, other: C): ... /// def f(self, other: C[...]): ... /// def f(self, other: Annotated[C, ...]): ... /// ``` /// /// * `super().__new__`/`cls` call: /// /// ```python /// class C: /// def __new__(cls): ... /// instance = super().__new__(cls) /// @classmethod /// def m(cls): /// instance = cls() /// ``` /// /// This function is intentionally naive and does not handle more complex cases. /// It is expected to be expanded overtime, possibly when type-aware APIs are available. fn is_same_class_instance(name: &ast::ExprName, semantic: &SemanticModel) -> bool { let Some(binding_id) = semantic.resolve_name(name) else { return false; }; let binding = semantic.binding(binding_id); typing::check_type::<SameClassInstanceChecker>(binding, semantic) } struct SameClassInstanceChecker; impl SameClassInstanceChecker { /// Whether `name` resolves to a class which the semantic model is traversing. fn is_current_class_name(name: &ast::ExprName, semantic: &SemanticModel) -> bool { semantic.current_scopes().any(|scope| { let ScopeKind::Class(class) = scope.kind else { return false; }; class.name.id == name.id }) } } impl TypeChecker for SameClassInstanceChecker { /// `C`, `C[T]`, `Annotated[C, ...]`, `Annotated[C[T], ...]` fn match_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool { let Some(class_name) = find_class_name(annotation, semantic) else { return false; }; Self::is_current_class_name(class_name, semantic) } /// `cls()`, `C()`, `C[T]()`, `super().__new__()` fn match_initializer(initializer: &Expr, semantic: &SemanticModel) -> bool { let Expr::Call(call) = initializer else { return false; }; match &*call.func { Expr::Subscript(_) => Self::match_annotation(&call.func, semantic), Expr::Name(name) => { matches!(&*name.id, "cls" | "mcs") || Self::is_current_class_name(name, semantic) } Expr::Attribute(ast::ExprAttribute { value, attr, .. }) => { let Expr::Call(ast::ExprCall { func, .. }) = &**value else { return false; }; let Expr::Name(ast::ExprName { id: func, .. }) = &**func else { return false; }; func == "super" && attr == "__new__" } _ => false, } } } /// Convert `Annotated[C[T], ...]` to `C` (and similar) to `C` recursively. fn find_class_name<'a>(expr: &'a Expr, semantic: &'a SemanticModel) -> Option<&'a ast::ExprName> { match expr { Expr::Name(name) => Some(name), Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => { if semantic.match_typing_expr(value, "Annotated") { let [expr, ..] = &slice.as_tuple_expr()?.elts[..] else { return None; }; return find_class_name(expr, semantic); } find_class_name(value, semantic) } _ => None, } }
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_self/rules/mod.rs
crates/ruff_linter/src/rules/flake8_self/rules/mod.rs
pub(crate) use private_member_access::*; mod private_member_access;
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_gettext/settings.rs
crates/ruff_linter/src/rules/flake8_gettext/settings.rs
use crate::display_settings; use ruff_macros::CacheKey; use ruff_python_ast::name::Name; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, CacheKey)] pub struct Settings { pub function_names: Vec<Name>, } pub fn default_func_names() -> Vec<Name> { vec![ Name::new_static("_"), Name::new_static("gettext"), Name::new_static("ngettext"), ] } impl Default for Settings { fn default() -> Self { Self { function_names: default_func_names(), } } } impl Display for Settings { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { display_settings! { formatter = f, namespace = "linter.flake8_gettext", fields = [ self.function_names | array ] } 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_gettext/mod.rs
crates/ruff_linter/src/rules/flake8_gettext/mod.rs
//! Rules from [flake8-gettext](https://pypi.org/project/flake8-gettext/). use crate::checkers::ast::Checker; use crate::preview::is_extended_i18n_function_matching_enabled; use ruff_python_ast::name::Name; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; pub(crate) mod rules; pub mod settings; /// Returns true if the [`Expr`] is an internationalization function call. pub(crate) fn is_gettext_func_call( checker: &Checker, func: &Expr, functions_names: &[Name], ) -> bool { if func .as_name_expr() .map(ast::ExprName::id) .is_some_and(|id| functions_names.contains(id)) { return true; } if !is_extended_i18n_function_matching_enabled(checker.settings()) { return false; } let semantic = checker.semantic(); let Some(qualified_name) = semantic.resolve_qualified_name(func) else { return false; }; if semantic.seen_module(Modules::BUILTINS) && matches!( qualified_name.segments(), ["builtins", id] if functions_names.contains(&Name::new(id)), ) { return true; } matches!( qualified_name.segments(), ["gettext", "gettext" | "ngettext"] ) } #[cfg(test)] mod tests { use std::path::Path; use anyhow::Result; use test_case::test_case; use crate::registry::Rule; use crate::settings::types::PreviewMode; use crate::test::test_path; use crate::{assert_diagnostics, settings}; #[test_case(Rule::FStringInGetTextFuncCall, Path::new("INT001.py"))] #[test_case(Rule::FormatInGetTextFuncCall, Path::new("INT002.py"))] #[test_case(Rule::PrintfInGetTextFuncCall, Path::new("INT003.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("flake8_gettext").join(path).as_path(), &settings::LinterSettings::for_rule(rule_code), )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test_case(Rule::FStringInGetTextFuncCall, Path::new("INT001.py"))] #[test_case(Rule::FormatInGetTextFuncCall, Path::new("INT002.py"))] #[test_case(Rule::PrintfInGetTextFuncCall, Path::new("INT003.py"))] fn rules_preview(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!("preview__{}_{}", rule_code.name(), path.to_string_lossy()); let diagnostics = test_path( Path::new("flake8_gettext").join(path).as_path(), &settings::LinterSettings { preview: PreviewMode::Enabled, ..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/flake8_gettext/rules/printf_in_gettext_func_call.rs
crates/ruff_linter/src/rules/flake8_gettext/rules/printf_in_gettext_func_call.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr, Operator}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for printf-style formatted strings in `gettext` function calls. /// /// ## Why is this bad? /// In the `gettext` API, the `gettext` function (often aliased to `_`) returns /// a translation of its input argument by looking it up in a translation /// catalog. /// /// Calling `gettext` with a formatted string as its argument can cause /// unexpected behavior. Since the formatted string is resolved before the /// function call, the translation catalog will look up the formatted string, /// rather than the printf-style template. /// /// Instead, format the value returned by the function call, rather than /// its argument. /// /// ## Example /// ```python /// from gettext import gettext as _ /// /// name = "Maria" /// _("Hello, %s!" % name) # Looks for "Hello, Maria!". /// ``` /// /// Use instead: /// ```python /// from gettext import gettext as _ /// /// name = "Maria" /// _("Hello, %s!") % name # Looks for "Hello, %s!". /// ``` /// /// ## Options /// /// - `lint.flake8-gettext.function-names` /// /// ## References /// - [Python documentation: `gettext` — Multilingual internationalization services](https://docs.python.org/3/library/gettext.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.260")] pub(crate) struct PrintfInGetTextFuncCall; impl Violation for PrintfInGetTextFuncCall { #[derive_message_formats] fn message(&self) -> String { "printf-style format is resolved before function call; consider `_(\"string %s\") % arg`" .to_string() } } /// INT003 pub(crate) fn printf_in_gettext_func_call(checker: &Checker, args: &[Expr]) { if let Some(first) = args.first() { if let Expr::BinOp(ast::ExprBinOp { op: Operator::Mod, left, .. }) = &first { if left.is_string_literal_expr() { checker.report_diagnostic(PrintfInGetTextFuncCall {}, first.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/flake8_gettext/rules/format_in_gettext_func_call.rs
crates/ruff_linter/src/rules/flake8_gettext/rules/format_in_gettext_func_call.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; /// ## What it does /// Checks for `str.format` calls in `gettext` function calls. /// /// ## Why is this bad? /// In the `gettext` API, the `gettext` function (often aliased to `_`) returns /// a translation of its input argument by looking it up in a translation /// catalog. /// /// Calling `gettext` with a formatted string as its argument can cause /// unexpected behavior. Since the formatted string is resolved before the /// function call, the translation catalog will look up the formatted string, /// rather than the `str.format`-style template. /// /// Instead, format the value returned by the function call, rather than /// its argument. /// /// ## Example /// ```python /// from gettext import gettext as _ /// /// name = "Maria" /// _("Hello, {}!".format(name)) # Looks for "Hello, Maria!". /// ``` /// /// Use instead: /// ```python /// from gettext import gettext as _ /// /// name = "Maria" /// _("Hello, %s!") % name # Looks for "Hello, %s!". /// ``` /// /// ## Options /// /// - `lint.flake8-gettext.function-names` /// /// ## References /// - [Python documentation: `gettext` — Multilingual internationalization services](https://docs.python.org/3/library/gettext.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.260")] pub(crate) struct FormatInGetTextFuncCall; impl Violation for FormatInGetTextFuncCall { #[derive_message_formats] fn message(&self) -> String { "`format` method argument is resolved before function call; consider `_(\"string %s\") % arg`".to_string() } } /// INT002 pub(crate) fn format_in_gettext_func_call(checker: &Checker, args: &[Expr]) { if let Some(first) = args.first() { if let Expr::Call(ast::ExprCall { func, .. }) = &first { if let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() { if attr == "format" { checker.report_diagnostic(FormatInGetTextFuncCall {}, first.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/flake8_gettext/rules/f_string_in_gettext_func_call.rs
crates/ruff_linter/src/rules/flake8_gettext/rules/f_string_in_gettext_func_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 f-strings in `gettext` function calls. /// /// ## Why is this bad? /// In the `gettext` API, the `gettext` function (often aliased to `_`) returns /// a translation of its input argument by looking it up in a translation /// catalog. /// /// Calling `gettext` with an f-string as its argument can cause unexpected /// behavior. Since the f-string is resolved before the function call, the /// translation catalog will look up the formatted string, rather than the /// f-string template. /// /// Instead, format the value returned by the function call, rather than /// its argument. /// /// ## Example /// ```python /// from gettext import gettext as _ /// /// name = "Maria" /// _(f"Hello, {name}!") # Looks for "Hello, Maria!". /// ``` /// /// Use instead: /// ```python /// from gettext import gettext as _ /// /// name = "Maria" /// _("Hello, %s!") % name # Looks for "Hello, %s!". /// ``` /// /// ## Options /// /// - `lint.flake8-gettext.function-names` /// /// ## References /// - [Python documentation: `gettext` — Multilingual internationalization services](https://docs.python.org/3/library/gettext.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.260")] pub(crate) struct FStringInGetTextFuncCall; impl Violation for FStringInGetTextFuncCall { #[derive_message_formats] fn message(&self) -> String { "f-string is resolved before function call; consider `_(\"string %s\") % arg`".to_string() } } /// INT001 pub(crate) fn f_string_in_gettext_func_call(checker: &Checker, args: &[Expr]) { if let Some(first) = args.first() { if first.is_f_string_expr() { checker.report_diagnostic(FStringInGetTextFuncCall {}, first.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/flake8_gettext/rules/mod.rs
crates/ruff_linter/src/rules/flake8_gettext/rules/mod.rs
pub(crate) use f_string_in_gettext_func_call::*; pub(crate) use format_in_gettext_func_call::*; pub(crate) use printf_in_gettext_func_call::*; mod f_string_in_gettext_func_call; mod format_in_gettext_func_call; mod printf_in_gettext_func_call;
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_bugbear/settings.rs
crates/ruff_linter/src/rules/flake8_bugbear/settings.rs
//! Settings for the `flake8-bugbear` plugin. use crate::display_settings; use ruff_macros::CacheKey; use std::fmt::{Display, Formatter}; #[derive(Debug, Clone, Default, CacheKey)] pub struct Settings { pub extend_immutable_calls: Vec<String>, } impl Display for Settings { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { display_settings! { formatter = f, namespace = "linter.flake8_bugbear", fields = [ self.extend_immutable_calls | array ] } 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_bugbear/helpers.rs
crates/ruff_linter/src/rules/flake8_bugbear/helpers.rs
use ruff_notebook::CellOffsets; use ruff_python_semantic::SemanticModel; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::Locator; use ruff_python_ast::{self as ast, Arguments, Expr}; /// Return `true` if the statement containing the current expression is the last /// top-level expression in the cell. This assumes that the source is a Jupyter /// Notebook. pub(super) fn at_last_top_level_expression_in_cell( semantic: &SemanticModel, locator: &Locator, cell_offsets: Option<&CellOffsets>, ) -> bool { if !semantic.at_top_level() { return false; } let current_statement_end = semantic.current_statement().end(); cell_offsets .and_then(|cell_offsets| cell_offsets.containing_range(current_statement_end)) .is_some_and(|cell_range| { SimpleTokenizer::new( locator.contents(), TextRange::new(current_statement_end, cell_range.end()), ) .all(|token| token.kind() == SimpleTokenKind::Semi || token.kind().is_trivia()) }) } /// Return `true` if the [`Expr`] appears to be an infinite iterator (e.g., a call to /// `itertools.cycle` or similar). pub(crate) fn is_infinite_iterable(arg: &Expr, semantic: &SemanticModel) -> bool { let Expr::Call(ast::ExprCall { func, arguments: Arguments { args, keywords, .. }, .. }) = &arg else { return false; }; semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| match qualified_name.segments() { ["itertools", "cycle" | "count"] => true, ["itertools", "repeat"] => { // Ex) `itertools.repeat(1)` if keywords.is_empty() && args.len() == 1 { return true; } // Ex) `itertools.repeat(1, None)` if args.len() == 2 && args[1].is_none_literal_expr() { return true; } // Ex) `itertools.repeat(1, times=None)` for keyword in keywords { if keyword.arg.as_ref().is_some_and(|name| name == "times") && keyword.value.is_none_literal_expr() { return true; } } false } _ => false, }) } /// Return `true` if any expression in the iterator appears to be an infinite iterator. pub(crate) fn any_infinite_iterables<'a>( iter: impl IntoIterator<Item = &'a Expr>, semantic: &SemanticModel, ) -> bool { iter.into_iter() .any(|arg| is_infinite_iterable(arg, semantic)) }
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_bugbear/mod.rs
crates/ruff_linter/src/rules/flake8_bugbear/mod.rs
//! Rules from [flake8-bugbear](https://pypi.org/project/flake8-bugbear/). pub(crate) mod helpers; 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::assert_diagnostics; use crate::registry::Rule; use crate::settings::LinterSettings; use crate::test::test_path; use crate::settings::types::PreviewMode; use ruff_python_ast::PythonVersion; #[test_case(Rule::AbstractBaseClassWithoutAbstractMethod, Path::new("B024.py"))] #[test_case(Rule::AssertFalse, Path::new("B011.py"))] #[test_case(Rule::AssertRaisesException, Path::new("B017_0.py"))] #[test_case(Rule::AssertRaisesException, Path::new("B017_1.py"))] #[test_case(Rule::AssignmentToOsEnviron, Path::new("B003.py"))] #[test_case(Rule::CachedInstanceMethod, Path::new("B019.py"))] #[test_case(Rule::ClassAsDataStructure, Path::new("class_as_data_structure.py"))] #[test_case(Rule::DuplicateHandlerException, Path::new("B014.py"))] #[test_case(Rule::DuplicateTryBlockException, Path::new("B025.py"))] #[test_case(Rule::DuplicateValue, Path::new("B033.py"))] #[test_case(Rule::EmptyMethodWithoutAbstractDecorator, Path::new("B027.py"))] #[test_case(Rule::EmptyMethodWithoutAbstractDecorator, Path::new("B027.pyi"))] #[test_case(Rule::ExceptWithEmptyTuple, Path::new("B029.py"))] #[test_case(Rule::ExceptWithNonExceptionClasses, Path::new("B030.py"))] #[test_case(Rule::FStringDocstring, Path::new("B021.py"))] #[test_case(Rule::FunctionCallInDefaultArgument, Path::new("B006_B008.py"))] #[test_case(Rule::FunctionUsesLoopVariable, Path::new("B023.py"))] #[test_case(Rule::GetAttrWithConstant, Path::new("B009_B010.py"))] #[test_case(Rule::JumpStatementInFinally, Path::new("B012.py"))] #[test_case(Rule::LoopVariableOverridesIterator, Path::new("B020.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_1.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_2.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_3.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_4.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_5.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_6.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_7.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_8.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_9.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_B008.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_1.pyi"))] #[test_case(Rule::NoExplicitStacklevel, Path::new("B028.py"))] #[test_case(Rule::RaiseLiteral, Path::new("B016.py"))] #[test_case(Rule::RaiseWithoutFromInsideExcept, Path::new("B904.py"))] #[test_case(Rule::ReSubPositionalArgs, Path::new("B034.py"))] #[test_case(Rule::RedundantTupleInExceptionHandler, Path::new("B013.py"))] #[test_case(Rule::ReuseOfGroupbyGenerator, Path::new("B031.py"))] #[test_case(Rule::SetAttrWithConstant, Path::new("B009_B010.py"))] #[test_case(Rule::StarArgUnpackingAfterKeywordArg, Path::new("B026.py"))] #[test_case(Rule::StaticKeyDictComprehension, Path::new("B035.py"))] #[test_case(Rule::StripWithMultiCharacters, Path::new("B005.py"))] #[test_case(Rule::UnaryPrefixIncrementDecrement, Path::new("B002.py"))] #[test_case(Rule::UnintentionalTypeAnnotation, Path::new("B032.py"))] #[test_case(Rule::UnreliableCallableCheck, Path::new("B004.py"))] #[test_case(Rule::UnusedLoopControlVariable, Path::new("B007.py"))] #[test_case(Rule::UselessComparison, Path::new("B015.ipynb"))] #[test_case(Rule::UselessComparison, Path::new("B015.py"))] #[test_case(Rule::UselessContextlibSuppress, Path::new("B022.py"))] #[test_case(Rule::UselessExpression, Path::new("B018.ipynb"))] #[test_case(Rule::UselessExpression, Path::new("B018.py"))] #[test_case(Rule::ReturnInGenerator, Path::new("B901.py"))] #[test_case(Rule::LoopIteratorMutation, Path::new("B909.py"))] #[test_case(Rule::MutableContextvarDefault, Path::new("B039.py"))] #[test_case(Rule::BatchedWithoutExplicitStrict, Path::new("B911.py"))] fn rules(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy()); let diagnostics = test_path( Path::new("flake8_bugbear").join(path).as_path(), &LinterSettings::for_rule(rule_code), )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test_case(Rule::MapWithoutExplicitStrict, Path::new("B912.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_1.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_2.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_3.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_4.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_5.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_6.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_7.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_8.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_9.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_B008.py"))] #[test_case(Rule::MutableArgumentDefault, Path::new("B006_1.pyi"))] fn preview_rules(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!( "preview__{}_{}", rule_code.noqa_code(), path.to_string_lossy() ); let diagnostics = test_path( Path::new("flake8_bugbear").join(path).as_path(), &LinterSettings { preview: PreviewMode::Enabled, unresolved_target_version: PythonVersion::PY314.into(), ..LinterSettings::for_rule(rule_code) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test_case( Rule::ClassAsDataStructure, Path::new("class_as_data_structure.py"), PythonVersion::PY39 )] #[test_case( Rule::MapWithoutExplicitStrict, Path::new("B912.py"), PythonVersion::PY313 )] fn rules_with_target_version( rule_code: Rule, path: &Path, target_version: PythonVersion, ) -> Result<()> { let snapshot = format!( "{}_py{}{}_{}", rule_code.noqa_code(), target_version.major, target_version.minor, path.to_string_lossy(), ); let diagnostics = test_path( Path::new("flake8_bugbear").join(path).as_path(), &LinterSettings { unresolved_target_version: target_version.into(), ..LinterSettings::for_rule(rule_code) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test] fn zip_without_explicit_strict() -> Result<()> { let snapshot = "B905.py"; let diagnostics = test_path( Path::new("flake8_bugbear").join(snapshot).as_path(), &LinterSettings::for_rule(Rule::ZipWithoutExplicitStrict), )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test] fn extend_immutable_calls_arg_annotation() -> Result<()> { let snapshot = "extend_immutable_calls_arg_annotation".to_string(); let diagnostics = test_path( Path::new("flake8_bugbear/B006_extended.py"), &LinterSettings { flake8_bugbear: super::settings::Settings { extend_immutable_calls: vec![ "custom.ImmutableTypeA".to_string(), "custom.ImmutableTypeB".to_string(), ], }, ..LinterSettings::for_rule(Rule::MutableArgumentDefault) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test] fn extend_immutable_calls_arg_default() -> Result<()> { let snapshot = "extend_immutable_calls_arg_default".to_string(); let diagnostics = test_path( Path::new("flake8_bugbear/B008_extended.py"), &LinterSettings { flake8_bugbear: super::settings::Settings { extend_immutable_calls: vec![ "fastapi.Depends".to_string(), "fastapi.Query".to_string(), "custom.ImmutableTypeA".to_string(), "B008_extended.Class".to_string(), ], }, ..LinterSettings::for_rule(Rule::FunctionCallInDefaultArgument) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test] fn extend_mutable_contextvar_default() -> Result<()> { let snapshot = "extend_mutable_contextvar_default".to_string(); let diagnostics = test_path( Path::new("flake8_bugbear/B039_extended.py"), &LinterSettings { flake8_bugbear: super::settings::Settings { extend_immutable_calls: vec!["fastapi.Query".to_string()], }, ..LinterSettings::for_rule(Rule::MutableContextvarDefault) }, )?; 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_bugbear/rules/class_as_data_structure.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/class_as_data_structure.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_python_semantic::analyze::visibility::{self, Visibility::Public}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use ruff_python_ast::PythonVersion; /// ## What it does /// Checks for classes that only have a public `__init__` method, /// without base classes and decorators. /// /// ## Why is this bad? /// Classes with just an `__init__` are possibly better off /// being a dataclass or a namedtuple, which have less boilerplate. /// /// ## Example /// ```python /// class Point: /// def __init__(self, x: float, y: float): /// self.x = x /// self.y = y /// ``` /// /// Use instead: /// ```python /// from dataclasses import dataclass /// /// /// @dataclass /// class Point: /// x: float /// y: float /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.9.0")] pub(crate) struct ClassAsDataStructure; impl Violation for ClassAsDataStructure { #[derive_message_formats] fn message(&self) -> String { "Class could be dataclass or namedtuple".to_string() } } /// B903 pub(crate) fn class_as_data_structure(checker: &Checker, class_def: &ast::StmtClassDef) { // skip stub files if checker.source_type.is_stub() { return; } // allow decorated classes if !class_def.decorator_list.is_empty() { return; } // allow classes with base classes if class_def.arguments.is_some() { return; } let mut public_methods = 0; let mut has_dunder_init = false; for stmt in &class_def.body { if public_methods > 1 && has_dunder_init { // we're good to break here break; } match stmt { ast::Stmt::FunctionDef(func_def) => { if !has_dunder_init && func_def.name.to_string() == "__init__" && func_def .parameters .iter() // skip `self` .skip(1) .all(|param| param.annotation().is_some() && !param.is_variadic()) && (func_def.parameters.kwonlyargs.is_empty() || checker.target_version() >= PythonVersion::PY310) // `__init__` should not have complicated logic in it // only assignments && func_def .body .iter() .all(is_simple_assignment_to_attribute) { has_dunder_init = true; } if matches!(visibility::method_visibility(func_def), Public) { public_methods += 1; } } // Ignore class variables ast::Stmt::Assign(_) | ast::Stmt::AnnAssign(_) | // and expressions (e.g. string literals) ast::Stmt::Expr(_) => {} _ => { // Bail for anything else - e.g. nested classes // or conditional methods. return; } } } if has_dunder_init && public_methods == 1 { checker.report_diagnostic(ClassAsDataStructure, class_def.range()); } } // Checks whether a statement is a, possibly augmented, // assignment of a name to an attribute. fn is_simple_assignment_to_attribute(stmt: &ast::Stmt) -> bool { match stmt { ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { let [target] = targets.as_slice() else { return false; }; target.is_attribute_expr() && value.is_name_expr() } ast::Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => { target.is_attribute_expr() && value.as_ref().is_some_and(|val| val.is_name_expr()) } _ => 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/flake8_bugbear/rules/re_sub_positional_args.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/re_sub_positional_args.rs
use std::fmt; use ruff_python_ast::{self as ast}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::Modules; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for calls to `re.sub`, `re.subn`, and `re.split` that pass `count`, /// `maxsplit`, or `flags` as positional arguments. /// /// ## Why is this bad? /// Passing `count`, `maxsplit`, or `flags` as positional arguments to /// `re.sub`, `re.subn`, or `re.split` can lead to confusion, as most methods in /// the `re` module accept `flags` as the third positional argument, while /// `re.sub`, `re.subn`, and `re.split` have different signatures. /// /// Instead, pass `count`, `maxsplit`, and `flags` as keyword arguments. /// /// ## Example /// ```python /// import re /// /// re.split("pattern", "replacement", 1) /// ``` /// /// Use instead: /// ```python /// import re /// /// re.split("pattern", "replacement", maxsplit=1) /// ``` /// /// ## References /// - [Python documentation: `re.sub`](https://docs.python.org/3/library/re.html#re.sub) /// - [Python documentation: `re.subn`](https://docs.python.org/3/library/re.html#re.subn) /// - [Python documentation: `re.split`](https://docs.python.org/3/library/re.html#re.split) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.278")] pub(crate) struct ReSubPositionalArgs { method: Method, } impl Violation for ReSubPositionalArgs { #[derive_message_formats] fn message(&self) -> String { let ReSubPositionalArgs { method } = self; let param_name = method.param_name(); format!( "`{method}` should pass `{param_name}` and `flags` as keyword arguments to avoid confusion due to unintuitive argument positions" ) } } /// B034 pub(crate) fn re_sub_positional_args(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::RE) { return; } let Some(method) = checker .semantic() .resolve_qualified_name(&call.func) .and_then(|qualified_name| match qualified_name.segments() { ["re", "sub"] => Some(Method::Sub), ["re", "subn"] => Some(Method::Subn), ["re", "split"] => Some(Method::Split), _ => None, }) else { return; }; if call.arguments.args.len() > method.num_args() { checker.report_diagnostic(ReSubPositionalArgs { method }, call.range()); } } #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum Method { Sub, Subn, Split, } impl fmt::Display for Method { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { Self::Sub => fmt.write_str("re.sub"), Self::Subn => fmt.write_str("re.subn"), Self::Split => fmt.write_str("re.split"), } } } impl Method { const fn param_name(self) -> &'static str { match self { Self::Sub => "count", Self::Subn => "count", Self::Split => "maxsplit", } } const fn num_args(self) -> usize { match self { Self::Sub => 3, Self::Subn => 3, Self::Split => 2, } } }
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_bugbear/rules/reuse_of_groupby_generator.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/reuse_of_groupby_generator.rs
use ruff_python_ast::{self as ast, Comprehension, Expr, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::{self, Visitor}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for multiple usage of the generator returned from /// `itertools.groupby()`. /// /// ## Why is this bad? /// Using the generator more than once will do nothing on the second usage. /// If that data is needed later, it should be stored as a list. /// /// ## Example: /// ```python /// import itertools /// /// for name, group in itertools.groupby(data): /// for _ in range(5): /// do_something_with_the_group(group) /// ``` /// /// Use instead: /// ```python /// import itertools /// /// for name, group in itertools.groupby(data): /// values = list(group) /// for _ in range(5): /// do_something_with_the_group(values) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.260")] pub(crate) struct ReuseOfGroupbyGenerator; impl Violation for ReuseOfGroupbyGenerator { #[derive_message_formats] fn message(&self) -> String { "Using the generator returned from `itertools.groupby()` more than once will do nothing on the second usage".to_string() } } /// A [`Visitor`] that collects all the usage of `group_name` in the body of /// a `for` loop. struct GroupNameFinder<'a> { /// Variable name for the group. group_name: &'a str, /// Number of times the `group_name` variable was seen during the visit. usage_count: u32, /// A flag indicating that the visitor is inside a nested `for` or `while` /// loop or inside a `dict`, `list` or `set` comprehension. nested: bool, /// A flag indicating that the `group_name` variable has been overridden /// during the visit. overridden: bool, /// A stack of counters where each counter is itself a list of usage count. /// This is used specifically for mutually exclusive statements such as an /// `if` or `match`. /// /// The stack element represents an entire `if` or `match` statement while /// the number inside the element represents the usage count for one of /// the branches of the statement. The order of the count corresponds the /// branch order. counter_stack: Vec<Vec<u32>>, /// A list of reused expressions. exprs: Vec<&'a Expr>, } impl<'a> GroupNameFinder<'a> { fn new(group_name: &'a str) -> Self { GroupNameFinder { group_name, usage_count: 0, nested: false, overridden: false, counter_stack: Vec::new(), exprs: Vec::new(), } } fn name_matches(&self, expr: &Expr) -> bool { if let Expr::Name(ast::ExprName { id, .. }) = expr { id == self.group_name } else { false } } /// Increment the usage count for the group name by the given value. /// If we're in one of the branches of a mutually exclusive statement, /// then increment the count for that branch. Otherwise, increment the /// global count. fn increment_usage_count(&mut self, value: u32) { if let Some(last) = self.counter_stack.last_mut() { *last.last_mut().unwrap() += value; } else { self.usage_count += value; } } /// Reset the usage count for the group name by the given value. /// This function is called when there is a `continue`, `break`, or `return` statement. fn reset_usage_count(&mut self) { if let Some(last) = self.counter_stack.last_mut() { *last.last_mut().unwrap() = 0; } else { self.usage_count = 0; } } } impl<'a> Visitor<'a> for GroupNameFinder<'a> { fn visit_stmt(&mut self, stmt: &'a Stmt) { if self.overridden { return; } match stmt { Stmt::For(ast::StmtFor { target, iter, body, .. }) => { if self.name_matches(target) { self.overridden = true; } else { if self.name_matches(iter) { self.increment_usage_count(1); // This could happen when the group is being looped // over multiple times: // for item in group: // ... // // # Group is being reused here // for item in group: // ... if self.usage_count > 1 { self.exprs.push(iter); } } self.nested = true; visitor::walk_body(self, body); self.nested = false; } } Stmt::While(ast::StmtWhile { body, .. }) => { self.nested = true; visitor::walk_body(self, body); self.nested = false; } Stmt::If(ast::StmtIf { test, body, elif_else_clauses, range: _, node_index: _, }) => { // base if plus branches let mut if_stack = Vec::with_capacity(1 + elif_else_clauses.len()); // Initialize the vector with the count for the if branch. if_stack.push(0); self.counter_stack.push(if_stack); self.visit_expr(test); self.visit_body(body); for clause in elif_else_clauses { self.counter_stack.last_mut().unwrap().push(0); self.visit_elif_else_clause(clause); } if let Some(last) = self.counter_stack.pop() { // This is the max number of group usage from all the // branches of this `if` statement. let max_count = last.into_iter().max().unwrap_or(0); self.increment_usage_count(max_count); } } Stmt::Match(ast::StmtMatch { subject, cases, range: _, node_index: _, }) => { self.counter_stack.push(Vec::with_capacity(cases.len())); self.visit_expr(subject); for match_case in cases { self.counter_stack.last_mut().unwrap().push(0); self.visit_match_case(match_case); } if let Some(last) = self.counter_stack.pop() { // This is the max number of group usage from all the // branches of this `match` statement. let max_count = last.into_iter().max().unwrap_or(0); self.increment_usage_count(max_count); } } Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { if targets.iter().any(|target| self.name_matches(target)) { self.overridden = true; } else { self.visit_expr(value); } } Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => { if self.name_matches(target) { self.overridden = true; } else if let Some(expr) = value { self.visit_expr(expr); } } Stmt::Continue(_) | Stmt::Break(_) => { self.reset_usage_count(); } Stmt::Return(ast::StmtReturn { value, range: _, node_index: _, }) => { if let Some(expr) = value { self.visit_expr(expr); } self.reset_usage_count(); } _ => visitor::walk_stmt(self, stmt), } } fn visit_comprehension(&mut self, comprehension: &'a Comprehension) { if self.name_matches(&comprehension.target) { self.overridden = true; } if self.overridden { return; } if self.name_matches(&comprehension.iter) { self.increment_usage_count(1); if self.usage_count > 1 { self.exprs.push(&comprehension.iter); } } } fn visit_expr(&mut self, expr: &'a Expr) { if let Expr::Named(ast::ExprNamed { target, .. }) = expr { if self.name_matches(target) { self.overridden = true; } } if self.overridden { return; } match expr { Expr::ListComp(ast::ExprListComp { elt, generators, range: _, node_index: _, }) | Expr::SetComp(ast::ExprSetComp { elt, generators, range: _, node_index: _, }) => { for comprehension in generators { self.visit_comprehension(comprehension); } if !self.overridden { self.nested = true; visitor::walk_expr(self, elt); self.nested = false; } } Expr::DictComp(ast::ExprDictComp { key, value, generators, range: _, node_index: _, }) => { for comprehension in generators { self.visit_comprehension(comprehension); } if !self.overridden { self.nested = true; visitor::walk_expr(self, key); visitor::walk_expr(self, value); self.nested = false; } } _ => { if self.name_matches(expr) { self.increment_usage_count(1); let current_usage_count = self.usage_count + self .counter_stack .iter() .map(|count| count.last().unwrap_or(&0)) .sum::<u32>(); // For nested loops, the variable usage could be once but the // loop makes it being used multiple times. if self.nested || current_usage_count > 1 { self.exprs.push(expr); } } else { visitor::walk_expr(self, expr); } } } } } /// B031 pub(crate) fn reuse_of_groupby_generator( checker: &Checker, target: &Expr, body: &[Stmt], iter: &Expr, ) { let Expr::Call(ast::ExprCall { func, .. }) = &iter else { return; }; let Expr::Tuple(tuple) = target else { // Ignore any `groupby()` invocation that isn't unpacked return; }; if tuple.len() != 2 { return; } // We have an invocation of groupby which is a simple unpacking let Expr::Name(ast::ExprName { id: group_name, .. }) = &tuple.elts[1] else { return; }; // Check if the function call is `itertools.groupby` if !checker .semantic() .resolve_qualified_name(func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["itertools", "groupby"])) { return; } let mut finder = GroupNameFinder::new(group_name); for stmt in body { finder.visit_stmt(stmt); } for expr in finder.exprs { checker.report_diagnostic(ReuseOfGroupbyGenerator, 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/flake8_bugbear/rules/assignment_to_os_environ.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/assignment_to_os_environ.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; /// ## What it does /// Checks for assignments to `os.environ`. /// /// ## Why is this bad? /// In Python, `os.environ` is a mapping that represents the environment of the /// current process. /// /// However, reassigning to `os.environ` does not clear the environment. Instead, /// it merely updates the `os.environ` for the current process. This can lead to /// unexpected behavior, especially when running the program in a subprocess. /// /// Instead, use `os.environ.clear()` to clear the environment, or use the /// `env` argument of `subprocess.Popen` to pass a custom environment to /// a subprocess. /// /// ## Example /// ```python /// import os /// /// os.environ = {"foo": "bar"} /// ``` /// /// Use instead: /// ```python /// import os /// /// os.environ.clear() /// os.environ["foo"] = "bar" /// ``` /// /// ## References /// - [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ) /// - [Python documentation: `subprocess.Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.102")] pub(crate) struct AssignmentToOsEnviron; impl Violation for AssignmentToOsEnviron { #[derive_message_formats] fn message(&self) -> String { "Assigning to `os.environ` doesn't clear the environment".to_string() } } /// B003 pub(crate) fn assignment_to_os_environ(checker: &Checker, targets: &[Expr]) { let [target] = targets else { return; }; let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = target else { return; }; if attr != "environ" { return; } let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else { return; }; if id != "os" { return; } checker.report_diagnostic(AssignmentToOsEnviron, target.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/flake8_bugbear/rules/mutable_contextvar_default.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_contextvar_default.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_subscript; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::Modules; use ruff_python_semantic::analyze::typing::{is_immutable_func, is_mutable_expr, is_mutable_func}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of mutable objects as `ContextVar` defaults. /// /// ## Why is this bad? /// /// The `ContextVar` default is evaluated once, when the `ContextVar` is defined. /// /// The same mutable object is then shared across all `.get()` method calls to /// the `ContextVar`. If the object is modified, those modifications will persist /// across calls, which can lead to unexpected behavior. /// /// Instead, prefer to use immutable data structures. Alternatively, take /// `None` as a default, and initialize a new mutable object inside for each /// call using the `.set()` method. /// /// Types outside the standard library can be marked as immutable with the /// [`lint.flake8-bugbear.extend-immutable-calls`] configuration option. /// /// ## Example /// ```python /// from contextvars import ContextVar /// /// /// cv: ContextVar[list] = ContextVar("cv", default=[]) /// ``` /// /// Use instead: /// ```python /// from contextvars import ContextVar /// /// /// cv: ContextVar[list | None] = ContextVar("cv", default=None) /// /// ... /// /// if cv.get() is None: /// cv.set([]) /// ``` /// /// ## Options /// - `lint.flake8-bugbear.extend-immutable-calls` /// /// ## References /// - [Python documentation: `contextvars` — Context Variables](https://docs.python.org/3/library/contextvars.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.8.0")] pub(crate) struct MutableContextvarDefault; impl Violation for MutableContextvarDefault { #[derive_message_formats] fn message(&self) -> String { "Do not use mutable data structures for `ContextVar` defaults".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with `None`; initialize with `.set()``".to_string()) } } /// B039 pub(crate) fn mutable_contextvar_default(checker: &Checker, call: &ast::ExprCall) { if !checker.semantic().seen_module(Modules::CONTEXTVARS) { return; } let Some(default) = call .arguments .find_keyword("default") .map(|keyword| &keyword.value) else { return; }; let extend_immutable_calls: Vec<QualifiedName> = checker .settings() .flake8_bugbear .extend_immutable_calls .iter() .map(|target| QualifiedName::from_dotted_name(target)) .collect(); if (is_mutable_expr(default, checker.semantic()) || matches!( default, Expr::Call(ast::ExprCall { func, .. }) if !is_mutable_func(func, checker.semantic()) && !is_immutable_func(func, checker.semantic(), &extend_immutable_calls))) && checker .semantic() .resolve_qualified_name(map_subscript(&call.func)) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["contextvars", "ContextVar"]) }) { checker.report_diagnostic(MutableContextvarDefault, default.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/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, ExceptHandler, Expr}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits::pad; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for single-element tuples in exception handlers (e.g., /// `except (ValueError,):`). /// /// Note: Single-element tuples consisting of a starred expression /// are allowed. /// /// ## Why is this bad? /// A tuple with a single element can be more concisely and idiomatically /// expressed as a single value. /// /// ## Example /// ```python /// try: /// ... /// except (ValueError,): /// ... /// ``` /// /// Use instead: /// ```python /// try: /// ... /// except ValueError: /// ... /// ``` /// /// ## References /// - [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.89")] pub(crate) struct RedundantTupleInExceptionHandler { name: String, } impl AlwaysFixableViolation for RedundantTupleInExceptionHandler { #[derive_message_formats] fn message(&self) -> String { "A length-one tuple literal is redundant in exception handlers".to_string() } fn fix_title(&self) -> String { let RedundantTupleInExceptionHandler { name } = self; format!("Replace with `except {name}`") } } /// B013 pub(crate) fn redundant_tuple_in_exception_handler(checker: &Checker, handlers: &[ExceptHandler]) { for handler in handlers { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_: Some(type_), .. }) = handler else { continue; }; let Expr::Tuple(ast::ExprTuple { elts, .. }) = type_.as_ref() else { continue; }; let [elt] = elts.as_slice() else { continue; }; // It is not safe to replace a single-element // tuple consisting of a starred expression // by the unstarred expression because the unstarred // expression can be any iterable whereas `except` must // be followed by a literal or a tuple. For example: // ```python // except (*[ValueError,FileNotFoundError],) // ``` if elt.is_starred_expr() { continue; } let mut diagnostic = checker.report_diagnostic( RedundantTupleInExceptionHandler { name: checker.generator().expr(elt), }, type_.range(), ); // If there's no space between the `except` and the tuple, we need to insert a space, // as in: // ```python // except(ValueError,): // ``` // Otherwise, the output will be invalid syntax, since we're removing a set of // parentheses. diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( pad( checker.generator().expr(elt), type_.range(), checker.locator(), ), type_.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/flake8_bugbear/rules/return_in_generator.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/return_in_generator.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor::{Visitor, walk_expr, walk_stmt}; use ruff_python_ast::{self as ast, Expr, Stmt, StmtFunctionDef}; use ruff_text_size::TextRange; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `return {value}` statements in functions that also contain `yield` /// or `yield from` statements. /// /// ## Why is this bad? /// Using `return {value}` in a generator function was syntactically invalid in /// Python 2. In Python 3 `return {value}` _can_ be used in a generator; however, /// the combination of `yield` and `return` can lead to confusing behavior, as /// the `return` statement will cause the generator to raise `StopIteration` /// with the value provided, rather than returning the value to the caller. /// /// For example, given: /// ```python /// from collections.abc import Iterable /// from pathlib import Path /// /// /// def get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]: /// dir_path = Path(".") /// if file_types is None: /// return dir_path.glob("*") /// /// for file_type in file_types: /// yield from dir_path.glob(f"*.{file_type}") /// ``` /// /// Readers might assume that `get_file_paths()` would return an iterable of /// `Path` objects in the directory; in reality, though, `list(get_file_paths())` /// evaluates to `[]`, since the `return` statement causes the generator to raise /// `StopIteration` with the value `dir_path.glob("*")`: /// /// ```shell /// >>> list(get_file_paths(file_types=["cfg", "toml"])) /// [PosixPath('setup.cfg'), PosixPath('pyproject.toml')] /// >>> list(get_file_paths()) /// [] /// ``` /// /// For intentional uses of `return` in a generator, consider suppressing this /// diagnostic. /// /// ## Example /// ```python /// from collections.abc import Iterable /// from pathlib import Path /// /// /// def get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]: /// dir_path = Path(".") /// if file_types is None: /// return dir_path.glob("*") /// /// for file_type in file_types: /// yield from dir_path.glob(f"*.{file_type}") /// ``` /// /// Use instead: /// /// ```python /// from collections.abc import Iterable /// from pathlib import Path /// /// /// def get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]: /// dir_path = Path(".") /// if file_types is None: /// yield from dir_path.glob("*") /// else: /// for file_type in file_types: /// yield from dir_path.glob(f"*.{file_type}") /// ``` #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.4.8")] pub(crate) struct ReturnInGenerator; impl Violation for ReturnInGenerator { #[derive_message_formats] fn message(&self) -> String { "Using `yield` and `return {value}` in a generator function can lead to confusing behavior" .to_string() } } /// B901 pub(crate) fn return_in_generator(checker: &Checker, function_def: &StmtFunctionDef) { if function_def.name.id == "__await__" { return; } // Async functions are flagged by the `ReturnInGenerator` semantic syntax error. if function_def.is_async { return; } let mut visitor = ReturnInGeneratorVisitor::default(); visitor.visit_body(&function_def.body); if visitor.has_yield { if let Some(return_) = visitor.return_ { checker.report_diagnostic(ReturnInGenerator, return_); } } } #[derive(Default)] struct ReturnInGeneratorVisitor { return_: Option<TextRange>, has_yield: bool, } impl Visitor<'_> for ReturnInGeneratorVisitor { fn visit_stmt(&mut self, stmt: &Stmt) { match stmt { Stmt::FunctionDef(_) => { // Do not recurse into nested functions; they're evaluated separately. } Stmt::Return(ast::StmtReturn { value: Some(_), range, node_index: _, }) => { self.return_ = Some(*range); walk_stmt(self, stmt); } _ => walk_stmt(self, stmt), } } fn visit_expr(&mut self, expr: &Expr) { match expr { Expr::Lambda(_) => {} Expr::Yield(_) | Expr::YieldFrom(_) => { self.has_yield = true; } _ => 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/flake8_bugbear/rules/loop_iterator_mutation.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_iterator_mutation.rs
use std::collections::HashMap; use std::fmt::Debug; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::comparable::ComparableExpr; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::{ Expr, ExprAttribute, ExprCall, ExprSubscript, ExprTuple, Stmt, StmtAssign, StmtAugAssign, StmtDelete, StmtFor, StmtIf, visitor::{self, Visitor}, }; use ruff_text_size::TextRange; use crate::Violation; use crate::checkers::ast::Checker; use crate::fix::snippet::SourceCodeSnippet; /// ## What it does /// Checks for mutations to an iterable during a loop iteration. /// /// ## Why is this bad? /// When iterating over an iterable, mutating the iterable can lead to unexpected /// behavior, like skipping elements or infinite loops. /// /// ## Example /// ```python /// items = [1, 2, 3] /// /// for item in items: /// print(item) /// /// # Create an infinite loop by appending to the list. /// items.append(item) /// ``` /// /// ## References /// - [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#typesseq-mutable) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "v0.3.7")] pub(crate) struct LoopIteratorMutation { name: Option<SourceCodeSnippet>, } impl Violation for LoopIteratorMutation { #[derive_message_formats] fn message(&self) -> String { if let Some(name) = self.name.as_ref().and_then(SourceCodeSnippet::full_display) { format!("Mutation to loop iterable `{name}` during iteration") } else { "Mutation to loop iterable during iteration".to_string() } } } /// B909 pub(crate) fn loop_iterator_mutation(checker: &Checker, stmt_for: &StmtFor) { let StmtFor { target, iter, body, orelse: _, is_async: _, range: _, node_index: _, } = stmt_for; let (index, target, iter) = match iter.as_ref() { Expr::Name(_) | Expr::Attribute(_) => { // Ex) Given, `for item in items:`, `item` is the index and `items` is the iterable. (&**target, &**target, &**iter) } Expr::Call(ExprCall { func, arguments, .. }) => { // Ex) Given `for i, item in enumerate(items):`, `i` is the index and `items` is the // iterable. if checker.semantic().match_builtin_expr(func, "enumerate") { // Ex) `items` let Some(iter) = arguments.args.first() else { return; }; let Expr::Tuple(ExprTuple { elts, .. }) = &**target else { return; }; let [index, target] = elts.as_slice() else { return; }; // Ex) `i` (index, target, iter) } else { return; } } _ => { return; } }; // Collect mutations to the iterable. let mutations = { let mut visitor = LoopMutationsVisitor::new(iter, target, index); visitor.visit_body(body); visitor.mutations }; // Create a diagnostic for each mutation. for mutation in mutations.values().flatten() { let name = UnqualifiedName::from_expr(iter) .map(|name| name.to_string()) .map(SourceCodeSnippet::new); checker.report_diagnostic(LoopIteratorMutation { name }, *mutation); } } /// Returns `true` if the method mutates when called on an iterator. fn is_mutating_function(function_name: &str) -> bool { matches!( function_name, "append" | "sort" | "reverse" | "remove" | "clear" | "extend" | "insert" | "pop" | "popitem" | "setdefault" | "update" | "intersection_update" | "difference_update" | "symmetric_difference_update" | "add" | "discard" ) } /// A visitor to collect mutations to a variable in a loop. #[derive(Debug, Clone)] struct LoopMutationsVisitor<'a> { iter: &'a Expr, target: &'a Expr, index: &'a Expr, mutations: HashMap<u32, Vec<TextRange>>, branches: Vec<u32>, branch: u32, } impl<'a> LoopMutationsVisitor<'a> { /// Initialize the visitor. fn new(iter: &'a Expr, target: &'a Expr, index: &'a Expr) -> Self { Self { iter, target, index, mutations: HashMap::new(), branches: vec![0], branch: 0, } } /// Register a mutation. fn add_mutation(&mut self, range: TextRange) { self.mutations.entry(self.branch).or_default().push(range); } /// Handle, e.g., `del items[0]`. fn handle_delete(&mut self, range: TextRange, targets: &[Expr]) { for target in targets { if let Expr::Subscript(ExprSubscript { range: _, node_index: _, value, slice: _, ctx: _, }) = target { // Find, e.g., `del items[0]`. if ComparableExpr::from(self.iter) == ComparableExpr::from(value) { self.add_mutation(range); } } } } /// Handle, e.g., `items[0] = 1`. fn handle_assign(&mut self, range: TextRange, targets: &[Expr]) { for target in targets { if let Expr::Subscript(ExprSubscript { range: _, node_index: _, value, slice, ctx: _, }) = target { // Find, e.g., `items[0] = 1`. if ComparableExpr::from(self.iter) == ComparableExpr::from(value) { // But allow, e.g., `for item in items: items[item] = 1`. if ComparableExpr::from(self.index) != ComparableExpr::from(slice) && ComparableExpr::from(self.target) != ComparableExpr::from(slice) { self.add_mutation(range); } } } } } /// Handle, e.g., `items += [1]`. fn handle_aug_assign(&mut self, range: TextRange, target: &Expr) { if ComparableExpr::from(self.iter) == ComparableExpr::from(target) { self.add_mutation(range); } } /// Handle, e.g., `items.append(1)`. fn handle_call(&mut self, func: &Expr) { if let Expr::Attribute(ExprAttribute { range, node_index: _, value, attr, ctx: _, }) = func { if is_mutating_function(attr.as_str()) { // Find, e.g., `items.remove(1)`. if ComparableExpr::from(self.iter) == ComparableExpr::from(value) { self.add_mutation(*range); } } } } } /// `Visitor` to collect all used identifiers in a statement. impl<'a> Visitor<'a> for LoopMutationsVisitor<'a> { fn visit_stmt(&mut self, stmt: &'a Stmt) { match stmt { // Ex) `del items[0]` Stmt::Delete(StmtDelete { range, targets, node_index: _, }) => { self.handle_delete(*range, targets); visitor::walk_stmt(self, stmt); } // Ex) `items[0] = 1` Stmt::Assign(StmtAssign { range, targets, .. }) => { self.handle_assign(*range, targets); visitor::walk_stmt(self, stmt); } // Ex) `items += [1]` Stmt::AugAssign(StmtAugAssign { range, target, .. }) => { self.handle_aug_assign(*range, target); visitor::walk_stmt(self, stmt); } // Ex) `if True: items.append(1)` Stmt::If(StmtIf { test, body, elif_else_clauses, .. }) => { // Handle the `if` branch. self.branch += 1; self.branches.push(self.branch); self.visit_expr(test); self.visit_body(body); self.branches.pop(); // Handle the `elif` and `else` branches. for clause in elif_else_clauses { self.branch += 1; self.branches.push(self.branch); if let Some(test) = &clause.test { self.visit_expr(test); } self.visit_body(&clause.body); self.branches.pop(); } } // On break, clear the mutations for the current branch. Stmt::Break(_) | Stmt::Return(_) => { if let Some(mutations) = self.mutations.get_mut(&self.branch) { mutations.clear(); } } // Avoid recursion for class and function definitions. Stmt::ClassDef(_) | Stmt::FunctionDef(_) => {} // Default case. _ => { visitor::walk_stmt(self, stmt); } } } fn visit_expr(&mut self, expr: &'a Expr) { // Ex) `items.append(1)` if let Expr::Call(ExprCall { func, .. }) = expr { self.handle_call(func); } 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/flake8_bugbear/rules/no_explicit_stacklevel.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/no_explicit_stacklevel.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; use crate::{AlwaysFixableViolation, Fix}; use crate::{checkers::ast::Checker, fix::edits::add_argument}; /// ## What it does /// Checks for `warnings.warn` calls without an explicit `stacklevel` keyword /// argument. /// /// ## Why is this bad? /// The `warnings.warn` method uses a `stacklevel` of 1 by default, which /// will output a stack frame of the line on which the "warn" method /// is called. Setting it to a higher number will output a stack frame /// from higher up the stack. /// /// It's recommended to use a `stacklevel` of 2 or higher, to give the caller /// more context about the warning. /// /// ## Example /// ```python /// import warnings /// /// warnings.warn("This is a warning") /// ``` /// /// Use instead: /// ```python /// import warnings /// /// warnings.warn("This is a warning", stacklevel=2) /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe because it changes /// the behavior of the code. Moreover, the fix will assign /// a stacklevel of 2, while the user may wish to assign a /// higher stacklevel to address the diagnostic. /// /// ## References /// - [Python documentation: `warnings.warn`](https://docs.python.org/3/library/warnings.html#warnings.warn) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.257")] pub(crate) struct NoExplicitStacklevel; impl AlwaysFixableViolation for NoExplicitStacklevel { #[derive_message_formats] fn message(&self) -> String { "No explicit `stacklevel` keyword argument found".to_string() } fn fix_title(&self) -> String { "Set `stacklevel=2`".to_string() } } /// B028 pub(crate) fn no_explicit_stacklevel(checker: &Checker, call: &ast::ExprCall) { if !checker .semantic() .resolve_qualified_name(&call.func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["warnings", "warn"])) { return; } // When prefixes are supplied, stacklevel is implicitly overridden to be `max(2, stacklevel)`. // // Signature as of Python 3.13 (https://docs.python.org/3/library/warnings.html#warnings.warn) // ```text // 0 1 2 3 4 // warnings.warn(message, category=None, stacklevel=1, source=None, *, skip_file_prefixes=()) // ``` if call .arguments .find_argument_value("stacklevel", 2) .is_some() || is_skip_file_prefixes_param_set(&call.arguments) || call .arguments .args .iter() .any(ruff_python_ast::Expr::is_starred_expr) || call .arguments .keywords .iter() .any(|keyword| keyword.arg.is_none()) { return; } let mut diagnostic = checker.report_diagnostic(NoExplicitStacklevel, call.func.range()); let edit = add_argument("stacklevel=2", &call.arguments, checker.tokens()); diagnostic.set_fix(Fix::unsafe_edit(edit)); } /// Returns `true` if `skip_file_prefixes` is set to its non-default value. /// The default value of `skip_file_prefixes` is an empty tuple. fn is_skip_file_prefixes_param_set(arguments: &ast::Arguments) -> bool { arguments .find_keyword("skip_file_prefixes") .is_some_and(|keyword| match &keyword.value { Expr::Tuple(tuple) => !tuple.elts.is_empty(), _ => 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/flake8_bugbear/rules/assert_false.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_false.rs
use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Stmt}; use ruff_text_size::{Ranged, TextRange}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_const_false; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for uses of `assert False`. /// /// ## Why is this bad? /// Python removes `assert` statements when running in optimized mode /// (`python -O`), making `assert False` an unreliable means of /// raising an `AssertionError`. /// /// Instead, raise an `AssertionError` directly. /// /// ## Example /// ```python /// assert False /// ``` /// /// Use instead: /// ```python /// raise AssertionError /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe, as changing an `assert` to a /// `raise` will change the behavior of your program when running in /// optimized mode (`python -O`). /// /// ## References /// - [Python documentation: `assert`](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.67")] pub(crate) struct AssertFalse; impl AlwaysFixableViolation for AssertFalse { #[derive_message_formats] fn message(&self) -> String { "Do not `assert False` (`python -O` removes these calls), raise `AssertionError()`" .to_string() } fn fix_title(&self) -> String { "Replace `assert False`".to_string() } } fn assertion_error(msg: Option<&Expr>) -> Stmt { Stmt::Raise(ast::StmtRaise { range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, exc: Some(Box::new(Expr::Call(ast::ExprCall { func: Box::new(Expr::Name(ast::ExprName { id: "AssertionError".into(), ctx: ExprContext::Load, range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, })), arguments: Arguments { args: if let Some(msg) = msg { Box::from([msg.clone()]) } else { Box::from([]) }, keywords: Box::from([]), range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, }, range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, }))), cause: None, }) } /// B011 pub(crate) fn assert_false(checker: &Checker, stmt: &Stmt, test: &Expr, msg: Option<&Expr>) { if !is_const_false(test) { return; } let mut diagnostic = checker.report_diagnostic(AssertFalse, test.range()); diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( checker.generator().stmt(&assertion_error(msg)), 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/flake8_bugbear/rules/setattr_with_constant.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/setattr_with_constant.rs
use ruff_python_ast::{self as ast, Expr, ExprContext, Identifier, Stmt}; use ruff_text_size::{Ranged, TextRange}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_codegen::Generator; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; use unicode_normalization::UnicodeNormalization; use crate::checkers::ast::Checker; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for uses of `setattr` that take a constant attribute value as an /// argument (e.g., `setattr(obj, "foo", 42)`). /// /// ## Why is this bad? /// `setattr` is used to set attributes dynamically. If the attribute is /// defined as a constant, it is no safer than a typical property access. When /// possible, prefer property access over `setattr` calls, as the former is /// more concise and idiomatic. /// /// ## Example /// ```python /// setattr(obj, "foo", 42) /// ``` /// /// Use instead: /// ```python /// obj.foo = 42 /// ``` /// /// ## Fix safety /// The fix is marked as unsafe for attribute names that are not in NFKC (Normalization Form KC) /// normalization. Python normalizes identifiers using NFKC when using attribute access syntax /// (e.g., `obj.attr = value`), but does not normalize string arguments passed to `setattr`. /// Rewriting `setattr(obj, "ſ", 1)` to `obj.ſ = 1` would be interpreted as `obj.s = 1` at /// runtime, changing behavior. /// /// For example, the long s character `"ſ"` normalizes to `"s"` under NFKC, so: /// ```python /// # This creates an attribute with the exact name "ſ" /// setattr(obj, "ſ", 1) /// getattr(obj, "ſ") # Returns 1 /// /// # But this would normalize to "s" and set a different attribute /// obj.ſ = 1 # This is interpreted as obj.s = 1, not obj.ſ = 1 /// ``` /// /// ## References /// - [Python documentation: `setattr`](https://docs.python.org/3/library/functions.html#setattr) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.111")] pub(crate) struct SetAttrWithConstant; impl AlwaysFixableViolation for SetAttrWithConstant { #[derive_message_formats] fn message(&self) -> String { "Do not call `setattr` with a constant attribute value. It is not any safer than \ normal property access." .to_string() } fn fix_title(&self) -> String { "Replace `setattr` with assignment".to_string() } } fn assignment(obj: &Expr, name: &str, value: &Expr, generator: Generator) -> String { let stmt = Stmt::Assign(ast::StmtAssign { targets: vec![Expr::Attribute(ast::ExprAttribute { value: Box::new(obj.clone()), attr: Identifier::new(name.to_string(), TextRange::default()), ctx: ExprContext::Store, range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, })], value: Box::new(value.clone()), range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, }); generator.stmt(&stmt) } /// B010 pub(crate) fn setattr_with_constant(checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr]) { let [obj, name, value] = args else { return; }; if obj.is_starred_expr() { return; } let Expr::StringLiteral(ast::ExprStringLiteral { value: name, .. }) = name else { return; }; if !is_identifier(name.to_str()) { return; } // Ignore if the attribute name is `__debug__`. Assigning to the `__debug__` property is a // `SyntaxError`. if name.to_str() == "__debug__" { return; } if is_mangled_private(name.to_str()) { return; } if !checker.semantic().match_builtin_expr(func, "setattr") { return; } // Mark fixes as unsafe for non-NFKC attribute names. Python normalizes identifiers using NFKC, so using // attribute syntax (e.g., `obj.attr = value`) would normalize the name and potentially change // program behavior. let attr_name = name.to_str(); let is_unsafe = attr_name.nfkc().collect::<String>() != attr_name; // We can only replace a `setattr` call (which is an `Expr`) with an assignment // (which is a `Stmt`) if the `Expr` is already being used as a `Stmt` // (i.e., it's directly within an `Stmt::Expr`). if let Stmt::Expr(ast::StmtExpr { value: child, range: _, node_index: _, }) = checker.semantic().current_statement() { if expr == child.as_ref() { let mut diagnostic = checker.report_diagnostic(SetAttrWithConstant, expr.range()); let edit = Edit::range_replacement( assignment(obj, name.to_str(), value, checker.generator()), expr.range(), ); let fix = if is_unsafe { Fix::unsafe_edit(edit) } else { Fix::safe_edit(edit) }; diagnostic.set_fix(fix); } } }
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_bugbear/rules/jump_statement_in_finally.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/jump_statement_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 `break`, `continue`, and `return` statements in `finally` /// blocks. /// /// ## Why is this bad? /// The use of `break`, `continue`, and `return` statements in `finally` blocks /// can cause exceptions to be silenced. /// /// `finally` blocks execute regardless of whether an exception is raised. If a /// `break`, `continue`, or `return` statement is reached in a `finally` block, /// any exception raised in the `try` or `except` blocks will be silenced. /// /// ## Example /// ```python /// def speed(distance, time): /// try: /// return distance / time /// except ZeroDivisionError: /// raise ValueError("Time cannot be zero") /// finally: /// return 299792458 # `ValueError` is silenced /// ``` /// /// Use instead: /// ```python /// def speed(distance, time): /// try: /// return distance / time /// except ZeroDivisionError: /// raise ValueError("Time cannot be zero") /// ``` /// /// ## References /// - [Python documentation: The `try` statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct JumpStatementInFinally { name: String, } impl Violation for JumpStatementInFinally { #[derive_message_formats] fn message(&self) -> String { let JumpStatementInFinally { name } = self; format!("`{name}` inside `finally` blocks cause exceptions to be silenced") } } fn walk_stmt(checker: &Checker, body: &[Stmt], f: fn(&Stmt) -> bool) { for stmt in body { if f(stmt) { checker.report_diagnostic( JumpStatementInFinally { name: match stmt { Stmt::Break(_) => "break", Stmt::Continue(_) => "continue", Stmt::Return(_) => "return", _ => unreachable!("Expected Stmt::Break | Stmt::Continue | Stmt::Return"), } .to_owned(), }, stmt.range(), ); } match stmt { Stmt::While(ast::StmtWhile { body, .. }) | Stmt::For(ast::StmtFor { body, .. }) => { walk_stmt(checker, body, Stmt::is_return_stmt); } Stmt::If(ast::StmtIf { body, .. }) | Stmt::Try(ast::StmtTry { body, .. }) | Stmt::With(ast::StmtWith { body, .. }) => { walk_stmt(checker, body, f); } Stmt::Match(ast::StmtMatch { cases, .. }) => { for case in cases { walk_stmt(checker, &case.body, f); } } _ => {} } } } /// B012 pub(crate) fn jump_statement_in_finally(checker: &Checker, finalbody: &[Stmt]) { walk_stmt(checker, finalbody, |stmt| { matches!(stmt, Stmt::Break(_) | Stmt::Continue(_) | Stmt::Return(_)) }); }
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_bugbear/rules/static_key_dict_comprehension.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/static_key_dict_comprehension.rs
use rustc_hash::FxHashMap; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::StoredNameFinder; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::fix::snippet::SourceCodeSnippet; /// ## What it does /// Checks for dictionary comprehensions that use a static key, like a string /// literal or a variable defined outside the comprehension. /// /// ## Why is this bad? /// Using a static key (like a string literal) in a dictionary comprehension /// is usually a mistake, as it will result in a dictionary with only one key, /// despite the comprehension iterating over multiple values. /// /// ## Example /// ```python /// data = ["some", "Data"] /// {"key": value.upper() for value in data} /// ``` /// /// Use instead: /// ```python /// data = ["some", "Data"] /// {value: value.upper() for value in data} /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.2.0")] pub(crate) struct StaticKeyDictComprehension { key: SourceCodeSnippet, } impl Violation for StaticKeyDictComprehension { #[derive_message_formats] fn message(&self) -> String { if let Some(key) = self.key.full_display() { format!("Dictionary comprehension uses static key: `{key}`") } else { "Dictionary comprehension uses static key".to_string() } } } /// B035, RUF011 pub(crate) fn static_key_dict_comprehension(checker: &Checker, dict_comp: &ast::ExprDictComp) { // Collect the bound names in the comprehension's generators. let names = { let mut visitor = StoredNameFinder::default(); for generator in &dict_comp.generators { visitor.visit_comprehension(generator); } visitor.names }; if is_constant(&dict_comp.key, &names) { checker.report_diagnostic( StaticKeyDictComprehension { key: SourceCodeSnippet::from_str(checker.locator().slice(dict_comp.key.as_ref())), }, dict_comp.key.range(), ); } } /// Returns `true` if the given expression is a constant in the context of the dictionary /// comprehension. fn is_constant(key: &Expr, names: &FxHashMap<&str, &ast::ExprName>) -> bool { match key { Expr::Tuple(tuple) => tuple.iter().all(|elem| is_constant(elem, names)), Expr::Name(ast::ExprName { id, .. }) => !names.contains_key(id.as_str()), Expr::Attribute(ast::ExprAttribute { value, .. }) => is_constant(value, names), Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => { is_constant(value, names) && is_constant(slice, names) } Expr::BinOp(ast::ExprBinOp { left, right, .. }) => { is_constant(left, names) && is_constant(right, names) } Expr::BoolOp(ast::ExprBoolOp { values, .. }) => { values.iter().all(|value| is_constant(value, names)) } Expr::UnaryOp(ast::ExprUnaryOp { operand, .. }) => is_constant(operand, names), expr if expr.is_literal_expr() => true, _ => 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/flake8_bugbear/rules/abstract_base_class.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/abstract_base_class.rs
use ruff_python_ast::{self as ast, Arguments, Expr, Keyword, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::visibility::{is_abstract, is_overload}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::registry::Rule; /// ## What it does /// Checks for abstract classes without abstract methods or properties. /// Annotated but unassigned class variables are regarded as abstract. /// /// ## Why is this bad? /// Abstract base classes are used to define interfaces. If an abstract base /// class has no abstract methods or properties, you may have forgotten /// to add an abstract method or property to the class, /// or omitted an `@abstractmethod` decorator. /// /// If the class is _not_ meant to be used as an interface, consider removing /// the `ABC` base class from the class definition. /// /// ## Example /// ```python /// from abc import ABC /// from typing import ClassVar /// /// /// class Foo(ABC): /// class_var: ClassVar[str] = "assigned" /// /// def method(self): /// bar() /// ``` /// /// Use instead: /// ```python /// from abc import ABC, abstractmethod /// from typing import ClassVar /// /// /// class Foo(ABC): /// class_var: ClassVar[str] # unassigned /// /// @abstractmethod /// def method(self): /// bar() /// ``` /// /// ## References /// - [Python documentation: `abc`](https://docs.python.org/3/library/abc.html) /// - [Python documentation: `typing.ClassVar`](https://docs.python.org/3/library/typing.html#typing.ClassVar) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.118")] pub(crate) struct AbstractBaseClassWithoutAbstractMethod { name: String, } impl Violation for AbstractBaseClassWithoutAbstractMethod { #[derive_message_formats] fn message(&self) -> String { let AbstractBaseClassWithoutAbstractMethod { name } = self; format!("`{name}` is an abstract base class, but it has no abstract methods or properties") } } /// ## What it does /// Checks for empty methods in abstract base classes without an abstract /// decorator. /// /// ## Why is this bad? /// Empty methods in abstract base classes without an abstract decorator may be /// be indicative of a mistake. If the method is meant to be abstract, add an /// `@abstractmethod` decorator to the method. /// /// ## Example /// /// ```python /// from abc import ABC /// /// /// class Foo(ABC): /// def method(self): ... /// ``` /// /// Use instead: /// /// ```python /// from abc import ABC, abstractmethod /// /// /// class Foo(ABC): /// @abstractmethod /// def method(self): ... /// ``` /// /// ## References /// - [Python documentation: `abc`](https://docs.python.org/3/library/abc.html) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.118")] pub(crate) struct EmptyMethodWithoutAbstractDecorator { name: String, } impl Violation for EmptyMethodWithoutAbstractDecorator { #[derive_message_formats] fn message(&self) -> String { let EmptyMethodWithoutAbstractDecorator { name } = self; format!( "`{name}` is an empty method in an abstract base class, but has no abstract decorator" ) } } fn is_abc_class(bases: &[Expr], keywords: &[Keyword], semantic: &SemanticModel) -> bool { keywords.iter().any(|keyword| { keyword.arg.as_ref().is_some_and(|arg| arg == "metaclass") && semantic .resolve_qualified_name(&keyword.value) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["abc", "ABCMeta"]) }) }) || bases.iter().any(|base| { semantic .resolve_qualified_name(base) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["abc", "ABC"])) }) } fn is_empty_body(body: &[Stmt]) -> bool { body.iter().all(|stmt| match stmt { Stmt::Pass(_) => true, Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) => { matches!( value.as_ref(), Expr::StringLiteral(_) | Expr::EllipsisLiteral(_) ) } _ => false, }) } /// B024 /// B027 pub(crate) fn abstract_base_class( checker: &Checker, stmt: &Stmt, name: &str, arguments: Option<&Arguments>, body: &[Stmt], ) { let Some(Arguments { args, keywords, .. }) = arguments else { return; }; if args.len() + keywords.len() != 1 { return; } if !is_abc_class(args, keywords, checker.semantic()) { return; } let mut has_abstract_method = false; for stmt in body { // https://github.com/PyCQA/flake8-bugbear/issues/293 // If an ABC declares an attribute by providing a type annotation // but does not actually assign a value for that attribute, // assume it is intended to be an "abstract attribute" if matches!( stmt, Stmt::AnnAssign(ast::StmtAnnAssign { value: None, .. }) ) { has_abstract_method = true; continue; } let Stmt::FunctionDef(ast::StmtFunctionDef { decorator_list, body, name: method_name, .. }) = stmt else { continue; }; let has_abstract_decorator = is_abstract(decorator_list, checker.semantic()); has_abstract_method |= has_abstract_decorator; if !checker.is_rule_enabled(Rule::EmptyMethodWithoutAbstractDecorator) { continue; } if !has_abstract_decorator && is_empty_body(body) && !is_overload(decorator_list, checker.semantic()) { checker.report_diagnostic( EmptyMethodWithoutAbstractDecorator { name: format!("{name}.{method_name}"), }, stmt.range(), ); } } if checker.is_rule_enabled(Rule::AbstractBaseClassWithoutAbstractMethod) { if !has_abstract_method { checker.report_diagnostic( AbstractBaseClassWithoutAbstractMethod { name: name.to_string(), }, 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/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs
use ruff_python_ast::{Expr, Keyword}; 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 function calls that use star-argument unpacking after providing a /// keyword argument /// /// ## Why is this bad? /// In Python, you can use star-argument unpacking to pass a list or tuple of /// arguments to a function. /// /// Providing a star-argument after a keyword argument can lead to confusing /// behavior, and is only supported for backwards compatibility. /// /// ## Example /// ```python /// def foo(x, y, z): /// return x, y, z /// /// /// foo(1, 2, 3) # (1, 2, 3) /// foo(1, *[2, 3]) # (1, 2, 3) /// # foo(x=1, *[2, 3]) # TypeError /// # foo(y=2, *[1, 3]) # TypeError /// foo(z=3, *[1, 2]) # (1, 2, 3) # No error, but confusing! /// ``` /// /// Use instead: /// ```python /// def foo(x, y, z): /// return x, y, z /// /// /// foo(1, 2, 3) # (1, 2, 3) /// foo(x=1, y=2, z=3) # (1, 2, 3) /// foo(*[1, 2, 3]) # (1, 2, 3) /// foo(*[1, 2], 3) # (1, 2, 3) /// ``` /// /// ## References /// - [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls) /// - [Disallow iterable argument unpacking after a keyword argument?](https://github.com/python/cpython/issues/82741) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.109")] pub(crate) struct StarArgUnpackingAfterKeywordArg; impl Violation for StarArgUnpackingAfterKeywordArg { #[derive_message_formats] fn message(&self) -> String { "Star-arg unpacking after a keyword argument is strongly discouraged".to_string() } } /// B026 pub(crate) fn star_arg_unpacking_after_keyword_arg( checker: &Checker, args: &[Expr], keywords: &[Keyword], ) { let Some(keyword) = keywords.first() else { return; }; for arg in args { let Expr::Starred(_) = arg else { continue; }; if arg.start() <= keyword.start() { continue; } checker.report_diagnostic(StarArgUnpackingAfterKeywordArg, 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/flake8_bugbear/rules/getattr_with_constant.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/getattr_with_constant.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private}; use ruff_source_file::LineRanges; use ruff_text_size::Ranged; use unicode_normalization::UnicodeNormalization; use crate::checkers::ast::Checker; use crate::fix::edits::pad; use crate::{AlwaysFixableViolation, Edit, Fix}; /// ## What it does /// Checks for uses of `getattr` that take a constant attribute value as an /// argument (e.g., `getattr(obj, "foo")`). /// /// ## Why is this bad? /// `getattr` is used to access attributes dynamically. If the attribute is /// defined as a constant, it is no safer than a typical property access. When /// possible, prefer property access over `getattr` calls, as the former is /// more concise and idiomatic. /// /// /// ## Example /// ```python /// getattr(obj, "foo") /// ``` /// /// Use instead: /// ```python /// obj.foo /// ``` /// /// ## Fix safety /// The fix is marked as unsafe for attribute names that are not in NFKC (Normalization Form KC) /// normalization. Python normalizes identifiers using NFKC when using attribute access syntax /// (e.g., `obj.attr`), but does not normalize string arguments passed to `getattr`. Rewriting /// `getattr(obj, "ſ")` to `obj.ſ` would be interpreted as `obj.s` at runtime, changing behavior. /// /// For example, the long s character `"ſ"` normalizes to `"s"` under NFKC, so: /// ```python /// # This accesses an attribute with the exact name "ſ" (if it exists) /// value = getattr(obj, "ſ") /// /// # But this would normalize to "s" and access a different attribute /// obj.ſ # This is interpreted as obj.s, not obj.ſ /// ``` /// /// ## References /// - [Python documentation: `getattr`](https://docs.python.org/3/library/functions.html#getattr) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.110")] pub(crate) struct GetAttrWithConstant; impl AlwaysFixableViolation for GetAttrWithConstant { #[derive_message_formats] fn message(&self) -> String { "Do not call `getattr` with a constant attribute value. It is not any safer than \ normal property access." .to_string() } fn fix_title(&self) -> String { "Replace `getattr` with attribute access".to_string() } } /// B009 pub(crate) fn getattr_with_constant(checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr]) { let [obj, arg] = args else { return; }; if obj.is_starred_expr() { return; } let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = arg else { return; }; if !is_identifier(value.to_str()) { return; } if is_mangled_private(value.to_str()) { return; } if !checker.semantic().match_builtin_expr(func, "getattr") { return; } // Mark fixes as unsafe for non-NFKC attribute names. Python normalizes identifiers using NFKC, so using // attribute syntax (e.g., `obj.attr`) would normalize the name and potentially change // program behavior. let attr_name = value.to_str(); let is_unsafe = attr_name.nfkc().collect::<String>() != attr_name; let mut diagnostic = checker.report_diagnostic(GetAttrWithConstant, expr.range()); let edit = Edit::range_replacement( pad( if matches!( obj, Expr::Name(_) | Expr::Attribute(_) | Expr::Subscript(_) | Expr::Call(_) ) && !checker.locator().contains_line_break(obj.range()) { format!("{}.{}", checker.locator().slice(obj), value) } else { // Defensively parenthesize any other expressions. For example, attribute accesses // on `int` literals must be parenthesized, e.g., `getattr(1, "real")` becomes // `(1).real`. The same is true for named expressions and others. format!("({}).{}", checker.locator().slice(obj), value) }, expr.range(), checker.locator(), ), expr.range(), ); let fix = if is_unsafe { Fix::unsafe_edit(edit) } else { Fix::safe_edit(edit) }; diagnostic.set_fix(fix); }
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_bugbear/rules/useless_comparison.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_comparison.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Expr, Stmt}; use ruff_python_semantic::ScopeKind; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bugbear::helpers::at_last_top_level_expression_in_cell; /// ## What it does /// Checks for useless comparisons. /// /// ## Why is this bad? /// Useless comparisons have no effect on the program, and are often included /// by mistake. If the comparison is intended to enforce an invariant, prepend /// the comparison with an `assert`. Otherwise, remove it entirely. /// /// ## Example /// ```python /// foo == bar /// ``` /// /// Use instead: /// ```python /// assert foo == bar, "`foo` and `bar` should be equal." /// ``` /// /// ## Notebook behavior /// For Jupyter Notebooks, this rule is not applied to the last top-level expression in a cell. /// This is because it's common to have a notebook cell that ends with an expression, /// which will result in the `repr` of the evaluated expression being printed as the cell's output. /// /// ## References /// - [Python documentation: `assert` statement](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.102")] pub(crate) struct UselessComparison { at: ComparisonLocationAt, } impl Violation for UselessComparison { #[derive_message_formats] fn message(&self) -> String { match self.at { ComparisonLocationAt::MiddleBody => { "Pointless comparison. Did you mean to assign a value? \ Otherwise, prepend `assert` or remove it." .to_string() } ComparisonLocationAt::EndOfFunction => { "Pointless comparison at end of function scope. Did you mean \ to return the expression result?" .to_string() } } } } /// B015 pub(crate) fn useless_comparison(checker: &Checker, expr: &Expr) { if expr.is_compare_expr() { let semantic = checker.semantic(); if checker.source_type.is_ipynb() && at_last_top_level_expression_in_cell( semantic, checker.locator(), checker.cell_offsets(), ) { return; } if let ScopeKind::Function(func_def) = semantic.current_scope().kind { if func_def .body .last() .and_then(Stmt::as_expr_stmt) .is_some_and(|last_stmt| &*last_stmt.value == expr) { checker.report_diagnostic( UselessComparison { at: ComparisonLocationAt::EndOfFunction, }, expr.range(), ); return; } } checker.report_diagnostic( UselessComparison { at: ComparisonLocationAt::MiddleBody, }, expr.range(), ); } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum ComparisonLocationAt { MiddleBody, EndOfFunction, }
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_bugbear/rules/assert_raises_exception.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/assert_raises_exception.rs
use std::fmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Arguments, Expr, WithItem}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `assertRaises` and `pytest.raises` context managers that catch /// `Exception` or `BaseException`. /// /// ## Why is this bad? /// These forms catch every `Exception`, which can lead to tests passing even /// if, e.g., the code under consideration raises a `SyntaxError` or /// `IndentationError`. /// /// Either assert for a more specific exception (builtin or custom), or use /// `assertRaisesRegex` or `pytest.raises(..., match=<REGEX>)` respectively. /// /// ## Example /// ```python /// self.assertRaises(Exception, foo) /// ``` /// /// Use instead: /// ```python /// self.assertRaises(SomeSpecificException, foo) /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.83")] pub(crate) struct AssertRaisesException { exception: ExceptionKind, } impl Violation for AssertRaisesException { #[derive_message_formats] fn message(&self) -> String { let AssertRaisesException { exception } = self; format!("Do not assert blind exception: `{exception}`") } } #[derive(Debug, PartialEq, Eq)] enum ExceptionKind { BaseException, Exception, } impl fmt::Display for ExceptionKind { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { ExceptionKind::BaseException => fmt.write_str("BaseException"), ExceptionKind::Exception => fmt.write_str("Exception"), } } } fn detect_blind_exception( semantic: &ruff_python_semantic::SemanticModel<'_>, func: &Expr, arguments: &Arguments, ) -> Option<ExceptionKind> { let is_assert_raises = matches!( func, &Expr::Attribute(ast::ExprAttribute { ref attr, .. }) if attr.as_str() == "assertRaises" ); let is_pytest_raises = semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pytest", "raises"])); if !(is_assert_raises || is_pytest_raises) { return None; } if is_pytest_raises { if arguments.find_keyword("match").is_some() { return None; } if arguments .find_positional(1) .is_some_and(|arg| matches!(arg, Expr::StringLiteral(_) | Expr::BytesLiteral(_))) { return None; } } let exception_argument_name = if is_pytest_raises { "expected_exception" } else { "exception" }; let exception_expr = arguments.find_argument_value(exception_argument_name, 0)?; let builtin_symbol = semantic.resolve_builtin_symbol(exception_expr)?; match builtin_symbol { "Exception" => Some(ExceptionKind::Exception), "BaseException" => Some(ExceptionKind::BaseException), _ => None, } } /// B017 pub(crate) fn assert_raises_exception(checker: &Checker, items: &[WithItem]) { for item in items { let Expr::Call(ast::ExprCall { func, arguments, range: _, node_index: _, }) = &item.context_expr else { continue; }; if item.optional_vars.is_some() { continue; } if let Some(exception) = detect_blind_exception(checker.semantic(), func.as_ref(), arguments) { checker.report_diagnostic(AssertRaisesException { exception }, item.range()); } } } /// B017 (call form) pub(crate) fn assert_raises_exception_call( checker: &Checker, ast::ExprCall { func, arguments, range, node_index: _, }: &ast::ExprCall, ) { let semantic = checker.semantic(); if arguments.args.len() < 2 && arguments.find_argument("func", 1).is_none() { return; } if let Some(exception) = detect_blind_exception(semantic, func.as_ref(), arguments) { checker.report_diagnostic(AssertRaisesException { exception }, *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/flake8_bugbear/rules/strip_with_multi_characters.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs
use itertools::Itertools; 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; /// ## What it does /// Checks for uses of multi-character strings in `.strip()`, `.lstrip()`, and /// `.rstrip()` calls. /// /// ## Why is this bad? /// All characters in the call to `.strip()`, `.lstrip()`, or `.rstrip()` are /// removed from the leading and trailing ends of the string. If the string /// contains multiple characters, the reader may be misled into thinking that /// a prefix or suffix is being removed, rather than a set of characters. /// /// 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. /// /// ## Known problems /// As a heuristic, this rule only flags multi-character strings that contain /// duplicate characters. This allows usages like `.strip("xyz")`, which /// removes all occurrences of the characters `x`, `y`, and `z` from the /// leading and trailing ends of the string, but not `.strip("foo")`. /// /// The use of unique, multi-character strings may be intentional and /// consistent with the intent of `.strip()`, `.lstrip()`, or `.rstrip()`, /// while the use of duplicate-character strings is very likely to be a /// mistake. /// /// ## Example /// ```python /// "text.txt".strip(".txt") # "e" /// ``` /// /// Use instead: /// ```python /// "text.txt".removesuffix(".txt") # "text" /// ``` /// /// ## References /// - [Python documentation: `str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.106")] pub(crate) struct StripWithMultiCharacters; impl Violation for StripWithMultiCharacters { #[derive_message_formats] fn message(&self) -> String { "Using `.strip()` with multi-character strings is misleading".to_string() } } /// B005 pub(crate) fn strip_with_multi_characters( checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr], ) { let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func else { return; }; if !matches!(attr.as_str(), "strip" | "lstrip" | "rstrip") { return; } let [Expr::StringLiteral(ast::ExprStringLiteral { value, .. })] = args else { return; }; if value.chars().count() > 1 && !value.chars().all_unique() { checker.report_diagnostic(StripWithMultiCharacters, 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/flake8_bugbear/rules/zip_without_explicit_strict.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits::add_argument; use crate::rules::flake8_bugbear::helpers::any_infinite_iterables; use crate::{AlwaysFixableViolation, Applicability, Fix}; /// ## What it does /// Checks for `zip` calls without an explicit `strict` parameter when called with two or more iterables, or any starred argument. /// /// ## Why is this bad? /// By default, if the iterables passed to `zip` are of different lengths, the /// resulting iterator will be silently truncated to the length of the shortest /// iterable. This can lead to subtle bugs. /// /// Pass `strict=True` to raise a `ValueError` if the iterables are of /// non-uniform length. Alternatively, if the iterables are deliberately of /// different lengths, pass `strict=False` to make the intention explicit. /// /// ## Example /// ```python /// zip(a, b) /// ``` /// /// Use instead: /// ```python /// zip(a, b, strict=True) /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe. While adding `strict=False` preserves /// the runtime behavior, it can obscure situations where the iterables are of /// unequal length. Ruff prefers to alert users so they can choose the intended /// behavior themselves. /// /// ## References /// - [Python documentation: `zip`](https://docs.python.org/3/library/functions.html#zip) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.167")] pub(crate) struct ZipWithoutExplicitStrict; impl AlwaysFixableViolation for ZipWithoutExplicitStrict { #[derive_message_formats] fn message(&self) -> String { "`zip()` without an explicit `strict=` parameter".to_string() } fn fix_title(&self) -> String { "Add explicit value for parameter `strict=`".to_string() } } /// B905 pub(crate) fn zip_without_explicit_strict(checker: &Checker, call: &ast::ExprCall) { let semantic = checker.semantic(); if semantic.match_builtin_expr(&call.func, "zip") && call.arguments.find_keyword("strict").is_none() && ( // at least 2 iterables call.arguments.args.len() >= 2 // or a starred argument || call.arguments.args.iter().any(ast::Expr::is_starred_expr) ) && !any_infinite_iterables(call.arguments.args.iter(), semantic) { checker .report_diagnostic(ZipWithoutExplicitStrict, call.range()) .set_fix(Fix::applicable_edit( add_argument("strict=False", &call.arguments, checker.tokens()), Applicability::Unsafe, )); } }
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_bugbear/rules/mutable_argument_default.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/mutable_argument_default.rs
use std::fmt::Write; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::is_docstring_stmt; use ruff_python_ast::name::QualifiedName; use ruff_python_ast::token::parenthesized_range; use ruff_python_ast::{self as ast, Expr, ParameterWithDefault}; use ruff_python_semantic::SemanticModel; use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::typing::{is_immutable_annotation, is_mutable_expr}; use ruff_python_trivia::{indentation_at_offset, textwrap}; use ruff_source_file::LineRanges; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::preview::{ is_b006_check_guaranteed_mutable_expr_enabled, is_b006_unsafe_fix_preserve_assignment_expr_enabled, }; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for uses of mutable objects as function argument defaults. /// /// ## Why is this bad? /// Function defaults are evaluated once, when the function is defined. /// /// The same mutable object is then shared across all calls to the function. /// If the object is modified, those modifications will persist across calls, /// which can lead to unexpected behavior. /// /// Instead, prefer to use immutable data structures, or take `None` as a /// default, and initialize a new mutable object inside the function body /// for each call. /// /// Arguments with immutable type annotations will be ignored by this rule. /// Types outside of the standard library can be marked as immutable with the /// [`lint.flake8-bugbear.extend-immutable-calls`] configuration option. /// /// ## Known problems /// Mutable argument defaults can be used intentionally to cache computation /// results. Replacing the default with `None` or an immutable data structure /// does not work for such usages. Instead, prefer the `@functools.lru_cache` /// decorator from the standard library. /// /// ## Example /// ```python /// def add_to_list(item, some_list=[]): /// some_list.append(item) /// return some_list /// /// /// l1 = add_to_list(0) # [0] /// l2 = add_to_list(1) # [0, 1] /// ``` /// /// Use instead: /// ```python /// def add_to_list(item, some_list=None): /// if some_list is None: /// some_list = [] /// some_list.append(item) /// return some_list /// /// /// l1 = add_to_list(0) # [0] /// l2 = add_to_list(1) # [1] /// ``` /// /// ## Options /// - `lint.flake8-bugbear.extend-immutable-calls` /// /// ## Fix safety /// /// This fix is marked as unsafe because it replaces the mutable default with `None` /// and initializes it in the function body, which may not be what the user intended, /// as described above. /// /// ## References /// - [Python documentation: Default Argument Values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.92")] pub(crate) struct MutableArgumentDefault; impl Violation for MutableArgumentDefault { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Do not use mutable data structures for argument defaults".to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with `None`; initialize within function".to_string()) } } /// B006 pub(crate) fn mutable_argument_default(checker: &Checker, function_def: &ast::StmtFunctionDef) { // Skip stub files if checker.source_type.is_stub() { return; } for parameter in function_def.parameters.iter_non_variadic_params() { let Some(default) = parameter.default() else { continue; }; let extend_immutable_calls: Vec<QualifiedName> = checker .settings() .flake8_bugbear .extend_immutable_calls .iter() .map(|target| QualifiedName::from_dotted_name(target)) .collect(); let is_mut_expr = if is_b006_check_guaranteed_mutable_expr_enabled(checker.settings()) { is_guaranteed_mutable_expr(default, checker.semantic()) } else { is_mutable_expr(default, checker.semantic()) }; if is_mut_expr && !parameter.annotation().is_some_and(|expr| { is_immutable_annotation(expr, checker.semantic(), extend_immutable_calls.as_slice()) }) { let mut diagnostic = checker.report_diagnostic(MutableArgumentDefault, default.range()); // If the function body is on the same line as the function def, do not fix if let Some(fix) = move_initialization(function_def, parameter, default, checker) { diagnostic.set_fix(fix); } } } } /// Returns `true` if the expression is guaranteed to create a mutable object. fn is_guaranteed_mutable_expr(expr: &Expr, semantic: &SemanticModel) -> bool { match expr { Expr::Generator(_) => true, Expr::Tuple(ast::ExprTuple { elts, .. }) => { elts.iter().any(|e| is_guaranteed_mutable_expr(e, semantic)) } Expr::Named(ast::ExprNamed { value, .. }) => is_guaranteed_mutable_expr(value, semantic), _ => is_mutable_expr(expr, semantic), } } /// Generate a [`Fix`] to move a mutable argument default initialization /// into the function body. fn move_initialization( function_def: &ast::StmtFunctionDef, parameter: &ParameterWithDefault, default: &Expr, checker: &Checker, ) -> Option<Fix> { let indexer = checker.indexer(); let locator = checker.locator(); let stylist = checker.stylist(); let mut body = function_def.body.iter().peekable(); // Avoid attempting to fix single-line functions. let statement = body.peek()?; if indexer.preceded_by_multi_statement_line(statement, locator.contents()) { return None; } let range = match parenthesized_range(default.into(), parameter.into(), checker.tokens()) { Some(range) => range, None => default.range(), }; // Set the default argument value to `None`. let default_edit = Edit::range_replacement("None".to_string(), range); // If the function is a stub, this is the only necessary edit. if is_stub(function_def, checker.semantic()) { return Some(Fix::unsafe_edit(default_edit)); } // Add an `if`, to set the argument to its original value if still `None`. let mut content = String::new(); let _ = write!(&mut content, "if {} is None:", parameter.parameter.name()); content.push_str(stylist.line_ending().as_str()); content.push_str(stylist.indentation()); if is_b006_unsafe_fix_preserve_assignment_expr_enabled(checker.settings()) { let _ = write!( &mut content, "{} = {}", parameter.parameter.name(), locator.slice( parenthesized_range(default.into(), parameter.into(), checker.tokens()) .unwrap_or(default.range()) ) ); } else { let _ = write!( &mut content, "{} = {}", parameter.name(), checker.generator().expr(default) ); } content.push_str(stylist.line_ending().as_str()); // Determine the indentation depth of the function body. let indentation = indentation_at_offset(statement.start(), locator.contents())?; // Indent the edit to match the body indentation. let mut content = textwrap::indent(&content, indentation).to_string(); // Find the position to insert the initialization after docstring and imports let mut pos = locator.line_start(statement.start()); while let Some(statement) = body.next() { // If the statement is a docstring or an import, insert _after_ it. if is_docstring_stmt(statement) || statement.is_import_stmt() || statement.is_import_from_stmt() { if let Some(next) = body.peek() { // If there's a second statement, insert _before_ it, but ensure this isn't a // multi-statement line. if indexer.in_multi_statement_line(statement, locator.contents()) { continue; } pos = locator.line_start(next.start()); } else if locator.full_line_end(statement.end()) == locator.text_len() { // If the statement is at the end of the file, without a trailing newline, insert // _after_ it with an extra newline. content = format!("{}{}", stylist.line_ending().as_str(), content); pos = locator.full_line_end(statement.end()); break; } else { // If this is the only statement, insert _after_ it. pos = locator.full_line_end(statement.end()); break; } } else { break; } } let initialization_edit = Edit::insertion(content, pos); Some(Fix::unsafe_edits(default_edit, [initialization_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/flake8_bugbear/rules/mod.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/mod.rs
pub(crate) use abstract_base_class::*; pub(crate) use assert_false::*; pub(crate) use assert_raises_exception::*; pub(crate) use assignment_to_os_environ::*; pub(crate) use batched_without_explicit_strict::*; pub(crate) use cached_instance_method::*; pub(crate) use class_as_data_structure::*; pub(crate) use duplicate_exceptions::*; pub(crate) use duplicate_value::*; pub(crate) use except_with_empty_tuple::*; pub(crate) use except_with_non_exception_classes::*; pub(crate) use f_string_docstring::*; pub(crate) use function_call_in_argument_default::*; pub(crate) use function_uses_loop_variable::*; pub(crate) use getattr_with_constant::*; pub(crate) use jump_statement_in_finally::*; pub(crate) use loop_iterator_mutation::*; pub(crate) use loop_variable_overrides_iterator::*; pub(crate) use map_without_explicit_strict::*; pub(crate) use mutable_argument_default::*; pub(crate) use mutable_contextvar_default::*; pub(crate) use no_explicit_stacklevel::*; pub(crate) use raise_literal::*; pub(crate) use raise_without_from_inside_except::*; pub(crate) use re_sub_positional_args::*; pub(crate) use redundant_tuple_in_exception_handler::*; pub(crate) use return_in_generator::*; pub(crate) use reuse_of_groupby_generator::*; pub(crate) use setattr_with_constant::*; pub(crate) use star_arg_unpacking_after_keyword_arg::*; pub(crate) use static_key_dict_comprehension::*; pub(crate) use strip_with_multi_characters::*; pub(crate) use unary_prefix_increment_decrement::*; pub(crate) use unintentional_type_annotation::*; pub(crate) use unreliable_callable_check::*; pub(crate) use unused_loop_control_variable::*; pub(crate) use useless_comparison::*; pub(crate) use useless_contextlib_suppress::*; pub(crate) use useless_expression::*; pub(crate) use zip_without_explicit_strict::*; mod abstract_base_class; mod assert_false; mod assert_raises_exception; mod assignment_to_os_environ; mod batched_without_explicit_strict; mod cached_instance_method; mod class_as_data_structure; mod duplicate_exceptions; mod duplicate_value; mod except_with_empty_tuple; mod except_with_non_exception_classes; mod f_string_docstring; mod function_call_in_argument_default; mod function_uses_loop_variable; mod getattr_with_constant; mod jump_statement_in_finally; mod loop_iterator_mutation; mod loop_variable_overrides_iterator; mod map_without_explicit_strict; mod mutable_argument_default; mod mutable_contextvar_default; mod no_explicit_stacklevel; mod raise_literal; mod raise_without_from_inside_except; mod re_sub_positional_args; mod redundant_tuple_in_exception_handler; mod return_in_generator; mod reuse_of_groupby_generator; mod setattr_with_constant; mod star_arg_unpacking_after_keyword_arg; mod static_key_dict_comprehension; mod strip_with_multi_characters; mod unary_prefix_increment_decrement; mod unintentional_type_annotation; mod unreliable_callable_check; mod unused_loop_control_variable; mod useless_comparison; mod useless_contextlib_suppress; mod useless_expression; mod zip_without_explicit_strict;
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_bugbear/rules/batched_without_explicit_strict.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/batched_without_explicit_strict.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::ExprCall; use ruff_python_ast::PythonVersion; use crate::checkers::ast::Checker; use crate::rules::flake8_bugbear::helpers::is_infinite_iterable; use crate::{FixAvailability, Violation}; /// ## What it does /// Checks for `itertools.batched` calls without an explicit `strict` parameter. /// /// ## Why is this bad? /// By default, if the length of the iterable is not divisible by /// the second argument to `itertools.batched`, the last batch /// will be shorter than the rest. /// /// In Python 3.13, a `strict` parameter was added which allows controlling if the batches must be of uniform length. /// Pass `strict=True` to raise a `ValueError` if the batches are of non-uniform length. /// Otherwise, pass `strict=False` to make the intention explicit. /// /// ## Example /// ```python /// import itertools /// /// itertools.batched(iterable, n) /// ``` /// /// Use instead if the batches must be of uniform length: /// ```python /// import itertools /// /// itertools.batched(iterable, n, strict=True) /// ``` /// /// Or if the batches can be of non-uniform length: /// ```python /// import itertools /// /// itertools.batched(iterable, n, strict=False) /// ``` /// /// ## Known deviations /// Unlike the upstream `B911`, this rule will not report infinite iterators /// (e.g., `itertools.cycle(...)`). /// /// ## Options /// - `target-version` /// /// ## References /// - [Python documentation: `batched`](https://docs.python.org/3/library/itertools.html#batched) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "0.10.0")] pub(crate) struct BatchedWithoutExplicitStrict; impl Violation for BatchedWithoutExplicitStrict { const FIX_AVAILABILITY: FixAvailability = FixAvailability::None; #[derive_message_formats] fn message(&self) -> String { "`itertools.batched()` without an explicit `strict` parameter".to_string() } fn fix_title(&self) -> Option<String> { Some("Add an explicit `strict` parameter".to_string()) } } /// B911 pub(crate) fn batched_without_explicit_strict(checker: &Checker, call: &ExprCall) { if checker.target_version() < PythonVersion::PY313 { return; } let semantic = checker.semantic(); let (func, arguments) = (&call.func, &call.arguments); let Some(qualified_name) = semantic.resolve_qualified_name(func) else { return; }; if !matches!(qualified_name.segments(), ["itertools", "batched"]) { return; } if arguments.find_keyword("strict").is_some() { return; } let Some(iterable) = arguments.find_positional(0) else { return; }; if is_infinite_iterable(iterable, semantic) { return; } checker.report_diagnostic(BatchedWithoutExplicitStrict, 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/flake8_bugbear/rules/function_uses_loop_variable.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::types::Node; use ruff_python_ast::visitor; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Comprehension, Expr, ExprContext, Stmt}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for function definitions that use a loop variable. /// /// ## Why is this bad? /// The loop variable is not bound in the function definition, so it will always /// have the value it had in the last iteration when the function is called. /// /// Instead, consider using a default argument to bind the loop variable at /// function definition time. Or, use `functools.partial`. /// /// ## Example /// ```python /// adders = [lambda x: x + i for i in range(3)] /// values = [adder(1) for adder in adders] # [3, 3, 3] /// ``` /// /// Use instead: /// ```python /// adders = [lambda x, i=i: x + i for i in range(3)] /// values = [adder(1) for adder in adders] # [1, 2, 3] /// ``` /// /// Or: /// ```python /// from functools import partial /// /// adders = [partial(lambda x, i: x + i, i=i) for i in range(3)] /// values = [adder(1) for adder in adders] # [1, 2, 3] /// ``` /// /// ## References /// - [The Hitchhiker's Guide to Python: Late Binding Closures](https://docs.python-guide.org/writing/gotchas/#late-binding-closures) /// - [Python documentation: `functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.139")] pub(crate) struct FunctionUsesLoopVariable { name: String, } impl Violation for FunctionUsesLoopVariable { #[derive_message_formats] fn message(&self) -> String { let FunctionUsesLoopVariable { name } = self; format!("Function definition does not bind loop variable `{name}`") } } #[derive(Default)] struct LoadedNamesVisitor<'a> { loaded: Vec<&'a ast::ExprName>, stored: Vec<&'a ast::ExprName>, } /// `Visitor` to collect all used identifiers in a statement. impl<'a> Visitor<'a> for LoadedNamesVisitor<'a> { fn visit_expr(&mut self, expr: &'a Expr) { match expr { Expr::Name(name) => match &name.ctx { ExprContext::Load => self.loaded.push(name), ExprContext::Store => self.stored.push(name), _ => {} }, _ => visitor::walk_expr(self, expr), } } } #[derive(Default)] struct SuspiciousVariablesVisitor<'a> { names: Vec<&'a ast::ExprName>, safe_functions: Vec<&'a Expr>, } /// `Visitor` to collect all suspicious variables (those referenced in /// functions, but not bound as arguments). impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> { fn visit_stmt(&mut self, stmt: &'a Stmt) { match stmt { Stmt::FunctionDef(ast::StmtFunctionDef { parameters, body, .. }) => { // Collect all loaded variable names. let mut visitor = LoadedNamesVisitor::default(); visitor.visit_body(body); // Treat any non-arguments as "suspicious". self.names .extend(visitor.loaded.into_iter().filter(|loaded| { if visitor.stored.iter().any(|stored| stored.id == loaded.id) { return false; } if parameters.includes(&loaded.id) { return false; } true })); return; } Stmt::Return(ast::StmtReturn { value: Some(value), range: _, node_index: _, }) => { // Mark `return lambda: x` as safe. if value.is_lambda_expr() { self.safe_functions.push(value); } } _ => {} } visitor::walk_stmt(self, stmt); } fn visit_expr(&mut self, expr: &'a Expr) { match expr { Expr::Call(ast::ExprCall { func, arguments, range: _, node_index: _, }) => { match func.as_ref() { Expr::Name(ast::ExprName { id, .. }) => { if matches!(id.as_str(), "filter" | "reduce" | "map") { for arg in &*arguments.args { if arg.is_lambda_expr() { self.safe_functions.push(arg); } } } } Expr::Attribute(ast::ExprAttribute { value, attr, .. }) => { if attr == "reduce" { if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() { if id == "functools" { for arg in &*arguments.args { if arg.is_lambda_expr() { self.safe_functions.push(arg); } } } } } } _ => {} } for keyword in &*arguments.keywords { if keyword.arg.as_ref().is_some_and(|arg| arg == "key") && keyword.value.is_lambda_expr() { self.safe_functions.push(&keyword.value); } } } Expr::Lambda(ast::ExprLambda { parameters, body, range: _, node_index: _, }) => { if !self.safe_functions.contains(&expr) { // Collect all loaded variable names. let mut visitor = LoadedNamesVisitor::default(); visitor.visit_expr(body); // Treat any non-arguments as "suspicious". self.names .extend(visitor.loaded.into_iter().filter(|loaded| { if visitor.stored.iter().any(|stored| stored.id == loaded.id) { return false; } if parameters .as_ref() .is_some_and(|parameters| parameters.includes(&loaded.id)) { return false; } true })); return; } } _ => {} } visitor::walk_expr(self, expr); } } #[derive(Default)] struct NamesFromAssignmentsVisitor<'a> { names: Vec<&'a str>, } /// `Visitor` to collect all names used in an assignment expression. impl<'a> Visitor<'a> for NamesFromAssignmentsVisitor<'a> { fn visit_expr(&mut self, expr: &'a Expr) { match expr { Expr::Name(ast::ExprName { id, .. }) => { self.names.push(id.as_str()); } Expr::Starred(ast::ExprStarred { value, .. }) => { self.visit_expr(value); } Expr::List(ast::ExprList { elts, .. }) | Expr::Tuple(ast::ExprTuple { elts, .. }) => { for expr in elts { self.visit_expr(expr); } } _ => {} } } } #[derive(Default)] struct AssignedNamesVisitor<'a> { names: Vec<&'a str>, } /// `Visitor` to collect all used identifiers in a statement. impl<'a> Visitor<'a> for AssignedNamesVisitor<'a> { fn visit_stmt(&mut self, stmt: &'a Stmt) { if stmt.is_function_def_stmt() { // Don't recurse. return; } match stmt { Stmt::Assign(ast::StmtAssign { targets, .. }) => { let mut visitor = NamesFromAssignmentsVisitor::default(); for expr in targets { visitor.visit_expr(expr); } self.names.extend(visitor.names); } Stmt::AugAssign(ast::StmtAugAssign { target, .. }) | Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) | Stmt::For(ast::StmtFor { target, .. }) => { let mut visitor = NamesFromAssignmentsVisitor::default(); visitor.visit_expr(target); self.names.extend(visitor.names); } _ => {} } visitor::walk_stmt(self, stmt); } fn visit_expr(&mut self, expr: &'a Expr) { if expr.is_lambda_expr() { // Don't recurse. return; } visitor::walk_expr(self, expr); } fn visit_comprehension(&mut self, comprehension: &'a Comprehension) { let mut visitor = NamesFromAssignmentsVisitor::default(); visitor.visit_expr(&comprehension.target); self.names.extend(visitor.names); visitor::walk_comprehension(self, comprehension); } } /// B023 pub(crate) fn function_uses_loop_variable(checker: &Checker, node: &Node) { // Identify any "suspicious" variables. These are defined as variables that are // referenced in a function or lambda body, but aren't bound as arguments. let suspicious_variables = { let mut visitor = SuspiciousVariablesVisitor::default(); match node { Node::Stmt(stmt) => visitor.visit_stmt(stmt), Node::Expr(expr) => visitor.visit_expr(expr), } visitor.names }; if !suspicious_variables.is_empty() { // Identify any variables that are assigned in the loop (ignoring functions). let reassigned_in_loop = { let mut visitor = AssignedNamesVisitor::default(); match node { Node::Stmt(stmt) => visitor.visit_stmt(stmt), Node::Expr(expr) => visitor.visit_expr(expr), } visitor.names }; // If a variable was used in a function or lambda body, and assigned in the // loop, flag it. for name in suspicious_variables { if reassigned_in_loop.contains(&name.id.as_str()) { if checker.insert_flake8_bugbear_range(name.range()) { checker.report_diagnostic( FunctionUsesLoopVariable { name: 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/flake8_bugbear/rules/unreliable_callable_check.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs
use ruff_diagnostics::Applicability; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast, Expr}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for uses of `hasattr` to test if an object is callable (e.g., /// `hasattr(obj, "__call__")`). /// /// ## Why is this bad? /// Using `hasattr` is an unreliable mechanism for testing if an object is /// callable. If `obj` implements a custom `__getattr__`, or if its `__call__` /// is itself not callable, you may get misleading results. /// /// Instead, use `callable(obj)` to test if `obj` is callable. /// /// ## Example /// ```python /// hasattr(obj, "__call__") /// ``` /// /// Use instead: /// ```python /// callable(obj) /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe because the replacement may not be semantically /// equivalent to the original expression, potentially changing the behavior of the code. /// /// For example, an imported module may have a `__call__` attribute but is not considered /// a callable object: /// ```python /// import operator /// /// assert hasattr(operator, "__call__") /// assert callable(operator) is False /// ``` /// Additionally, `__call__` may be defined only as an instance method: /// ```python /// class A: /// def __init__(self): /// self.__call__ = None /// /// /// assert hasattr(A(), "__call__") /// assert callable(A()) is False /// ``` /// /// Additionally, if there are comments in the `hasattr` call expression, they may be removed: /// ```python /// hasattr( /// # comment 1 /// obj, # comment 2 /// # comment 3 /// "__call__", # comment 4 /// # comment 5 /// ) /// ``` /// /// ## References /// - [Python documentation: `callable`](https://docs.python.org/3/library/functions.html#callable) /// - [Python documentation: `hasattr`](https://docs.python.org/3/library/functions.html#hasattr) /// - [Python documentation: `__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) /// - [Python documentation: `__call__`](https://docs.python.org/3/reference/datamodel.html#object.__call__) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.106")] pub(crate) struct UnreliableCallableCheck; impl Violation for UnreliableCallableCheck { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { "Using `hasattr(x, \"__call__\")` to test if x is callable is unreliable. Use \ `callable(x)` for consistent results." .to_string() } fn fix_title(&self) -> Option<String> { Some("Replace with `callable()`".to_string()) } } /// B004 pub(crate) fn unreliable_callable_check( checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr], keywords: &[ast::Keyword], ) { if !keywords.is_empty() { return; } let [obj, attr, ..] = args else { return; }; let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = attr else { return; }; if value != "__call__" { return; } let Some(builtins_function) = checker.semantic().resolve_builtin_symbol(func) else { return; }; // Validate function arguments based on function name let valid_args = match builtins_function { "hasattr" => { // hasattr should have exactly 2 positional arguments and no keywords args.len() == 2 } "getattr" => { // getattr should have 2 or 3 positional arguments and no keywords args.len() == 2 || args.len() == 3 } _ => return, }; if !valid_args { return; } let mut diagnostic = checker.report_diagnostic(UnreliableCallableCheck, expr.range()); if builtins_function == "hasattr" { diagnostic.try_set_fix(|| { let (import_edit, binding) = checker.importer().get_or_import_builtin_symbol( "callable", expr.start(), checker.semantic(), )?; let binding_edit = Edit::range_replacement( format!("{binding}({})", checker.locator().slice(obj)), expr.range(), ); Ok(Fix::applicable_edits( binding_edit, import_edit, Applicability::Unsafe, )) }); } }
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_bugbear/rules/loop_variable_overrides_iterator.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs
use ruff_python_ast::{self as ast, Expr}; use rustc_hash::FxHashMap; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::visitor; use ruff_python_ast::visitor::Visitor; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for loop control variables that override the loop iterable. /// /// ## Why is this bad? /// Loop control variables should not override the loop iterable, as this can /// lead to confusing behavior. /// /// Instead, use a distinct variable name for any loop control variables. /// /// ## Example /// ```python /// items = [1, 2, 3] /// /// for items in items: /// print(items) /// ``` /// /// Use instead: /// ```python /// items = [1, 2, 3] /// /// for item in items: /// print(item) /// ``` /// /// ## References /// - [Python documentation: The `for` statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.121")] pub(crate) struct LoopVariableOverridesIterator { name: String, } impl Violation for LoopVariableOverridesIterator { #[derive_message_formats] fn message(&self) -> String { let LoopVariableOverridesIterator { name } = self; format!("Loop control variable `{name}` overrides iterable it iterates") } } /// B020 pub(crate) fn loop_variable_overrides_iterator(checker: &Checker, target: &Expr, iter: &Expr) { let target_names = { let mut target_finder = NameFinder::default(); target_finder.visit_expr(target); target_finder.names }; let iter_names = { let mut iter_finder = NameFinder::default(); iter_finder.visit_expr(iter); iter_finder.names }; for (name, expr) in target_names { if iter_names.contains_key(name) { checker.report_diagnostic( LoopVariableOverridesIterator { name: name.to_string(), }, expr.range(), ); } } } #[derive(Default)] struct NameFinder<'a> { names: FxHashMap<&'a str, &'a Expr>, } impl<'a> Visitor<'a> for NameFinder<'a> { fn visit_expr(&mut self, expr: &'a Expr) { match expr { Expr::Name(ast::ExprName { id, .. }) => { self.names.insert(id, expr); } Expr::ListComp(ast::ExprListComp { generators, .. }) | Expr::DictComp(ast::ExprDictComp { generators, .. }) | Expr::SetComp(ast::ExprSetComp { generators, .. }) | Expr::Generator(ast::ExprGenerator { generators, .. }) => { for comp in generators { self.visit_expr(&comp.iter); } } Expr::Lambda(ast::ExprLambda { parameters, body, range: _, node_index: _, }) => { visitor::walk_expr(self, body); if let Some(parameters) = parameters { for parameter in parameters.iter_non_variadic_params() { self.names.remove(parameter.name().as_str()); } } } _ => 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/flake8_bugbear/rules/duplicate_value.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_value.rs
use anyhow::{Context, Result}; use rustc_hash::FxHashMap; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::Expr; use ruff_python_ast::comparable::HashableExpr; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for set literals that contain duplicate items. /// /// ## Why is this bad? /// In Python, sets are unordered collections of unique elements. Including a /// duplicate item in a set literal is redundant, as the duplicate item will be /// replaced with a single item at runtime. /// /// ## Example /// ```python /// {1, 2, 3, 1} /// ``` /// /// Use instead: /// ```python /// {1, 2, 3} /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.271")] pub(crate) struct DuplicateValue { value: String, existing: String, } impl Violation for DuplicateValue { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { let DuplicateValue { value, existing } = self; if value == existing { format!("Sets should not contain duplicate item `{value}`") } else { format!( "Sets should not contain duplicate items, but `{existing}` and `{value}` has the same value" ) } } fn fix_title(&self) -> Option<String> { Some("Remove duplicate item".to_string()) } } /// B033 pub(crate) fn duplicate_value(checker: &Checker, set: &ast::ExprSet) { let mut seen_values: FxHashMap<HashableExpr, &Expr> = FxHashMap::default(); for (index, value) in set.iter().enumerate() { if value.is_literal_expr() { if let Some(existing) = seen_values.insert(HashableExpr::from(value), value) { let mut diagnostic = checker.report_diagnostic( DuplicateValue { value: checker.generator().expr(value), existing: checker.generator().expr(existing), }, value.range(), ); diagnostic.try_set_fix(|| { remove_member(set, index, checker.locator().contents()).map(Fix::safe_edit) }); } } } } /// Remove the member at the given index from the [`ast::ExprSet`]. fn remove_member(set: &ast::ExprSet, index: usize, source: &str) -> Result<Edit> { if index < set.len() - 1 { // Case 1: the expression is _not_ the last node, so delete from the start of the // expression to the end of the subsequent comma. // Ex) Delete `"a"` in `{"a", "b", "c"}`. let mut tokenizer = SimpleTokenizer::starts_at(set.elts[index].end(), source); // Find the trailing comma. tokenizer .find(|token| token.kind == SimpleTokenKind::Comma) .context("Unable to find trailing comma")?; // Find the next non-whitespace token. let next = tokenizer .find(|token| { token.kind != SimpleTokenKind::Whitespace && token.kind != SimpleTokenKind::Newline }) .context("Unable to find next token")?; Ok(Edit::deletion(set.elts[index].start(), next.start())) } else if index > 0 { // Case 2: the expression is the last node, but not the _only_ node, so delete from the // start of the previous comma to the end of the expression. // Ex) Delete `"c"` in `{"a", "b", "c"}`. let mut tokenizer = SimpleTokenizer::starts_at(set.elts[index - 1].end(), source); // Find the trailing comma. let comma = tokenizer .find(|token| token.kind == SimpleTokenKind::Comma) .context("Unable to find trailing comma")?; Ok(Edit::deletion(comma.start(), set.elts[index].end())) } else { // Case 3: expression is the only node, so delete it. // Ex) Delete `"a"` in `{"a"}`. Ok(Edit::range_deletion(set.elts[index].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/flake8_bugbear/rules/raise_without_from_inside_except.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs
use ruff_python_ast as ast; use ruff_python_ast::Stmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::RaiseStatementVisitor; use ruff_python_ast::statement_visitor::StatementVisitor; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for `raise` statements in exception handlers that lack a `from` /// clause. /// /// ## Why is this bad? /// In Python, `raise` can be used with or without an exception from which the /// current exception is derived. This is known as exception chaining. When /// printing the stack trace, chained exceptions are displayed in such a way /// so as make it easier to trace the exception back to its root cause. /// /// When raising an exception from within an `except` clause, always include a /// `from` clause to facilitate exception chaining. If the exception is not /// chained, it will be difficult to trace the exception back to its root cause. /// /// ## Example /// ```python /// try: /// ... /// except FileNotFoundError: /// if ...: /// raise RuntimeError("...") /// else: /// raise UserWarning("...") /// ``` /// /// Use instead: /// ```python /// try: /// ... /// except FileNotFoundError as exc: /// if ...: /// raise RuntimeError("...") from None /// else: /// raise UserWarning("...") from exc /// ``` /// /// ## References /// - [Python documentation: `raise` statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.138")] pub(crate) struct RaiseWithoutFromInsideExcept { is_star: bool, } impl Violation for RaiseWithoutFromInsideExcept { #[derive_message_formats] fn message(&self) -> String { if self.is_star { "Within an `except*` clause, raise exceptions with `raise ... from err` or `raise ... \ from None` to distinguish them from errors in exception handling" .to_string() } else { "Within an `except` clause, raise exceptions with `raise ... from err` or `raise ... \ from None` to distinguish them from errors in exception handling" .to_string() } } } /// B904 pub(crate) fn raise_without_from_inside_except( checker: &Checker, name: Option<&str>, body: &[Stmt], ) { let raises = { let mut visitor = RaiseStatementVisitor::default(); visitor.visit_body(body); visitor.raises }; for (range, exc, cause) in raises { if cause.is_none() { if let Some(exc) = exc { // If the raised object is bound to the same name, it's a re-raise, which is // allowed (but may be flagged by other diagnostics). // // For example: // ```python // try: // ... // except ValueError as exc: // raise exc // ``` if let Some(name) = name { if exc .as_name_expr() .is_some_and(|ast::ExprName { id, .. }| name == id) { continue; } } let is_star = checker .semantic() .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); checker.report_diagnostic(RaiseWithoutFromInsideExcept { is_star }, 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/flake8_bugbear/rules/cached_instance_method.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/cached_instance_method.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::helpers::map_callable; use ruff_python_ast::{self as ast, Expr}; use ruff_python_semantic::analyze::{class, function_type}; use ruff_python_semantic::{ScopeKind, SemanticModel}; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for uses of the `functools.lru_cache` and `functools.cache` /// decorators on methods. /// /// ## Why is this bad? /// Using the `functools.lru_cache` and `functools.cache` decorators on methods /// can lead to memory leaks, as the global cache will retain a reference to /// the instance, preventing it from being garbage collected. /// /// Instead, refactor the method to depend only on its arguments and not on the /// instance of the class, or use the `@lru_cache` decorator on a function /// outside of the class. /// /// This rule ignores instance methods on enumeration classes, as enum members /// are singletons. /// /// ## Example /// ```python /// from functools import lru_cache /// /// /// def square(x: int) -> int: /// return x * x /// /// /// class Number: /// value: int /// /// @lru_cache /// def squared(self): /// return square(self.value) /// ``` /// /// Use instead: /// ```python /// from functools import lru_cache /// /// /// @lru_cache /// def square(x: int) -> int: /// return x * x /// /// /// class Number: /// value: int /// /// def squared(self): /// return square(self.value) /// ``` /// /// ## Options /// /// This rule only applies to regular methods, not static or class methods. You can customize how /// Ruff categorizes methods with the following options: /// /// - `lint.pep8-naming.classmethod-decorators` /// - `lint.pep8-naming.staticmethod-decorators` /// /// ## References /// - [Python documentation: `functools.lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache) /// - [Python documentation: `functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache) /// - [don't lru_cache methods!](https://www.youtube.com/watch?v=sVjtp6tGo0g) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.114")] pub(crate) struct CachedInstanceMethod; impl Violation for CachedInstanceMethod { #[derive_message_formats] fn message(&self) -> String { "Use of `functools.lru_cache` or `functools.cache` on methods can lead to memory leaks" .to_string() } } /// B019 pub(crate) fn cached_instance_method(checker: &Checker, function_def: &ast::StmtFunctionDef) { let scope = checker.semantic().current_scope(); // Parent scope _must_ be a class. let ScopeKind::Class(class_def) = scope.kind else { return; }; // The function must be an _instance_ method. let type_ = function_type::classify( &function_def.name, &function_def.decorator_list, scope, checker.semantic(), &checker.settings().pep8_naming.classmethod_decorators, &checker.settings().pep8_naming.staticmethod_decorators, ); if !matches!(type_, function_type::FunctionType::Method) { return; } for decorator in &function_def.decorator_list { if is_cache_func(map_callable(&decorator.expression), checker.semantic()) { // If we found a cached instance method, validate (lazily) that the class is not an enum. if class::is_enumeration(class_def, checker.semantic()) { return; } checker.report_diagnostic(CachedInstanceMethod, decorator.range()); } } } /// Returns `true` if the given expression is a call to `functools.lru_cache` or `functools.cache`. fn is_cache_func(expr: &Expr, semantic: &SemanticModel) -> bool { semantic .resolve_qualified_name(expr) .is_some_and(|qualified_name| { matches!( qualified_name.segments(), ["functools", "lru_cache" | "cache"] ) }) }
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_bugbear/rules/raise_literal.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/raise_literal.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 `raise` statements that raise a literal value. /// /// ## Why is this bad? /// `raise` must be followed by an exception instance or an exception class, /// and exceptions must be instances of `BaseException` or a subclass thereof. /// Raising a literal will raise a `TypeError` at runtime. /// /// ## Example /// ```python /// raise "foo" /// ``` /// /// Use instead: /// ```python /// raise Exception("foo") /// ``` /// /// ## References /// - [Python documentation: `raise` statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.102")] pub(crate) struct RaiseLiteral; impl Violation for RaiseLiteral { #[derive_message_formats] fn message(&self) -> String { "Cannot raise a literal. Did you intend to return it or raise an Exception?".to_string() } } /// B016 pub(crate) fn raise_literal(checker: &Checker, expr: &Expr) { if expr.is_literal_expr() { checker.report_diagnostic(RaiseLiteral, 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/flake8_bugbear/rules/function_call_in_argument_default.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/function_call_in_argument_default.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::{QualifiedName, UnqualifiedName}; use ruff_python_ast::visitor; use ruff_python_ast::visitor::Visitor; use ruff_python_ast::{self as ast, Expr, Parameters}; use ruff_python_semantic::analyze::typing::{ is_immutable_annotation, is_immutable_func, is_immutable_newtype_call, is_mutable_func, }; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for function calls in default function arguments. /// /// ## Why is this bad? /// Any function call that's used in a default argument will only be performed /// once, at definition time. The returned value will then be reused by all /// calls to the function, which can lead to unexpected behaviour. /// /// Parameters with immutable type annotations will be ignored by this rule. /// Those whose default arguments are `NewType` calls where the original type /// is immutable are also ignored. /// /// Calls and types outside of the standard library can be marked as an exception /// to this rule with the [`lint.flake8-bugbear.extend-immutable-calls`] configuration option. /// /// ## Example /// /// ```python /// def create_list() -> list[int]: /// return [1, 2, 3] /// /// /// def mutable_default(arg: list[int] = create_list()) -> list[int]: /// arg.append(4) /// return arg /// ``` /// /// Use instead: /// /// ```python /// def better(arg: list[int] | None = None) -> list[int]: /// if arg is None: /// arg = create_list() /// /// arg.append(4) /// return arg /// ``` /// /// If the use of a singleton is intentional, assign the result call to a /// module-level variable, and use that variable in the default argument: /// /// ```python /// ERROR = ValueError("Hosts weren't successfully added") /// /// /// def add_host(error: Exception = ERROR) -> None: ... /// ``` /// /// ## Options /// - `lint.flake8-bugbear.extend-immutable-calls` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.102")] pub(crate) struct FunctionCallInDefaultArgument { name: Option<String>, } impl Violation for FunctionCallInDefaultArgument { #[derive_message_formats] fn message(&self) -> String { if let Some(name) = &self.name { format!( "Do not perform function call `{name}` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable" ) } else { "Do not perform function call in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable".to_string() } } } struct ArgumentDefaultVisitor<'a, 'b> { checker: &'a Checker<'b>, extend_immutable_calls: &'a [QualifiedName<'b>], } impl<'a, 'b> ArgumentDefaultVisitor<'a, 'b> { fn new(checker: &'a Checker<'b>, extend_immutable_calls: &'a [QualifiedName<'b>]) -> Self { Self { checker, extend_immutable_calls, } } } impl Visitor<'_> for ArgumentDefaultVisitor<'_, '_> { fn visit_expr(&mut self, expr: &Expr) { match expr { Expr::Call(ast::ExprCall { func, .. }) => { if !is_mutable_func(func, self.checker.semantic()) && !is_immutable_func( func, self.checker.semantic(), self.extend_immutable_calls, ) && !func.as_name_expr().is_some_and(|name| { is_immutable_newtype_call( name, self.checker.semantic(), self.extend_immutable_calls, ) }) { self.checker.report_diagnostic( FunctionCallInDefaultArgument { name: UnqualifiedName::from_expr(func).map(|name| name.to_string()), }, expr.range(), ); } visitor::walk_expr(self, expr); } Expr::Lambda(_) => { // Don't recurse. } _ => visitor::walk_expr(self, expr), } } } /// B008 pub(crate) fn function_call_in_argument_default(checker: &Checker, parameters: &Parameters) { // Map immutable calls to (module, member) format. let extend_immutable_calls: Vec<QualifiedName> = checker .settings() .flake8_bugbear .extend_immutable_calls .iter() .map(|target| QualifiedName::from_dotted_name(target)) .collect(); let mut visitor = ArgumentDefaultVisitor::new(checker, &extend_immutable_calls); for parameter in parameters.iter_non_variadic_params() { if let Some(default) = parameter.default() { if !parameter.annotation().is_some_and(|expr| { is_immutable_annotation(expr, checker.semantic(), &extend_immutable_calls) }) { visitor.visit_expr(default); } } } }
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_bugbear/rules/map_without_explicit_strict.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/map_without_explicit_strict.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{self as ast}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::fix::edits::add_argument; use crate::rules::flake8_bugbear::helpers::any_infinite_iterables; use crate::{AlwaysFixableViolation, Applicability, Fix}; /// ## What it does /// Checks for `map` calls without an explicit `strict` parameter when called with two or more iterables, or any starred argument. /// /// This rule applies to Python 3.14 and later, where `map` accepts a `strict` keyword /// argument. For details, see: [What’s New in Python 3.14](https://docs.python.org/dev/whatsnew/3.14.html). /// /// ## Why is this bad? /// By default, if the iterables passed to `map` are of different lengths, the /// resulting iterator will be silently truncated to the length of the shortest /// iterable. This can lead to subtle bugs. /// /// Pass `strict=True` to raise a `ValueError` if the iterables are of /// non-uniform length. Alternatively, if the iterables are deliberately of /// different lengths, pass `strict=False` to make the intention explicit. /// /// ## Example /// ```python /// map(f, a, b) /// ``` /// /// Use instead: /// ```python /// map(f, a, b, strict=True) /// ``` /// /// ## Fix safety /// This rule's fix is marked as unsafe. While adding `strict=False` preserves /// the runtime behavior, it can obscure situations where the iterables are of /// unequal length. Ruff prefers to alert users so they can choose the intended /// behavior themselves. /// /// ## References /// - [Python documentation: `map`](https://docs.python.org/3/library/functions.html#map) /// - [What’s New in Python 3.14](https://docs.python.org/dev/whatsnew/3.14.html) #[derive(ViolationMetadata)] #[violation_metadata(preview_since = "0.13.2")] pub(crate) struct MapWithoutExplicitStrict; impl AlwaysFixableViolation for MapWithoutExplicitStrict { #[derive_message_formats] fn message(&self) -> String { "`map()` without an explicit `strict=` parameter".to_string() } fn fix_title(&self) -> String { "Add explicit value for parameter `strict=`".to_string() } } /// B912 pub(crate) fn map_without_explicit_strict(checker: &Checker, call: &ast::ExprCall) { let semantic = checker.semantic(); if semantic.match_builtin_expr(&call.func, "map") && call.arguments.find_keyword("strict").is_none() && ( // at least 2 iterables (+ 1 function) call.arguments.args.len() >= 3 // or a starred argument || call.arguments.args.iter().any(ast::Expr::is_starred_expr) ) && !any_infinite_iterables(call.arguments.args.iter().skip(1), semantic) { checker .report_diagnostic(MapWithoutExplicitStrict, call.range()) .set_fix(Fix::applicable_edit( add_argument("strict=False", &call.arguments, checker.tokens()), Applicability::Unsafe, )); } }
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_bugbear/rules/duplicate_exceptions.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs
use itertools::Itertools; use rustc_hash::{FxHashMap, FxHashSet}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::{self as ast, ExceptHandler, Expr, ExprContext}; use ruff_text_size::{Ranged, TextRange}; use crate::checkers::ast::Checker; use crate::fix::edits::pad; use crate::registry::Rule; use crate::{AlwaysFixableViolation, Violation}; use crate::{Edit, Fix}; /// ## What it does /// Checks for `try-except` blocks with duplicate exception handlers. /// /// ## Why is this bad? /// Duplicate exception handlers are redundant, as the first handler will catch /// the exception, making the second handler unreachable. /// /// ## Example /// ```python /// try: /// ... /// except ValueError: /// ... /// except ValueError: /// ... /// ``` /// /// Use instead: /// ```python /// try: /// ... /// except ValueError: /// ... /// ``` /// /// ## References /// - [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.67")] pub(crate) struct DuplicateTryBlockException { name: String, is_star: bool, } impl Violation for DuplicateTryBlockException { #[derive_message_formats] fn message(&self) -> String { let DuplicateTryBlockException { name, is_star } = self; if *is_star { format!("try-except* block with duplicate exception `{name}`") } else { format!("try-except block with duplicate exception `{name}`") } } } /// ## What it does /// Checks for exception handlers that catch duplicate exceptions. /// /// ## Why is this bad? /// Including the same exception multiple times in the same handler is redundant, /// as the first exception will catch the exception, making the second exception /// unreachable. The same applies to exception hierarchies, as a handler for a /// parent exception (like `Exception`) will also catch child exceptions (like /// `ValueError`). /// /// ## Example /// ```python /// try: /// ... /// except (Exception, ValueError): # `Exception` includes `ValueError`. /// ... /// ``` /// /// Use instead: /// ```python /// try: /// ... /// except Exception: /// ... /// ``` /// /// ## References /// - [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause) /// - [Python documentation: Exception hierarchy](https://docs.python.org/3/library/exceptions.html#exception-hierarchy) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.67")] pub(crate) struct DuplicateHandlerException { pub names: Vec<String>, } impl AlwaysFixableViolation for DuplicateHandlerException { #[derive_message_formats] fn message(&self) -> String { let DuplicateHandlerException { names } = self; if let [name] = names.as_slice() { format!("Exception handler with duplicate exception: `{name}`") } else { let names = names.iter().map(|name| format!("`{name}`")).join(", "); format!("Exception handler with duplicate exceptions: {names}") } } fn fix_title(&self) -> String { "De-duplicate exceptions".to_string() } } fn type_pattern(elts: Vec<&Expr>) -> Expr { ast::ExprTuple { elts: elts.into_iter().cloned().collect(), ctx: ExprContext::Load, range: TextRange::default(), node_index: ruff_python_ast::AtomicNodeIndex::NONE, parenthesized: true, } .into() } /// B014 fn duplicate_handler_exceptions<'a>( checker: &Checker, expr: &'a Expr, elts: &'a [Expr], ) -> FxHashMap<UnqualifiedName<'a>, &'a Expr> { let mut seen: FxHashMap<UnqualifiedName, &Expr> = FxHashMap::default(); let mut duplicates: FxHashSet<UnqualifiedName> = FxHashSet::default(); let mut unique_elts: Vec<&Expr> = Vec::default(); for type_ in elts { if let Some(name) = UnqualifiedName::from_expr(type_) { if seen.contains_key(&name) { duplicates.insert(name); } else { seen.entry(name).or_insert(type_); unique_elts.push(type_); } } } if checker.is_rule_enabled(Rule::DuplicateHandlerException) { // TODO(charlie): Handle "BaseException" and redundant exception aliases. if !duplicates.is_empty() { let mut diagnostic = checker.report_diagnostic( DuplicateHandlerException { names: duplicates .into_iter() .map(|qualified_name| qualified_name.segments().join(".")) .sorted() .collect::<Vec<String>>(), }, expr.range(), ); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( // Single exceptions don't require parentheses, but since we're _removing_ // parentheses, insert whitespace as needed. if let [elt] = unique_elts.as_slice() { pad( checker.generator().expr(elt), expr.range(), checker.locator(), ) } else { // Multiple exceptions must always be parenthesized. This is done // manually as the generator never parenthesizes lone tuples. format!("({})", checker.generator().expr(&type_pattern(unique_elts))) }, expr.range(), ))); } } seen } /// B025 pub(crate) fn duplicate_exceptions(checker: &Checker, handlers: &[ExceptHandler]) { let mut seen: FxHashSet<UnqualifiedName> = FxHashSet::default(); let mut duplicates: FxHashMap<UnqualifiedName, Vec<&Expr>> = FxHashMap::default(); for handler in handlers { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_: Some(type_), .. }) = handler else { continue; }; match type_.as_ref() { Expr::Attribute(_) | Expr::Name(_) => { if let Some(name) = UnqualifiedName::from_expr(type_) { if seen.contains(&name) { duplicates.entry(name).or_default().push(type_); } else { seen.insert(name); } } } Expr::Tuple(ast::ExprTuple { elts, .. }) => { for (name, expr) in duplicate_handler_exceptions(checker, type_, elts) { if seen.contains(&name) { duplicates.entry(name).or_default().push(expr); } else { seen.insert(name); } } } _ => {} } } if checker.is_rule_enabled(Rule::DuplicateTryBlockException) { for (name, exprs) in duplicates { for expr in exprs { let is_star = checker .semantic() .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); checker.report_diagnostic( DuplicateTryBlockException { name: name.segments().join("."), is_star, }, 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/flake8_bugbear/rules/unintentional_type_annotation.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs
use ruff_python_ast::{self as ast, Expr, 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 the unintentional use of type annotations. /// /// ## Why is this bad? /// The use of a colon (`:`) in lieu of an assignment (`=`) can be syntactically valid, but /// is almost certainly a mistake when used in a subscript or attribute assignment. /// /// ## Example /// ```python /// a["b"]: 1 /// ``` /// /// Use instead: /// ```python /// a["b"] = 1 /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.250")] pub(crate) struct UnintentionalTypeAnnotation; impl Violation for UnintentionalTypeAnnotation { #[derive_message_formats] fn message(&self) -> String { "Possible unintentional type annotation (using `:`). Did you mean to assign (using `=`)?" .to_string() } } /// B032 pub(crate) fn unintentional_type_annotation( checker: &Checker, target: &Expr, value: Option<&Expr>, stmt: &Stmt, ) { if value.is_some() { return; } match target { Expr::Subscript(ast::ExprSubscript { value, .. }) => { if value.is_name_expr() { checker.report_diagnostic(UnintentionalTypeAnnotation, stmt.range()); } } Expr::Attribute(ast::ExprAttribute { value, .. }) => { if let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() { if id != "self" { checker.report_diagnostic(UnintentionalTypeAnnotation, 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/flake8_bugbear/rules/unused_loop_control_variable.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast as ast; use ruff_python_ast::helpers; use ruff_python_ast::helpers::{NameFinder, StoredNameFinder}; use ruff_python_ast::visitor::Visitor; use ruff_python_semantic::Binding; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{Edit, Fix, FixAvailability, Violation}; /// ## What it does /// Checks for unused variables in loops (e.g., `for` and `while` statements). /// /// ## Why is this bad? /// Defining a variable in a loop statement that is never used can confuse /// readers. /// /// If the variable is intended to be unused (e.g., to facilitate /// destructuring of a tuple or other object), prefix it with an underscore /// to indicate the intent. Otherwise, remove the variable entirely. /// /// ## Example /// ```python /// for i, j in foo: /// bar(i) /// ``` /// /// Use instead: /// ```python /// for i, _j in foo: /// bar(i) /// ``` /// /// ## Options /// /// - `lint.dummy-variable-rgx` /// /// ## References /// - [PEP 8: Naming Conventions](https://peps.python.org/pep-0008/#naming-conventions) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.84")] pub(crate) struct UnusedLoopControlVariable { /// The name of the loop control variable. name: String, /// The name to which the variable should be renamed, if it can be /// safely renamed. rename: Option<String>, /// Whether the variable is certain to be unused in the loop body, or /// merely suspect. A variable _may_ be used, but undetectably /// so, if the loop incorporates by magic control flow (e.g., /// `locals()`). certainty: Certainty, } impl Violation for UnusedLoopControlVariable { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { let UnusedLoopControlVariable { name, certainty, .. } = self; match certainty { Certainty::Certain => { format!("Loop control variable `{name}` not used within loop body") } Certainty::Uncertain => { format!("Loop control variable `{name}` may not be used within loop body") } } } fn fix_title(&self) -> Option<String> { let UnusedLoopControlVariable { rename, name, .. } = self; rename .as_ref() .map(|rename| format!("Rename unused `{name}` to `{rename}`")) } } /// B007 pub(crate) fn unused_loop_control_variable(checker: &Checker, stmt_for: &ast::StmtFor) { let control_names = { let mut finder = StoredNameFinder::default(); finder.visit_expr(stmt_for.target.as_ref()); finder.names }; let used_names = { let mut finder = NameFinder::default(); for stmt in &stmt_for.body { finder.visit_stmt(stmt); } finder.names }; for (name, expr) in control_names { // Ignore names that are already underscore-prefixed. if checker.settings().dummy_variable_rgx.is_match(name) { continue; } // Ignore any names that are actually used in the loop body. if used_names.contains_key(name) { continue; } // Avoid fixing any variables that _may_ be used, but undetectably so. let certainty = if helpers::uses_magic_variable_access(&stmt_for.body, |id| { checker.semantic().has_builtin_binding(id) }) { Certainty::Uncertain } else { Certainty::Certain }; // Attempt to rename the variable by prepending an underscore, but avoid // applying the fix if doing so wouldn't actually cause us to ignore the // violation in the next pass. let rename = format!("_{name}"); let rename = checker .settings() .dummy_variable_rgx .is_match(rename.as_str()) .then_some(rename); let mut diagnostic = checker.report_diagnostic( UnusedLoopControlVariable { name: name.to_string(), rename: rename.clone(), certainty, }, expr.range(), ); if let Some(rename) = rename { if certainty == Certainty::Certain { // Avoid fixing if the variable, or any future bindings to the variable, are // used _after_ the loop. let scope = checker.semantic().current_scope(); if scope .get_all(name) .map(|binding_id| checker.semantic().binding(binding_id)) .filter(|binding| binding.start() >= expr.start()) .all(Binding::is_unused) { diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( rename, expr.range(), ))); } } } } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Certainty { Certain, Uncertain, }
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_bugbear/rules/f_string_docstring.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/f_string_docstring.rs
use ruff_python_ast::{self as ast, Stmt}; 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 docstrings that are written via f-strings. /// /// ## Why is this bad? /// Python will interpret the f-string as a joined string, rather than as a /// docstring. As such, the "docstring" will not be accessible via the /// `__doc__` attribute, nor will it be picked up by any automated /// documentation tooling. /// /// ## Example /// ```python /// def foo(): /// f"""Not a docstring.""" /// ``` /// /// Use instead: /// ```python /// def foo(): /// """A docstring.""" /// ``` /// /// ## References /// - [PEP 257 – Docstring Conventions](https://peps.python.org/pep-0257/) /// - [Python documentation: Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.116")] pub(crate) struct FStringDocstring; impl Violation for FStringDocstring { #[derive_message_formats] fn message(&self) -> String { "f-string used as docstring. Python will interpret this as a joined string, rather than a docstring.".to_string() } } /// B021 pub(crate) fn f_string_docstring(checker: &Checker, body: &[Stmt]) { let Some(stmt) = body.first() else { return; }; let Stmt::Expr(ast::StmtExpr { value, range: _, node_index: _, }) = stmt else { return; }; if !value.is_f_string_expr() { return; } checker.report_diagnostic(FStringDocstring, 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/flake8_bugbear/rules/useless_expression.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_expression.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Expr; use ruff_python_ast::helpers::contains_effect; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::flake8_bugbear::helpers::at_last_top_level_expression_in_cell; /// ## What it does /// Checks for useless expressions. /// /// ## Why is this bad? /// Useless expressions have no effect on the program, and are often included /// by mistake. Assign a useless expression to a variable, or remove it /// entirely. /// /// ## Example /// ```python /// 1 + 1 /// ``` /// /// Use instead: /// ```python /// foo = 1 + 1 /// ``` /// /// ## Notebook behavior /// For Jupyter Notebooks, this rule is not applied to the last top-level expression in a cell. /// This is because it's common to have a notebook cell that ends with an expression, /// which will result in the `repr` of the evaluated expression being printed as the cell's output. /// /// ## Known problems /// This rule ignores expression types that are commonly used for their side /// effects, such as function calls. /// /// However, if a seemingly useless expression (like an attribute access) is /// needed to trigger a side effect, consider assigning it to an anonymous /// variable, to indicate that the return value is intentionally ignored. /// /// For example, given: /// ```python /// with errors.ExceptionRaisedContext(): /// obj.attribute /// ``` /// /// Use instead: /// ```python /// with errors.ExceptionRaisedContext(): /// _ = obj.attribute /// ``` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.100")] pub(crate) struct UselessExpression { kind: Kind, } impl Violation for UselessExpression { #[derive_message_formats] fn message(&self) -> String { match self.kind { Kind::Expression => { "Found useless expression. Either assign it to a variable or remove it.".to_string() } Kind::Attribute => { "Found useless attribute access. Either assign it to a variable or remove it." .to_string() } } } } /// B018 pub(crate) fn useless_expression(checker: &Checker, value: &Expr) { // Ignore comparisons, as they're handled by `useless_comparison`. if value.is_compare_expr() { return; } // Ignore strings, to avoid false positives with docstrings. if matches!( value, Expr::FString(_) | Expr::StringLiteral(_) | Expr::EllipsisLiteral(_) ) { return; } if checker.source_type.is_ipynb() && at_last_top_level_expression_in_cell( checker.semantic(), checker.locator(), checker.cell_offsets(), ) { return; } // Ignore statements that have side effects. if contains_effect(value, |id| checker.semantic().has_builtin_binding(id)) { // Flag attributes as useless expressions, even if they're attached to calls or other // expressions. if value.is_attribute_expr() { checker.report_diagnostic( UselessExpression { kind: Kind::Attribute, }, value.range(), ); } return; } checker.report_diagnostic( UselessExpression { kind: Kind::Expression, }, value.range(), ); } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum Kind { Expression, Attribute, }
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_bugbear/rules/except_with_non_exception_classes.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_non_exception_classes.rs
use std::collections::VecDeque; use ruff_python_ast::{self as ast, ExceptHandler, Expr, Operator}; 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 exception handlers that catch non-exception classes. /// /// ## Why is this bad? /// Catching classes that do not inherit from `BaseException` will raise a /// `TypeError`. /// /// ## Example /// ```python /// try: /// 1 / 0 /// except 1: /// ... /// ``` /// /// Use instead: /// ```python /// try: /// 1 / 0 /// except ZeroDivisionError: /// ... /// ``` /// /// ## References /// - [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause) /// - [Python documentation: Built-in Exceptions](https://docs.python.org/3/library/exceptions.html#built-in-exceptions) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.255")] pub(crate) struct ExceptWithNonExceptionClasses { is_star: bool, } impl Violation for ExceptWithNonExceptionClasses { #[derive_message_formats] fn message(&self) -> String { if self.is_star { "`except*` handlers should only be exception classes or tuples of exception classes" .to_string() } else { "`except` handlers should only be exception classes or tuples of exception classes" .to_string() } } } /// B030 pub(crate) fn except_with_non_exception_classes(checker: &Checker, except_handler: &ExceptHandler) { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_, .. }) = except_handler; let Some(type_) = type_ else { return; }; for expr in flatten_iterables(type_) { if !matches!( expr, Expr::Subscript(_) | Expr::Attribute(_) | Expr::Name(_) | Expr::Call(_), ) { let is_star = checker .semantic() .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); checker.report_diagnostic(ExceptWithNonExceptionClasses { is_star }, expr.range()); } } } /// Given an [`Expr`], flatten any [`Expr::Starred`] expressions and any /// [`Expr::BinOp`] expressions into a flat list of expressions. /// /// This should leave any unstarred iterables alone (subsequently raising a /// warning for B029). fn flatten_iterables(expr: &Expr) -> Vec<&Expr> { // Unpack the top-level Tuple into queue, otherwise add as-is. let mut exprs_to_process: VecDeque<&Expr> = match expr { Expr::Tuple(ast::ExprTuple { elts, .. }) => elts.iter().collect(), _ => vec![expr].into(), }; let mut flattened_exprs: Vec<&Expr> = Vec::with_capacity(exprs_to_process.len()); while let Some(expr) = exprs_to_process.pop_front() { match expr { Expr::Starred(ast::ExprStarred { value, .. }) => match value.as_ref() { Expr::Tuple(ast::ExprTuple { elts, .. }) | Expr::List(ast::ExprList { elts, .. }) => { exprs_to_process.append(&mut elts.iter().collect()); } Expr::BinOp(ast::ExprBinOp { op: Operator::Add, .. }) => { exprs_to_process.push_back(value); } _ => flattened_exprs.push(value), }, Expr::BinOp(ast::ExprBinOp { left, right, op: Operator::Add, .. }) => { for expr in [left, right] { // If left or right are tuples, starred, or binary operators, flatten them. match expr.as_ref() { Expr::Tuple(ast::ExprTuple { elts, .. }) => { exprs_to_process.append(&mut elts.iter().collect()); } Expr::Starred(ast::ExprStarred { value, .. }) => { exprs_to_process.push_back(value); } Expr::BinOp(ast::ExprBinOp { op: Operator::Add, .. }) => { exprs_to_process.push_back(expr); } _ => flattened_exprs.push(expr), } } } _ => flattened_exprs.push(expr), } } flattened_exprs }
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_bugbear/rules/useless_contextlib_suppress.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.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 `contextlib.suppress` without arguments. /// /// ## Why is this bad? /// `contextlib.suppress` is a context manager that suppresses exceptions. It takes, /// as arguments, the exceptions to suppress within the enclosed block. If no /// exceptions are specified, then the context manager won't suppress any /// exceptions, and is thus redundant. /// /// Consider adding exceptions to the `contextlib.suppress` call, or removing the /// context manager entirely. /// /// ## Example /// ```python /// import contextlib /// /// with contextlib.suppress(): /// foo() /// ``` /// /// Use instead: /// ```python /// import contextlib /// /// with contextlib.suppress(Exception): /// foo() /// ``` /// /// ## References /// - [Python documentation: `contextlib.suppress`](https://docs.python.org/3/library/contextlib.html#contextlib.suppress) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.118")] pub(crate) struct UselessContextlibSuppress; impl Violation for UselessContextlibSuppress { #[derive_message_formats] fn message(&self) -> String { "No arguments passed to `contextlib.suppress`. No exceptions will be suppressed and \ therefore this context manager is redundant" .to_string() } } /// B022 pub(crate) fn useless_contextlib_suppress( checker: &Checker, expr: &Expr, func: &Expr, args: &[Expr], ) { if args.is_empty() && checker .semantic() .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["contextlib", "suppress"]) }) { checker.report_diagnostic(UselessContextlibSuppress, 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/flake8_bugbear/rules/except_with_empty_tuple.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs
use ruff_python_ast::{self as ast}; use ruff_python_ast::{ExceptHandler, 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 exception handlers that catch an empty tuple. /// /// ## Why is this bad? /// An exception handler that catches an empty tuple will not catch anything, /// and is indicative of a mistake. Instead, add exceptions to the `except` /// clause. /// /// ## Example /// ```python /// try: /// 1 / 0 /// except (): /// ... /// ``` /// /// Use instead: /// ```python /// try: /// 1 / 0 /// except ZeroDivisionError: /// ... /// ``` /// /// ## References /// - [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.250")] pub(crate) struct ExceptWithEmptyTuple { is_star: bool, } impl Violation for ExceptWithEmptyTuple { #[derive_message_formats] fn message(&self) -> String { if self.is_star { "Using `except* ():` with an empty tuple does not catch anything; add exceptions to handle".to_string() } else { "Using `except ():` with an empty tuple does not catch anything; add exceptions to handle".to_string() } } } /// B029 pub(crate) fn except_with_empty_tuple(checker: &Checker, except_handler: &ExceptHandler) { let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { type_, .. }) = except_handler; let Some(type_) = type_ else { return; }; let Expr::Tuple(ast::ExprTuple { elts, .. }) = type_.as_ref() else { return; }; if elts.is_empty() { let is_star = checker .semantic() .current_statement() .as_try_stmt() .is_some_and(|try_stmt| try_stmt.is_star); checker.report_diagnostic(ExceptWithEmptyTuple { is_star }, except_handler.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/flake8_bugbear/rules/unary_prefix_increment_decrement.rs
crates/ruff_linter/src/rules/flake8_bugbear/rules/unary_prefix_increment_decrement.rs
use ruff_python_ast::{self as ast, Expr, UnaryOp}; 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 attempted use of the unary prefix increment (`++`) or /// decrement operator (`--`). /// /// ## Why is this bad? /// Python does not support the unary prefix increment or decrement operator. /// Writing `++n` is equivalent to `+(+(n))` and writing `--n` is equivalent to /// `-(-(n))`. In both cases, it is equivalent to `n`. /// /// ## Example /// ```python /// ++x /// --y /// ``` /// /// Use instead: /// ```python /// x += 1 /// y -= 1 /// ``` /// /// ## References /// - [Python documentation: Unary arithmetic and bitwise operations](https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations) /// - [Python documentation: Augmented assignment statements](https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements) #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.83")] pub(crate) struct UnaryPrefixIncrementDecrement { operator: UnaryPrefixOperatorType, } impl Violation for UnaryPrefixIncrementDecrement { #[derive_message_formats] fn message(&self) -> String { match self.operator { UnaryPrefixOperatorType::Increment => { "Python does not support the unary prefix increment operator (`++`)".to_string() } UnaryPrefixOperatorType::Decrement => { "Python does not support the unary prefix decrement operator (`--`)".to_string() } } } } /// B002 pub(crate) fn unary_prefix_increment_decrement( checker: &Checker, expr: &Expr, op: UnaryOp, operand: &Expr, ) { let Expr::UnaryOp(ast::ExprUnaryOp { op: nested_op, .. }) = operand else { return; }; match (op, nested_op) { (UnaryOp::UAdd, UnaryOp::UAdd) => { checker.report_diagnostic( UnaryPrefixIncrementDecrement { operator: UnaryPrefixOperatorType::Increment, }, expr.range(), ); } (UnaryOp::USub, UnaryOp::USub) => { checker.report_diagnostic( UnaryPrefixIncrementDecrement { operator: UnaryPrefixOperatorType::Decrement, }, expr.range(), ); } _ => {} } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] enum UnaryPrefixOperatorType { Increment, Decrement, }
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_import_conventions/settings.rs
crates/ruff_linter/src/rules/flake8_import_conventions/settings.rs
//! Settings for import conventions. use std::fmt::{Display, Formatter}; use rustc_hash::{FxHashMap, FxHashSet}; use serde::{Deserialize, Serialize}; use ruff_macros::CacheKey; use crate::display_settings; const CONVENTIONAL_ALIASES: &[(&str, &str)] = &[ ("altair", "alt"), ("matplotlib", "mpl"), ("matplotlib.pyplot", "plt"), ("networkx", "nx"), ("numpy", "np"), ("numpy.typing", "npt"), ("pandas", "pd"), ("seaborn", "sns"), ("tensorflow", "tf"), ("tkinter", "tk"), ("holoviews", "hv"), ("panel", "pn"), ("plotly.express", "px"), ("polars", "pl"), ("pyarrow", "pa"), ("xml.etree.ElementTree", "ET"), ]; #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, CacheKey)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct BannedAliases(Vec<String>); impl Display for BannedAliases { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "[")?; for (i, alias) in self.0.iter().enumerate() { if i > 0 { write!(f, ", ")?; } write!(f, "{alias}")?; } write!(f, "]") } } impl BannedAliases { /// Returns an iterator over the banned aliases. pub fn iter(&self) -> impl Iterator<Item = &str> { self.0.iter().map(String::as_str) } } impl FromIterator<String> for BannedAliases { fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self { Self(iter.into_iter().collect()) } } #[derive(Debug, Clone, CacheKey)] pub struct Settings { pub aliases: FxHashMap<String, String>, pub banned_aliases: FxHashMap<String, BannedAliases>, pub banned_from: FxHashSet<String>, } pub fn default_aliases() -> FxHashMap<String, String> { CONVENTIONAL_ALIASES .iter() .map(|(k, v)| ((*k).to_string(), (*v).to_string())) .collect::<FxHashMap<_, _>>() } impl Default for Settings { fn default() -> Self { Self { aliases: default_aliases(), banned_aliases: FxHashMap::default(), banned_from: FxHashSet::default(), } } } impl Display for Settings { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { display_settings! { formatter = f, namespace = "linter.flake8_import_conventions", fields = [ self.aliases | map, self.banned_aliases | map, self.banned_from | set, ] } 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_import_conventions/mod.rs
crates/ruff_linter/src/rules/flake8_import_conventions/mod.rs
//! Rules from [flake8-import-conventions](https://github.com/joaopalmeiro/flake8-import-conventions). pub(crate) mod rules; pub mod settings; #[cfg(test)] mod tests { use std::path::Path; use anyhow::Result; use rustc_hash::{FxHashMap, FxHashSet}; use crate::assert_diagnostics; use crate::registry::Rule; use crate::rules::flake8_import_conventions::settings::{BannedAliases, default_aliases}; use crate::settings::LinterSettings; use crate::test::test_path; #[test] fn defaults() -> Result<()> { let diagnostics = test_path( Path::new("flake8_import_conventions/defaults.py"), &LinterSettings::for_rule(Rule::UnconventionalImportAlias), )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn custom() -> Result<()> { let mut aliases = default_aliases(); aliases.extend(FxHashMap::from_iter([ ("dask.array".to_string(), "da".to_string()), ("dask.dataframe".to_string(), "dd".to_string()), ])); let diagnostics = test_path( Path::new("flake8_import_conventions/custom.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases, banned_aliases: FxHashMap::default(), banned_from: FxHashSet::default(), }, ..LinterSettings::for_rule(Rule::UnconventionalImportAlias) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn custom_banned() -> Result<()> { let diagnostics = test_path( Path::new("flake8_import_conventions/custom_banned.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases: default_aliases(), banned_aliases: FxHashMap::from_iter([ ( "typing".to_string(), BannedAliases::from_iter(["t".to_string(), "ty".to_string()]), ), ( "numpy".to_string(), BannedAliases::from_iter(["nmp".to_string(), "npy".to_string()]), ), ( "tensorflow.keras.backend".to_string(), BannedAliases::from_iter(["K".to_string()]), ), ( "torch.nn.functional".to_string(), BannedAliases::from_iter(["F".to_string()]), ), ]), banned_from: FxHashSet::default(), }, ..LinterSettings::for_rule(Rule::BannedImportAlias) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn custom_banned_from() -> Result<()> { let diagnostics = test_path( Path::new("flake8_import_conventions/custom_banned_from.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases: default_aliases(), banned_aliases: FxHashMap::default(), banned_from: FxHashSet::from_iter([ "logging.config".to_string(), "typing".to_string(), "pandas".to_string(), ]), }, ..LinterSettings::for_rule(Rule::BannedImportFrom) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn remove_defaults() -> Result<()> { let diagnostics = test_path( Path::new("flake8_import_conventions/remove_default.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases: FxHashMap::from_iter([ ("altair".to_string(), "alt".to_string()), ("matplotlib.pyplot".to_string(), "plt".to_string()), ("pandas".to_string(), "pd".to_string()), ("seaborn".to_string(), "sns".to_string()), ]), banned_aliases: FxHashMap::default(), banned_from: FxHashSet::default(), }, ..LinterSettings::for_rule(Rule::UnconventionalImportAlias) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn override_defaults() -> Result<()> { let mut aliases = default_aliases(); aliases.extend(FxHashMap::from_iter([( "numpy".to_string(), "nmp".to_string(), )])); let diagnostics = test_path( Path::new("flake8_import_conventions/override_default.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases, banned_aliases: FxHashMap::default(), banned_from: FxHashSet::default(), }, ..LinterSettings::for_rule(Rule::UnconventionalImportAlias) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn from_imports() -> Result<()> { let mut aliases = default_aliases(); aliases.extend(FxHashMap::from_iter([ ("xml.dom.minidom".to_string(), "md".to_string()), ( "xml.dom.minidom.parseString".to_string(), "pstr".to_string(), ), ])); let diagnostics = test_path( Path::new("flake8_import_conventions/from_imports.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases, banned_aliases: FxHashMap::default(), banned_from: FxHashSet::default(), }, ..LinterSettings::for_rule(Rule::UnconventionalImportAlias) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn tricky() -> Result<()> { let diagnostics = test_path( Path::new("flake8_import_conventions/tricky.py"), &LinterSettings::for_rule(Rule::UnconventionalImportAlias), )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn same_name() -> Result<()> { let mut aliases = default_aliases(); aliases.extend(FxHashMap::from_iter([( "django.conf.settings".to_string(), "settings".to_string(), )])); let diagnostics = test_path( Path::new("flake8_import_conventions/same_name.py"), &LinterSettings { flake8_import_conventions: super::settings::Settings { aliases, banned_aliases: FxHashMap::default(), banned_from: FxHashSet::default(), }, ..LinterSettings::for_rule(Rule::UnconventionalImportAlias) }, )?; assert_diagnostics!(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_import_conventions/rules/unconventional_import_alias.rs
crates/ruff_linter/src/rules/flake8_import_conventions/rules/unconventional_import_alias.rs
use rustc_hash::FxHashMap; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_semantic::{Binding, Imported}; use ruff_text_size::Ranged; use crate::checkers::ast::Checker; use crate::{Fix, FixAvailability, Violation}; use crate::renamer::Renamer; /// ## What it does /// Checks for imports that are typically imported using a common convention, /// like `import pandas as pd`, and enforces that convention. /// /// ## Why is this bad? /// Consistency is good. Use a common convention for imports to make your code /// more readable and idiomatic. /// /// For example, `import pandas as pd` is a common /// convention for importing the `pandas` library, and users typically expect /// Pandas to be aliased as `pd`. /// /// ## Example /// ```python /// import pandas /// ``` /// /// Use instead: /// ```python /// import pandas as pd /// ``` /// /// ## Options /// - `lint.flake8-import-conventions.aliases` /// - `lint.flake8-import-conventions.extend-aliases` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.166")] pub(crate) struct UnconventionalImportAlias { name: String, asname: String, } impl Violation for UnconventionalImportAlias { const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; #[derive_message_formats] fn message(&self) -> String { let UnconventionalImportAlias { name, asname } = self; format!("`{name}` should be imported as `{asname}`") } fn fix_title(&self) -> Option<String> { let UnconventionalImportAlias { name, asname } = self; Some(format!("Alias `{name}` to `{asname}`")) } } /// ICN001 pub(crate) fn unconventional_import_alias( checker: &Checker, binding: &Binding, conventions: &FxHashMap<String, String>, ) { let Some(import) = binding.as_any_import() else { return; }; let qualified_name = import.qualified_name().to_string(); let Some(expected_alias) = conventions.get(qualified_name.as_str()) else { return; }; let name = binding.name(checker.source()); if name == expected_alias { return; } let mut diagnostic = checker.report_diagnostic( UnconventionalImportAlias { name: qualified_name, asname: expected_alias.clone(), }, binding.range(), ); if !import.is_submodule_import() { if checker.semantic().is_available(expected_alias) { diagnostic.try_set_fix(|| { let scope = &checker.semantic().scopes[binding.scope]; let (edit, rest) = Renamer::rename( name, expected_alias, scope, checker.semantic(), checker.stylist(), )?; Ok(Fix::unsafe_edits(edit, rest)) }); } } }
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_import_conventions/rules/banned_import_from.rs
crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_from.rs
use rustc_hash::FxHashSet; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::Stmt; use ruff_text_size::Ranged; use crate::{Violation, checkers::ast::Checker}; /// ## What it does /// Checks for member imports that should instead be accessed by importing the /// module. /// /// ## Why is this bad? /// Consistency is good. Use a common convention for imports to make your code /// more readable and idiomatic. /// /// For example, it's common to import `pandas` as `pd`, and then access /// members like `Series` via `pd.Series`, rather than importing `Series` /// directly. /// /// ## Example /// ```python /// from pandas import Series /// ``` /// /// Use instead: /// ```python /// import pandas as pd /// /// pd.Series /// ``` /// /// ## Options /// - `lint.flake8-import-conventions.banned-from` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.263")] pub(crate) struct BannedImportFrom { name: String, } impl Violation for BannedImportFrom { #[derive_message_formats] fn message(&self) -> String { let BannedImportFrom { name } = self; format!("Members of `{name}` should not be imported explicitly") } } /// ICN003 pub(crate) fn banned_import_from( checker: &Checker, stmt: &Stmt, name: &str, banned_conventions: &FxHashSet<String>, ) { if banned_conventions.contains(name) { checker.report_diagnostic( BannedImportFrom { name: name.to_string(), }, 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/flake8_import_conventions/rules/mod.rs
crates/ruff_linter/src/rules/flake8_import_conventions/rules/mod.rs
pub(crate) use banned_import_alias::*; pub(crate) use banned_import_from::*; pub(crate) use unconventional_import_alias::*; mod banned_import_alias; mod banned_import_from; mod unconventional_import_alias;
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_import_conventions/rules/banned_import_alias.rs
crates/ruff_linter/src/rules/flake8_import_conventions/rules/banned_import_alias.rs
use rustc_hash::FxHashMap; 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; use crate::rules::flake8_import_conventions::settings::BannedAliases; /// ## What it does /// Checks for imports that use non-standard naming conventions, like /// `import tensorflow.keras.backend as K`. /// /// ## Why is this bad? /// Consistency is good. Avoid using a non-standard naming convention for /// imports, and, in particular, choosing import aliases that violate PEP 8. /// /// For example, aliasing via `import tensorflow.keras.backend as K` violates /// the guidance of PEP 8, and is thus avoided in some projects. /// /// ## Example /// ```python /// import tensorflow.keras.backend as K /// ``` /// /// Use instead: /// ```python /// import tensorflow as tf /// /// tf.keras.backend /// ``` /// /// ## Options /// - `lint.flake8-import-conventions.banned-aliases` #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.262")] pub(crate) struct BannedImportAlias { name: String, asname: String, } impl Violation for BannedImportAlias { #[derive_message_formats] fn message(&self) -> String { let BannedImportAlias { name, asname } = self; format!("`{name}` should not be imported as `{asname}`") } } /// ICN002 pub(crate) fn banned_import_alias( checker: &Checker, stmt: &Stmt, name: &str, asname: &str, banned_conventions: &FxHashMap<String, BannedAliases>, ) { if let Some(banned_aliases) = banned_conventions.get(name) { if banned_aliases .iter() .any(|banned_alias| banned_alias == asname) { checker.report_diagnostic( BannedImportAlias { name: name.to_string(), asname: asname.to_string(), }, 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/pep8_naming/settings.rs
crates/ruff_linter/src/rules/pep8_naming/settings.rs
//! Settings for the `pep8-naming` plugin. use std::error::Error; use std::fmt; use std::fmt::Formatter; use globset::{Glob, GlobSet, GlobSetBuilder}; use ruff_cache::{CacheKey, CacheKeyHasher}; use ruff_macros::CacheKey; use crate::display_settings; #[derive(Debug, Clone, CacheKey)] pub struct Settings { pub ignore_names: IgnoreNames, pub classmethod_decorators: Vec<String>, pub staticmethod_decorators: Vec<String>, } impl Default for Settings { fn default() -> Self { Self { ignore_names: IgnoreNames::Default, classmethod_decorators: Vec::new(), staticmethod_decorators: Vec::new(), } } } impl fmt::Display for Settings { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { display_settings! { formatter = f, namespace = "linter.pep8_naming", fields = [ self.ignore_names, self.classmethod_decorators | array, self.staticmethod_decorators | array ] } Ok(()) } } /// Error returned by the [`TryFrom`] implementation of [`Settings`]. #[derive(Debug)] pub enum SettingsError { InvalidIgnoreName(globset::Error), } impl fmt::Display for SettingsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SettingsError::InvalidIgnoreName(err) => { write!(f, "Invalid pattern in ignore-names: {err}") } } } } impl Error for SettingsError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { SettingsError::InvalidIgnoreName(err) => Some(err), } } } /// The default names to ignore. /// /// Must be kept in-sync with the `matches!` macro in [`IgnoreNames::matches`]. static DEFAULTS: &[&str] = &[ "setUp", "tearDown", "setUpClass", "tearDownClass", "setUpModule", "tearDownModule", "asyncSetUp", "asyncTearDown", "setUpTestData", "failureException", "longMessage", "maxDiff", ]; #[derive(Debug, Clone)] pub enum IgnoreNames { Default, UserProvided { matcher: GlobSet, literals: Vec<String>, }, } impl IgnoreNames { /// Create a new [`IgnoreNames`] from the given options. pub fn from_options( ignore_names: Option<Vec<String>>, extend_ignore_names: Option<Vec<String>>, ) -> Result<Self, SettingsError> { // If the user is not customizing the set of ignored names, use the default matcher, // which is hard-coded to avoid expensive regex matching. if ignore_names.is_none() && extend_ignore_names.as_ref().is_none_or(Vec::is_empty) { return Ok(IgnoreNames::Default); } let mut builder = GlobSetBuilder::new(); let mut literals = Vec::new(); // Add the ignored names from the `ignore-names` option. If omitted entirely, use the // defaults if let Some(names) = ignore_names { for name in names { builder.add(Glob::new(&name).map_err(SettingsError::InvalidIgnoreName)?); literals.push(name); } } else { for name in DEFAULTS { builder.add(Glob::new(name).unwrap()); literals.push((*name).to_string()); } } // Add the ignored names from the `extend-ignore-names` option. if let Some(names) = extend_ignore_names { for name in names { builder.add(Glob::new(&name).map_err(SettingsError::InvalidIgnoreName)?); literals.push(name); } } let matcher = builder.build().map_err(SettingsError::InvalidIgnoreName)?; Ok(IgnoreNames::UserProvided { matcher, literals }) } /// Returns `true` if the given name matches any of the ignored patterns. pub fn matches(&self, name: &str) -> bool { match self { IgnoreNames::Default => matches!( name, "setUp" | "tearDown" | "setUpClass" | "tearDownClass" | "setUpModule" | "tearDownModule" | "asyncSetUp" | "asyncTearDown" | "setUpTestData" | "failureException" | "longMessage" | "maxDiff" ), IgnoreNames::UserProvided { matcher, .. } => matcher.is_match(name), } } /// Create a new [`IgnoreNames`] from the given patterns. pub fn from_patterns( patterns: impl IntoIterator<Item = String>, ) -> Result<Self, SettingsError> { let mut builder = GlobSetBuilder::new(); let mut literals = Vec::new(); for name in patterns { builder.add(Glob::new(&name).map_err(SettingsError::InvalidIgnoreName)?); literals.push(name); } let matcher = builder.build().map_err(SettingsError::InvalidIgnoreName)?; Ok(IgnoreNames::UserProvided { matcher, literals }) } } impl CacheKey for IgnoreNames { fn cache_key(&self, state: &mut CacheKeyHasher) { match self { IgnoreNames::Default => { "default".cache_key(state); } IgnoreNames::UserProvided { literals: patterns, .. } => { "user-provided".cache_key(state); patterns.cache_key(state); } } } } impl fmt::Display for IgnoreNames { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { IgnoreNames::Default => { writeln!(f, "[")?; for elem in DEFAULTS { writeln!(f, "\t{elem},")?; } write!(f, "]")?; } IgnoreNames::UserProvided { literals: patterns, .. } => { writeln!(f, "[")?; for elem in patterns { writeln!(f, "\t{elem},")?; } write!(f, "]")?; } } 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/pep8_naming/helpers.rs
crates/ruff_linter/src/rules/pep8_naming/helpers.rs
use itertools::Itertools; use ruff_python_ast::name::UnqualifiedName; use ruff_python_ast::{self as ast, Expr, Stmt}; use ruff_python_semantic::{SemanticModel, analyze}; use ruff_python_stdlib::str::{is_cased_lowercase, is_cased_uppercase}; pub(super) fn is_camelcase(name: &str) -> bool { !is_cased_lowercase(name) && !is_cased_uppercase(name) && !name.contains('_') } pub(super) fn is_mixed_case(name: &str) -> bool { !is_cased_lowercase(name) && name .strip_prefix('_') .unwrap_or(name) .chars() .next() .map_or_else(|| false, char::is_lowercase) } pub(super) fn is_acronym(name: &str, asname: &str) -> bool { name.chars().filter(|c| c.is_uppercase()).join("") == asname } /// Returns `true` if the statement is an assignment to a named tuple. pub(super) fn is_named_tuple_assignment(stmt: &Stmt, semantic: &SemanticModel) -> bool { let Stmt::Assign(ast::StmtAssign { value, .. }) = stmt else { return false; }; let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else { return false; }; semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| { matches!(qualified_name.segments(), ["collections", "namedtuple"]) || semantic.match_typing_qualified_name(&qualified_name, "NamedTuple") }) } /// Returns `true` if the statement is an assignment to a `TypedDict`. pub(super) fn is_typed_dict_assignment(stmt: &Stmt, semantic: &SemanticModel) -> bool { if !semantic.seen_typing() { return false; } let Stmt::Assign(ast::StmtAssign { value, .. }) = stmt else { return false; }; let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else { return false; }; semantic.match_typing_expr(func, "TypedDict") } /// Returns `true` if the statement is an assignment to a `TypeVar` or `NewType`. pub(super) fn is_type_var_assignment(stmt: &Stmt, semantic: &SemanticModel) -> bool { if !semantic.seen_typing() { return false; } let Stmt::Assign(ast::StmtAssign { value, .. }) = stmt else { return false; }; let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else { return false; }; semantic .resolve_qualified_name(func) .is_some_and(|qualified_name| { semantic.match_typing_qualified_name(&qualified_name, "TypeVar") || semantic.match_typing_qualified_name(&qualified_name, "NewType") }) } /// Returns `true` if the statement is an assignment to a `TypeAlias`. pub(super) fn is_type_alias_assignment(stmt: &Stmt, semantic: &SemanticModel) -> bool { match stmt { Stmt::AnnAssign(ast::StmtAnnAssign { annotation, .. }) => { semantic.match_typing_expr(annotation, "TypeAlias") } Stmt::TypeAlias(_) => true, _ => false, } } /// Returns `true` if the statement is an assignment to a `TypedDict`. pub(super) fn is_typed_dict_class(class_def: &ast::StmtClassDef, semantic: &SemanticModel) -> bool { if !semantic.seen_typing() { return false; } analyze::class::any_qualified_base_class(class_def, semantic, &|qualified_name| { semantic.match_typing_qualified_name(&qualified_name, "TypedDict") }) } /// Returns `true` if a statement appears to be a dynamic import of a Django model. /// /// For example, in Django, it's common to use `get_model` to access a model dynamically, as in: /// ```python /// def migrate_existing_attachment_data( /// apps: StateApps, schema_editor: BaseDatabaseSchemaEditor /// ) -> None: /// Attachment = apps.get_model("zerver", "Attachment") /// ``` pub(super) fn is_django_model_import(name: &str, stmt: &Stmt, semantic: &SemanticModel) -> bool { fn match_model_import(name: &str, expr: &Expr, semantic: &SemanticModel) -> bool { let Expr::Call(ast::ExprCall { func, arguments, .. }) = expr else { return false; }; if arguments.is_empty() { return false; } // Match against, e.g., `apps.get_model("zerver", "Attachment")`. if let Some(unqualified_name) = UnqualifiedName::from_expr(func.as_ref()) { if matches!(unqualified_name.segments(), [.., "get_model"]) { if let Some(argument) = arguments .find_argument_value("model_name", arguments.args.len().saturating_sub(1)) { if let Some(string_literal) = argument.as_string_literal_expr() { if string_literal.value.to_str() == name { return true; } } else { return true; } } } } // Match against, e.g., `import_string("zerver.models.Attachment")`. if let Some(qualified_name) = semantic.resolve_qualified_name(func.as_ref()) { if matches!( qualified_name.segments(), ["django", "utils", "module_loading", "import_string"] ) { if let Some(argument) = arguments.find_argument_value("dotted_path", 0) { if let Some(string_literal) = argument.as_string_literal_expr() { if let Some((.., model)) = string_literal.value.to_str().rsplit_once('.') { if model == name { return true; } } } } } } false } match stmt { Stmt::AnnAssign(ast::StmtAnnAssign { value: Some(value), .. }) => match_model_import(name, value.as_ref(), semantic), Stmt::Assign(ast::StmtAssign { value, .. }) => { match_model_import(name, value.as_ref(), semantic) } _ => false, } } #[cfg(test)] mod tests { use super::{is_acronym, is_camelcase, is_mixed_case}; #[test] fn test_is_camelcase() { assert!(is_camelcase("Camel")); assert!(is_camelcase("CamelCase")); assert!(!is_camelcase("camel")); assert!(!is_camelcase("camel_case")); assert!(!is_camelcase("CAMEL")); assert!(!is_camelcase("CAMEL_CASE")); } #[test] fn test_is_mixed_case() { assert!(is_mixed_case("mixedCase")); assert!(is_mixed_case("mixed_Case")); assert!(is_mixed_case("_mixed_Case")); assert!(!is_mixed_case("mixed_case")); assert!(!is_mixed_case("MIXED_CASE")); assert!(!is_mixed_case("")); assert!(!is_mixed_case("_")); } #[test] fn test_is_acronym() { assert!(is_acronym("AB", "AB")); assert!(is_acronym("AbcDef", "AD")); assert!(!is_acronym("AbcDef", "Ad")); assert!(!is_acronym("AbcDef", "AB")); } }
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/pep8_naming/mod.rs
crates/ruff_linter/src/rules/pep8_naming/mod.rs
//! Rules from [pep8-naming](https://pypi.org/project/pep8-naming/). mod helpers; pub(crate) mod rules; pub mod settings; #[cfg(test)] mod tests { use std::path::{Path, PathBuf}; use anyhow::Result; use rustc_hash::FxHashMap; use test_case::test_case; use crate::registry::Rule; use crate::rules::pep8_naming::settings::IgnoreNames; use crate::rules::{flake8_import_conventions, pep8_naming}; use crate::test::test_path; use crate::{assert_diagnostics, settings}; #[test_case(Rule::InvalidClassName, Path::new("N801.py"))] #[test_case(Rule::InvalidFunctionName, Path::new("N802.py"))] #[test_case(Rule::InvalidArgumentName, Path::new("N803.py"))] #[test_case(Rule::InvalidArgumentName, Path::new("N804.py"))] #[test_case(Rule::InvalidFirstArgumentNameForClassMethod, Path::new("N804.py"))] #[test_case(Rule::InvalidFirstArgumentNameForMethod, Path::new("N805.py"))] #[test_case(Rule::NonLowercaseVariableInFunction, Path::new("N806.py"))] #[test_case(Rule::DunderFunctionName, Path::new("N807.py"))] #[test_case(Rule::ConstantImportedAsNonConstant, Path::new("N811.py"))] #[test_case(Rule::LowercaseImportedAsNonLowercase, Path::new("N812.py"))] #[test_case(Rule::CamelcaseImportedAsLowercase, Path::new("N813.py"))] #[test_case(Rule::CamelcaseImportedAsConstant, Path::new("N814.py"))] #[test_case(Rule::MixedCaseVariableInClassScope, Path::new("N815.py"))] #[test_case(Rule::MixedCaseVariableInGlobalScope, Path::new("N816.py"))] #[test_case(Rule::CamelcaseImportedAsAcronym, Path::new("N817.py"))] #[test_case(Rule::ErrorSuffixOnExceptionName, Path::new("N818.py"))] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/mod with spaces/__init__.py") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/mod with spaces/file.py") )] #[test_case(Rule::InvalidModuleName, Path::new("N999/module/flake9/__init__.py"))] #[test_case(Rule::InvalidModuleName, Path::new("N999/module/MODULE/__init__.py"))] #[test_case(Rule::InvalidModuleName, Path::new("N999/module/MODULE/file.py"))] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/mod-with-dashes/__init__.py") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/valid_name/__init__.py") )] #[test_case(Rule::InvalidModuleName, Path::new("N999/module/no_module/test.txt"))] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/valid_name/file-with-dashes.py") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/valid_name/__main__.py") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/invalid_name/0001_initial.py") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/valid_name/__setup__.py") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/valid_name/file-with-dashes") )] #[test_case( Rule::InvalidModuleName, Path::new("N999/module/invalid_name/import.py") )] fn rules(rule_code: Rule, path: &Path) -> Result<()> { let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy()); let diagnostics = test_path( Path::new("pep8_naming").join(path).as_path(), &settings::LinterSettings { ..settings::LinterSettings::for_rule(rule_code) }, )?; assert_diagnostics!(snapshot, diagnostics); Ok(()) } #[test] fn camelcase_imported_as_incorrect_convention() -> Result<()> { let diagnostics = test_path( Path::new("pep8_naming").join("N817.py").as_path(), &settings::LinterSettings { flake8_import_conventions: flake8_import_conventions::settings::Settings { aliases: FxHashMap::from_iter([( "xml.etree.ElementTree".to_string(), "XET".to_string(), )]), ..Default::default() }, ..settings::LinterSettings::for_rule(Rule::CamelcaseImportedAsAcronym) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn classmethod_decorators() -> Result<()> { let diagnostics = test_path( Path::new("pep8_naming").join("N805.py").as_path(), &settings::LinterSettings { pep8_naming: pep8_naming::settings::Settings { classmethod_decorators: vec![ "classmethod".to_string(), "pydantic.validator".to_string(), "expression".to_string(), ], ..Default::default() }, ..settings::LinterSettings::for_rule(Rule::InvalidFirstArgumentNameForMethod) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test] fn staticmethod_decorators() -> Result<()> { let diagnostics = test_path( Path::new("pep8_naming").join("N805.py").as_path(), &settings::LinterSettings { pep8_naming: pep8_naming::settings::Settings { staticmethod_decorators: vec![ "staticmethod".to_string(), "thisisstatic".to_string(), ], ..Default::default() }, ..settings::LinterSettings::for_rule(Rule::InvalidFirstArgumentNameForMethod) }, )?; assert_diagnostics!(diagnostics); Ok(()) } #[test_case(Rule::InvalidClassName, "N801.py")] #[test_case(Rule::InvalidFunctionName, "N802.py")] #[test_case(Rule::InvalidArgumentName, "N803.py")] #[test_case(Rule::InvalidFirstArgumentNameForClassMethod, "N804.py")] #[test_case(Rule::InvalidFirstArgumentNameForMethod, "N805.py")] #[test_case(Rule::NonLowercaseVariableInFunction, "N806.py")] #[test_case(Rule::DunderFunctionName, "N807.py")] #[test_case(Rule::ConstantImportedAsNonConstant, "N811.py")] #[test_case(Rule::LowercaseImportedAsNonLowercase, "N812.py")] #[test_case(Rule::CamelcaseImportedAsLowercase, "N813.py")] #[test_case(Rule::CamelcaseImportedAsConstant, "N814.py")] #[test_case(Rule::MixedCaseVariableInClassScope, "N815.py")] #[test_case(Rule::MixedCaseVariableInGlobalScope, "N816.py")] #[test_case(Rule::CamelcaseImportedAsAcronym, "N817.py")] #[test_case(Rule::ErrorSuffixOnExceptionName, "N818.py")] #[test_case(Rule::InvalidModuleName, "N999/badAllowed/__init__.py")] fn ignore_names(rule_code: Rule, path: &str) -> Result<()> { let snapshot = format!("ignore_names_{}_{path}", rule_code.noqa_code()); let diagnostics = test_path( PathBuf::from_iter(["pep8_naming", "ignore_names", path]).as_path(), &settings::LinterSettings { pep8_naming: pep8_naming::settings::Settings { ignore_names: IgnoreNames::from_patterns([ "*allowed*".to_string(), "*Allowed*".to_string(), "*ALLOWED*".to_string(), "BA".to_string(), // For N817. ]) .unwrap(), ..Default::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/pep8_naming/rules/invalid_class_name.rs
crates/ruff_linter/src/rules/pep8_naming/rules/invalid_class_name.rs
use ruff_python_ast::Stmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pep8_naming::settings::IgnoreNames; /// ## What it does /// Checks for class names that do not follow the `CamelCase` convention. /// /// ## Why is this bad? /// [PEP 8] recommends the use of the `CapWords` (or `CamelCase`) convention /// for class names: /// /// > Class names should normally use the `CapWords` convention. /// > /// > The naming convention for functions may be used instead in cases where the interface is /// > documented and used primarily as a callable. /// > /// > Note that there is a separate convention for builtin names: most builtin names are single /// > words (or two words run together), with the `CapWords` convention used only for exception /// > names and builtin constants. /// /// ## Example /// ```python /// class my_class: /// pass /// ``` /// /// Use instead: /// ```python /// class MyClass: /// pass /// ``` /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/#class-names #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.77")] pub(crate) struct InvalidClassName { name: String, } impl Violation for InvalidClassName { #[derive_message_formats] fn message(&self) -> String { let InvalidClassName { name } = self; format!("Class name `{name}` should use CapWords convention") } } /// N801 pub(crate) fn invalid_class_name( checker: &Checker, class_def: &Stmt, name: &str, ignore_names: &IgnoreNames, ) { let stripped = name.trim_start_matches('_'); if !stripped.chars().next().is_some_and(char::is_uppercase) || stripped.contains('_') { // Ignore any explicitly-allowed names. if ignore_names.matches(name) { return; } checker.report_diagnostic( InvalidClassName { name: name.to_string(), }, class_def.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/pep8_naming/rules/invalid_argument_name.rs
crates/ruff_linter/src/rules/pep8_naming/rules/invalid_argument_name.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{ExprLambda, Parameters, StmtFunctionDef}; use ruff_python_semantic::ScopeKind; use ruff_python_semantic::analyze::visibility::is_override; use ruff_python_stdlib::str; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; /// ## What it does /// Checks for argument names that do not follow the `snake_case` convention. /// /// ## Why is this bad? /// [PEP 8] recommends that function names should be lower case and separated /// by underscores (also known as `snake_case`). /// /// > Function names should be lowercase, with words separated by underscores /// > as necessary to improve readability. /// > /// > Variable names follow the same convention as function names. /// > /// > mixedCase is allowed only in contexts where that’s already the /// > prevailing style (e.g. threading.py), to retain backwards compatibility. /// /// Methods decorated with [`@typing.override`][override] are ignored. /// /// ## Example /// ```python /// def my_function(A, myArg): /// pass /// ``` /// /// Use instead: /// ```python /// def my_function(a, my_arg): /// pass /// ``` /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments /// [preview]: https://docs.astral.sh/ruff/preview/ /// /// [override]: https://docs.python.org/3/library/typing.html#typing.override #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.77")] pub(crate) struct InvalidArgumentName { name: String, } impl Violation for InvalidArgumentName { #[derive_message_formats] fn message(&self) -> String { let InvalidArgumentName { name } = self; format!("Argument name `{name}` should be lowercase") } } /// N803 pub(crate) fn invalid_argument_name_function(checker: &Checker, function_def: &StmtFunctionDef) { let semantic = checker.semantic(); let scope = semantic.current_scope(); if matches!(scope.kind, ScopeKind::Class(_)) && is_override(&function_def.decorator_list, semantic) { return; } invalid_argument_name(checker, &function_def.parameters); } /// N803 pub(crate) fn invalid_argument_name_lambda(checker: &Checker, lambda: &ExprLambda) { let Some(parameters) = &lambda.parameters else { return; }; invalid_argument_name(checker, parameters); } /// N803 fn invalid_argument_name(checker: &Checker, parameters: &Parameters) { let ignore_names = &checker.settings().pep8_naming.ignore_names; for parameter in parameters { let name = parameter.name().as_str(); if str::is_lowercase(name) { continue; } if ignore_names.matches(name) { continue; } checker.report_diagnostic( InvalidArgumentName { name: name.to_string(), }, parameter.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/pep8_naming/rules/mixed_case_variable_in_class_scope.rs
crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.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; use crate::rules::pep8_naming::helpers; /// ## What it does /// Checks for class variable names that follow the `mixedCase` convention. /// /// ## Why is this bad? /// [PEP 8] recommends that variable names should be lower case and separated /// by underscores (also known as `snake_case`). /// /// > Function names should be lowercase, with words separated by underscores /// > as necessary to improve readability. /// > /// > Variable names follow the same convention as function names. /// > /// > mixedCase is allowed only in contexts where that’s already the /// > prevailing style (e.g. threading.py), to retain backwards compatibility. /// /// ## Example /// ```python /// class MyClass: /// myVariable = "hello" /// another_variable = "world" /// ``` /// /// Use instead: /// ```python /// class MyClass: /// my_variable = "hello" /// another_variable = "world" /// ``` /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.89")] pub(crate) struct MixedCaseVariableInClassScope { name: String, } impl Violation for MixedCaseVariableInClassScope { #[derive_message_formats] fn message(&self) -> String { let MixedCaseVariableInClassScope { name } = self; format!("Variable `{name}` in class scope should not be mixedCase") } } /// N815 pub(crate) fn mixed_case_variable_in_class_scope( checker: &Checker, expr: &Expr, name: &str, class_def: &ast::StmtClassDef, ) { if !helpers::is_mixed_case(name) { return; } let parent = checker.semantic().current_statement(); if helpers::is_named_tuple_assignment(parent, checker.semantic()) || helpers::is_typed_dict_class(class_def, checker.semantic()) { return; } if checker.settings().pep8_naming.ignore_names.matches(name) { return; } checker.report_diagnostic( MixedCaseVariableInClassScope { name: name.to_string(), }, 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/pep8_naming/rules/error_suffix_on_exception_name.rs
crates/ruff_linter/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs
use ruff_python_ast::{self as ast, Arguments, Expr, Stmt}; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pep8_naming::settings::IgnoreNames; /// ## What it does /// Checks for custom exception definitions that omit the `Error` suffix. /// /// ## Why is this bad? /// The `Error` suffix is recommended by [PEP 8]: /// /// > Because exceptions should be classes, the class naming convention /// > applies here. However, you should use the suffix `"Error"` on your /// > exception names (if the exception actually is an error). /// /// ## Example /// /// ```python /// class Validation(Exception): ... /// ``` /// /// Use instead: /// /// ```python /// class ValidationError(Exception): ... /// ``` /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/#exception-names #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.89")] pub(crate) struct ErrorSuffixOnExceptionName { name: String, } impl Violation for ErrorSuffixOnExceptionName { #[derive_message_formats] fn message(&self) -> String { let ErrorSuffixOnExceptionName { name } = self; format!("Exception name `{name}` should be named with an Error suffix") } } /// N818 pub(crate) fn error_suffix_on_exception_name( checker: &Checker, class_def: &Stmt, arguments: Option<&Arguments>, name: &str, ignore_names: &IgnoreNames, ) { if name.ends_with("Error") { return; } if !arguments.is_some_and(|arguments| { arguments.args.iter().any(|base| { if let Expr::Name(ast::ExprName { id, .. }) = &base { id == "Exception" || id.ends_with("Error") } else { false } }) }) { return; } // Ignore any explicitly-allowed names. if ignore_names.matches(name) { return; } checker.report_diagnostic( ErrorSuffixOnExceptionName { name: name.to_string(), }, class_def.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/pep8_naming/rules/mixed_case_variable_in_global_scope.rs
crates/ruff_linter/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.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::pep8_naming::helpers; /// ## What it does /// Checks for global variable names that follow the `mixedCase` convention. /// /// ## Why is this bad? /// [PEP 8] recommends that global variable names should be lower case and /// separated by underscores (also known as `snake_case`). /// /// > ### Global Variable Names /// > (Let’s hope that these variables are meant for use inside one module /// > only.) The conventions are about the same as those for functions. /// > /// > Modules that are designed for use via `from M import *` should use the /// > `__all__` mechanism to prevent exporting globals, or use the older /// > convention of prefixing such globals with an underscore (which you might /// > want to do to indicate these globals are “module non-public”). /// > /// > ### Function and Variable Names /// > Function names should be lowercase, with words separated by underscores /// > as necessary to improve readability. /// > /// > Variable names follow the same convention as function names. /// > /// > mixedCase is allowed only in contexts where that’s already the prevailing /// > style (e.g. threading.py), to retain backwards compatibility. /// /// ## Example /// ```python /// myVariable = "hello" /// another_variable = "world" /// yet_anotherVariable = "foo" /// ``` /// /// Use instead: /// ```python /// my_variable = "hello" /// another_variable = "world" /// yet_another_variable = "foo" /// ``` /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/#global-variable-names #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.89")] pub(crate) struct MixedCaseVariableInGlobalScope { name: String, } impl Violation for MixedCaseVariableInGlobalScope { #[derive_message_formats] fn message(&self) -> String { let MixedCaseVariableInGlobalScope { name } = self; format!("Variable `{name}` in global scope should not be mixedCase") } } /// N816 pub(crate) fn mixed_case_variable_in_global_scope(checker: &Checker, expr: &Expr, name: &str) { if !helpers::is_mixed_case(name) { return; } let parent = checker.semantic().current_statement(); if helpers::is_named_tuple_assignment(parent, checker.semantic()) { return; } if checker.settings().pep8_naming.ignore_names.matches(name) { return; } checker.report_diagnostic( MixedCaseVariableInGlobalScope { name: name.to_string(), }, 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/pep8_naming/rules/constant_imported_as_non_constant.rs
crates/ruff_linter/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs
use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::{Alias, Stmt}; use ruff_python_stdlib::str; use ruff_text_size::Ranged; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pep8_naming::{helpers, settings::IgnoreNames}; /// ## What it does /// Checks for constant imports that are aliased to non-constant-style /// names. /// /// ## Why is this bad? /// [PEP 8] recommends naming conventions for classes, functions, /// constants, and more. The use of inconsistent naming styles between /// import and alias names may lead readers to expect an import to be of /// another type (e.g., confuse a Python class with a constant). /// /// Import aliases should thus follow the same naming style as the member /// being imported. /// /// ## Example /// ```python /// from example import CONSTANT_VALUE as ConstantValue /// ``` /// /// Use instead: /// ```python /// from example import CONSTANT_VALUE /// ``` /// /// ## Note /// Identifiers consisting of a single uppercase character are ambiguous under /// the rules of [PEP 8], which specifies `CamelCase` for classes and /// `ALL_CAPS_SNAKE_CASE` for constants. Without a second character, it is not /// possible to reliably guess whether the identifier is intended to be part /// of a `CamelCase` string for a class or an `ALL_CAPS_SNAKE_CASE` string for /// a constant, since both conventions will produce the same output when given /// a single input character. Therefore, this lint rule does not apply to cases /// where the imported identifier consists of a single uppercase character. /// /// A common example of a single uppercase character being used for a class /// name can be found in Django's `django.db.models.Q` class. /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.82")] pub(crate) struct ConstantImportedAsNonConstant { name: String, asname: String, } impl Violation for ConstantImportedAsNonConstant { #[derive_message_formats] fn message(&self) -> String { let ConstantImportedAsNonConstant { name, asname } = self; format!("Constant `{name}` imported as non-constant `{asname}`") } } /// N811 pub(crate) fn constant_imported_as_non_constant( checker: &Checker, name: &str, asname: &str, alias: &Alias, stmt: &Stmt, ignore_names: &IgnoreNames, ) { if str::is_cased_uppercase(name) && !(str::is_cased_uppercase(asname) // Single-character names are ambiguous. // It could be a class or a constant, so allow it to be imported // as `SCREAMING_SNAKE_CASE` *or* `CamelCase`. || (name.chars().nth(1).is_none() && helpers::is_camelcase(asname))) { // Ignore any explicitly-allowed names. if ignore_names.matches(name) || ignore_names.matches(asname) { return; } let mut diagnostic = checker.report_diagnostic( ConstantImportedAsNonConstant { name: name.to_string(), asname: asname.to_string(), }, alias.range(), ); diagnostic.set_parent(stmt.start()); } }
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/pep8_naming/rules/dunder_function_name.rs
crates/ruff_linter/src/rules/pep8_naming/rules/dunder_function_name.rs
use ruff_python_ast::Stmt; use ruff_macros::{ViolationMetadata, derive_message_formats}; use ruff_python_ast::identifier::Identifier; use ruff_python_semantic::analyze::visibility; use ruff_python_semantic::{Scope, ScopeKind}; use crate::Violation; use crate::checkers::ast::Checker; use crate::rules::pep8_naming::settings::IgnoreNames; /// ## What it does /// Checks for functions with "dunder" names (that is, names with two /// leading and trailing underscores) that are not documented. /// /// ## Why is this bad? /// [PEP 8] recommends that only documented "dunder" methods are used: /// /// > ..."magic" objects or attributes that live in user-controlled /// > namespaces. E.g. `__init__`, `__import__` or `__file__`. Never invent /// > such names; only use them as documented. /// /// ## Example /// ```python /// def __my_function__(): /// pass /// ``` /// /// Use instead: /// ```python /// def my_function(): /// pass /// ``` /// /// ## Options /// - `lint.pep8-naming.ignore-names` /// - `lint.pep8-naming.extend-ignore-names` /// /// [PEP 8]: https://peps.python.org/pep-0008/ #[derive(ViolationMetadata)] #[violation_metadata(stable_since = "v0.0.82")] pub(crate) struct DunderFunctionName; impl Violation for DunderFunctionName { #[derive_message_formats] fn message(&self) -> String { "Function name should not start and end with `__`".to_string() } } /// N807 pub(crate) fn dunder_function_name( checker: &Checker, scope: &Scope, stmt: &Stmt, name: &str, ignore_names: &IgnoreNames, ) { if matches!(scope.kind, ScopeKind::Class(_)) { return; } if !visibility::is_magic(name) { return; } // Allowed under PEP 562 (https://peps.python.org/pep-0562/). if matches!(scope.kind, ScopeKind::Module) && (name == "__getattr__" || name == "__dir__") { return; } // Ignore any explicitly-allowed names. if ignore_names.matches(name) { return; } checker.report_diagnostic(DunderFunctionName, stmt.identifier()); }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false