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_commas/rules/mod.rs | crates/ruff_linter/src/rules/flake8_commas/rules/mod.rs | pub(crate) use trailing_commas::*;
mod trailing_commas;
| 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_todos/mod.rs | crates/ruff_linter/src/rules/flake8_todos/mod.rs | pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::InvalidTodoTag, Path::new("TD001.py"))]
#[test_case(Rule::MissingTodoAuthor, Path::new("TD002.py"))]
#[test_case(Rule::MissingTodoLink, Path::new("TD003.py"))]
#[test_case(Rule::MissingTodoColon, Path::new("TD004.py"))]
#[test_case(Rule::MissingTodoDescription, Path::new("TD005.py"))]
#[test_case(Rule::InvalidTodoCapitalization, Path::new("TD006.py"))]
#[test_case(Rule::MissingSpaceAfterTodoColon, Path::new("TD007.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_todos").join(path).as_path(),
&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_todos/rules/todos.rs | crates/ruff_linter/src/rules/flake8_todos/rules/todos.rs | use std::sync::LazyLock;
use regex::RegexSet;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_trivia::CommentRanges;
use ruff_text_size::{TextLen, TextRange, TextSize};
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::directives::{TodoComment, TodoDirective, TodoDirectiveKind};
use crate::{AlwaysFixableViolation, Edit, Fix, Violation};
/// ## What it does
/// Checks that a TODO comment is labelled with "TODO".
///
/// ## Why is this bad?
/// Ambiguous tags reduce code visibility and can lead to dangling TODOs.
/// For example, if a comment is tagged with "FIXME" rather than "TODO", it may
/// be overlooked by future readers.
///
/// Note that this rule will only flag "FIXME" and "XXX" tags as incorrect.
///
/// ## Example
/// ```python
/// # FIXME(ruff): this should get fixed!
/// ```
///
/// Use instead:
/// ```python
/// # TODO(ruff): this is now fixed!
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct InvalidTodoTag {
pub tag: String,
}
impl Violation for InvalidTodoTag {
#[derive_message_formats]
fn message(&self) -> String {
let InvalidTodoTag { tag } = self;
format!("Invalid TODO tag: `{tag}`")
}
}
/// ## What it does
/// Checks that a TODO comment includes an author.
///
/// ## Why is this bad?
/// Including an author on a TODO provides future readers with context around
/// the issue. While the TODO author is not always considered responsible for
/// fixing the issue, they are typically the individual with the most context.
///
/// ## Example
/// ```python
/// # TODO: should assign an author here
/// ```
///
/// Use instead
/// ```python
/// # TODO(charlie): now an author is assigned
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct MissingTodoAuthor;
impl Violation for MissingTodoAuthor {
#[derive_message_formats]
fn message(&self) -> String {
"Missing author in TODO; try: `# TODO(<author_name>): ...` or `# TODO @<author_name>: ...`"
.to_string()
}
}
/// ## What it does
/// Checks that a TODO comment is associated with a link to a relevant issue
/// or ticket.
///
/// ## Why is this bad?
/// Including an issue link near a TODO makes it easier for resolvers
/// to get context around the issue.
///
/// ## Example
/// ```python
/// # TODO: this link has no issue
/// ```
///
/// Use one of these instead:
/// ```python
/// # TODO(charlie): this comment has an issue link
/// # https://github.com/astral-sh/ruff/issues/3870
///
/// # TODO(charlie): this comment has a 3-digit issue code
/// # 003
///
/// # TODO(charlie): https://github.com/astral-sh/ruff/issues/3870
/// # this comment has an issue link
///
/// # TODO(charlie): #003 this comment has a 3-digit issue code
/// # with leading character `#`
///
/// # TODO(charlie): this comment has an issue code (matches the regex `[A-Z]+\-?\d+`)
/// # SIXCHR-003
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct MissingTodoLink;
impl Violation for MissingTodoLink {
#[derive_message_formats]
fn message(&self) -> String {
"Missing issue link for this TODO".to_string()
}
}
/// ## What it does
/// Checks that a "TODO" tag is followed by a colon.
///
/// ## Why is this bad?
/// "TODO" tags are typically followed by a parenthesized author name, a colon,
/// a space, and a description of the issue, in that order.
///
/// Deviating from this pattern can lead to inconsistent and non-idiomatic
/// comments.
///
/// ## Example
/// ```python
/// # TODO(charlie) fix this colon
/// ```
///
/// Used instead:
/// ```python
/// # TODO(charlie): colon fixed
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct MissingTodoColon;
impl Violation for MissingTodoColon {
#[derive_message_formats]
fn message(&self) -> String {
"Missing colon in TODO".to_string()
}
}
/// ## What it does
/// Checks that a "TODO" tag contains a description of the issue following the
/// tag itself.
///
/// ## Why is this bad?
/// TODO comments should include a description of the issue to provide context
/// for future readers.
///
/// ## Example
/// ```python
/// # TODO(charlie)
/// ```
///
/// Use instead:
/// ```python
/// # TODO(charlie): fix some issue
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct MissingTodoDescription;
impl Violation for MissingTodoDescription {
#[derive_message_formats]
fn message(&self) -> String {
"Missing issue description after `TODO`".to_string()
}
}
/// ## What it does
/// Checks that a "TODO" tag is properly capitalized (i.e., that the tag is
/// uppercase).
///
/// ## Why is this bad?
/// Capitalizing the "TODO" in a TODO comment is a convention that makes it
/// easier for future readers to identify TODOs.
///
/// ## Example
/// ```python
/// # todo(charlie): capitalize this
/// ```
///
/// Use instead:
/// ```python
/// # TODO(charlie): this is capitalized
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct InvalidTodoCapitalization {
tag: String,
}
impl AlwaysFixableViolation for InvalidTodoCapitalization {
#[derive_message_formats]
fn message(&self) -> String {
let InvalidTodoCapitalization { tag } = self;
format!("Invalid TODO capitalization: `{tag}` should be `TODO`")
}
fn fix_title(&self) -> String {
let InvalidTodoCapitalization { tag } = self;
format!("Replace `{tag}` with `TODO`")
}
}
/// ## What it does
/// Checks that the colon after a "TODO" tag is followed by a space.
///
/// ## Why is this bad?
/// "TODO" tags are typically followed by a parenthesized author name, a colon,
/// a space, and a description of the issue, in that order.
///
/// Deviating from this pattern can lead to inconsistent and non-idiomatic
/// comments.
///
/// ## Example
/// ```python
/// # TODO(charlie):fix this
/// ```
///
/// Use instead:
/// ```python
/// # TODO(charlie): fix this
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct MissingSpaceAfterTodoColon;
impl Violation for MissingSpaceAfterTodoColon {
#[derive_message_formats]
fn message(&self) -> String {
"Missing space after colon in TODO".to_string()
}
}
static ISSUE_LINK_OWN_LINE_REGEX_SET: LazyLock<RegexSet> = LazyLock::new(|| {
RegexSet::new([
r"^#\s*(http|https)://.*", // issue link
r"^#\s*\d+$", // issue code - like "003"
r"^#\s*[A-Z]+\-?\d+$", // issue code - like "TD003"
])
.unwrap()
});
static ISSUE_LINK_TODO_LINE_REGEX_SET: LazyLock<RegexSet> = LazyLock::new(|| {
RegexSet::new([
r"\s*(http|https)://.*", // issue link
r"\s*#\d+.*", // issue code - like "#003"
])
.unwrap()
});
pub(crate) fn todos(
context: &LintContext,
todo_comments: &[TodoComment],
locator: &Locator,
comment_ranges: &CommentRanges,
) {
for todo_comment in todo_comments {
let TodoComment {
directive,
content,
range_index,
..
} = todo_comment;
let range = todo_comment.range;
// flake8-todos doesn't support HACK directives.
if matches!(directive.kind, TodoDirectiveKind::Hack) {
continue;
}
directive_errors(context, directive);
static_errors(context, content, range, directive);
let mut has_issue_link = false;
// VSCode recommended links on same line are ok:
// `# TODO(dylan): #1234`
if ISSUE_LINK_TODO_LINE_REGEX_SET
.is_match(locator.slice(TextRange::new(directive.range.end(), range.end())))
{
continue;
}
let mut curr_range = range;
for next_range in comment_ranges.iter().skip(range_index + 1).copied() {
// Ensure that next_comment_range is in the same multiline comment "block" as
// comment_range.
if !locator
.slice(TextRange::new(curr_range.end(), next_range.start()))
.chars()
.all(char::is_whitespace)
{
break;
}
let next_comment = locator.slice(next_range);
if TodoDirective::from_comment(next_comment, next_range).is_some() {
break;
}
if ISSUE_LINK_OWN_LINE_REGEX_SET.is_match(next_comment) {
has_issue_link = true;
}
// If the next_comment isn't a tag or an issue, it's worthless in the context of this
// linter. We can increment here instead of waiting for the next iteration of the outer
// loop.
curr_range = next_range;
}
if !has_issue_link {
// TD003
context.report_diagnostic_if_enabled(MissingTodoLink, directive.range);
}
}
}
/// Check that the directive itself is valid. This function modifies `diagnostics` in-place.
fn directive_errors(context: &LintContext, directive: &TodoDirective) {
if directive.content == "TODO" {
return;
}
if directive.content.to_uppercase() == "TODO" {
// TD006
if let Some(mut diagnostic) = context.report_diagnostic_if_enabled(
InvalidTodoCapitalization {
tag: directive.content.to_string(),
},
directive.range,
) {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
"TODO".to_string(),
directive.range,
)));
}
} else {
// TD001
context.report_diagnostic_if_enabled(
InvalidTodoTag {
tag: directive.content.to_string(),
},
directive.range,
);
}
}
/// Checks for "static" errors in the comment: missing colon, missing author, etc.
pub(crate) fn static_errors(
context: &LintContext,
comment: &str,
comment_range: TextRange,
directive: &TodoDirective,
) {
let post_directive = &comment[usize::from(directive.range.end() - comment_range.start())..];
let trimmed = post_directive.trim_start();
let content_offset = post_directive.text_len() - trimmed.text_len();
let author_end = content_offset
+ if trimmed.starts_with('(') {
if let Some(end_index) = trimmed.find(')') {
TextSize::try_from(end_index + 1).unwrap()
} else {
trimmed.text_len()
}
} else if trimmed.starts_with('@') {
if let Some(end_index) = trimmed.find(|c: char| c.is_whitespace() || c == ':') {
TextSize::try_from(end_index).unwrap()
} else {
// TD002
context.report_diagnostic_if_enabled(MissingTodoAuthor, directive.range);
TextSize::new(0)
}
} else {
// TD002
context.report_diagnostic_if_enabled(MissingTodoAuthor, directive.range);
TextSize::new(0)
};
let after_author = &post_directive[usize::from(author_end)..];
if let Some(after_colon) = after_author.strip_prefix(':') {
if after_colon.is_empty() {
// TD005
context.report_diagnostic_if_enabled(MissingTodoDescription, directive.range);
} else if !after_colon.starts_with(char::is_whitespace) {
// TD007
context.report_diagnostic_if_enabled(MissingSpaceAfterTodoColon, directive.range);
}
} else {
// TD004
context.report_diagnostic_if_enabled(MissingTodoColon, directive.range);
if after_author.is_empty() {
// TD005
context.report_diagnostic_if_enabled(MissingTodoDescription, directive.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_todos/rules/mod.rs | crates/ruff_linter/src/rules/flake8_todos/rules/mod.rs | pub(crate) use todos::*;
mod todos;
| 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/fastapi/mod.rs | crates/ruff_linter/src/rules/fastapi/mod.rs | //! FastAPI-specific rules.
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use ruff_python_ast::PythonVersion;
use crate::registry::Rule;
use crate::settings::LinterSettings;
use crate::test::test_path;
use crate::{assert_diagnostics, assert_diagnostics_diff};
#[test_case(Rule::FastApiRedundantResponseModel, Path::new("FAST001.py"))]
#[test_case(Rule::FastApiNonAnnotatedDependency, Path::new("FAST002_0.py"))]
#[test_case(Rule::FastApiNonAnnotatedDependency, Path::new("FAST002_1.py"))]
#[test_case(Rule::FastApiNonAnnotatedDependency, Path::new("FAST002_2.py"))]
#[test_case(Rule::FastApiUnusedPathParameter, Path::new("FAST003.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("fastapi").join(path).as_path(),
&LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::FastApiRedundantResponseModel, Path::new("FAST001.py"))]
#[test_case(Rule::FastApiUnusedPathParameter, Path::new("FAST003.py"))]
fn deferred_annotations_diff(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"deferred_annotations_diff_{}_{}",
rule_code.name(),
path.to_string_lossy()
);
assert_diagnostics_diff!(
snapshot,
Path::new("fastapi").join(path).as_path(),
&LinterSettings {
unresolved_target_version: PythonVersion::PY313.into(),
..LinterSettings::for_rule(rule_code)
},
&LinterSettings {
unresolved_target_version: PythonVersion::PY314.into(),
..LinterSettings::for_rule(rule_code)
},
);
Ok(())
}
// FAST002 autofixes use `typing_extensions` on Python 3.8,
// since `typing.Annotated` was added in Python 3.9
#[test_case(Rule::FastApiNonAnnotatedDependency, Path::new("FAST002_0.py"))]
#[test_case(Rule::FastApiNonAnnotatedDependency, Path::new("FAST002_1.py"))]
#[test_case(Rule::FastApiNonAnnotatedDependency, Path::new("FAST002_2.py"))]
fn rules_py38(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}_py38", rule_code.name(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("fastapi").join(path).as_path(),
&LinterSettings {
unresolved_target_version: PythonVersion::PY38.into(),
..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/fastapi/rules/fastapi_unused_path_parameter.rs | crates/ruff_linter/src/rules/fastapi/rules/fastapi_unused_path_parameter.rs | use std::ops::Range;
use std::sync::LazyLock;
use regex::{CaptureMatches, Regex};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::{Arguments, Expr, ExprCall, ExprSubscript, Parameter, ParameterWithDefault};
use ruff_python_semantic::{BindingKind, Modules, ScopeKind, SemanticModel};
use ruff_python_stdlib::identifiers::is_identifier;
use ruff_text_size::{Ranged, TextSize};
use crate::Fix;
use crate::checkers::ast::Checker;
use crate::fix::edits::add_parameter;
use crate::rules::fastapi::rules::is_fastapi_route_decorator;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Identifies FastAPI routes that declare path parameters in the route path
/// that are not included in the function signature.
///
/// ## Why is this bad?
/// Path parameters are used to extract values from the URL path.
///
/// If a path parameter is declared in the route path but not in the function
/// signature, it will not be accessible in the function body, which is likely
/// a mistake.
///
/// If a path parameter is declared in the route path, but as a positional-only
/// argument in the function signature, it will also not be accessible in the
/// function body, as FastAPI will not inject the parameter.
///
/// ## Known problems
/// If the path parameter is _not_ a valid Python identifier (e.g., `user-id`, as
/// opposed to `user_id`), FastAPI will normalize it. However, this rule simply
/// ignores such path parameters, as FastAPI's normalization behavior is undocumented.
///
/// ## Example
///
/// ```python
/// from fastapi import FastAPI
///
/// app = FastAPI()
///
///
/// @app.get("/things/{thing_id}")
/// async def read_thing(query: str): ...
/// ```
///
/// Use instead:
///
/// ```python
/// from fastapi import FastAPI
///
/// app = FastAPI()
///
///
/// @app.get("/things/{thing_id}")
/// async def read_thing(thing_id: int, query: str): ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as modifying a function signature can
/// change the behavior of the code.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct FastApiUnusedPathParameter {
arg_name: String,
function_name: String,
is_positional: bool,
}
impl Violation for FastApiUnusedPathParameter {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let Self {
arg_name,
function_name,
is_positional,
} = self;
if !is_positional {
format!(
"Parameter `{arg_name}` appears in route path, but not in `{function_name}` signature"
)
} else {
format!(
"Parameter `{arg_name}` appears in route path, but only as a positional-only argument in `{function_name}` signature"
)
}
}
fn fix_title(&self) -> Option<String> {
let Self {
arg_name,
is_positional,
..
} = self;
if *is_positional {
None
} else {
Some(format!("Add `{arg_name}` to function signature"))
}
}
}
/// FAST003
pub(crate) fn fastapi_unused_path_parameter(
checker: &Checker,
function_def: &ast::StmtFunctionDef,
) {
if !checker.semantic().seen_module(Modules::FASTAPI) {
return;
}
// Get the route path from the decorator.
let route_decorator = function_def
.decorator_list
.iter()
.find_map(|decorator| is_fastapi_route_decorator(decorator, checker.semantic()));
let Some(route_decorator) = route_decorator else {
return;
};
let Some(path_arg) = route_decorator.arguments.args.first() else {
return;
};
let diagnostic_range = path_arg.range();
// We can't really handle anything other than string literals.
let path = match path_arg.as_string_literal_expr() {
Some(path_arg) => &path_arg.value,
None => return,
};
// Extract the path parameters from the route path.
let path_params = PathParamIterator::new(path.to_str());
// Extract the arguments from the function signature
let mut named_args = vec![];
for parameter_with_default in non_posonly_non_variadic_parameters(function_def) {
let ParameterWithDefault { parameter, .. } = parameter_with_default;
if let Some(alias) = parameter_alias(parameter, checker.semantic()) {
named_args.push(alias);
} else {
named_args.push(parameter.name.as_str());
}
let Some(dependency) =
Dependency::from_parameter(parameter_with_default, checker.semantic())
else {
continue;
};
if let Some(parameter_names) = dependency.parameter_names() {
named_args.extend_from_slice(parameter_names);
} else {
// If we can't determine the dependency, we can't really do anything.
return;
}
}
// Check if any of the path parameters are not in the function signature.
for (path_param, range) in path_params {
// If the path parameter is already in the function or the dependency signature,
// we don't need to do anything.
if named_args.contains(&path_param) {
continue;
}
// Determine whether the path parameter is used as a positional-only argument. In this case,
// the path parameter injection won't work, but we also can't fix it (yet), since we'd need
// to make the parameter non-positional-only.
let is_positional = function_def
.parameters
.posonlyargs
.iter()
.any(|param| param.name() == path_param);
let mut diagnostic = checker.report_diagnostic(
FastApiUnusedPathParameter {
arg_name: path_param.to_string(),
function_name: function_def.name.to_string(),
is_positional,
},
#[expect(clippy::cast_possible_truncation)]
diagnostic_range
.add_start(TextSize::from(range.start as u32 + 1))
.sub_end(TextSize::from((path.len() - range.end + 1) as u32)),
);
if !is_positional && is_identifier(path_param) && path_param != "__debug__" {
diagnostic.set_fix(Fix::unsafe_edit(add_parameter(
path_param,
&function_def.parameters,
checker.locator().contents(),
)));
}
}
}
/// Returns an iterator over the non-positional-only, non-variadic parameters of a function.
fn non_posonly_non_variadic_parameters(
function_def: &ast::StmtFunctionDef,
) -> impl Iterator<Item = &ParameterWithDefault> {
function_def
.parameters
.args
.iter()
.chain(&function_def.parameters.kwonlyargs)
}
#[derive(Debug, is_macro::Is)]
enum Dependency<'a> {
/// Not defined in the same file, or otherwise cannot be determined to be a function.
Unknown,
/// A function defined in the same file, whose parameter names are as given.
Function(Vec<&'a str>),
/// A class defined in the same file, whose constructor parameter names are as given.
Class(Vec<&'a str>),
/// There are multiple `Depends()` calls.
///
/// Multiple `Depends` annotations aren't supported by fastapi and the exact behavior is
/// [unspecified](https://github.com/astral-sh/ruff/pull/15364#discussion_r1912551710).
Multiple,
}
impl<'a> Dependency<'a> {
fn parameter_names(&self) -> Option<&[&'a str]> {
match self {
Self::Unknown => None,
Self::Multiple => None,
Self::Function(parameter_names) => Some(parameter_names.as_slice()),
Self::Class(parameter_names) => Some(parameter_names.as_slice()),
}
}
}
impl<'a> Dependency<'a> {
/// Return `foo` in the first metadata `Depends(foo)`,
/// or that of the default value:
///
/// ```python
/// def _(
/// a: Annotated[str, Depends(foo)],
/// # ^^^^^^^^^^^^
/// a: str = Depends(foo),
/// # ^^^^^^^^^^^^
/// ): ...
/// ```
fn from_parameter(
parameter: &'a ParameterWithDefault,
semantic: &SemanticModel<'a>,
) -> Option<Self> {
if let Some(dependency) = parameter
.default()
.and_then(|default| Self::from_default(default, semantic))
{
return Some(dependency);
}
let ExprSubscript { value, slice, .. } = parameter.annotation()?.as_subscript_expr()?;
if !semantic.match_typing_expr(value, "Annotated") {
return None;
}
let Expr::Tuple(tuple) = slice.as_ref() else {
return None;
};
let mut dependencies = tuple.elts.iter().skip(1).filter_map(|metadata_element| {
let arguments = depends_arguments(metadata_element, semantic)?;
// Arguments to `Depends` can be empty if the dependency is a class
// that FastAPI will call to create an instance of the class itself.
// https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/#shortcut
if arguments.is_empty() {
Self::from_dependency_name(tuple.elts.first()?.as_name_expr()?, semantic)
} else {
Self::from_depends_call(arguments, semantic)
}
});
let dependency = dependencies.next()?;
if dependencies.next().is_some() {
Some(Self::Multiple)
} else {
Some(dependency)
}
}
fn from_default(expr: &'a Expr, semantic: &SemanticModel<'a>) -> Option<Self> {
let arguments = depends_arguments(expr, semantic)?;
Self::from_depends_call(arguments, semantic)
}
fn from_depends_call(arguments: &'a Arguments, semantic: &SemanticModel<'a>) -> Option<Self> {
let Some(Expr::Name(name)) = arguments.find_argument_value("dependency", 0) else {
return None;
};
Self::from_dependency_name(name, semantic)
}
fn from_dependency_name(name: &'a ast::ExprName, semantic: &SemanticModel<'a>) -> Option<Self> {
let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else {
return Some(Self::Unknown);
};
match binding.kind {
BindingKind::FunctionDefinition(scope_id) => {
let scope = &semantic.scopes[scope_id];
let ScopeKind::Function(function_def) = scope.kind else {
return Some(Self::Unknown);
};
let parameter_names = non_posonly_non_variadic_parameters(function_def)
.map(|param| param.name().as_str())
.collect();
Some(Self::Function(parameter_names))
}
BindingKind::ClassDefinition(scope_id) => {
let scope = &semantic.scopes[scope_id];
let ScopeKind::Class(class_def) = scope.kind else {
return Some(Self::Unknown);
};
let parameter_names = if class_def
.bases()
.iter()
.any(|expr| is_pydantic_base_model(expr, semantic))
{
class_def
.body
.iter()
.filter_map(|stmt| {
stmt.as_ann_assign_stmt()
.and_then(|ann_assign| ann_assign.target.as_name_expr())
.map(|name| name.id.as_str())
})
.collect()
} else if let Some(init_def) = class_def
.body
.iter()
.filter_map(|stmt| stmt.as_function_def_stmt())
.find(|func_def| func_def.name.as_str() == "__init__")
{
// Skip `self` parameter
non_posonly_non_variadic_parameters(init_def)
.skip(1)
.map(|param| param.name().as_str())
.collect()
} else {
return None;
};
Some(Self::Class(parameter_names))
}
_ => Some(Self::Unknown),
}
}
}
fn depends_arguments<'a>(expr: &'a Expr, semantic: &SemanticModel) -> Option<&'a Arguments> {
let Expr::Call(ExprCall {
func, arguments, ..
}) = expr
else {
return None;
};
if !is_fastapi_depends(func.as_ref(), semantic) {
return None;
}
Some(arguments)
}
fn is_fastapi_depends(expr: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["fastapi", "Depends"]))
}
fn is_pydantic_base_model(expr: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(expr)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["pydantic", "BaseModel"])
})
}
/// Extract the expected in-route name for a given parameter, if it has an alias.
/// For example, given `document_id: Annotated[str, Path(alias="documentId")]`, returns `"documentId"`.
fn parameter_alias<'a>(parameter: &'a Parameter, semantic: &SemanticModel) -> Option<&'a str> {
let Some(annotation) = ¶meter.annotation else {
return None;
};
let Expr::Subscript(subscript) = annotation.as_ref() else {
return None;
};
let Expr::Tuple(tuple) = subscript.slice.as_ref() else {
return None;
};
let Some(Expr::Call(path)) = tuple.elts.get(1) else {
return None;
};
// Find the `alias` keyword argument.
let alias = path
.arguments
.find_keyword("alias")
.map(|alias| &alias.value)?;
// Ensure that it's a literal string.
let Expr::StringLiteral(alias) = alias else {
return None;
};
// Verify that the subscript was a `typing.Annotated`.
if !semantic.match_typing_expr(&subscript.value, "Annotated") {
return None;
}
// Verify that the call was a `fastapi.Path`.
if !semantic
.resolve_qualified_name(&path.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["fastapi", "Path"]))
{
return None;
}
Some(alias.value.to_str())
}
/// An iterator to extract parameters from FastAPI route paths.
///
/// The iterator yields tuples of the parameter name and the range of the parameter in the input,
/// inclusive of curly braces.
///
/// FastAPI only recognizes path parameters when there are no leading or trailing spaces around
/// the parameter name. For example, `/{x}` is a valid parameter, but `/{ x }` is treated literally.
#[derive(Debug)]
struct PathParamIterator<'a> {
inner: CaptureMatches<'a, 'a>,
}
impl<'a> PathParamIterator<'a> {
fn new(input: &'a str) -> Self {
/// Matches the Starlette pattern for path parameters with optional converters from
/// <https://github.com/Kludex/starlette/blob/e18637c68e36d112b1983bc0c8b663681e6a4c50/starlette/routing.py#L121>
static FASTAPI_PATH_PARAM_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"\{([a-zA-Z_][a-zA-Z0-9_]*)(?::[a-zA-Z_][a-zA-Z0-9_]*)?\}").unwrap()
});
Self {
inner: FASTAPI_PATH_PARAM_REGEX.captures_iter(input),
}
}
}
impl<'a> Iterator for PathParamIterator<'a> {
type Item = (&'a str, Range<usize>);
fn next(&mut self) -> Option<Self::Item> {
self.inner
.next()
// Extract the first capture group (the path parameter), but return the range of the
// whole match (everything in braces and including the braces themselves).
.and_then(|capture| Some((capture.get(1)?.as_str(), capture.get(0)?.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/fastapi/rules/fastapi_redundant_response_model.rs | crates/ruff_linter/src/rules/fastapi/rules/fastapi_redundant_response_model.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Decorator, Expr, ExprCall, Keyword, StmtFunctionDef};
use ruff_python_semantic::{Modules, SemanticModel};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::rules::fastapi::rules::is_fastapi_route_decorator;
use crate::{AlwaysFixableViolation, Fix};
/// ## What it does
/// Checks for FastAPI routes that use the optional `response_model` parameter
/// with the same type as the return type.
///
/// ## Why is this bad?
/// FastAPI routes automatically infer the response model type from the return
/// type, so specifying it explicitly is redundant.
///
/// The `response_model` parameter is used to override the default response
/// model type. For example, `response_model` can be used to specify that
/// a non-serializable response type should instead be serialized via an
/// alternative type.
///
/// For more information, see the [FastAPI documentation](https://fastapi.tiangolo.com/tutorial/response-model/).
///
/// ## Example
///
/// ```python
/// from fastapi import FastAPI
/// from pydantic import BaseModel
///
/// app = FastAPI()
///
///
/// class Item(BaseModel):
/// name: str
///
///
/// @app.post("/items/", response_model=Item)
/// async def create_item(item: Item) -> Item:
/// return item
/// ```
///
/// Use instead:
///
/// ```python
/// from fastapi import FastAPI
/// from pydantic import BaseModel
///
/// app = FastAPI()
///
///
/// class Item(BaseModel):
/// name: str
///
///
/// @app.post("/items/")
/// async def create_item(item: Item) -> Item:
/// return item
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.8.0")]
pub(crate) struct FastApiRedundantResponseModel;
impl AlwaysFixableViolation for FastApiRedundantResponseModel {
#[derive_message_formats]
fn message(&self) -> String {
"FastAPI route with redundant `response_model` argument".to_string()
}
fn fix_title(&self) -> String {
"Remove argument".to_string()
}
}
/// FAST001
pub(crate) fn fastapi_redundant_response_model(checker: &Checker, function_def: &StmtFunctionDef) {
if !checker.semantic().seen_module(Modules::FASTAPI) {
return;
}
for decorator in &function_def.decorator_list {
let Some((call, response_model_arg)) =
check_decorator(function_def, decorator, checker.semantic())
else {
continue;
};
let mut diagnostic =
checker.report_diagnostic(FastApiRedundantResponseModel, response_model_arg.range());
diagnostic.try_set_fix(|| {
remove_argument(
response_model_arg,
&call.arguments,
Parentheses::Preserve,
checker.source(),
checker.tokens(),
)
.map(Fix::unsafe_edit)
});
}
}
fn check_decorator<'a>(
function_def: &StmtFunctionDef,
decorator: &'a Decorator,
semantic: &'a SemanticModel,
) -> Option<(&'a ExprCall, &'a Keyword)> {
let call = is_fastapi_route_decorator(decorator, semantic)?;
let response_model_arg = call.arguments.find_keyword("response_model")?;
let return_value = function_def.returns.as_ref()?;
if is_identical_types(&response_model_arg.value, return_value, semantic) {
Some((call, response_model_arg))
} else {
None
}
}
fn is_identical_types(
response_model_arg: &Expr,
return_value: &Expr,
semantic: &SemanticModel,
) -> bool {
if let (Expr::Name(response_mode_name_expr), Expr::Name(return_value_name_expr)) =
(response_model_arg, return_value)
{
return semantic.resolve_name(response_mode_name_expr)
== semantic.resolve_name(return_value_name_expr);
}
if let (Expr::Subscript(response_mode_subscript), Expr::Subscript(return_value_subscript)) =
(response_model_arg, return_value)
{
return is_identical_types(
&response_mode_subscript.value,
&return_value_subscript.value,
semantic,
) && is_identical_types(
&response_mode_subscript.slice,
&return_value_subscript.slice,
semantic,
);
}
if let (Expr::Tuple(response_mode_tuple), Expr::Tuple(return_value_tuple)) =
(response_model_arg, return_value)
{
return response_mode_tuple.len() == return_value_tuple.len()
&& response_mode_tuple
.iter()
.zip(return_value_tuple)
.all(|(x, y)| is_identical_types(x, y, semantic));
}
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/fastapi/rules/mod.rs | crates/ruff_linter/src/rules/fastapi/rules/mod.rs | pub(crate) use fastapi_non_annotated_dependency::*;
pub(crate) use fastapi_redundant_response_model::*;
pub(crate) use fastapi_unused_path_parameter::*;
mod fastapi_non_annotated_dependency;
mod fastapi_redundant_response_model;
mod fastapi_unused_path_parameter;
use ruff_python_ast as ast;
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::typing;
/// Returns `true` if the function is a FastAPI route.
pub(crate) fn is_fastapi_route(
function_def: &ast::StmtFunctionDef,
semantic: &SemanticModel,
) -> bool {
function_def
.decorator_list
.iter()
.any(|decorator| is_fastapi_route_decorator(decorator, semantic).is_some())
}
/// Returns `true` if the decorator is indicative of a FastAPI route.
pub(crate) fn is_fastapi_route_decorator<'a>(
decorator: &'a ast::Decorator,
semantic: &'a SemanticModel,
) -> Option<&'a ast::ExprCall> {
let call = decorator.expression.as_call_expr()?;
is_fastapi_route_call(call, semantic).then_some(call)
}
pub(crate) fn is_fastapi_route_call(call_expr: &ast::ExprCall, semantic: &SemanticModel) -> bool {
let ast::Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = &*call_expr.func else {
return false;
};
if !matches!(
attr.as_str(),
"get" | "post" | "put" | "delete" | "patch" | "options" | "head" | "trace"
) {
return false;
}
let Some(name) = value.as_name_expr() else {
return false;
};
let Some(binding_id) = semantic.resolve_name(name) else {
return false;
};
typing::is_fastapi_route(semantic.binding(binding_id), 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/fastapi/rules/fastapi_non_annotated_dependency.rs | crates/ruff_linter/src/rules/fastapi/rules/fastapi_non_annotated_dependency.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::helpers::map_callable;
use ruff_python_semantic::Modules;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::rules::fastapi::rules::is_fastapi_route;
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
/// ## What it does
/// Identifies FastAPI routes with deprecated uses of `Depends` or similar.
///
/// ## Why is this bad?
/// The [FastAPI documentation] recommends the use of [`typing.Annotated`][typing-annotated]
/// for defining route dependencies and parameters, rather than using `Depends`,
/// `Query` or similar as a default value for a parameter. Using this approach
/// everywhere helps ensure consistency and clarity in defining dependencies
/// and parameters.
///
/// `Annotated` was added to the `typing` module in Python 3.9; however,
/// the third-party [`typing_extensions`][typing-extensions] package
/// provides a backport that can be used on older versions of Python.
///
/// ## Example
///
/// ```python
/// from fastapi import Depends, FastAPI
///
/// app = FastAPI()
///
///
/// async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
/// return {"q": q, "skip": skip, "limit": limit}
///
///
/// @app.get("/items/")
/// async def read_items(commons: dict = Depends(common_parameters)):
/// return commons
/// ```
///
/// Use instead:
///
/// ```python
/// from typing import Annotated
///
/// from fastapi import Depends, FastAPI
///
/// app = FastAPI()
///
///
/// async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
/// return {"q": q, "skip": skip, "limit": limit}
///
///
/// @app.get("/items/")
/// async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
/// return commons
/// ```
///
/// ## Fix safety
/// This fix is always unsafe, as adding/removing/changing a function parameter's
/// default value can change runtime behavior. Additionally, comments inside the
/// deprecated uses might be removed.
///
/// ## Availability
///
/// Because this rule relies on the third-party `typing_extensions` module for Python versions
/// before 3.9, if the target version is < 3.9 and `typing_extensions` imports have been
/// disabled by the [`lint.typing-extensions`] linter option the diagnostic will not be emitted
/// and no fix will be offered.
///
/// ## Options
///
/// - `lint.typing-extensions`
///
/// [FastAPI documentation]: https://fastapi.tiangolo.com/tutorial/query-params-str-validations/?h=annotated#advantages-of-annotated
/// [typing-annotated]: https://docs.python.org/3/library/typing.html#typing.Annotated
/// [typing-extensions]: https://typing-extensions.readthedocs.io/en/stable/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.8.0")]
pub(crate) struct FastApiNonAnnotatedDependency {
py_version: PythonVersion,
}
impl Violation for FastApiNonAnnotatedDependency {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"FastAPI dependency without `Annotated`".to_string()
}
fn fix_title(&self) -> Option<String> {
let title = if self.py_version >= PythonVersion::PY39 {
"Replace with `typing.Annotated`"
} else {
"Replace with `typing_extensions.Annotated`"
};
Some(title.to_string())
}
}
/// FAST002
pub(crate) fn fastapi_non_annotated_dependency(
checker: &Checker,
function_def: &ast::StmtFunctionDef,
) {
if !checker.semantic().seen_module(Modules::FASTAPI)
|| !is_fastapi_route(function_def, checker.semantic())
{
return;
}
// `create_diagnostic` needs to know if a default argument has been seen to
// avoid emitting fixes that would remove defaults and cause a syntax error.
let mut seen_default = false;
for parameter in function_def
.parameters
.args
.iter()
.chain(&function_def.parameters.kwonlyargs)
{
let (Some(annotation), Some(default)) = (parameter.annotation(), parameter.default())
else {
seen_default |= parameter.default.is_some();
continue;
};
if let Some(dependency) = is_fastapi_dependency(checker, default) {
let dependency_call = DependencyCall::from_expression(default);
let dependency_parameter = DependencyParameter {
annotation,
default,
kind: dependency,
name: parameter.name(),
range: parameter.range,
};
seen_default = create_diagnostic(
checker,
&dependency_parameter,
dependency_call,
seen_default,
);
} else {
seen_default |= parameter.default.is_some();
}
}
}
fn is_fastapi_dependency(checker: &Checker, expr: &ast::Expr) -> Option<FastApiDependency> {
checker
.semantic()
.resolve_qualified_name(map_callable(expr))
.and_then(|qualified_name| match qualified_name.segments() {
["fastapi", dependency_name] => match *dependency_name {
"Query" => Some(FastApiDependency::Query),
"Path" => Some(FastApiDependency::Path),
"Body" => Some(FastApiDependency::Body),
"Cookie" => Some(FastApiDependency::Cookie),
"Header" => Some(FastApiDependency::Header),
"File" => Some(FastApiDependency::File),
"Form" => Some(FastApiDependency::Form),
"Depends" => Some(FastApiDependency::Depends),
"Security" => Some(FastApiDependency::Security),
_ => None,
},
_ => None,
})
}
#[derive(Debug, Copy, Clone)]
enum FastApiDependency {
Query,
Path,
Body,
Cookie,
Header,
File,
Form,
Depends,
Security,
}
struct DependencyParameter<'a> {
annotation: &'a ast::Expr,
default: &'a ast::Expr,
range: TextRange,
name: &'a str,
kind: FastApiDependency,
}
struct DependencyCall<'a> {
default_argument: ast::ArgOrKeyword<'a>,
keyword_arguments: Vec<&'a ast::Keyword>,
}
impl<'a> DependencyCall<'a> {
fn from_expression(expr: &'a ast::Expr) -> Option<Self> {
let call = expr.as_call_expr()?;
let default_argument = call.arguments.find_argument("default", 0)?;
let keyword_arguments = call
.arguments
.keywords
.iter()
.filter(|kwarg| kwarg.arg.as_ref().is_some_and(|name| name != "default"))
.collect();
Some(Self {
default_argument,
keyword_arguments,
})
}
}
/// Create a [`Diagnostic`] for `parameter` and return an updated value of `seen_default`.
///
/// While all of the *input* `parameter` values have default values (see the `needs_update` match in
/// [`fastapi_non_annotated_dependency`]), some of the fixes remove default values. For example,
///
/// ```python
/// def handler(some_path_param: str = Path()): pass
/// ```
///
/// Gets fixed to
///
/// ```python
/// def handler(some_path_param: Annotated[str, Path()]): pass
/// ```
///
/// Causing it to lose its default value. That's fine in this example but causes a syntax error if
/// `some_path_param` comes after another argument with a default. We only compute the information
/// necessary to determine this while generating the fix, thus the need to return an updated
/// `seen_default` here.
fn create_diagnostic(
checker: &Checker,
parameter: &DependencyParameter,
dependency_call: Option<DependencyCall>,
mut seen_default: bool,
) -> bool {
let Some(importer) = checker.typing_importer("Annotated", PythonVersion::PY39) else {
return seen_default;
};
let mut diagnostic = checker.report_diagnostic(
FastApiNonAnnotatedDependency {
py_version: checker.target_version(),
},
parameter.range,
);
let try_generate_fix = || {
let (import_edit, binding) = importer.import(parameter.range.start())?;
// Each of these classes takes a single, optional default
// argument, followed by kw-only arguments
// Refine the match from `is_fastapi_dependency` to exclude Depends
// and Security, which don't have the same argument structure. The
// others need to be converted from `q: str = Query("")` to `q:
// Annotated[str, Query()] = ""` for example, but Depends and
// Security need to stay like `Annotated[str, Depends(callable)]`
let is_route_param = !matches!(
parameter.kind,
FastApiDependency::Depends | FastApiDependency::Security
);
let content = match dependency_call {
Some(dependency_call) if is_route_param => {
let kwarg_list = dependency_call
.keyword_arguments
.iter()
.map(|kwarg| checker.locator().slice(kwarg.range()))
.collect::<Vec<_>>()
.join(", ");
// Check if the default argument is ellipsis (...), which in FastAPI means "required"
let is_default_argument_ellipsis = matches!(
dependency_call.default_argument.value(),
ast::Expr::EllipsisLiteral(_)
);
if is_default_argument_ellipsis && seen_default {
// For ellipsis after a parameter with default, can't remove the default
return Ok(None);
}
if !is_default_argument_ellipsis {
// For actual default values, mark that we've seen a default
seen_default = true;
}
let base_format = format!(
"{parameter_name}: {binding}[{annotation}, {default_}({kwarg_list})]",
parameter_name = parameter.name,
annotation = checker.locator().slice(parameter.annotation.range()),
default_ = checker
.locator()
.slice(map_callable(parameter.default).range()),
);
if is_default_argument_ellipsis {
// For ellipsis, don't add a default value since the parameter
// should remain required after conversion to Annotated
base_format
} else {
// For actual default values, preserve them
let default_value = checker
.locator()
.slice(dependency_call.default_argument.value().range());
format!("{base_format} = {default_value}")
}
}
_ => {
if seen_default {
return Ok(None);
}
format!(
"{parameter_name}: {binding}[{annotation}, {default_}]",
parameter_name = parameter.name,
annotation = checker.locator().slice(parameter.annotation.range()),
default_ = checker.locator().slice(parameter.default.range())
)
}
};
let parameter_edit = Edit::range_replacement(content, parameter.range);
Ok(Some(Fix::unsafe_edits(import_edit, [parameter_edit])))
};
// make sure we set `seen_default` if we bail out of `try_generate_fix` early. we could
// `match` on the result directly, but still calling `try_set_optional_fix` avoids
// duplicating the debug logging here
let fix: anyhow::Result<Option<Fix>> = try_generate_fix();
if fix.is_err() {
seen_default = true;
}
diagnostic.try_set_optional_fix(|| fix);
seen_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_simplify/mod.rs | crates/ruff_linter/src/rules/flake8_simplify/mod.rs | //! Rules from [flake8-simplify](https://pypi.org/project/flake8-simplify/).
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::settings::LinterSettings;
use crate::settings::types::PreviewMode;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::DuplicateIsinstanceCall, Path::new("SIM101.py"))]
#[test_case(Rule::CollapsibleIf, Path::new("SIM102.py"))]
#[test_case(Rule::NeedlessBool, Path::new("SIM103.py"))]
#[test_case(Rule::SuppressibleException, Path::new("SIM105_0.py"))]
#[test_case(Rule::SuppressibleException, Path::new("SIM105_1.py"))]
#[test_case(Rule::SuppressibleException, Path::new("SIM105_2.py"))]
#[test_case(Rule::SuppressibleException, Path::new("SIM105_3.py"))]
#[test_case(Rule::SuppressibleException, Path::new("SIM105_4.py"))]
#[test_case(Rule::ReturnInTryExceptFinally, Path::new("SIM107.py"))]
#[test_case(Rule::IfElseBlockInsteadOfIfExp, Path::new("SIM108.py"))]
#[test_case(Rule::CompareWithTuple, Path::new("SIM109.py"))]
#[test_case(Rule::ReimplementedBuiltin, Path::new("SIM110.py"))]
#[test_case(Rule::ReimplementedBuiltin, Path::new("SIM111.py"))]
#[test_case(Rule::UncapitalizedEnvironmentVariables, Path::new("SIM112.py"))]
#[test_case(Rule::EnumerateForLoop, Path::new("SIM113.py"))]
#[test_case(Rule::IfWithSameArms, Path::new("SIM114.py"))]
#[test_case(Rule::OpenFileWithContextHandler, Path::new("SIM115.py"))]
#[test_case(Rule::IfElseBlockInsteadOfDictLookup, Path::new("SIM116.py"))]
#[test_case(Rule::MultipleWithStatements, Path::new("SIM117.py"))]
#[test_case(Rule::InDictKeys, Path::new("SIM118.py"))]
#[test_case(Rule::NegateEqualOp, Path::new("SIM201.py"))]
#[test_case(Rule::NegateNotEqualOp, Path::new("SIM202.py"))]
#[test_case(Rule::DoubleNegation, Path::new("SIM208.py"))]
#[test_case(Rule::IfExprWithTrueFalse, Path::new("SIM210.py"))]
#[test_case(Rule::IfExprWithFalseTrue, Path::new("SIM211.py"))]
#[test_case(Rule::IfExprWithTwistedArms, Path::new("SIM212.py"))]
#[test_case(Rule::ExprAndNotExpr, Path::new("SIM220.py"))]
#[test_case(Rule::ExprOrNotExpr, Path::new("SIM221.py"))]
#[test_case(Rule::ExprOrTrue, Path::new("SIM222.py"))]
#[test_case(Rule::ExprAndFalse, Path::new("SIM223.py"))]
#[test_case(Rule::YodaConditions, Path::new("SIM300.py"))]
#[test_case(Rule::IfElseBlockInsteadOfDictGet, Path::new("SIM401.py"))]
#[test_case(Rule::SplitStaticString, Path::new("SIM905.py"))]
#[test_case(Rule::DictGetWithNoneDefault, Path::new("SIM910.py"))]
#[test_case(Rule::ZipDictKeysAndValues, Path::new("SIM911.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_simplify").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::SplitStaticString, Path::new("SIM905.py"))]
#[test_case(Rule::DictGetWithNoneDefault, Path::new("SIM910.py"))]
#[test_case(Rule::EnumerateForLoop, Path::new("SIM113.py"))]
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_simplify").join(path).as_path(),
&LinterSettings {
preview: PreviewMode::Enabled,
..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_simplify/rules/zip_dict_keys_and_values.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/zip_dict_keys_and_values.rs | use ast::{ExprAttribute, ExprName, Identifier};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Arguments, Expr};
use ruff_python_semantic::analyze::typing::is_dict;
use ruff_text_size::Ranged;
use crate::fix::edits;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::{checkers::ast::Checker, fix::snippet::SourceCodeSnippet};
/// ## What it does
/// Checks for use of `zip()` to iterate over keys and values of a dictionary at once.
///
/// ## Why is this bad?
/// The `dict` type provides an `.items()` method which is faster and more readable.
///
/// ## Example
/// ```python
/// flag_stars = {"USA": 50, "Slovenia": 3, "Panama": 2, "Australia": 6}
///
/// for country, stars in zip(flag_stars.keys(), flag_stars.values()):
/// print(f"{country}'s flag has {stars} stars.")
/// ```
///
/// Use instead:
/// ```python
/// flag_stars = {"USA": 50, "Slovenia": 3, "Panama": 2, "Australia": 6}
///
/// for country, stars in flag_stars.items():
/// print(f"{country}'s flag has {stars} stars.")
/// ```
///
/// ## References
/// - [Python documentation: `dict.items`](https://docs.python.org/3/library/stdtypes.html#dict.items)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.2.0")]
pub(crate) struct ZipDictKeysAndValues {
expected: SourceCodeSnippet,
actual: SourceCodeSnippet,
}
impl AlwaysFixableViolation for ZipDictKeysAndValues {
#[derive_message_formats]
fn message(&self) -> String {
let ZipDictKeysAndValues { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
format!("Use `{expected}` instead of `{actual}`")
} else {
"Use `dict.items()` instead of `zip(dict.keys(), dict.values())`".to_string()
}
}
fn fix_title(&self) -> String {
let ZipDictKeysAndValues { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
format!("Replace `{actual}` with `{expected}`")
} else {
"Replace `zip(dict.keys(), dict.values())` with `dict.items()`".to_string()
}
}
}
/// SIM911
pub(crate) fn zip_dict_keys_and_values(checker: &Checker, expr: &ast::ExprCall) {
let ast::ExprCall {
func,
arguments: Arguments { args, keywords, .. },
..
} = expr;
match &keywords[..] {
[] => {}
[
ast::Keyword {
arg: Some(name), ..
},
] if name.as_str() == "strict" => {}
_ => return,
}
let [arg1, arg2] = &args[..] else {
return;
};
let Some((var1, attr1, args1)) = get_var_attr_args(arg1) else {
return;
};
let Some((var2, attr2, args2)) = get_var_attr_args(arg2) else {
return;
};
if var1.id != var2.id
|| attr1 != "keys"
|| attr2 != "values"
|| !args1.is_empty()
|| !args2.is_empty()
{
return;
}
if !checker.semantic().match_builtin_expr(func, "zip") {
return;
}
let Some(binding) = checker
.semantic()
.resolve_name(var1)
.map(|id| checker.semantic().binding(id))
else {
return;
};
if !is_dict(binding, checker.semantic()) {
return;
}
let expected = edits::pad(
format!("{}.items()", checker.locator().slice(var1)),
expr.range(),
checker.locator(),
);
let actual = checker.locator().slice(expr);
let mut diagnostic = checker.report_diagnostic(
ZipDictKeysAndValues {
expected: SourceCodeSnippet::new(expected.clone()),
actual: SourceCodeSnippet::from_str(actual),
},
expr.range(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
expected,
expr.range(),
)));
}
fn get_var_attr_args(expr: &Expr) -> Option<(&ExprName, &Identifier, &Arguments)> {
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = expr
else {
return None;
};
let Expr::Attribute(ExprAttribute { value, attr, .. }) = func.as_ref() else {
return None;
};
let Expr::Name(var_name) = value.as_ref() else {
return None;
};
Some((var_name, attr, arguments))
}
| 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_simplify/rules/reimplemented_builtin.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::name::Name;
use ruff_python_ast::traversal;
use ruff_python_ast::{
self as ast, Arguments, CmpOp, Comprehension, Expr, ExprContext, Stmt, UnaryOp,
};
use ruff_python_codegen::Generator;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::fits;
use crate::line_width::LineWidthBuilder;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `for` loops that can be replaced with a builtin function, like
/// `any` or `all`.
///
/// ## Why is this bad?
/// Using a builtin function is more concise and readable.
///
/// ## Example
/// ```python
/// def foo():
/// for item in iterable:
/// if predicate(item):
/// return True
/// return False
/// ```
///
/// Use instead:
/// ```python
/// def foo():
/// return any(predicate(item) for item in iterable)
/// ```
///
/// ## Fix safety
///
/// This fix is always marked as unsafe because it might remove comments.
///
/// ## Options
///
/// The rule will avoid flagging cases where using the builtin function would exceed the configured
/// line length, as determined by these options:
///
/// - `lint.pycodestyle.max-line-length`
/// - `indent-width`
///
/// ## References
/// - [Python documentation: `any`](https://docs.python.org/3/library/functions.html#any)
/// - [Python documentation: `all`](https://docs.python.org/3/library/functions.html#all)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct ReimplementedBuiltin {
replacement: String,
}
impl Violation for ReimplementedBuiltin {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let ReimplementedBuiltin { replacement } = self;
format!("Use `{replacement}` instead of `for` loop")
}
fn fix_title(&self) -> Option<String> {
let ReimplementedBuiltin { replacement } = self;
Some(format!("Replace with `{replacement}`"))
}
}
/// SIM110, SIM111
pub(crate) fn convert_for_loop_to_any_all(checker: &Checker, stmt: &Stmt) {
if !checker.semantic().current_scope().kind.is_function() {
return;
}
// The `for` loop itself must consist of an `if` with a `return`.
let Some(loop_) = match_loop(stmt) else {
return;
};
// Afterwards, there are two cases to consider:
// - `for` loop with an `else: return True` or `else: return False`.
// - `for` loop followed by `return True` or `return False`.
let Some(terminal) = match_else_return(stmt).or_else(|| {
let parent = checker.semantic().current_statement_parent()?;
let sibling = traversal::suite(stmt, parent)?.next_sibling()?;
match_sibling_return(stmt, sibling)
}) else {
return;
};
// Check if any of the expressions contain an `await`, `yield`, or `yield from` expression.
// If so, turning the code into an any() or all() call would produce a SyntaxError.
if contains_yield_like(loop_.target) || contains_yield_like(loop_.test) {
return;
}
match (loop_.return_value, terminal.return_value) {
// Replace with `any`.
(true, false) => {
let contents = return_stmt(
Name::new_static("any"),
loop_.test,
loop_.target,
loop_.iter,
checker.generator(),
);
// Don't flag if the resulting expression would exceed the maximum line length.
if !fits(
&contents,
stmt.into(),
checker.locator(),
checker.settings().pycodestyle.max_line_length,
checker.settings().tab_size,
) {
return;
}
let mut diagnostic = checker.report_diagnostic(
ReimplementedBuiltin {
replacement: contents.clone(),
},
TextRange::new(stmt.start(), terminal.stmt.end()),
);
if checker.semantic().has_builtin_binding("any") {
diagnostic.set_fix(Fix::unsafe_edit(Edit::replacement(
contents,
stmt.start(),
terminal.stmt.end(),
)));
}
}
// Replace with `all`.
(false, true) => {
// Invert the condition.
let test = {
if let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::Not,
operand,
range: _,
node_index: _,
}) = &loop_.test
{
*operand.clone()
} else if let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
}) = &loop_.test
{
if let ([op], [comparator]) = (&**ops, &**comparators) {
let op = match op {
CmpOp::Eq => CmpOp::NotEq,
CmpOp::NotEq => CmpOp::Eq,
CmpOp::Lt => CmpOp::GtE,
CmpOp::LtE => CmpOp::Gt,
CmpOp::Gt => CmpOp::LtE,
CmpOp::GtE => CmpOp::Lt,
CmpOp::Is => CmpOp::IsNot,
CmpOp::IsNot => CmpOp::Is,
CmpOp::In => CmpOp::NotIn,
CmpOp::NotIn => CmpOp::In,
};
let node = ast::ExprCompare {
left: left.clone(),
ops: Box::from([op]),
comparators: Box::from([comparator.clone()]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
node.into()
} else {
let node = ast::ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(loop_.test.clone()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
node.into()
}
} else {
let node = ast::ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(loop_.test.clone()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
node.into()
}
};
let contents = return_stmt(
Name::new_static("all"),
&test,
loop_.target,
loop_.iter,
checker.generator(),
);
// Don't flag if the resulting expression would exceed the maximum line length.
let line_start = checker.locator().line_start(stmt.start());
if LineWidthBuilder::new(checker.settings().tab_size)
.add_str(
checker
.locator()
.slice(TextRange::new(line_start, stmt.start())),
)
.add_str(&contents)
> checker.settings().pycodestyle.max_line_length
{
return;
}
let mut diagnostic = checker.report_diagnostic(
ReimplementedBuiltin {
replacement: contents.clone(),
},
TextRange::new(stmt.start(), terminal.stmt.end()),
);
if checker.semantic().has_builtin_binding("all") {
diagnostic.set_fix(Fix::unsafe_edit(Edit::replacement(
contents,
stmt.start(),
terminal.stmt.end(),
)));
}
}
_ => {}
}
}
/// Represents a `for` loop with a conditional `return`, like:
/// ```python
/// for x in y:
/// if x == 0:
/// return True
/// ```
#[derive(Debug)]
struct Loop<'a> {
/// The `return` value of the loop.
return_value: bool,
/// The test condition in the loop.
test: &'a Expr,
/// The target of the loop.
target: &'a Expr,
/// The iterator of the loop.
iter: &'a Expr,
}
/// Represents a `return` statement following a `for` loop, like:
/// ```python
/// for x in y:
/// if x == 0:
/// return True
/// return False
/// ```
///
/// Or:
/// ```python
/// for x in y:
/// if x == 0:
/// return True
/// else:
/// return False
/// ```
#[derive(Debug)]
struct Terminal<'a> {
return_value: bool,
stmt: &'a Stmt,
}
fn match_loop(stmt: &Stmt) -> Option<Loop<'_>> {
let Stmt::For(ast::StmtFor {
body, target, iter, ..
}) = stmt
else {
return None;
};
// The loop itself should contain a single `if` statement, with a single `return` statement in
// the body.
let [
Stmt::If(ast::StmtIf {
body: nested_body,
test: nested_test,
elif_else_clauses: nested_elif_else_clauses,
range: _,
node_index: _,
}),
] = body.as_slice()
else {
return None;
};
if !nested_elif_else_clauses.is_empty() {
return None;
}
let [
Stmt::Return(ast::StmtReturn {
value: Some(value),
range: _,
node_index: _,
}),
] = nested_body.as_slice()
else {
return None;
};
let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = value.as_ref() else {
return None;
};
Some(Loop {
return_value: *value,
test: nested_test,
target,
iter,
})
}
/// If a `Stmt::For` contains an `else` with a single boolean `return`, return the [`Terminal`]
/// representing that `return`.
///
/// For example, matches the `return` in:
/// ```python
/// for x in y:
/// if x == 0:
/// return True
/// return False
/// ```
fn match_else_return(stmt: &Stmt) -> Option<Terminal<'_>> {
let Stmt::For(ast::StmtFor { orelse, .. }) = stmt else {
return None;
};
// The `else` block has to contain a single `return True` or `return False`.
let [
Stmt::Return(ast::StmtReturn {
value: Some(next_value),
range: _,
node_index: _,
}),
] = orelse.as_slice()
else {
return None;
};
let Expr::BooleanLiteral(ast::ExprBooleanLiteral {
value: next_value, ..
}) = next_value.as_ref()
else {
return None;
};
Some(Terminal {
return_value: *next_value,
stmt,
})
}
/// If a `Stmt::For` is followed by a boolean `return`, return the [`Terminal`] representing that
/// `return`.
///
/// For example, matches the `return` in:
/// ```python
/// for x in y:
/// if x == 0:
/// return True
/// else:
/// return False
/// ```
fn match_sibling_return<'a>(stmt: &'a Stmt, sibling: &'a Stmt) -> Option<Terminal<'a>> {
let Stmt::For(ast::StmtFor { orelse, .. }) = stmt else {
return None;
};
// The loop itself shouldn't have an `else` block.
if !orelse.is_empty() {
return None;
}
// The next statement has to be a `return True` or `return False`.
let Stmt::Return(ast::StmtReturn {
value: Some(next_value),
range: _,
node_index: _,
}) = &sibling
else {
return None;
};
let Expr::BooleanLiteral(ast::ExprBooleanLiteral {
value: next_value, ..
}) = next_value.as_ref()
else {
return None;
};
Some(Terminal {
return_value: *next_value,
stmt: sibling,
})
}
/// Generate a return statement for an `any` or `all` builtin comprehension.
fn return_stmt(id: Name, test: &Expr, target: &Expr, iter: &Expr, generator: Generator) -> String {
let node = ast::ExprGenerator {
elt: Box::new(test.clone()),
generators: vec![Comprehension {
target: target.clone(),
iter: iter.clone(),
ifs: vec![],
is_async: false,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}],
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: false,
};
let node1 = ast::ExprName {
id,
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node2 = ast::ExprCall {
func: Box::new(node1.into()),
arguments: Arguments {
args: Box::from([node.into()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node3 = ast::StmtReturn {
value: Some(Box::new(node2.into())),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
generator.stmt(&node3.into())
}
/// Return `true` if the [`Expr`] contains an `await`, `yield`, or `yield from` expression.
fn contains_yield_like(expr: &Expr) -> bool {
any_over_expr(expr, &Expr::is_await_expr)
|| any_over_expr(expr, &Expr::is_yield_expr)
|| any_over_expr(expr, &Expr::is_yield_from_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_simplify/rules/ast_ifexp.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/ast_ifexp.rs | use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, UnaryOp};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::{is_const_false, is_const_true};
use ruff_python_ast::name::Name;
use ruff_python_ast::token::parenthesized_range;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `if` expressions that can be replaced with `bool()` calls.
///
/// ## Why is this bad?
/// `if` expressions that evaluate to `True` for a truthy condition an `False`
/// for a falsey condition can be replaced with `bool()` calls, which are more
/// concise and readable.
///
/// ## Example
/// ```python
/// True if a else False
/// ```
///
/// Use instead:
/// ```python
/// bool(a)
/// ```
///
/// ## Fix safety
///
/// This fix is marked as unsafe because it may change the program’s behavior if the condition does not
/// return a proper Boolean. While the fix will try to wrap non-boolean values in a call to bool,
/// custom implementations of comparison functions like `__eq__` can avoid the bool call and still
/// lead to altered behavior. Moreover, the fix may remove comments.
///
/// ## References
/// - [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.214")]
pub(crate) struct IfExprWithTrueFalse {
is_compare: bool,
}
impl Violation for IfExprWithTrueFalse {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
if self.is_compare {
"Remove unnecessary `True if ... else False`".to_string()
} else {
"Use `bool(...)` instead of `True if ... else False`".to_string()
}
}
fn fix_title(&self) -> Option<String> {
let title = if self.is_compare {
"Remove unnecessary `True if ... else False`"
} else {
"Replace with `bool(...)"
};
Some(title.to_string())
}
}
/// ## What it does
/// Checks for `if` expressions that can be replaced by negating a given
/// condition.
///
/// ## Why is this bad?
/// `if` expressions that evaluate to `False` for a truthy condition and `True`
/// for a falsey condition can be replaced with `not` operators, which are more
/// concise and readable.
///
/// ## Example
/// ```python
/// False if a else True
/// ```
///
/// Use instead:
/// ```python
/// not a
/// ```
///
/// ## References
/// - [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.214")]
pub(crate) struct IfExprWithFalseTrue;
impl AlwaysFixableViolation for IfExprWithFalseTrue {
#[derive_message_formats]
fn message(&self) -> String {
"Use `not ...` instead of `False if ... else True`".to_string()
}
fn fix_title(&self) -> String {
"Replace with `not ...`".to_string()
}
}
/// ## What it does
/// Checks for `if` expressions that check against a negated condition.
///
/// ## Why is this bad?
/// `if` expressions that check against a negated condition are more difficult
/// to read than `if` expressions that check against the condition directly.
///
/// ## Example
/// ```python
/// b if not a else a
/// ```
///
/// Use instead:
/// ```python
/// a if a else b
/// ```
///
/// ## References
/// - [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.214")]
pub(crate) struct IfExprWithTwistedArms {
expr_body: String,
expr_else: String,
}
impl AlwaysFixableViolation for IfExprWithTwistedArms {
#[derive_message_formats]
fn message(&self) -> String {
let IfExprWithTwistedArms {
expr_body,
expr_else,
} = self;
format!(
"Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not \
{expr_else} else {expr_else}`"
)
}
fn fix_title(&self) -> String {
let IfExprWithTwistedArms {
expr_body,
expr_else,
} = self;
format!("Replace with `{expr_else} if {expr_else} else {expr_body}`")
}
}
/// SIM210
pub(crate) fn if_expr_with_true_false(
checker: &Checker,
expr: &Expr,
test: &Expr,
body: &Expr,
orelse: &Expr,
) {
if !is_const_true(body) || !is_const_false(orelse) {
return;
}
let mut diagnostic = checker.report_diagnostic(
IfExprWithTrueFalse {
is_compare: test.is_compare_expr(),
},
expr.range(),
);
if test.is_compare_expr() {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker
.locator()
.slice(
parenthesized_range(test.into(), expr.into(), checker.tokens())
.unwrap_or(test.range()),
)
.to_string(),
expr.range(),
)));
} else if checker.semantic().has_builtin_binding("bool") {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(
&ast::ExprCall {
func: Box::new(
ast::ExprName {
id: Name::new_static("bool"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
arguments: Arguments {
args: Box::from([test.clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
expr.range(),
)));
}
}
/// SIM211
pub(crate) fn if_expr_with_false_true(
checker: &Checker,
expr: &Expr,
test: &Expr,
body: &Expr,
orelse: &Expr,
) {
if !is_const_false(body) || !is_const_true(orelse) {
return;
}
let mut diagnostic = checker.report_diagnostic(IfExprWithFalseTrue, expr.range());
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(
&ast::ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(test.clone()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
expr.range(),
)));
}
/// SIM212
pub(crate) fn twisted_arms_in_ifexpr(
checker: &Checker,
expr: &Expr,
test: &Expr,
body: &Expr,
orelse: &Expr,
) {
let Expr::UnaryOp(ast::ExprUnaryOp {
op,
operand,
range: _,
node_index: _,
}) = &test
else {
return;
};
if !op.is_not() {
return;
}
// Check if the test operand and else branch use the same variable.
let Expr::Name(ast::ExprName { id: test_id, .. }) = operand.as_ref() else {
return;
};
let Expr::Name(ast::ExprName { id: orelse_id, .. }) = orelse else {
return;
};
if !test_id.eq(orelse_id) {
return;
}
let mut diagnostic = checker.report_diagnostic(
IfExprWithTwistedArms {
expr_body: checker.generator().expr(body),
expr_else: checker.generator().expr(orelse),
},
expr.range(),
);
let node = body.clone();
let node1 = orelse.clone();
let node2 = orelse.clone();
let node3 = ast::ExprIf {
test: Box::new(node2),
body: Box::new(node1),
orelse: Box::new(node),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node3.into()),
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_simplify/rules/needless_bool.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/needless_bool.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::Name;
use ruff_python_ast::traversal;
use ruff_python_ast::{self as ast, Arguments, ElifElseClause, Expr, ExprContext, Stmt};
use ruff_python_semantic::analyze::typing::{is_sys_version_block, is_type_checking_block};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `if` statements that can be replaced with `bool`.
///
/// ## Why is this bad?
/// `if` statements that return `True` for a truthy condition and `False` for
/// a falsy condition can be replaced with boolean casts.
///
/// ## Example
/// Given:
/// ```python
/// def foo(x: int) -> bool:
/// if x > 0:
/// return True
/// else:
/// return False
/// ```
///
/// Use instead:
/// ```python
/// def foo(x: int) -> bool:
/// return x > 0
/// ```
///
/// Or, given:
/// ```python
/// def foo(x: int) -> bool:
/// if x > 0:
/// return True
/// return False
/// ```
///
/// Use instead:
/// ```python
/// def foo(x: int) -> bool:
/// return x > 0
/// ```
///
/// ## Fix safety
///
/// This fix is marked as unsafe because it may change the program’s behavior if the condition does not
/// return a proper Boolean. While the fix will try to wrap non-boolean values in a call to bool,
/// custom implementations of comparison functions like `__eq__` can avoid the bool call and still
/// lead to altered behavior.
///
/// ## References
/// - [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.214")]
pub(crate) struct NeedlessBool {
condition: Option<SourceCodeSnippet>,
negate: bool,
}
impl Violation for NeedlessBool {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let NeedlessBool { condition, negate } = self;
if let Some(condition) = condition.as_ref().and_then(SourceCodeSnippet::full_display) {
format!("Return the condition `{condition}` directly")
} else if *negate {
"Return the negated condition directly".to_string()
} else {
"Return the condition directly".to_string()
}
}
fn fix_title(&self) -> Option<String> {
let NeedlessBool { condition, .. } = self;
Some(
if let Some(condition) = condition.as_ref().and_then(SourceCodeSnippet::full_display) {
format!("Replace with `return {condition}`")
} else {
"Inline condition".to_string()
},
)
}
}
/// SIM103
pub(crate) fn needless_bool(checker: &Checker, stmt: &Stmt) {
let Stmt::If(stmt_if) = stmt else { return };
let ast::StmtIf {
test: if_test,
body: if_body,
elif_else_clauses,
..
} = stmt_if;
// Extract an `if` or `elif` (that returns) followed by an else (that returns the same value)
let (if_test, if_body, else_body, range) = match elif_else_clauses.as_slice() {
// if-else case:
// ```python
// if x > 0:
// return True
// else:
// return False
// ```
[
ElifElseClause {
body: else_body,
test: None,
..
},
] => (
if_test.as_ref(),
if_body,
else_body.as_slice(),
stmt_if.range(),
),
// elif-else case
// ```python
// if x > 0:
// return True
// elif x < 0:
// return False
// ```
[
..,
ElifElseClause {
body: elif_body,
test: Some(elif_test),
range: elif_range,
node_index: _,
},
ElifElseClause {
body: else_body,
test: None,
range: else_range,
node_index: _,
},
] => (
elif_test,
elif_body,
else_body.as_slice(),
TextRange::new(elif_range.start(), else_range.end()),
),
// if-implicit-else case:
// ```python
// if x > 0:
// return True
// return False
// ```
[] => {
// Fetching the next sibling is expensive, so do some validation early.
if is_one_line_return_bool(if_body).is_none() {
return;
}
// Fetch the next sibling statement.
let Some(next_stmt) = checker
.semantic()
.current_statement_parent()
.and_then(|parent| traversal::suite(stmt, parent))
.and_then(|suite| suite.next_sibling())
else {
return;
};
// If the next sibling is not a return statement, abort.
if !next_stmt.is_return_stmt() {
return;
}
(
if_test.as_ref(),
if_body,
std::slice::from_ref(next_stmt),
TextRange::new(stmt_if.start(), next_stmt.end()),
)
}
_ => return,
};
// Both branches must be one-liners that return a boolean.
let (Some(if_return), Some(else_return)) = (
is_one_line_return_bool(if_body),
is_one_line_return_bool(else_body),
) else {
return;
};
// Determine whether the return values are inverted, as in:
// ```python
// if x > 0:
// return False
// else:
// return True
// ```
let inverted = match (if_return, else_return) {
(Bool::True, Bool::False) => false,
(Bool::False, Bool::True) => true,
// If the branches have the same condition, abort (although the code could be
// simplified).
_ => return,
};
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
if is_sys_version_block(stmt_if, checker.semantic()) {
return;
}
// Avoid suggesting ternary for `if TYPE_CHECKING:`-style checks.
if is_type_checking_block(stmt_if, checker.semantic()) {
return;
}
// Generate the replacement condition.
let condition = if checker
.comment_ranges()
.has_comments(&range, checker.source())
{
None
} else {
// If the return values are inverted, wrap the condition in a `not`.
if inverted {
match if_test {
Expr::UnaryOp(ast::ExprUnaryOp {
op: ast::UnaryOp::Not,
operand,
..
}) => Some((**operand).clone()),
Expr::Compare(ast::ExprCompare {
ops,
left,
comparators,
..
}) if matches!(
ops.as_ref(),
[ast::CmpOp::Eq
| ast::CmpOp::NotEq
| ast::CmpOp::In
| ast::CmpOp::NotIn
| ast::CmpOp::Is
| ast::CmpOp::IsNot]
) =>
{
let ([op], [right]) = (ops.as_ref(), comparators.as_ref()) else {
unreachable!("Single comparison with multiple comparators");
};
Some(Expr::Compare(ast::ExprCompare {
ops: Box::new([op.negate()]),
left: left.clone(),
comparators: Box::new([right.clone()]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}))
}
_ => Some(Expr::UnaryOp(ast::ExprUnaryOp {
op: ast::UnaryOp::Not,
operand: Box::new(if_test.clone()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})),
}
} else if if_test.is_compare_expr() {
// If the condition is a comparison, we can replace it with the condition, since we
// know it's a boolean.
Some(if_test.clone())
} else if checker.semantic().has_builtin_binding("bool") {
// Otherwise, we need to wrap the condition in a call to `bool`.
let func_node = ast::ExprName {
id: Name::new_static("bool"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let call_node = ast::ExprCall {
func: Box::new(func_node.into()),
arguments: Arguments {
args: Box::from([if_test.clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
Some(Expr::Call(call_node))
} else {
None
}
};
// Generate the replacement `return` statement.
let replacement = condition.as_ref().map(|expr| {
Stmt::Return(ast::StmtReturn {
value: Some(Box::new(expr.clone())),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
});
// Generate source code.
let replacement = replacement
.as_ref()
.map(|stmt| checker.generator().stmt(stmt));
let condition = condition
.as_ref()
.map(|expr| checker.generator().expr(expr));
let mut diagnostic = checker.report_diagnostic(
NeedlessBool {
condition: condition.map(SourceCodeSnippet::new),
negate: inverted,
},
range,
);
if let Some(replacement) = replacement {
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
replacement,
range,
)));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Bool {
True,
False,
}
impl From<bool> for Bool {
fn from(value: bool) -> Self {
if value { Bool::True } else { Bool::False }
}
}
fn is_one_line_return_bool(stmts: &[Stmt]) -> Option<Bool> {
let [stmt] = stmts else {
return None;
};
let Stmt::Return(ast::StmtReturn {
value,
range: _,
node_index: _,
}) = stmt
else {
return None;
};
let Some(Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. })) = value.as_deref() else {
return None;
};
Some((*value).into())
}
| 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_simplify/rules/if_with_same_arms.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/if_with_same_arms.rs | use std::borrow::Cow;
use anyhow::Result;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableStmt;
use ruff_python_ast::stmt_if::{IfElifBranch, if_elif_branches};
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{self as ast, Expr};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `if` branches with identical arm bodies.
///
/// ## Why is this bad?
/// If multiple arms of an `if` statement have the same body, using `or`
/// better signals the intent of the statement.
///
/// ## Example
/// ```python
/// if x == 1:
/// print("Hello")
/// elif x == 2:
/// print("Hello")
/// ```
///
/// Use instead:
/// ```python
/// if x == 1 or x == 2:
/// print("Hello")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.246")]
pub(crate) struct IfWithSameArms;
impl Violation for IfWithSameArms {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Combine `if` branches using logical `or` operator".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Combine `if` branches".to_string())
}
}
/// SIM114
pub(crate) fn if_with_same_arms(checker: &Checker, stmt_if: &ast::StmtIf) {
let mut branches_iter = if_elif_branches(stmt_if).peekable();
while let Some(current_branch) = branches_iter.next() {
let Some(following_branch) = branches_iter.peek() else {
continue;
};
// The bodies must have the same code ...
if current_branch.body.len() != following_branch.body.len() {
continue;
}
if !current_branch
.body
.iter()
.zip(following_branch.body)
.all(|(stmt1, stmt2)| ComparableStmt::from(stmt1) == ComparableStmt::from(stmt2))
{
continue;
}
// ...and the same comments
let first_comments = checker
.comment_ranges()
.comments_in_range(body_range(¤t_branch, checker.locator()))
.iter()
.map(|range| checker.locator().slice(*range));
let second_comments = checker
.comment_ranges()
.comments_in_range(body_range(following_branch, checker.locator()))
.iter()
.map(|range| checker.locator().slice(*range));
if !first_comments.eq(second_comments) {
continue;
}
let mut diagnostic = checker.report_diagnostic(
IfWithSameArms,
TextRange::new(current_branch.start(), following_branch.end()),
);
diagnostic.try_set_fix(|| {
merge_branches(
stmt_if,
¤t_branch,
following_branch,
checker.locator(),
checker.tokens(),
)
});
}
}
/// Generate a [`Fix`] to merge two [`IfElifBranch`] branches.
fn merge_branches(
stmt_if: &ast::StmtIf,
current_branch: &IfElifBranch,
following_branch: &IfElifBranch,
locator: &Locator,
tokens: &ruff_python_ast::token::Tokens,
) -> Result<Fix> {
// Identify the colon (`:`) at the end of the current branch's test.
let Some(current_branch_colon) =
SimpleTokenizer::starts_at(current_branch.test.end(), locator.contents())
.find(|token| token.kind == SimpleTokenKind::Colon)
else {
return Err(anyhow::anyhow!("Expected colon after test"));
};
let deletion_edit = Edit::deletion(
locator.full_line_end(current_branch.end()),
locator.full_line_end(following_branch.end()),
);
// If the following test isn't parenthesized, consider parenthesizing it.
let following_branch_test = if let Some(range) =
parenthesized_range(following_branch.test.into(), stmt_if.into(), tokens)
{
Cow::Borrowed(locator.slice(range))
} else if matches!(
following_branch.test,
Expr::Lambda(_) | Expr::Named(_) | Expr::If(_)
) {
// If the following expressions binds more tightly than `or`, parenthesize it.
Cow::Owned(format!("({})", locator.slice(following_branch.test)))
} else {
Cow::Borrowed(locator.slice(following_branch.test))
};
let insertion_edit = Edit::insertion(
format!(" or {following_branch_test}"),
current_branch_colon.start(),
);
// If the current test isn't parenthesized, consider parenthesizing it.
//
// For example, if the current test is `x if x else y`, we should parenthesize it to
// `(x if x else y) or ...`.
let parenthesize_edit =
if matches!(
current_branch.test,
Expr::Lambda(_) | Expr::Named(_) | Expr::If(_)
) && parenthesized_range(current_branch.test.into(), stmt_if.into(), tokens).is_none()
{
Some(Edit::range_replacement(
format!("({})", locator.slice(current_branch.test)),
current_branch.test.range(),
))
} else {
None
};
Ok(Fix::safe_edits(
deletion_edit,
parenthesize_edit.into_iter().chain(Some(insertion_edit)),
))
}
/// Return the [`TextRange`] of an [`IfElifBranch`]'s body (from the end of the test to the end of
/// the body).
fn body_range(branch: &IfElifBranch, locator: &Locator) -> TextRange {
TextRange::new(
locator.line_end(branch.test.end()),
locator.line_end(branch.end()),
)
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_simplify/rules/ast_expr.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/ast_expr.rs | use ruff_python_ast::{self as ast, Arguments, Expr, str_prefix::StringLiteralPrefix};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Modules;
use ruff_python_semantic::analyze::typing::is_dict;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Check for environment variables that are not capitalized.
///
/// ## Why is this bad?
/// By convention, environment variables should be capitalized.
///
/// On Windows, environment variables are case-insensitive and are converted to
/// uppercase, so using lowercase environment variables can lead to subtle bugs.
///
/// ## Example
/// ```python
/// import os
///
/// os.environ["foo"]
/// ```
///
/// Use instead:
/// ```python
/// import os
///
/// os.environ["FOO"]
/// ```
///
/// ## Fix safety
///
/// This fix is always marked as unsafe because automatically capitalizing environment variable names
/// can change program behavior in environments where the variable names are case-sensitive, such as most
/// Unix-like systems.
///
/// ## References
/// - [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.218")]
pub(crate) struct UncapitalizedEnvironmentVariables {
expected: SourceCodeSnippet,
actual: SourceCodeSnippet,
}
impl Violation for UncapitalizedEnvironmentVariables {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UncapitalizedEnvironmentVariables { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
format!("Use capitalized environment variable `{expected}` instead of `{actual}`")
} else {
"Use capitalized environment variable".to_string()
}
}
fn fix_title(&self) -> Option<String> {
let UncapitalizedEnvironmentVariables { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
Some(format!("Replace `{actual}` with `{expected}`"))
} else {
Some("Capitalize environment variable".to_string())
}
}
}
/// ## What it does
/// Checks for `dict.get()` calls that pass `None` as the default value.
///
/// ## Why is this bad?
/// `None` is the default value for `dict.get()`, so it is redundant to pass it
/// explicitly.
///
/// ## Example
/// ```python
/// ages = {"Tom": 23, "Maria": 23, "Dog": 11}
/// age = ages.get("Cat", None)
/// ```
///
/// Use instead:
/// ```python
/// ages = {"Tom": 23, "Maria": 23, "Dog": 11}
/// age = ages.get("Cat")
/// ```
///
/// ## References
/// - [Python documentation: `dict.get`](https://docs.python.org/3/library/stdtypes.html#dict.get)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.261")]
pub(crate) struct DictGetWithNoneDefault {
expected: SourceCodeSnippet,
actual: SourceCodeSnippet,
}
impl AlwaysFixableViolation for DictGetWithNoneDefault {
#[derive_message_formats]
fn message(&self) -> String {
let DictGetWithNoneDefault { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
format!("Use `{expected}` instead of `{actual}`")
} else {
"Use `dict.get()` without default value".to_string()
}
}
fn fix_title(&self) -> String {
let DictGetWithNoneDefault { expected, actual } = self;
if let (Some(expected), Some(actual)) = (expected.full_display(), actual.full_display()) {
format!("Replace `{actual}` with `{expected}`")
} else {
"Remove default value".to_string()
}
}
}
/// Returns whether the given environment variable is allowed to be lowercase.
///
/// References:
/// - <https://unix.stackexchange.com/a/212972/>
/// - <https://about.gitlab.com/blog/2021/01/27/we-need-to-talk-no-proxy/#http_proxy-and-https_proxy/>
fn is_lowercase_allowed(env_var: &str) -> bool {
matches!(env_var, "https_proxy" | "http_proxy" | "no_proxy")
}
/// SIM112
pub(crate) fn use_capital_environment_variables(checker: &Checker, expr: &Expr) {
if !checker.semantic().seen_module(Modules::OS) {
return;
}
// Ex) `os.environ['foo']`
if let Expr::Subscript(_) = expr {
check_os_environ_subscript(checker, expr);
return;
}
// Ex) `os.environ.get('foo')`, `os.getenv('foo')`
let Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, .. },
..
}) = expr
else {
return;
};
let Some(arg) = args.first() else {
return;
};
let Expr::StringLiteral(ast::ExprStringLiteral { value: env_var, .. }) = arg else {
return;
};
if !checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["os", "environ", "get"] | ["os", "getenv"]
)
})
{
return;
}
if is_lowercase_allowed(env_var.to_str()) {
return;
}
let capital_env_var = env_var.to_str().to_ascii_uppercase();
if capital_env_var == env_var.to_str() {
return;
}
checker.report_diagnostic(
UncapitalizedEnvironmentVariables {
expected: SourceCodeSnippet::new(capital_env_var),
actual: SourceCodeSnippet::new(env_var.to_string()),
},
arg.range(),
);
}
fn check_os_environ_subscript(checker: &Checker, expr: &Expr) {
let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr else {
return;
};
let Expr::Attribute(ast::ExprAttribute {
value: attr_value,
attr,
..
}) = value.as_ref()
else {
return;
};
let Expr::Name(ast::ExprName { id, .. }) = attr_value.as_ref() else {
return;
};
if id != "os" || attr != "environ" {
return;
}
let Expr::StringLiteral(ast::ExprStringLiteral { value: env_var, .. }) = slice.as_ref() else {
return;
};
if is_lowercase_allowed(env_var.to_str()) {
return;
}
let capital_env_var = env_var.to_str().to_ascii_uppercase();
if capital_env_var == env_var.to_str() {
return;
}
let mut diagnostic = checker.report_diagnostic(
UncapitalizedEnvironmentVariables {
expected: SourceCodeSnippet::new(capital_env_var.clone()),
actual: SourceCodeSnippet::new(env_var.to_string()),
},
slice.range(),
);
let node = ast::StringLiteral {
value: capital_env_var.into_boxed_str(),
flags: checker.default_string_flags().with_prefix({
if env_var.is_unicode() {
StringLiteralPrefix::Unicode
} else {
StringLiteralPrefix::Empty
}
}),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let new_env_var = node.into();
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&new_env_var),
slice.range(),
)));
}
/// SIM910
pub(crate) fn dict_get_with_none_default(checker: &Checker, expr: &Expr) {
let Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, keywords, .. },
range: _,
node_index: _,
}) = expr
else {
return;
};
if !keywords.is_empty() {
return;
}
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else {
return;
};
if attr != "get" {
return;
}
let Some(key) = args.first() else {
return;
};
if !crate::preview::is_sim910_expanded_key_support_enabled(checker.settings()) {
if !(key.is_literal_expr() || key.is_name_expr()) {
return;
}
}
let Some(default) = args.get(1) else {
return;
};
if !default.is_none_literal_expr() {
return;
}
// Check if the value is a dictionary.
match value.as_ref() {
Expr::Dict(_) | Expr::DictComp(_) => {}
Expr::Name(name) => {
let Some(binding) = checker
.semantic()
.resolve_name(name)
.map(|id| checker.semantic().binding(id))
else {
return;
};
if !is_dict(binding, checker.semantic()) {
return;
}
}
_ => return,
}
let expected = format!(
"{}({})",
checker.locator().slice(func.as_ref()),
checker.locator().slice(key)
);
let actual = checker.locator().slice(expr);
let mut diagnostic = checker.report_diagnostic(
DictGetWithNoneDefault {
expected: SourceCodeSnippet::new(expected.clone()),
actual: SourceCodeSnippet::from_str(actual),
},
expr.range(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
expected,
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_simplify/rules/ast_unary_op.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/ast_unary_op.rs | use ruff_python_ast::{self as ast, Arguments, CmpOp, Expr, ExprContext, Stmt, UnaryOp};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::Name;
use ruff_python_semantic::ScopeKind;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for negated `==` operators.
///
/// ## Why is this bad?
/// Negated `==` operators are less readable than `!=` operators. When testing
/// for non-equality, it is more common to use `!=` than `==`.
///
/// ## Example
/// ```python
/// not a == b
/// ```
///
/// Use instead:
/// ```python
/// a != b
/// ```
///
/// ## Fix safety
/// The fix is marked as unsafe, as it might change the behaviour
/// if `a` and/or `b` overrides `__eq__`/`__ne__`
/// in such a manner that they don't return booleans.
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.213")]
pub(crate) struct NegateEqualOp {
left: String,
right: String,
}
impl AlwaysFixableViolation for NegateEqualOp {
#[derive_message_formats]
fn message(&self) -> String {
let NegateEqualOp { left, right } = self;
format!("Use `{left} != {right}` instead of `not {left} == {right}`")
}
fn fix_title(&self) -> String {
"Replace with `!=` operator".to_string()
}
}
/// ## What it does
/// Checks for negated `!=` operators.
///
/// ## Why is this bad?
/// Negated `!=` operators are less readable than `==` operators, as they avoid a
/// double negation.
///
/// ## Example
/// ```python
/// not a != b
/// ```
///
/// Use instead:
/// ```python
/// a == b
/// ```
///
/// ## Fix safety
/// The fix is marked as unsafe, as it might change the behaviour
/// if `a` and/or `b` overrides `__ne__`/`__eq__`
/// in such a manner that they don't return booleans.
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.213")]
pub(crate) struct NegateNotEqualOp {
left: String,
right: String,
}
impl AlwaysFixableViolation for NegateNotEqualOp {
#[derive_message_formats]
fn message(&self) -> String {
let NegateNotEqualOp { left, right } = self;
format!("Use `{left} == {right}` instead of `not {left} != {right}`")
}
fn fix_title(&self) -> String {
"Replace with `==` operator".to_string()
}
}
/// ## What it does
/// Checks for double negations (i.e., multiple `not` operators).
///
/// ## Why is this bad?
/// A double negation is redundant and less readable than omitting the `not`
/// operators entirely.
///
/// ## Example
/// ```python
/// not (not a)
/// ```
///
/// Use instead:
/// ```python
/// a
/// ```
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.213")]
pub(crate) struct DoubleNegation {
expr: String,
}
impl AlwaysFixableViolation for DoubleNegation {
#[derive_message_formats]
fn message(&self) -> String {
let DoubleNegation { expr } = self;
format!("Use `{expr}` instead of `not (not {expr})`")
}
fn fix_title(&self) -> String {
let DoubleNegation { expr } = self;
format!("Replace with `{expr}`")
}
}
fn is_dunder_method(name: &str) -> bool {
matches!(
name,
"__eq__" | "__ne__" | "__lt__" | "__le__" | "__gt__" | "__ge__"
)
}
fn is_exception_check(stmt: &Stmt) -> bool {
let Stmt::If(ast::StmtIf { body, .. }) = stmt else {
return false;
};
matches!(body.as_slice(), [Stmt::Raise(_)])
}
/// SIM201
pub(crate) fn negation_with_equal_op(checker: &Checker, expr: &Expr, op: UnaryOp, operand: &Expr) {
if !matches!(op, UnaryOp::Not) {
return;
}
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
}) = operand
else {
return;
};
if !matches!(&ops[..], [CmpOp::Eq]) {
return;
}
if is_exception_check(checker.semantic().current_statement()) {
return;
}
// Avoid flagging issues in dunder implementations.
if let ScopeKind::Function(ast::StmtFunctionDef { name, .. }) =
&checker.semantic().current_scope().kind
{
if is_dunder_method(name) {
return;
}
}
let mut diagnostic = checker.report_diagnostic(
NegateEqualOp {
left: checker.generator().expr(left),
right: checker.generator().expr(&comparators[0]),
},
expr.range(),
);
let node = ast::ExprCompare {
left: left.clone(),
ops: Box::from([CmpOp::NotEq]),
comparators: comparators.clone(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node.into()),
expr.range(),
)));
}
/// SIM202
pub(crate) fn negation_with_not_equal_op(
checker: &Checker,
expr: &Expr,
op: UnaryOp,
operand: &Expr,
) {
if !matches!(op, UnaryOp::Not) {
return;
}
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
}) = operand
else {
return;
};
if !matches!(&**ops, [CmpOp::NotEq]) {
return;
}
if is_exception_check(checker.semantic().current_statement()) {
return;
}
// Avoid flagging issues in dunder implementations.
if let ScopeKind::Function(ast::StmtFunctionDef { name, .. }) =
&checker.semantic().current_scope().kind
{
if is_dunder_method(name) {
return;
}
}
let mut diagnostic = checker.report_diagnostic(
NegateNotEqualOp {
left: checker.generator().expr(left),
right: checker.generator().expr(&comparators[0]),
},
expr.range(),
);
let node = ast::ExprCompare {
left: left.clone(),
ops: Box::from([CmpOp::Eq]),
comparators: comparators.clone(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&node.into()),
expr.range(),
)));
}
/// SIM208
pub(crate) fn double_negation(checker: &Checker, expr: &Expr, op: UnaryOp, operand: &Expr) {
if !matches!(op, UnaryOp::Not) {
return;
}
let Expr::UnaryOp(ast::ExprUnaryOp {
op: operand_op,
operand,
range: _,
node_index: _,
}) = operand
else {
return;
};
if !matches!(operand_op, UnaryOp::Not) {
return;
}
let mut diagnostic = checker.report_diagnostic(
DoubleNegation {
expr: checker.generator().expr(operand),
},
expr.range(),
);
if checker.semantic().in_boolean_test() {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
checker.locator().slice(operand.as_ref()).to_string(),
expr.range(),
)));
} else if checker.semantic().has_builtin_binding("bool") {
let node = ast::ExprName {
id: Name::new_static("bool"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node1 = ast::ExprCall {
func: Box::new(node.into()),
arguments: Arguments {
args: Box::from([*operand.clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
checker.generator().expr(&node1.into()),
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_simplify/rules/if_else_block_instead_of_if_exp.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_if_exp.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::contains_effect;
use ruff_python_ast::{self as ast, BoolOp, ElifElseClause, Expr, Stmt};
use ruff_python_semantic::analyze::typing::{is_sys_version_block, is_type_checking_block};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::fits;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Check for `if`-`else`-blocks that can be replaced with a ternary
/// or binary operator.
///
/// The lint is suppressed if the suggested replacement would exceed
/// the maximum line length configured in [pycodestyle.max-line-length].
///
/// ## Why is this bad?
/// `if`-`else`-blocks that assign a value to a variable in both branches can
/// be expressed more concisely by using a ternary or binary operator.
///
/// ## Example
///
/// ```python
/// if foo:
/// bar = x
/// else:
/// bar = y
/// ```
///
/// Use instead:
/// ```python
/// bar = x if foo else y
/// ```
///
/// Or:
///
/// ```python
/// if cond:
/// z = cond
/// else:
/// z = other_cond
/// ```
///
/// Use instead:
///
/// ```python
/// z = cond or other_cond
/// ```
///
/// ## Known issues
/// This is an opinionated style rule that may not always be to everyone's
/// taste, especially for code that makes use of complex `if` conditions.
/// Ternary operators can also make it harder to measure [code coverage]
/// with tools that use line profiling.
///
/// ## Options
///
/// - `lint.pycodestyle.max-line-length`
/// - `indent-width`
///
/// ## References
/// - [Python documentation: Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions)
///
/// [code coverage]: https://github.com/nedbat/coveragepy/issues/509
/// [pycodestyle.max-line-length]: https://docs.astral.sh/ruff/settings/#lint_pycodestyle_max-line-length
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.213")]
pub(crate) struct IfElseBlockInsteadOfIfExp {
/// The ternary or binary expression to replace the `if`-`else`-block.
contents: String,
/// Whether to use a binary or ternary assignment.
kind: AssignmentKind,
}
impl Violation for IfElseBlockInsteadOfIfExp {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let IfElseBlockInsteadOfIfExp { contents, kind } = self;
match kind {
AssignmentKind::Ternary => {
format!("Use ternary operator `{contents}` instead of `if`-`else`-block")
}
AssignmentKind::Binary => {
format!("Use binary operator `{contents}` instead of `if`-`else`-block")
}
}
}
fn fix_title(&self) -> Option<String> {
let IfElseBlockInsteadOfIfExp { contents, .. } = self;
Some(format!("Replace `if`-`else`-block with `{contents}`"))
}
}
/// SIM108
pub(crate) fn if_else_block_instead_of_if_exp(checker: &Checker, stmt_if: &ast::StmtIf) {
let ast::StmtIf {
test,
body,
elif_else_clauses,
range: _,
node_index: _,
} = stmt_if;
// `test: None` to only match an `else` clause
let [
ElifElseClause {
body: else_body,
test: None,
..
},
] = elif_else_clauses.as_slice()
else {
return;
};
let [
Stmt::Assign(ast::StmtAssign {
targets: body_targets,
value: body_value,
..
}),
] = body.as_slice()
else {
return;
};
let [
Stmt::Assign(ast::StmtAssign {
targets: else_targets,
value: else_value,
..
}),
] = else_body.as_slice()
else {
return;
};
let ([body_target], [else_target]) = (body_targets.as_slice(), else_targets.as_slice()) else {
return;
};
let Expr::Name(ast::ExprName { id: body_id, .. }) = body_target else {
return;
};
let Expr::Name(ast::ExprName { id: else_id, .. }) = else_target else {
return;
};
if body_id != else_id {
return;
}
// Avoid suggesting ternary for `if (yield ...)`-style checks.
// TODO(charlie): Fix precedence handling for yields in generator.
if matches!(
body_value.as_ref(),
Expr::Yield(_) | Expr::YieldFrom(_) | Expr::Await(_)
) {
return;
}
if matches!(
else_value.as_ref(),
Expr::Yield(_) | Expr::YieldFrom(_) | Expr::Await(_)
) {
return;
}
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
if is_sys_version_block(stmt_if, checker.semantic()) {
return;
}
// Avoid suggesting ternary for `if TYPE_CHECKING:`-style checks.
if is_type_checking_block(stmt_if, checker.semantic()) {
return;
}
// In most cases we should now suggest a ternary operator,
// but there are three edge cases where a binary operator
// is more appropriate.
//
// For the reader's convenience, here is how
// the notation translates to the if-else block:
//
// ```python
// if test:
// target_var = body_value
// else:
// target_var = else_value
// ```
//
// The match statement below implements the following
// logic:
// - If `test == body_value`, replace with `target_var = test or else_value`
// - If `test == not body_value`, replace with `target_var = body_value and else_value`
// - If `not test == body_value`, replace with `target_var = body_value and else_value`
// - Otherwise, replace with `target_var = body_value if test else else_value`
let (contents, assignment_kind) = match (test, body_value) {
(test_node, body_node)
if ComparableExpr::from(test_node) == ComparableExpr::from(body_node)
&& !contains_effect(test_node, |id| checker.semantic().has_builtin_binding(id)) =>
{
let target_var = &body_target;
let binary = assignment_binary_or(target_var, body_value, else_value);
(checker.generator().stmt(&binary), AssignmentKind::Binary)
}
(test_node, body_node)
if (test_node.as_unary_op_expr().is_some_and(|op_expr| {
op_expr.op.is_not()
&& ComparableExpr::from(&op_expr.operand) == ComparableExpr::from(body_node)
}) || body_node.as_unary_op_expr().is_some_and(|op_expr| {
op_expr.op.is_not()
&& ComparableExpr::from(&op_expr.operand) == ComparableExpr::from(test_node)
})) && !contains_effect(test_node, |id| {
checker.semantic().has_builtin_binding(id)
}) =>
{
let target_var = &body_target;
let binary = assignment_binary_and(target_var, body_value, else_value);
(checker.generator().stmt(&binary), AssignmentKind::Binary)
}
_ => {
let target_var = &body_target;
let ternary = assignment_ternary(target_var, body_value, test, else_value);
(checker.generator().stmt(&ternary), AssignmentKind::Ternary)
}
};
// Don't flag if the resulting expression would exceed the maximum line length.
if !fits(
&contents,
stmt_if.into(),
checker.locator(),
checker.settings().pycodestyle.max_line_length,
checker.settings().tab_size,
) {
return;
}
let mut diagnostic = checker.report_diagnostic(
IfElseBlockInsteadOfIfExp {
contents: contents.clone(),
kind: assignment_kind,
},
stmt_if.range(),
);
if !checker
.comment_ranges()
.has_comments(stmt_if, checker.source())
{
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
contents,
stmt_if.range(),
)));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AssignmentKind {
Binary,
Ternary,
}
fn assignment_ternary(
target_var: &Expr,
body_value: &Expr,
test: &Expr,
orelse_value: &Expr,
) -> Stmt {
let node = ast::ExprIf {
test: Box::new(test.clone()),
body: Box::new(body_value.clone()),
orelse: Box::new(orelse_value.clone()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node1 = ast::StmtAssign {
targets: vec![target_var.clone()],
value: Box::new(node.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
node1.into()
}
fn assignment_binary_and(target_var: &Expr, left_value: &Expr, right_value: &Expr) -> Stmt {
let node = ast::ExprBoolOp {
op: BoolOp::And,
values: vec![left_value.clone(), right_value.clone()],
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node1 = ast::StmtAssign {
targets: vec![target_var.clone()],
value: Box::new(node.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
node1.into()
}
fn assignment_binary_or(target_var: &Expr, left_value: &Expr, right_value: &Expr) -> Stmt {
(ast::StmtAssign {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
targets: vec![target_var.clone()],
value: Box::new(
(ast::ExprBoolOp {
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
op: BoolOp::Or,
values: vec![left_value.clone(), right_value.clone()],
})
.into(),
),
})
.into()
}
| 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_simplify/rules/open_file_with_context_handler.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs | use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::{ScopeKind, SemanticModel};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for cases where files are opened (e.g., using the builtin `open()` function)
/// without using a context manager.
///
/// ## Why is this bad?
/// If a file is opened without a context manager, it is not guaranteed that
/// the file will be closed (e.g., if an exception is raised), which can cause
/// resource leaks. The rule detects a wide array of IO calls where context managers
/// could be used, such as `open`, `pathlib.Path(...).open()`, `tempfile.TemporaryFile()`
/// or`tarfile.TarFile(...).gzopen()`.
///
/// ## Example
/// ```python
/// file = open("foo.txt")
/// ...
/// file.close()
/// ```
///
/// Use instead:
/// ```python
/// with open("foo.txt") as file:
/// ...
/// ```
///
/// ## References
/// - [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.219")]
pub(crate) struct OpenFileWithContextHandler;
impl Violation for OpenFileWithContextHandler {
#[derive_message_formats]
fn message(&self) -> String {
"Use a context manager for opening files".to_string()
}
}
/// Return `true` if the current expression is nested in an `await
/// exit_stack.enter_async_context` call.
fn match_async_exit_stack(semantic: &SemanticModel) -> bool {
let Some(expr) = semantic.current_expression_grandparent() else {
return false;
};
let Expr::Await(ast::ExprAwait {
value,
range: _,
node_index: _,
}) = expr
else {
return false;
};
let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else {
return false;
};
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
return false;
};
if attr != "enter_async_context" {
return false;
}
for parent in semantic.current_statements() {
if let Stmt::With(ast::StmtWith { items, .. }) = parent {
for item in items {
if let Expr::Call(ast::ExprCall { func, .. }) = &item.context_expr {
if semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["contextlib", "AsyncExitStack"])
})
{
return true;
}
}
}
}
}
false
}
/// Return `true` if the current expression is nested in an
/// `exit_stack.enter_context` call.
fn match_exit_stack(semantic: &SemanticModel) -> bool {
let Some(expr) = semantic.current_expression_parent() else {
return false;
};
let Expr::Call(ast::ExprCall { func, .. }) = expr else {
return false;
};
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
return false;
};
if attr != "enter_context" {
return false;
}
for parent in semantic.current_statements() {
if let Stmt::With(ast::StmtWith { items, .. }) = parent {
for item in items {
if let Expr::Call(ast::ExprCall { func, .. }) = &item.context_expr {
if semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["contextlib", "ExitStack"])
})
{
return true;
}
}
}
}
}
false
}
/// Return `true` if the current expression is nested in a call to one of the
/// unittest context manager methods: `cls.enterClassContext()`,
/// `self.enterContext()`, or `self.enterAsyncContext()`.
fn match_unittest_context_methods(semantic: &SemanticModel) -> bool {
let Some(expr) = semantic.current_expression_parent() else {
return false;
};
let Expr::Call(ast::ExprCall { func, .. }) = expr else {
return false;
};
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func.as_ref() else {
return false;
};
let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else {
return false;
};
matches!(
(id.as_str(), attr.as_str()),
("cls", "enterClassContext") | ("self", "enterContext" | "enterAsyncContext")
)
}
/// Return `true` if the expression is a call to `open()`,
/// or a call to some other standard-library function that opens a file.
fn is_open_call(semantic: &SemanticModel, call: &ast::ExprCall) -> bool {
let func = &*call.func;
// Ex) `open(...)`
if let Some(qualified_name) = semantic.resolve_qualified_name(func) {
return matches!(
qualified_name.segments(),
[
"" | "builtins"
| "bz2"
| "codecs"
| "dbm"
| "gzip"
| "tarfile"
| "shelve"
| "tokenize"
| "wave",
"open"
] | ["dbm", "gnu" | "ndbm" | "dumb" | "sqlite3", "open"]
| ["fileinput", "FileInput" | "input"]
| ["io", "open" | "open_code"]
| ["lzma", "LZMAFile" | "open"]
| ["tarfile", "TarFile", "taropen"]
| [
"tempfile",
"TemporaryFile" | "NamedTemporaryFile" | "SpooledTemporaryFile"
]
);
}
// Ex) `pathlib.Path(...).open()`
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func else {
return false;
};
let Expr::Call(ast::ExprCall { func, .. }) = &**value else {
return false;
};
// E.g. for `pathlib.Path(...).open()`, `qualified_name_of_instance.segments() == ["pathlib", "Path"]`
let Some(qualified_name_of_instance) = semantic.resolve_qualified_name(func) else {
return false;
};
matches!(
(qualified_name_of_instance.segments(), &**attr),
(
["pathlib", "Path"] | ["zipfile", "ZipFile"] | ["lzma", "LZMAFile"],
"open"
) | (
["tarfile", "TarFile"],
"open" | "taropen" | "gzopen" | "bz2open" | "xzopen"
)
)
}
/// Return `true` if the current expression is immediately followed by a `.close()` call.
fn is_immediately_closed(semantic: &SemanticModel) -> bool {
let Some(expr) = semantic.current_expression_grandparent() else {
return false;
};
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = expr
else {
return false;
};
if !arguments.is_empty() {
return false;
}
let Expr::Attribute(ast::ExprAttribute { attr, .. }) = func.as_ref() else {
return false;
};
attr.as_str() == "close"
}
/// SIM115
pub(crate) fn open_file_with_context_handler(checker: &Checker, call: &ast::ExprCall) {
let semantic = checker.semantic();
if !is_open_call(semantic, call) {
return;
}
// Ex) `open("foo.txt").close()`
if is_immediately_closed(semantic) {
return;
}
// Ex) `with open("foo.txt") as f: ...`
if semantic.current_statement().is_with_stmt() {
return;
}
// Ex) `return open("foo.txt")`
if semantic.current_statement().is_return_stmt() {
return;
}
// Ex) `with contextlib.ExitStack() as exit_stack: ...`
if match_exit_stack(semantic) {
return;
}
// Ex) `with contextlib.AsyncExitStack() as exit_stack: ...`
if match_async_exit_stack(semantic) {
return;
}
// Ex) `self.enterContext(open("foo.txt"))`
if match_unittest_context_methods(semantic) {
return;
}
// Ex) `def __enter__(self): ...`
if let ScopeKind::Function(ast::StmtFunctionDef { name, .. }) =
&checker.semantic().current_scope().kind
{
if name == "__enter__" {
return;
}
}
checker.report_diagnostic(OpenFileWithContextHandler, 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_simplify/rules/yoda_conditions.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/yoda_conditions.rs | use std::cmp;
use anyhow::Result;
use libcst_native::CompOp;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, CmpOp, Expr, UnaryOp};
use ruff_python_codegen::Stylist;
use ruff_python_stdlib::str::{self};
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::cst::helpers::or_space;
use crate::cst::matchers::{match_comparison, transform_expression};
use crate::fix::edits::pad;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for conditions that position a constant on the left-hand side of the
/// comparison operator, rather than the right-hand side.
///
/// ## Why is this bad?
/// These conditions (sometimes referred to as "Yoda conditions") are less
/// readable than conditions that place the variable on the left-hand side of
/// the comparison operator.
///
/// In some languages, Yoda conditions are used to prevent accidental
/// assignment in conditions (i.e., accidental uses of the `=` operator,
/// instead of the `==` operator). However, Python does not allow assignments
/// in conditions unless using the `:=` operator, so Yoda conditions provide
/// no benefit in this regard.
///
/// ## Example
/// ```python
/// if "Foo" == foo:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// if foo == "Foo":
/// ...
/// ```
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
/// - [Python documentation: Assignment statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.207")]
pub(crate) struct YodaConditions {
suggestion: Option<SourceCodeSnippet>,
}
impl Violation for YodaConditions {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Yoda condition detected".to_string()
}
fn fix_title(&self) -> Option<String> {
let YodaConditions { suggestion } = self;
suggestion
.as_ref()
.and_then(|suggestion| suggestion.full_display())
.map(|suggestion| format!("Rewrite as `{suggestion}`"))
}
}
/// Comparisons left-hand side must not be more [`ConstantLikelihood`] than the right-hand side.
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
enum ConstantLikelihood {
/// The expression is unlikely to be a constant (e.g., `foo` or `foo(bar)`).
Unlikely = 0,
/// The expression is likely to be a constant (e.g., `FOO`).
Probably = 1,
/// The expression is definitely a constant (e.g., `42` or `"foo"`).
Definitely = 2,
}
impl From<&Expr> for ConstantLikelihood {
/// Determine the [`ConstantLikelihood`] of an expression.
fn from(expr: &Expr) -> Self {
match expr {
_ if expr.is_literal_expr() => ConstantLikelihood::Definitely,
Expr::Attribute(ast::ExprAttribute { attr, .. }) => {
ConstantLikelihood::from_identifier(attr)
}
Expr::Name(ast::ExprName { id, .. }) => ConstantLikelihood::from_identifier(id),
Expr::Tuple(tuple) => tuple
.iter()
.map(ConstantLikelihood::from)
.min()
.unwrap_or(ConstantLikelihood::Definitely),
Expr::List(list) => list
.iter()
.map(ConstantLikelihood::from)
.min()
.unwrap_or(ConstantLikelihood::Definitely),
Expr::Dict(dict) => dict
.items
.iter()
.flat_map(|item| std::iter::once(&item.value).chain(item.key.as_ref()))
.map(ConstantLikelihood::from)
.min()
.unwrap_or(ConstantLikelihood::Definitely),
Expr::BinOp(ast::ExprBinOp { left, right, .. }) => cmp::min(
ConstantLikelihood::from(&**left),
ConstantLikelihood::from(&**right),
),
Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::UAdd | UnaryOp::USub | UnaryOp::Invert,
operand,
range: _,
node_index: _,
}) => ConstantLikelihood::from(&**operand),
_ => ConstantLikelihood::Unlikely,
}
}
}
impl ConstantLikelihood {
/// Determine the [`ConstantLikelihood`] of an identifier.
fn from_identifier(identifier: &str) -> Self {
if str::is_cased_uppercase(identifier) {
ConstantLikelihood::Probably
} else {
ConstantLikelihood::Unlikely
}
}
}
/// Generate a fix to reverse a comparison.
fn reverse_comparison(expr: &Expr, locator: &Locator, stylist: &Stylist) -> Result<String> {
let range = expr.range();
let source_code = locator.slice(range);
transform_expression(source_code, stylist, |mut expression| {
let comparison = match_comparison(&mut expression)?;
let left = (*comparison.left).clone();
// Copy the right side to the left side.
*comparison.left = comparison.comparisons[0].comparator.clone();
// Copy the left side to the right side.
comparison.comparisons[0].comparator = left;
// Reverse the operator.
let op = comparison.comparisons[0].operator.clone();
comparison.comparisons[0].operator = match op {
CompOp::LessThan {
whitespace_before,
whitespace_after,
} => CompOp::GreaterThan {
whitespace_before: or_space(whitespace_before),
whitespace_after: or_space(whitespace_after),
},
CompOp::GreaterThan {
whitespace_before,
whitespace_after,
} => CompOp::LessThan {
whitespace_before: or_space(whitespace_before),
whitespace_after: or_space(whitespace_after),
},
CompOp::LessThanEqual {
whitespace_before,
whitespace_after,
} => CompOp::GreaterThanEqual {
whitespace_before: or_space(whitespace_before),
whitespace_after: or_space(whitespace_after),
},
CompOp::GreaterThanEqual {
whitespace_before,
whitespace_after,
} => CompOp::LessThanEqual {
whitespace_before: or_space(whitespace_before),
whitespace_after: or_space(whitespace_after),
},
CompOp::Equal {
whitespace_before,
whitespace_after,
} => CompOp::Equal {
whitespace_before: or_space(whitespace_before),
whitespace_after: or_space(whitespace_after),
},
CompOp::NotEqual {
whitespace_before,
whitespace_after,
} => CompOp::NotEqual {
whitespace_before: or_space(whitespace_before),
whitespace_after: or_space(whitespace_after),
},
_ => panic!("Expected comparison operator"),
};
Ok(expression)
})
}
/// SIM300
pub(crate) fn yoda_conditions(
checker: &Checker,
expr: &Expr,
left: &Expr,
ops: &[CmpOp],
comparators: &[Expr],
) {
let ([op], [right]) = (ops, comparators) else {
return;
};
if !matches!(
op,
CmpOp::Eq | CmpOp::NotEq | CmpOp::Lt | CmpOp::LtE | CmpOp::Gt | CmpOp::GtE,
) {
return;
}
if ConstantLikelihood::from(left) <= ConstantLikelihood::from(right) {
return;
}
if let Ok(suggestion) = reverse_comparison(expr, checker.locator(), checker.stylist()) {
let mut diagnostic = checker.report_diagnostic(
YodaConditions {
suggestion: Some(SourceCodeSnippet::new(suggestion.clone())),
},
expr.range(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
pad(suggestion, expr.range(), checker.locator()),
expr.range(),
)));
} else {
checker.report_diagnostic(YodaConditions { suggestion: None }, 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_simplify/rules/fix_with.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/fix_with.rs | use anyhow::{Result, bail};
use libcst_native::{CompoundStatement, Statement, Suite, With};
use ruff_python_ast as ast;
use ruff_python_ast::whitespace;
use ruff_python_codegen::Stylist;
use ruff_source_file::LineRanges;
use ruff_text_size::Ranged;
use crate::Edit;
use crate::Locator;
use crate::cst::matchers::{match_function_def, match_indented_block, match_statement, match_with};
use crate::fix::codemods::CodegenStylist;
/// (SIM117) Convert `with a: with b:` to `with a, b:`.
pub(crate) fn fix_multiple_with_statements(
locator: &Locator,
stylist: &Stylist,
with_stmt: &ast::StmtWith,
) -> Result<Edit> {
// Infer the indentation of the outer block.
let Some(outer_indent) = whitespace::indentation(locator.contents(), with_stmt) else {
bail!("Unable to fix multiline statement");
};
// Extract the module text.
let contents = locator.lines_str(with_stmt.range());
// If the block is indented, "embed" it in a function definition, to preserve
// indentation while retaining valid source code. (We'll strip the prefix later
// on.)
let module_text = if outer_indent.is_empty() {
contents.to_string()
} else {
format!("def f():{}{contents}", stylist.line_ending().as_str())
};
// Parse the CST.
let mut tree = match_statement(&module_text)?;
let statement = if outer_indent.is_empty() {
&mut tree
} else {
let embedding = match_function_def(&mut tree)?;
let indented_block = match_indented_block(&mut embedding.body)?;
indented_block.indent = Some(outer_indent);
let Some(statement) = indented_block.body.first_mut() else {
bail!("Expected indented block to have at least one statement")
};
statement
};
let outer_with = match_with(statement)?;
let With {
body: Suite::IndentedBlock(outer_body),
..
} = outer_with
else {
bail!("Expected outer with to have indented body")
};
let [Statement::Compound(CompoundStatement::With(inner_with))] = &mut *outer_body.body else {
bail!("Expected one inner with statement");
};
outer_with.items.append(&mut inner_with.items);
if outer_with.lpar.is_none() {
outer_with.lpar.clone_from(&inner_with.lpar);
outer_with.rpar.clone_from(&inner_with.rpar);
}
outer_with.body = inner_with.body.clone();
// Reconstruct and reformat the code.
let module_text = tree.codegen_stylist(stylist);
let contents = if outer_indent.is_empty() {
module_text
} else {
module_text
.strip_prefix(&format!("def f():{}", stylist.line_ending().as_str()))
.unwrap()
.to_string()
};
let range = locator.lines_range(with_stmt.range());
Ok(Edit::range_replacement(contents, 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_simplify/rules/collapsible_if.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/collapsible_if.rs | use std::borrow::Cow;
use anyhow::{Result, bail};
use libcst_native::ParenthesizedNode;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::{self as ast, ElifElseClause, Expr, Stmt, whitespace};
use ruff_python_codegen::Stylist;
use ruff_python_semantic::analyze::typing::{is_sys_version_block, is_type_checking_block};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::cst::helpers::space;
use crate::cst::matchers::{match_function_def, match_if, match_indented_block, match_statement};
use crate::fix::codemods::CodegenStylist;
use crate::fix::edits::fits;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for nested `if` statements that can be collapsed into a single `if`
/// statement.
///
/// ## Why is this bad?
/// Nesting `if` statements leads to deeper indentation and makes code harder to
/// read. Instead, combine the conditions into a single `if` statement with an
/// `and` operator.
///
/// ## Example
/// ```python
/// if foo:
/// if bar:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// if foo and bar:
/// ...
/// ```
///
/// ## Options
///
/// The rule will consult these two settings when deciding if a fix can be provided:
///
/// - `lint.pycodestyle.max-line-length`
/// - `indent-width`
///
/// Lines that would exceed the configured line length will not be fixed automatically.
///
/// ## References
/// - [Python documentation: The `if` statement](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)
/// - [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct CollapsibleIf;
impl Violation for CollapsibleIf {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use a single `if` statement instead of nested `if` statements".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Combine `if` statements using `and`".to_string())
}
}
/// SIM102
pub(crate) fn nested_if_statements(
checker: &Checker,
stmt_if: &ast::StmtIf,
parent: Option<&Stmt>,
) {
let Some(nested_if) = nested_if_body(stmt_if) else {
return;
};
// Find the deepest nested if-statement, to inform the range.
let Some(test) = find_last_nested_if(nested_if.body()) else {
return;
};
// Check if the parent is already emitting a larger diagnostic including this if statement
if let Some(Stmt::If(stmt_if)) = parent {
if let Some(nested_if) = nested_if_body(stmt_if) {
// In addition to repeating the `nested_if_body` and `find_last_nested_if` check, we
// also need to be the first child in the parent
let body = nested_if.body();
if matches!(&body[0], Stmt::If(inner) if *inner == *stmt_if)
&& find_last_nested_if(body).is_some()
{
return;
}
}
}
let Some(colon) = SimpleTokenizer::starts_at(test.end(), checker.locator().contents())
.skip_trivia()
.find(|token| token.kind == SimpleTokenKind::Colon)
else {
return;
};
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
if is_sys_version_block(stmt_if, checker.semantic()) {
return;
}
// Avoid suggesting ternary for `if TYPE_CHECKING:`-style checks.
if is_type_checking_block(stmt_if, checker.semantic()) {
return;
}
let mut diagnostic = checker.report_diagnostic(
CollapsibleIf,
TextRange::new(nested_if.start(), colon.end()),
);
// The fixer preserves comments in the nested body, but removes comments between
// the outer and inner if statements.
if !checker.comment_ranges().intersects(TextRange::new(
nested_if.start(),
nested_if.body()[0].start(),
)) {
diagnostic.try_set_optional_fix(|| {
match collapse_nested_if(checker.locator(), checker.stylist(), nested_if) {
Ok(edit) => {
if edit.content().is_none_or(|content| {
fits(
content,
(&nested_if).into(),
checker.locator(),
checker.settings().pycodestyle.max_line_length,
checker.settings().tab_size,
)
}) {
Ok(Some(Fix::unsafe_edit(edit)))
} else {
Ok(None)
}
}
Err(err) => bail!("Failed to collapse `if`: {err}"),
}
});
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum NestedIf<'a> {
If(&'a ast::StmtIf),
Elif(&'a ElifElseClause),
}
impl<'a> NestedIf<'a> {
pub(super) fn body(self) -> &'a [Stmt] {
match self {
NestedIf::If(stmt_if) => &stmt_if.body,
NestedIf::Elif(clause) => &clause.body,
}
}
pub(super) fn is_elif(self) -> bool {
matches!(self, NestedIf::Elif(..))
}
}
impl Ranged for NestedIf<'_> {
fn range(&self) -> TextRange {
match self {
NestedIf::If(stmt_if) => stmt_if.range(),
NestedIf::Elif(clause) => clause.range(),
}
}
}
impl<'a> From<&NestedIf<'a>> for AnyNodeRef<'a> {
fn from(value: &NestedIf<'a>) -> Self {
match value {
NestedIf::If(stmt_if) => (*stmt_if).into(),
NestedIf::Elif(clause) => (*clause).into(),
}
}
}
/// Returns the body, the range of the `if` or `elif` and whether the range is for an `if` or `elif`
fn nested_if_body(stmt_if: &ast::StmtIf) -> Option<NestedIf<'_>> {
let ast::StmtIf {
test,
body,
elif_else_clauses,
..
} = stmt_if;
// It must be the last condition, otherwise there could be another `elif` or `else` that only
// depends on the outer of the two conditions
let (test, nested_if) = if let Some(clause) = elif_else_clauses.last() {
if let Some(test) = &clause.test {
(test, NestedIf::Elif(clause))
} else {
// The last condition is an `else` (different rule)
return None;
}
} else {
(test.as_ref(), NestedIf::If(stmt_if))
};
// The nested if must be the only child, otherwise there is at least one more statement that
// only depends on the outer condition
if body.len() > 1 {
return None;
}
// Allow `if __name__ == "__main__":` statements.
if is_main_check(test) {
return None;
}
// Allow `if True:` and `if False:` statements.
if test.is_boolean_literal_expr() {
return None;
}
Some(nested_if)
}
/// Find the last nested if statement and return the test expression and the
/// last statement.
///
/// ```python
/// if xxx:
/// if yyy:
/// # ^^^ returns this expression
/// z = 1
/// ...
/// ```
fn find_last_nested_if(body: &[Stmt]) -> Option<&Expr> {
let [
Stmt::If(ast::StmtIf {
test,
body: inner_body,
elif_else_clauses,
..
}),
] = body
else {
return None;
};
if !elif_else_clauses.is_empty() {
return None;
}
find_last_nested_if(inner_body).or(Some(test))
}
/// Returns `true` if an expression is an `if __name__ == "__main__":` check.
fn is_main_check(expr: &Expr) -> bool {
if let Expr::Compare(ast::ExprCompare {
left, comparators, ..
}) = expr
{
if let Expr::Name(ast::ExprName { id, .. }) = left.as_ref() {
if id == "__name__" {
if let [Expr::StringLiteral(ast::ExprStringLiteral { value, .. })] = &**comparators
{
if value == "__main__" {
return true;
}
}
}
}
}
false
}
fn parenthesize_and_operand(expr: libcst_native::Expression) -> libcst_native::Expression {
match &expr {
_ if !expr.lpar().is_empty() => expr,
libcst_native::Expression::BooleanOperation(boolean_operation)
if matches!(
boolean_operation.operator,
libcst_native::BooleanOp::Or { .. }
) =>
{
expr.with_parens(
libcst_native::LeftParen::default(),
libcst_native::RightParen::default(),
)
}
libcst_native::Expression::IfExp(_)
| libcst_native::Expression::Lambda(_)
| libcst_native::Expression::NamedExpr(_) => expr.with_parens(
libcst_native::LeftParen::default(),
libcst_native::RightParen::default(),
),
_ => expr,
}
}
/// Convert `if a: if b:` to `if a and b:`.
pub(super) fn collapse_nested_if(
locator: &Locator,
stylist: &Stylist,
nested_if: NestedIf,
) -> Result<Edit> {
// Infer the indentation of the outer block.
let Some(outer_indent) = whitespace::indentation(locator.contents(), &nested_if) else {
bail!("Unable to fix multiline statement");
};
// Extract the module text.
let contents = locator.lines_str(nested_if.range());
// If this is an `elif`, we have to remove the `elif` keyword for now. (We'll
// restore the `el` later on.)
let module_text = if nested_if.is_elif() {
Cow::Owned(contents.replacen("elif", "if", 1))
} else {
Cow::Borrowed(contents)
};
// If the block is indented, "embed" it in a function definition, to preserve
// indentation while retaining valid source code. (We'll strip the prefix later
// on.)
let module_text = if outer_indent.is_empty() {
module_text
} else {
Cow::Owned(format!(
"def f():{}{module_text}",
stylist.line_ending().as_str()
))
};
// Parse the CST.
let mut tree = match_statement(&module_text)?;
let statement = if outer_indent.is_empty() {
&mut tree
} else {
let embedding = match_function_def(&mut tree)?;
let indented_block = match_indented_block(&mut embedding.body)?;
indented_block.indent = Some(outer_indent);
let Some(statement) = indented_block.body.first_mut() else {
bail!("Expected indented block to have at least one statement")
};
statement
};
let outer_if = match_if(statement)?;
let libcst_native::If {
body: libcst_native::Suite::IndentedBlock(outer_body),
orelse: None,
..
} = outer_if
else {
bail!("Expected outer if to have indented body and no else")
};
let [
libcst_native::Statement::Compound(libcst_native::CompoundStatement::If(
inner_if @ libcst_native::If { orelse: None, .. },
)),
] = &mut *outer_body.body
else {
bail!("Expected one inner if statement");
};
outer_if.test =
libcst_native::Expression::BooleanOperation(Box::new(libcst_native::BooleanOperation {
left: Box::new(parenthesize_and_operand(outer_if.test.clone())),
operator: libcst_native::BooleanOp::And {
whitespace_before: space(),
whitespace_after: space(),
},
right: Box::new(parenthesize_and_operand(inner_if.test.clone())),
lpar: vec![],
rpar: vec![],
}));
outer_if.body = inner_if.body.clone();
// Reconstruct and reformat the code.
let module_text = tree.codegen_stylist(stylist);
let module_text = if outer_indent.is_empty() {
&module_text
} else {
module_text
.strip_prefix(&format!("def f():{}", stylist.line_ending().as_str()))
.unwrap()
};
let contents = if nested_if.is_elif() {
Cow::Owned(module_text.replacen("if", "elif", 1))
} else {
Cow::Borrowed(module_text)
};
let range = locator.lines_range(nested_if.range());
Ok(Edit::range_replacement(contents.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_simplify/rules/suppressible_exception.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/suppressible_exception.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers;
use ruff_python_ast::name::UnqualifiedName;
use ruff_python_ast::{self as ast, ExceptHandler, Stmt};
use ruff_source_file::LineRanges;
use ruff_text_size::Ranged;
use ruff_text_size::{TextLen, TextRange};
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `try`-`except`-`pass` blocks that can be replaced with the
/// `contextlib.suppress` context manager.
///
/// ## Why is this bad?
/// Using `contextlib.suppress` is more concise and directly communicates the
/// intent of the code: to suppress a given exception.
///
/// Note that `contextlib.suppress` is slower than using `try`-`except`-`pass`
/// directly. For performance-critical code, consider retaining the
/// `try`-`except`-`pass` pattern.
///
/// ## Example
/// ```python
/// try:
/// 1 / 0
/// except ZeroDivisionError:
/// pass
/// ```
///
/// Use instead:
/// ```python
/// import contextlib
///
/// with contextlib.suppress(ZeroDivisionError):
/// 1 / 0
/// ```
///
/// ## References
/// - [Python documentation: `contextlib.suppress`](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)
/// - [Python documentation: `try` statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)
/// - [a simpler `try`/`except` (and why maybe shouldn't)](https://www.youtube.com/watch?v=MZAJ8qnC7mk)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct SuppressibleException {
exception: String,
}
impl Violation for SuppressibleException {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let SuppressibleException { exception } = self;
format!("Use `contextlib.suppress({exception})` instead of `try`-`except`-`pass`")
}
fn fix_title(&self) -> Option<String> {
let SuppressibleException { exception } = self;
Some(format!(
"Replace `try`-`except`-`pass` with `with contextlib.suppress({exception}): ...`"
))
}
}
fn is_empty(body: &[Stmt]) -> bool {
match body {
[Stmt::Pass(_)] => true,
[
Stmt::Expr(ast::StmtExpr {
value,
range: _,
node_index: _,
}),
] => value.is_ellipsis_literal_expr(),
_ => false,
}
}
/// SIM105
pub(crate) fn suppressible_exception(
checker: &Checker,
stmt: &Stmt,
try_body: &[Stmt],
handlers: &[ExceptHandler],
orelse: &[Stmt],
finalbody: &[Stmt],
) {
if !matches!(
try_body,
[Stmt::Delete(_)
| Stmt::Assign(_)
| Stmt::AugAssign(_)
| Stmt::AnnAssign(_)
| Stmt::Assert(_)
| Stmt::Import(_)
| Stmt::ImportFrom(_)
| Stmt::Expr(_)
| Stmt::Pass(_)]
) || !orelse.is_empty()
|| !finalbody.is_empty()
{
return;
}
let [
ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
body, range, type_, ..
}),
] = handlers
else {
return;
};
if !is_empty(body) {
return;
}
let Some(handler_names) = helpers::extract_handled_exceptions(handlers)
.into_iter()
.map(|expr| UnqualifiedName::from_expr(expr).map(|name| name.to_string()))
.collect::<Option<Vec<String>>>()
else {
return;
};
let exception = if handler_names.is_empty() {
if type_.is_none() {
// case where there are no handler names provided at all
"BaseException".to_string()
} else {
// case where handler names is an empty tuple
String::new()
}
} else {
handler_names.join(", ")
};
let mut diagnostic = checker.report_diagnostic(
SuppressibleException {
exception: exception.clone(),
},
stmt.range(),
);
if !checker
.comment_ranges()
.has_comments(stmt, checker.source())
{
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("contextlib", "suppress"),
stmt.start(),
checker.semantic(),
)?;
let mut rest: Vec<Edit> = Vec::new();
let content: String;
if exception == "BaseException" && handler_names.is_empty() {
let (import_exception, binding_exception) =
checker.importer().get_or_import_symbol(
&ImportRequest::import("builtins", &exception),
stmt.start(),
checker.semantic(),
)?;
content = format!("with {binding}({binding_exception})");
rest.push(import_exception);
} else {
content = format!("with {binding}({exception})");
}
rest.push(Edit::range_deletion(
checker.locator().full_lines_range(*range),
));
rest.push(Edit::range_replacement(
content,
TextRange::at(stmt.start(), "try".text_len()),
));
Ok(Fix::unsafe_edits(import_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_simplify/rules/mod.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/mod.rs | pub(crate) use ast_bool_op::*;
pub(crate) use ast_expr::*;
pub(crate) use ast_ifexp::*;
pub(crate) use ast_unary_op::*;
pub(crate) use ast_with::*;
pub(crate) use collapsible_if::*;
pub(crate) use enumerate_for_loop::*;
pub(crate) use if_else_block_instead_of_dict_get::*;
pub(crate) use if_else_block_instead_of_dict_lookup::*;
pub(crate) use if_else_block_instead_of_if_exp::*;
pub(crate) use if_with_same_arms::*;
pub(crate) use key_in_dict::*;
pub(crate) use needless_bool::*;
pub(crate) use open_file_with_context_handler::*;
pub(crate) use reimplemented_builtin::*;
pub(crate) use return_in_try_except_finally::*;
pub(crate) use split_static_string::*;
pub(crate) use suppressible_exception::*;
pub(crate) use yoda_conditions::*;
pub(crate) use zip_dict_keys_and_values::*;
mod ast_bool_op;
mod ast_expr;
mod ast_ifexp;
mod ast_unary_op;
mod ast_with;
mod collapsible_if;
mod enumerate_for_loop;
mod fix_with;
mod if_else_block_instead_of_dict_get;
mod if_else_block_instead_of_dict_lookup;
mod if_else_block_instead_of_if_exp;
mod if_with_same_arms;
mod key_in_dict;
mod needless_bool;
mod open_file_with_context_handler;
mod reimplemented_builtin;
mod return_in_try_except_finally;
mod split_static_string;
mod suppressible_exception;
mod yoda_conditions;
mod zip_dict_keys_and_values;
| 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_simplify/rules/ast_bool_op.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/ast_bool_op.rs | use std::collections::BTreeMap;
use std::iter;
use itertools::Either::{Left, Right};
use itertools::Itertools;
use ruff_python_ast::{self as ast, Arguments, BoolOp, CmpOp, Expr, ExprContext, UnaryOp};
use ruff_text_size::{Ranged, TextRange};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::{Truthiness, contains_effect};
use ruff_python_ast::name::Name;
use ruff_python_ast::token::parenthesized_range;
use ruff_python_codegen::Generator;
use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::{AlwaysFixableViolation, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for multiple `isinstance` calls on the same target.
///
/// ## Why is this bad?
/// To check if an object is an instance of any one of multiple types
/// or classes, it is unnecessary to use multiple `isinstance` calls, as
/// the second argument of the `isinstance` built-in function accepts a
/// tuple of types and classes.
///
/// Using a single `isinstance` call implements the same behavior with more
/// concise code and clearer intent.
///
/// ## Example
/// ```python
/// if isinstance(obj, int) or isinstance(obj, float):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// if isinstance(obj, (int, float)):
/// pass
/// ```
///
/// ## References
/// - [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.212")]
pub(crate) struct DuplicateIsinstanceCall {
name: Option<String>,
}
impl Violation for DuplicateIsinstanceCall {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
if let Some(name) = &self.name {
format!("Multiple `isinstance` calls for `{name}`, merge into a single call")
} else {
"Multiple `isinstance` calls for expression, merge into a single call".to_string()
}
}
fn fix_title(&self) -> Option<String> {
Some(if let Some(name) = &self.name {
format!("Merge `isinstance` calls for `{name}`")
} else {
"Merge `isinstance` calls".to_string()
})
}
}
/// ## What it does
/// Checks for boolean expressions that contain multiple equality comparisons
/// to the same value.
///
/// ## Why is this bad?
/// To check if an object is equal to any one of multiple values, it's more
/// concise to use the `in` operator with a tuple of values.
///
/// ## Example
/// ```python
/// if foo == x or foo == y:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// if foo in (x, y):
/// ...
/// ```
///
/// ## References
/// - [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.213")]
pub(crate) struct CompareWithTuple {
replacement: String,
}
impl AlwaysFixableViolation for CompareWithTuple {
#[derive_message_formats]
fn message(&self) -> String {
let CompareWithTuple { replacement } = self;
format!("Use `{replacement}` instead of multiple equality comparisons")
}
fn fix_title(&self) -> String {
let CompareWithTuple { replacement } = self;
format!("Replace with `{replacement}`")
}
}
/// ## What it does
/// Checks for `and` expressions that include both an expression and its
/// negation.
///
/// ## Why is this bad?
/// An `and` expression that includes both an expression and its negation will
/// always evaluate to `False`.
///
/// ## Example
/// ```python
/// x and not x
/// ```
///
/// ## References
/// - [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct ExprAndNotExpr {
name: String,
}
impl AlwaysFixableViolation for ExprAndNotExpr {
#[derive_message_formats]
fn message(&self) -> String {
let ExprAndNotExpr { name } = self;
format!("Use `False` instead of `{name} and not {name}`")
}
fn fix_title(&self) -> String {
"Replace with `False`".to_string()
}
}
/// ## What it does
/// Checks for `or` expressions that include both an expression and its
/// negation.
///
/// ## Why is this bad?
/// An `or` expression that includes both an expression and its negation will
/// always evaluate to `True`.
///
/// ## Example
/// ```python
/// x or not x
/// ```
///
/// ## References
/// - [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct ExprOrNotExpr {
name: String,
}
impl AlwaysFixableViolation for ExprOrNotExpr {
#[derive_message_formats]
fn message(&self) -> String {
let ExprOrNotExpr { name } = self;
format!("Use `True` instead of `{name} or not {name}`")
}
fn fix_title(&self) -> String {
"Replace with `True`".to_string()
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ContentAround {
Before,
After,
Both,
}
/// ## What it does
/// Checks for `or` expressions that contain truthy values.
///
/// ## Why is this bad?
/// If the expression is used as a condition, it can be replaced in-full with
/// `True`.
///
/// In other cases, the expression can be short-circuited to the first truthy
/// value.
///
/// By using `True` (or the first truthy value), the code is more concise
/// and easier to understand, since it no longer contains redundant conditions.
///
/// ## Example
/// ```python
/// if x or [1] or y:
/// pass
///
/// a = x or [1] or y
/// ```
///
/// Use instead:
/// ```python
/// if True:
/// pass
///
/// a = x or [1]
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct ExprOrTrue {
expr: String,
remove: ContentAround,
}
impl AlwaysFixableViolation for ExprOrTrue {
#[derive_message_formats]
fn message(&self) -> String {
let ExprOrTrue { expr, remove } = self;
let replaced = match remove {
ContentAround::After => format!("{expr} or ..."),
ContentAround::Before => format!("... or {expr}"),
ContentAround::Both => format!("... or {expr} or ..."),
};
format!("Use `{expr}` instead of `{replaced}`")
}
fn fix_title(&self) -> String {
let ExprOrTrue { expr, .. } = self;
format!("Replace with `{expr}`")
}
}
/// ## What it does
/// Checks for `and` expressions that contain falsey values.
///
/// ## Why is this bad?
/// If the expression is used as a condition, it can be replaced in-full with
/// `False`.
///
/// In other cases, the expression can be short-circuited to the first falsey
/// value.
///
/// By using `False` (or the first falsey value), the code is more concise
/// and easier to understand, since it no longer contains redundant conditions.
///
/// ## Example
/// ```python
/// if x and [] and y:
/// pass
///
/// a = x and [] and y
/// ```
///
/// Use instead:
/// ```python
/// if False:
/// pass
///
/// a = x and []
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.208")]
pub(crate) struct ExprAndFalse {
expr: String,
remove: ContentAround,
}
impl AlwaysFixableViolation for ExprAndFalse {
#[derive_message_formats]
fn message(&self) -> String {
let ExprAndFalse { expr, remove } = self;
let replaced = match remove {
ContentAround::After => format!(r#"{expr} and ..."#),
ContentAround::Before => format!("... and {expr}"),
ContentAround::Both => format!("... and {expr} and ..."),
};
format!("Use `{expr}` instead of `{replaced}`")
}
fn fix_title(&self) -> String {
let ExprAndFalse { expr, .. } = self;
format!("Replace with `{expr}`")
}
}
/// Return `true` if two `Expr` instances are equivalent names.
pub(crate) fn is_same_expr<'a>(a: &'a Expr, b: &'a Expr) -> Option<&'a str> {
if let (Expr::Name(ast::ExprName { id: a, .. }), Expr::Name(ast::ExprName { id: b, .. })) =
(&a, &b)
{
if a == b {
return Some(a);
}
}
None
}
/// If `call` is an `isinstance()` call, return its target.
fn isinstance_target<'a>(call: &'a Expr, semantic: &'a SemanticModel) -> Option<&'a Expr> {
// Verify that this is an `isinstance` call.
let ast::ExprCall {
func,
arguments:
Arguments {
args,
keywords,
range: _,
node_index: _,
},
range: _,
node_index: _,
} = call.as_call_expr()?;
if args.len() != 2 {
return None;
}
if !keywords.is_empty() {
return None;
}
if !semantic.match_builtin_expr(func, "isinstance") {
return None;
}
// Collect the target (e.g., `obj` in `isinstance(obj, int)`).
Some(&args[0])
}
/// SIM101
pub(crate) fn duplicate_isinstance_call(checker: &Checker, expr: &Expr) {
let Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::Or,
values,
range: _,
node_index: _,
}) = expr
else {
return;
};
// Locate duplicate `isinstance` calls, represented as a vector of vectors
// of indices of the relevant `Expr` instances in `values`.
let mut duplicates: Vec<Vec<usize>> = Vec::new();
let mut last_target_option: Option<ComparableExpr> = None;
for (index, call) in values.iter().enumerate() {
let Some(target) = isinstance_target(call, checker.semantic()) else {
last_target_option = None;
continue;
};
if last_target_option
.as_ref()
.is_some_and(|last_target| *last_target == ComparableExpr::from(target))
{
duplicates
.last_mut()
.expect("last_target should have a corresponding entry")
.push(index);
} else {
last_target_option = Some(target.into());
duplicates.push(vec![index]);
}
}
// Generate a `Diagnostic` for each duplicate.
for indices in duplicates {
if indices.len() > 1 {
// Grab the target used in each duplicate `isinstance` call (e.g., `obj` in
// `isinstance(obj, int)`).
let target = if let Expr::Call(ast::ExprCall {
arguments: Arguments { args, .. },
..
}) = &values[indices[0]]
{
args.first()
.expect("`isinstance` should have two arguments")
} else {
unreachable!("Indices should only contain `isinstance` calls")
};
let mut diagnostic = checker.report_diagnostic(
DuplicateIsinstanceCall {
name: if let Expr::Name(ast::ExprName { id, .. }) = target {
Some(id.to_string())
} else {
None
},
},
expr.range(),
);
if !contains_effect(target, |id| checker.semantic().has_builtin_binding(id)) {
// Grab the types used in each duplicate `isinstance` call (e.g., `int` and `str`
// in `isinstance(obj, int) or isinstance(obj, str)`).
let types: Vec<&Expr> = indices
.iter()
.map(|index| &values[*index])
.map(|expr| {
let Expr::Call(ast::ExprCall {
arguments: Arguments { args, .. },
..
}) = expr
else {
unreachable!("Indices should only contain `isinstance` calls")
};
args.get(1).expect("`isinstance` should have two arguments")
})
.collect();
// Generate a single `isinstance` call.
let tuple = ast::ExprTuple {
// Flatten all the types used across the `isinstance` calls.
elts: types
.iter()
.flat_map(|value| {
if let Expr::Tuple(tuple) = value {
Left(tuple.iter())
} else {
Right(iter::once(*value))
}
})
.map(Clone::clone)
.collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
};
let isinstance_call = ast::ExprCall {
func: Box::new(
ast::ExprName {
id: Name::new_static("isinstance"),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
arguments: Arguments {
args: Box::from([target.clone(), tuple.into()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into();
// Generate the combined `BoolOp`.
let [first, .., last] = indices.as_slice() else {
unreachable!("Indices should have at least two elements")
};
let before = values.iter().take(*first).cloned();
let after = values.iter().skip(last + 1).cloned();
let bool_op = ast::ExprBoolOp {
op: BoolOp::Or,
values: before
.chain(iter::once(isinstance_call))
.chain(after)
.collect(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into();
let fixed_source = checker.generator().expr(&bool_op);
// Populate the `Fix`. Replace the _entire_ `BoolOp`. Note that if we have
// multiple duplicates, the fixes will conflict.
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
pad(fixed_source, expr.range(), checker.locator()),
expr.range(),
)));
}
}
}
}
fn match_eq_target(expr: &Expr) -> Option<(&Name, &Expr)> {
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
}) = expr
else {
return None;
};
if **ops != [CmpOp::Eq] {
return None;
}
let Expr::Name(ast::ExprName { id, .. }) = &**left else {
return None;
};
let [comparator] = &**comparators else {
return None;
};
if !comparator.is_name_expr() {
return None;
}
Some((id, comparator))
}
/// SIM109
pub(crate) fn compare_with_tuple(checker: &Checker, expr: &Expr) {
let Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::Or,
values,
range: _,
node_index: _,
}) = expr
else {
return;
};
// Given `a == "foo" or a == "bar"`, we generate `{"a": [(0, "foo"), (1,
// "bar")]}`.
let mut id_to_comparators: BTreeMap<&Name, Vec<(usize, &Expr)>> = BTreeMap::new();
for (index, value) in values.iter().enumerate() {
if let Some((id, comparator)) = match_eq_target(value) {
id_to_comparators
.entry(id)
.or_default()
.push((index, comparator));
}
}
for (id, matches) in id_to_comparators {
if matches.len() == 1 {
continue;
}
let (indices, comparators): (Vec<_>, Vec<_>) = matches.iter().copied().unzip();
// Avoid rewriting (e.g.) `a == "foo" or a == f()`.
if comparators
.iter()
.any(|expr| contains_effect(expr, |id| checker.semantic().has_builtin_binding(id)))
{
continue;
}
// Avoid removing comments.
if checker
.comment_ranges()
.has_comments(expr, checker.source())
{
continue;
}
// Create a `x in (a, b)` expression.
let node = ast::ExprTuple {
elts: comparators.into_iter().cloned().collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
};
let node1 = ast::ExprName {
id: id.clone(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node2 = ast::ExprCompare {
left: Box::new(node1.into()),
ops: Box::from([CmpOp::In]),
comparators: Box::from([node.into()]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let in_expr = node2.into();
let mut diagnostic = checker.report_diagnostic(
CompareWithTuple {
replacement: checker.generator().expr(&in_expr),
},
expr.range(),
);
let unmatched: Vec<Expr> = values
.iter()
.enumerate()
.filter(|(index, _)| !indices.contains(index))
.map(|(_, elt)| elt.clone())
.collect();
let in_expr = if unmatched.is_empty() {
in_expr
} else {
// Wrap in a `x in (a, b) or ...` boolean operation.
let node = ast::ExprBoolOp {
op: BoolOp::Or,
values: iter::once(in_expr).chain(unmatched).collect(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
node.into()
};
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
checker.generator().expr(&in_expr),
expr.range(),
)));
}
}
/// SIM220
pub(crate) fn expr_and_not_expr(checker: &Checker, expr: &Expr) {
let Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::And,
values,
range: _,
node_index: _,
}) = expr
else {
return;
};
if values.len() < 2 {
return;
}
// Collect all negated and non-negated expressions.
let mut negated_expr = vec![];
let mut non_negated_expr = vec![];
for expr in values {
if let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::Not,
operand,
range: _,
node_index: _,
}) = expr
{
negated_expr.push(operand);
} else {
non_negated_expr.push(expr);
}
}
if negated_expr.is_empty() {
return;
}
if contains_effect(expr, |id| checker.semantic().has_builtin_binding(id)) {
return;
}
for negate_expr in negated_expr {
for non_negate_expr in &non_negated_expr {
if let Some(id) = is_same_expr(negate_expr, non_negate_expr) {
let mut diagnostic = checker.report_diagnostic(
ExprAndNotExpr {
name: id.to_string(),
},
expr.range(),
);
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
"False".to_string(),
expr.range(),
)));
}
}
}
}
/// SIM221
pub(crate) fn expr_or_not_expr(checker: &Checker, expr: &Expr) {
let Expr::BoolOp(ast::ExprBoolOp {
op: BoolOp::Or,
values,
range: _,
node_index: _,
}) = expr
else {
return;
};
if values.len() < 2 {
return;
}
// Collect all negated and non-negated expressions.
let mut negated_expr = vec![];
let mut non_negated_expr = vec![];
for expr in values {
if let Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::Not,
operand,
range: _,
node_index: _,
}) = expr
{
negated_expr.push(operand);
} else {
non_negated_expr.push(expr);
}
}
if negated_expr.is_empty() {
return;
}
if contains_effect(expr, |id| checker.semantic().has_builtin_binding(id)) {
return;
}
for negate_expr in negated_expr {
for non_negate_expr in &non_negated_expr {
if let Some(id) = is_same_expr(negate_expr, non_negate_expr) {
let mut diagnostic = checker.report_diagnostic(
ExprOrNotExpr {
name: id.to_string(),
},
expr.range(),
);
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
"True".to_string(),
expr.range(),
)));
}
}
}
}
fn get_short_circuit_edit(
expr: &Expr,
range: TextRange,
truthiness: bool,
in_boolean_test: bool,
generator: Generator,
) -> Edit {
let content = if in_boolean_test {
if truthiness {
"True".to_string()
} else {
"False".to_string()
}
} else {
generator.expr(expr)
};
Edit::range_replacement(
if matches!(expr, Expr::Tuple(tuple) if !tuple.is_empty()) {
format!("({content})")
} else {
content
},
range,
)
}
fn is_short_circuit(
expr: &Expr,
expected_op: BoolOp,
checker: &Checker,
) -> Option<(Edit, ContentAround)> {
let Expr::BoolOp(ast::ExprBoolOp {
op,
values,
range: _,
node_index: _,
}) = expr
else {
return None;
};
if *op != expected_op {
return None;
}
let short_circuit_truthiness = match op {
BoolOp::And => false,
BoolOp::Or => true,
};
let mut furthest = expr;
let mut edit = None;
let mut remove = None;
for (index, (value, next_value)) in values.iter().tuple_windows().enumerate() {
// Keep track of the location of the furthest-right, truthy or falsey expression.
let value_truthiness =
Truthiness::from_expr(value, |id| checker.semantic().has_builtin_binding(id));
let next_value_truthiness =
Truthiness::from_expr(next_value, |id| checker.semantic().has_builtin_binding(id));
// Keep track of the location of the furthest-right, non-effectful expression.
if value_truthiness.is_unknown()
&& (!checker.semantic().in_boolean_test()
|| contains_effect(value, |id| checker.semantic().has_builtin_binding(id)))
{
furthest = next_value;
continue;
}
// If the current expression is a constant, and it matches the short-circuit value, then
// we can return the location of the expression. This should only trigger if the
// short-circuit expression is the first expression in the list; otherwise, we'll see it
// as `next_value` before we see it as `value`.
if value_truthiness.into_bool() == Some(short_circuit_truthiness) {
remove = Some(ContentAround::After);
edit = Some(get_short_circuit_edit(
value,
TextRange::new(
parenthesized_range(furthest.into(), expr.into(), checker.tokens())
.unwrap_or(furthest.range())
.start(),
expr.end(),
),
short_circuit_truthiness,
checker.semantic().in_boolean_test(),
checker.generator(),
));
break;
}
// If the next expression is a constant, and it matches the short-circuit value, then
// we can return the location of the expression.
if next_value_truthiness.into_bool() == Some(short_circuit_truthiness) {
remove = Some(if index + 1 == values.len() - 1 {
ContentAround::Before
} else {
ContentAround::Both
});
edit = Some(get_short_circuit_edit(
next_value,
TextRange::new(
parenthesized_range(furthest.into(), expr.into(), checker.tokens())
.unwrap_or(furthest.range())
.start(),
expr.end(),
),
short_circuit_truthiness,
checker.semantic().in_boolean_test(),
checker.generator(),
));
break;
}
}
match (edit, remove) {
(Some(edit), Some(remove)) => Some((edit, remove)),
_ => None,
}
}
/// SIM222
pub(crate) fn expr_or_true(checker: &Checker, expr: &Expr) {
if checker.semantic().in_string_type_definition() {
return;
}
if let Some((edit, remove)) = is_short_circuit(expr, BoolOp::Or, checker) {
let mut diagnostic = checker.report_diagnostic(
ExprOrTrue {
expr: edit.content().unwrap_or_default().to_string(),
remove,
},
edit.range(),
);
diagnostic.set_fix(Fix::unsafe_edit(edit));
}
}
/// SIM223
pub(crate) fn expr_and_false(checker: &Checker, expr: &Expr) {
if checker.semantic().in_string_type_definition() {
return;
}
if let Some((edit, remove)) = is_short_circuit(expr, BoolOp::And, checker) {
let mut diagnostic = checker.report_diagnostic(
ExprAndFalse {
expr: edit.content().unwrap_or_default().to_string(),
remove,
},
edit.range(),
);
diagnostic.set_fix(Fix::unsafe_edit(edit));
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_simplify/rules/split_static_string.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/split_static_string.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StringFlags;
use ruff_python_ast::{
Expr, ExprCall, ExprContext, ExprList, ExprUnaryOp, StringLiteral, StringLiteralFlags,
StringLiteralValue, UnaryOp, str::TripleQuotes,
};
use ruff_text_size::{Ranged, TextRange};
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use crate::checkers::ast::Checker;
use crate::preview::is_maxsplit_without_separator_fix_enabled;
use crate::settings::LinterSettings;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for static `str.split` calls that can be replaced with list literals.
///
/// ## Why is this bad?
/// List literals are more readable and do not require the overhead of calling `str.split`.
///
/// ## Example
/// ```python
/// "a,b,c,d".split(",")
/// ```
///
/// Use instead:
/// ```python
/// ["a", "b", "c", "d"]
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe for implicit string concatenations with comments interleaved
/// between segments, as comments may be removed.
///
/// For example, the fix would be marked as unsafe in the following case:
/// ```python
/// (
/// "a" # comment
/// "," # comment
/// "b" # comment
/// ).split(",")
/// ```
///
/// as this is converted to `["a", "b"]` without any of the comments.
///
/// ## References
/// - [Python documentation: `str.split`](https://docs.python.org/3/library/stdtypes.html#str.split)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct SplitStaticString {
method: Method,
}
#[derive(Copy, Clone, Debug)]
enum Method {
Split,
RSplit,
}
impl Method {
fn is_rsplit(self) -> bool {
matches!(self, Method::RSplit)
}
}
impl Display for Method {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Method::Split => f.write_str("split"),
Method::RSplit => f.write_str("rsplit"),
}
}
}
impl Violation for SplitStaticString {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Consider using a list literal instead of `str.{}`",
self.method
)
}
fn fix_title(&self) -> Option<String> {
Some("Replace with list literal".to_string())
}
}
/// SIM905
pub(crate) fn split_static_string(
checker: &Checker,
attr: &str,
call: &ExprCall,
str_value: &StringLiteralValue,
) {
let ExprCall { arguments, .. } = call;
let maxsplit_arg = arguments.find_argument_value("maxsplit", 1);
let Some(maxsplit_value) = get_maxsplit_value(maxsplit_arg) else {
return;
};
// `split` vs `rsplit`.
let method = if attr == "split" {
Method::Split
} else {
Method::RSplit
};
let sep_arg = arguments.find_argument_value("sep", 0);
let split_replacement = if let Some(sep) = sep_arg {
match sep {
Expr::NoneLiteral(_) => {
split_default(str_value, maxsplit_value, method, checker.settings())
}
Expr::StringLiteral(sep_value) => {
let sep_value_str = sep_value.value.to_str();
Some(split_sep(str_value, sep_value_str, maxsplit_value, method))
}
// Ignore names until type inference is available.
_ => {
return;
}
}
} else {
split_default(str_value, maxsplit_value, method, checker.settings())
};
let mut diagnostic = checker.report_diagnostic(SplitStaticString { method }, call.range());
if let Some(ref replacement_expr) = split_replacement {
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(checker.generator().expr(replacement_expr), call.range()),
// The fix does not preserve comments within implicit string concatenations.
if checker.comment_ranges().intersects(call.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
},
));
}
}
fn replace_flags(elt: &str, flags: StringLiteralFlags) -> StringLiteralFlags {
// In the ideal case we can wrap the element in _single_ quotes of the same
// style. For example, both of these are okay:
//
// ```python
// """itemA
// itemB
// itemC""".split() # -> ["itemA", "itemB", "itemC"]
// ```
//
// ```python
// r"""itemA
// 'single'quoted
// """.split() # -> [r"itemA",r"'single'quoted'"]
// ```
if !flags.prefix().is_raw() || !elt.contains(flags.quote_style().as_char()) {
flags.with_triple_quotes(TripleQuotes::No)
}
// If we have a raw string containing a quotation mark of the same style,
// then we have to swap the style of quotation marks used
else if !elt.contains(flags.quote_style().opposite().as_char()) {
flags
.with_quote_style(flags.quote_style().opposite())
.with_triple_quotes(TripleQuotes::No)
} else
// If both types of quotes are used in the raw, triple-quoted string, then
// we are forced to either add escapes or keep the triple quotes. We opt for
// the latter.
{
flags
}
}
fn construct_replacement(elts: &[&str], flags: StringLiteralFlags) -> Expr {
Expr::List(ExprList {
elts: elts
.iter()
.map(|elt| {
let element_flags = replace_flags(elt, flags);
Expr::from(StringLiteral {
value: Box::from(*elt),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
flags: element_flags,
})
})
.collect(),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
}
fn split_default(
str_value: &StringLiteralValue,
max_split: i32,
method: Method,
settings: &LinterSettings,
) -> Option<Expr> {
let string_val = str_value.to_str();
match max_split.cmp(&0) {
Ordering::Greater if !is_maxsplit_without_separator_fix_enabled(settings) => None,
Ordering::Greater | Ordering::Equal => {
let Ok(max_split) = usize::try_from(max_split) else {
return None;
};
let list_items = split_whitespace_with_maxsplit(string_val, max_split, method);
Some(construct_replacement(
&list_items,
str_value.first_literal_flags(),
))
}
Ordering::Less => {
let list_items: Vec<&str> = string_val
.split(py_unicode_is_whitespace)
.filter(|s| !s.is_empty())
.collect();
Some(construct_replacement(
&list_items,
str_value.first_literal_flags(),
))
}
}
}
fn split_sep(
str_value: &StringLiteralValue,
sep_value: &str,
max_split: i32,
method: Method,
) -> Expr {
let value = str_value.to_str();
let list_items: Vec<&str> = if let Ok(split_n) = usize::try_from(max_split) {
match method {
Method::Split => value.splitn(split_n + 1, sep_value).collect(),
Method::RSplit => {
let mut items: Vec<&str> = value.rsplitn(split_n + 1, sep_value).collect();
items.reverse();
items
}
}
} else {
match method {
Method::Split => value.split(sep_value).collect(),
Method::RSplit => {
let mut items: Vec<&str> = value.rsplit(sep_value).collect();
items.reverse();
items
}
}
};
construct_replacement(&list_items, str_value.first_literal_flags())
}
/// Returns the value of the `maxsplit` argument as an `i32`, if it is a numeric value.
fn get_maxsplit_value(arg: Option<&Expr>) -> Option<i32> {
if let Some(maxsplit) = arg {
match maxsplit {
// Negative number.
Expr::UnaryOp(ExprUnaryOp {
op: UnaryOp::USub,
operand,
..
}) => {
match &**operand {
Expr::NumberLiteral(maxsplit_val) => maxsplit_val
.value
.as_int()
.and_then(ruff_python_ast::Int::as_i32)
.map(|f| -f),
// Ignore when `maxsplit` is not a numeric value.
_ => None,
}
}
// Positive number
Expr::NumberLiteral(maxsplit_val) => maxsplit_val
.value
.as_int()
.and_then(ruff_python_ast::Int::as_i32),
// Ignore when `maxsplit` is not a numeric value.
_ => None,
}
} else {
// Default value is -1 (no splits).
Some(-1)
}
}
/// Like [`char::is_whitespace`] but with Python's notion of whitespace.
///
/// <https://github.com/astral-sh/ruff/issues/19845>
/// <https://github.com/python/cpython/blob/v3.14.0rc1/Objects/unicodetype_db.h#L6673-L6711>
#[rustfmt::skip]
#[inline]
const fn py_unicode_is_whitespace(ch: char) -> bool {
matches!(
ch,
| '\u{0009}'
| '\u{000A}'
| '\u{000B}'
| '\u{000C}'
| '\u{000D}'
| '\u{001C}'
| '\u{001D}'
| '\u{001E}'
| '\u{001F}'
| '\u{0020}'
| '\u{0085}'
| '\u{00A0}'
| '\u{1680}'
| '\u{2000}'..='\u{200A}'
| '\u{2028}'
| '\u{2029}'
| '\u{202F}'
| '\u{205F}'
| '\u{3000}'
)
}
struct WhitespaceMaxSplitIterator<'a> {
remaining: &'a str,
max_split: usize,
splits: usize,
method: Method,
}
impl<'a> WhitespaceMaxSplitIterator<'a> {
fn new(s: &'a str, max_split: usize, method: Method) -> Self {
let remaining = match method {
Method::Split => s.trim_start_matches(py_unicode_is_whitespace),
Method::RSplit => s.trim_end_matches(py_unicode_is_whitespace),
};
Self {
remaining,
max_split,
splits: 0,
method,
}
}
}
impl<'a> Iterator for WhitespaceMaxSplitIterator<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining.is_empty() {
return None;
}
if self.splits >= self.max_split {
let result = self.remaining;
self.remaining = "";
return Some(result);
}
self.splits += 1;
match self.method {
Method::Split => match self.remaining.split_once(py_unicode_is_whitespace) {
Some((s, remaining)) => {
self.remaining = remaining.trim_start_matches(py_unicode_is_whitespace);
Some(s)
}
None => Some(std::mem::take(&mut self.remaining)),
},
Method::RSplit => match self.remaining.rsplit_once(py_unicode_is_whitespace) {
Some((remaining, s)) => {
self.remaining = remaining.trim_end_matches(py_unicode_is_whitespace);
Some(s)
}
None => Some(std::mem::take(&mut self.remaining)),
},
}
}
}
// From the Python documentation:
// > If sep is not specified or is None, a different splitting algorithm is applied: runs of
// > consecutive whitespace are regarded as a single separator, and the result will contain
// > no empty strings at the start or end if the string has leading or trailing whitespace.
// > Consequently, splitting an empty string or a string consisting of just whitespace with
// > a None separator returns [].
// https://docs.python.org/3/library/stdtypes.html#str.split
fn split_whitespace_with_maxsplit(s: &str, max_split: usize, method: Method) -> Vec<&str> {
let mut result: Vec<_> = WhitespaceMaxSplitIterator::new(s, max_split, method).collect();
if method.is_rsplit() {
result.reverse();
}
result
}
#[cfg(test)]
mod tests {
use super::{Method, split_whitespace_with_maxsplit};
use test_case::test_case;
#[test_case(" ", 1, &[])]
#[test_case("a b", 1, &["a", "b"])]
#[test_case("a b", 2, &["a", "b"])]
#[test_case(" a b c d ", 2, &["a", "b", "c d "])]
#[test_case(" a b c ", 1, &["a", "b c "])]
#[test_case(" x ", 0, &["x "])]
#[test_case(" ", 0, &[])]
#[test_case("a\u{3000}b", 1, &["a", "b"])]
fn test_split_whitespace_with_maxsplit(s: &str, max_split: usize, expected: &[&str]) {
let parts = split_whitespace_with_maxsplit(s, max_split, Method::Split);
assert_eq!(parts, expected);
}
#[test_case(" ", 1, &[])]
#[test_case("a b", 1, &["a", "b"])]
#[test_case("a b", 2, &["a", "b"])]
#[test_case(" a b c d ", 2, &[" a b", "c", "d"])]
#[test_case(" a b c ", 1, &[" a b", "c"])]
#[test_case(" x ", 0, &[" x"])]
#[test_case(" ", 0, &[])]
#[test_case("a\u{3000}b", 1, &["a", "b"])]
fn test_rsplit_whitespace_with_maxsplit(s: &str, max_split: usize, expected: &[&str]) {
let parts = split_whitespace_with_maxsplit(s, max_split, Method::RSplit);
assert_eq!(parts, expected);
}
}
| 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_simplify/rules/if_else_block_instead_of_dict_get.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_get.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::contains_effect;
use ruff_python_ast::{
self as ast, Arguments, CmpOp, ElifElseClause, Expr, ExprContext, Identifier, Stmt,
};
use ruff_python_semantic::analyze::typing::{
is_known_to_be_of_type_dict, is_sys_version_block, is_type_checking_block,
};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::fits;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `if` statements that can be replaced with `dict.get` calls.
///
/// ## Why is this bad?
/// `dict.get()` calls can be used to replace `if` statements that assign a
/// value to a variable in both branches, falling back to a default value if
/// the key is not found. When possible, using `dict.get` is more concise and
/// more idiomatic.
///
/// Under [preview mode](https://docs.astral.sh/ruff/preview), this rule will
/// also suggest replacing `if`-`else` _expressions_ with `dict.get` calls.
///
/// ## Example
/// ```python
/// foo = {}
/// if "bar" in foo:
/// value = foo["bar"]
/// else:
/// value = 0
/// ```
///
/// Use instead:
/// ```python
/// foo = {}
/// value = foo.get("bar", 0)
/// ```
///
/// If preview mode is enabled:
/// ```python
/// value = foo["bar"] if "bar" in foo else 0
/// ```
///
/// Use instead:
/// ```python
/// value = foo.get("bar", 0)
/// ```
///
/// ## Options
///
/// The rule will avoid flagging cases where using the resulting `dict.get` call would exceed the
/// configured line length, as determined by these options:
///
/// - `lint.pycodestyle.max-line-length`
/// - `indent-width`
///
/// ## References
/// - [Python documentation: Mapping Types](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.219")]
pub(crate) struct IfElseBlockInsteadOfDictGet {
contents: String,
}
impl Violation for IfElseBlockInsteadOfDictGet {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let IfElseBlockInsteadOfDictGet { contents } = self;
format!("Use `{contents}` instead of an `if` block")
}
fn fix_title(&self) -> Option<String> {
let IfElseBlockInsteadOfDictGet { contents } = self;
Some(format!("Replace with `{contents}`"))
}
}
/// SIM401
pub(crate) fn if_else_block_instead_of_dict_get(checker: &Checker, stmt_if: &ast::StmtIf) {
let ast::StmtIf {
test,
body,
elif_else_clauses,
..
} = stmt_if;
let [body_stmt] = body.as_slice() else {
return;
};
let [
ElifElseClause {
body: else_body,
test: None,
..
},
] = elif_else_clauses.as_slice()
else {
return;
};
let [else_body_stmt] = else_body.as_slice() else {
return;
};
let Stmt::Assign(ast::StmtAssign {
targets: body_var,
value: body_value,
..
}) = &body_stmt
else {
return;
};
let [body_var] = body_var.as_slice() else {
return;
};
let Stmt::Assign(ast::StmtAssign {
targets: orelse_var,
value: orelse_value,
..
}) = &else_body_stmt
else {
return;
};
let [orelse_var] = orelse_var.as_slice() else {
return;
};
let Expr::Compare(ast::ExprCompare {
left: test_key,
ops,
comparators: test_dict,
range: _,
node_index: _,
}) = &**test
else {
return;
};
let [test_dict] = &**test_dict else {
return;
};
if !test_dict
.as_name_expr()
.is_some_and(|dict_name| is_known_to_be_of_type_dict(checker.semantic(), dict_name))
{
return;
}
let (expected_var, expected_value, default_var, default_value) = match ops[..] {
[CmpOp::In] => (body_var, body_value, orelse_var, orelse_value.as_ref()),
[CmpOp::NotIn] => (orelse_var, orelse_value, body_var, body_value.as_ref()),
_ => {
return;
}
};
let Expr::Subscript(ast::ExprSubscript {
value: expected_subscript,
slice: expected_slice,
..
}) = expected_value.as_ref()
else {
return;
};
// Check that the dictionary key, target variables, and dictionary name are all
// equivalent.
if ComparableExpr::from(expected_slice) != ComparableExpr::from(test_key)
|| ComparableExpr::from(expected_var) != ComparableExpr::from(default_var)
|| ComparableExpr::from(test_dict) != ComparableExpr::from(expected_subscript)
{
return;
}
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
if is_sys_version_block(stmt_if, checker.semantic()) {
return;
}
// Avoid suggesting ternary for `if TYPE_CHECKING:`-style checks.
if is_type_checking_block(stmt_if, checker.semantic()) {
return;
}
// Check that the default value is not "complex".
if contains_effect(default_value, |id| {
checker.semantic().has_builtin_binding(id)
}) {
return;
}
let node = default_value.clone();
let node1 = *test_key.clone();
let node2 = ast::ExprAttribute {
value: expected_subscript.clone(),
attr: Identifier::new("get".to_string(), TextRange::default()),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node3 = ast::ExprCall {
func: Box::new(node2.into()),
arguments: Arguments {
args: Box::from([node1, node]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let node4 = expected_var.clone();
let node5 = ast::StmtAssign {
targets: vec![node4],
value: Box::new(node3.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let contents = checker.generator().stmt(&node5.into());
// Don't flag if the resulting expression would exceed the maximum line length.
if !fits(
&contents,
stmt_if.into(),
checker.locator(),
checker.settings().pycodestyle.max_line_length,
checker.settings().tab_size,
) {
return;
}
let mut diagnostic = checker.report_diagnostic(
IfElseBlockInsteadOfDictGet {
contents: contents.clone(),
},
stmt_if.range(),
);
if !checker
.comment_ranges()
.has_comments(stmt_if, checker.source())
{
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
contents,
stmt_if.range(),
)));
}
}
/// SIM401
pub(crate) fn if_exp_instead_of_dict_get(
checker: &Checker,
expr: &Expr,
test: &Expr,
body: &Expr,
orelse: &Expr,
) {
let Expr::Compare(ast::ExprCompare {
left: test_key,
ops,
comparators: test_dict,
range: _,
node_index: _,
}) = test
else {
return;
};
let [test_dict] = &**test_dict else {
return;
};
let (body, default_value) = match &**ops {
[CmpOp::In] => (body, orelse),
[CmpOp::NotIn] => (orelse, body),
_ => {
return;
}
};
let Expr::Subscript(ast::ExprSubscript {
value: expected_subscript,
slice: expected_slice,
..
}) = body
else {
return;
};
if ComparableExpr::from(expected_slice) != ComparableExpr::from(test_key)
|| ComparableExpr::from(test_dict) != ComparableExpr::from(expected_subscript)
{
return;
}
// Check that the default value is not "complex".
if contains_effect(default_value, |id| {
checker.semantic().has_builtin_binding(id)
}) {
return;
}
let default_value_node = default_value.clone();
let dict_key_node = *test_key.clone();
let dict_get_node = ast::ExprAttribute {
value: expected_subscript.clone(),
attr: Identifier::new("get".to_string(), TextRange::default()),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let fixed_node = ast::ExprCall {
func: Box::new(dict_get_node.into()),
arguments: Arguments {
args: Box::from([dict_key_node, default_value_node]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let contents = checker.generator().expr(&fixed_node.into());
let mut diagnostic = checker.report_diagnostic(
IfElseBlockInsteadOfDictGet {
contents: contents.clone(),
},
expr.range(),
);
if !checker
.comment_ranges()
.has_comments(expr, checker.source())
{
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
contents,
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_simplify/rules/enumerate_for_loop.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/enumerate_for_loop.rs | use crate::preview::is_enumerate_for_loop_int_index_enabled;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt};
use ruff_python_ast::{self as ast, Expr, Int, Number, Operator, Stmt};
use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType};
use ruff_python_semantic::analyze::typing;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for `for` loops with explicit loop-index variables that can be replaced
/// with `enumerate()`.
///
/// In [preview], this rule checks for index variables initialized with any integer rather than only
/// a literal zero.
///
/// ## Why is this bad?
/// When iterating over a sequence, it's often desirable to keep track of the
/// index of each element alongside the element itself. Prefer the `enumerate`
/// builtin over manually incrementing a counter variable within the loop, as
/// `enumerate` is more concise and idiomatic.
///
/// ## Example
/// ```python
/// fruits = ["apple", "banana", "cherry"]
/// i = 0
/// for fruit in fruits:
/// print(f"{i + 1}. {fruit}")
/// i += 1
/// ```
///
/// Use instead:
/// ```python
/// fruits = ["apple", "banana", "cherry"]
/// for i, fruit in enumerate(fruits):
/// print(f"{i + 1}. {fruit}")
/// ```
///
/// ## References
/// - [Python documentation: `enumerate`](https://docs.python.org/3/library/functions.html#enumerate)
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.2.0")]
pub(crate) struct EnumerateForLoop {
index: String,
}
impl Violation for EnumerateForLoop {
#[derive_message_formats]
fn message(&self) -> String {
let EnumerateForLoop { index } = self;
format!("Use `enumerate()` for index variable `{index}` in `for` loop")
}
}
/// SIM113
pub(crate) fn enumerate_for_loop(checker: &Checker, for_stmt: &ast::StmtFor) {
// If the loop is async, abort.
if for_stmt.is_async {
return;
}
// If the loop contains a `continue`, abort.
let mut visitor = LoopControlFlowVisitor::default();
visitor.visit_body(&for_stmt.body);
if visitor.has_continue {
return;
}
for stmt in &for_stmt.body {
// Find the augmented assignment expression (e.g., `i += 1`).
if let Some(index) = match_index_increment(stmt) {
// Find the binding corresponding to the initialization (e.g., `i = 1`).
let Some(id) = checker.semantic().resolve_name(index) else {
continue;
};
// If it's not an assignment (e.g., it's a function argument), ignore it.
let binding = checker.semantic().binding(id);
if !binding.kind.is_assignment() {
continue;
}
// If the variable is global or nonlocal, ignore it.
if binding.is_global() || binding.is_nonlocal() {
continue;
}
// Ensure that the index variable was initialized to 0 (or instance of `int` if preview is enabled).
let Some(value) = typing::find_binding_value(binding, checker.semantic()) else {
continue;
};
if !(matches!(
value,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: Number::Int(Int::ZERO),
..
})
) || matches!(
ResolvedPythonType::from(value),
ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer))
) && is_enumerate_for_loop_int_index_enabled(checker.settings()))
{
continue;
}
// If the binding is not at the same level as the `for` loop (e.g., it's in an `if`),
// ignore it.
let Some(for_loop_id) = checker.semantic().current_statement_id() else {
continue;
};
let Some(assignment_id) = binding.source else {
continue;
};
if checker.semantic().parent_statement_id(for_loop_id)
!= checker.semantic().parent_statement_id(assignment_id)
{
continue;
}
// Identify the binding created by the augmented assignment.
// TODO(charlie): There should be a way to go from `ExprName` to `BindingId` (like
// `resolve_name`, but for bindings rather than references).
let binding = {
let mut bindings = checker
.semantic()
.current_scope()
.get_all(&index.id)
.map(|id| checker.semantic().binding(id))
.filter(|binding| for_stmt.range().contains_range(binding.range()));
let Some(binding) = bindings.next() else {
continue;
};
// If there are multiple assignments to this variable _within_ the loop, ignore it.
if bindings.next().is_some() {
continue;
}
binding
};
// If the variable is used outside the loop, ignore it.
if binding.references.iter().any(|id| {
let reference = checker.semantic().reference(*id);
!for_stmt.range().contains_range(reference.range())
}) {
continue;
}
checker.report_diagnostic(
EnumerateForLoop {
index: index.id.to_string(),
},
stmt.range(),
);
}
}
}
/// If the statement is an index increment statement (e.g., `i += 1`), return
/// the name of the index variable.
fn match_index_increment(stmt: &Stmt) -> Option<&ast::ExprName> {
let Stmt::AugAssign(ast::StmtAugAssign {
target,
op: Operator::Add,
value,
..
}) = stmt
else {
return None;
};
let name = target.as_name_expr()?;
if matches!(
value.as_ref(),
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: Number::Int(Int::ONE),
..
})
) {
return Some(name);
}
None
}
#[derive(Debug, Default)]
struct LoopControlFlowVisitor {
has_continue: bool,
}
impl StatementVisitor<'_> for LoopControlFlowVisitor {
fn visit_stmt(&mut self, stmt: &Stmt) {
match stmt {
Stmt::Continue(_) => self.has_continue = true,
Stmt::FunctionDef(_) | Stmt::ClassDef(_) => {
// Don't recurse.
}
_ => walk_stmt(self, stmt),
}
}
}
| 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_simplify/rules/ast_with.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/ast_with.rs | use anyhow::bail;
use ast::Expr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Stmt, WithItem};
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange};
use super::fix_with;
use crate::Fix;
use crate::checkers::ast::Checker;
use crate::fix::edits::fits;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for the unnecessary nesting of multiple consecutive context
/// managers.
///
/// ## Why is this bad?
/// In Python 3, a single `with` block can include multiple context
/// managers.
///
/// Combining multiple context managers into a single `with` statement
/// will minimize the indentation depth of the code, making it more
/// readable.
///
/// The following context managers are exempt when used as standalone
/// statements:
///
/// - `anyio`.{`CancelScope`, `fail_after`, `move_on_after`}
/// - `asyncio`.{`timeout`, `timeout_at`}
/// - `trio`.{`fail_after`, `fail_at`, `move_on_after`, `move_on_at`}
///
/// ## Example
/// ```python
/// with A() as a:
/// with B() as b:
/// pass
/// ```
///
/// Use instead:
/// ```python
/// with A() as a, B() as b:
/// pass
/// ```
///
/// ## Options
///
/// The rule will consult these two settings when deciding if a fix can be provided:
///
/// - `lint.pycodestyle.max-line-length`
/// - `indent-width`
///
/// Lines that would exceed the configured line length will not be fixed automatically.
///
/// ## References
/// - [Python documentation: The `with` statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct MultipleWithStatements;
impl Violation for MultipleWithStatements {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use a single `with` statement with multiple contexts instead of nested `with` \
statements"
.to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Combine `with` statements".to_string())
}
}
/// Returns a boolean indicating whether it's an async with statement, the items
/// and body.
fn next_with(body: &[Stmt]) -> Option<(bool, &[WithItem], &[Stmt])> {
let [
Stmt::With(ast::StmtWith {
is_async,
items,
body,
..
}),
] = body
else {
return None;
};
Some((*is_async, items, body))
}
/// Check if `with_items` contains a single item which should not necessarily be
/// grouped with other items.
///
/// For example:
/// ```python
/// async with asyncio.timeout(1):
/// with resource1(), resource2():
/// ...
/// ```
fn explicit_with_items(checker: &Checker, with_items: &[WithItem]) -> bool {
let [with_item] = with_items else {
return false;
};
let Expr::Call(expr_call) = &with_item.context_expr else {
return false;
};
checker
.semantic()
.resolve_qualified_name(&expr_call.func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["asyncio", "timeout" | "timeout_at"]
| ["anyio", "CancelScope" | "fail_after" | "move_on_after"]
| [
"trio",
"fail_after" | "fail_at" | "move_on_after" | "move_on_at"
]
)
})
}
/// SIM117
pub(crate) fn multiple_with_statements(
checker: &Checker,
with_stmt: &ast::StmtWith,
with_parent: Option<&Stmt>,
) {
// Make sure we fix from top to bottom for nested with statements, e.g. for
// ```python
// with A():
// with B():
// with C():
// print("hello")
// ```
// suggests
// ```python
// with A(), B():
// with C():
// print("hello")
// ```
// but not the following
// ```python
// with A():
// with B(), C():
// print("hello")
// ```
if let Some(Stmt::With(ast::StmtWith { body, .. })) = with_parent {
if body.len() == 1 {
return;
}
}
if let Some((is_async, items, _body)) = next_with(&with_stmt.body) {
if is_async != with_stmt.is_async {
// One of the statements is an async with, while the other is not,
// we can't merge those statements.
return;
}
if explicit_with_items(checker, &with_stmt.items) || explicit_with_items(checker, items) {
return;
}
let Some(colon) = items.last().and_then(|item| {
SimpleTokenizer::starts_at(item.end(), checker.locator().contents())
.skip_trivia()
.find(|token| token.kind == SimpleTokenKind::Colon)
}) else {
return;
};
let mut diagnostic = checker.report_diagnostic(
MultipleWithStatements,
TextRange::new(with_stmt.start(), colon.end()),
);
if !checker
.comment_ranges()
.intersects(TextRange::new(with_stmt.start(), with_stmt.body[0].start()))
{
diagnostic.try_set_optional_fix(|| {
match fix_with::fix_multiple_with_statements(
checker.locator(),
checker.stylist(),
with_stmt,
) {
Ok(edit) => {
if edit.content().is_none_or(|content| {
fits(
content,
with_stmt.into(),
checker.locator(),
checker.settings().pycodestyle.max_line_length,
checker.settings().tab_size,
)
}) {
Ok(Some(Fix::safe_edit(edit)))
} else {
Ok(None)
}
}
Err(err) => bail!("Failed to collapse `with`: {err}"),
}
});
}
}
}
| 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_simplify/rules/if_else_block_instead_of_dict_lookup.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/if_else_block_instead_of_dict_lookup.rs | use rustc_hash::FxHashSet;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableLiteral;
use ruff_python_ast::helpers::contains_effect;
use ruff_python_ast::{self as ast, CmpOp, ElifElseClause, Expr, Stmt};
use ruff_python_semantic::analyze::typing::{is_sys_version_block, is_type_checking_block};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for three or more consecutive if-statements with direct returns
///
/// ## Why is this bad?
/// These can be simplified by using a dictionary
///
/// ## Example
/// ```python
/// def find_phrase(x):
/// if x == 1:
/// return "Hello"
/// elif x == 2:
/// return "Goodbye"
/// elif x == 3:
/// return "Good morning"
/// else:
/// return "Goodnight"
/// ```
///
/// Use instead:
/// ```python
/// def find_phrase(x):
/// phrases = {1: "Hello", 2: "Goodye", 3: "Good morning"}
/// return phrases.get(x, "Goodnight")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.250")]
pub(crate) struct IfElseBlockInsteadOfDictLookup;
impl Violation for IfElseBlockInsteadOfDictLookup {
#[derive_message_formats]
fn message(&self) -> String {
"Use a dictionary instead of consecutive `if` statements".to_string()
}
}
/// SIM116
pub(crate) fn if_else_block_instead_of_dict_lookup(checker: &Checker, stmt_if: &ast::StmtIf) {
// Throughout this rule:
// * Each if or elif statement's test must consist of a constant equality check with the same variable.
// * Each if or elif statement's body must consist of a single `return`.
// * The else clause must be empty, or a single `return`.
let ast::StmtIf {
body,
test,
elif_else_clauses,
..
} = stmt_if;
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
}) = test.as_ref()
else {
return;
};
let Expr::Name(ast::ExprName { id: target, .. }) = left.as_ref() else {
return;
};
if **ops != [CmpOp::Eq] {
return;
}
let [expr] = &**comparators else {
return;
};
let Some(literal_expr) = expr.as_literal_expr() else {
return;
};
let [
Stmt::Return(ast::StmtReturn {
value,
range: _,
node_index: _,
}),
] = body.as_slice()
else {
return;
};
if value.as_ref().is_some_and(|value| {
contains_effect(value, |id| checker.semantic().has_builtin_binding(id))
}) {
return;
}
// Avoid suggesting ternary for `if sys.version_info >= ...`-style checks.
if is_sys_version_block(stmt_if, checker.semantic()) {
return;
}
// Avoid suggesting ternary for `if TYPE_CHECKING:`-style checks.
if is_type_checking_block(stmt_if, checker.semantic()) {
return;
}
// The `expr` was checked to be a literal above, so this is safe.
let mut literals: FxHashSet<ComparableLiteral> = FxHashSet::default();
literals.insert(literal_expr.into());
for clause in elif_else_clauses {
let ElifElseClause { test, body, .. } = clause;
let [
Stmt::Return(ast::StmtReturn {
value,
range: _,
node_index: _,
}),
] = body.as_slice()
else {
return;
};
match test.as_ref() {
// `else`
None => {
// The else must also be a single effect-free return statement
let [
Stmt::Return(ast::StmtReturn {
value,
range: _,
node_index: _,
}),
] = body.as_slice()
else {
return;
};
if value.as_ref().is_some_and(|value| {
contains_effect(value, |id| checker.semantic().has_builtin_binding(id))
}) {
return;
}
}
// `elif`
Some(Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
range: _,
node_index: _,
})) => {
let Expr::Name(ast::ExprName { id, .. }) = left.as_ref() else {
return;
};
if id != target || **ops != [CmpOp::Eq] {
return;
}
let [expr] = &**comparators else {
return;
};
let Some(literal_expr) = expr.as_literal_expr() else {
return;
};
if value.as_ref().is_some_and(|value| {
contains_effect(value, |id| checker.semantic().has_builtin_binding(id))
}) {
return;
}
// The `expr` was checked to be a literal above, so this is safe.
literals.insert(literal_expr.into());
}
// Different `elif`
_ => {
return;
}
}
}
if literals.len() < 3 {
return;
}
checker.report_diagnostic(IfElseBlockInsteadOfDictLookup, stmt_if.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_simplify/rules/key_in_dict.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/key_in_dict.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{self as ast, Arguments, CmpOp, Comprehension, Expr};
use ruff_python_semantic::analyze::typing;
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Fix};
use crate::{Applicability, Edit};
/// ## What it does
/// Checks for key-existence checks against `dict.keys()` calls.
///
/// ## Why is this bad?
/// When checking for the existence of a key in a given dictionary, using
/// `key in dict` is more readable and efficient than `key in dict.keys()`,
/// while having the same semantics.
///
/// ## Example
/// ```python
/// key in foo.keys()
/// ```
///
/// Use instead:
/// ```python
/// key in foo
/// ```
///
/// ## Fix safety
/// Given `key in obj.keys()`, `obj` _could_ be a dictionary, or it could be
/// another type that defines a `.keys()` method. In the latter case, removing
/// the `.keys()` attribute could lead to a runtime error. The fix is marked
/// as safe when the type of `obj` is known to be a dictionary; otherwise, it
/// is marked as unsafe.
///
/// ## References
/// - [Python documentation: Mapping Types](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.176")]
pub(crate) struct InDictKeys {
operator: String,
}
impl AlwaysFixableViolation for InDictKeys {
#[derive_message_formats]
fn message(&self) -> String {
let InDictKeys { operator } = self;
format!("Use `key {operator} dict` instead of `key {operator} dict.keys()`")
}
fn fix_title(&self) -> String {
"Remove `.keys()`".to_string()
}
}
/// SIM118
fn key_in_dict(checker: &Checker, left: &Expr, right: &Expr, operator: CmpOp, parent: AnyNodeRef) {
let Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, keywords, .. },
range: _,
node_index: _,
}) = &right
else {
return;
};
if !(args.is_empty() && keywords.is_empty()) {
return;
}
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func.as_ref() else {
return;
};
if attr != "keys" {
return;
}
// Ignore `self.keys()`, which will almost certainly be intentional, as in:
// ```python
// def __contains__(self, key: object) -> bool:
// return key in self.keys()
// ```
if value
.as_name_expr()
.is_some_and(|name| matches!(name.id.as_str(), "self"))
{
return;
}
// Extract the exact range of the left and right expressions.
let left_range =
parenthesized_range(left.into(), parent, checker.tokens()).unwrap_or(left.range());
let right_range =
parenthesized_range(right.into(), parent, checker.tokens()).unwrap_or(right.range());
let mut diagnostic = checker.report_diagnostic(
InDictKeys {
operator: operator.as_str().to_string(),
},
TextRange::new(left_range.start(), right_range.end()),
);
// Delete from the start of the dot to the end of the expression.
if let Some(dot) = SimpleTokenizer::starts_at(value.end(), checker.locator().contents())
.skip_trivia()
.find(|token| token.kind == SimpleTokenKind::Dot)
{
// The fix is only safe if we know the expression is a dictionary, since other types
// can define a `.keys()` method.
let applicability = {
let is_dict = value.as_name_expr().is_some_and(|name| {
let Some(binding) = checker
.semantic()
.only_binding(name)
.map(|id| checker.semantic().binding(id))
else {
return false;
};
typing::is_dict(binding, checker.semantic())
});
if is_dict {
Applicability::Safe
} else {
Applicability::Unsafe
}
};
// If the `.keys()` is followed by (e.g.) a keyword, we need to insert a space,
// since we're removing parentheses, which could lead to invalid syntax, as in:
// ```python
// if key in foo.keys()and bar:
// ```
let range = TextRange::new(dot.start(), right.end());
if checker
.locator()
.after(range.end())
.chars()
.next()
.is_some_and(|char| char.is_ascii_alphabetic())
{
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(" ".to_string(), range),
applicability,
));
} else {
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_deletion(range),
applicability,
));
}
}
}
/// SIM118 in a `for` loop.
pub(crate) fn key_in_dict_for(checker: &Checker, for_stmt: &ast::StmtFor) {
key_in_dict(
checker,
&for_stmt.target,
&for_stmt.iter,
CmpOp::In,
for_stmt.into(),
);
}
/// SIM118 in a comprehension.
pub(crate) fn key_in_dict_comprehension(checker: &Checker, comprehension: &Comprehension) {
key_in_dict(
checker,
&comprehension.target,
&comprehension.iter,
CmpOp::In,
comprehension.into(),
);
}
/// SIM118 in a comparison.
pub(crate) fn key_in_dict_compare(checker: &Checker, compare: &ast::ExprCompare) {
let [op] = &*compare.ops else {
return;
};
if !matches!(op, CmpOp::In | CmpOp::NotIn) {
return;
}
let [right] = &*compare.comparators else {
return;
};
key_in_dict(checker, &compare.left, right, *op, compare.into());
}
| 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_simplify/rules/return_in_try_except_finally.rs | crates/ruff_linter/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs | use ruff_python_ast::{self as ast, ExceptHandler, 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 `return` statements in `try`-`except` and `finally` blocks.
///
/// ## Why is this bad?
/// The `return` statement in a `finally` block will always be executed, even if
/// an exception is raised in the `try` or `except` block. This can lead to
/// unexpected behavior.
///
/// ## Example
/// ```python
/// def squared(n):
/// try:
/// sqr = n**2
/// return sqr
/// except Exception:
/// return "An exception occurred"
/// finally:
/// return -1 # Always returns -1.
/// ```
///
/// Use instead:
/// ```python
/// def squared(n):
/// try:
/// return_value = n**2
/// except Exception:
/// return_value = "An exception occurred"
/// finally:
/// return_value = -1
/// return return_value
/// ```
///
/// ## References
/// - [Python documentation: Defining Clean-up Actions](https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.211")]
pub(crate) struct ReturnInTryExceptFinally;
impl Violation for ReturnInTryExceptFinally {
#[derive_message_formats]
fn message(&self) -> String {
"Don't use `return` in `try`-`except` and `finally`".to_string()
}
}
fn find_return(stmts: &[Stmt]) -> Option<&Stmt> {
stmts.iter().find(|stmt| stmt.is_return_stmt())
}
/// SIM107
pub(crate) fn return_in_try_except_finally(
checker: &Checker,
body: &[Stmt],
handlers: &[ExceptHandler],
finalbody: &[Stmt],
) {
let try_has_return = find_return(body).is_some();
let except_has_return = handlers.iter().any(|handler| {
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { body, .. }) = handler;
find_return(body).is_some()
});
if try_has_return || except_has_return {
if let Some(finally_return) = find_return(finalbody) {
checker.report_diagnostic(ReturnInTryExceptFinally, finally_return.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_blind_except/mod.rs | crates/ruff_linter/src/rules/flake8_blind_except/mod.rs | //! Rules from [flake8-blind-except](https://pypi.org/project/flake8-blind-except/).
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::BlindExcept, Path::new("BLE.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_blind_except").join(path).as_path(),
&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_blind_except/rules/blind_except.rs | crates/ruff_linter/src/rules/flake8_blind_except/rules/blind_except.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_const_true;
use ruff_python_ast::statement_visitor::{StatementVisitor, walk_stmt};
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::logging;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for `except` clauses that catch all exceptions. This includes
/// `except BaseException` and `except Exception`.
///
///
/// ## Why is this bad?
/// Overly broad `except` clauses can lead to unexpected behavior, such as
/// catching `KeyboardInterrupt` or `SystemExit` exceptions that prevent the
/// user from exiting the program.
///
/// Instead of catching all exceptions, catch only those that are expected to
/// be raised in the `try` block.
///
/// ## Example
/// ```python
/// try:
/// foo()
/// except BaseException:
/// ...
/// ```
///
/// Use instead:
/// ```python
/// try:
/// foo()
/// except FileNotFoundError:
/// ...
/// ```
///
/// Exceptions that are re-raised will _not_ be flagged, as they're expected to
/// be caught elsewhere:
/// ```python
/// try:
/// foo()
/// except BaseException:
/// raise
/// ```
///
/// Exceptions that are logged via `logging.exception()` or are logged via
/// `logging.error()` or `logging.critical()` with `exc_info` enabled will
/// _not_ be flagged, as this is a common pattern for propagating exception
/// traces:
/// ```python
/// try:
/// foo()
/// except BaseException:
/// logging.exception("Something went wrong")
/// ```
///
/// ## Options
///
/// - `lint.logger-objects`
///
/// ## References
/// - [Python documentation: The `try` statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)
/// - [Python documentation: Exception hierarchy](https://docs.python.org/3/library/exceptions.html#exception-hierarchy)
/// - [PEP 8: Programming Recommendations on bare `except`](https://peps.python.org/pep-0008/#programming-recommendations)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.127")]
pub(crate) struct BlindExcept {
name: String,
}
impl Violation for BlindExcept {
#[derive_message_formats]
fn message(&self) -> String {
let BlindExcept { name } = self;
format!("Do not catch blind exception: `{name}`")
}
}
fn contains_blind_exception<'a>(
semantic: &'a SemanticModel,
expr: &'a Expr,
) -> Option<(&'a str, ruff_text_size::TextRange)> {
match expr {
Expr::Tuple(ast::ExprTuple { elts, .. }) => elts
.iter()
.find_map(|elt| contains_blind_exception(semantic, elt)),
_ => {
let builtin_exception_type = semantic.resolve_builtin_symbol(expr)?;
matches!(builtin_exception_type, "BaseException" | "Exception")
.then(|| (builtin_exception_type, expr.range()))
}
}
}
/// BLE001
pub(crate) fn blind_except(
checker: &Checker,
type_: Option<&Expr>,
name: Option<&str>,
body: &[Stmt],
) {
let Some(type_) = type_ else {
return;
};
let semantic = checker.semantic();
let Some((builtin_exception_type, range)) = contains_blind_exception(semantic, type_) else {
return;
};
// If the exception is re-raised, don't flag an error.
let mut visitor = ReraiseVisitor::new(name);
visitor.visit_body(body);
if visitor.seen() {
return;
}
// If the exception is logged, don't flag an error.
let mut visitor = LogExceptionVisitor::new(semantic, &checker.settings().logger_objects);
visitor.visit_body(body);
if visitor.seen() {
return;
}
checker.report_diagnostic(
BlindExcept {
name: builtin_exception_type.into(),
},
range,
);
}
/// A visitor to detect whether the exception with the given name was re-raised.
struct ReraiseVisitor<'a> {
name: Option<&'a str>,
seen: bool,
}
impl<'a> ReraiseVisitor<'a> {
/// Create a new [`ReraiseVisitor`] with the given exception name.
fn new(name: Option<&'a str>) -> Self {
Self { name, seen: false }
}
/// Returns `true` if the exception was re-raised.
fn seen(&self) -> bool {
self.seen
}
}
impl<'a> StatementVisitor<'a> for ReraiseVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
if self.seen {
return;
}
match stmt {
Stmt::Raise(ast::StmtRaise { exc, cause, .. }) => {
// except Exception [as <name>]:
// raise [<exc> [from <cause>]]
let reraised = match (self.name, exc.as_deref(), cause.as_deref()) {
// `raise`
(_, None, None) => true,
// `raise SomeExc from <name>`
(Some(name), _, Some(Expr::Name(ast::ExprName { id, .. }))) if name == id => {
true
}
// `raise <name>` and `raise <name> from SomeCause`
(Some(name), Some(Expr::Name(ast::ExprName { id, .. })), _) if name == id => {
true
}
_ => false,
};
if reraised {
self.seen = true;
}
}
Stmt::Try(_) | Stmt::FunctionDef(_) | Stmt::ClassDef(_) => {}
_ => walk_stmt(self, stmt),
}
}
}
/// A visitor to detect whether the exception was logged.
struct LogExceptionVisitor<'a> {
semantic: &'a SemanticModel<'a>,
logger_objects: &'a [String],
seen: bool,
}
impl<'a> LogExceptionVisitor<'a> {
/// Create a new [`LogExceptionVisitor`] with the given exception name.
fn new(semantic: &'a SemanticModel<'a>, logger_objects: &'a [String]) -> Self {
Self {
semantic,
logger_objects,
seen: false,
}
}
/// Returns `true` if the exception was logged.
fn seen(&self) -> bool {
self.seen
}
}
impl<'a> StatementVisitor<'a> for LogExceptionVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
if self.seen {
return;
}
match stmt {
Stmt::Expr(ast::StmtExpr { value, .. }) => {
if let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = value.as_ref()
{
match func.as_ref() {
Expr::Attribute(ast::ExprAttribute { attr, .. }) => {
if logging::is_logger_candidate(
func,
self.semantic,
self.logger_objects,
) {
if match attr.as_str() {
"exception" => true,
"error" | "critical" => arguments
.find_keyword("exc_info")
.is_some_and(|keyword| is_const_true(&keyword.value)),
_ => false,
} {
self.seen = true;
}
}
}
Expr::Name(ast::ExprName { .. }) => {
if self.semantic.resolve_qualified_name(func).is_some_and(
|qualified_name| match qualified_name.segments() {
["logging", "exception"] => true,
["logging", "error" | "critical"] => arguments
.find_keyword("exc_info")
.is_some_and(|keyword| is_const_true(&keyword.value)),
_ => false,
},
) {
self.seen = true;
}
}
_ => {}
}
}
}
Stmt::Try(_) | Stmt::FunctionDef(_) | Stmt::ClassDef(_) => {}
_ => walk_stmt(self, stmt),
}
}
}
| 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_blind_except/rules/mod.rs | crates/ruff_linter/src/rules/flake8_blind_except/rules/mod.rs | pub(crate) use blind_except::*;
mod blind_except;
| 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_async/helpers.rs | crates/ruff_linter/src/rules/flake8_async/helpers.rs | use ruff_python_ast::name::QualifiedName;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) enum AsyncModule {
/// `anyio`
AnyIo,
/// `asyncio`
AsyncIo,
/// `trio`
Trio,
}
impl AsyncModule {
pub(super) fn try_from(qualified_name: &QualifiedName<'_>) -> Option<Self> {
match qualified_name.segments() {
["asyncio", ..] => Some(Self::AsyncIo),
["anyio", ..] => Some(Self::AnyIo),
["trio", ..] => Some(Self::Trio),
_ => None,
}
}
}
impl std::fmt::Display for AsyncModule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AsyncModule::AnyIo => write!(f, "anyio"),
AsyncModule::AsyncIo => write!(f, "asyncio"),
AsyncModule::Trio => write!(f, "trio"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) enum MethodName {
AsyncIoTimeout,
AsyncIoTimeoutAt,
AnyIoMoveOnAfter,
AnyIoFailAfter,
AnyIoCancelScope,
TrioAcloseForcefully,
TrioCancelScope,
TrioCancelShieldedCheckpoint,
TrioCheckpoint,
TrioCheckpointIfCancelled,
TrioFailAfter,
TrioFailAt,
TrioMoveOnAfter,
TrioMoveOnAt,
TrioOpenFile,
TrioOpenProcess,
TrioOpenSslOverTcpListeners,
TrioOpenSslOverTcpStream,
TrioOpenTcpListeners,
TrioOpenTcpStream,
TrioOpenUnixSocket,
TrioPermanentlyDetachCoroutineObject,
TrioReattachDetachedCoroutineObject,
TrioRunProcess,
TrioServeListeners,
TrioServeSslOverTcp,
TrioServeTcp,
TrioSleep,
TrioSleepForever,
TrioTemporarilyDetachCoroutineObject,
TrioWaitReadable,
TrioWaitTaskRescheduled,
TrioWaitWritable,
}
impl MethodName {
/// Returns `true` if the method is async, `false` if it is sync.
pub(super) fn is_async(self) -> bool {
matches!(
self,
MethodName::TrioAcloseForcefully
| MethodName::TrioCancelShieldedCheckpoint
| MethodName::TrioCheckpoint
| MethodName::TrioCheckpointIfCancelled
| MethodName::TrioOpenFile
| MethodName::TrioOpenProcess
| MethodName::TrioOpenSslOverTcpListeners
| MethodName::TrioOpenSslOverTcpStream
| MethodName::TrioOpenTcpListeners
| MethodName::TrioOpenTcpStream
| MethodName::TrioOpenUnixSocket
| MethodName::TrioPermanentlyDetachCoroutineObject
| MethodName::TrioReattachDetachedCoroutineObject
| MethodName::TrioRunProcess
| MethodName::TrioServeListeners
| MethodName::TrioServeSslOverTcp
| MethodName::TrioServeTcp
| MethodName::TrioSleep
| MethodName::TrioSleepForever
| MethodName::TrioTemporarilyDetachCoroutineObject
| MethodName::TrioWaitReadable
| MethodName::TrioWaitTaskRescheduled
| MethodName::TrioWaitWritable
)
}
/// Returns `true` if the method a timeout context manager.
pub(super) fn is_timeout_context(self) -> bool {
matches!(
self,
MethodName::AsyncIoTimeout
| MethodName::AsyncIoTimeoutAt
| MethodName::AnyIoMoveOnAfter
| MethodName::AnyIoFailAfter
| MethodName::AnyIoCancelScope
| MethodName::TrioMoveOnAfter
| MethodName::TrioMoveOnAt
| MethodName::TrioFailAfter
| MethodName::TrioFailAt
| MethodName::TrioCancelScope
)
}
}
impl MethodName {
pub(super) fn try_from(qualified_name: &QualifiedName<'_>) -> Option<Self> {
match qualified_name.segments() {
["asyncio", "timeout"] => Some(Self::AsyncIoTimeout),
["asyncio", "timeout_at"] => Some(Self::AsyncIoTimeoutAt),
["anyio", "move_on_after"] => Some(Self::AnyIoMoveOnAfter),
["anyio", "fail_after"] => Some(Self::AnyIoFailAfter),
["anyio", "CancelScope"] => Some(Self::AnyIoCancelScope),
["trio", "CancelScope"] => Some(Self::TrioCancelScope),
["trio", "aclose_forcefully"] => Some(Self::TrioAcloseForcefully),
["trio", "fail_after"] => Some(Self::TrioFailAfter),
["trio", "fail_at"] => Some(Self::TrioFailAt),
["trio", "lowlevel", "cancel_shielded_checkpoint"] => {
Some(Self::TrioCancelShieldedCheckpoint)
}
["trio", "lowlevel", "checkpoint"] => Some(Self::TrioCheckpoint),
["trio", "lowlevel", "checkpoint_if_cancelled"] => {
Some(Self::TrioCheckpointIfCancelled)
}
["trio", "lowlevel", "open_process"] => Some(Self::TrioOpenProcess),
["trio", "lowlevel", "permanently_detach_coroutine_object"] => {
Some(Self::TrioPermanentlyDetachCoroutineObject)
}
["trio", "lowlevel", "reattach_detached_coroutine_object"] => {
Some(Self::TrioReattachDetachedCoroutineObject)
}
["trio", "lowlevel", "temporarily_detach_coroutine_object"] => {
Some(Self::TrioTemporarilyDetachCoroutineObject)
}
["trio", "lowlevel", "wait_readable"] => Some(Self::TrioWaitReadable),
["trio", "lowlevel", "wait_task_rescheduled"] => Some(Self::TrioWaitTaskRescheduled),
["trio", "lowlevel", "wait_writable"] => Some(Self::TrioWaitWritable),
["trio", "move_on_after"] => Some(Self::TrioMoveOnAfter),
["trio", "move_on_at"] => Some(Self::TrioMoveOnAt),
["trio", "open_file"] => Some(Self::TrioOpenFile),
["trio", "open_ssl_over_tcp_listeners"] => Some(Self::TrioOpenSslOverTcpListeners),
["trio", "open_ssl_over_tcp_stream"] => Some(Self::TrioOpenSslOverTcpStream),
["trio", "open_tcp_listeners"] => Some(Self::TrioOpenTcpListeners),
["trio", "open_tcp_stream"] => Some(Self::TrioOpenTcpStream),
["trio", "open_unix_socket"] => Some(Self::TrioOpenUnixSocket),
["trio", "run_process"] => Some(Self::TrioRunProcess),
["trio", "serve_listeners"] => Some(Self::TrioServeListeners),
["trio", "serve_ssl_over_tcp"] => Some(Self::TrioServeSslOverTcp),
["trio", "serve_tcp"] => Some(Self::TrioServeTcp),
["trio", "sleep"] => Some(Self::TrioSleep),
["trio", "sleep_forever"] => Some(Self::TrioSleepForever),
_ => None,
}
}
}
impl std::fmt::Display for MethodName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MethodName::AsyncIoTimeout => write!(f, "asyncio.timeout"),
MethodName::AsyncIoTimeoutAt => write!(f, "asyncio.timeout_at"),
MethodName::AnyIoMoveOnAfter => write!(f, "anyio.move_on_after"),
MethodName::AnyIoFailAfter => write!(f, "anyio.fail_after"),
MethodName::AnyIoCancelScope => write!(f, "anyio.CancelScope"),
MethodName::TrioAcloseForcefully => write!(f, "trio.aclose_forcefully"),
MethodName::TrioCancelScope => write!(f, "trio.CancelScope"),
MethodName::TrioCancelShieldedCheckpoint => {
write!(f, "trio.lowlevel.cancel_shielded_checkpoint")
}
MethodName::TrioCheckpoint => write!(f, "trio.lowlevel.checkpoint"),
MethodName::TrioCheckpointIfCancelled => {
write!(f, "trio.lowlevel.checkpoint_if_cancelled")
}
MethodName::TrioFailAfter => write!(f, "trio.fail_after"),
MethodName::TrioFailAt => write!(f, "trio.fail_at"),
MethodName::TrioMoveOnAfter => write!(f, "trio.move_on_after"),
MethodName::TrioMoveOnAt => write!(f, "trio.move_on_at"),
MethodName::TrioOpenFile => write!(f, "trio.open_file"),
MethodName::TrioOpenProcess => write!(f, "trio.lowlevel.open_process"),
MethodName::TrioOpenSslOverTcpListeners => {
write!(f, "trio.open_ssl_over_tcp_listeners")
}
MethodName::TrioOpenSslOverTcpStream => write!(f, "trio.open_ssl_over_tcp_stream"),
MethodName::TrioOpenTcpListeners => write!(f, "trio.open_tcp_listeners"),
MethodName::TrioOpenTcpStream => write!(f, "trio.open_tcp_stream"),
MethodName::TrioOpenUnixSocket => write!(f, "trio.open_unix_socket"),
MethodName::TrioPermanentlyDetachCoroutineObject => {
write!(f, "trio.lowlevel.permanently_detach_coroutine_object")
}
MethodName::TrioReattachDetachedCoroutineObject => {
write!(f, "trio.lowlevel.reattach_detached_coroutine_object")
}
MethodName::TrioRunProcess => write!(f, "trio.run_process"),
MethodName::TrioServeListeners => write!(f, "trio.serve_listeners"),
MethodName::TrioServeSslOverTcp => write!(f, "trio.serve_ssl_over_tcp"),
MethodName::TrioServeTcp => write!(f, "trio.serve_tcp"),
MethodName::TrioSleep => write!(f, "trio.sleep"),
MethodName::TrioSleepForever => write!(f, "trio.sleep_forever"),
MethodName::TrioTemporarilyDetachCoroutineObject => {
write!(f, "trio.lowlevel.temporarily_detach_coroutine_object")
}
MethodName::TrioWaitReadable => write!(f, "trio.lowlevel.wait_readable"),
MethodName::TrioWaitTaskRescheduled => write!(f, "trio.lowlevel.wait_task_rescheduled"),
MethodName::TrioWaitWritable => write!(f, "trio.lowlevel.wait_writable"),
}
}
}
| 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_async/mod.rs | crates/ruff_linter/src/rules/flake8_async/mod.rs | //! Rules from [flake8-async](https://pypi.org/project/flake8-async/).
mod helpers;
pub(crate) mod rules;
#[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 ruff_python_ast::PythonVersion;
#[test_case(Rule::CancelScopeNoCheckpoint, Path::new("ASYNC100.py"))]
#[test_case(Rule::TrioSyncCall, Path::new("ASYNC105.py"))]
#[test_case(Rule::AsyncFunctionWithTimeout, Path::new("ASYNC109_0.py"))]
#[test_case(Rule::AsyncFunctionWithTimeout, Path::new("ASYNC109_1.py"))]
#[test_case(Rule::AsyncBusyWait, Path::new("ASYNC110.py"))]
#[test_case(Rule::AsyncZeroSleep, Path::new("ASYNC115.py"))]
#[test_case(Rule::LongSleepNotForever, Path::new("ASYNC116.py"))]
#[test_case(Rule::BlockingHttpCallInAsyncFunction, Path::new("ASYNC210.py"))]
#[test_case(Rule::BlockingHttpCallHttpxInAsyncFunction, Path::new("ASYNC212.py"))]
#[test_case(Rule::CreateSubprocessInAsyncFunction, Path::new("ASYNC22x.py"))]
#[test_case(Rule::RunProcessInAsyncFunction, Path::new("ASYNC22x.py"))]
#[test_case(Rule::WaitForProcessInAsyncFunction, Path::new("ASYNC22x.py"))]
#[test_case(Rule::BlockingOpenCallInAsyncFunction, Path::new("ASYNC230.py"))]
#[test_case(Rule::BlockingPathMethodInAsyncFunction, Path::new("ASYNC240.py"))]
#[test_case(Rule::BlockingInputInAsyncFunction, Path::new("ASYNC250.py"))]
#[test_case(Rule::BlockingSleepInAsyncFunction, Path::new("ASYNC251.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_async").join(path).as_path(),
&LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Path::new("ASYNC109_0.py"); "asyncio")]
#[test_case(Path::new("ASYNC109_1.py"); "trio")]
fn async109_python_310_or_older(path: &Path) -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_async").join(path),
&LinterSettings {
unresolved_target_version: PythonVersion::PY310.into(),
..LinterSettings::for_rule(Rule::AsyncFunctionWithTimeout)
},
)?;
assert_diagnostics!(path.file_name().unwrap().to_str().unwrap(), 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_async/rules/blocking_process_invocation.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_process_invocation.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::typing::find_assigned_value;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that async functions do not create subprocesses with blocking methods.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// call to complete, negating the benefits of asynchronous programming.
///
/// Instead of making a blocking call, use an equivalent asynchronous library
/// or function, like [`trio.run_process()`](https://trio.readthedocs.io/en/stable/reference-io.html#trio.run_process)
/// or [`anyio.run_process()`](https://anyio.readthedocs.io/en/latest/api.html#anyio.run_process).
///
/// ## Example
/// ```python
/// import os
///
///
/// async def foo():
/// os.popen(cmd)
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
///
///
/// async def foo():
/// asyncio.create_subprocess_shell(cmd)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct CreateSubprocessInAsyncFunction;
impl Violation for CreateSubprocessInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Async functions should not create subprocesses with blocking methods".to_string()
}
}
/// ## What it does
/// Checks that async functions do not run processes with blocking methods.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// call to complete, negating the benefits of asynchronous programming.
///
/// Instead of making a blocking call, use an equivalent asynchronous library
/// or function, like [`trio.run_process()`](https://trio.readthedocs.io/en/stable/reference-io.html#trio.run_process)
/// or [`anyio.run_process()`](https://anyio.readthedocs.io/en/latest/api.html#anyio.run_process).
///
/// ## Example
/// ```python
/// import subprocess
///
///
/// async def foo():
/// subprocess.run(cmd)
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
///
///
/// async def foo():
/// asyncio.create_subprocess_shell(cmd)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct RunProcessInAsyncFunction;
impl Violation for RunProcessInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Async functions should not run processes with blocking methods".to_string()
}
}
/// ## What it does
/// Checks that async functions do not wait on processes with blocking methods.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// call to complete, negating the benefits of asynchronous programming.
///
/// Instead of making a blocking call, use an equivalent asynchronous library
/// or function, like [`trio.to_thread.run_sync()`](https://trio.readthedocs.io/en/latest/reference-core.html#trio.to_thread.run_sync)
/// or [`anyio.to_thread.run_sync()`](https://anyio.readthedocs.io/en/latest/api.html#anyio.to_thread.run_sync).
///
/// ## Example
/// ```python
/// import os
///
///
/// async def foo():
/// os.waitpid(0)
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
/// import os
///
///
/// def wait_for_process():
/// os.waitpid(0)
///
///
/// async def foo():
/// await asyncio.loop.run_in_executor(None, wait_for_process)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct WaitForProcessInAsyncFunction;
impl Violation for WaitForProcessInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Async functions should not wait on processes with blocking methods".to_string()
}
}
/// ASYNC220, ASYNC221, ASYNC222
pub(crate) fn blocking_process_invocation(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().in_async_context() {
return;
}
let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};
let range = call.func.range();
match qualified_name.segments() {
["subprocess", "Popen"] | ["os", "popen"] => {
checker.report_diagnostic_if_enabled(CreateSubprocessInAsyncFunction, range)
}
["os", "system" | "posix_spawn" | "posix_spawnp"]
| [
"subprocess",
"run" | "call" | "check_call" | "check_output" | "getoutput" | "getstatusoutput",
] => checker.report_diagnostic_if_enabled(RunProcessInAsyncFunction, range),
["os", "wait" | "wait3" | "wait4" | "waitid" | "waitpid"] => {
checker.report_diagnostic_if_enabled(WaitForProcessInAsyncFunction, range)
}
[
"os",
"spawnl" | "spawnle" | "spawnlp" | "spawnlpe" | "spawnv" | "spawnve" | "spawnvp"
| "spawnvpe",
] => {
if is_p_wait(call, checker.semantic()) {
checker.report_diagnostic_if_enabled(RunProcessInAsyncFunction, range)
} else {
checker.report_diagnostic_if_enabled(CreateSubprocessInAsyncFunction, range)
}
}
_ => return,
};
}
fn is_p_wait(call: &ast::ExprCall, semantic: &SemanticModel) -> bool {
let Some(arg) = call.arguments.find_argument_value("mode", 0) else {
return true;
};
if let Some(qualified_name) = semantic.resolve_qualified_name(arg) {
return matches!(qualified_name.segments(), ["os", "P_WAIT"]);
} else if let Expr::Name(ast::ExprName { id, .. }) = arg {
let Some(value) = find_assigned_value(id, semantic) else {
return false;
};
if let Some(qualified_name) = semantic.resolve_qualified_name(value) {
return matches!(qualified_name.segments(), ["os", "P_WAIT"]);
}
}
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_async/rules/blocking_http_call_httpx.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call_httpx.rs | use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::analyze::typing::{TypeChecker, check_type, traverse_union_and_optional};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that async functions do not use blocking httpx clients.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking HTTP call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// HTTP response, negating the benefits of asynchronous programming.
///
/// Instead of using the blocking `httpx` client, use the asynchronous client.
///
/// ## Example
/// ```python
/// import httpx
///
///
/// async def fetch():
/// client = httpx.Client()
/// response = client.get(...)
/// ```
///
/// Use instead:
/// ```python
/// import httpx
///
///
/// async def fetch():
/// async with httpx.AsyncClient() as client:
/// response = await client.get(...)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.12.11")]
pub(crate) struct BlockingHttpCallHttpxInAsyncFunction {
name: String,
call: String,
}
impl Violation for BlockingHttpCallHttpxInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Blocking httpx method {name}.{call}() in async context, use httpx.AsyncClient",
name = self.name,
call = self.call,
)
}
}
struct HttpxClientChecker;
impl TypeChecker for HttpxClientChecker {
fn match_annotation(
annotation: &ruff_python_ast::Expr,
semantic: &ruff_python_semantic::SemanticModel,
) -> bool {
// match base annotation directly
if semantic
.resolve_qualified_name(annotation)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["httpx", "Client"]))
{
return true;
}
// otherwise traverse any union or optional annotation
let mut found = false;
traverse_union_and_optional(
&mut |inner_expr, _| {
if semantic
.resolve_qualified_name(inner_expr)
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["httpx", "Client"])
})
{
found = true;
}
},
semantic,
annotation,
);
found
}
fn match_initializer(
initializer: &ruff_python_ast::Expr,
semantic: &ruff_python_semantic::SemanticModel,
) -> bool {
let Expr::Call(ExprCall { func, .. }) = initializer else {
return false;
};
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["httpx", "Client"]))
}
}
/// ASYNC212
pub(crate) fn blocking_http_call_httpx(checker: &Checker, call: &ExprCall) {
let semantic = checker.semantic();
if !semantic.in_async_context() {
return;
}
let Some(ast::ExprAttribute { value, attr, .. }) = call.func.as_attribute_expr() else {
return;
};
let Some(name) = value.as_name_expr() else {
return;
};
let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else {
return;
};
if check_type::<HttpxClientChecker>(binding, semantic) {
if matches!(
attr.id.as_str(),
"close"
| "delete"
| "get"
| "head"
| "options"
| "patch"
| "post"
| "put"
| "request"
| "send"
| "stream"
) {
checker.report_diagnostic(
BlockingHttpCallHttpxInAsyncFunction {
name: name.id.to_string(),
call: attr.id.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_async/rules/blocking_http_call.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call.rs | use ruff_python_ast::ExprCall;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::QualifiedName;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that async functions do not contain blocking HTTP calls.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking HTTP call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// HTTP response, negating the benefits of asynchronous programming.
///
/// Instead of making a blocking HTTP call, use an asynchronous HTTP client
/// library such as `aiohttp` or `httpx`.
///
/// ## Example
/// ```python
/// import urllib
///
///
/// async def fetch():
/// urllib.request.urlopen("https://example.com/foo/bar").read()
/// ```
///
/// Use instead:
/// ```python
/// import aiohttp
///
///
/// async def fetch():
/// async with aiohttp.ClientSession() as session:
/// async with session.get("https://example.com/foo/bar") as resp:
/// ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct BlockingHttpCallInAsyncFunction;
impl Violation for BlockingHttpCallInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Async functions should not call blocking HTTP methods".to_string()
}
}
fn is_blocking_http_call(qualified_name: &QualifiedName) -> bool {
matches!(
qualified_name.segments(),
["urllib", "request", "urlopen"]
| ["urllib3", "request"]
| [
"httpx" | "requests",
"get"
| "post"
| "delete"
| "patch"
| "put"
| "head"
| "connect"
| "options"
| "trace"
]
)
}
/// ASYNC210
pub(crate) fn blocking_http_call(checker: &Checker, call: &ExprCall) {
if checker.semantic().in_async_context() {
if checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
.as_ref()
.is_some_and(is_blocking_http_call)
{
checker.report_diagnostic(BlockingHttpCallInAsyncFunction, 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_async/rules/async_zero_sleep.rs | crates/ruff_linter/src/rules/flake8_async/rules/async_zero_sleep.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprCall, Int, Number};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::rules::flake8_async::helpers::AsyncModule;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `trio.sleep(0)` or `anyio.sleep(0)`.
///
/// ## Why is this bad?
/// `trio.sleep(0)` is equivalent to calling `trio.lowlevel.checkpoint()`.
/// However, the latter better conveys the intent of the code.
///
/// ## Example
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.sleep(0)
/// ```
///
/// Use instead:
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.lowlevel.checkpoint()
/// ```
/// ## Fix safety
/// This rule's fix is marked as unsafe if there's comments in the
/// `trio.sleep(0)` expression, as comments may be removed.
///
/// For example, the fix would be marked as unsafe in the following case:
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.sleep( # comment
/// # comment
/// 0
/// )
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct AsyncZeroSleep {
module: AsyncModule,
}
impl AlwaysFixableViolation for AsyncZeroSleep {
#[derive_message_formats]
fn message(&self) -> String {
let Self { module } = self;
format!("Use `{module}.lowlevel.checkpoint()` instead of `{module}.sleep(0)`")
}
fn fix_title(&self) -> String {
let Self { module } = self;
format!("Replace with `{module}.lowlevel.checkpoint()`")
}
}
/// ASYNC115
pub(crate) fn async_zero_sleep(checker: &Checker, call: &ExprCall) {
if !(checker.semantic().seen_module(Modules::TRIO)
|| checker.semantic().seen_module(Modules::ANYIO))
{
return;
}
if call.arguments.len() != 1 {
return;
}
let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};
let Some(module) = AsyncModule::try_from(&qualified_name) else {
return;
};
// Determine the correct argument name
let arg_name = match module {
AsyncModule::Trio => "seconds",
AsyncModule::AnyIo => "delay",
AsyncModule::AsyncIo => return,
};
let Some(arg) = call.arguments.find_argument_value(arg_name, 0) else {
return;
};
match arg {
Expr::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => {
if !matches!(value, Number::Int(Int::ZERO)) {
return;
}
}
_ => return,
}
let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};
if let Some(module) = AsyncModule::try_from(&qualified_name) {
let is_relevant_module = matches!(module, AsyncModule::Trio | AsyncModule::AnyIo);
let is_sleep = is_relevant_module && matches!(qualified_name.segments(), [_, "sleep"]);
if !is_sleep {
return;
}
let mut diagnostic = checker.report_diagnostic(AsyncZeroSleep { module }, call.range());
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from(&module.to_string(), "lowlevel"),
call.func.start(),
checker.semantic(),
)?;
let reference_edit =
Edit::range_replacement(format!("{binding}.checkpoint"), call.func.range());
let arg_edit = Edit::range_replacement("()".to_string(), call.arguments.range());
Ok(Fix::applicable_edits(
import_edit,
[reference_edit, arg_edit],
if checker.comment_ranges().intersects(call.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
},
))
});
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_async/rules/blocking_input.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_input.rs | use ruff_python_ast::ExprCall;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that async functions do not contain blocking usage of input from user.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking input call will block the entire
/// event loop, preventing it from executing other tasks while waiting for user
/// input, negating the benefits of asynchronous programming.
///
/// Instead of making a blocking input call directly, wrap the input call in
/// an executor to execute the blocking call on another thread.
///
/// ## Example
/// ```python
/// async def foo():
/// username = input("Username:")
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
///
///
/// async def foo():
/// loop = asyncio.get_running_loop()
/// username = await loop.run_in_executor(None, input, "Username:")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.12.12")]
pub(crate) struct BlockingInputInAsyncFunction;
impl Violation for BlockingInputInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Blocking call to input() in async context".to_string()
}
}
/// ASYNC250
pub(crate) fn blocking_input(checker: &Checker, call: &ExprCall) {
if checker.semantic().in_async_context() {
if checker.semantic().match_builtin_expr(&call.func, "input") {
checker.report_diagnostic(BlockingInputInAsyncFunction, 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_async/rules/blocking_open_call.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_open_call.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::{SemanticModel, analyze};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that async functions do not open files with blocking methods like `open`.
///
/// ## Why is this bad?
/// Blocking an async function via a blocking call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// call to complete, negating the benefits of asynchronous programming.
///
/// Instead of making a blocking call, use an equivalent asynchronous library
/// or function.
///
/// ## Example
/// ```python
/// async def foo():
/// with open("bar.txt") as f:
/// contents = f.read()
/// ```
///
/// Use instead:
/// ```python
/// import anyio
///
///
/// async def foo():
/// async with await anyio.open_file("bar.txt") as f:
/// contents = await f.read()
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct BlockingOpenCallInAsyncFunction;
impl Violation for BlockingOpenCallInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Async functions should not open files with blocking methods like `open`".to_string()
}
}
/// ASYNC230
pub(crate) fn blocking_open_call(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().in_async_context() {
return;
}
if is_open_call(&call.func, checker.semantic())
|| is_open_call_from_pathlib(call.func.as_ref(), checker.semantic())
{
checker.report_diagnostic(BlockingOpenCallInAsyncFunction, call.func.range());
}
}
/// Returns `true` if the expression resolves to a blocking open call, like `open` or `Path().open()`.
fn is_open_call(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["" | "io", "open"] | ["io", "open_code"]
)
})
}
/// Returns `true` if an expression resolves to a call to `pathlib.Path.open`.
pub(crate) fn is_open_call_from_pathlib(func: &Expr, semantic: &SemanticModel) -> bool {
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func else {
return false;
};
if attr.as_str() != "open" {
return false;
}
// First: is this an inlined call to `pathlib.Path.open`?
// ```python
// from pathlib import Path
// Path("foo").open()
// ```
if let Expr::Call(call) = value.as_ref() {
let Some(qualified_name) = semantic.resolve_qualified_name(call.func.as_ref()) else {
return false;
};
if qualified_name.segments() == ["pathlib", "Path"] {
return true;
}
}
// Second, is this a call to `pathlib.Path.open` via a variable?
// ```python
// from pathlib import Path
// path = Path("foo")
// path.open()
// ```
let Expr::Name(name) = value.as_ref() else {
return false;
};
let Some(binding_id) = semantic.resolve_name(name) else {
return false;
};
let binding = semantic.binding(binding_id);
let Some(Expr::Call(call)) = analyze::typing::find_binding_value(binding, semantic) else {
return false;
};
semantic
.resolve_qualified_name(call.func.as_ref())
.is_some_and(|qualified_name| qualified_name.segments() == ["pathlib", "Path"])
}
| 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_async/rules/blocking_path_methods.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_path_methods.rs | use crate::Violation;
use crate::checkers::ast::Checker;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_semantic::analyze::typing::{TypeChecker, check_type, traverse_union_and_optional};
use ruff_text_size::Ranged;
/// ## What it does
/// Checks that async functions do not call blocking `os.path` or `pathlib.Path`
/// methods.
///
/// ## Why is this bad?
/// Calling some `os.path` or `pathlib.Path` methods in an async function will block
/// the entire event loop, preventing it from executing other tasks while waiting
/// for the operation. This negates the benefits of asynchronous programming.
///
/// Instead, use the methods' async equivalents from `trio.Path` or `anyio.Path`.
///
/// ## Example
/// ```python
/// import os
///
///
/// async def func():
/// path = "my_file.txt"
/// file_exists = os.path.exists(path)
/// ```
///
/// Use instead:
/// ```python
/// import trio
///
///
/// async def func():
/// path = trio.Path("my_file.txt")
/// file_exists = await path.exists()
/// ```
///
/// Non-blocking methods are OK to use:
/// ```python
/// import pathlib
///
///
/// async def func():
/// path = pathlib.Path("my_file.txt")
/// file_dirname = path.dirname()
/// new_path = os.path.join("/tmp/src/", path)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.13.2")]
pub(crate) struct BlockingPathMethodInAsyncFunction {
path_library: String,
}
impl Violation for BlockingPathMethodInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Async functions should not use {path_library} methods, use trio.Path or anyio.path",
path_library = self.path_library
)
}
}
/// ASYNC240
pub(crate) fn blocking_os_path(checker: &Checker, call: &ExprCall) {
let semantic = checker.semantic();
if !semantic.in_async_context() {
return;
}
// Check if an expression is calling I/O related os.path method.
// Just initializing pathlib.Path object is OK, we can return
// early in that scenario.
if let Some(qualified_name) = semantic.resolve_qualified_name(call.func.as_ref()) {
let segments = qualified_name.segments();
if !matches!(segments, ["os", "path", _]) {
return;
}
let Some(os_path_method) = segments.last() else {
return;
};
if maybe_calling_io_operation(os_path_method) {
checker.report_diagnostic(
BlockingPathMethodInAsyncFunction {
path_library: "os.path".to_string(),
},
call.func.range(),
);
}
return;
}
let Some(ast::ExprAttribute { value, attr, .. }) = call.func.as_attribute_expr() else {
return;
};
if !maybe_calling_io_operation(attr.id.as_str()) {
return;
}
// Check if an expression is a pathlib.Path constructor that directly
// calls an I/O method.
if PathlibPathChecker::match_initializer(value, semantic) {
checker.report_diagnostic(
BlockingPathMethodInAsyncFunction {
path_library: "pathlib.Path".to_string(),
},
call.func.range(),
);
return;
}
// Lastly, check if a variable is a pathlib.Path instance and it's
// calling an I/O method.
let Some(name) = value.as_name_expr() else {
return;
};
let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else {
return;
};
if check_type::<PathlibPathChecker>(binding, semantic) {
checker.report_diagnostic(
BlockingPathMethodInAsyncFunction {
path_library: "pathlib.Path".to_string(),
},
call.func.range(),
);
}
}
struct PathlibPathChecker;
impl PathlibPathChecker {
fn is_pathlib_path_constructor(
semantic: &ruff_python_semantic::SemanticModel,
expr: &Expr,
) -> bool {
let Some(qualified_name) = semantic.resolve_qualified_name(expr) else {
return false;
};
matches!(
qualified_name.segments(),
[
"pathlib",
"Path"
| "PosixPath"
| "PurePath"
| "PurePosixPath"
| "PureWindowsPath"
| "WindowsPath"
]
)
}
}
impl TypeChecker for PathlibPathChecker {
fn match_annotation(annotation: &Expr, semantic: &ruff_python_semantic::SemanticModel) -> bool {
if Self::is_pathlib_path_constructor(semantic, annotation) {
return true;
}
let mut found = false;
traverse_union_and_optional(
&mut |inner_expr, _| {
if Self::is_pathlib_path_constructor(semantic, inner_expr) {
found = true;
}
},
semantic,
annotation,
);
found
}
fn match_initializer(
initializer: &Expr,
semantic: &ruff_python_semantic::SemanticModel,
) -> bool {
let Expr::Call(ast::ExprCall { func, .. }) = initializer else {
return false;
};
Self::is_pathlib_path_constructor(semantic, func)
}
}
fn maybe_calling_io_operation(attr: &str) -> bool {
// ".open()" is added to the allow list to let ASYNC 230 handle
// that case.
!matches!(
attr,
"ALLOW_MISSING"
| "altsep"
| "anchor"
| "as_posix"
| "as_uri"
| "basename"
| "commonpath"
| "commonprefix"
| "curdir"
| "defpath"
| "devnull"
| "dirname"
| "drive"
| "expandvars"
| "extsep"
| "genericpath"
| "is_absolute"
| "is_relative_to"
| "is_reserved"
| "isabs"
| "join"
| "joinpath"
| "match"
| "name"
| "normcase"
| "os"
| "open"
| "pardir"
| "parent"
| "parents"
| "parts"
| "pathsep"
| "relative_to"
| "root"
| "samestat"
| "sep"
| "split"
| "splitdrive"
| "splitext"
| "splitroot"
| "stem"
| "suffix"
| "suffixes"
| "supports_unicode_filenames"
| "sys"
| "with_name"
| "with_segments"
| "with_stem"
| "with_suffix"
)
}
| 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_async/rules/cancel_scope_no_checkpoint.rs | crates/ruff_linter/src/rules/flake8_async/rules/cancel_scope_no_checkpoint.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::{AwaitVisitor, any_over_body};
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{Expr, StmtWith, WithItem};
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_async::helpers::MethodName;
/// ## What it does
/// Checks for timeout context managers which do not contain a checkpoint.
///
/// For the purposes of this check, `yield` is considered a checkpoint,
/// since checkpoints may occur in the caller to which we yield.
///
/// ## Why is this bad?
/// Some asynchronous context managers, such as `asyncio.timeout` and
/// `trio.move_on_after`, have no effect unless they contain a checkpoint.
/// The use of such context managers without an `await`, `async with` or
/// `async for` statement is likely a mistake.
///
/// ## Example
/// ```python
/// import asyncio
///
///
/// async def func():
/// async with asyncio.timeout(2):
/// do_something()
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
///
///
/// async def func():
/// async with asyncio.timeout(2):
/// do_something()
/// await awaitable()
/// ```
///
/// ## References
/// - [`asyncio` timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts)
/// - [`anyio` timeouts](https://anyio.readthedocs.io/en/stable/cancellation.html)
/// - [`trio` timeouts](https://trio.readthedocs.io/en/stable/reference-core.html#cancellation-and-timeouts)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.269")]
pub(crate) struct CancelScopeNoCheckpoint {
method_name: MethodName,
}
impl Violation for CancelScopeNoCheckpoint {
#[derive_message_formats]
fn message(&self) -> String {
let Self { method_name } = self;
format!(
"A `with {method_name}(...):` context does not contain any `await` statements. This makes it pointless, as the timeout can only be triggered by a checkpoint."
)
}
}
/// ASYNC100
pub(crate) fn cancel_scope_no_checkpoint(
checker: &Checker,
with_stmt: &StmtWith,
with_items: &[WithItem],
) {
let Some((with_item_pos, method_name)) = with_items
.iter()
.enumerate()
.filter_map(|(pos, item)| {
let call = item.context_expr.as_call_expr()?;
let qualified_name = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())?;
let method_name = MethodName::try_from(&qualified_name)?;
if method_name.is_timeout_context() {
Some((pos, method_name))
} else {
None
}
})
.next_back()
else {
return;
};
// If this is an `async with` and the timeout has items after it, then the
// further items are checkpoints.
if with_stmt.is_async && with_item_pos < with_items.len() - 1 {
return;
}
// Treat yields as checkpoints, since checkpoints can happen
// in the caller yielded to.
// See: https://flake8-async.readthedocs.io/en/latest/rules.html#async100
// See: https://github.com/astral-sh/ruff/issues/12873
if any_over_body(&with_stmt.body, &Expr::is_yield_expr) {
return;
}
// If the body contains an `await` statement, the context manager is used correctly.
let mut visitor = AwaitVisitor::default();
visitor.visit_body(&with_stmt.body);
if visitor.seen_await {
return;
}
checker.report_diagnostic(CancelScopeNoCheckpoint { method_name }, with_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_async/rules/sync_call.rs | crates/ruff_linter/src/rules/flake8_async/rules/sync_call.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprCall};
use ruff_python_semantic::Modules;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::rules::flake8_async::helpers::MethodName;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for calls to trio functions that are not immediately awaited.
///
/// ## Why is this bad?
/// Many of the functions exposed by trio are asynchronous, and must be awaited
/// to take effect. Calling a trio function without an `await` can lead to
/// `RuntimeWarning` diagnostics and unexpected behaviour.
///
/// ## Example
/// ```python
/// import trio
///
///
/// async def double_sleep(x):
/// trio.sleep(2 * x)
/// ```
///
/// Use instead:
/// ```python
/// import trio
///
///
/// async def double_sleep(x):
/// await trio.sleep(2 * x)
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as adding an `await` to a function
/// call changes its semantics and runtime behavior.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct TrioSyncCall {
method_name: MethodName,
}
impl Violation for TrioSyncCall {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let Self { method_name } = self;
format!("Call to `{method_name}` is not immediately awaited")
}
fn fix_title(&self) -> Option<String> {
Some("Add `await`".to_string())
}
}
/// ASYNC105
pub(crate) fn sync_call(checker: &Checker, call: &ExprCall) {
if !checker.semantic().seen_module(Modules::TRIO) {
return;
}
let Some(method_name) = ({
let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};
MethodName::try_from(&qualified_name)
}) else {
return;
};
if !method_name.is_async() {
return;
}
if checker
.semantic()
.current_expression_parent()
.is_some_and(Expr::is_await_expr)
{
return;
}
let mut diagnostic = checker.report_diagnostic(TrioSyncCall { method_name }, call.range);
if checker.semantic().in_async_context() {
diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion(
pad(
"await".to_string(),
TextRange::new(call.func.start(), call.func.start()),
checker.locator(),
),
call.func.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/flake8_async/rules/mod.rs | crates/ruff_linter/src/rules/flake8_async/rules/mod.rs | pub(crate) use async_busy_wait::*;
pub(crate) use async_function_with_timeout::*;
pub(crate) use async_zero_sleep::*;
pub(crate) use blocking_http_call::*;
pub(crate) use blocking_http_call_httpx::*;
pub(crate) use blocking_input::*;
pub(crate) use blocking_open_call::*;
pub(crate) use blocking_path_methods::*;
pub(crate) use blocking_process_invocation::*;
pub(crate) use blocking_sleep::*;
pub(crate) use cancel_scope_no_checkpoint::*;
pub(crate) use long_sleep_not_forever::*;
pub(crate) use sync_call::*;
mod async_busy_wait;
mod async_function_with_timeout;
mod async_zero_sleep;
mod blocking_http_call;
mod blocking_http_call_httpx;
mod blocking_input;
pub(crate) mod blocking_open_call;
mod blocking_path_methods;
mod blocking_process_invocation;
mod blocking_sleep;
mod cancel_scope_no_checkpoint;
mod long_sleep_not_forever;
mod sync_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_async/rules/async_function_with_timeout.rs | crates/ruff_linter/src/rules/flake8_async/rules/async_function_with_timeout.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_async::helpers::AsyncModule;
use ruff_python_ast::PythonVersion;
#[expect(clippy::doc_link_with_quotes)]
/// ## What it does
/// Checks for `async` function definitions with `timeout` parameters.
///
/// ## Why is this bad?
/// Rather than implementing asynchronous timeout behavior manually, prefer
/// built-in timeout functionality, such as `asyncio.timeout`, `trio.fail_after`,
/// or `anyio.move_on_after`, among others.
///
/// This rule is highly opinionated to enforce a design pattern
/// called ["structured concurrency"] that allows for
/// `async` functions to be oblivious to timeouts,
/// instead letting callers to handle the logic with a context manager.
///
/// ## Details
///
/// This rule attempts to detect which async framework your code is using
/// by analysing the imports in the file it's checking. If it sees an
/// `anyio` import in your code, it will assume `anyio` is your framework
/// of choice; if it sees a `trio` import, it will assume `trio`; if it
/// sees neither, it will assume `asyncio`. `asyncio.timeout` was added
/// in Python 3.11, so if `asyncio` is detected as the framework being used,
/// this rule will be ignored when your configured [`target-version`] is set
/// to less than Python 3.11.
///
/// For functions that wrap `asyncio.timeout`, `trio.fail_after` or
/// `anyio.move_on_after`, false positives from this rule can be avoided
/// by using a different parameter name.
///
/// ## Example
///
/// ```python
/// async def long_running_task(timeout): ...
///
///
/// async def main():
/// await long_running_task(timeout=2)
/// ```
///
/// Use instead:
///
/// ```python
/// async def long_running_task(): ...
///
///
/// async def main():
/// async with asyncio.timeout(2):
/// await long_running_task()
/// ```
///
/// ## References
/// - [`asyncio` timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts)
/// - [`anyio` timeouts](https://anyio.readthedocs.io/en/stable/cancellation.html)
/// - [`trio` timeouts](https://trio.readthedocs.io/en/stable/reference-core.html#cancellation-and-timeouts)
///
/// ["structured concurrency"]: https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#timeouts-and-cancellation
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct AsyncFunctionWithTimeout {
module: AsyncModule,
}
impl Violation for AsyncFunctionWithTimeout {
#[derive_message_formats]
fn message(&self) -> String {
"Async function definition with a `timeout` parameter".to_string()
}
fn fix_title(&self) -> Option<String> {
let Self { module } = self;
let recommendation = match module {
AsyncModule::AnyIo => "anyio.fail_after",
AsyncModule::Trio => "trio.fail_after",
AsyncModule::AsyncIo => "asyncio.timeout",
};
Some(format!("Use `{recommendation}` instead"))
}
}
/// ASYNC109
pub(crate) fn async_function_with_timeout(checker: &Checker, function_def: &ast::StmtFunctionDef) {
// Detect `async` calls with a `timeout` argument.
if !function_def.is_async {
return;
}
// If the function doesn't have a `timeout` parameter, avoid raising the diagnostic.
let Some(timeout) = function_def.parameters.find("timeout") else {
return;
};
// Get preferred module.
let module = if checker.semantic().seen_module(Modules::ANYIO) {
AsyncModule::AnyIo
} else if checker.semantic().seen_module(Modules::TRIO) {
AsyncModule::Trio
} else {
AsyncModule::AsyncIo
};
// asyncio.timeout feature was first introduced in Python 3.11
if module == AsyncModule::AsyncIo && checker.target_version() < PythonVersion::PY311 {
return;
}
checker.report_diagnostic(AsyncFunctionWithTimeout { module }, timeout.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_async/rules/long_sleep_not_forever.rs | crates/ruff_linter/src/rules/flake8_async/rules/long_sleep_not_forever.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprCall, ExprNumberLiteral, Number};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::rules::flake8_async::helpers::AsyncModule;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `trio.sleep()` or `anyio.sleep()` with a delay greater than 24 hours.
///
/// ## Why is this bad?
/// Calling `sleep()` with a delay greater than 24 hours is usually intended
/// to sleep indefinitely. Instead of using a large delay,
/// `trio.sleep_forever()` or `anyio.sleep_forever()` better conveys the intent.
///
///
/// ## Example
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.sleep(86401)
/// ```
///
/// Use instead:
/// ```python
/// import trio
///
///
/// async def func():
/// await trio.sleep_forever()
/// ```
///
/// ## Fix safety
///
/// This fix is marked as unsafe as it changes program behavior.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.13.0")]
pub(crate) struct LongSleepNotForever {
module: AsyncModule,
}
impl Violation for LongSleepNotForever {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let Self { module } = self;
format!(
"`{module}.sleep()` with >24 hour interval should usually be `{module}.sleep_forever()`"
)
}
fn fix_title(&self) -> Option<String> {
let Self { module } = self;
Some(format!("Replace with `{module}.sleep_forever()`"))
}
}
/// ASYNC116
pub(crate) fn long_sleep_not_forever(checker: &Checker, call: &ExprCall) {
if !(checker.semantic().seen_module(Modules::TRIO)
|| checker.semantic().seen_module(Modules::ANYIO))
{
return;
}
if call.arguments.len() != 1 {
return;
}
let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};
let Some(module) = AsyncModule::try_from(&qualified_name) else {
return;
};
// Determine the correct argument name
let arg_name = match module {
AsyncModule::Trio => "seconds",
AsyncModule::AnyIo => "delay",
AsyncModule::AsyncIo => return,
};
let Some(arg) = call.arguments.find_argument_value(arg_name, 0) else {
return;
};
let Expr::NumberLiteral(ExprNumberLiteral { value, .. }) = arg else {
return;
};
// TODO(ekohilas): Replace with Duration::from_days(1).as_secs(); when available.
let one_day_in_secs = 60 * 60 * 24;
match value {
Number::Int(int_value) => match int_value.as_u64() {
Some(int_value) if int_value <= one_day_in_secs => return,
_ => {} // The number is too large, and more than 24 hours
},
Number::Float(float_value) =>
{
#[expect(clippy::cast_precision_loss)]
if *float_value <= one_day_in_secs as f64 {
return;
}
}
Number::Complex { .. } => return,
}
let Some(qualified_name) = checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
else {
return;
};
let Some(module) = AsyncModule::try_from(&qualified_name) else {
return;
};
let is_relevant_module = matches!(module, AsyncModule::AnyIo | AsyncModule::Trio);
let is_sleep = is_relevant_module && matches!(qualified_name.segments(), [_, "sleep"]);
if !is_sleep {
return;
}
let mut diagnostic = checker.report_diagnostic(LongSleepNotForever { module }, call.range());
let replacement_function = "sleep_forever";
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from(&module.to_string(), replacement_function),
call.func.start(),
checker.semantic(),
)?;
let reference_edit = Edit::range_replacement(binding, call.func.range());
let arg_edit = Edit::range_replacement("()".to_string(), call.arguments.range());
Ok(Fix::unsafe_edits(import_edit, [reference_edit, arg_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_async/rules/blocking_sleep.rs | crates/ruff_linter/src/rules/flake8_async/rules/blocking_sleep.rs | use ruff_python_ast::ExprCall;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::QualifiedName;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks that async functions do not call `time.sleep`.
///
/// ## Why is this bad?
/// Blocking an async function via a `time.sleep` call will block the entire
/// event loop, preventing it from executing other tasks while waiting for the
/// `time.sleep`, negating the benefits of asynchronous programming.
///
/// Instead of `time.sleep`, use `asyncio.sleep`.
///
/// ## Example
/// ```python
/// import time
///
///
/// async def fetch():
/// time.sleep(1)
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
///
///
/// async def fetch():
/// await asyncio.sleep(1)
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct BlockingSleepInAsyncFunction;
impl Violation for BlockingSleepInAsyncFunction {
#[derive_message_formats]
fn message(&self) -> String {
"Async functions should not call `time.sleep`".to_string()
}
}
fn is_blocking_sleep(qualified_name: &QualifiedName) -> bool {
matches!(qualified_name.segments(), ["time", "sleep"])
}
/// ASYNC251
pub(crate) fn blocking_sleep(checker: &Checker, call: &ExprCall) {
if checker.semantic().in_async_context() {
if checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
.as_ref()
.is_some_and(is_blocking_sleep)
{
checker.report_diagnostic(BlockingSleepInAsyncFunction, 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_async/rules/async_busy_wait.rs | crates/ruff_linter/src/rules/flake8_async/rules/async_busy_wait.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_async::helpers::AsyncModule;
/// ## What it does
/// Checks for the use of an async sleep function in a `while` loop.
///
/// ## Why is this bad?
/// Instead of sleeping in a `while` loop, and waiting for a condition
/// to become true, it's preferable to `await` on an `Event` object such
/// as: `asyncio.Event`, `trio.Event`, or `anyio.Event`.
///
/// ## Example
/// ```python
/// import asyncio
///
/// DONE = False
///
///
/// async def func():
/// while not DONE:
/// await asyncio.sleep(1)
/// ```
///
/// Use instead:
/// ```python
/// import asyncio
///
/// DONE = asyncio.Event()
///
///
/// async def func():
/// await DONE.wait()
/// ```
///
/// ## References
/// - [`asyncio` events](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event)
/// - [`anyio` events](https://anyio.readthedocs.io/en/latest/api.html#anyio.Event)
/// - [`trio` events](https://trio.readthedocs.io/en/latest/reference-core.html#trio.Event)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct AsyncBusyWait {
module: AsyncModule,
}
impl Violation for AsyncBusyWait {
#[derive_message_formats]
fn message(&self) -> String {
let Self { module } = self;
format!("Use `{module}.Event` instead of awaiting `{module}.sleep` in a `while` loop")
}
}
/// ASYNC110
pub(crate) fn async_busy_wait(checker: &Checker, while_stmt: &ast::StmtWhile) {
// The body should be a single `await` call.
let [stmt] = while_stmt.body.as_slice() else {
return;
};
let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else {
return;
};
let Expr::Await(ast::ExprAwait { value, .. }) = value.as_ref() else {
return;
};
let Expr::Call(ast::ExprCall { func, .. }) = value.as_ref() else {
return;
};
let Some(qualified_name) = checker.semantic().resolve_qualified_name(func.as_ref()) else {
return;
};
if matches!(
qualified_name.segments(),
["trio" | "anyio", "sleep" | "sleep_until"] | ["asyncio", "sleep"]
) {
checker.report_diagnostic(
AsyncBusyWait {
module: AsyncModule::try_from(&qualified_name).unwrap(),
},
while_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_fixme/mod.rs | crates/ruff_linter/src/rules/flake8_fixme/mod.rs | pub mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::LineContainsFixme; "T001")]
#[test_case(Rule::LineContainsHack; "T002")]
#[test_case(Rule::LineContainsTodo; "T003")]
#[test_case(Rule::LineContainsXxx; "T004")]
fn rules(rule_code: Rule) -> Result<()> {
let snapshot = format!("{}_T00.py", rule_code.name());
let diagnostics = test_path(
Path::new("flake8_fixme/T00.py"),
&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_fixme/rules/todos.rs | crates/ruff_linter/src/rules/flake8_fixme/rules/todos.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
use crate::checkers::ast::LintContext;
use crate::directives::{TodoComment, TodoDirectiveKind};
/// ## What it does
/// Checks for "TODO" comments.
///
/// ## Why is this bad?
/// "TODO" comments are used to describe an issue that should be resolved
/// (usually, a missing feature, optimization, or refactoring opportunity).
///
/// Consider resolving the issue before deploying the code.
///
/// Note that if you use "TODO" comments as a form of documentation (e.g.,
/// to [provide context for future work](https://gist.github.com/dmnd/ed5d8ef8de2e4cfea174bd5dafcda382)),
/// this rule may not be appropriate for your project.
///
/// ## Example
/// ```python
/// def greet(name):
/// return f"Hello, {name}!" # TODO: Add support for custom greetings.
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.272")]
pub(crate) struct LineContainsTodo;
impl Violation for LineContainsTodo {
#[derive_message_formats]
fn message(&self) -> String {
"Line contains TODO, consider resolving the issue".to_string()
}
}
/// ## What it does
/// Checks for "FIXME" comments.
///
/// ## Why is this bad?
/// "FIXME" comments are used to describe an issue that should be resolved
/// (usually, a bug or unexpected behavior).
///
/// Consider resolving the issue before deploying the code.
///
/// Note that if you use "FIXME" comments as a form of documentation, this
/// rule may not be appropriate for your project.
///
/// ## Example
/// ```python
/// def speed(distance, time):
/// return distance / time # FIXME: Raises ZeroDivisionError for time = 0.
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.272")]
pub(crate) struct LineContainsFixme;
impl Violation for LineContainsFixme {
#[derive_message_formats]
fn message(&self) -> String {
"Line contains FIXME, consider resolving the issue".to_string()
}
}
/// ## What it does
/// Checks for "XXX" comments.
///
/// ## Why is this bad?
/// "XXX" comments are used to describe an issue that should be resolved.
///
/// Consider resolving the issue before deploying the code, or, at minimum,
/// using a more descriptive comment tag (e.g, "TODO").
///
/// ## Example
/// ```python
/// def speed(distance, time):
/// return distance / time # XXX: Raises ZeroDivisionError for time = 0.
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.272")]
pub(crate) struct LineContainsXxx;
impl Violation for LineContainsXxx {
#[derive_message_formats]
fn message(&self) -> String {
"Line contains XXX, consider resolving the issue".to_string()
}
}
/// ## What it does
/// Checks for "HACK" comments.
///
/// ## Why is this bad?
/// "HACK" comments are used to describe an issue that should be resolved
/// (usually, a suboptimal solution or temporary workaround).
///
/// Consider resolving the issue before deploying the code.
///
/// Note that if you use "HACK" comments as a form of documentation, this
/// rule may not be appropriate for your project.
///
/// ## Example
/// ```python
/// import os
///
///
/// def running_windows(): # HACK: Use platform module instead.
/// try:
/// os.mkdir("C:\\Windows\\System32\\")
/// except FileExistsError:
/// return True
/// else:
/// os.rmdir("C:\\Windows\\System32\\")
/// return False
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.272")]
pub(crate) struct LineContainsHack;
impl Violation for LineContainsHack {
#[derive_message_formats]
fn message(&self) -> String {
"Line contains HACK, consider resolving the issue".to_string()
}
}
pub(crate) fn todos(context: &LintContext, directive_ranges: &[TodoComment]) {
for TodoComment { directive, .. } in directive_ranges {
match directive.kind {
// FIX001
TodoDirectiveKind::Fixme => {
context.report_diagnostic_if_enabled(LineContainsFixme, directive.range);
}
// FIX002
TodoDirectiveKind::Hack => {
context.report_diagnostic_if_enabled(LineContainsHack, directive.range);
}
// FIX003
TodoDirectiveKind::Todo => {
context.report_diagnostic_if_enabled(LineContainsTodo, directive.range);
}
// FIX004
TodoDirectiveKind::Xxx => {
context.report_diagnostic_if_enabled(LineContainsXxx, directive.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_fixme/rules/mod.rs | crates/ruff_linter/src/rules/flake8_fixme/rules/mod.rs | pub(crate) use todos::*;
mod todos;
| 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/ruff/settings.rs | crates/ruff_linter/src/rules/ruff/settings.rs | //! Settings for the `ruff` plugin.
use crate::display_settings;
use ruff_macros::CacheKey;
use std::fmt;
#[derive(Debug, Clone, CacheKey, Default)]
pub struct Settings {
pub parenthesize_tuple_in_subscript: bool,
pub strictly_empty_init_modules: bool,
}
impl fmt::Display for Settings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.ruff",
fields = [
self.parenthesize_tuple_in_subscript,
self.strictly_empty_init_modules,
]
}
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/ruff/helpers.rs | crates/ruff_linter/src/rules/ruff/helpers.rs | use ruff_python_ast::helpers::{Truthiness, map_callable, map_subscript};
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_semantic::{BindingKind, Modules, SemanticModel, analyze};
/// Return `true` if the given [`Expr`] is a special class attribute, like `__slots__`.
///
/// While `__slots__` is typically defined via a tuple, Python accepts any iterable and, in
/// particular, allows the use of a dictionary to define the attribute names (as keys) and
/// docstrings (as values).
pub(super) fn is_special_attribute(value: &Expr) -> bool {
if let Expr::Name(ast::ExprName { id, .. }) = value {
matches!(
id.as_str(),
"__slots__" | "__dict__" | "__weakref__" | "__annotations__"
)
} else {
false
}
}
/// Returns `true` if the given [`Expr`] is a stdlib `dataclasses.field` call.
fn is_stdlib_dataclass_field(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["dataclasses", "field"]))
}
/// Returns `true` if the given [`Expr`] is a call to an `attrs` field function.
fn is_attrs_field(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["attrs", "field" | "Factory"]
// See https://github.com/python-attrs/attrs/blob/main/src/attr/__init__.py#L33
| ["attr", "ib" | "attr" | "attrib" | "field" | "Factory"]
)
})
}
/// Return `true` if `func` represents a `field()` call corresponding to the `dataclass_kind` variant passed in.
///
/// I.e., if `DataclassKind::Attrs` is passed in,
/// return `true` if `func` represents a call to `attr.ib()` or `attrs.field()`;
/// if `DataclassKind::Stdlib` is passed in,
/// return `true` if `func` represents a call to `dataclasse.field()`.
pub(super) fn is_dataclass_field(
func: &Expr,
semantic: &SemanticModel,
dataclass_kind: DataclassKind,
) -> bool {
match dataclass_kind {
DataclassKind::Attrs(..) => is_attrs_field(func, semantic),
DataclassKind::Stdlib => is_stdlib_dataclass_field(func, semantic),
}
}
/// Returns `true` if the given [`Expr`] is a `typing.ClassVar` annotation.
pub(super) fn is_class_var_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool {
if !semantic.seen_typing() {
return false;
}
// ClassVar can be used either with a subscript `ClassVar[...]` or without (the type is
// inferred).
semantic.match_typing_expr(map_subscript(annotation), "ClassVar")
}
/// Returns `true` if the given [`Expr`] is a `typing.Final` annotation.
pub(super) fn is_final_annotation(annotation: &Expr, semantic: &SemanticModel) -> bool {
if !semantic.seen_typing() {
return false;
}
// Final can be used either with a subscript `Final[...]` or without (the type is
// inferred).
semantic.match_typing_expr(map_subscript(annotation), "Final")
}
/// Values that [`attrs`'s `auto_attribs`][1] accept.
///
/// [1]: https://www.attrs.org/en/stable/api.html#attrs.define
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) enum AttrsAutoAttribs {
/// `a: str = ...` are automatically converted to fields.
True,
/// Only `attrs.field()`/`attr.ib()` calls are considered fields.
False,
/// `True` if any attributes are annotated (and no unannotated `attrs.field`s are found).
/// `False` otherwise.
None,
/// The provided value is not a literal.
Unknown,
}
/// Enumeration of various kinds of dataclasses recognised by Ruff
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) enum DataclassKind {
/// dataclasses created by the stdlib `dataclasses` module
Stdlib,
/// dataclasses created by the third-party `attrs` library
Attrs(AttrsAutoAttribs),
}
/// Return the kind of dataclass this class definition is (stdlib or `attrs`),
/// or `None` if the class is not a dataclass.
pub(super) fn dataclass_kind<'a>(
class_def: &'a ast::StmtClassDef,
semantic: &SemanticModel,
) -> Option<(DataclassKind, &'a ast::Decorator)> {
if !(semantic.seen_module(Modules::DATACLASSES) || semantic.seen_module(Modules::ATTRS)) {
return None;
}
for decorator in &class_def.decorator_list {
let Some(qualified_name) =
semantic.resolve_qualified_name(map_callable(&decorator.expression))
else {
continue;
};
match qualified_name.segments() {
["attrs" | "attr", func @ ("define" | "frozen" | "mutable")]
// See https://github.com/python-attrs/attrs/blob/main/src/attr/__init__.py#L32
| ["attr", func @ ("s" | "attributes" | "attrs")] => {
// `.define`, `.frozen` and `.mutable` all default `auto_attribs` to `None`,
// whereas `@attr.s` implicitly sets `auto_attribs=False`.
// https://www.attrs.org/en/stable/api.html#attrs.define
// https://www.attrs.org/en/stable/api-attr.html#attr.s
let Expr::Call(ExprCall { arguments, .. }) = &decorator.expression else {
let auto_attribs = if *func == "s" {
AttrsAutoAttribs::False
} else {
AttrsAutoAttribs::None
};
return Some((DataclassKind::Attrs(auto_attribs), decorator));
};
let Some(auto_attribs) = arguments.find_keyword("auto_attribs") else {
return Some((DataclassKind::Attrs(AttrsAutoAttribs::None), decorator));
};
let auto_attribs = match Truthiness::from_expr(&auto_attribs.value, |id| {
semantic.has_builtin_binding(id)
}) {
// `auto_attribs` requires an exact `True` to be true
Truthiness::True => AttrsAutoAttribs::True,
// Or an exact `None` to auto-detect.
Truthiness::None => AttrsAutoAttribs::None,
// Otherwise, anything else (even a truthy value, like `1`) is considered `False`.
Truthiness::Truthy | Truthiness::False | Truthiness::Falsey => {
AttrsAutoAttribs::False
}
// Unless, of course, we can't determine the value.
Truthiness::Unknown => AttrsAutoAttribs::Unknown,
};
return Some((DataclassKind::Attrs(auto_attribs), decorator));
}
["dataclasses", "dataclass"] => return Some((DataclassKind::Stdlib, decorator)),
_ => continue,
}
}
None
}
/// Return true if dataclass (stdlib or `attrs`) is frozen
pub(super) fn is_frozen_dataclass(
dataclass_decorator: &ast::Decorator,
semantic: &SemanticModel,
) -> bool {
let Some(qualified_name) =
semantic.resolve_qualified_name(map_callable(&dataclass_decorator.expression))
else {
return false;
};
match qualified_name.segments() {
["dataclasses", "dataclass"] => {
let Expr::Call(ExprCall { arguments, .. }) = &dataclass_decorator.expression else {
return false;
};
let Some(keyword) = arguments.find_keyword("frozen") else {
return false;
};
Truthiness::from_expr(&keyword.value, |id| semantic.has_builtin_binding(id))
.into_bool()
.unwrap_or_default()
}
["attrs" | "attr", "frozen"] => true,
_ => false,
}
}
/// Returns `true` if the given class has "default copy" semantics.
///
/// For example, Pydantic `BaseModel` and `BaseSettings` subclasses copy attribute defaults on
/// instance creation. As such, the use of mutable default values is safe for such classes.
pub(super) fn has_default_copy_semantics(
class_def: &ast::StmtClassDef,
semantic: &SemanticModel,
) -> bool {
analyze::class::any_qualified_base_class(class_def, semantic, &|qualified_name| {
matches!(
qualified_name.segments(),
[
"pydantic",
"BaseModel" | "RootModel" | "BaseSettings" | "BaseConfig"
] | ["pydantic", "generics", "GenericModel"]
| [
"pydantic",
"v1",
"BaseModel" | "BaseSettings" | "BaseConfig"
]
| ["pydantic", "v1", "generics", "GenericModel"]
| ["pydantic_settings", "BaseSettings"]
| ["msgspec", "Struct"]
| ["sqlmodel", "SQLModel"]
)
})
}
/// Returns `true` if the given function is an instantiation of a class that implements the
/// descriptor protocol.
///
/// See: <https://docs.python.org/3.10/reference/datamodel.html#descriptors>
pub(super) fn is_descriptor_class(func: &Expr, semantic: &SemanticModel) -> bool {
semantic.lookup_attribute(func).is_some_and(|id| {
let BindingKind::ClassDefinition(scope_id) = semantic.binding(id).kind else {
return false;
};
// Look for `__get__`, `__set__`, and `__delete__` methods.
["__get__", "__set__", "__delete__"].iter().any(|method| {
semantic.scopes[scope_id]
.get(method)
.is_some_and(|id| semantic.binding(id).kind.is_function_definition())
})
})
}
| 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/ruff/mod.rs | crates/ruff_linter/src/rules/ruff/mod.rs | //! Ruff-specific rules.
mod helpers;
pub(crate) mod rules;
pub mod settings;
pub(crate) mod typing;
#[cfg(test)]
mod tests {
use std::fs;
use std::path::Path;
use anyhow::Result;
use regex::Regex;
use ruff_python_ast::PythonVersion;
use ruff_source_file::SourceFileBuilder;
use rustc_hash::FxHashSet;
use test_case::test_case;
use crate::pyproject_toml::lint_pyproject_toml;
use crate::registry::Rule;
use crate::settings::LinterSettings;
use crate::settings::types::{CompiledPerFileIgnoreList, PerFileIgnore, PreviewMode};
use crate::test::{test_path, test_resource_path};
use crate::{assert_diagnostics, assert_diagnostics_diff, settings};
#[test_case(Rule::CollectionLiteralConcatenation, Path::new("RUF005.py"))]
#[test_case(Rule::CollectionLiteralConcatenation, Path::new("RUF005_slices.py"))]
#[test_case(Rule::AsyncioDanglingTask, Path::new("RUF006.py"))]
#[test_case(Rule::ZipInsteadOfPairwise, Path::new("RUF007.py"))]
#[test_case(Rule::MutableDataclassDefault, Path::new("RUF008.py"))]
#[test_case(Rule::MutableDataclassDefault, Path::new("RUF008_attrs.py"))]
#[test_case(Rule::MutableDataclassDefault, Path::new("RUF008_deferred.py"))]
#[test_case(Rule::FunctionCallInDataclassDefaultArgument, Path::new("RUF009.py"))]
#[test_case(
Rule::FunctionCallInDataclassDefaultArgument,
Path::new("RUF009_attrs.py")
)]
#[test_case(
Rule::FunctionCallInDataclassDefaultArgument,
Path::new("RUF009_attrs_auto_attribs.py")
)]
#[test_case(
Rule::FunctionCallInDataclassDefaultArgument,
Path::new("RUF009_deferred.py")
)]
#[test_case(Rule::ExplicitFStringTypeConversion, Path::new("RUF010.py"))]
#[test_case(Rule::MutableClassDefault, Path::new("RUF012.py"))]
#[test_case(Rule::MutableClassDefault, Path::new("RUF012_deferred.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_0.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_1.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_2.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_3.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_4.py"))]
#[test_case(
Rule::UnnecessaryIterableAllocationForFirstElement,
Path::new("RUF015.py")
)]
#[test_case(Rule::InvalidIndexType, Path::new("RUF016.py"))]
#[test_case(Rule::QuadraticListSummation, Path::new("RUF017_1.py"))]
#[test_case(Rule::QuadraticListSummation, Path::new("RUF017_0.py"))]
#[test_case(Rule::AssignmentInAssert, Path::new("RUF018.py"))]
#[test_case(Rule::UnnecessaryKeyCheck, Path::new("RUF019.py"))]
#[test_case(Rule::NeverUnion, Path::new("RUF020.py"))]
#[test_case(Rule::ParenthesizeChainedOperators, Path::new("RUF021.py"))]
#[test_case(Rule::UnsortedDunderAll, Path::new("RUF022.py"))]
#[test_case(Rule::UnsortedDunderSlots, Path::new("RUF023.py"))]
#[test_case(Rule::MutableFromkeysValue, Path::new("RUF024.py"))]
#[test_case(Rule::DefaultFactoryKwarg, Path::new("RUF026.py"))]
#[test_case(Rule::MissingFStringSyntax, Path::new("RUF027_0.py"))]
#[test_case(Rule::MissingFStringSyntax, Path::new("RUF027_1.py"))]
#[test_case(Rule::MissingFStringSyntax, Path::new("RUF027_2.py"))]
#[test_case(Rule::InvalidFormatterSuppressionComment, Path::new("RUF028.py"))]
#[test_case(Rule::UnusedAsync, Path::new("RUF029.py"))]
#[test_case(Rule::AssertWithPrintMessage, Path::new("RUF030.py"))]
#[test_case(Rule::IncorrectlyParenthesizedTupleInSubscript, Path::new("RUF031.py"))]
#[test_case(Rule::DecimalFromFloatLiteral, Path::new("RUF032.py"))]
#[test_case(Rule::PostInitDefault, Path::new("RUF033.py"))]
#[test_case(Rule::UselessIfElse, Path::new("RUF034.py"))]
#[test_case(Rule::NoneNotAtEndOfUnion, Path::new("RUF036.py"))]
#[test_case(Rule::NoneNotAtEndOfUnion, Path::new("RUF036.pyi"))]
#[test_case(Rule::UnnecessaryEmptyIterableWithinDequeCall, Path::new("RUF037.py"))]
#[test_case(Rule::RedundantBoolLiteral, Path::new("RUF038.py"))]
#[test_case(Rule::RedundantBoolLiteral, Path::new("RUF038.pyi"))]
#[test_case(Rule::InvalidAssertMessageLiteralArgument, Path::new("RUF040.py"))]
#[test_case(Rule::UnnecessaryNestedLiteral, Path::new("RUF041.py"))]
#[test_case(Rule::UnnecessaryNestedLiteral, Path::new("RUF041.pyi"))]
#[test_case(Rule::PytestRaisesAmbiguousPattern, Path::new("RUF043.py"))]
#[test_case(Rule::UnnecessaryCastToInt, Path::new("RUF046.py"))]
#[test_case(Rule::UnnecessaryCastToInt, Path::new("RUF046_CR.py"))]
#[test_case(Rule::UnnecessaryCastToInt, Path::new("RUF046_LF.py"))]
#[test_case(Rule::NeedlessElse, Path::new("RUF047_if.py"))]
#[test_case(Rule::NeedlessElse, Path::new("RUF047_for.py"))]
#[test_case(Rule::NeedlessElse, Path::new("RUF047_while.py"))]
#[test_case(Rule::NeedlessElse, Path::new("RUF047_try.py"))]
#[test_case(Rule::MapIntVersionParsing, Path::new("RUF048.py"))]
#[test_case(Rule::MapIntVersionParsing, Path::new("RUF048_1.py"))]
#[test_case(Rule::DataclassEnum, Path::new("RUF049.py"))]
#[test_case(Rule::IfKeyInDictDel, Path::new("RUF051.py"))]
#[test_case(Rule::UsedDummyVariable, Path::new("RUF052_0.py"))]
#[test_case(Rule::UsedDummyVariable, Path::new("RUF052_1.py"))]
#[test_case(Rule::ClassWithMixedTypeVars, Path::new("RUF053.py"))]
#[test_case(Rule::FalsyDictGetFallback, Path::new("RUF056.py"))]
#[test_case(Rule::UnnecessaryRound, Path::new("RUF057.py"))]
#[test_case(Rule::StarmapZip, Path::new("RUF058_0.py"))]
#[test_case(Rule::StarmapZip, Path::new("RUF058_1.py"))]
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_0.py"))]
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_1.py"))]
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_2.py"))]
#[test_case(Rule::UnusedUnpackedVariable, Path::new("RUF059_3.py"))]
#[test_case(Rule::InEmptyCollection, Path::new("RUF060.py"))]
#[test_case(Rule::LegacyFormPytestRaises, Path::new("RUF061_raises.py"))]
#[test_case(Rule::LegacyFormPytestRaises, Path::new("RUF061_warns.py"))]
#[test_case(Rule::LegacyFormPytestRaises, Path::new("RUF061_deprecated_call.py"))]
#[test_case(Rule::NonOctalPermissions, Path::new("RUF064.py"))]
#[test_case(Rule::LoggingEagerConversion, Path::new("RUF065_0.py"))]
#[test_case(Rule::LoggingEagerConversion, Path::new("RUF065_1.py"))]
#[test_case(Rule::PropertyWithoutReturn, Path::new("RUF066.py"))]
#[test_case(Rule::RedirectedNOQA, Path::new("RUF101_0.py"))]
#[test_case(Rule::RedirectedNOQA, Path::new("RUF101_1.py"))]
#[test_case(Rule::InvalidRuleCode, Path::new("RUF102.py"))]
#[test_case(Rule::NonEmptyInitModule, Path::new("RUF067/modules/__init__.py"))]
#[test_case(Rule::NonEmptyInitModule, Path::new("RUF067/modules/okay.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("ruff").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn prefer_parentheses_getitem_tuple() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF031_prefer_parens.py"),
&LinterSettings {
ruff: super::settings::Settings {
parenthesize_tuple_in_subscript: true,
..super::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::IncorrectlyParenthesizedTupleInSubscript)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn no_remove_parentheses_starred_expr_py310() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF031.py"),
&LinterSettings {
ruff: super::settings::Settings {
parenthesize_tuple_in_subscript: false,
..super::settings::Settings::default()
},
unresolved_target_version: PythonVersion::PY310.into(),
..LinterSettings::for_rule(Rule::IncorrectlyParenthesizedTupleInSubscript)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test_case(Path::new("RUF013_0.py"))]
#[test_case(Path::new("RUF013_1.py"))]
fn implicit_optional_py39(path: &Path) -> Result<()> {
let snapshot = format!(
"PY39_{}_{}",
Rule::ImplicitOptional.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("ruff").join(path).as_path(),
&settings::LinterSettings::for_rule(Rule::ImplicitOptional)
.with_target_version(PythonVersion::PY39),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn access_annotations_from_class_dict_py39_no_typing_extensions() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF063.py"),
&LinterSettings {
typing_extensions: false,
unresolved_target_version: PythonVersion::PY39.into(),
..LinterSettings::for_rule(Rule::AccessAnnotationsFromClassDict)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn access_annotations_from_class_dict_py39_with_typing_extensions() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF063.py"),
&LinterSettings {
typing_extensions: true,
unresolved_target_version: PythonVersion::PY39.into(),
..LinterSettings::for_rule(Rule::AccessAnnotationsFromClassDict)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn access_annotations_from_class_dict_py310() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF063.py"),
&LinterSettings {
unresolved_target_version: PythonVersion::PY310.into(),
..LinterSettings::for_rule(Rule::AccessAnnotationsFromClassDict)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn access_annotations_from_class_dict_py314() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF063.py"),
&LinterSettings {
unresolved_target_version: PythonVersion::PY314.into(),
..LinterSettings::for_rule(Rule::AccessAnnotationsFromClassDict)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn confusables() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/confusables.py"),
&settings::LinterSettings {
allowed_confusables: FxHashSet::from_iter(['−', 'ρ', '∗']),
..settings::LinterSettings::for_rules(vec![
Rule::AmbiguousUnicodeCharacterString,
Rule::AmbiguousUnicodeCharacterDocstring,
Rule::AmbiguousUnicodeCharacterComment,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn confusables_deferred_annotations_diff() -> Result<()> {
assert_diagnostics_diff!(
Path::new("ruff/confusables.py"),
&LinterSettings {
unresolved_target_version: PythonVersion::PY313.into(),
allowed_confusables: FxHashSet::from_iter(['−', 'ρ', '∗']),
..settings::LinterSettings::for_rules(vec![
Rule::AmbiguousUnicodeCharacterString,
Rule::AmbiguousUnicodeCharacterDocstring,
Rule::AmbiguousUnicodeCharacterComment,
])
},
&LinterSettings {
unresolved_target_version: PythonVersion::PY314.into(),
allowed_confusables: FxHashSet::from_iter(['−', 'ρ', '∗']),
..settings::LinterSettings::for_rules(vec![
Rule::AmbiguousUnicodeCharacterString,
Rule::AmbiguousUnicodeCharacterDocstring,
Rule::AmbiguousUnicodeCharacterComment,
])
},
);
Ok(())
}
#[test]
fn preview_confusables() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/confusables.py"),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
allowed_confusables: FxHashSet::from_iter(['−', 'ρ', '∗']),
..settings::LinterSettings::for_rules(vec![
Rule::AmbiguousUnicodeCharacterString,
Rule::AmbiguousUnicodeCharacterDocstring,
Rule::AmbiguousUnicodeCharacterComment,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn noqa() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/noqa.py"),
&settings::LinterSettings::for_rules(vec![
Rule::UnusedVariable,
Rule::AmbiguousVariableName,
]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn range_suppressions() -> Result<()> {
assert_diagnostics_diff!(
Path::new("ruff/suppressions.py"),
&settings::LinterSettings::for_rules(vec![
Rule::UnusedVariable,
Rule::AmbiguousVariableName,
Rule::UnusedNOQA,
Rule::InvalidRuleCode,
Rule::InvalidSuppressionComment,
Rule::UnmatchedSuppressionComment,
])
.with_external_rules(&["TK421"]),
&settings::LinterSettings::for_rules(vec![
Rule::UnusedVariable,
Rule::AmbiguousVariableName,
Rule::UnusedNOQA,
Rule::InvalidRuleCode,
Rule::InvalidSuppressionComment,
Rule::UnmatchedSuppressionComment,
])
.with_external_rules(&["TK421"])
.with_preview_mode(),
);
Ok(())
}
#[test]
fn ruf100_0() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_0.py"),
&settings::LinterSettings {
external: vec!["V101".to_string()],
..settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::LineTooLong,
Rule::UnusedImport,
Rule::UnusedVariable,
Rule::TabIndentation,
Rule::YodaConditions,
Rule::SuspiciousEvalUsage,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruf100_0_prefix() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_0.py"),
&settings::LinterSettings {
external: vec!["V".to_string()],
..settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::LineTooLong,
Rule::UnusedImport,
Rule::UnusedVariable,
Rule::TabIndentation,
Rule::YodaConditions,
Rule::SuspiciousEvalUsage,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruf100_1() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_1.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedNOQA, Rule::UnusedImport]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruf100_2() -> Result<()> {
let mut settings =
settings::LinterSettings::for_rules(vec![Rule::UnusedNOQA, Rule::UnusedImport]);
settings.per_file_ignores = CompiledPerFileIgnoreList::resolve(vec![PerFileIgnore::new(
"RUF100_2.py".to_string(),
&["F401".parse().unwrap()],
None,
)])
.unwrap();
let diagnostics = test_path(Path::new("ruff/RUF100_2.py"), &settings)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruf100_3() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_3.py"),
&settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::LineTooLong,
Rule::UndefinedName,
]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruf100_4() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_4.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedNOQA, Rule::UnusedImport]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruf100_5() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_5.py"),
&settings::LinterSettings {
..settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::LineTooLong,
Rule::CommentedOutCode,
])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_noqa_filedirective_unused() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_6.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedNOQA]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_noqa_filedirective_unused_last_of_many() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF100_7.py"),
&settings::LinterSettings::for_rules(vec![
Rule::UnusedNOQA,
Rule::FStringMissingPlaceholders,
Rule::LineTooLong,
Rule::UnusedVariable,
]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn invalid_rule_code_external_rules() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/RUF102.py"),
&settings::LinterSettings {
external: vec!["V".to_string()],
..settings::LinterSettings::for_rule(Rule::InvalidRuleCode)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_per_file_ignores() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/ruff_per_file_ignores.py"),
&settings::LinterSettings {
per_file_ignores: CompiledPerFileIgnoreList::resolve(vec![PerFileIgnore::new(
"ruff_per_file_ignores.py".to_string(),
&["F401".parse().unwrap(), "RUF100".parse().unwrap()],
None,
)])
.unwrap(),
..settings::LinterSettings::for_rules(vec![Rule::UnusedImport, Rule::UnusedNOQA])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_per_file_ignores_empty() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/ruff_per_file_ignores.py"),
&settings::LinterSettings {
per_file_ignores: CompiledPerFileIgnoreList::resolve(vec![PerFileIgnore::new(
"ruff_per_file_ignores.py".to_string(),
&["RUF100".parse().unwrap()],
None,
)])
.unwrap(),
..settings::LinterSettings::for_rules(vec![Rule::UnusedNOQA])
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn flake8_noqa() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/flake8_noqa.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedImport, Rule::UnusedVariable]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_noqa_all() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/ruff_noqa_all.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedImport, Rule::UnusedVariable]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_noqa_codes() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/ruff_noqa_codes.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedImport, Rule::UnusedVariable]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn ruff_noqa_invalid() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/ruff_noqa_invalid.py"),
&settings::LinterSettings::for_rules(vec![Rule::UnusedImport, Rule::UnusedVariable]),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn redirects() -> Result<()> {
let diagnostics = test_path(
Path::new("ruff/redirects.py"),
&settings::LinterSettings::for_rule(Rule::NonPEP604AnnotationUnion),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test_case(Rule::InvalidPyprojectToml, Path::new("bleach"))]
#[test_case(Rule::InvalidPyprojectToml, Path::new("invalid_author"))]
#[test_case(Rule::InvalidPyprojectToml, Path::new("maturin"))]
#[test_case(Rule::InvalidPyprojectToml, Path::new("various_invalid"))]
#[test_case(Rule::InvalidPyprojectToml, Path::new("pep639"))]
fn invalid_pyproject_toml(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let path = test_resource_path("fixtures")
.join("ruff")
.join("pyproject_toml")
.join(path)
.join("pyproject.toml");
let contents = fs::read_to_string(path)?;
let source_file = SourceFileBuilder::new("pyproject.toml", contents).finish();
let messages = lint_pyproject_toml(
&source_file,
&settings::LinterSettings::for_rule(Rule::InvalidPyprojectToml),
);
assert_diagnostics!(snapshot, messages);
Ok(())
}
#[test_case(Rule::UnrawRePattern, Path::new("RUF039.py"))]
#[test_case(Rule::UnrawRePattern, Path::new("RUF039_concat.py"))]
#[test_case(Rule::UnnecessaryRegularExpression, Path::new("RUF055_0.py"))]
#[test_case(Rule::UnnecessaryRegularExpression, Path::new("RUF055_1.py"))]
#[test_case(Rule::UnnecessaryRegularExpression, Path::new("RUF055_2.py"))]
#[test_case(Rule::UnnecessaryRegularExpression, Path::new("RUF055_3.py"))]
#[test_case(Rule::IndentedFormFeed, Path::new("RUF054.py"))]
#[test_case(Rule::ImplicitClassVarInDataclass, Path::new("RUF045.py"))]
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("ruff").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::UnrawRePattern, Path::new("RUF039_py_version_sensitive.py"))]
fn preview_rules_py37(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"preview__py37__{}_{}",
rule_code.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("ruff").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
unresolved_target_version: PythonVersion::PY37.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::UnrawRePattern, Path::new("RUF039_py_version_sensitive.py"))]
fn preview_rules_py38(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"preview__py38__{}_{}",
rule_code.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("ruff").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
unresolved_target_version: PythonVersion::PY38.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::UsedDummyVariable, Path::new("RUF052_0.py"), r"^_+", 1)]
#[test_case(Rule::UsedDummyVariable, Path::new("RUF052_0.py"), r"", 2)]
fn custom_regexp_preset(
rule_code: Rule,
path: &Path,
regex_pattern: &str,
id: u8,
) -> Result<()> {
// Compile the regex from the pattern string
let regex = Regex::new(regex_pattern).unwrap();
let snapshot = format!(
"custom_dummy_var_regexp_preset__{}_{}_{}",
rule_code.noqa_code(),
path.to_string_lossy(),
id,
);
let diagnostics = test_path(
Path::new("ruff").join(path).as_path(),
&settings::LinterSettings {
dummy_variable_rgx: regex,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::StarmapZip, Path::new("RUF058_2.py"))]
fn map_strict_py314(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"py314__{}_{}",
rule_code.noqa_code(),
path.to_string_lossy()
);
let diagnostics = test_path(
Path::new("ruff").join(path).as_path(),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY314.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_0.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_1.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_2.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_3.py"))]
#[test_case(Rule::ImplicitOptional, Path::new("RUF013_4.py"))]
fn ruf013_add_future_import(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("add_future_import_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("ruff").join(path).as_path(),
&settings::LinterSettings {
future_annotations: true,
unresolved_target_version: PythonVersion::PY39.into(),
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn strictly_empty_init_modules_ruf067() -> Result<()> {
assert_diagnostics_diff!(
Path::new("ruff/RUF067/modules/__init__.py"),
&LinterSettings {
ruff: super::settings::Settings {
strictly_empty_init_modules: false,
..super::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::NonEmptyInitModule)
},
&LinterSettings {
ruff: super::settings::Settings {
strictly_empty_init_modules: true,
..super::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::NonEmptyInitModule)
},
);
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/ruff/typing.rs | crates/ruff_linter/src/rules/ruff/typing.rs | use itertools::Either::{Left, Right};
use ruff_python_ast::name::QualifiedName;
use ruff_python_ast::{self as ast, Expr, Operator};
use ruff_python_stdlib::sys::is_known_standard_library;
use crate::checkers::ast::Checker;
/// Returns `true` if the given qualified name is a known type.
///
/// A known type is either a builtin type, any object from the standard library,
/// or a type from the `typing_extensions` module.
fn is_known_type(qualified_name: &QualifiedName, version: ast::PythonVersion) -> bool {
match qualified_name.segments() {
["" | "typing_extensions", ..] => true,
[module, ..] => is_known_standard_library(version.minor, module),
_ => false,
}
}
/// Returns an iterator over the expressions in a slice. If the slice is not a
/// tuple, the iterator will only yield the slice.
fn resolve_slice_value(slice: &Expr) -> impl Iterator<Item = &Expr> {
match slice {
Expr::Tuple(tuple) => Left(tuple.iter()),
_ => Right(std::iter::once(slice)),
}
}
#[derive(Debug)]
enum TypingTarget<'a> {
/// Literal `None` type.
None,
/// A `typing.Any` type.
Any,
/// Literal `object` type.
Object,
/// Forward reference to a type e.g., `"List[str]"`.
ForwardReference(&'a Expr),
/// A `typing.Union` type e.g., `Union[int, str]`.
Union(Option<&'a Expr>),
/// A PEP 604 union type e.g., `int | str`.
PEP604Union(&'a Expr, &'a Expr),
/// A `typing.Literal` type e.g., `Literal[1, 2, 3]`.
Literal(Option<&'a Expr>),
/// A `typing.Optional` type e.g., `Optional[int]`.
Optional(Option<&'a Expr>),
/// A `typing.Annotated` type e.g., `Annotated[int, ...]`.
Annotated(Option<&'a Expr>),
/// The `typing.Hashable` type.
Hashable,
/// Special type used to represent an unknown type (and not a typing target)
/// which could be a type alias.
Unknown,
/// Special type used to represent a known type (and not a typing target).
/// A known type is either a builtin type, any object from the standard
/// library, or a type from the `typing_extensions` module.
Known,
}
impl<'a> TypingTarget<'a> {
fn try_from_expr(
expr: &'a Expr,
checker: &'a Checker,
version: ast::PythonVersion,
) -> Option<Self> {
let semantic = checker.semantic();
match expr {
Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => {
semantic.resolve_qualified_name(value).map_or(
// If we can't resolve the call path, it must be defined
// in the same file and could be a type alias.
Some(TypingTarget::Unknown),
|qualified_name| {
if semantic.match_typing_qualified_name(&qualified_name, "Optional") {
Some(TypingTarget::Optional(Some(slice.as_ref())))
} else if semantic.match_typing_qualified_name(&qualified_name, "Literal") {
Some(TypingTarget::Literal(Some(slice.as_ref())))
} else if semantic.match_typing_qualified_name(&qualified_name, "Union") {
Some(TypingTarget::Union(Some(slice.as_ref())))
} else if semantic.match_typing_qualified_name(&qualified_name, "Annotated")
{
Some(TypingTarget::Annotated(
resolve_slice_value(slice.as_ref()).next(),
))
} else {
if is_known_type(&qualified_name, version) {
Some(TypingTarget::Known)
} else {
Some(TypingTarget::Unknown)
}
}
},
)
}
Expr::BinOp(ast::ExprBinOp {
left,
op: Operator::BitOr,
right,
..
}) => Some(TypingTarget::PEP604Union(left, right)),
Expr::NoneLiteral(_) => Some(TypingTarget::None),
Expr::StringLiteral(string_expr) => checker
.parse_type_annotation(string_expr)
.ok()
.map(|parsed_annotation| {
TypingTarget::ForwardReference(parsed_annotation.expression())
}),
_ => semantic.resolve_qualified_name(expr).map_or(
// If we can't resolve the call path, it must be defined in the
// same file, so we assume it's `Any` as it could be a type alias.
Some(TypingTarget::Unknown),
|qualified_name| {
if semantic.match_typing_qualified_name(&qualified_name, "Optional") {
Some(TypingTarget::Optional(None))
} else if semantic.match_typing_qualified_name(&qualified_name, "Literal") {
Some(TypingTarget::Literal(None))
} else if semantic.match_typing_qualified_name(&qualified_name, "Union") {
Some(TypingTarget::Union(None))
} else if semantic.match_typing_qualified_name(&qualified_name, "Annotated") {
Some(TypingTarget::Annotated(None))
} else if semantic.match_typing_qualified_name(&qualified_name, "Any") {
Some(TypingTarget::Any)
} else if matches!(qualified_name.segments(), ["" | "builtins", "object"]) {
Some(TypingTarget::Object)
} else if semantic.match_typing_qualified_name(&qualified_name, "Hashable")
|| matches!(
qualified_name.segments(),
["collections", "abc", "Hashable"]
)
{
Some(TypingTarget::Hashable)
} else if !is_known_type(&qualified_name, version) {
// If it's not a known type, we assume it's `Any`.
Some(TypingTarget::Unknown)
} else {
Some(TypingTarget::Known)
}
},
),
}
}
/// Check if the [`TypingTarget`] explicitly allows `None`.
fn contains_none(&self, checker: &Checker, version: ast::PythonVersion) -> bool {
match self {
TypingTarget::None
| TypingTarget::Optional(_)
| TypingTarget::Hashable
| TypingTarget::Any
| TypingTarget::Object
| TypingTarget::Unknown => true,
TypingTarget::Known => false,
TypingTarget::Literal(slice) => slice.is_some_and(|slice| {
resolve_slice_value(slice).any(|element| {
// Literal can only contain `None`, a literal value, other `Literal`
// or an enum value.
match TypingTarget::try_from_expr(element, checker, version) {
None | Some(TypingTarget::None) => true,
Some(new_target @ TypingTarget::Literal(_)) => {
new_target.contains_none(checker, version)
}
_ => false,
}
})
}),
TypingTarget::Union(slice) => slice.is_some_and(|slice| {
resolve_slice_value(slice).any(|element| {
TypingTarget::try_from_expr(element, checker, version)
.is_none_or(|new_target| new_target.contains_none(checker, version))
})
}),
TypingTarget::PEP604Union(left, right) => [left, right].iter().any(|element| {
TypingTarget::try_from_expr(element, checker, version)
.is_none_or(|new_target| new_target.contains_none(checker, version))
}),
TypingTarget::Annotated(expr) => expr.is_some_and(|expr| {
TypingTarget::try_from_expr(expr, checker, version)
.is_none_or(|new_target| new_target.contains_none(checker, version))
}),
TypingTarget::ForwardReference(expr) => {
TypingTarget::try_from_expr(expr, checker, version)
.is_none_or(|new_target| new_target.contains_none(checker, version))
}
}
}
/// Check if the [`TypingTarget`] explicitly allows `Any`.
fn contains_any(&self, checker: &Checker, version: ast::PythonVersion) -> bool {
match self {
TypingTarget::Any => true,
// `Literal` cannot contain `Any` as it's a dynamic value.
TypingTarget::Literal(_)
| TypingTarget::None
| TypingTarget::Hashable
| TypingTarget::Object
| TypingTarget::Known
| TypingTarget::Unknown => false,
TypingTarget::Union(slice) => slice.is_some_and(|slice| {
resolve_slice_value(slice).any(|element| {
TypingTarget::try_from_expr(element, checker, version)
.is_none_or(|new_target| new_target.contains_any(checker, version))
})
}),
TypingTarget::PEP604Union(left, right) => [left, right].iter().any(|element| {
TypingTarget::try_from_expr(element, checker, version)
.is_none_or(|new_target| new_target.contains_any(checker, version))
}),
TypingTarget::Annotated(expr) | TypingTarget::Optional(expr) => {
expr.is_some_and(|expr| {
TypingTarget::try_from_expr(expr, checker, version)
.is_none_or(|new_target| new_target.contains_any(checker, version))
})
}
TypingTarget::ForwardReference(expr) => {
TypingTarget::try_from_expr(expr, checker, version)
.is_none_or(|new_target| new_target.contains_any(checker, version))
}
}
}
}
/// Check if the given annotation [`Expr`] explicitly allows `None`.
///
/// This function will return `None` if the annotation explicitly allows `None`
/// otherwise it will return the annotation itself. If it's a `Annotated` type,
/// then the inner type will be checked.
///
/// This function assumes that the annotation is a valid typing annotation expression.
pub(crate) fn type_hint_explicitly_allows_none<'a>(
annotation: &'a Expr,
checker: &'a Checker,
version: ast::PythonVersion,
) -> Option<&'a Expr> {
match TypingTarget::try_from_expr(annotation, checker, version) {
None |
// Short circuit on top level `None`, `Any` or `Optional`
Some(TypingTarget::None | TypingTarget::Optional(_) | TypingTarget::Any) => None,
// Top-level `Annotated` node should check for the inner type and
// return the inner type if it doesn't allow `None`. If `Annotated`
// is found nested inside another type, then the outer type should
// be returned.
Some(TypingTarget::Annotated(expr)) => {
expr.and_then(|expr| type_hint_explicitly_allows_none(expr, checker, version))
}
Some(target) => {
if target.contains_none(checker, version) {
return None;
}
Some(annotation)
}
}
}
/// Check if the given annotation [`Expr`] resolves to `Any`.
///
/// This function assumes that the annotation is a valid typing annotation expression.
pub(crate) fn type_hint_resolves_to_any(
annotation: &Expr,
checker: &Checker,
version: ast::PythonVersion,
) -> bool {
match TypingTarget::try_from_expr(annotation, checker, version) {
// Short circuit on top level `Any`
None | Some(TypingTarget::Any) => true,
// `Optional` is `Optional[Any]` which is `Any | None`.
Some(TypingTarget::Optional(None)) => true,
// Top-level `Annotated` node should check if the inner type resolves
// to `Any`.
Some(TypingTarget::Annotated(expr)) => {
expr.is_some_and(|expr| type_hint_resolves_to_any(expr, checker, version))
}
Some(target) => target.contains_any(checker, version),
}
}
#[cfg(test)]
mod tests {
use super::is_known_type;
use ruff_python_ast as ast;
use ruff_python_ast::name::QualifiedName;
#[test]
fn test_is_known_type() {
assert!(is_known_type(
&QualifiedName::builtin("int"),
ast::PythonVersion::PY311
));
assert!(is_known_type(
&QualifiedName::from_iter(["builtins", "int"]),
ast::PythonVersion::PY311
));
assert!(is_known_type(
&QualifiedName::from_iter(["typing", "Optional"]),
ast::PythonVersion::PY311
));
assert!(is_known_type(
&QualifiedName::from_iter(["typing_extensions", "Literal"]),
ast::PythonVersion::PY311
));
assert!(is_known_type(
&QualifiedName::from_iter(["zoneinfo", "ZoneInfo"]),
ast::PythonVersion::PY311
));
assert!(!is_known_type(
&QualifiedName::from_iter(["zoneinfo", "ZoneInfo"]),
ast::PythonVersion::PY38
));
}
}
| 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/ruff/rules/decimal_from_float_literal.rs | crates/ruff_linter/src/rules/ruff/rules/decimal_from_float_literal.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_codegen::Stylist;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for `Decimal` calls passing a float literal.
///
/// ## Why is this bad?
/// Float literals have limited precision that can lead to unexpected results.
/// The `Decimal` class is designed to handle numbers with fixed-point precision,
/// so a string literal should be used instead.
///
/// ## Example
///
/// ```python
/// num = Decimal(1.2345)
/// ```
///
/// Use instead:
/// ```python
/// num = Decimal("1.2345")
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe because it changes the underlying value
/// of the `Decimal` instance that is constructed. This can lead to unexpected
/// behavior if your program relies on the previous value (whether deliberately or not).
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.9.0")]
pub(crate) struct DecimalFromFloatLiteral;
impl AlwaysFixableViolation for DecimalFromFloatLiteral {
#[derive_message_formats]
fn message(&self) -> String {
"`Decimal()` called with float literal argument".to_string()
}
fn fix_title(&self) -> String {
"Replace with string literal".to_string()
}
}
/// RUF032: `Decimal()` called with float literal argument
pub(crate) fn decimal_from_float_literal_syntax(checker: &Checker, call: &ast::ExprCall) {
let Some(arg) = call.arguments.args.first() else {
return;
};
if let Some(float) = extract_float_literal(arg, Sign::Positive) {
if checker
.semantic()
.resolve_qualified_name(call.func.as_ref())
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["decimal", "Decimal"])
})
{
checker
.report_diagnostic(DecimalFromFloatLiteral, arg.range())
.set_fix(fix_float_literal(
arg.range(),
float,
checker.locator(),
checker.stylist(),
));
}
}
}
#[derive(Debug, Clone, Copy)]
enum Sign {
Positive,
Negative,
}
impl Sign {
const fn as_str(self) -> &'static str {
match self {
Self::Positive => "",
Self::Negative => "-",
}
}
const fn flip(self) -> Self {
match self {
Self::Negative => Self::Positive,
Self::Positive => Self::Negative,
}
}
}
impl fmt::Display for Sign {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Copy, Clone)]
struct Float {
/// The range of the float excluding the sign.
/// E.g. for `+--+-+-4.3`, this will be the range of `4.3`
value_range: TextRange,
/// The resolved sign of the float (either `-` or `+`)
sign: Sign,
}
fn extract_float_literal(arg: &ast::Expr, sign: Sign) -> Option<Float> {
match arg {
ast::Expr::NumberLiteral(number_literal_expr) if number_literal_expr.value.is_float() => {
Some(Float {
value_range: arg.range(),
sign,
})
}
ast::Expr::UnaryOp(ast::ExprUnaryOp {
operand,
op: ast::UnaryOp::UAdd,
..
}) => extract_float_literal(operand, sign),
ast::Expr::UnaryOp(ast::ExprUnaryOp {
operand,
op: ast::UnaryOp::USub,
..
}) => extract_float_literal(operand, sign.flip()),
_ => None,
}
}
fn fix_float_literal(
original_range: TextRange,
float: Float,
locator: &Locator,
stylist: &Stylist,
) -> Fix {
let quote = stylist.quote();
let Float { value_range, sign } = float;
let float_value = locator.slice(value_range);
let content = format!("{quote}{sign}{float_value}{quote}");
Fix::unsafe_edit(Edit::range_replacement(content, original_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/ruff/rules/zip_instead_of_pairwise.rs | crates/ruff_linter/src/rules/ruff/rules/zip_instead_of_pairwise.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Arguments, Expr, Int};
use ruff_text_size::Ranged;
use crate::{Edit, Fix, FixAvailability, Violation};
use crate::{checkers::ast::Checker, importer::ImportRequest};
/// ## What it does
/// Checks for use of `zip()` to iterate over successive pairs of elements.
///
/// ## Why is this bad?
/// When iterating over successive pairs of elements, prefer
/// `itertools.pairwise()` over `zip()`.
///
/// `itertools.pairwise()` is more readable and conveys the intent of the code
/// more clearly.
///
/// ## Example
/// ```python
/// letters = "ABCD"
/// zip(letters, letters[1:]) # ("A", "B"), ("B", "C"), ("C", "D")
/// ```
///
/// Use instead:
/// ```python
/// from itertools import pairwise
///
/// letters = "ABCD"
/// pairwise(letters) # ("A", "B"), ("B", "C"), ("C", "D")
/// ```
///
/// ## Fix safety
///
/// The fix is always marked unsafe because it assumes that slicing an object
/// (e.g., `obj[1:]`) produces a value with the same type and iteration behavior
/// as the original object, which is not guaranteed for user-defined types that
/// override `__getitem__` without properly handling slices. Moreover, the fix
/// could delete comments.
///
/// ## References
/// - [Python documentation: `itertools.pairwise`](https://docs.python.org/3/library/itertools.html#itertools.pairwise)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.257")]
pub(crate) struct ZipInsteadOfPairwise;
impl Violation for ZipInsteadOfPairwise {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `itertools.pairwise()` over `zip()` when iterating over successive pairs"
.to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace `zip()` with `itertools.pairwise()`".to_string())
}
}
#[derive(Debug)]
struct SliceInfo {
id: String,
slice_start: Option<i32>,
}
/// Return the argument name, lower bound, and upper bound for an expression, if it's a slice.
fn match_slice_info(expr: &Expr) -> Option<SliceInfo> {
let Expr::Subscript(ast::ExprSubscript { value, slice, .. }) = expr else {
return None;
};
let Expr::Name(ast::ExprName { id, .. }) = value.as_ref() else {
return None;
};
let Expr::Slice(ast::ExprSlice { lower, step, .. }) = slice.as_ref() else {
return None;
};
// Avoid false positives for slices with a step.
if let Some(step) = step {
if !matches!(
step.as_ref(),
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(Int::ONE),
..
})
) {
return None;
}
}
// If the slice start is a non-constant, we can't be sure that it's successive.
let slice_start = if let Some(lower) = lower.as_ref() {
let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(int),
range: _,
node_index: _,
}) = lower.as_ref()
else {
return None;
};
Some(int.as_i32()?)
} else {
None
};
Some(SliceInfo {
id: id.to_string(),
slice_start,
})
}
/// RUF007
pub(crate) fn zip_instead_of_pairwise(checker: &Checker, call: &ast::ExprCall) {
let ast::ExprCall {
func,
arguments: Arguments { args, .. },
..
} = call;
// Require exactly two positional arguments.
let [first, second] = args.as_ref() else {
return;
};
// Require second argument to be a `Subscript`.
if !second.is_subscript_expr() {
return;
}
// Require the function to be the builtin `zip`.
if !checker.semantic().match_builtin_expr(func, "zip") {
return;
}
// Allow the first argument to be a `Name` or `Subscript`.
let Some(first_arg_info) = ({
if let Expr::Name(ast::ExprName { id, .. }) = first {
Some(SliceInfo {
id: id.to_string(),
slice_start: None,
})
} else {
match_slice_info(first)
}
}) else {
return;
};
let Some(second_arg_info) = match_slice_info(second) else {
return;
};
// Verify that the arguments match the same name.
if first_arg_info.id != second_arg_info.id {
return;
}
// Verify that the arguments are successive.
if second_arg_info.slice_start.unwrap_or(0) - first_arg_info.slice_start.unwrap_or(0) != 1 {
return;
}
let mut diagnostic = checker.report_diagnostic(ZipInsteadOfPairwise, func.range());
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("itertools", "pairwise"),
func.start(),
checker.semantic(),
)?;
let reference_edit =
Edit::range_replacement(format!("{binding}({})", first_arg_info.id), call.range());
Ok(Fix::unsafe_edits(import_edit, [reference_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/ruff/rules/unnecessary_iterable_allocation_for_first_element.rs | crates/ruff_linter/src/rules/ruff/rules/unnecessary_iterable_allocation_for_first_element.rs | use std::borrow::Cow;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Arguments, Comprehension, Expr, Int};
use ruff_python_semantic::SemanticModel;
use ruff_python_stdlib::builtins::is_iterator;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks the following constructs, all of which can be replaced by
/// `next(iter(...))`:
///
/// - `list(...)[0]`
/// - `tuple(...)[0]`
/// - `list(i for i in ...)[0]`
/// - `[i for i in ...][0]`
/// - `list(...).pop(0)`
///
/// ## Why is this bad?
/// Calling e.g. `list(...)` will create a new list of the entire collection,
/// which can be very expensive for large collections. If you only need the
/// first element of the collection, you can use `next(...)` or
/// `next(iter(...)` to lazily fetch the first element. The same is true for
/// the other constructs.
///
/// ## Example
/// ```python
/// head = list(x)[0]
/// head = [x * x for x in range(10)][0]
/// ```
///
/// Use instead:
/// ```python
/// head = next(iter(x))
/// head = next(x * x for x in range(10))
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as migrating from (e.g.) `list(...)[0]`
/// to `next(iter(...))` can change the behavior of your program in two ways:
///
/// 1. First, all above-mentioned constructs will eagerly evaluate the entire
/// collection, while `next(iter(...))` will only evaluate the first
/// element. As such, any side effects that occur during iteration will be
/// delayed.
/// 2. Second, accessing members of a collection via square bracket notation
/// `[0]` or the `pop()` function will raise `IndexError` if the collection
/// is empty, while `next(iter(...))` will raise `StopIteration`.
///
/// ## References
/// - [Iterators and Iterables in Python: Run Efficient Iterations](https://realpython.com/python-iterators-iterables/#when-to-use-an-iterator-in-python)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.278")]
pub(crate) struct UnnecessaryIterableAllocationForFirstElement {
iterable: SourceCodeSnippet,
}
impl AlwaysFixableViolation for UnnecessaryIterableAllocationForFirstElement {
#[derive_message_formats]
fn message(&self) -> String {
let iterable = &self.iterable.truncated_display();
format!("Prefer `next({iterable})` over single element slice")
}
fn fix_title(&self) -> String {
let iterable = &self.iterable.truncated_display();
format!("Replace with `next({iterable})`")
}
}
/// RUF015
pub(crate) fn unnecessary_iterable_allocation_for_first_element(checker: &Checker, expr: &Expr) {
let value = match expr {
// Ex) `list(x)[0]`
Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => {
if !is_zero(slice) {
return;
}
value
}
// Ex) `list(x).pop(0)`
Expr::Call(ast::ExprCall {
func, arguments, ..
}) => {
if !arguments.keywords.is_empty() {
return;
}
let [arg] = arguments.args.as_ref() else {
return;
};
if !is_zero(arg) {
return;
}
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else {
return;
};
if !matches!(attr.as_str(), "pop") {
return;
}
value
}
_ => return,
};
let Some(target) = match_iteration_target(value, checker.semantic()) else {
return;
};
let iterable = checker.locator().slice(target.range);
let iterable = if target.iterable {
Cow::Borrowed(iterable)
} else {
Cow::Owned(format!("iter({iterable})"))
};
let mut diagnostic = checker.report_diagnostic(
UnnecessaryIterableAllocationForFirstElement {
iterable: SourceCodeSnippet::new(iterable.to_string()),
},
expr.range(),
);
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("next({iterable})"),
expr.range(),
)));
}
/// Check that the slice [`Expr`] is a slice of the first element (e.g., `x[0]`).
fn is_zero(expr: &Expr) -> bool {
matches!(
expr,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(Int::ZERO),
..
})
)
}
#[derive(Debug)]
struct IterationTarget {
/// The [`TextRange`] of the target.
range: TextRange,
/// Whether the target is an iterable (e.g., a generator). If not, the target must be wrapped
/// in `iter(...)` prior to calling `next(...)`.
iterable: bool,
}
/// Return the [`IterationTarget`] of an expression, if the expression can be sliced into (i.e.,
/// is a list comprehension, or call to `list` or `tuple`).
///
/// For example, given `list(x)`, returns the range of `x`. Given `[x * x for x in y]`, returns the
/// range of `x * x for x in y`.
///
/// As a special-case, given `[x for x in y]`, returns the range of `y` (rather than the
/// redundant comprehension).
fn match_iteration_target(expr: &Expr, semantic: &SemanticModel) -> Option<IterationTarget> {
let result = match expr {
Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, .. },
..
}) => {
let [arg] = &**args else {
return None;
};
let builtin_function_name = semantic.resolve_builtin_symbol(func)?;
if !matches!(builtin_function_name, "tuple" | "list") {
return None;
}
match arg {
Expr::Generator(ast::ExprGenerator {
elt, generators, ..
}) => match match_simple_comprehension(elt, generators) {
Some(range) => IterationTarget {
range,
iterable: false,
},
None => IterationTarget {
range: arg.range(),
iterable: true,
},
},
Expr::ListComp(ast::ExprListComp {
elt, generators, ..
}) => match match_simple_comprehension(elt, generators) {
Some(range) => IterationTarget {
range,
iterable: false,
},
None => IterationTarget {
range: arg
.range()
// Remove the `[`
.add_start(TextSize::from(1))
// Remove the `]`
.sub_end(TextSize::from(1)),
iterable: true,
},
},
Expr::Call(ast::ExprCall { func, .. }) => IterationTarget {
range: arg.range(),
iterable: semantic
.resolve_builtin_symbol(func)
.is_some_and(is_iterator),
},
_ => IterationTarget {
range: arg.range(),
iterable: false,
},
}
}
Expr::ListComp(ast::ExprListComp {
elt, generators, ..
}) => match match_simple_comprehension(elt, generators) {
Some(range) => IterationTarget {
range,
iterable: false,
},
None => IterationTarget {
range: expr
.range()
// Remove the `[`
.add_start(TextSize::from(1))
// Remove the `]`
.sub_end(TextSize::from(1)),
iterable: true,
},
},
Expr::List(ast::ExprList { elts, .. }) => {
let [elt] = elts.as_slice() else {
return None;
};
let Expr::Starred(ast::ExprStarred { value, .. }) = elt else {
return None;
};
let iterable = if let ast::Expr::Call(ast::ExprCall { func, .. }) = &**value {
semantic
.resolve_builtin_symbol(func)
.is_some_and(is_iterator)
} else {
false
};
IterationTarget {
range: value.range(),
iterable,
}
}
_ => return None,
};
Some(result)
}
/// Returns the [`Expr`] target for a comprehension, if the comprehension is "simple"
/// (e.g., `x` for `[i for i in x]`).
fn match_simple_comprehension(elt: &Expr, generators: &[Comprehension]) -> Option<TextRange> {
let [
generator @ Comprehension {
is_async: false, ..
},
] = generators
else {
return None;
};
// Ignore if there's an `if` statement in the comprehension, since it filters the list.
if !generator.ifs.is_empty() {
return None;
}
// Verify that the generator is, e.g. `i for i in x`, as opposed to `i for j in x`.
let elt = elt.as_name_expr()?;
let target = generator.target.as_name_expr()?;
if elt.id != target.id {
return None;
}
Some(generator.iter.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/ruff/rules/unused_noqa.rs | crates/ruff_linter/src/rules/ruff/rules/unused_noqa.rs | use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::AlwaysFixableViolation;
#[derive(Debug, PartialEq, Eq, Default)]
pub(crate) struct UnusedCodes {
pub disabled: Vec<String>,
pub duplicated: Vec<String>,
pub unknown: Vec<String>,
pub unmatched: Vec<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum UnusedNOQAKind {
Noqa,
Suppression,
}
impl UnusedNOQAKind {
fn as_str(&self) -> &str {
match self {
UnusedNOQAKind::Noqa => "`noqa` directive",
UnusedNOQAKind::Suppression => "suppression",
}
}
}
/// ## What it does
/// Checks for `noqa` directives that are no longer applicable.
///
/// ## Why is this bad?
/// A `noqa` directive that no longer matches any diagnostic violations is
/// likely included by mistake, and should be removed to avoid confusion.
///
/// ## Example
/// ```python
/// import foo # noqa: F401
///
///
/// def bar():
/// foo.bar()
/// ```
///
/// Use instead:
/// ```python
/// import foo
///
///
/// def bar():
/// foo.bar()
/// ```
///
/// ## Options
/// - `lint.external`
///
/// ## References
/// - [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.155")]
pub(crate) struct UnusedNOQA {
pub codes: Option<UnusedCodes>,
pub kind: UnusedNOQAKind,
}
impl AlwaysFixableViolation for UnusedNOQA {
#[derive_message_formats]
fn message(&self) -> String {
match &self.codes {
Some(codes) => {
let mut codes_by_reason = vec![];
if !codes.unmatched.is_empty() {
codes_by_reason.push(format!(
"unused: {}",
codes
.unmatched
.iter()
.map(|code| format!("`{code}`"))
.join(", ")
));
}
if !codes.disabled.is_empty() {
codes_by_reason.push(format!(
"non-enabled: {}",
codes
.disabled
.iter()
.map(|code| format!("`{code}`"))
.join(", ")
));
}
if !codes.duplicated.is_empty() {
codes_by_reason.push(format!(
"duplicated: {}",
codes
.duplicated
.iter()
.map(|code| format!("`{code}`"))
.join(", ")
));
}
if !codes.unknown.is_empty() {
codes_by_reason.push(format!(
"unknown: {}",
codes
.unknown
.iter()
.map(|code| format!("`{code}`"))
.join(", ")
));
}
if codes_by_reason.is_empty() {
format!("Unused {}", self.kind.as_str())
} else {
format!(
"Unused {} ({})",
self.kind.as_str(),
codes_by_reason.join("; ")
)
}
}
None => format!("Unused blanket {}", self.kind.as_str()),
}
}
fn fix_title(&self) -> String {
format!("Remove unused {}", self.kind.as_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/ruff/rules/unmatched_suppression_comment.rs | crates/ruff_linter/src/rules/ruff/rules/unmatched_suppression_comment.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
/// ## What it does
/// Checks for unmatched range suppression comments
///
/// ## Why is this bad?
/// Unmatched range suppression comments can inadvertently suppress violations
/// over larger sections of code than intended, particularly at module scope.
///
/// ## Example
/// ```python
/// def foo():
/// # ruff: disable[E501] # unmatched
/// REALLY_LONG_VALUES = [...]
///
/// print(REALLY_LONG_VALUES)
/// ```
///
/// Use instead:
/// ```python
/// def foo():
/// # ruff: disable[E501]
/// REALLY_LONG_VALUES = [...]
/// # ruff: enable[E501]
///
/// print(REALLY_LONG_VALUES)
/// ```
///
/// ## References
/// - [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.14.11")]
pub(crate) struct UnmatchedSuppressionComment;
impl Violation for UnmatchedSuppressionComment {
#[derive_message_formats]
fn message(&self) -> String {
"Suppression comment without matching `#ruff:enable` comment".to_string()
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/pytest_raises_ambiguous_pattern.rs | crates/ruff_linter/src/rules/ruff/rules/pytest_raises_ambiguous_pattern.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_pytest_style::rules::is_pytest_raises;
/// ## What it does
/// Checks for non-raw literal string arguments passed to the `match` parameter
/// of `pytest.raises()` where the string contains at least one unescaped
/// regex metacharacter.
///
/// ## Why is this bad?
/// The `match` argument is implicitly converted to a regex under the hood.
/// It should be made explicit whether the string is meant to be a regex or a "plain" pattern
/// by prefixing the string with the `r` suffix, escaping the metacharacter(s)
/// in the string using backslashes, or wrapping the entire string in a call to
/// `re.escape()`.
///
/// ## Example
///
/// ```python
/// import pytest
///
///
/// with pytest.raises(Exception, match="A full sentence."):
/// do_thing_that_raises()
/// ```
///
/// If the pattern is intended to be a regular expression, use a raw string to signal this
/// intention:
///
/// ```python
/// import pytest
///
///
/// with pytest.raises(Exception, match=r"A full sentence."):
/// do_thing_that_raises()
/// ```
///
/// Alternatively, escape any regex metacharacters with `re.escape`:
///
/// ```python
/// import pytest
/// import re
///
///
/// with pytest.raises(Exception, match=re.escape("A full sentence.")):
/// do_thing_that_raises()
/// ```
///
/// or directly with backslashes:
///
/// ```python
/// import pytest
/// import re
///
///
/// with pytest.raises(Exception, "A full sentence\\."):
/// do_thing_that_raises()
/// ```
///
/// ## References
/// - [Python documentation: `re.escape`](https://docs.python.org/3/library/re.html#re.escape)
/// - [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.13.0")]
pub(crate) struct PytestRaisesAmbiguousPattern;
impl Violation for PytestRaisesAmbiguousPattern {
#[derive_message_formats]
fn message(&self) -> String {
"Pattern passed to `match=` contains metacharacters but is neither escaped nor raw"
.to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Use a raw string or `re.escape()` to make the intention explicit".to_string())
}
}
/// RUF043
pub(crate) fn pytest_raises_ambiguous_pattern(checker: &Checker, call: &ast::ExprCall) {
if !is_pytest_raises(&call.func, checker.semantic()) {
return;
}
// It *can* be passed as a positional argument if you try very hard,
// but pytest only documents it as a keyword argument, and it's quite hard pass it positionally
let Some(ast::Keyword { value, .. }) = call.arguments.find_keyword("match") else {
return;
};
let ast::Expr::StringLiteral(string) = value else {
return;
};
let any_part_is_raw = string.value.iter().any(|part| part.flags.prefix().is_raw());
if any_part_is_raw || !string_has_unescaped_metacharacters(&string.value) {
return;
}
checker.report_diagnostic(PytestRaisesAmbiguousPattern, string.range);
}
fn string_has_unescaped_metacharacters(value: &ast::StringLiteralValue) -> bool {
let mut escaped = false;
for character in value.chars() {
if escaped {
if escaped_char_is_regex_metasequence(character) {
return true;
}
escaped = false;
continue;
}
if character == '\\' {
escaped = true;
continue;
}
if char_is_regex_metacharacter(character) {
return true;
}
}
false
}
/// Whether the sequence `\<c>` means anything special:
///
/// * `\A`: Start of input
/// * `\b`, `\B`: Word boundary and non-word-boundary
/// * `\d`, `\D`: Digit and non-digit
/// * `\s`, `\S`: Whitespace and non-whitespace
/// * `\w`, `\W`: Word and non-word character
/// * `\z`: End of input
///
/// `\u`, `\U`, `\N`, `\x`, `\a`, `\f`, `\n`, `\r`, `\t`, `\v`
/// are also valid in normal strings and thus do not count.
/// `\b` means backspace only in character sets,
/// while backreferences (e.g., `\1`) are not valid without groups,
/// both of which should be caught in [`string_has_unescaped_metacharacters`].
const fn escaped_char_is_regex_metasequence(c: char) -> bool {
matches!(c, 'A' | 'b' | 'B' | 'd' | 'D' | 's' | 'S' | 'w' | 'W' | 'z')
}
const fn char_is_regex_metacharacter(c: char) -> bool {
matches!(
c,
'.' | '^' | '$' | '*' | '+' | '?' | '{' | '[' | '\\' | '|' | '(' | ')'
)
}
| 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/ruff/rules/unused_async.rs | crates/ruff_linter/src/rules/ruff/rules/unused_async.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::visitor::source_order;
use ruff_python_ast::{self as ast, AnyNodeRef, Expr, Stmt};
use ruff_python_semantic::Modules;
use ruff_python_semantic::analyze::function_type::is_stub;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::fastapi::rules::is_fastapi_route;
/// ## What it does
/// Checks for functions declared `async` that do not await or otherwise use features requiring the
/// function to be declared `async`.
///
/// ## Why is this bad?
/// Declaring a function `async` when it's not is usually a mistake, and will artificially limit the
/// contexts where that function may be called. In some cases, labeling a function `async` is
/// semantically meaningful (e.g. with the trio library).
///
/// ## Example
/// ```python
/// async def foo():
/// bar()
/// ```
///
/// Use instead:
/// ```python
/// def foo():
/// bar()
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.4.0")]
pub(crate) struct UnusedAsync {
name: String,
}
impl Violation for UnusedAsync {
#[derive_message_formats]
fn message(&self) -> String {
let UnusedAsync { name } = self;
format!(
"Function `{name}` is declared `async`, but doesn't `await` or use `async` features."
)
}
}
#[derive(Default)]
struct AsyncExprVisitor {
found_await_or_async: bool,
}
/// Traverse a function's body to find whether it contains an await-expr, an async-with, or an
/// async-for. Stop traversing after one is found. The bodies of inner-functions and inner-classes
/// aren't traversed.
impl<'a> source_order::SourceOrderVisitor<'a> for AsyncExprVisitor {
fn enter_node(&mut self, _node: AnyNodeRef<'a>) -> source_order::TraversalSignal {
if self.found_await_or_async {
source_order::TraversalSignal::Skip
} else {
source_order::TraversalSignal::Traverse
}
}
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::With(ast::StmtWith { is_async: true, .. }) => {
self.found_await_or_async = true;
}
Stmt::For(ast::StmtFor { is_async: true, .. }) => {
self.found_await_or_async = true;
}
// avoid counting inner classes' or functions' bodies toward the search
Stmt::FunctionDef(function_def) => {
function_def_visit_preorder_except_body(function_def, self);
}
Stmt::ClassDef(class_def) => {
class_def_visit_preorder_except_body(class_def, self);
}
_ => source_order::walk_stmt(self, stmt),
}
}
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Await(_) => {
self.found_await_or_async = true;
}
_ => source_order::walk_expr(self, expr),
}
}
fn visit_comprehension(&mut self, comprehension: &'a ast::Comprehension) {
if comprehension.is_async {
self.found_await_or_async = true;
} else {
source_order::walk_comprehension(self, comprehension);
}
}
}
/// Very nearly `crate::node::StmtFunctionDef.visit_preorder`, except it is specialized and,
/// crucially, doesn't traverse the body.
fn function_def_visit_preorder_except_body<'a, V>(
function_def: &'a ast::StmtFunctionDef,
visitor: &mut V,
) where
V: source_order::SourceOrderVisitor<'a>,
{
let ast::StmtFunctionDef {
parameters,
decorator_list,
returns,
type_params,
..
} = function_def;
for decorator in decorator_list {
visitor.visit_decorator(decorator);
}
if let Some(type_params) = type_params {
visitor.visit_type_params(type_params);
}
visitor.visit_parameters(parameters);
if let Some(expr) = returns {
visitor.visit_annotation(expr);
}
}
/// Very nearly `crate::node::StmtClassDef.visit_preorder`, except it is specialized and,
/// crucially, doesn't traverse the body.
fn class_def_visit_preorder_except_body<'a, V>(class_def: &'a ast::StmtClassDef, visitor: &mut V)
where
V: source_order::SourceOrderVisitor<'a>,
{
let ast::StmtClassDef {
arguments,
decorator_list,
type_params,
..
} = class_def;
for decorator in decorator_list {
visitor.visit_decorator(decorator);
}
if let Some(type_params) = type_params {
visitor.visit_type_params(type_params);
}
if let Some(arguments) = arguments {
visitor.visit_arguments(arguments);
}
}
/// RUF029
pub(crate) fn unused_async(
checker: &Checker,
function_def @ ast::StmtFunctionDef {
is_async,
name,
body,
..
}: &ast::StmtFunctionDef,
) {
if !is_async {
return;
}
if checker.semantic().current_scope().kind.is_class() {
return;
}
// Ignore stubs (e.g., `...`).
if is_stub(function_def, checker.semantic()) {
return;
}
if checker.semantic().seen_module(Modules::FASTAPI)
&& is_fastapi_route(function_def, checker.semantic())
{
return;
}
let found_await_or_async = {
let mut visitor = AsyncExprVisitor::default();
source_order::walk_body(&mut visitor, body);
visitor.found_await_or_async
};
if !found_await_or_async {
checker.report_diagnostic(
UnusedAsync {
name: name.to_string(),
},
function_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/ruff/rules/collection_literal_concatenation.rs | crates/ruff_linter/src/rules/ruff/rules/collection_literal_concatenation.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprContext, Operator};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of the `+` operator to concatenate collections.
///
/// ## Why is this bad?
/// In Python, the `+` operator can be used to concatenate collections (e.g.,
/// `x + y` to concatenate the lists `x` and `y`).
///
/// However, collections can be concatenated more efficiently using the
/// unpacking operator (e.g., `[*x, *y]` to concatenate `x` and `y`).
///
/// Prefer the unpacking operator to concatenate collections, as it is more
/// readable and flexible. The `*` operator can unpack any iterable, whereas
/// `+` operates only on particular sequences which, in many cases, must be of
/// the same type.
///
/// ## Example
/// ```python
/// foo = [2, 3, 4]
/// bar = [1] + foo + [5, 6]
/// ```
///
/// Use instead:
/// ```python
/// foo = [2, 3, 4]
/// bar = [1, *foo, 5, 6]
/// ```
///
/// ## Fix safety
///
/// The fix is always marked as unsafe because the `+` operator uses the `__add__` magic method and
/// `*`-unpacking uses the `__iter__` magic method. Both of these could have custom
/// implementations, causing the fix to change program behaviour.
///
/// ## References
/// - [PEP 448 – Additional Unpacking Generalizations](https://peps.python.org/pep-0448/)
/// - [Python documentation: Sequence Types — `list`, `tuple`, `range`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.227")]
pub(crate) struct CollectionLiteralConcatenation {
expression: SourceCodeSnippet,
}
impl Violation for CollectionLiteralConcatenation {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
if let Some(expression) = self.expression.full_display() {
format!("Consider `{expression}` instead of concatenation")
} else {
"Consider iterable unpacking instead of concatenation".to_string()
}
}
fn fix_title(&self) -> Option<String> {
let title = match self.expression.full_display() {
Some(expression) => format!("Replace with `{expression}`"),
None => "Replace with iterable unpacking".to_string(),
};
Some(title)
}
}
fn make_splat_elts(
splat_element: &Expr,
other_elements: &[Expr],
splat_at_left: bool,
) -> Vec<Expr> {
let mut new_elts = other_elements.to_owned();
let node = ast::ExprStarred {
value: Box::from(splat_element.clone()),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let splat = node.into();
if splat_at_left {
new_elts.insert(0, splat);
} else {
new_elts.push(splat);
}
new_elts
}
#[derive(Debug, Copy, Clone)]
enum Type {
List,
Tuple,
}
/// Recursively merge all the tuples and lists in the expression.
fn concatenate_expressions(expr: &Expr) -> Option<(Expr, Type)> {
let Expr::BinOp(ast::ExprBinOp {
left,
op: Operator::Add,
right,
range: _,
node_index: _,
}) = expr
else {
return None;
};
let new_left = match left.as_ref() {
Expr::BinOp(ast::ExprBinOp { .. }) => match concatenate_expressions(left) {
Some((new_left, _)) => new_left,
None => *left.clone(),
},
_ => *left.clone(),
};
let new_right = match right.as_ref() {
Expr::BinOp(ast::ExprBinOp { .. }) => match concatenate_expressions(right) {
Some((new_right, _)) => new_right,
None => *right.clone(),
},
_ => *right.clone(),
};
// Figure out which way the splat is, and the type of the collection.
let (type_, splat_element, other_elements, splat_at_left) = match (&new_left, &new_right) {
(Expr::List(ast::ExprList { elts: l_elts, .. }), _) => {
(Type::List, &new_right, l_elts, false)
}
(Expr::Tuple(ast::ExprTuple { elts: l_elts, .. }), _) => {
(Type::Tuple, &new_right, l_elts, false)
}
(_, Expr::List(ast::ExprList { elts: r_elts, .. })) => {
(Type::List, &new_left, r_elts, true)
}
(_, Expr::Tuple(ast::ExprTuple { elts: r_elts, .. })) => {
(Type::Tuple, &new_left, r_elts, true)
}
_ => return None,
};
let new_elts = match splat_element {
// We'll be a bit conservative here; only calls, names and attribute accesses
// will be considered as splat elements.
Expr::Call(_) | Expr::Attribute(_) | Expr::Name(_) => {
make_splat_elts(splat_element, other_elements, splat_at_left)
}
// Subscripts are also considered safe-ish to splat if the indexer is a slice.
Expr::Subscript(ast::ExprSubscript { slice, .. }) if matches!(&**slice, Expr::Slice(_)) => {
make_splat_elts(splat_element, other_elements, splat_at_left)
}
// If the splat element is itself a list/tuple, insert them in the other list/tuple.
Expr::List(ast::ExprList { elts, .. }) if matches!(type_, Type::List) => {
other_elements.iter().chain(elts).cloned().collect()
}
Expr::Tuple(ast::ExprTuple { elts, .. }) if matches!(type_, Type::Tuple) => {
other_elements.iter().chain(elts).cloned().collect()
}
_ => return None,
};
let new_expr = match type_ {
Type::List => ast::ExprList {
elts: new_elts,
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
Type::Tuple => ast::ExprTuple {
elts: new_elts,
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
}
.into(),
};
Some((new_expr, type_))
}
/// RUF005
pub(crate) fn collection_literal_concatenation(checker: &Checker, expr: &Expr) {
// If the expression is already a child of an addition, we'll have analyzed it already.
if matches!(
checker.semantic().current_expression_parent(),
Some(Expr::BinOp(ast::ExprBinOp {
op: Operator::Add,
..
}))
) {
return;
}
let Some((new_expr, type_)) = concatenate_expressions(expr) else {
return;
};
let contents = match type_ {
// Wrap the new expression in parentheses if it was a tuple.
Type::Tuple => format!("({})", checker.generator().expr(&new_expr)),
Type::List => checker.generator().expr(&new_expr),
};
let mut diagnostic = checker.report_diagnostic(
CollectionLiteralConcatenation {
expression: SourceCodeSnippet::new(contents.clone()),
},
expr.range(),
);
if !checker
.comment_ranges()
.has_comments(expr, checker.source())
{
// This suggestion could be unsafe if the non-literal expression in the
// expression has overridden the `__add__` (or `__radd__`) magic methods.
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
contents,
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/ruff/rules/invalid_assert_message_literal_argument.rs | crates/ruff_linter/src/rules/ruff/rules/invalid_assert_message_literal_argument.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, StmtAssert};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for invalid use of literals in assert message arguments.
///
/// ## Why is this bad?
/// An assert message which is a non-string literal was likely intended
/// to be used in a comparison assertion, rather than as a message.
///
/// ## Example
/// ```python
/// fruits = ["apples", "plums", "pears"]
/// fruits.filter(lambda fruit: fruit.startwith("p"))
/// assert len(fruits), 2 # True unless the list is empty
/// ```
///
/// Use instead:
/// ```python
/// fruits = ["apples", "plums", "pears"]
/// fruits.filter(lambda fruit: fruit.startwith("p"))
/// assert len(fruits) == 2
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct InvalidAssertMessageLiteralArgument;
impl Violation for InvalidAssertMessageLiteralArgument {
#[derive_message_formats]
fn message(&self) -> String {
"Non-string literal used as assert message".to_string()
}
}
/// RUF040
pub(crate) fn invalid_assert_message_literal_argument(checker: &Checker, stmt: &StmtAssert) {
let Some(message) = stmt.msg.as_deref() else {
return;
};
if !matches!(
message,
Expr::NumberLiteral(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_)
| Expr::BytesLiteral(_)
) {
return;
}
checker.report_diagnostic(InvalidAssertMessageLiteralArgument, message.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/ruff/rules/invalid_suppression_comment.rs | crates/ruff_linter/src/rules/ruff/rules/invalid_suppression_comment.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::AlwaysFixableViolation;
use crate::suppression::{InvalidSuppressionKind, ParseErrorKind};
/// ## What it does
/// Checks for invalid suppression comments
///
/// ## Why is this bad?
/// Invalid suppression comments are ignored by Ruff, and should either
/// be fixed or removed to avoid confusion.
///
/// ## Example
/// ```python
/// ruff: disable # missing codes
/// ```
///
/// Use instead:
/// ```python
/// # ruff: disable[E501]
/// ```
///
/// Or delete the invalid suppression comment.
///
/// ## References
/// - [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.14.11")]
pub(crate) struct InvalidSuppressionComment {
pub(crate) kind: InvalidSuppressionCommentKind,
}
impl AlwaysFixableViolation for InvalidSuppressionComment {
#[derive_message_formats]
fn message(&self) -> String {
let msg = match self.kind {
InvalidSuppressionCommentKind::Invalid(InvalidSuppressionKind::Indentation) => {
"unexpected indentation".to_string()
}
InvalidSuppressionCommentKind::Invalid(InvalidSuppressionKind::Trailing) => {
"trailing comments are not supported".to_string()
}
InvalidSuppressionCommentKind::Invalid(InvalidSuppressionKind::Unmatched) => {
"no matching 'disable' comment".to_string()
}
InvalidSuppressionCommentKind::Error(error) => format!("{error}"),
};
format!("Invalid suppression comment: {msg}")
}
fn fix_title(&self) -> String {
"Remove suppression comment".to_string()
}
}
pub(crate) enum InvalidSuppressionCommentKind {
Invalid(InvalidSuppressionKind),
Error(ParseErrorKind),
}
| 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/ruff/rules/confusables.rs | crates/ruff_linter/src/rules/ruff/rules/confusables.rs | //! This file is auto-generated by `scripts/update_ambiguous_characters.py`.
/// Via: <https://github.com/hediet/vscode-unicode-data/blob/main/out/ambiguous.json>
/// See: <https://github.com/microsoft/vscode/blob/095ddabc52b82498ee7f718a34f9dd11d59099a8/src/vs/base/common/strings.ts#L1094>
pub(crate) fn confusable(c: u32) -> Option<char> {
let result = match c {
160u32 => ' ',
180u32 => '`',
184u32 => ',',
215u32 => 'x',
305u32 => 'i',
383u32 => 'f',
388u32 => 'b',
397u32 => 'g',
422u32 => 'R',
423u32 => '2',
439u32 => '3',
444u32 => '5',
445u32 => 's',
448u32 => 'I',
451u32 => '!',
540u32 => '3',
546u32 => '8',
547u32 => '8',
577u32 => '?',
593u32 => 'a',
609u32 => 'g',
611u32 => 'y',
617u32 => 'i',
618u32 => 'i',
623u32 => 'w',
651u32 => 'u',
655u32 => 'y',
660u32 => '?',
697u32 => '`',
699u32 => '`',
700u32 => '`',
701u32 => '`',
702u32 => '`',
706u32 => '<',
707u32 => '>',
708u32 => '^',
710u32 => '^',
712u32 => '`',
714u32 => '`',
715u32 => '`',
720u32 => ':',
727u32 => '-',
731u32 => 'i',
732u32 => '~',
756u32 => '`',
760u32 => ':',
884u32 => '`',
890u32 => 'i',
894u32 => ';',
895u32 => 'J',
900u32 => '`',
913u32 => 'A',
914u32 => 'B',
917u32 => 'E',
918u32 => 'Z',
919u32 => 'H',
921u32 => 'I',
922u32 => 'K',
924u32 => 'M',
925u32 => 'N',
927u32 => 'O',
929u32 => 'P',
932u32 => 'T',
933u32 => 'Y',
935u32 => 'X',
945u32 => 'a',
947u32 => 'y',
953u32 => 'i',
957u32 => 'v',
959u32 => 'o',
961u32 => 'p',
963u32 => 'o',
965u32 => 'u',
978u32 => 'Y',
988u32 => 'F',
1000u32 => '2',
1009u32 => 'p',
1010u32 => 'c',
1011u32 => 'j',
1017u32 => 'C',
1018u32 => 'M',
1029u32 => 'S',
1030u32 => 'I',
1032u32 => 'J',
1040u32 => 'A',
1042u32 => 'B',
1045u32 => 'E',
1047u32 => '3',
1050u32 => 'K',
1052u32 => 'M',
1053u32 => 'H',
1054u32 => 'O',
1056u32 => 'P',
1057u32 => 'C',
1058u32 => 'T',
1059u32 => 'Y',
1061u32 => 'X',
1068u32 => 'b',
1072u32 => 'a',
1073u32 => '6',
1075u32 => 'r',
1077u32 => 'e',
1086u32 => 'o',
1088u32 => 'p',
1089u32 => 'c',
1091u32 => 'y',
1093u32 => 'x',
1109u32 => 's',
1110u32 => 'i',
1112u32 => 'j',
1121u32 => 'w',
1140u32 => 'V',
1141u32 => 'v',
1198u32 => 'Y',
1199u32 => 'y',
1211u32 => 'h',
1213u32 => 'e',
1216u32 => 'I',
1231u32 => 'i',
1248u32 => '3',
1281u32 => 'd',
1292u32 => 'G',
1307u32 => 'q',
1308u32 => 'W',
1309u32 => 'w',
1357u32 => 'U',
1359u32 => 'S',
1365u32 => 'O',
1370u32 => '`',
1373u32 => '`',
1377u32 => 'w',
1379u32 => 'q',
1382u32 => 'q',
1392u32 => 'h',
1400u32 => 'n',
1404u32 => 'n',
1405u32 => 'u',
1409u32 => 'g',
1412u32 => 'f',
1413u32 => 'o',
1417u32 => ':',
1472u32 => 'l',
1475u32 => ':',
1493u32 => 'l',
1496u32 => 'v',
1497u32 => '`',
1503u32 => 'l',
1505u32 => 'o',
1523u32 => '`',
1549u32 => ',',
1575u32 => 'l',
1607u32 => 'o',
1632u32 => '.',
1633u32 => 'l',
1637u32 => 'o',
1639u32 => 'V',
1643u32 => ',',
1645u32 => '*',
1726u32 => 'o',
1729u32 => 'o',
1748u32 => '-',
1749u32 => 'o',
1776u32 => '.',
1777u32 => 'I',
1781u32 => 'o',
1783u32 => 'V',
1793u32 => '.',
1794u32 => '.',
1795u32 => ':',
1796u32 => ':',
1984u32 => 'O',
1994u32 => 'l',
2036u32 => '`',
2037u32 => '`',
2042u32 => '_',
2307u32 => ':',
2406u32 => 'o',
2429u32 => '?',
2534u32 => 'O',
2538u32 => '8',
2541u32 => '9',
2662u32 => 'o',
2663u32 => '9',
2666u32 => '8',
2691u32 => ':',
2790u32 => 'o',
2819u32 => '8',
2848u32 => 'O',
2918u32 => 'O',
2920u32 => '9',
3046u32 => 'o',
3074u32 => 'o',
3174u32 => 'o',
3202u32 => 'o',
3302u32 => 'o',
3330u32 => 'o',
3360u32 => 'o',
3430u32 => 'o',
3437u32 => '9',
3458u32 => 'o',
3664u32 => 'o',
3792u32 => 'o',
4125u32 => 'o',
4160u32 => 'o',
4327u32 => 'y',
4351u32 => 'o',
4608u32 => 'U',
4816u32 => 'O',
5024u32 => 'D',
5025u32 => 'R',
5026u32 => 'T',
5029u32 => 'i',
5033u32 => 'Y',
5034u32 => 'A',
5035u32 => 'J',
5036u32 => 'E',
5038u32 => '?',
5043u32 => 'W',
5047u32 => 'M',
5051u32 => 'H',
5053u32 => 'Y',
5056u32 => 'G',
5058u32 => 'h',
5059u32 => 'Z',
5070u32 => '4',
5071u32 => 'b',
5074u32 => 'R',
5076u32 => 'W',
5077u32 => 'S',
5081u32 => 'V',
5082u32 => 'S',
5086u32 => 'L',
5087u32 => 'C',
5090u32 => 'P',
5094u32 => 'K',
5095u32 => 'd',
5102u32 => '6',
5107u32 => 'G',
5108u32 => 'B',
5120u32 => '=',
5167u32 => 'V',
5171u32 => '>',
5176u32 => '<',
5194u32 => '`',
5196u32 => 'U',
5229u32 => 'P',
5231u32 => 'd',
5234u32 => 'b',
5261u32 => 'J',
5290u32 => 'L',
5311u32 => '2',
5441u32 => 'x',
5500u32 => 'H',
5501u32 => 'x',
5511u32 => 'R',
5551u32 => 'b',
5556u32 => 'F',
5573u32 => 'A',
5598u32 => 'D',
5610u32 => 'D',
5616u32 => 'M',
5623u32 => 'B',
5741u32 => 'X',
5742u32 => 'x',
5760u32 => ' ',
5810u32 => '<',
5815u32 => 'X',
5825u32 => 'I',
5836u32 => '`',
5845u32 => 'K',
5846u32 => 'M',
5868u32 => ':',
5869u32 => '+',
5941u32 => '/',
6147u32 => ':',
6153u32 => ':',
7428u32 => 'c',
7439u32 => 'o',
7441u32 => 'o',
7452u32 => 'u',
7456u32 => 'v',
7457u32 => 'w',
7458u32 => 'z',
7462u32 => 'r',
7555u32 => 'g',
7564u32 => 'y',
7837u32 => 'f',
7935u32 => 'y',
8125u32 => '`',
8126u32 => 'i',
8127u32 => '`',
8128u32 => '~',
8175u32 => '`',
8189u32 => '`',
8190u32 => '`',
8192u32 => ' ',
8193u32 => ' ',
8194u32 => ' ',
8195u32 => ' ',
8196u32 => ' ',
8197u32 => ' ',
8198u32 => ' ',
8199u32 => ' ',
8200u32 => ' ',
8201u32 => ' ',
8202u32 => ' ',
8208u32 => '-',
8209u32 => '-',
8210u32 => '-',
8211u32 => '-',
8216u32 => '`',
8217u32 => '`',
8218u32 => ',',
8219u32 => '`',
8228u32 => '.',
8232u32 => ' ',
8233u32 => ' ',
8239u32 => ' ',
8242u32 => '`',
8245u32 => '`',
8249u32 => '<',
8250u32 => '>',
8257u32 => '/',
8259u32 => '-',
8260u32 => '/',
8270u32 => '*',
8275u32 => '~',
8282u32 => ':',
8287u32 => ' ',
8450u32 => 'C',
8458u32 => 'g',
8459u32 => 'H',
8460u32 => 'H',
8461u32 => 'H',
8462u32 => 'h',
8464u32 => 'I',
8465u32 => 'I',
8466u32 => 'L',
8467u32 => 'l',
8469u32 => 'N',
8473u32 => 'P',
8474u32 => 'Q',
8475u32 => 'R',
8476u32 => 'R',
8477u32 => 'R',
8484u32 => 'Z',
8488u32 => 'Z',
8490u32 => 'K',
8492u32 => 'B',
8493u32 => 'C',
8494u32 => 'e',
8495u32 => 'e',
8496u32 => 'E',
8497u32 => 'F',
8499u32 => 'M',
8500u32 => 'o',
8505u32 => 'i',
8509u32 => 'y',
8517u32 => 'D',
8518u32 => 'd',
8519u32 => 'e',
8520u32 => 'i',
8521u32 => 'j',
8544u32 => 'I',
8548u32 => 'V',
8553u32 => 'X',
8556u32 => 'L',
8557u32 => 'C',
8558u32 => 'D',
8559u32 => 'M',
8560u32 => 'i',
8564u32 => 'v',
8569u32 => 'x',
8572u32 => 'I',
8573u32 => 'c',
8574u32 => 'd',
8722u32 => '-',
8725u32 => '/',
8726u32 => '\\',
8727u32 => '*',
8739u32 => 'I',
8744u32 => 'v',
8746u32 => 'U',
8758u32 => ':',
8764u32 => '~',
8868u32 => 'T',
8897u32 => 'v',
8899u32 => 'U',
8959u32 => 'E',
9075u32 => 'i',
9076u32 => 'p',
9082u32 => 'a',
9213u32 => 'I',
9585u32 => '/',
9587u32 => 'X',
10088u32 => '(',
10089u32 => ')',
10094u32 => '<',
10095u32 => '>',
10098u32 => '(',
10099u32 => ')',
10100u32 => '{',
10101u32 => '}',
10133u32 => '+',
10134u32 => '-',
10187u32 => '/',
10189u32 => '\\',
10201u32 => 'T',
10539u32 => 'x',
10540u32 => 'x',
10741u32 => '\\',
10744u32 => '/',
10745u32 => '\\',
10799u32 => 'x',
11397u32 => 'r',
11406u32 => 'H',
11410u32 => 'I',
11412u32 => 'K',
11416u32 => 'M',
11418u32 => 'N',
11422u32 => 'O',
11423u32 => 'o',
11426u32 => 'P',
11427u32 => 'p',
11428u32 => 'C',
11429u32 => 'c',
11430u32 => 'T',
11432u32 => 'Y',
11436u32 => 'X',
11450u32 => '-',
11462u32 => '/',
11466u32 => '9',
11468u32 => '3',
11472u32 => 'L',
11474u32 => '6',
11576u32 => 'V',
11577u32 => 'E',
11599u32 => 'I',
11601u32 => '!',
11604u32 => 'O',
11605u32 => 'Q',
11613u32 => 'X',
11840u32 => '=',
12034u32 => '\\',
12035u32 => '/',
12295u32 => 'O',
12308u32 => '(',
12309u32 => ')',
12339u32 => '/',
12448u32 => '=',
12494u32 => '/',
12755u32 => '/',
12756u32 => '\\',
20022u32 => '\\',
20031u32 => '/',
42192u32 => 'B',
42193u32 => 'P',
42194u32 => 'd',
42195u32 => 'D',
42196u32 => 'T',
42198u32 => 'G',
42199u32 => 'K',
42201u32 => 'J',
42202u32 => 'C',
42204u32 => 'Z',
42205u32 => 'F',
42207u32 => 'M',
42208u32 => 'N',
42209u32 => 'L',
42210u32 => 'S',
42211u32 => 'R',
42214u32 => 'V',
42215u32 => 'H',
42218u32 => 'W',
42219u32 => 'X',
42220u32 => 'Y',
42222u32 => 'A',
42224u32 => 'E',
42226u32 => 'I',
42227u32 => 'O',
42228u32 => 'U',
42232u32 => '.',
42233u32 => ',',
42237u32 => ':',
42239u32 => '=',
42510u32 => '.',
42564u32 => '2',
42567u32 => 'i',
42719u32 => 'V',
42731u32 => '?',
42735u32 => '2',
42801u32 => 's',
42842u32 => '2',
42858u32 => '3',
42862u32 => '9',
42872u32 => '&',
42889u32 => ':',
42892u32 => '`',
42904u32 => 'F',
42905u32 => 'f',
42911u32 => 'u',
42923u32 => '3',
42930u32 => 'J',
42931u32 => 'X',
42932u32 => 'B',
43826u32 => 'e',
43829u32 => 'f',
43837u32 => 'o',
43847u32 => 'r',
43848u32 => 'r',
43854u32 => 'u',
43858u32 => 'u',
43866u32 => 'y',
43893u32 => 'i',
43905u32 => 'r',
43907u32 => 'w',
43923u32 => 'z',
43945u32 => 'v',
43946u32 => 's',
43951u32 => 'c',
64422u32 => 'o',
64423u32 => 'o',
64424u32 => 'o',
64425u32 => 'o',
64426u32 => 'o',
64427u32 => 'o',
64428u32 => 'o',
64429u32 => 'o',
64830u32 => '(',
64831u32 => ')',
65072u32 => ':',
65101u32 => '_',
65102u32 => '_',
65103u32 => '_',
65112u32 => '-',
65128u32 => '\\',
65165u32 => 'l',
65166u32 => 'l',
65257u32 => 'o',
65258u32 => 'o',
65259u32 => 'o',
65260u32 => 'o',
65281u32 => '!',
65282u32 => '"',
65283u32 => '#',
65284u32 => '$',
65285u32 => '%',
65286u32 => '&',
65287u32 => '`',
65288u32 => '(',
65289u32 => ')',
65290u32 => '*',
65291u32 => '+',
65292u32 => ',',
65293u32 => '-',
65294u32 => '.',
65295u32 => '/',
65296u32 => '0',
65297u32 => '1',
65298u32 => '2',
65299u32 => '3',
65300u32 => '4',
65301u32 => '5',
65302u32 => '6',
65303u32 => '7',
65304u32 => '8',
65305u32 => '9',
65306u32 => ':',
65307u32 => ';',
65308u32 => '<',
65309u32 => '=',
65310u32 => '>',
65311u32 => '?',
65312u32 => '@',
65313u32 => 'A',
65314u32 => 'B',
65315u32 => 'C',
65316u32 => 'D',
65317u32 => 'E',
65318u32 => 'F',
65319u32 => 'G',
65320u32 => 'H',
65321u32 => 'I',
65322u32 => 'J',
65323u32 => 'K',
65324u32 => 'L',
65325u32 => 'M',
65326u32 => 'N',
65327u32 => 'O',
65328u32 => 'P',
65329u32 => 'Q',
65330u32 => 'R',
65331u32 => 'S',
65332u32 => 'T',
65333u32 => 'U',
65334u32 => 'V',
65335u32 => 'W',
65336u32 => 'X',
65337u32 => 'Y',
65338u32 => 'Z',
65339u32 => '[',
65340u32 => '\\',
65341u32 => ']',
65342u32 => '^',
65343u32 => '_',
65344u32 => '`',
65345u32 => 'a',
65346u32 => 'b',
65347u32 => 'c',
65348u32 => 'd',
65349u32 => 'e',
65350u32 => 'f',
65351u32 => 'g',
65352u32 => 'h',
65353u32 => 'i',
65354u32 => 'j',
65355u32 => 'k',
65356u32 => 'l',
65357u32 => 'm',
65358u32 => 'n',
65359u32 => 'o',
65360u32 => 'p',
65361u32 => 'q',
65362u32 => 'r',
65363u32 => 's',
65364u32 => 't',
65365u32 => 'u',
65366u32 => 'v',
65367u32 => 'w',
65368u32 => 'x',
65369u32 => 'y',
65370u32 => 'z',
65371u32 => '{',
65372u32 => '|',
65373u32 => '}',
65374u32 => '~',
65512u32 => 'I',
66178u32 => 'B',
66182u32 => 'E',
66183u32 => 'F',
66186u32 => '|',
66192u32 => 'X',
66194u32 => 'O',
66197u32 => 'P',
66198u32 => 'S',
66199u32 => 'T',
66203u32 => '+',
66208u32 => 'A',
66209u32 => 'B',
66210u32 => 'C',
66213u32 => 'F',
66219u32 => 'O',
66224u32 => 'M',
66225u32 => 'T',
66226u32 => 'Y',
66228u32 => 'X',
66255u32 => 'H',
66293u32 => 'Z',
66305u32 => 'B',
66306u32 => 'C',
66313u32 => '|',
66321u32 => 'M',
66325u32 => 'T',
66327u32 => 'X',
66330u32 => '8',
66335u32 => '*',
66336u32 => 'l',
66338u32 => 'X',
66564u32 => 'O',
66581u32 => 'C',
66587u32 => 'L',
66592u32 => 'S',
66604u32 => 'o',
66621u32 => 'c',
66632u32 => 's',
66740u32 => 'R',
66754u32 => 'O',
66766u32 => 'U',
66770u32 => '7',
66794u32 => 'o',
66806u32 => 'u',
66835u32 => 'N',
66838u32 => 'O',
66840u32 => 'K',
66844u32 => 'C',
66845u32 => 'V',
66853u32 => 'F',
66854u32 => 'L',
66855u32 => 'X',
68176u32 => '.',
70864u32 => 'O',
71430u32 => 'v',
71434u32 => 'w',
71438u32 => 'w',
71439u32 => 'w',
71840u32 => 'V',
71842u32 => 'F',
71843u32 => 'L',
71844u32 => 'Y',
71846u32 => 'E',
71849u32 => 'Z',
71852u32 => '9',
71854u32 => 'E',
71855u32 => '4',
71858u32 => 'L',
71861u32 => 'O',
71864u32 => 'U',
71867u32 => '5',
71868u32 => 'T',
71872u32 => 'v',
71873u32 => 's',
71874u32 => 'F',
71875u32 => 'i',
71876u32 => 'z',
71878u32 => '7',
71880u32 => 'o',
71882u32 => '3',
71884u32 => '9',
71893u32 => '6',
71894u32 => '9',
71895u32 => 'o',
71896u32 => 'u',
71900u32 => 'y',
71904u32 => 'O',
71909u32 => 'Z',
71910u32 => 'W',
71913u32 => 'C',
71916u32 => 'X',
71919u32 => 'W',
71922u32 => 'C',
93960u32 => 'V',
93962u32 => 'T',
93974u32 => 'L',
93992u32 => 'I',
94005u32 => 'R',
94010u32 => 'S',
94011u32 => '3',
94015u32 => '>',
94016u32 => 'A',
94018u32 => 'U',
94019u32 => 'Y',
94033u32 => '`',
94034u32 => '`',
119_060_u32 => '{',
119_149_u32 => '.',
119_302_u32 => '3',
119_309_u32 => 'V',
119_311_u32 => '\\',
119_314_u32 => '7',
119_315_u32 => 'F',
119_318_u32 => 'R',
119_338_u32 => 'L',
119_350_u32 => '<',
119_351_u32 => '>',
119_354_u32 => '/',
119_355_u32 => '\\',
119_808_u32 => 'A',
119_809_u32 => 'B',
119_810_u32 => 'C',
119_811_u32 => 'D',
119_812_u32 => 'E',
119_813_u32 => 'F',
119_814_u32 => 'G',
119_815_u32 => 'H',
119_816_u32 => 'I',
119_817_u32 => 'J',
119_818_u32 => 'K',
119_819_u32 => 'L',
119_820_u32 => 'M',
119_821_u32 => 'N',
119_822_u32 => 'O',
119_823_u32 => 'P',
119_824_u32 => 'Q',
119_825_u32 => 'R',
119_826_u32 => 'S',
119_827_u32 => 'T',
119_828_u32 => 'U',
119_829_u32 => 'V',
119_830_u32 => 'W',
119_831_u32 => 'X',
119_832_u32 => 'Y',
119_833_u32 => 'Z',
119_834_u32 => 'a',
119_835_u32 => 'b',
119_836_u32 => 'c',
119_837_u32 => 'd',
119_838_u32 => 'e',
119_839_u32 => 'f',
119_840_u32 => 'g',
119_841_u32 => 'h',
119_842_u32 => 'i',
119_843_u32 => 'j',
119_844_u32 => 'k',
119_845_u32 => 'l',
119_846_u32 => 'm',
119_847_u32 => 'n',
119_848_u32 => 'o',
119_849_u32 => 'p',
119_850_u32 => 'q',
119_851_u32 => 'r',
119_852_u32 => 's',
119_853_u32 => 't',
119_854_u32 => 'u',
119_855_u32 => 'v',
119_856_u32 => 'w',
119_857_u32 => 'x',
119_858_u32 => 'y',
119_859_u32 => 'z',
119_860_u32 => 'A',
119_861_u32 => 'B',
119_862_u32 => 'C',
119_863_u32 => 'D',
119_864_u32 => 'E',
119_865_u32 => 'F',
119_866_u32 => 'G',
119_867_u32 => 'H',
119_868_u32 => 'I',
119_869_u32 => 'J',
119_870_u32 => 'K',
119_871_u32 => 'L',
119_872_u32 => 'M',
119_873_u32 => 'N',
119_874_u32 => 'O',
119_875_u32 => 'P',
119_876_u32 => 'Q',
119_877_u32 => 'R',
119_878_u32 => 'S',
119_879_u32 => 'T',
119_880_u32 => 'U',
119_881_u32 => 'V',
119_882_u32 => 'W',
119_883_u32 => 'X',
119_884_u32 => 'Y',
119_885_u32 => 'Z',
119_886_u32 => 'a',
119_887_u32 => 'b',
119_888_u32 => 'c',
119_889_u32 => 'd',
119_890_u32 => 'e',
119_891_u32 => 'f',
119_892_u32 => 'g',
119_894_u32 => 'i',
119_895_u32 => 'j',
119_896_u32 => 'k',
119_897_u32 => 'l',
119_899_u32 => 'n',
119_900_u32 => 'o',
119_901_u32 => 'p',
119_902_u32 => 'q',
119_903_u32 => 'r',
119_904_u32 => 's',
119_905_u32 => 't',
119_906_u32 => 'u',
119_907_u32 => 'v',
119_908_u32 => 'w',
119_909_u32 => 'x',
119_910_u32 => 'y',
119_911_u32 => 'z',
119_912_u32 => 'A',
119_913_u32 => 'B',
119_914_u32 => 'C',
119_915_u32 => 'D',
119_916_u32 => 'E',
119_917_u32 => 'F',
119_918_u32 => 'G',
119_919_u32 => 'H',
119_920_u32 => 'I',
119_921_u32 => 'J',
119_922_u32 => 'K',
119_923_u32 => 'L',
119_924_u32 => 'M',
119_925_u32 => 'N',
119_926_u32 => 'O',
119_927_u32 => 'P',
119_928_u32 => 'Q',
119_929_u32 => 'R',
119_930_u32 => 'S',
119_931_u32 => 'T',
119_932_u32 => 'U',
119_933_u32 => 'V',
119_934_u32 => 'W',
119_935_u32 => 'X',
119_936_u32 => 'Y',
119_937_u32 => 'Z',
119_938_u32 => 'a',
119_939_u32 => 'b',
119_940_u32 => 'c',
119_941_u32 => 'd',
119_942_u32 => 'e',
119_943_u32 => 'f',
119_944_u32 => 'g',
119_945_u32 => 'h',
119_946_u32 => 'i',
119_947_u32 => 'j',
119_948_u32 => 'k',
119_949_u32 => 'l',
119_951_u32 => 'n',
119_952_u32 => 'o',
119_953_u32 => 'p',
119_954_u32 => 'q',
119_955_u32 => 'r',
119_956_u32 => 's',
119_957_u32 => 't',
119_958_u32 => 'u',
119_959_u32 => 'v',
119_960_u32 => 'w',
119_961_u32 => 'x',
119_962_u32 => 'y',
119_963_u32 => 'z',
119_964_u32 => 'A',
119_966_u32 => 'C',
119_967_u32 => 'D',
119_970_u32 => 'G',
119_973_u32 => 'J',
119_974_u32 => 'K',
119_977_u32 => 'N',
119_978_u32 => 'O',
119_979_u32 => 'P',
119_980_u32 => 'Q',
119_982_u32 => 'S',
119_983_u32 => 'T',
119_984_u32 => 'U',
119_985_u32 => 'V',
119_986_u32 => 'W',
119_987_u32 => 'X',
119_988_u32 => 'Y',
119_989_u32 => 'Z',
119_990_u32 => 'a',
119_991_u32 => 'b',
119_992_u32 => 'c',
119_993_u32 => 'd',
119_995_u32 => 'f',
119_997_u32 => 'h',
119_998_u32 => 'i',
119_999_u32 => 'j',
120_000_u32 => 'k',
120_001_u32 => 'l',
120_003_u32 => 'n',
120_005_u32 => 'p',
120_006_u32 => 'q',
120_007_u32 => 'r',
120_008_u32 => 's',
120_009_u32 => 't',
120_010_u32 => 'u',
120_011_u32 => 'v',
120_012_u32 => 'w',
120_013_u32 => 'x',
120_014_u32 => 'y',
120_015_u32 => 'z',
120_016_u32 => 'A',
120_017_u32 => 'B',
120_018_u32 => 'C',
120_019_u32 => 'D',
120_020_u32 => 'E',
120_021_u32 => 'F',
120_022_u32 => 'G',
120_023_u32 => 'H',
120_024_u32 => 'I',
120_025_u32 => 'J',
120_026_u32 => 'K',
120_027_u32 => 'L',
120_028_u32 => 'M',
120_029_u32 => 'N',
120_030_u32 => 'O',
120_031_u32 => 'P',
120_032_u32 => 'Q',
120_033_u32 => 'R',
120_034_u32 => 'S',
120_035_u32 => 'T',
120_036_u32 => 'U',
120_037_u32 => 'V',
120_038_u32 => 'W',
120_039_u32 => 'X',
120_040_u32 => 'Y',
120_041_u32 => 'Z',
120_042_u32 => 'a',
120_043_u32 => 'b',
120_044_u32 => 'c',
120_045_u32 => 'd',
120_046_u32 => 'e',
120_047_u32 => 'f',
120_048_u32 => 'g',
120_049_u32 => 'h',
120_050_u32 => 'i',
120_051_u32 => 'j',
120_052_u32 => 'k',
120_053_u32 => 'l',
120_055_u32 => 'n',
120_056_u32 => 'o',
120_057_u32 => 'p',
120_058_u32 => 'q',
120_059_u32 => 'r',
120_060_u32 => 's',
120_061_u32 => 't',
120_062_u32 => 'u',
120_063_u32 => 'v',
120_064_u32 => 'w',
120_065_u32 => 'x',
120_066_u32 => 'y',
120_067_u32 => 'z',
120_068_u32 => 'A',
120_069_u32 => 'B',
120_071_u32 => 'D',
120_072_u32 => 'E',
120_073_u32 => 'F',
120_074_u32 => 'G',
120_077_u32 => 'J',
120_078_u32 => 'K',
120_079_u32 => 'L',
120_080_u32 => 'M',
120_081_u32 => 'N',
120_082_u32 => 'O',
120_083_u32 => 'P',
120_084_u32 => 'Q',
120_086_u32 => 'S',
120_087_u32 => 'T',
120_088_u32 => 'U',
120_089_u32 => 'V',
120_090_u32 => 'W',
120_091_u32 => 'X',
120_092_u32 => 'Y',
120_094_u32 => 'a',
120_095_u32 => 'b',
120_096_u32 => 'c',
120_097_u32 => 'd',
120_098_u32 => 'e',
120_099_u32 => 'f',
120_100_u32 => 'g',
120_101_u32 => 'h',
120_102_u32 => 'i',
120_103_u32 => 'j',
120_104_u32 => 'k',
120_105_u32 => 'I',
120_107_u32 => 'n',
120_108_u32 => 'o',
120_109_u32 => 'p',
120_110_u32 => 'q',
120_111_u32 => 'r',
120_112_u32 => 's',
120_113_u32 => 't',
120_114_u32 => 'u',
120_115_u32 => 'v',
120_116_u32 => 'w',
120_117_u32 => 'x',
120_118_u32 => 'y',
120_119_u32 => 'z',
120_120_u32 => 'A',
120_121_u32 => 'B',
120_123_u32 => 'D',
120_124_u32 => 'E',
120_125_u32 => 'F',
120_126_u32 => 'G',
120_128_u32 => 'I',
120_129_u32 => 'J',
120_130_u32 => 'K',
120_131_u32 => 'L',
120_132_u32 => 'M',
120_134_u32 => 'O',
120_138_u32 => 'S',
120_139_u32 => 'T',
120_140_u32 => 'U',
120_141_u32 => 'V',
120_142_u32 => 'W',
120_143_u32 => 'X',
120_144_u32 => 'Y',
120_146_u32 => 'a',
120_147_u32 => 'b',
120_148_u32 => 'c',
120_149_u32 => 'd',
120_150_u32 => 'e',
120_151_u32 => 'f',
120_152_u32 => 'g',
120_153_u32 => 'h',
120_154_u32 => 'i',
120_155_u32 => 'j',
120_156_u32 => 'k',
120_157_u32 => 'I',
120_159_u32 => 'n',
120_160_u32 => 'o',
120_161_u32 => 'p',
120_162_u32 => 'q',
120_163_u32 => 'r',
120_164_u32 => 's',
120_165_u32 => 't',
120_166_u32 => 'u',
120_167_u32 => 'v',
120_168_u32 => 'w',
120_169_u32 => 'x',
120_170_u32 => 'y',
120_171_u32 => 'z',
120_172_u32 => 'A',
120_173_u32 => 'B',
120_174_u32 => 'C',
120_175_u32 => 'D',
120_176_u32 => 'E',
120_177_u32 => 'F',
120_178_u32 => 'G',
120_179_u32 => 'H',
120_180_u32 => 'I',
120_181_u32 => 'J',
120_182_u32 => 'K',
120_183_u32 => 'L',
120_184_u32 => 'M',
120_185_u32 => 'N',
120_186_u32 => 'O',
120_187_u32 => 'P',
120_188_u32 => 'Q',
120_189_u32 => 'R',
120_190_u32 => 'S',
120_191_u32 => 'T',
120_192_u32 => 'U',
120_193_u32 => 'V',
120_194_u32 => 'W',
120_195_u32 => 'X',
120_196_u32 => 'Y',
120_197_u32 => 'Z',
120_198_u32 => 'a',
120_199_u32 => 'b',
120_200_u32 => 'c',
120_201_u32 => 'd',
120_202_u32 => 'e',
120_203_u32 => 'f',
120_204_u32 => 'g',
120_205_u32 => 'h',
120_206_u32 => 'i',
120_207_u32 => 'j',
120_208_u32 => 'k',
120_209_u32 => 'I',
120_211_u32 => 'n',
120_212_u32 => 'o',
120_213_u32 => 'p',
120_214_u32 => 'q',
120_215_u32 => 'r',
120_216_u32 => 's',
120_217_u32 => 't',
120_218_u32 => 'u',
120_219_u32 => 'v',
120_220_u32 => 'w',
120_221_u32 => 'x',
120_222_u32 => 'y',
120_223_u32 => 'z',
120_224_u32 => 'A',
120_225_u32 => 'B',
120_226_u32 => 'C',
120_227_u32 => 'D',
120_228_u32 => 'E',
120_229_u32 => 'F',
120_230_u32 => 'G',
120_231_u32 => 'H',
120_232_u32 => 'I',
120_233_u32 => 'J',
120_234_u32 => 'K',
120_235_u32 => 'L',
120_236_u32 => 'M',
120_237_u32 => 'N',
120_238_u32 => 'O',
120_239_u32 => 'P',
120_240_u32 => 'Q',
120_241_u32 => 'R',
120_242_u32 => 'S',
120_243_u32 => 'T',
120_244_u32 => 'U',
120_245_u32 => 'V',
120_246_u32 => 'W',
120_247_u32 => 'X',
120_248_u32 => 'Y',
120_249_u32 => 'Z',
120_250_u32 => 'a',
120_251_u32 => 'b',
120_252_u32 => 'c',
120_253_u32 => 'd',
120_254_u32 => 'e',
120_255_u32 => 'f',
120_256_u32 => 'g',
120_257_u32 => 'h',
120_258_u32 => 'i',
120_259_u32 => 'j',
120_260_u32 => 'k',
120_261_u32 => 'I',
120_263_u32 => 'n',
120_264_u32 => 'o',
120_265_u32 => 'p',
120_266_u32 => 'q',
120_267_u32 => 'r',
120_268_u32 => 's',
120_269_u32 => 't',
120_270_u32 => 'u',
120_271_u32 => 'v',
120_272_u32 => 'w',
120_273_u32 => 'x',
120_274_u32 => 'y',
120_275_u32 => 'z',
120_276_u32 => 'A',
120_277_u32 => 'B',
120_278_u32 => 'C',
120_279_u32 => 'D',
120_280_u32 => 'E',
120_281_u32 => 'F',
120_282_u32 => 'G',
120_283_u32 => 'H',
120_284_u32 => 'I',
120_285_u32 => 'J',
120_286_u32 => 'K',
120_287_u32 => 'L',
120_288_u32 => 'M',
120_289_u32 => 'N',
120_290_u32 => 'O',
120_291_u32 => 'P',
120_292_u32 => 'Q',
120_293_u32 => 'R',
120_294_u32 => 'S',
120_295_u32 => 'T',
120_296_u32 => 'U',
120_297_u32 => 'V',
120_298_u32 => 'W',
120_299_u32 => 'X',
120_300_u32 => 'Y',
120_301_u32 => 'Z',
120_302_u32 => 'a',
120_303_u32 => 'b',
120_304_u32 => 'c',
120_305_u32 => 'd',
120_306_u32 => 'e',
120_307_u32 => 'f',
120_308_u32 => 'g',
120_309_u32 => 'h',
120_310_u32 => 'i',
120_311_u32 => 'j',
120_312_u32 => 'k',
120_313_u32 => 'I',
120_315_u32 => 'n',
120_316_u32 => 'o',
120_317_u32 => 'p',
120_318_u32 => 'q',
120_319_u32 => 'r',
120_320_u32 => 's',
120_321_u32 => 't',
120_322_u32 => 'u',
120_323_u32 => 'v',
120_324_u32 => 'w',
120_325_u32 => 'x',
120_326_u32 => 'y',
120_327_u32 => 'z',
120_328_u32 => 'A',
120_329_u32 => 'B',
120_330_u32 => 'C',
120_331_u32 => 'D',
120_332_u32 => 'E',
120_333_u32 => 'F',
120_334_u32 => 'G',
120_335_u32 => 'H',
120_336_u32 => 'I',
120_337_u32 => 'J',
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | true |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/starmap_zip.rs | crates/ruff_linter/src/rules/ruff/rules/starmap_zip.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::PythonVersion;
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::{Expr, ExprCall, token::parenthesized_range};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `itertools.starmap` calls where the second argument is a `zip` call.
///
/// ## Why is this bad?
/// `zip`-ping iterables only to unpack them later from within `starmap` is unnecessary.
/// For such cases, `map()` should be used instead.
///
/// ## Example
///
/// ```python
/// from itertools import starmap
///
///
/// starmap(func, zip(a, b))
/// starmap(func, zip(a, b, strict=True))
/// ```
///
/// Use instead:
///
/// ```python
/// map(func, a, b)
/// map(func, a, b, strict=True) # 3.14+
/// ```
///
/// ## Fix safety
///
/// This rule's fix is marked as unsafe if the `starmap` or `zip` expressions contain comments that
/// would be deleted by applying the fix. Otherwise, the fix can be applied safely.
///
/// ## Fix availability
///
/// This rule will emit a diagnostic but not suggest a fix if `map` has been shadowed from its
/// builtin binding.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct StarmapZip;
impl Violation for StarmapZip {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`itertools.starmap` called on `zip` iterable".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Use `map` instead".to_string())
}
}
/// RUF058
pub(crate) fn starmap_zip(checker: &Checker, call: &ExprCall) {
let semantic = checker.semantic();
if !call.arguments.keywords.is_empty() {
return;
}
let [_map_func, Expr::Call(iterable_call)] = &*call.arguments.args else {
return;
};
let keywords = &iterable_call.arguments.keywords;
match checker.target_version().cmp(&PythonVersion::PY314) {
// Keyword arguments not supported for `map` before Python 3.14
std::cmp::Ordering::Less => {
if !keywords.is_empty() {
return;
}
}
// Only supported keyword argument is `strict` starting in 3.14
std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => {
if keywords.len() > 1 {
return;
}
if keywords.len() == 1 && iterable_call.arguments.find_keyword("strict").is_none() {
return;
}
}
}
let positionals = &iterable_call.arguments.args;
// `zip(*a)` where `a` is empty is valid, but `map(_, *a)` isn't.
if !positionals.is_empty() && positionals.iter().all(Expr::is_starred_expr) {
return;
}
if !semantic
.resolve_qualified_name(&call.func)
.is_some_and(|it| matches!(it.segments(), ["itertools", "starmap"]))
{
return;
}
if !semantic.match_builtin_expr(&iterable_call.func, "zip") {
return;
}
let mut diagnostic = checker.report_diagnostic(StarmapZip, call.range);
if let Some(fix) = replace_with_map(call, iterable_call, checker) {
diagnostic.set_fix(fix);
}
}
/// Replace the `starmap` call with a call to the `map` builtin, if `map` has not been shadowed.
fn replace_with_map(starmap: &ExprCall, zip: &ExprCall, checker: &Checker) -> Option<Fix> {
if !checker.semantic().has_builtin_binding("map") {
return None;
}
let change_func_to_map = Edit::range_replacement("map".to_string(), starmap.func.range());
let mut remove_zip = vec![];
let full_zip_range =
parenthesized_range(zip.into(), starmap.into(), checker.tokens()).unwrap_or(zip.range());
// Delete any parentheses around the `zip` call to prevent that the argument turns into a tuple.
remove_zip.push(Edit::range_deletion(TextRange::new(
full_zip_range.start(),
zip.start(),
)));
let full_zip_func_range = parenthesized_range((&zip.func).into(), zip.into(), checker.tokens())
.unwrap_or(zip.func.range());
// Delete the `zip` callee
remove_zip.push(Edit::range_deletion(full_zip_func_range));
// Delete the `(` from the `zip(...)` call
remove_zip.push(Edit::range_deletion(zip.arguments.l_paren_range()));
// `zip` can be called without arguments but `map` can't.
if zip.arguments.is_empty() {
remove_zip.push(Edit::insertion("[]".to_string(), zip.arguments.start()));
}
let after_zip = checker.tokens().after(full_zip_range.end());
// Remove any trailing commas after the `zip` call to avoid multiple trailing commas
// if the iterable has a trailing comma.
if let Some(trailing_comma) = after_zip.iter().find(|token| !token.kind().is_trivia()) {
if trailing_comma.kind() == TokenKind::Comma {
remove_zip.push(Edit::range_deletion(trailing_comma.range()));
}
}
// Delete the `)` from the `zip(...)` call
remove_zip.push(Edit::range_deletion(zip.arguments.r_paren_range()));
// Delete any trailing parentheses wrapping the `zip` call.
remove_zip.push(Edit::range_deletion(TextRange::new(
zip.end(),
full_zip_range.end(),
)));
let comment_ranges = checker.comment_ranges();
let applicability = if comment_ranges.intersects(starmap.func.range())
|| comment_ranges.intersects(full_zip_range)
{
Applicability::Unsafe
} else {
Applicability::Safe
};
Some(Fix::applicable_edits(
change_func_to_map,
remove_zip,
applicability,
))
}
| 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/ruff/rules/unnecessary_regular_expression.rs | crates/ruff_linter/src/rules/ruff/rules/unnecessary_regular_expression.rs | use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{
Arguments, CmpOp, Expr, ExprAttribute, ExprBytesLiteral, ExprCall, ExprCompare, ExprContext,
ExprStringLiteral, ExprUnaryOp, Identifier, UnaryOp,
};
use ruff_python_semantic::analyze::typing::find_binding_value;
use ruff_python_semantic::{Modules, SemanticModel};
use ruff_text_size::TextRange;
use crate::checkers::ast::Checker;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
///
/// Checks for uses of the `re` module that can be replaced with builtin `str` methods.
///
/// ## Why is this bad?
///
/// Performing checks on strings directly can make the code simpler, may require
/// less escaping, and will often be faster.
///
/// ## Example
///
/// ```python
/// re.sub("abc", "", s)
/// ```
///
/// Use instead:
///
/// ```python
/// s.replace("abc", "")
/// ```
///
/// ## Details
///
/// The rule reports the following calls when the first argument to the call is
/// a plain string literal, and no additional flags are passed:
///
/// - `re.sub`
/// - `re.match`
/// - `re.search`
/// - `re.fullmatch`
/// - `re.split`
///
/// For `re.sub`, the `repl` (replacement) argument must also be a string literal,
/// not a function. For `re.match`, `re.search`, and `re.fullmatch`, the return
/// value must also be used only for its truth value.
///
/// ## Fix safety
///
/// This rule's fix is marked as unsafe if the affected expression contains comments. Otherwise,
/// the fix can be applied safely.
///
/// ## References
/// - [Python Regular Expression HOWTO: Common Problems - Use String Methods](https://docs.python.org/3/howto/regex.html#use-string-methods)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.8.1")]
pub(crate) struct UnnecessaryRegularExpression {
replacement: Option<String>,
}
impl Violation for UnnecessaryRegularExpression {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Plain string pattern passed to `re` function".to_string()
}
fn fix_title(&self) -> Option<String> {
Some(format!("Replace with `{}`", self.replacement.as_ref()?))
}
}
const METACHARACTERS: [char; 12] = ['.', '^', '$', '*', '+', '?', '{', '[', '\\', '|', '(', ')'];
const ESCAPABLE_SINGLE_CHARACTERS: &str = "abfnrtv";
/// RUF055
pub(crate) fn unnecessary_regular_expression(checker: &Checker, call: &ExprCall) {
// adapted from unraw_re_pattern
let semantic = checker.semantic();
if !semantic.seen_module(Modules::RE) {
return;
}
let Some(qualified_name) = semantic.resolve_qualified_name(&call.func) else {
return;
};
let ["re", func] = qualified_name.segments() else {
return;
};
// skip calls with more than `pattern` and `string` arguments (and `repl`
// for `sub`)
let Some(re_func) = ReFunc::from_call_expr(semantic, call, func) else {
return;
};
// For now, restrict this rule to string literals and variables that can be resolved to literals
let Some(literal) = resolve_literal(re_func.pattern, semantic) else {
return;
};
// For now, reject any regex metacharacters. Compare to the complete list
// from https://docs.python.org/3/howto/regex.html#matching-characters
let has_metacharacters = match &literal {
Literal::Str(str_lit) => str_lit.value.to_str().contains(METACHARACTERS),
Literal::Bytes(bytes_lit) => bytes_lit
.value
.iter()
.any(|part| part.iter().any(|&b| METACHARACTERS.contains(&(b as char)))),
};
if has_metacharacters {
return;
}
// Now we know the pattern is a string literal with no metacharacters, so
// we can proceed with the str method replacement.
let new_expr = re_func.replacement();
let repl = new_expr.map(|expr| checker.generator().expr(&expr));
let mut diagnostic = checker.report_diagnostic(
UnnecessaryRegularExpression {
replacement: repl.clone(),
},
re_func.range,
);
if let Some(repl) = repl {
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(repl, re_func.range),
if checker.comment_ranges().intersects(re_func.range) {
Applicability::Unsafe
} else {
Applicability::Safe
},
));
}
}
/// The `re` functions supported by this rule.
#[derive(Debug)]
enum ReFuncKind<'a> {
// Only `Some` if it's a fixable `re.sub()` call
Sub { repl: Option<&'a Expr> },
Match,
Search,
Fullmatch,
Split,
}
#[derive(Debug)]
struct ReFunc<'a> {
kind: ReFuncKind<'a>,
pattern: &'a Expr,
string: &'a Expr,
comparison_to_none: Option<ComparisonToNone>,
range: TextRange,
}
impl<'a> ReFunc<'a> {
fn from_call_expr(
semantic: &'a SemanticModel,
call: &'a ExprCall,
func_name: &str,
) -> Option<Self> {
// the proposed fixes for match, search, and fullmatch rely on the
// return value only being used for its truth value or being compared to None
let comparison_to_none = get_comparison_to_none(semantic);
let in_truthy_context = semantic.in_boolean_test() || comparison_to_none.is_some();
let (comparison_to_none, range) = match comparison_to_none {
Some((cmp, range)) => (Some(cmp), range),
None => (None, call.range),
};
match (func_name, call.arguments.len()) {
// `split` is the safest of these to fix, as long as metacharacters
// have already been filtered out from the `pattern`
("split", 2) => Some(ReFunc {
kind: ReFuncKind::Split,
pattern: call.arguments.find_argument_value("pattern", 0)?,
string: call.arguments.find_argument_value("string", 1)?,
comparison_to_none,
range,
}),
// `sub` is only safe to fix if `repl` is a string. `re.sub` also
// allows it to be a function, which will *not* work in the str
// version
("sub", 3) => {
let repl = call.arguments.find_argument_value("repl", 1)?;
let lit = resolve_literal(repl, semantic)?;
let mut fixable = true;
match lit {
Literal::Str(lit_str) => {
// Perform escape analysis for replacement literals.
for (c, next) in lit_str.value.to_str().chars().tuple_windows() {
// `\\0` (or any other ASCII digit) and `\\g` have special meaning in `repl` strings.
// Meanwhile, nearly all other escapes of ASCII letters in a `repl` string causes
// `re.PatternError` to be raised at runtime.
//
// If we see that the escaped character is an alphanumeric ASCII character,
// we should only emit a diagnostic suggesting to replace the `re.sub()` call with
// `str.replace`if we can detect that the escaped character is one that is both
// valid in a `repl` string *and* does not have any special meaning in a REPL string.
//
// It's out of scope for this rule to change invalid `re.sub()` calls into something
// that would not raise an exception at runtime. They should be left as-is.
if c == '\\' && next.is_ascii_alphanumeric() {
if ESCAPABLE_SINGLE_CHARACTERS.contains(next) {
fixable = false;
} else {
return None;
}
}
}
}
Literal::Bytes(lit_bytes) => {
for part in &lit_bytes.value {
for (byte, next) in part.iter().copied().tuple_windows() {
if byte == b'\\' && (next as char).is_ascii_alphanumeric() {
if ESCAPABLE_SINGLE_CHARACTERS.contains(next as char) {
fixable = false;
} else {
return None;
}
}
}
}
}
}
Some(ReFunc {
kind: ReFuncKind::Sub {
repl: fixable.then_some(repl),
},
pattern: call.arguments.find_argument_value("pattern", 0)?,
string: call.arguments.find_argument_value("string", 2)?,
comparison_to_none,
range,
})
}
("match", 2) if in_truthy_context => Some(ReFunc {
kind: ReFuncKind::Match,
pattern: call.arguments.find_argument_value("pattern", 0)?,
string: call.arguments.find_argument_value("string", 1)?,
comparison_to_none,
range,
}),
("search", 2) if in_truthy_context => Some(ReFunc {
kind: ReFuncKind::Search,
pattern: call.arguments.find_argument_value("pattern", 0)?,
string: call.arguments.find_argument_value("string", 1)?,
comparison_to_none,
range,
}),
("fullmatch", 2) if in_truthy_context => Some(ReFunc {
kind: ReFuncKind::Fullmatch,
pattern: call.arguments.find_argument_value("pattern", 0)?,
string: call.arguments.find_argument_value("string", 1)?,
comparison_to_none,
range,
}),
_ => None,
}
}
/// Get replacement for the call or parent expression.
///
/// Examples:
/// `re.search("abc", s) is None` => `"abc" not in s`
/// `re.search("abc", s)` => `"abc" in s`
fn replacement(&self) -> Option<Expr> {
match (&self.kind, &self.comparison_to_none) {
// string.replace(pattern, repl)
(ReFuncKind::Sub { repl }, _) => repl
.cloned()
.map(|repl| self.method_expr("replace", vec![self.pattern.clone(), repl])),
// string.split(pattern)
(ReFuncKind::Split, _) => Some(self.method_expr("split", vec![self.pattern.clone()])),
// pattern in string
(ReFuncKind::Search, None | Some(ComparisonToNone::IsNot)) => {
Some(ReFunc::compare_expr(self.pattern, CmpOp::In, self.string))
}
// pattern not in string
(ReFuncKind::Search, Some(ComparisonToNone::Is)) => Some(ReFunc::compare_expr(
self.pattern,
CmpOp::NotIn,
self.string,
)),
// string.startswith(pattern)
(ReFuncKind::Match, None | Some(ComparisonToNone::IsNot)) => {
Some(self.method_expr("startswith", vec![self.pattern.clone()]))
}
// not string.startswith(pattern)
(ReFuncKind::Match, Some(ComparisonToNone::Is)) => {
let expr = self.method_expr("startswith", vec![self.pattern.clone()]);
let negated_expr = Expr::UnaryOp(ExprUnaryOp {
op: UnaryOp::Not,
operand: Box::new(expr),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
Some(negated_expr)
}
// string == pattern
(ReFuncKind::Fullmatch, None | Some(ComparisonToNone::IsNot)) => {
Some(ReFunc::compare_expr(self.string, CmpOp::Eq, self.pattern))
}
// string != pattern
(ReFuncKind::Fullmatch, Some(ComparisonToNone::Is)) => Some(ReFunc::compare_expr(
self.string,
CmpOp::NotEq,
self.pattern,
)),
}
}
/// Return a new compare expr of the form `left op right`
fn compare_expr(left: &Expr, op: CmpOp, right: &Expr) -> Expr {
Expr::Compare(ExprCompare {
left: Box::new(left.clone()),
ops: Box::new([op]),
comparators: Box::new([right.clone()]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
}
/// Return a new method call expression on `self.string` with `args` like
/// `self.string.method(args...)`
fn method_expr(&self, method: &str, args: Vec<Expr>) -> Expr {
let method = Expr::Attribute(ExprAttribute {
value: Box::new(self.string.clone()),
attr: Identifier::new(method, TextRange::default()),
ctx: ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
Expr::Call(ExprCall {
func: Box::new(method),
arguments: Arguments {
args: args.into_boxed_slice(),
keywords: Box::new([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
})
}
}
/// A literal that can be either a string or a bytes literal.
enum Literal<'a> {
Str(&'a ExprStringLiteral),
Bytes(&'a ExprBytesLiteral),
}
/// Try to resolve `name` to either a string or bytes literal in `semantic`.
fn resolve_literal<'a>(name: &'a Expr, semantic: &'a SemanticModel) -> Option<Literal<'a>> {
if let Some(str_lit) = resolve_string_literal(name, semantic) {
return Some(Literal::Str(str_lit));
}
if let Some(bytes_lit) = resolve_bytes_literal(name, semantic) {
return Some(Literal::Bytes(bytes_lit));
}
None
}
/// Try to resolve `name` to an [`ExprBytesLiteral`] in `semantic`.
fn resolve_bytes_literal<'a>(
name: &'a Expr,
semantic: &'a SemanticModel,
) -> Option<&'a ExprBytesLiteral> {
if name.is_bytes_literal_expr() {
return name.as_bytes_literal_expr();
}
if let Some(name_expr) = name.as_name_expr() {
let binding = semantic.binding(semantic.only_binding(name_expr)?);
let value = find_binding_value(binding, semantic)?;
if value.is_bytes_literal_expr() {
return value.as_bytes_literal_expr();
}
}
None
}
/// Try to resolve `name` to an [`ExprStringLiteral`] in `semantic`.
fn resolve_string_literal<'a>(
name: &'a Expr,
semantic: &'a SemanticModel,
) -> Option<&'a ExprStringLiteral> {
if name.is_string_literal_expr() {
return name.as_string_literal_expr();
}
if let Some(name_expr) = name.as_name_expr() {
let binding = semantic.binding(semantic.only_binding(name_expr)?);
let value = find_binding_value(binding, semantic)?;
if value.is_string_literal_expr() {
return value.as_string_literal_expr();
}
}
None
}
#[derive(Clone, Copy, Debug)]
enum ComparisonToNone {
Is,
IsNot,
}
/// If the regex call is compared to `None`, return the comparison and its range.
/// Example: `re.search("abc", s) is None`
fn get_comparison_to_none(semantic: &SemanticModel) -> Option<(ComparisonToNone, TextRange)> {
let parent_expr = semantic.current_expression_parent()?;
let Expr::Compare(ExprCompare {
ops,
comparators,
range,
..
}) = parent_expr
else {
return None;
};
let Some(Expr::NoneLiteral(_)) = comparators.first() else {
return None;
};
match ops.as_ref() {
[CmpOp::Is] => Some((ComparisonToNone::Is, *range)),
[CmpOp::IsNot] => Some((ComparisonToNone::IsNot, *range)),
_ => 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/ruff/rules/unused_unpacked_variable.rs | crates/ruff_linter/src/rules/ruff/rules/unused_unpacked_variable.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::Binding;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::renamer::ShadowedKind;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for the presence of unused variables in unpacked assignments.
///
/// ## Why is this bad?
/// A variable that is defined but never used can confuse readers.
///
/// If a variable is intentionally defined-but-not-used, it should be
/// prefixed with an underscore, or some other value that adheres to the
/// [`lint.dummy-variable-rgx`] pattern.
///
/// ## Example
///
/// ```python
/// def get_pair():
/// return 1, 2
///
///
/// def foo():
/// x, y = get_pair()
/// return x
/// ```
///
/// Use instead:
///
/// ```python
/// def foo():
/// x, _ = get_pair()
/// return x
/// ```
///
/// ## See also
///
/// This rule applies only to unpacked assignments. For regular assignments, see
/// [`unused-variable`][F841].
///
/// ## Options
/// - `lint.dummy-variable-rgx`
///
/// [F841]: https://docs.astral.sh/ruff/rules/unused-variable/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.13.0")]
pub(crate) struct UnusedUnpackedVariable {
pub name: String,
}
impl Violation for UnusedUnpackedVariable {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UnusedUnpackedVariable { name } = self;
format!("Unpacked variable `{name}` is never used")
}
fn fix_title(&self) -> Option<String> {
Some("Prefix it with an underscore or any other dummy variable pattern".to_string())
}
}
/// Generate a [`Edit`] to remove an unused variable assignment to a [`Binding`].
fn remove_unused_variable(binding: &Binding, checker: &Checker) -> Option<Fix> {
let node_id = binding.source?;
let isolation = Checker::isolation(checker.semantic().parent_statement_id(node_id));
let name = binding.name(checker.source());
let renamed = format!("_{name}");
if ShadowedKind::new(binding, &renamed, checker).shadows_any() {
return None;
}
if checker.settings().dummy_variable_rgx.is_match(&renamed) {
let edit = Edit::range_replacement(renamed, binding.range());
return Some(Fix::unsafe_edit(edit).isolate(isolation));
}
None
}
/// RUF059
pub(crate) fn unused_unpacked_variable(checker: &Checker, name: &str, binding: &Binding) {
if !binding.is_unpacked_assignment() {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnusedUnpackedVariable {
name: name.to_string(),
},
binding.range(),
);
if let Some(fix) = remove_unused_variable(binding, checker) {
diagnostic.set_fix(fix);
}
// Add Unnecessary tag for unused unpacked variables
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary);
}
| 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/ruff/rules/missing_fstring_syntax.rs | crates/ruff_linter/src/rules/ruff/rules/missing_fstring_syntax.rs | use memchr::memchr2_iter;
use rustc_hash::FxHashSet;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_literal::format::FormatSpec;
use ruff_python_parser::parse_expression;
use ruff_python_semantic::analyze::logging::is_logger_candidate;
use ruff_python_semantic::{Modules, SemanticModel, TypingOnlyBindingsStatus};
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::rules::fastapi::rules::is_fastapi_route_call;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Searches for strings that look like they were meant to be f-strings, but are missing an `f` prefix.
///
/// ## Why is this bad?
/// Expressions inside curly braces are only evaluated if the string has an `f` prefix.
///
/// ## Details
///
/// There are many possible string literals which are not meant to be f-strings
/// despite containing f-string-like syntax. As such, this lint ignores all strings
/// where one of the following conditions applies:
///
/// 1. The string is a standalone expression. For example, the rule ignores all docstrings.
/// 2. The string is part of a function call with argument names that match at least one variable
/// (for example: `format("Message: {value}", value="Hello World")`)
/// 3. The string (or a parent expression of the string) has a direct method call on it
/// (for example: `"{value}".format(...)`)
/// 4. The string has no `{...}` expression sections, or uses invalid f-string syntax.
/// 5. The string references variables that are not in scope, or it doesn't capture variables at all.
/// 6. Any format specifiers in the potential f-string are invalid.
/// 7. The string is part of a function call that is known to expect a template string rather than an
/// evaluated f-string: for example, a [`logging`][logging] call, a [`gettext`][gettext] call,
/// or a [FastAPI path].
///
/// ## Example
///
/// ```python
/// name = "Sarah"
/// day_of_week = "Tuesday"
/// print("Hello {name}! It is {day_of_week} today!")
/// ```
///
/// Use instead:
/// ```python
/// name = "Sarah"
/// day_of_week = "Tuesday"
/// print(f"Hello {name}! It is {day_of_week} today!")
/// ```
///
/// ## Fix safety
///
/// This fix will always change the behavior of the program and, despite the precautions detailed
/// above, this may be undesired. As such the fix is always marked as unsafe.
///
/// ## Options
///
/// - `lint.logger-objects`
///
/// [logging]: https://docs.python.org/3/howto/logging-cookbook.html#using-particular-formatting-styles-throughout-your-application
/// [gettext]: https://docs.python.org/3/library/gettext.html
/// [FastAPI path]: https://fastapi.tiangolo.com/tutorial/path-params/
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.2.1")]
pub(crate) struct MissingFStringSyntax;
impl AlwaysFixableViolation for MissingFStringSyntax {
#[derive_message_formats]
fn message(&self) -> String {
r"Possible f-string without an `f` prefix".to_string()
}
fn fix_title(&self) -> String {
"Add `f` prefix".into()
}
}
/// RUF027
pub(crate) fn missing_fstring_syntax(checker: &Checker, literal: &ast::StringLiteral) {
let semantic = checker.semantic();
// fstrings are never correct as type definitions
if semantic.in_type_definition() {
return;
}
// we want to avoid statement expressions that are just a string literal.
// there's no reason to have standalone f-strings and this lets us avoid docstrings too
if let ast::Stmt::Expr(ast::StmtExpr { value, .. }) = semantic.current_statement() {
match value.as_ref() {
ast::Expr::StringLiteral(_) | ast::Expr::FString(_) => return,
_ => {}
}
}
let logger_objects = &checker.settings().logger_objects;
let fastapi_seen = semantic.seen_module(Modules::FASTAPI);
// We also want to avoid:
// - Expressions inside `gettext()` calls
// - Expressions passed to logging calls (since the `logging` module evaluates them lazily:
// https://docs.python.org/3/howto/logging-cookbook.html#using-particular-formatting-styles-throughout-your-application)
// - `fastAPI` paths: https://fastapi.tiangolo.com/tutorial/path-params/
// - Expressions where a method is immediately called on the string literal
if semantic
.current_expressions()
.filter_map(ast::Expr::as_call_expr)
.any(|call_expr| {
is_method_call_on_literal(call_expr, literal)
|| is_gettext(call_expr, semantic)
|| is_logger_candidate(&call_expr.func, semantic, logger_objects)
|| (fastapi_seen && is_fastapi_route_call(call_expr, semantic))
})
{
return;
}
if should_be_fstring(literal, checker.locator(), semantic) {
checker
.report_diagnostic(MissingFStringSyntax, literal.range())
.set_fix(fix_fstring_syntax(literal.range()));
}
}
/// Returns `true` if an expression appears to be a `gettext` call.
///
/// We want to avoid statement expressions and assignments related to aliases
/// of the gettext API.
///
/// See <https://docs.python.org/3/library/gettext.html> for details. When one
/// uses `_` to mark a string for translation, the tools look for these markers
/// and replace the original string with its translated counterpart. If the
/// string contains variable placeholders or formatting, it can complicate the
/// translation process, lead to errors or incorrect translations.
fn is_gettext(call_expr: &ast::ExprCall, semantic: &SemanticModel) -> bool {
let func = &*call_expr.func;
let short_circuit = match func {
ast::Expr::Name(ast::ExprName { id, .. }) => {
matches!(id.as_str(), "gettext" | "ngettext" | "_")
}
ast::Expr::Attribute(ast::ExprAttribute { attr, .. }) => {
matches!(attr.as_str(), "gettext" | "ngettext")
}
_ => false,
};
if short_circuit {
return true;
}
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["gettext", "gettext" | "ngettext"] | ["builtins", "_"]
)
})
}
/// Return `true` if `call_expr` is a method call on an [`ast::ExprStringLiteral`]
/// in which `literal` is one of the [`ast::StringLiteral`] parts.
///
/// For example: `expr` is a node representing the expression `"{foo}".format(foo="bar")`,
/// and `literal` is the node representing the string literal `"{foo}"`.
fn is_method_call_on_literal(call_expr: &ast::ExprCall, literal: &ast::StringLiteral) -> bool {
let ast::Expr::Attribute(ast::ExprAttribute { value, .. }) = &*call_expr.func else {
return false;
};
let ast::Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = &**value else {
return false;
};
value.as_slice().contains(literal)
}
/// Returns `true` if `literal` is likely an f-string with a missing `f` prefix.
/// See [`MissingFStringSyntax`] for the validation criteria.
fn should_be_fstring(
literal: &ast::StringLiteral,
locator: &Locator,
semantic: &SemanticModel,
) -> bool {
if !has_brackets(&literal.value) {
return false;
}
let fstring_expr = format!("f{}", locator.slice(literal));
let Ok(parsed) = parse_expression(&fstring_expr) else {
return false;
};
// Note: Range offsets for `value` are based on `fstring_expr`
let ast::Expr::FString(ast::ExprFString { value, .. }) = parsed.expr() else {
return false;
};
let mut arg_names = FxHashSet::default();
for expr in semantic
.current_expressions()
.filter_map(ast::Expr::as_call_expr)
{
let ast::Arguments { keywords, args, .. } = &expr.arguments;
for keyword in keywords {
if let Some(ident) = keyword.arg.as_ref() {
arg_names.insert(&ident.id);
}
}
for arg in args {
if let ast::Expr::Name(ast::ExprName { id, .. }) = arg {
arg_names.insert(id);
}
}
}
for f_string in value.f_strings() {
let mut has_name = false;
for element in f_string.elements.interpolations() {
if let ast::Expr::Name(ast::ExprName { id, .. }) = element.expression.as_ref() {
if arg_names.contains(id) {
return false;
}
if semantic
// the parsed expression nodes have incorrect ranges
// so we need to use the range of the literal for the
// lookup in order to get reasonable results.
.simulate_runtime_load_at_location_in_scope(
id,
literal.range(),
semantic.scope_id,
TypingOnlyBindingsStatus::Disallowed,
)
.is_none_or(|id| semantic.binding(id).kind.is_builtin())
{
return false;
}
has_name = true;
}
if let Some(spec) = &element.format_spec {
let spec = &fstring_expr[spec.range()];
if FormatSpec::parse(spec).is_err() {
return false;
}
}
}
if !has_name {
return false;
}
}
true
}
// fast check to disqualify any string literal without brackets
#[inline]
fn has_brackets(possible_fstring: &str) -> bool {
// this qualifies rare false positives like "{ unclosed bracket"
// but it's faster in the general case
memchr2_iter(b'{', b'}', possible_fstring.as_bytes())
.nth(1)
.is_some()
}
fn fix_fstring_syntax(range: TextRange) -> Fix {
Fix::unsafe_edit(Edit::insertion("f".into(), range.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/ruff/rules/mutable_dataclass_default.rs | crates/ruff_linter/src/rules/ruff/rules/mutable_dataclass_default.rs | use ruff_python_ast::{self as ast, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_semantic::analyze::typing::{is_immutable_annotation, is_mutable_expr};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::ruff::helpers::{dataclass_kind, is_class_var_annotation};
/// ## What it does
/// Checks for mutable default values in dataclass attributes.
///
/// ## Why is this bad?
/// Mutable default values share state across all instances of the dataclass.
/// This can lead to bugs when the attributes are changed in one instance, as
/// those changes will unexpectedly affect all other instances.
///
/// Instead of sharing mutable defaults, use the `field(default_factory=...)`
/// pattern.
///
/// If the default value is intended to be mutable, it must be annotated with
/// `typing.ClassVar`; otherwise, a `ValueError` will be raised.
///
/// ## Example
/// ```python
/// from dataclasses import dataclass
///
///
/// @dataclass
/// class A:
/// # A list without a `default_factory` or `ClassVar` annotation
/// # will raise a `ValueError`.
/// mutable_default: list[int] = []
/// ```
///
/// Use instead:
/// ```python
/// from dataclasses import dataclass, field
///
///
/// @dataclass
/// class A:
/// mutable_default: list[int] = field(default_factory=list)
/// ```
///
/// Or:
/// ```python
/// from dataclasses import dataclass
/// from typing import ClassVar
///
///
/// @dataclass
/// class A:
/// mutable_default: ClassVar[list[int]] = []
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.262")]
pub(crate) struct MutableDataclassDefault;
impl Violation for MutableDataclassDefault {
#[derive_message_formats]
fn message(&self) -> String {
"Do not use mutable default values for dataclass attributes".to_string()
}
}
/// RUF008
pub(crate) fn mutable_dataclass_default(checker: &Checker, class_def: &ast::StmtClassDef) {
let semantic = checker.semantic();
if dataclass_kind(class_def, semantic).is_none() {
return;
}
for statement in &class_def.body {
let Stmt::AnnAssign(ast::StmtAnnAssign {
annotation,
value: Some(value),
..
}) = statement
else {
continue;
};
if is_mutable_expr(value, checker.semantic())
&& !is_class_var_annotation(annotation, checker.semantic())
&& !is_immutable_annotation(annotation, checker.semantic(), &[])
{
checker.report_diagnostic(MutableDataclassDefault, value.range());
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/implicit_classvar_in_dataclass.rs | crates/ruff_linter/src/rules/ruff/rules/implicit_classvar_in_dataclass.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_dunder;
use ruff_python_ast::{Expr, ExprName, Stmt, StmtAssign, StmtClassDef};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::ruff::helpers::{DataclassKind, dataclass_kind};
/// ## What it does
/// Checks for implicit class variables in dataclasses.
///
/// Variables matching the [`lint.dummy-variable-rgx`] are excluded
/// from this rule.
///
/// ## Why is this bad?
/// Class variables are shared between all instances of that class.
/// In dataclasses, fields with no annotations at all
/// are implicitly considered class variables, and a `TypeError` is
/// raised if a user attempts to initialize an instance of the class
/// with this field.
///
///
/// ```python
/// @dataclass
/// class C:
/// a = 1
/// b: str = ""
///
/// C(a = 42) # TypeError: C.__init__() got an unexpected keyword argument 'a'
/// ```
///
/// ## Example
///
/// ```python
/// @dataclass
/// class C:
/// a = 1
/// ```
///
/// Use instead:
///
/// ```python
/// from typing import ClassVar
///
///
/// @dataclass
/// class C:
/// a: ClassVar[int] = 1
/// ```
///
/// ## Options
/// - [`lint.dummy-variable-rgx`]
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.9.7")]
pub(crate) struct ImplicitClassVarInDataclass;
impl Violation for ImplicitClassVarInDataclass {
#[derive_message_formats]
fn message(&self) -> String {
"Assignment without annotation found in dataclass body".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Use `ClassVar[...]`".to_string())
}
}
/// RUF045
pub(crate) fn implicit_class_var_in_dataclass(checker: &mut Checker, class_def: &StmtClassDef) {
let dataclass_kind = dataclass_kind(class_def, checker.semantic());
if !matches!(dataclass_kind, Some((DataclassKind::Stdlib, _))) {
return;
}
for statement in &class_def.body {
let Stmt::Assign(StmtAssign { targets, .. }) = statement else {
continue;
};
if targets.len() > 1 {
continue;
}
let target = targets.first().unwrap();
let Expr::Name(ExprName { id, .. }) = target else {
continue;
};
if checker.settings().dummy_variable_rgx.is_match(id.as_str()) {
continue;
}
if is_dunder(id.as_str()) {
continue;
}
checker.report_diagnostic(ImplicitClassVarInDataclass, 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/ruff/rules/unnecessary_literal_within_deque_call.rs | crates/ruff_linter/src/rules/ruff/rules/unnecessary_literal_within_deque_call.rs | use ruff_diagnostics::{Applicability, Edit};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_empty_f_string;
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for usages of `collections.deque` that have an empty iterable as the first argument.
///
/// ## Why is this bad?
/// It's unnecessary to use an empty literal as a deque's iterable, since this is already the default behavior.
///
/// ## Example
///
/// ```python
/// from collections import deque
///
/// queue = deque(set())
/// queue = deque([], 10)
/// ```
///
/// Use instead:
///
/// ```python
/// from collections import deque
///
/// queue = deque()
/// queue = deque(maxlen=10)
/// ```
///
/// ## Fix safety
///
/// The fix is marked as unsafe whenever it would delete comments present in the `deque` call or if
/// there are unrecognized arguments other than `iterable` and `maxlen`.
///
/// ## Fix availability
///
/// This rule's fix is unavailable if any starred arguments are present after the initial iterable.
///
/// ## References
/// - [Python documentation: `collections.deque`](https://docs.python.org/3/library/collections.html#collections.deque)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.9.0")]
pub(crate) struct UnnecessaryEmptyIterableWithinDequeCall {
has_maxlen: bool,
}
impl Violation for UnnecessaryEmptyIterableWithinDequeCall {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Unnecessary empty iterable within a deque call".to_string()
}
fn fix_title(&self) -> Option<String> {
let title = if self.has_maxlen {
"Replace with `deque(maxlen=...)`"
} else {
"Replace with `deque()`"
};
Some(title.to_string())
}
}
/// RUF037
pub(crate) fn unnecessary_literal_within_deque_call(checker: &Checker, deque: &ast::ExprCall) {
let ast::ExprCall {
func, arguments, ..
} = deque;
let Some(qualified) = checker.semantic().resolve_qualified_name(func) else {
return;
};
if !matches!(qualified.segments(), ["collections", "deque"]) || arguments.len() > 2 {
return;
}
let Some(iterable) = arguments.find_argument("iterable", 0) else {
return;
};
let maxlen = arguments.find_argument_value("maxlen", 1);
let is_empty_literal = match iterable.value() {
Expr::Dict(dict) => dict.is_empty(),
Expr::List(list) => list.is_empty(),
Expr::Tuple(tuple) => tuple.is_empty(),
Expr::Call(call) => {
checker
.semantic()
.resolve_builtin_symbol(&call.func)
// other lints should handle empty list/dict/tuple calls,
// but this means that the lint still applies before those are fixed
.is_some_and(|name| {
name == "set" || name == "list" || name == "dict" || name == "tuple"
})
&& call.arguments.is_empty()
}
Expr::StringLiteral(string) => string.value.is_empty(),
Expr::BytesLiteral(bytes) => bytes.value.is_empty(),
Expr::FString(fstring) => is_empty_f_string(fstring),
Expr::TString(tstring) => tstring.value.is_empty_iterable(),
_ => false,
};
if !is_empty_literal {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEmptyIterableWithinDequeCall {
has_maxlen: maxlen.is_some(),
},
deque.range,
);
// Return without a fix in the presence of a starred argument because we can't accurately
// generate the fix. If all of the arguments are unpacked (e.g. `deque(*([], 10))`), we will
// have already returned after the first `find_argument_value` call.
if deque.arguments.args.iter().any(Expr::is_starred_expr) {
return;
}
diagnostic.try_set_fix(|| fix_unnecessary_literal_in_deque(checker, iterable, deque, maxlen));
}
fn fix_unnecessary_literal_in_deque(
checker: &Checker,
iterable: ast::ArgOrKeyword,
deque: &ast::ExprCall,
maxlen: Option<&Expr>,
) -> anyhow::Result<Fix> {
// if `maxlen` is `Some`, we know there were exactly two arguments, and we can replace the whole
// call. otherwise, we only delete the `iterable` argument and leave the others untouched.
let edit = if let Some(maxlen) = maxlen {
let deque_name = checker.locator().slice(
parenthesized_range(deque.func.as_ref().into(), deque.into(), checker.tokens())
.unwrap_or(deque.func.range()),
);
let len_str = checker.locator().slice(maxlen);
let deque_str = format!("{deque_name}(maxlen={len_str})");
Edit::range_replacement(deque_str, deque.range)
} else {
remove_argument(
&iterable,
&deque.arguments,
Parentheses::Preserve,
checker.source(),
checker.tokens(),
)?
};
let has_comments = checker.comment_ranges().intersects(edit.range());
// we've already checked maxlen.is_some() && args != 2 above, so this is the only problematic
// case left
let unknown_arguments = maxlen.is_none() && deque.arguments.len() != 1;
let applicability = if has_comments || unknown_arguments {
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(Fix::applicable_edit(edit, applicability))
}
| 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/ruff/rules/test_rules.rs | crates/ruff_linter/src/rules/ruff/rules/test_rules.rs | /// Fake rules for testing Ruff's behavior
///
/// All of these rules should be assigned to the RUF9XX codes.
///
/// Implementing a new test rule involves:
///
/// - Writing an empty struct for the rule
/// - Adding to the rule registry
/// - Adding to the `TEST_RULES` constant
/// - Implementing `Violation` for the rule
/// - Implementing `TestRule` for the rule
/// - Adding a match arm in `linter::check_path`
///
/// Rules that provide a fix _must_ not raise unconditionally or the linter
/// will not converge.
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_trivia::CommentRanges;
use ruff_text_size::TextSize;
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::registry::Rule;
use crate::{Edit, Fix, FixAvailability, Violation};
/// Check if a comment exists anywhere in a given file
fn comment_exists(text: &str, locator: &Locator, comment_ranges: &CommentRanges) -> bool {
for range in comment_ranges {
let comment_text = locator.slice(range);
if text.trim_end() == comment_text {
return true;
}
}
false
}
pub(crate) const TEST_RULES: &[Rule] = &[
Rule::StableTestRule,
Rule::StableTestRuleSafeFix,
Rule::StableTestRuleUnsafeFix,
Rule::StableTestRuleDisplayOnlyFix,
Rule::PreviewTestRule,
Rule::DeprecatedTestRule,
Rule::AnotherDeprecatedTestRule,
Rule::RemovedTestRule,
Rule::AnotherRemovedTestRule,
Rule::RedirectedFromTestRule,
Rule::RedirectedToTestRule,
Rule::RedirectedFromPrefixTestRule,
Rule::PanicyTestRule,
];
pub(crate) trait TestRule {
fn diagnostic(locator: &Locator, comment_ranges: &CommentRanges, context: &LintContext);
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.0.0")]
pub(crate) struct StableTestRule;
impl Violation for StableTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a stable test rule.".to_string()
}
}
impl TestRule for StableTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(StableTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.0.0")]
pub(crate) struct StableTestRuleSafeFix;
impl Violation for StableTestRuleSafeFix {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a stable test rule with a safe fix.".to_string()
}
}
impl TestRule for StableTestRuleSafeFix {
fn diagnostic(locator: &Locator, comment_ranges: &CommentRanges, context: &LintContext) {
let comment = "# fix from stable-test-rule-safe-fix\n".to_string();
if !comment_exists(&comment, locator, comment_ranges) {
context
.report_diagnostic(StableTestRuleSafeFix, ruff_text_size::TextRange::default())
.set_fix(Fix::safe_edit(Edit::insertion(comment, TextSize::new(0))));
}
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.0.0")]
pub(crate) struct StableTestRuleUnsafeFix;
impl Violation for StableTestRuleUnsafeFix {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a stable test rule with an unsafe fix.".to_string()
}
}
impl TestRule for StableTestRuleUnsafeFix {
fn diagnostic(locator: &Locator, comment_ranges: &CommentRanges, context: &LintContext) {
let comment = "# fix from stable-test-rule-unsafe-fix\n".to_string();
if !comment_exists(&comment, locator, comment_ranges) {
context
.report_diagnostic(
StableTestRuleUnsafeFix,
ruff_text_size::TextRange::default(),
)
.set_fix(Fix::unsafe_edit(Edit::insertion(comment, TextSize::new(0))));
}
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.0.0")]
pub(crate) struct StableTestRuleDisplayOnlyFix;
impl Violation for StableTestRuleDisplayOnlyFix {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a stable test rule with a display only fix.".to_string()
}
}
impl TestRule for StableTestRuleDisplayOnlyFix {
fn diagnostic(locator: &Locator, comment_ranges: &CommentRanges, context: &LintContext) {
let comment = "# fix from stable-test-rule-display-only-fix\n".to_string();
if !comment_exists(&comment, locator, comment_ranges) {
context
.report_diagnostic(
StableTestRuleDisplayOnlyFix,
ruff_text_size::TextRange::default(),
)
.set_fix(Fix::display_only_edit(Edit::insertion(
comment,
TextSize::new(0),
)));
}
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.0.0")]
pub(crate) struct PreviewTestRule;
impl Violation for PreviewTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a preview test rule.".to_string()
}
}
impl TestRule for PreviewTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(PreviewTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(deprecated_since = "0.0.0")]
pub(crate) struct DeprecatedTestRule;
impl Violation for DeprecatedTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a deprecated test rule.".to_string()
}
}
impl TestRule for DeprecatedTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(DeprecatedTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(deprecated_since = "0.0.0")]
pub(crate) struct AnotherDeprecatedTestRule;
impl Violation for AnotherDeprecatedTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is another deprecated test rule.".to_string()
}
}
impl TestRule for AnotherDeprecatedTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(
AnotherDeprecatedTestRule,
ruff_text_size::TextRange::default(),
);
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.0.0")]
pub(crate) struct RemovedTestRule;
impl Violation for RemovedTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a removed test rule.".to_string()
}
}
impl TestRule for RemovedTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(RemovedTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.0.0")]
pub(crate) struct AnotherRemovedTestRule;
impl Violation for AnotherRemovedTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a another removed test rule.".to_string()
}
}
impl TestRule for AnotherRemovedTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(AnotherRemovedTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.0.0")]
pub(crate) struct RedirectedFromTestRule;
impl Violation for RedirectedFromTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a test rule that was redirected to another.".to_string()
}
}
impl TestRule for RedirectedFromTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(RedirectedFromTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.0.0")]
pub(crate) struct RedirectedToTestRule;
impl Violation for RedirectedToTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a test rule that was redirected from another.".to_string()
}
}
impl TestRule for RedirectedToTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(RedirectedToTestRule, ruff_text_size::TextRange::default());
}
}
/// ## What it does
/// Fake rule for testing.
///
/// ## Why is this bad?
/// Tests must pass!
///
/// ## Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "0.0.0")]
pub(crate) struct RedirectedFromPrefixTestRule;
impl Violation for RedirectedFromPrefixTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"Hey this is a test rule that was redirected to another by prefix.".to_string()
}
}
impl TestRule for RedirectedFromPrefixTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
context.report_diagnostic(
RedirectedFromPrefixTestRule,
ruff_text_size::TextRange::default(),
);
}
}
/// # What it does
/// Fake rule for testing panics.
///
/// # Why is this bad?
/// Panics are bad.
///
/// # Example
/// ```python
/// foo
/// ```
///
/// Use instead:
/// ```python
/// bar
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.0.0")]
pub(crate) struct PanicyTestRule;
impl Violation for PanicyTestRule {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::None;
#[derive_message_formats]
fn message(&self) -> String {
"If you see this, maybe panic!".to_string()
}
}
impl TestRule for PanicyTestRule {
fn diagnostic(_locator: &Locator, _comment_ranges: &CommentRanges, context: &LintContext) {
assert!(
!context.source_file().name().ends_with("panic.py"),
"This is a fake panic for testing."
);
}
}
| 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/ruff/rules/dataclass_enum.rs | crates/ruff_linter/src/rules/ruff/rules/dataclass_enum.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StmtClassDef;
use ruff_python_semantic::analyze::class::is_enumeration;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::ruff::helpers::{DataclassKind, dataclass_kind};
/// ## What it does
/// Checks for enum classes which are also decorated with `@dataclass`.
///
/// ## Why is this bad?
/// Decorating an enum with `@dataclass()` does not cause any errors at runtime,
/// but may cause erroneous results:
///
/// ```python
/// @dataclass
/// class E(Enum):
/// A = 1
/// B = 2
///
/// print(E.A == E.B) # True
/// ```
///
/// ## Example
///
/// ```python
/// from dataclasses import dataclass
/// from enum import Enum
///
///
/// @dataclass
/// class E(Enum): ...
/// ```
///
/// Use instead:
///
/// ```python
/// from enum import Enum
///
///
/// class E(Enum): ...
/// ```
///
/// ## References
/// - [Python documentation: Enum HOWTO § Dataclass support](https://docs.python.org/3/howto/enum.html#dataclass-support)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct DataclassEnum;
impl Violation for DataclassEnum {
#[derive_message_formats]
fn message(&self) -> String {
"An enum class should not be decorated with `@dataclass`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Remove either `@dataclass` or `Enum`".to_string())
}
}
/// RUF049
pub(crate) fn dataclass_enum(checker: &Checker, class_def: &StmtClassDef) {
let semantic = checker.semantic();
let Some((DataclassKind::Stdlib, decorator)) = dataclass_kind(class_def, semantic) else {
return;
};
if !is_enumeration(class_def, semantic) {
return;
}
checker.report_diagnostic(DataclassEnum, decorator.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/ruff/rules/explicit_f_string_type_conversion.rs | crates/ruff_linter/src/rules/ruff/rules/explicit_f_string_type_conversion.rs | use std::fmt::Display;
use anyhow::Result;
use libcst_native::{LeftParen, ParenthesizedNode, RightParen};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::TokenKind;
use ruff_python_ast::{self as ast, Expr, OperatorPrecedence};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::cst::helpers::space;
use crate::cst::matchers::{
match_call_mut, match_formatted_string, match_formatted_string_expression, transform_expression,
};
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `str()`, `repr()`, and `ascii()` as explicit type
/// conversions within f-strings.
///
/// ## Why is this bad?
/// f-strings support dedicated conversion flags for these types, which are
/// more succinct and idiomatic.
///
/// Note that, in many cases, calling `str()` within an f-string is
/// unnecessary and can be removed entirely, as the value will be converted
/// to a string automatically, the notable exception being for classes that
/// implement a custom `__format__` method.
///
/// ## Example
/// ```python
/// a = "some string"
/// f"{repr(a)}"
/// ```
///
/// Use instead:
/// ```python
/// a = "some string"
/// f"{a!r}"
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.267")]
pub(crate) struct ExplicitFStringTypeConversion;
impl Violation for ExplicitFStringTypeConversion {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use explicit conversion flag".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with conversion flag".to_string())
}
}
/// RUF010
pub(crate) fn explicit_f_string_type_conversion(checker: &Checker, f_string: &ast::FString) {
for (index, element) in f_string.elements.iter().enumerate() {
let Some(ast::InterpolatedElement {
expression,
conversion,
..
}) = element.as_interpolation()
else {
continue;
};
// Skip if there's already a conversion flag.
if !conversion.is_none() {
continue;
}
let Expr::Call(call) = expression.as_ref() else {
continue;
};
let Some(conversion) = checker
.semantic()
.resolve_builtin_symbol(&call.func)
.and_then(Conversion::from_str)
else {
continue;
};
let arg = match conversion {
// Handles the cases: `f"{str(object=arg)}"` and `f"{str(arg)}"`
Conversion::Str if call.arguments.len() == 1 => {
let Some(arg) = call.arguments.find_argument_value("object", 0) else {
continue;
};
arg
}
Conversion::Str | Conversion::Repr | Conversion::Ascii => {
// Can't be a conversion otherwise.
if !call.arguments.keywords.is_empty() {
continue;
}
// Can't be a conversion otherwise.
let [arg] = call.arguments.args.as_ref() else {
continue;
};
arg
}
};
// Suppress lint for starred expressions.
if arg.is_starred_expr() {
return;
}
// Don't report diagnostic for f-string with debug text.
if element
.as_interpolation()
.is_some_and(|interpolation| interpolation.debug_text.is_some())
{
return;
}
let mut diagnostic =
checker.report_diagnostic(ExplicitFStringTypeConversion, expression.range());
diagnostic.try_set_fix(|| {
convert_call_to_conversion_flag(checker, conversion, f_string, index, arg)
});
}
}
/// Generate a [`Fix`] to replace an explicit type conversion with a conversion flag.
fn convert_call_to_conversion_flag(
checker: &Checker,
conversion: Conversion,
f_string: &ast::FString,
index: usize,
arg: &Expr,
) -> Result<Fix> {
let source_code = checker.locator().slice(f_string);
transform_expression(source_code, checker.stylist(), |mut expression| {
let formatted_string = match_formatted_string(&mut expression)?;
// Replace the formatted call expression at `index` with a conversion flag.
let formatted_string_expression =
match_formatted_string_expression(&mut formatted_string.parts[index])?;
let call = match_call_mut(&mut formatted_string_expression.expression)?;
formatted_string_expression.conversion = Some(conversion.as_str());
if starts_with_brace(checker, arg) {
formatted_string_expression.whitespace_before_expression = space();
}
formatted_string_expression.expression = if needs_paren_expr(arg) {
call.args[0]
.value
.clone()
.with_parens(LeftParen::default(), RightParen::default())
} else {
call.args[0].value.clone()
};
Ok(expression)
})
.map(|output| Fix::safe_edit(Edit::range_replacement(output, f_string.range())))
}
fn starts_with_brace(checker: &Checker, arg: &Expr) -> bool {
checker
.tokens()
.in_range(arg.range())
.iter()
// Skip the trivia tokens
.find(|token| !token.kind().is_trivia())
.is_some_and(|token| matches!(token.kind(), TokenKind::Lbrace))
}
fn needs_paren(precedence: OperatorPrecedence) -> bool {
precedence <= OperatorPrecedence::Lambda
}
fn needs_paren_expr(arg: &Expr) -> bool {
// Generator expressions need to be parenthesized in f-string expressions
if let Some(generator) = arg.as_generator_expr() {
return !generator.parenthesized;
}
// Check precedence for other expressions
needs_paren(OperatorPrecedence::from_expr(arg))
}
/// Represents the three built-in Python conversion functions that can be replaced
/// with f-string conversion flags.
#[derive(Copy, Clone)]
enum Conversion {
Ascii,
Str,
Repr,
}
impl Conversion {
fn from_str(value: &str) -> Option<Self> {
Some(match value {
"ascii" => Self::Ascii,
"str" => Self::Str,
"repr" => Self::Repr,
_ => return None,
})
}
fn as_str(self) -> &'static str {
match self {
Conversion::Ascii => "a",
Conversion::Str => "s",
Conversion::Repr => "r",
}
}
}
impl Display for Conversion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_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/ruff/rules/sort_dunder_slots.rs | crates/ruff_linter/src/rules/ruff/rules/sort_dunder_slots.rs | use std::borrow::Cow;
use itertools::izip;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_semantic::Binding;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::rules::ruff::rules::sequence_sorting::{
CommentComplexity, MultilineStringSequenceValue, SequenceKind, SortClassification,
SortingStyle, sort_single_line_elements_sequence,
};
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `__slots__` definitions that are not ordered according to a
/// [natural sort](https://en.wikipedia.org/wiki/Natural_sort_order).
///
/// ## Why is this bad?
/// Consistency is good. Use a common convention for this special variable
/// to make your code more readable and idiomatic.
///
/// ## Example
/// ```python
/// class Dog:
/// __slots__ = "name", "breed"
/// ```
///
/// Use instead:
/// ```python
/// class Dog:
/// __slots__ = "breed", "name"
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe in three situations.
///
/// Firstly, the fix is unsafe if there are any comments that take up
/// a whole line by themselves inside the `__slots__` definition, for example:
/// ```py
/// class Foo:
/// __slots__ = [
/// # eggy things
/// "duck_eggs",
/// "chicken_eggs",
/// # hammy things
/// "country_ham",
/// "parma_ham",
/// ]
/// ```
///
/// This is a common pattern used to delimit categories within a class's slots,
/// but it would be out of the scope of this rule to attempt to maintain these
/// categories when applying a natural sort to the items of `__slots__`.
///
/// Secondly, the fix is also marked as unsafe if there are more than two
/// `__slots__` items on a single line and that line also has a trailing
/// comment, since here it is impossible to accurately gauge which item the
/// comment should be moved with when sorting `__slots__`:
/// ```py
/// class Bar:
/// __slots__ = [
/// "a", "c", "e", # a comment
/// "b", "d", "f", # a second comment
/// ]
/// ```
///
/// Lastly, this rule's fix is marked as unsafe whenever Ruff can detect that
/// code elsewhere in the same file reads the `__slots__` variable in some way
/// and the `__slots__` variable is not assigned to a set. This is because the
/// order of the items in `__slots__` may have semantic significance if the
/// `__slots__` of a class is being iterated over, or being assigned to another
/// value.
///
/// In the vast majority of other cases, this rule's fix is unlikely to
/// cause breakage; as such, Ruff will otherwise mark this rule's fix as
/// safe. However, note that (although it's rare) the value of `__slots__`
/// could still be read by code outside of the module in which the
/// `__slots__` definition occurs, in which case this rule's fix could
/// theoretically cause breakage.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.8.0")]
pub(crate) struct UnsortedDunderSlots {
class_name: ast::name::Name,
}
impl Violation for UnsortedDunderSlots {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("`{}.__slots__` is not sorted", self.class_name)
}
fn fix_title(&self) -> Option<String> {
Some(format!(
"Apply a natural sort to `{}.__slots__`",
self.class_name
))
}
}
const SORTING_STYLE: SortingStyle = SortingStyle::Natural;
/// RUF023
/// Sort a tuple, list, dict or set that defines `__slots__` in a class scope.
///
/// This routine checks whether the display is sorted, and emits a
/// violation if it is not sorted. If the tuple/list/set was not sorted,
/// it attempts to set a `Fix` on the violation.
pub(crate) fn sort_dunder_slots(checker: &Checker, binding: &Binding) {
let semantic = checker.semantic();
let Some(stmt) = binding.statement(semantic) else {
return;
};
let (target, value) = match stmt {
ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => match targets.as_slice() {
[target] => (target, &**value),
_ => return,
},
ast::Stmt::AnnAssign(ast::StmtAnnAssign {
target,
value: Some(value),
..
}) => (&**target, &**value),
_ => return,
};
let Some(ast::ExprName { id, .. }) = target.as_name_expr() else {
return;
};
if id != "__slots__" {
return;
}
// We're only interested in `__slots__` in the class scope
let Some(enclosing_class) = semantic.scopes[binding.scope].kind.as_class() else {
return;
};
// and it has to be an assignment to a "display literal" (a literal dict/set/tuple/list)
let Some(display) = StringLiteralDisplay::new(value) else {
return;
};
let sort_classification = SortClassification::of_elements(&display.elts, SORTING_STYLE);
if sort_classification.is_not_a_list_of_string_literals() || sort_classification.is_sorted() {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnsortedDunderSlots {
class_name: enclosing_class.name.id.clone(),
},
display.range,
);
if let SortClassification::UnsortedAndMaybeFixable { items } = sort_classification {
if let Some((sorted_source_code, comment_complexity)) =
display.generate_sorted_source_code(&items, checker)
{
let edit = Edit::range_replacement(sorted_source_code, display.range());
let applicability = if comment_complexity.is_complex()
|| (binding.is_used() && !display.kind.is_set_literal())
{
Applicability::Unsafe
} else {
Applicability::Safe
};
diagnostic.set_fix(Fix::applicable_edit(edit, applicability));
}
}
}
/// Struct representing a [display](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries)
/// of string literals.
#[derive(Debug)]
struct StringLiteralDisplay<'a> {
/// The elts from the original AST node representing the display.
/// Each elt is the AST representation of a single string literal
/// element in the display
elts: Cow<'a, [ast::Expr]>,
/// The source-code range of the display as a whole
range: TextRange,
/// What kind of a display is it? A dict, set, list or tuple?
kind: DisplayKind<'a>,
}
impl Ranged for StringLiteralDisplay<'_> {
fn range(&self) -> TextRange {
self.range
}
}
impl<'a> StringLiteralDisplay<'a> {
fn new(node: &'a ast::Expr) -> Option<Self> {
let result = match node {
ast::Expr::List(ast::ExprList { elts, range, .. }) => {
let kind = DisplayKind::Sequence(SequenceKind::List);
Self {
elts: Cow::Borrowed(elts),
range: *range,
kind,
}
}
ast::Expr::Tuple(ast::ExprTuple {
elts,
range,
parenthesized,
..
}) => {
let kind = DisplayKind::Sequence(SequenceKind::Tuple {
parenthesized: *parenthesized,
});
Self {
elts: Cow::Borrowed(elts),
range: *range,
kind,
}
}
ast::Expr::Set(ast::ExprSet {
elts,
range,
node_index: _,
}) => {
let kind = DisplayKind::Sequence(SequenceKind::Set);
Self {
elts: Cow::Borrowed(elts),
range: *range,
kind,
}
}
ast::Expr::Dict(dict) => {
let mut narrowed_keys = Vec::with_capacity(dict.len());
for key in dict.iter_keys() {
if let Some(key) = key {
// This is somewhat unfortunate,
// *but* using a dict for __slots__ is very rare
narrowed_keys.push(key.to_owned());
} else {
return None;
}
}
// If `None` was present in the keys, it indicates a "** splat", .e.g
// `__slots__ = {"foo": "bar", **other_dict}`
// If `None` wasn't present in the keys,
// the length of the keys should always equal the length of the values
assert_eq!(narrowed_keys.len(), dict.len());
Self {
elts: Cow::Owned(narrowed_keys),
range: dict.range(),
kind: DisplayKind::Dict { items: &dict.items },
}
}
_ => return None,
};
Some(result)
}
fn generate_sorted_source_code(
&self,
elements: &[&str],
checker: &Checker,
) -> Option<(String, CommentComplexity)> {
let locator = checker.locator();
let multiline_classification = if locator.contains_line_break(self.range()) {
MultilineClassification::Multiline
} else {
MultilineClassification::SingleLine
};
match (&self.kind, multiline_classification) {
(DisplayKind::Sequence(sequence_kind), MultilineClassification::Multiline) => {
let analyzed_sequence = MultilineStringSequenceValue::from_source_range(
self.range(),
*sequence_kind,
locator,
checker.tokens(),
elements,
)?;
assert_eq!(analyzed_sequence.len(), self.elts.len());
let comment_complexity = analyzed_sequence.comment_complexity();
let sorted_code = analyzed_sequence.into_sorted_source_code(
SORTING_STYLE,
locator,
checker.stylist(),
);
Some((sorted_code, comment_complexity))
}
// Sorting multiline dicts is unsupported
(DisplayKind::Dict { .. }, MultilineClassification::Multiline) => None,
(DisplayKind::Sequence(sequence_kind), MultilineClassification::SingleLine) => {
let sorted_code = sort_single_line_elements_sequence(
*sequence_kind,
&self.elts,
elements,
locator,
SORTING_STYLE,
);
Some((sorted_code, CommentComplexity::Simple))
}
(DisplayKind::Dict { items }, MultilineClassification::SingleLine) => {
let sorted_code =
sort_single_line_elements_dict(&self.elts, elements, items, locator);
Some((sorted_code, CommentComplexity::Simple))
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MultilineClassification {
SingleLine,
Multiline,
}
/// An enumeration of the various kinds of
/// [display literals](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries)
/// Python provides for builtin containers.
#[derive(Debug, Copy, Clone)]
enum DisplayKind<'a> {
Sequence(SequenceKind),
Dict { items: &'a [ast::DictItem] },
}
impl DisplayKind<'_> {
const fn is_set_literal(self) -> bool {
matches!(self, Self::Sequence(SequenceKind::Set))
}
}
/// A newtype that zips together three iterables:
///
/// 1. The string values of a dict literal's keys;
/// 2. The original AST nodes for the dict literal's keys; and,
/// 3. The original AST nodes for the dict literal's values
///
/// The main purpose of separating this out into a separate struct
/// is to enforce the invariants that:
///
/// 1. The three iterables that are zipped together have the same length; and,
/// 2. The length of all three iterables is >= 2
struct DictElements<'a>(Vec<(&'a &'a str, &'a ast::Expr, &'a ast::Expr)>);
impl<'a> DictElements<'a> {
fn new(elements: &'a [&str], key_elts: &'a [ast::Expr], items: &'a [ast::DictItem]) -> Self {
assert_eq!(key_elts.len(), elements.len());
assert_eq!(elements.len(), items.len());
assert!(
elements.len() >= 2,
"A sequence with < 2 elements cannot be unsorted"
);
Self(izip!(elements, key_elts, items.iter().map(|item| &item.value)).collect())
}
fn last_item_index(&self) -> usize {
// Safe from underflow, as the constructor guarantees
// that the underlying vector has length >= 2
self.0.len() - 1
}
fn into_sorted_elts(mut self) -> impl Iterator<Item = (&'a ast::Expr, &'a ast::Expr)> {
self.0
.sort_by(|(elem1, _, _), (elem2, _, _)| SORTING_STYLE.compare(elem1, elem2));
self.0.into_iter().map(|(_, key, value)| (key, value))
}
}
/// Create a string representing a fixed-up single-line
/// definition of a `__slots__` dictionary that can be
/// inserted into the source code as a `range_replacement`
/// autofix.
///
/// N.B. This function could potentially be moved into
/// `sequence_sorting.rs` if any other modules need it,
/// but stays here for now, since this is currently the
/// only module that needs it
fn sort_single_line_elements_dict<'a>(
key_elts: &'a [ast::Expr],
elements: &'a [&str],
original_items: &'a [ast::DictItem],
locator: &Locator,
) -> String {
let element_trios = DictElements::new(elements, key_elts, original_items);
let last_item_index = element_trios.last_item_index();
let mut result = String::from('{');
// We grab the original source-code ranges using `locator.slice()`
// rather than using the expression generator, as this approach allows
// us to easily preserve stylistic choices in the original source code
// such as whether double or single quotes were used.
for (i, (key, value)) in element_trios.into_sorted_elts().enumerate() {
result.push_str(locator.slice(key));
result.push_str(": ");
result.push_str(locator.slice(value));
if i < last_item_index {
result.push_str(", ");
}
}
result.push('}');
result
}
| 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/ruff/rules/redirected_noqa.rs | crates/ruff_linter/src/rules/ruff/rules/redirected_noqa.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use crate::checkers::ast::LintContext;
use crate::noqa::{Codes, Directive, FileNoqaDirectives, NoqaDirectives};
use crate::rule_redirects::get_redirect_target;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for `noqa` directives that use redirected rule codes.
///
/// ## Why is this bad?
/// When one of Ruff's rule codes has been redirected, the implication is that the rule has
/// been deprecated in favor of another rule or code. To keep your codebase
/// consistent and up-to-date, prefer the canonical rule code over the deprecated
/// code.
///
/// ## Example
/// ```python
/// x = eval(command) # noqa: PGH001
/// ```
///
/// Use instead:
/// ```python
/// x = eval(command) # noqa: S307
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.6.0")]
pub(crate) struct RedirectedNOQA {
original: String,
target: String,
}
impl AlwaysFixableViolation for RedirectedNOQA {
#[derive_message_formats]
fn message(&self) -> String {
let RedirectedNOQA { original, target } = self;
format!("`{original}` is a redirect to `{target}`")
}
fn fix_title(&self) -> String {
let RedirectedNOQA { target, .. } = self;
format!("Replace with `{target}`")
}
}
/// RUF101 for in-line noqa directives
pub(crate) fn redirected_noqa(context: &LintContext, noqa_directives: &NoqaDirectives) {
for line in noqa_directives.lines() {
let Directive::Codes(directive) = &line.directive else {
continue;
};
build_diagnostics(context, directive);
}
}
/// RUF101 for file noqa directives
pub(crate) fn redirected_file_noqa(context: &LintContext, noqa_directives: &FileNoqaDirectives) {
for line in noqa_directives.lines() {
let Directive::Codes(codes) = &line.parsed_file_exemption else {
continue;
};
build_diagnostics(context, codes);
}
}
/// Convert a sequence of [Codes] into [Diagnostic]s and append them to `diagnostics`.
pub(crate) fn build_diagnostics(context: &LintContext, codes: &Codes<'_>) {
for code in codes.iter() {
if let Some(redirected) = get_redirect_target(code.as_str()) {
let mut diagnostic = context.report_diagnostic(
RedirectedNOQA {
original: code.to_string(),
target: redirected.to_string(),
},
code.range(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
redirected.to_string(),
code.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/ruff/rules/invalid_rule_code.rs | crates/ruff_linter/src/rules/ruff/rules/invalid_rule_code.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::noqa::{Code, Directive};
use crate::noqa::{Codes, NoqaDirectives};
use crate::registry::Rule;
use crate::rule_redirects::get_redirect_target;
use crate::{AlwaysFixableViolation, Edit, Fix};
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum InvalidRuleCodeKind {
Noqa,
Suppression,
}
impl InvalidRuleCodeKind {
fn as_str(&self) -> &str {
match self {
InvalidRuleCodeKind::Noqa => "`# noqa`",
InvalidRuleCodeKind::Suppression => "suppression",
}
}
}
/// ## What it does
/// Checks for `noqa` codes that are invalid.
///
/// ## Why is this bad?
/// Invalid rule codes serve no purpose and may indicate outdated code suppressions.
///
/// ## Example
/// ```python
/// import os # noqa: XYZ999
/// ```
///
/// Use instead:
/// ```python
/// import os
/// ```
///
/// Or if there are still valid codes needed:
/// ```python
/// import os # noqa: E402
/// ```
///
/// ## Options
/// - `lint.external`
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.11.4")]
pub(crate) struct InvalidRuleCode {
pub(crate) rule_code: String,
pub(crate) kind: InvalidRuleCodeKind,
}
impl AlwaysFixableViolation for InvalidRuleCode {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Invalid rule code in {}: {}",
self.kind.as_str(),
self.rule_code
)
}
fn fix_title(&self) -> String {
"Remove the rule code".to_string()
}
}
/// RUF102 for invalid noqa codes
pub(crate) fn invalid_noqa_code(
context: &LintContext,
noqa_directives: &NoqaDirectives,
locator: &Locator,
external: &[String],
) {
for line in noqa_directives.lines() {
let Directive::Codes(directive) = &line.directive else {
continue;
};
let all_valid = directive
.iter()
.all(|code| code_is_valid(code.as_str(), external));
if all_valid {
continue;
}
let (valid_codes, invalid_codes): (Vec<_>, Vec<_>) = directive
.iter()
.partition(|&code| code_is_valid(code.as_str(), external));
if valid_codes.is_empty() {
all_codes_invalid_diagnostic(directive, invalid_codes, context);
} else {
for invalid_code in invalid_codes {
some_codes_are_invalid_diagnostic(directive, invalid_code, locator, context);
}
}
}
}
pub(crate) fn code_is_valid(code: &str, external: &[String]) -> bool {
Rule::from_code(get_redirect_target(code).unwrap_or(code)).is_ok()
|| external.iter().any(|ext| code.starts_with(ext))
}
fn all_codes_invalid_diagnostic(
directive: &Codes<'_>,
invalid_codes: Vec<&Code<'_>>,
context: &LintContext,
) {
context
.report_diagnostic(
InvalidRuleCode {
rule_code: invalid_codes
.into_iter()
.map(Code::as_str)
.collect::<Vec<_>>()
.join(", "),
kind: InvalidRuleCodeKind::Noqa,
},
directive.range(),
)
.set_fix(Fix::safe_edit(Edit::range_deletion(directive.range())));
}
fn some_codes_are_invalid_diagnostic(
codes: &Codes,
invalid_code: &Code,
locator: &Locator,
context: &LintContext,
) {
context
.report_diagnostic(
InvalidRuleCode {
rule_code: invalid_code.to_string(),
kind: InvalidRuleCodeKind::Noqa,
},
invalid_code.range(),
)
.set_fix(Fix::safe_edit(remove_invalid_noqa(
codes,
invalid_code,
locator,
)));
}
fn remove_invalid_noqa(codes: &Codes, invalid_code: &Code, locator: &Locator) -> Edit {
// Is this the first code after the `:` that needs to get deleted
// For the first element, delete from after the `:` to the next comma (including)
// For any other element, delete from the previous comma (including) to the next comma (excluding)
let mut first = false;
// Find the index of the previous comma or colon.
let start = locator
.slice(TextRange::new(codes.start(), invalid_code.start()))
.rmatch_indices([',', ':'])
.next()
.map(|(offset, text)| {
let offset = codes.start() + TextSize::try_from(offset).unwrap();
if text == ":" {
first = true;
// Don't include the colon in the deletion range, or the noqa comment becomes invalid
offset + ':'.text_len()
} else {
offset
}
})
.unwrap_or(invalid_code.start());
// Find the index of the trailing comma (if any)
let end = locator
.slice(TextRange::new(invalid_code.end(), codes.end()))
.find(',')
.map(|offset| {
let offset = invalid_code.end() + TextSize::try_from(offset).unwrap();
if first {
offset + ','.text_len()
} else {
offset
}
})
.unwrap_or(invalid_code.end());
Edit::range_deletion(TextRange::new(start, end))
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/non_octal_permissions.rs | crates/ruff_linter/src/rules/ruff/rules/non_octal_permissions.rs | use ruff_diagnostics::{Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::QualifiedName;
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_semantic::{SemanticModel, analyze};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for standard library functions which take a numeric `mode` argument
/// where a non-octal integer literal is passed.
///
/// ## Why is this bad?
///
/// Numeric modes are made up of one to four octal digits. Converting a non-octal
/// integer to octal may not be the mode the author intended.
///
/// ## Example
///
/// ```python
/// os.chmod("foo", 644)
/// ```
///
/// Use instead:
///
/// ```python
/// os.chmod("foo", 0o644)
/// ```
///
/// ## Fix safety
///
/// There are two categories of fix, the first of which is where it looks like
/// the author intended to use an octal literal but the `0o` prefix is missing:
///
/// ```python
/// os.chmod("foo", 400)
/// os.chmod("foo", 644)
/// ```
///
/// This class of fix changes runtime behaviour. In the first case, `400`
/// corresponds to `0o620` (`u=rw,g=w,o=`). As this mode is not deemed likely,
/// it is changed to `0o400` (`u=r,go=`). Similarly, `644` corresponds to
/// `0o1204` (`u=ws,g=,o=r`) and is changed to `0o644` (`u=rw,go=r`).
///
/// The second category is decimal literals which are recognised as likely valid
/// but in decimal form:
///
/// ```python
/// os.chmod("foo", 256)
/// os.chmod("foo", 493)
/// ```
///
/// `256` corresponds to `0o400` (`u=r,go=`) and `493` corresponds to `0o755`
/// (`u=rwx,go=rx`). Both of these fixes keep runtime behavior unchanged. If the
/// original code really intended to use `0o256` (`u=w,g=rx,o=rw`) instead of
/// `256`, this fix should not be accepted.
///
/// As a special case, zero is allowed to omit the `0o` prefix unless it has
/// multiple digits:
///
/// ```python
/// os.chmod("foo", 0) # Ok
/// os.chmod("foo", 0o000) # Ok
/// os.chmod("foo", 000) # Lint emitted and fix suggested
/// ```
///
/// Ruff will suggest a safe fix for multi-digit zeros to add the `0o` prefix.
///
/// ## Fix availability
///
/// A fix is only available if the integer literal matches a set of common modes.
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.12.1")]
pub(crate) struct NonOctalPermissions;
impl Violation for NonOctalPermissions {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Non-octal mode".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with octal literal".to_string())
}
}
/// RUF064
pub(crate) fn non_octal_permissions(checker: &Checker, call: &ExprCall) {
let mode_arg = find_func_mode_arg(call, checker.semantic())
.or_else(|| find_method_mode_arg(call, checker.semantic()));
let Some(mode_arg) = mode_arg else {
return;
};
let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(int),
..
}) = mode_arg
else {
return;
};
let mode_literal = &checker.locator().contents()[mode_arg.range()];
if mode_literal.starts_with("0o") || mode_literal.starts_with("0O") || mode_literal == "0" {
return;
}
let mut diagnostic = checker.report_diagnostic(NonOctalPermissions, mode_arg.range());
// Don't suggest a fix for 0x or 0b literals.
if mode_literal.starts_with("0x") || mode_literal.starts_with("0b") {
return;
}
if mode_literal.chars().all(|c| c == '0') {
// Fix e.g. 000 as 0o000
let edit = Edit::range_replacement(format!("0o{mode_literal}"), mode_arg.range());
diagnostic.set_fix(Fix::safe_edit(edit));
return;
}
let Some(suggested) = int.as_u16().and_then(suggest_fix) else {
return;
};
let edit = Edit::range_replacement(format!("{suggested:#o}"), mode_arg.range());
diagnostic.set_fix(Fix::unsafe_edit(edit));
}
fn find_func_mode_arg<'a>(call: &'a ExprCall, semantic: &SemanticModel) -> Option<&'a Expr> {
let qualified_name = semantic.resolve_qualified_name(&call.func)?;
match qualified_name.segments() {
["os", "umask"] => call.arguments.find_argument_value("mode", 0),
[
"os",
"chmod" | "fchmod" | "lchmod" | "mkdir" | "makedirs" | "mkfifo" | "mknod",
] => call.arguments.find_argument_value("mode", 1),
["os", "open"] => call.arguments.find_argument_value("mode", 2),
["dbm", "open"] | ["dbm", "gnu" | "ndbm", "open"] => {
call.arguments.find_argument_value("mode", 2)
}
_ => None,
}
}
fn find_method_mode_arg<'a>(call: &'a ExprCall, semantic: &SemanticModel) -> Option<&'a Expr> {
let (type_name, attr_name) = resolve_method_call(&call.func, semantic)?;
match (type_name.segments(), attr_name) {
(
["pathlib", "Path" | "PosixPath" | "WindowsPath"],
"chmod" | "lchmod" | "mkdir" | "touch",
) => call.arguments.find_argument_value("mode", 0),
_ => None,
}
}
fn resolve_method_call<'a>(
func: &'a Expr,
semantic: &'a SemanticModel,
) -> Option<(QualifiedName<'a>, &'a str)> {
let Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func else {
return None;
};
// First: is this an inlined call like `pathlib.Path.chmod`?
// ```python
// from pathlib import Path
// Path("foo").chmod(0o644)
// ```
if let Expr::Call(call) = value.as_ref() {
let qualified_name = semantic.resolve_qualified_name(&call.func)?;
return Some((qualified_name, attr));
}
// Second, is this a call like `pathlib.Path.chmod` via a variable?
// ```python
// from pathlib import Path
// path = Path("foo")
// path.chmod()
// ```
let Expr::Name(name) = value.as_ref() else {
return None;
};
let binding_id = semantic.resolve_name(name)?;
let binding = semantic.binding(binding_id);
let Some(Expr::Call(call)) = analyze::typing::find_binding_value(binding, semantic) else {
return None;
};
let qualified_name = semantic.resolve_qualified_name(&call.func)?;
Some((qualified_name, attr))
}
/// Try to determine whether the integer literal
fn suggest_fix(mode: u16) -> Option<u16> {
// These suggestions are in the form of
// <missing `0o` prefix> | <mode as decimal> => <octal>
// If <as decimal> could theoretically be a valid octal literal, the
// comment explains why it's deemed unlikely to be intentional.
match mode {
400 | 256 => Some(0o400), // -w-r-xrw-, group/other > user unlikely
440 | 288 => Some(0o440),
444 | 292 => Some(0o444),
600 | 384 => Some(0o600),
640 | 416 => Some(0o640), // r----xrw-, other > user unlikely
644 | 420 => Some(0o644), // r---w----, group write but not read unlikely
660 | 432 => Some(0o660), // r---wx-w-, write but not read unlikely
664 | 436 => Some(0o664), // r---wxrw-, other > user unlikely
666 | 438 => Some(0o666),
700 | 448 => Some(0o700),
744 | 484 => Some(0o744),
750 | 488 => Some(0o750),
755 | 493 => Some(0o755),
770 | 504 => Some(0o770), // r-x---r--, other > group unlikely
775 | 509 => Some(0o775),
776 | 510 => Some(0o776), // r-x--x---, seems unlikely
777 | 511 => Some(0o777), // r-x--x--x, seems unlikely
_ => 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/ruff/rules/invalid_index_type.rs | crates/ruff_linter/src/rules/ruff/rules/invalid_index_type.rs | use ruff_python_ast::{Expr, ExprNumberLiteral, ExprSlice, ExprSubscript, Number};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_text_size::Ranged;
use std::fmt;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for indexed access to lists, strings, tuples, bytes, and comprehensions
/// using a type other than an integer or slice.
///
/// ## Why is this bad?
/// Only integers or slices can be used as indices to these types. Using
/// other types will result in a `TypeError` at runtime and a `SyntaxWarning` at
/// import time.
///
/// ## Example
/// ```python
/// var = [1, 2, 3]["x"]
/// ```
///
/// Use instead:
/// ```python
/// var = [1, 2, 3][0]
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.278")]
pub(crate) struct InvalidIndexType {
value_type: String,
index_type: String,
is_slice: bool,
}
impl Violation for InvalidIndexType {
#[derive_message_formats]
fn message(&self) -> String {
let InvalidIndexType {
value_type,
index_type,
is_slice,
} = self;
if *is_slice {
format!(
"Slice in indexed access to type `{value_type}` uses type `{index_type}` instead of an integer"
)
} else {
format!(
"Indexed access to type `{value_type}` uses type `{index_type}` instead of an integer or slice"
)
}
}
}
/// RUF016
pub(crate) fn invalid_index_type(checker: &Checker, expr: &ExprSubscript) {
let ExprSubscript {
value,
slice: index,
..
} = expr;
// Check the value being indexed is a list, tuple, string, f-string, bytes, or comprehension
if !matches!(
value.as_ref(),
Expr::List(_)
| Expr::ListComp(_)
| Expr::Tuple(_)
| Expr::FString(_)
| Expr::StringLiteral(_)
| Expr::BytesLiteral(_)
) {
return;
}
// The value types supported by this rule should always be checkable
let Some(value_type) = CheckableExprType::try_from(value) else {
debug_assert!(
false,
"Index value must be a checkable type to generate a violation message."
);
return;
};
// If the index is not a checkable type then we can't easily determine if there is a violation
let Some(index_type) = CheckableExprType::try_from(index) else {
return;
};
if index_type.is_literal() {
// If the index is a literal, require an integer
if index_type != CheckableExprType::IntLiteral
&& index_type != CheckableExprType::BooleanLiteral
{
checker.report_diagnostic(
InvalidIndexType {
value_type: value_type.to_string(),
index_type: index_type.to_string(),
is_slice: false,
},
index.range(),
);
}
} else if let Expr::Slice(ExprSlice {
lower, upper, step, ..
}) = index.as_ref()
{
for is_slice in [lower, upper, step].into_iter().flatten() {
let Some(is_slice_type) = CheckableExprType::try_from(is_slice) else {
return;
};
if is_slice_type.is_literal() {
// If the index is a slice, require integer or null bounds
if !matches!(
is_slice_type,
CheckableExprType::IntLiteral
| CheckableExprType::NoneLiteral
| CheckableExprType::BooleanLiteral
) {
checker.report_diagnostic(
InvalidIndexType {
value_type: value_type.to_string(),
index_type: is_slice_type.to_string(),
is_slice: true,
},
is_slice.range(),
);
}
} else if let Some(is_slice_type) = CheckableExprType::try_from(is_slice.as_ref()) {
checker.report_diagnostic(
InvalidIndexType {
value_type: value_type.to_string(),
index_type: is_slice_type.to_string(),
is_slice: true,
},
is_slice.range(),
);
}
}
} else {
// If it's some other checkable data type, it's a violation
checker.report_diagnostic(
InvalidIndexType {
value_type: value_type.to_string(),
index_type: index_type.to_string(),
is_slice: false,
},
index.range(),
);
}
}
/// An expression that can be checked for type compatibility.
///
/// These are generally "literal" type expressions in that we know their concrete type
/// without additional analysis; opposed to expressions like a function call where we
/// cannot determine what type it may return.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum CheckableExprType {
FString,
TString,
StringLiteral,
BytesLiteral,
IntLiteral,
FloatLiteral,
ComplexLiteral,
BooleanLiteral,
NoneLiteral,
EllipsisLiteral,
List,
ListComp,
SetComp,
DictComp,
Set,
Dict,
Tuple,
Slice,
Generator,
Lambda,
}
impl fmt::Display for CheckableExprType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::FString => f.write_str("str"),
Self::TString => f.write_str("Template"),
Self::StringLiteral => f.write_str("str"),
Self::BytesLiteral => f.write_str("bytes"),
Self::IntLiteral => f.write_str("int"),
Self::FloatLiteral => f.write_str("float"),
Self::ComplexLiteral => f.write_str("complex"),
Self::BooleanLiteral => f.write_str("bool"),
Self::NoneLiteral => f.write_str("None"),
Self::EllipsisLiteral => f.write_str("ellipsis"),
Self::List => f.write_str("list"),
Self::SetComp => f.write_str("set comprehension"),
Self::ListComp => f.write_str("list comprehension"),
Self::DictComp => f.write_str("dict comprehension"),
Self::Set => f.write_str("set"),
Self::Slice => f.write_str("slice"),
Self::Dict => f.write_str("dict"),
Self::Tuple => f.write_str("tuple"),
Self::Generator => f.write_str("generator"),
Self::Lambda => f.write_str("lambda"),
}
}
}
impl CheckableExprType {
fn try_from(expr: &Expr) -> Option<Self> {
match expr {
Expr::StringLiteral(_) => Some(Self::StringLiteral),
Expr::BytesLiteral(_) => Some(Self::BytesLiteral),
Expr::NumberLiteral(ExprNumberLiteral { value, .. }) => match value {
Number::Int(_) => Some(Self::IntLiteral),
Number::Float(_) => Some(Self::FloatLiteral),
Number::Complex { .. } => Some(Self::ComplexLiteral),
},
Expr::BooleanLiteral(_) => Some(Self::BooleanLiteral),
Expr::NoneLiteral(_) => Some(Self::NoneLiteral),
Expr::EllipsisLiteral(_) => Some(Self::EllipsisLiteral),
Expr::TString(_) => Some(Self::TString),
Expr::FString(_) => Some(Self::FString),
Expr::List(_) => Some(Self::List),
Expr::ListComp(_) => Some(Self::ListComp),
Expr::SetComp(_) => Some(Self::SetComp),
Expr::DictComp(_) => Some(Self::DictComp),
Expr::Set(_) => Some(Self::Set),
Expr::Dict(_) => Some(Self::Dict),
Expr::Tuple(_) => Some(Self::Tuple),
Expr::Slice(_) => Some(Self::Slice),
Expr::Generator(_) => Some(Self::Generator),
Expr::Lambda(_) => Some(Self::Lambda),
_ => None,
}
}
fn is_literal(self) -> bool {
matches!(
self,
Self::StringLiteral
| Self::BytesLiteral
| Self::IntLiteral
| Self::FloatLiteral
| Self::ComplexLiteral
| Self::BooleanLiteral
| Self::NoneLiteral
| Self::EllipsisLiteral
)
}
}
| 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/ruff/rules/sequence_sorting.rs | crates/ruff_linter/src/rules/ruff/rules/sequence_sorting.rs | /// Utilities for sorting constant lists of string literals.
///
/// Examples where these are useful:
/// - Sorting `__all__` in the global scope,
/// - Sorting `__slots__` in a class scope
use std::borrow::Cow;
use std::cmp::Ordering;
use itertools::Itertools;
use ruff_python_ast as ast;
use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_python_codegen::Stylist;
use ruff_python_stdlib::str::is_cased_uppercase;
use ruff_python_trivia::{SimpleTokenKind, first_non_trivia_token, leading_indentation};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::Locator;
/// An enumeration of the different sorting styles
/// currently supported for displays of string literals
#[derive(Debug, Clone, Copy)]
pub(super) enum SortingStyle {
/// Sort string-literal items according to a
/// [natural sort](https://en.wikipedia.org/wiki/Natural_sort_order).
Natural,
/// Sort string-literal items "isort-style".
///
/// An isort-style sort orders items first according to their casing:
/// SCREAMING_SNAKE_CASE names (conventionally used for global constants)
/// come first, followed by CamelCase names (conventionally used for
/// classes), followed by anything else. Within each category,
/// a [natural sort](https://en.wikipedia.org/wiki/Natural_sort_order)
/// is used to order the elements.
Isort,
}
impl SortingStyle {
pub(super) fn compare(self, a: &str, b: &str) -> Ordering {
match self {
Self::Natural => natord::compare(a, b),
Self::Isort => IsortSortKey::from(a).cmp(&IsortSortKey::from(b)),
}
}
}
/// A struct to implement logic necessary to achieve
/// an "isort-style sort".
///
/// An isort-style sort sorts items first according to their casing:
/// SCREAMING_SNAKE_CASE names (conventionally used for global constants)
/// come first, followed by CamelCase names (conventionally used for
/// classes), followed by anything else. Within each category,
/// a [natural sort](https://en.wikipedia.org/wiki/Natural_sort_order)
/// is used to order the elements.
struct IsortSortKey<'a> {
category: InferredMemberType,
value: &'a str,
}
impl Ord for IsortSortKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.category
.cmp(&other.category)
.then_with(|| natord::compare(self.value, other.value))
}
}
impl PartialOrd for IsortSortKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for IsortSortKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for IsortSortKey<'_> {}
impl<'a> From<&'a str> for IsortSortKey<'a> {
fn from(value: &'a str) -> Self {
Self {
category: InferredMemberType::of(value),
value,
}
}
}
/// Classification for the casing of an element in a
/// sequence of literal strings.
///
/// This is necessary to achieve an "isort-style" sort,
/// where elements are sorted first by category,
/// then, within categories, are sorted according
/// to a natural sort.
///
/// You'll notice that a very similar enum exists
/// in ruff's reimplementation of isort.
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone, Copy)]
enum InferredMemberType {
Constant,
Class,
Other,
}
impl InferredMemberType {
fn of(value: &str) -> Self {
// E.g. `CONSTANT`
if value.len() > 1 && is_cased_uppercase(value) {
Self::Constant
// E.g. `Class`
} else if value.starts_with(char::is_uppercase) {
Self::Class
// E.g. `some_variable` or `some_function`
} else {
Self::Other
}
}
}
/// An enumeration of the various kinds of sequences for which Python has
/// [display literals](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries).
///
/// (I'm aware a set isn't actually a "sequence",
/// *but* for our purposes it's conceptually a sequence,
/// since in terms of the AST structure it's almost identical
/// to tuples/lists.)
///
/// Whereas list, dict and set literals are always parenthesized
/// (e.g. lists always start with `[` and end with `]`),
/// single-line tuple literals *can* be unparenthesized.
/// We keep the original AST node around for the
/// Tuple variant so that this can be queried later.
#[derive(Copy, Clone, Debug)]
pub(super) enum SequenceKind {
List,
Set,
Tuple { parenthesized: bool },
}
impl SequenceKind {
// N.B. We only need the source code for the Tuple variant here,
// but if you already have a `Locator` instance handy,
// getting the source code is very cheap.
fn surrounding_brackets(self) -> (&'static str, &'static str) {
match self {
Self::List => ("[", "]"),
Self::Set => ("{", "}"),
Self::Tuple { parenthesized } => {
if parenthesized {
("(", ")")
} else {
("", "")
}
}
}
}
const fn opening_token_for_multiline_definition(self) -> TokenKind {
match self {
Self::List => TokenKind::Lsqb,
Self::Set => TokenKind::Lbrace,
Self::Tuple { .. } => TokenKind::Lpar,
}
}
const fn closing_token_for_multiline_definition(self) -> TokenKind {
match self {
Self::List => TokenKind::Rsqb,
Self::Set => TokenKind::Rbrace,
Self::Tuple { .. } => TokenKind::Rpar,
}
}
}
/// A newtype that zips together the string values of a display literal's elts,
/// together with the original AST nodes for that display literal's elts.
///
/// The main purpose of separating this out into a separate struct
/// is to enforce the invariants that:
///
/// 1. The two iterables that are zipped together have the same length; and,
/// 2. The length of both iterables is >= 2
struct SequenceElements<'a>(Vec<(&'a &'a str, &'a ast::Expr)>);
impl<'a> SequenceElements<'a> {
fn new(elements: &'a [&str], elts: &'a [ast::Expr]) -> Self {
assert_eq!(elements.len(), elts.len());
assert!(
elements.len() >= 2,
"A sequence with < 2 elements cannot be unsorted"
);
Self(elements.iter().zip(elts).collect())
}
fn last_item_index(&self) -> usize {
// Safe from underflow, as the constructor guarantees
// that the underlying vector has length >= 2
self.0.len() - 1
}
fn into_sorted_elts(
mut self,
sorting_style: SortingStyle,
) -> impl Iterator<Item = &'a ast::Expr> {
self.0
.sort_by(|(elem1, _), (elem2, _)| sorting_style.compare(elem1, elem2));
self.0.into_iter().map(|(_, elt)| elt)
}
}
/// Create a string representing a fixed-up single-line
/// definition of `__all__` or `__slots__` (etc.),
/// that can be inserted into the
/// source code as a `range_replacement` autofix.
pub(super) fn sort_single_line_elements_sequence(
kind: SequenceKind,
elts: &[ast::Expr],
elements: &[&str],
locator: &Locator,
sorting_style: SortingStyle,
) -> String {
let element_pairs = SequenceElements::new(elements, elts);
let last_item_index = element_pairs.last_item_index();
let (opening_paren, closing_paren) = kind.surrounding_brackets();
let mut result = String::from(opening_paren);
// We grab the original source-code ranges using `locator.slice()`
// rather than using the expression generator, as this approach allows
// us to easily preserve stylistic choices in the original source code
// such as whether double or single quotes were used.
for (i, elt) in element_pairs.into_sorted_elts(sorting_style).enumerate() {
result.push_str(locator.slice(elt));
if i < last_item_index {
result.push_str(", ");
}
}
result.push_str(closing_paren);
result
}
/// An enumeration of the possible conclusions we could come to
/// regarding the ordering of the elements in a display of string literals
#[derive(Debug, is_macro::Is)]
pub(super) enum SortClassification<'a> {
/// It's a display of string literals that is already sorted
Sorted,
/// It's an unsorted display of string literals,
/// but we wouldn't be able to autofix it
UnsortedButUnfixable,
/// It's an unsorted display of string literals,
/// and it's possible we could generate a fix for it;
/// here's the values of the elts so we can use them to
/// generate an autofix:
UnsortedAndMaybeFixable { items: Vec<&'a str> },
/// The display contains one or more items that are not string
/// literals.
NotAListOfStringLiterals,
}
impl<'a> SortClassification<'a> {
pub(super) fn of_elements(elements: &'a [ast::Expr], sorting_style: SortingStyle) -> Self {
// If it's of length less than 2, it has to be sorted already
let Some((first, rest @ [_, ..])) = elements.split_first() else {
return Self::Sorted;
};
// If any elt we encounter is not an ExprStringLiteral AST node,
// that indicates at least one item in the sequence is not a string literal,
// which means the sequence is out of scope for RUF022/RUF023/etc.
let Some(string_node) = first.as_string_literal_expr() else {
return Self::NotAListOfStringLiterals;
};
let mut current = string_node.value.to_str();
for expr in rest {
let Some(string_node) = expr.as_string_literal_expr() else {
return Self::NotAListOfStringLiterals;
};
let next = string_node.value.to_str();
if sorting_style.compare(next, current).is_lt() {
// Looks like the sequence was not in fact already sorted!
//
// Now we need to gather the necessary information we'd need
// to create an autofix. We need to know three things for this:
//
// 1. Are all items in the sequence string literals?
// (If not, we won't even be emitting the violation, let alone
// trying to fix it.)
// 2. Are any items in the sequence implicitly concatenated?
// (If so, we might be *emitting* the violation, but we definitely
// won't be trying to fix it.)
// 3. What is the value of each elt in the sequence?
let mut items = Vec::with_capacity(elements.len());
let mut any_implicit_concatenation = false;
for expr in elements {
let Some(string_node) = expr.as_string_literal_expr() else {
return Self::NotAListOfStringLiterals;
};
match string_node.as_single_part_string() {
Some(literal) => items.push(&*literal.value),
None => any_implicit_concatenation = true,
}
}
if any_implicit_concatenation {
return Self::UnsortedButUnfixable;
}
return Self::UnsortedAndMaybeFixable { items };
}
current = next;
}
// Looks like the sequence was already sorted -- hooray!
// We won't be emitting a violation this time.
Self::Sorted
}
}
/// The complexity of the comments in a multiline sequence.
///
/// A sequence like this has "simple" comments: it's unambiguous
/// which item each comment refers to, so there's no "risk" in sorting it:
///
/// ```py
/// __all__ = [
/// "foo", # comment1
/// "bar", # comment2
/// ]
/// ```
///
/// This sequence has complex comments: we can't safely autofix the sort here,
/// as the own-line comments might be used to create sections in `__all__`:
///
/// ```py
/// __all__ = [
/// # fooey things
/// "foo1",
/// "foo2",
/// # barey things
/// "bar1",
/// "foobar",
/// ]
/// ```
///
/// This sequence also has complex comments -- it's ambiguous which item
/// each comment should belong to:
///
/// ```py
/// __all__ = [
/// "foo1", "foo", "barfoo", # fooey things
/// "baz", bazz2", "fbaz", # barrey things
/// ]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(super) enum CommentComplexity {
Simple,
Complex,
}
impl CommentComplexity {
pub(super) const fn is_complex(self) -> bool {
matches!(self, CommentComplexity::Complex)
}
}
// An instance of this struct encapsulates an analysis
/// of a multiline Python tuple/list that represents an
/// `__all__`/`__slots__`/etc. definition or augmentation.
pub(super) struct MultilineStringSequenceValue<'a> {
items: Vec<StringSequenceItem<'a>>,
range: TextRange,
ends_with_trailing_comma: bool,
}
impl<'a> MultilineStringSequenceValue<'a> {
pub(super) fn len(&self) -> usize {
self.items.len()
}
/// Determine the [`CommentComplexity`] of this multiline string sequence.
pub(super) fn comment_complexity(&self) -> CommentComplexity {
if self.items.iter().tuple_windows().any(|(first, second)| {
first.has_own_line_comments()
|| first
.end_of_line_comments
.is_some_and(|end_line_comment| second.start() < end_line_comment.end())
}) || self
.items
.last()
.is_some_and(StringSequenceItem::has_own_line_comments)
{
CommentComplexity::Complex
} else {
CommentComplexity::Simple
}
}
/// Analyse the source range for a multiline Python tuple/list that
/// represents an `__all__`/`__slots__`/etc. definition or augmentation.
/// Return `None` if the analysis fails for whatever reason.
pub(super) fn from_source_range(
range: TextRange,
kind: SequenceKind,
locator: &Locator,
tokens: &Tokens,
string_items: &[&'a str],
) -> Option<MultilineStringSequenceValue<'a>> {
// Parse the multiline string sequence using the raw tokens.
// See the docs for `collect_string_sequence_lines()` for why we have to
// use the raw tokens, rather than just the AST, to do this parsing.
//
// Step (1). Start by collecting information on each line individually:
let (lines, ends_with_trailing_comma) =
collect_string_sequence_lines(range, kind, tokens, string_items)?;
// Step (2). Group lines together into sortable "items":
// - Any "item" contains a single element of the list/tuple
// - Assume that any comments on their own line are meant to be grouped
// with the element immediately below them: if the element moves,
// the comments above the element move with it.
// - The same goes for any comments on the same line as an element:
// if the element moves, the comment moves with it.
let items = collect_string_sequence_items(lines, range, locator);
Some(MultilineStringSequenceValue {
items,
range,
ends_with_trailing_comma,
})
}
/// Sort a multiline sequence of literal strings
/// that is known to be unsorted.
///
/// This function panics if it is called and `self.items`
/// has length < 2. It's redundant to call this method in this case,
/// since lists with < 2 items cannot be unsorted,
/// so this is a logic error.
pub(super) fn into_sorted_source_code(
mut self,
sorting_style: SortingStyle,
locator: &Locator,
stylist: &Stylist,
) -> String {
let (first_item_start, last_item_end) = match self.items.as_slice() {
[first_item, .., last_item] => (first_item.start(), last_item.end()),
_ => panic!(
"We shouldn't be attempting an autofix if a sequence has < 2 elements;
a sequence with 1 or 0 elements cannot be unsorted."
),
};
// As well as the "items" in a multiline string sequence,
// there is also a "prelude" and a "postlude":
// - Prelude == the region of source code from the opening parenthesis,
// up to the start of the first item in `__all__`/`__slots__`/etc.
// - Postlude == the region of source code from the end of the last
// item in `__all__`/`__slots__`/etc. up to and including the closing
// parenthesis.
//
// For example:
//
// ```python
// __all__ = [ # comment0
// # comment1
// "first item",
// "last item" # comment2
// # comment3
// ] # comment4
// ```
//
// - The prelude in the above example is the source code region
// starting just before the opening `[` and ending just after `# comment0`.
// `comment0` here counts as part of the prelude because it is on
// the same line as the opening paren, and because we haven't encountered
// any elements of `__all__` yet, but `comment1` counts as part of the first item,
// as it's on its own line, and all comments on their own line are grouped
// with the next element below them to make "items",
// (an "item" being a region of source code that all moves as one unit
// when `__all__` is sorted).
// - The postlude in the above example is the source code region starting
// just after `# comment2` and ending just after the closing paren.
// `# comment2` is part of the last item, as it's an inline comment on the
// same line as an element, but `# comment3` becomes part of the postlude
// because there are no items below it. `# comment4` is not part of the
// postlude: it's outside of the source-code range considered by this rule,
// and should therefore be untouched.
//
let newline = stylist.line_ending().as_str();
let start_offset = self.start();
let leading_indent = leading_indentation(locator.full_line_str(start_offset));
let item_indent = format!("{}{}", leading_indent, stylist.indentation().as_str());
let prelude =
multiline_string_sequence_prelude(first_item_start, newline, start_offset, locator);
let postlude = multiline_string_sequence_postlude(
last_item_end,
newline,
leading_indent,
&item_indent,
self.end(),
locator,
);
// We only add a trailing comma to the last item in the sequence
// as part of `join_multiline_string_sequence_items()`
// if both the following are true:
//
// (1) The last item in the original sequence had a trailing comma; AND,
// (2) The first "semantically significant" token in the postlude is not a comma
// (if the first semantically significant token *is* a comma, and we add another comma,
// we'll end up with two commas after the final item, which would be invalid syntax)
let needs_trailing_comma = self.ends_with_trailing_comma
&& first_non_trivia_token(TextSize::new(0), &postlude)
.is_none_or(|tok| tok.kind() != SimpleTokenKind::Comma);
self.items
.sort_by(|a, b| sorting_style.compare(a.value, b.value));
let joined_items = join_multiline_string_sequence_items(
&self.items,
locator,
&item_indent,
newline,
needs_trailing_comma,
);
format!("{prelude}{joined_items}{postlude}")
}
}
impl Ranged for MultilineStringSequenceValue<'_> {
fn range(&self) -> TextRange {
self.range
}
}
/// Collect data on each line of a multiline string sequence.
/// Return `None` if the sequence appears to be invalid,
/// or if it's an edge case we don't support.
///
/// Why do we need to do this using the raw tokens,
/// when we already have the AST? The AST strips out
/// crucial information that we need to track here for
/// a multiline string sequence, such as:
/// - The value of comments
/// - The amount of whitespace between the end of a line
/// and an inline comment
/// - Whether or not the final item in the tuple/list has a
/// trailing comma
///
/// All of this information is necessary to have at a later
/// stage if we're to sort items without doing unnecessary
/// brutality to the comments and pre-existing style choices
/// in the original source code.
fn collect_string_sequence_lines<'a>(
range: TextRange,
kind: SequenceKind,
tokens: &Tokens,
string_items: &[&'a str],
) -> Option<(Vec<StringSequenceLine<'a>>, bool)> {
// These first two variables are used for keeping track of state
// regarding the entirety of the string sequence...
let mut ends_with_trailing_comma = false;
let mut lines = vec![];
// ... all state regarding a single line of a string sequence
// is encapsulated in this variable
let mut line_state = LineState::default();
// An iterator over the string values in the sequence.
let mut string_items_iter = string_items.iter();
let mut token_iter = tokens.in_range(range).iter();
let first_token = token_iter.next()?;
if first_token.kind() != kind.opening_token_for_multiline_definition() {
return None;
}
let expected_final_token = kind.closing_token_for_multiline_definition();
for token in token_iter {
match token.kind() {
TokenKind::NonLogicalNewline => {
lines.push(line_state.into_string_sequence_line());
line_state = LineState::default();
}
TokenKind::Comment => {
line_state.visit_comment_token(token.range());
}
TokenKind::String => {
let Some(string_value) = string_items_iter.next() else {
unreachable!(
"Expected the number of string tokens to be equal to the number of string items in the sequence"
);
};
line_state.visit_string_token(string_value, token.range());
ends_with_trailing_comma = false;
}
TokenKind::Comma => {
line_state.visit_comma_token(token.range());
ends_with_trailing_comma = true;
}
kind if kind == expected_final_token => {
lines.push(line_state.into_string_sequence_line());
break;
}
_ => return None,
}
}
Some((lines, ends_with_trailing_comma))
}
/// This struct is for keeping track of state
/// regarding a single line in a multiline string sequence
/// It is purely internal to `collect_string_sequence_lines()`,
/// and should not be used outside that function.
///
/// There are three possible kinds of line in a multiline
/// string sequence, and we don't know what kind of a line
/// we're in until all tokens in that line have been processed:
///
/// - A line with just a comment
/// (`StringSequenceLine::JustAComment)`)
/// - A line with one or more string items in it
/// (`StringSequenceLine::OneOrMoreItems`)
/// - An empty line (`StringSequenceLine::Empty`)
///
/// As we process the tokens in a single line,
/// this struct accumulates the necessary state for us
/// to be able to determine what kind of a line we're in.
/// Once the entire line has been processed,
/// `into_string_sequence_line()` is called, which consumes
/// `self` and produces the classification for the line.
#[derive(Debug, Default)]
struct LineState<'a> {
first_item_in_line: Option<(&'a str, TextRange)>,
following_items_in_line: Vec<(&'a str, TextRange)>,
comment_range_start: Option<TextSize>,
comment_in_line: Option<TextRange>,
}
impl<'a> LineState<'a> {
fn visit_string_token(&mut self, token_value: &'a str, token_range: TextRange) {
if self.first_item_in_line.is_none() {
self.first_item_in_line = Some((token_value, token_range));
} else {
self.following_items_in_line
.push((token_value, token_range));
}
self.comment_range_start = Some(token_range.end());
}
fn visit_comma_token(&mut self, token_range: TextRange) {
self.comment_range_start = Some(token_range.end());
}
/// If this is a comment on its own line,
/// record the range of that comment.
///
/// *If*, however, we've already seen a comma
/// or a string in this line, that means that we're
/// in a line with items. In that case, we want to
/// record the range of the comment, *plus* the whitespace
/// (if any) preceding the comment. This is so that we don't
/// unnecessarily apply opinionated formatting changes
/// where they might not be welcome.
fn visit_comment_token(&mut self, token_range: TextRange) {
self.comment_in_line = {
if let Some(comment_range_start) = self.comment_range_start {
Some(TextRange::new(comment_range_start, token_range.end()))
} else {
Some(token_range)
}
}
}
fn into_string_sequence_line(self) -> StringSequenceLine<'a> {
if let Some(first_item) = self.first_item_in_line {
StringSequenceLine::OneOrMoreItems(LineWithItems {
first_item,
following_items: self.following_items_in_line,
trailing_comment_range: self.comment_in_line,
})
} else {
self.comment_in_line
.map_or(StringSequenceLine::Empty, |comment_range| {
StringSequenceLine::JustAComment(LineWithJustAComment(comment_range))
})
}
}
}
/// Instances of this struct represent source-code lines in the middle
/// of multiline tuples/lists/sets where the line contains
/// 0 elements of the sequence, but the line does have a comment in it.
#[derive(Debug)]
struct LineWithJustAComment(TextRange);
/// Instances of this struct represent source-code lines in
/// multiline tuples/lists/sets where the line contains at least
/// 1 element of the sequence. The line may contain > 1 element of the
/// sequence, and may also have a trailing comment after the element(s).
#[derive(Debug)]
struct LineWithItems<'a> {
// For elements in the list, we keep track of the value of the
// value of the element as well as the source-code range of the element.
// (We need to know the actual value so that we can sort the items.)
first_item: (&'a str, TextRange),
following_items: Vec<(&'a str, TextRange)>,
// For comments, we only need to keep track of the source-code range.
trailing_comment_range: Option<TextRange>,
}
impl LineWithItems<'_> {
fn num_items(&self) -> usize {
self.following_items.len() + 1
}
}
/// An enumeration of the possible kinds of source-code lines
/// that can exist in a multiline string sequence:
///
/// - A line that has no string elements, but does have a comment.
/// - A line that has one or more string elements,
/// and may also have a trailing comment.
/// - An entirely empty line.
#[derive(Debug)]
enum StringSequenceLine<'a> {
JustAComment(LineWithJustAComment),
OneOrMoreItems(LineWithItems<'a>),
Empty,
}
/// Given data on each line in a multiline string sequence,
/// group lines together into "items".
///
/// Each item contains exactly one string element,
/// but might contain multiple comments attached to that element
/// that must move with the element when the string sequence is sorted.
///
/// Note that any comments following the last item are discarded here,
/// but that doesn't matter: we add them back in `into_sorted_source_code()`
/// as part of the `postlude` (see comments in that function)
fn collect_string_sequence_items<'a>(
lines: Vec<StringSequenceLine<'a>>,
dunder_all_range: TextRange,
locator: &Locator,
) -> Vec<StringSequenceItem<'a>> {
let mut all_items = Vec::with_capacity(match lines.as_slice() {
[StringSequenceLine::OneOrMoreItems(single)] => single.num_items(),
_ => lines.len(),
});
let mut first_item_encountered = false;
let mut preceding_comment_ranges = vec![];
for line in lines {
match line {
StringSequenceLine::JustAComment(LineWithJustAComment(comment_range)) => {
// Comments on the same line as the opening paren and before any elements
// count as part of the "prelude"; these are not grouped into any item...
if first_item_encountered
|| locator.line_start(comment_range.start())
!= locator.line_start(dunder_all_range.start())
{
// ...but for all other comments that precede an element,
// group the comment with the element following that comment
// into an "item", so that the comment moves as one with the element
// when the list/tuple/set is sorted
preceding_comment_ranges.push(comment_range);
}
}
StringSequenceLine::OneOrMoreItems(LineWithItems {
first_item: (first_val, first_range),
following_items,
trailing_comment_range: comment_range,
}) => {
first_item_encountered = true;
all_items.push(StringSequenceItem::new(
first_val,
std::mem::take(&mut preceding_comment_ranges),
first_range,
comment_range,
));
for (value, range) in following_items {
all_items.push(StringSequenceItem::with_no_comments(value, range));
}
}
StringSequenceLine::Empty => continue, // discard empty lines
}
}
all_items
}
/// An instance of this struct represents a single element
/// from a multiline string sequence, *and* any comments that
/// are "attached" to it. The comments "attached" to the element
/// will move with the element when the tuple/list/set is sorted.
///
/// Comments on their own line immediately preceding the element will
/// always form a contiguous range with the range of the element itself;
/// however, inline comments won't necessary form a contiguous range.
/// Consider the following scenario, where both `# comment0` and `# comment1`
/// will move with the "a" element when the list is sorted:
///
/// ```python
/// __all__ = [
/// "b",
/// # comment0
/// "a", "c", # comment1
/// ]
/// ```
///
/// The desired outcome here is:
///
/// ```python
/// __all__ = [
/// # comment0
/// "a", # comment1
/// "b",
/// "c",
/// ]
/// ```
///
/// To achieve this, both `# comment0` and `# comment1`
/// are grouped into the `StringSequenceItem` instance
/// where the value is `"a"`, even though the source-code range
/// of `# comment1` does not form a contiguous range with the
/// source-code range of `"a"`.
#[derive(Debug)]
struct StringSequenceItem<'a> {
value: &'a str,
preceding_comment_ranges: Vec<TextRange>,
element_range: TextRange,
// total_range incorporates the ranges of preceding comments
// (which must be contiguous with the element),
// but doesn't incorporate any trailing comments
// (which might be contiguous, but also might not be)
total_range: TextRange,
end_of_line_comments: Option<TextRange>,
}
impl<'a> StringSequenceItem<'a> {
fn new(
value: &'a str,
preceding_comment_ranges: Vec<TextRange>,
element_range: TextRange,
end_of_line_comments: Option<TextRange>,
) -> Self {
let total_range = {
if let Some(first_comment_range) = preceding_comment_ranges.first() {
TextRange::new(first_comment_range.start(), element_range.end())
} else {
element_range
}
};
Self {
value,
preceding_comment_ranges,
element_range,
total_range,
end_of_line_comments,
}
}
fn with_no_comments(value: &'a str, element_range: TextRange) -> Self {
Self::new(value, vec![], element_range, None)
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | true |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/indented_form_feed.rs | crates/ruff_linter/src/rules/ruff/rules/indented_form_feed.rs | use memchr::memchr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_source_file::Line;
use ruff_text_size::{TextRange, TextSize};
use crate::{Violation, checkers::ast::LintContext};
/// ## What it does
/// Checks for form feed characters preceded by either a space or a tab.
///
/// ## Why is this bad?
/// [The language reference][lexical-analysis-indentation] states:
///
/// > A formfeed character may be present at the start of the line;
/// > it will be ignored for the indentation calculations above.
/// > Formfeed characters occurring elsewhere in the leading whitespace
/// > have an undefined effect (for instance, they may reset the space count to zero).
///
/// ## Example
///
/// ```python
/// if foo():\n \fbar()
/// ```
///
/// Use instead:
///
/// ```python
/// if foo():\n bar()
/// ```
///
/// [lexical-analysis-indentation]: https://docs.python.org/3/reference/lexical_analysis.html#indentation
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.9.6")]
pub(crate) struct IndentedFormFeed;
impl Violation for IndentedFormFeed {
#[derive_message_formats]
fn message(&self) -> String {
"Indented form feed".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Remove form feed".to_string())
}
}
const FORM_FEED: u8 = b'\x0c';
const SPACE: u8 = b' ';
const TAB: u8 = b'\t';
/// RUF054
pub(crate) fn indented_form_feed(line: &Line, context: &LintContext) {
let Some(index_relative_to_line) = memchr(FORM_FEED, line.as_bytes()) else {
return;
};
if index_relative_to_line == 0 {
return;
}
if line[..index_relative_to_line]
.as_bytes()
.iter()
.any(|byte| *byte != SPACE && *byte != TAB)
{
return;
}
let Ok(relative_index) = u32::try_from(index_relative_to_line) else {
return;
};
let absolute_index = line.start() + TextSize::new(relative_index);
let range = TextRange::at(absolute_index, 1.into());
context.report_diagnostic(IndentedFormFeed, 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/ruff/rules/none_not_at_end_of_union.rs | crates/ruff_linter/src/rules/ruff/rules/none_not_at_end_of_union.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Expr;
use ruff_python_semantic::analyze::typing::traverse_union;
use ruff_text_size::Ranged;
use smallvec::SmallVec;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for type annotations where `None` is not at the end of an union.
///
/// ## Why is this bad?
/// Type annotation unions are commutative, meaning that the order of the elements
/// does not matter. The `None` literal represents the absence of a value. For
/// readability, it's preferred to write the more informative type expressions first.
///
/// ## Example
/// ```python
/// def func(arg: None | int): ...
/// ```
///
/// Use instead:
/// ```python
/// def func(arg: int | None): ...
/// ```
///
/// ## References
/// - [Python documentation: Union type](https://docs.python.org/3/library/stdtypes.html#types-union)
/// - [Python documentation: `typing.Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)
/// - [Python documentation: `None`](https://docs.python.org/3/library/constants.html#None)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.7.4")]
pub(crate) struct NoneNotAtEndOfUnion;
impl Violation for NoneNotAtEndOfUnion {
#[derive_message_formats]
fn message(&self) -> String {
"`None` not at the end of the type annotation.".to_string()
}
}
/// RUF036
pub(crate) fn none_not_at_end_of_union<'a>(checker: &Checker, union: &'a Expr) {
let semantic = checker.semantic();
let mut none_exprs: SmallVec<[&Expr; 1]> = SmallVec::new();
let mut last_expr: Option<&Expr> = None;
let mut find_none = |expr: &'a Expr, _parent: &Expr| {
if matches!(expr, Expr::NoneLiteral(_)) {
none_exprs.push(expr);
}
last_expr = Some(expr);
};
// Walk through all type expressions in the union and keep track of `None` literals.
traverse_union(&mut find_none, semantic, union);
let Some(last_expr) = last_expr else {
return;
};
// The must be at least one `None` expression.
let Some(last_none) = none_exprs.last() else {
return;
};
// If any of the `None` literals is last we do not emit.
if *last_none == last_expr {
return;
}
for none_expr in none_exprs {
checker.report_diagnostic(NoneNotAtEndOfUnion, none_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/ruff/rules/map_int_version_parsing.rs | crates/ruff_linter/src/rules/ruff/rules/map_int_version_parsing.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for calls of the form `map(int, __version__.split("."))`.
///
/// ## Why is this bad?
/// `__version__` does not always contain integral-like elements.
///
/// ```python
/// import matplotlib # `__version__ == "3.9.1.post-1"` in our environment
///
/// # ValueError: invalid literal for int() with base 10: 'post1'
/// tuple(map(int, matplotlib.__version__.split(".")))
/// ```
///
/// See also [*Version specifiers* | Packaging spec][version-specifier].
///
/// ## Example
/// ```python
/// tuple(map(int, matplotlib.__version__.split(".")))
/// ```
///
/// Use instead:
/// ```python
/// import packaging.version as version
///
/// version.parse(matplotlib.__version__)
/// ```
///
/// [version-specifier]: https://packaging.python.org/en/latest/specifications/version-specifiers/#version-specifiers
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct MapIntVersionParsing;
impl Violation for MapIntVersionParsing {
#[derive_message_formats]
fn message(&self) -> String {
"`__version__` may contain non-integral-like elements".to_string()
}
}
/// RUF048
pub(crate) fn map_int_version_parsing(checker: &Checker, call: &ast::ExprCall) {
let semantic = checker.semantic();
let Some((first, second)) = map_call_with_two_arguments(semantic, call) else {
return;
};
if is_dunder_version_split_dot(second) && semantic.match_builtin_expr(first, "int") {
checker.report_diagnostic(MapIntVersionParsing, call.range());
}
}
fn map_call_with_two_arguments<'a>(
semantic: &SemanticModel,
call: &'a ast::ExprCall,
) -> Option<(&'a ast::Expr, &'a ast::Expr)> {
let ast::ExprCall {
func,
arguments:
ast::Arguments {
args,
keywords,
range: _,
node_index: _,
},
range: _,
node_index: _,
} = call;
if !keywords.is_empty() {
return None;
}
let [first, second] = &**args else {
return None;
};
if !semantic.match_builtin_expr(func, "map") {
return None;
}
Some((first, second))
}
/// Whether `expr` has the form `__version__.split(".")` or `something.__version__.split(".")`.
fn is_dunder_version_split_dot(expr: &ast::Expr) -> bool {
let ast::Expr::Call(ast::ExprCall {
func, arguments, ..
}) = expr
else {
return false;
};
if arguments.len() != 1 {
return false;
}
let Some(ast::Expr::StringLiteral(ast::ExprStringLiteral {
value,
range: _,
node_index: _,
})) = arguments.find_argument_value("sep", 0)
else {
return false;
};
if value.to_str() != "." {
return false;
}
is_dunder_version_split(func)
}
fn is_dunder_version_split(func: &ast::Expr) -> bool {
// foo.__version__.split(".")
// ---- value ---- ^^^^^ attr
let ast::Expr::Attribute(ast::ExprAttribute { attr, value, .. }) = func else {
return false;
};
if attr != "split" {
return false;
}
is_dunder_version(value)
}
fn is_dunder_version(expr: &ast::Expr) -> bool {
if let ast::Expr::Name(ast::ExprName { id, .. }) = expr {
return id == "__version__";
}
// foo.__version__.split(".")
// ^^^^^^^^^^^ attr
let ast::Expr::Attribute(ast::ExprAttribute { attr, .. }) = expr else {
return false;
};
attr == "__version__"
}
| 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/ruff/rules/unsafe_markup_use.rs | crates/ruff_linter/src/rules/ruff/rules/unsafe_markup_use.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
/// ## Removed
/// This rule was implemented in `bandit` and has been remapped to
/// [S704](unsafe-markup-use.md)
///
/// ## 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(removed_since = "0.10.0")]
pub(crate) struct RuffUnsafeMarkupUse {
name: String,
}
impl Violation for RuffUnsafeMarkupUse {
#[derive_message_formats]
fn message(&self) -> String {
let RuffUnsafeMarkupUse { name } = self;
format!("Unsafe use of `{name}` detected")
}
}
| 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/ruff/rules/static_key_dict_comprehension.rs | crates/ruff_linter/src/rules/ruff/rules/static_key_dict_comprehension.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
/// ## Removed
/// This rule was implemented in `flake8-bugbear` and has been remapped to [B035]
///
/// ## 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}
/// ```
///
/// [B035]: https://docs.astral.sh/ruff/rules/static-key-dict-comprehension/
#[derive(ViolationMetadata)]
#[violation_metadata(removed_since = "v0.2.0")]
pub(crate) struct RuffStaticKeyDictComprehension;
impl Violation for RuffStaticKeyDictComprehension {
#[derive_message_formats]
fn message(&self) -> String {
"Dictionary comprehension uses static key".to_string()
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/needless_else.rs | crates/ruff_linter/src/rules/ruff/rules/needless_else.rs | use std::cmp::Ordering;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::comment_indentation_after;
use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_python_ast::whitespace::indentation;
use ruff_python_ast::{Stmt, StmtExpr, StmtFor, StmtIf, StmtTry, StmtWhile};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for `else` clauses that only contains `pass` and `...` statements.
///
/// ## Why is this bad?
/// Such an else clause does nothing and can be removed.
///
/// ## Example
/// ```python
/// if foo:
/// bar()
/// else:
/// pass
/// ```
///
/// Use instead:
/// ```python
/// if foo:
/// bar()
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.9.3")]
pub(crate) struct NeedlessElse;
impl AlwaysFixableViolation for NeedlessElse {
#[derive_message_formats]
fn message(&self) -> String {
"Empty `else` clause".to_string()
}
fn fix_title(&self) -> String {
"Remove the `else` clause".to_string()
}
}
/// RUF047
pub(crate) fn needless_else(checker: &Checker, stmt: AnyNodeWithOrElse) {
let source = checker.source();
let tokens = checker.tokens();
let else_body = stmt.else_body();
if !body_is_no_op(else_body) {
return;
}
let Some(else_range) = stmt.else_range(tokens) else {
return;
};
if else_contains_comments(stmt, else_range, checker) {
return;
}
let else_line_start = source.line_start(else_range.start());
let else_full_end = source.full_line_end(else_range.end());
let remove_range = TextRange::new(else_line_start, else_full_end);
let edit = Edit::range_deletion(remove_range);
let fix = Fix::safe_edit(edit);
checker
.report_diagnostic(NeedlessElse, else_range)
.set_fix(fix);
}
/// Whether `body` contains only one `pass` or `...` statement.
fn body_is_no_op(body: &[Stmt]) -> bool {
match body {
[Stmt::Pass(_)] => true,
[Stmt::Expr(StmtExpr { value, .. })] => value.is_ellipsis_literal_expr(),
_ => false,
}
}
fn else_contains_comments(
stmt: AnyNodeWithOrElse,
else_range: TextRange,
checker: &Checker,
) -> bool {
let else_full_end = checker.source().full_line_end(else_range.end());
let commentable_range = TextRange::new(else_range.start(), else_full_end);
// A comment after the `else` keyword or after the dummy statement.
//
// ```python
// if ...:
// ...
// else: # comment
// pass # comment
// ```
if checker.comment_ranges().intersects(commentable_range) {
return true;
}
let Some(preceding_stmt) = stmt.body_before_else().last() else {
return false;
};
let Some(else_last_stmt) = stmt.else_body().last() else {
return false;
};
else_branch_has_preceding_comment(preceding_stmt, else_range, checker)
|| else_branch_has_trailing_comment(else_last_stmt, else_full_end, checker)
}
/// Returns `true` if the `else` clause header has a leading own-line comment.
///
/// ```python
/// if ...:
/// ...
/// # some comment
/// else:
/// pass
/// ```
fn else_branch_has_preceding_comment(
preceding_stmt: &Stmt,
else_range: TextRange,
checker: &Checker,
) -> bool {
let (tokens, source) = (checker.tokens(), checker.source());
let before_else_full_end = source.full_line_end(preceding_stmt.end());
let preceding_indentation = indentation(source, &preceding_stmt)
.unwrap_or_default()
.text_len();
for token in tokens.in_range(TextRange::new(before_else_full_end, else_range.start())) {
if token.kind() != TokenKind::Comment {
continue;
}
let comment_indentation =
comment_indentation_after(preceding_stmt.into(), token.range(), source);
match comment_indentation.cmp(&preceding_indentation) {
// Comment belongs to preceding statement.
Ordering::Greater | Ordering::Equal => continue,
Ordering::Less => return true,
}
}
false
}
/// Returns `true` if the `else` branch has a trailing own line comment:
///
/// ```python
/// if ...:
/// ...
/// else:
/// pass
/// # some comment
/// ```
fn else_branch_has_trailing_comment(
last_else_stmt: &Stmt,
else_full_end: TextSize,
checker: &Checker,
) -> bool {
let (tokens, source) = (checker.tokens(), checker.source());
let preceding_indentation = indentation(source, &last_else_stmt)
.unwrap_or_default()
.text_len();
for token in tokens.after(else_full_end) {
match token.kind() {
TokenKind::Comment => {
let comment_indentation =
comment_indentation_after(last_else_stmt.into(), token.range(), source);
match comment_indentation.cmp(&preceding_indentation) {
Ordering::Greater | Ordering::Equal => return true,
Ordering::Less => break,
}
}
TokenKind::NonLogicalNewline
| TokenKind::Newline
| TokenKind::Indent
| TokenKind::Dedent => {}
_ => break,
}
}
false
}
#[derive(Copy, Clone, Debug)]
pub(crate) enum AnyNodeWithOrElse<'a> {
While(&'a StmtWhile),
For(&'a StmtFor),
Try(&'a StmtTry),
If(&'a StmtIf),
}
impl<'a> AnyNodeWithOrElse<'a> {
/// Returns the range from the `else` keyword to the last statement in its block.
fn else_range(self, tokens: &Tokens) -> Option<TextRange> {
match self {
Self::For(_) | Self::While(_) | Self::Try(_) => {
let before_else = self.body_before_else();
let else_body = self.else_body();
let end = else_body.last()?.end();
let start = tokens
.in_range(TextRange::new(before_else.last()?.end(), end))
.iter()
.find(|token| token.kind() == TokenKind::Else)?
.start();
Some(TextRange::new(start, end))
}
Self::If(StmtIf {
elif_else_clauses, ..
}) => elif_else_clauses
.last()
.filter(|clause| clause.test.is_none())
.map(Ranged::range),
}
}
/// Returns the suite before the else block.
fn body_before_else(self) -> &'a [Stmt] {
match self {
Self::Try(StmtTry { body, handlers, .. }) => handlers
.last()
.and_then(|handler| handler.as_except_handler())
.map(|handler| &handler.body)
.unwrap_or(body),
Self::While(StmtWhile { body, .. }) | Self::For(StmtFor { body, .. }) => body,
Self::If(StmtIf {
body,
elif_else_clauses,
..
}) => elif_else_clauses
.iter()
.rev()
.find(|clause| clause.test.is_some())
.map(|clause| &*clause.body)
.unwrap_or(body),
}
}
/// Returns the `else` suite.
/// Defaults to an empty suite if the statement has no `else` block.
fn else_body(self) -> &'a [Stmt] {
match self {
Self::While(StmtWhile { orelse, .. })
| Self::For(StmtFor { orelse, .. })
| Self::Try(StmtTry { orelse, .. }) => orelse,
Self::If(StmtIf {
elif_else_clauses, ..
}) => elif_else_clauses
.last()
.filter(|clause| clause.test.is_none())
.map(|clause| &*clause.body)
.unwrap_or_default(),
}
}
}
impl<'a> From<&'a StmtFor> for AnyNodeWithOrElse<'a> {
fn from(value: &'a StmtFor) -> Self {
Self::For(value)
}
}
impl<'a> From<&'a StmtWhile> for AnyNodeWithOrElse<'a> {
fn from(value: &'a StmtWhile) -> Self {
Self::While(value)
}
}
impl<'a> From<&'a StmtIf> for AnyNodeWithOrElse<'a> {
fn from(value: &'a StmtIf) -> Self {
Self::If(value)
}
}
impl<'a> From<&'a StmtTry> for AnyNodeWithOrElse<'a> {
fn from(value: &'a StmtTry) -> Self {
Self::Try(value)
}
}
| 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/ruff/rules/logging_eager_conversion.rs | crates/ruff_linter/src/rules/ruff/rules/logging_eager_conversion.rs | use std::str::FromStr;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_literal::cformat::{
CConversionFlags, CFormatPart, CFormatSpec, CFormatString, CFormatType,
};
use ruff_python_literal::format::FormatConversion;
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::flake8_logging_format::rules::{LoggingCallType, find_logging_call};
/// ## What it does
/// Checks for eager string conversion of arguments to `logging` calls.
///
/// ## Why is this bad?
/// Arguments to `logging` calls will be formatted as strings automatically, so it
/// is unnecessary and less efficient to eagerly format the arguments before passing
/// them in.
///
/// ## Known problems
///
/// This rule detects uses of the `logging` module via a heuristic.
/// Specifically, it matches against:
///
/// - Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).
/// - Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).
/// - Objects whose name starts with `log` or ends with `logger` or `logging`,
/// when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).
/// - Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be
/// used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,
/// when [`lint.logger-objects`] is set to `["module.logger"]`).
///
/// ## Example
/// ```python
/// import logging
///
/// logging.basicConfig(format="%(message)s", level=logging.INFO)
///
/// user = "Maria"
///
/// logging.info("%s - Something happened", str(user))
/// ```
///
/// Use instead:
/// ```python
/// import logging
///
/// logging.basicConfig(format="%(message)s", level=logging.INFO)
///
/// user = "Maria"
///
/// logging.info("%s - Something happened", user)
/// ```
///
/// ## Options
/// - `lint.logger-objects`
///
/// ## References
/// - [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)
/// - [Python documentation: Optimization](https://docs.python.org/3/howto/logging.html#optimization)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.13.2")]
pub(crate) struct LoggingEagerConversion {
pub(crate) format_conversion: FormatConversion,
pub(crate) function_name: Option<&'static str>,
}
impl Violation for LoggingEagerConversion {
#[derive_message_formats]
fn message(&self) -> String {
let LoggingEagerConversion {
format_conversion,
function_name,
} = self;
match (format_conversion, function_name.as_deref()) {
(FormatConversion::Str, Some("oct")) => {
"Unnecessary `oct()` conversion when formatting with `%s`. \
Use `%#o` instead of `%s`"
.to_string()
}
(FormatConversion::Str, Some("hex")) => {
"Unnecessary `hex()` conversion when formatting with `%s`. \
Use `%#x` instead of `%s`"
.to_string()
}
(FormatConversion::Str, _) => {
"Unnecessary `str()` conversion when formatting with `%s`".to_string()
}
(FormatConversion::Repr, _) => {
"Unnecessary `repr()` conversion when formatting with `%s`. \
Use `%r` instead of `%s`"
.to_string()
}
(FormatConversion::Ascii, _) => {
"Unnecessary `ascii()` conversion when formatting with `%s`. \
Use `%a` instead of `%s`"
.to_string()
}
(FormatConversion::Bytes, _) => {
"Unnecessary `bytes()` conversion when formatting with `%b`".to_string()
}
}
}
}
/// RUF065
pub(crate) fn logging_eager_conversion(checker: &Checker, call: &ast::ExprCall) {
let Some((logging_call_type, _range)) = find_logging_call(checker, call) else {
return;
};
let msg_pos = match logging_call_type {
LoggingCallType::LevelCall(_) => 0,
LoggingCallType::LogCall => 1,
};
// Extract a format string from the logging statement msg argument
let Some(Expr::StringLiteral(string_literal)) =
call.arguments.find_argument_value("msg", msg_pos)
else {
return;
};
let Ok(format_string) = CFormatString::from_str(string_literal.value.to_str()) else {
return;
};
// Iterate over % placeholders in format string and zip with logging statement arguments
for (spec, arg) in format_string
.iter()
.filter_map(|(_, part)| {
if let CFormatPart::Spec(spec) = part {
Some(spec)
} else {
None
}
})
.zip(call.arguments.args.iter().skip(msg_pos + 1))
{
// Check if the argument is a call to eagerly format a value
if let Expr::Call(ast::ExprCall {
func,
arguments: str_call_args,
..
}) = arg
{
let CFormatType::String(format_conversion) = spec.format_type else {
continue;
};
// Check for various eager conversion patterns
match format_conversion {
// %s with str() - remove str() call
// Only flag if str() has exactly one argument (positional or keyword) that is not unpacked
FormatConversion::Str
if checker.semantic().match_builtin_expr(func.as_ref(), "str")
&& str_call_args.len() == 1
&& str_call_args
.find_argument("object", 0)
.is_some_and(|arg| !arg.is_variadic()) =>
{
checker.report_diagnostic(
LoggingEagerConversion {
format_conversion,
function_name: None,
},
arg.range(),
);
}
// %s with repr() - suggest using %r instead
FormatConversion::Str
if checker.semantic().match_builtin_expr(func.as_ref(), "repr") =>
{
checker.report_diagnostic(
LoggingEagerConversion {
format_conversion: FormatConversion::Repr,
function_name: None,
},
arg.range(),
);
}
// %s with ascii() - suggest using %a instead
FormatConversion::Str
if checker
.semantic()
.match_builtin_expr(func.as_ref(), "ascii") =>
{
checker.report_diagnostic(
LoggingEagerConversion {
format_conversion: FormatConversion::Ascii,
function_name: None,
},
arg.range(),
);
}
// %s with oct() - suggest using %#o instead
FormatConversion::Str
if checker.semantic().match_builtin_expr(func.as_ref(), "oct")
&& !has_complex_conversion_specifier(spec) =>
{
checker.report_diagnostic(
LoggingEagerConversion {
format_conversion: FormatConversion::Str,
function_name: Some("oct"),
},
arg.range(),
);
}
// %s with hex() - suggest using %#x instead
FormatConversion::Str
if checker.semantic().match_builtin_expr(func.as_ref(), "hex")
&& !has_complex_conversion_specifier(spec) =>
{
checker.report_diagnostic(
LoggingEagerConversion {
format_conversion: FormatConversion::Str,
function_name: Some("hex"),
},
arg.range(),
);
}
_ => {}
}
}
}
}
/// Check if a conversion specifier has complex flags or precision that make `oct()` or `hex()` necessary.
///
/// Returns `true` if any of these conditions are met:
/// - Flag `0` (zero-pad) is used, flag `-` (left-adjust) is not used, and minimum width is specified
/// - Flag ` ` (blank sign) is used
/// - Flag `+` (sign char) is used
/// - Precision is specified
fn has_complex_conversion_specifier(spec: &CFormatSpec) -> bool {
if spec.flags.intersects(CConversionFlags::ZERO_PAD)
&& !spec.flags.intersects(CConversionFlags::LEFT_ADJUST)
&& spec.min_field_width.is_some()
{
return true;
}
spec.flags
.intersects(CConversionFlags::BLANK_SIGN | CConversionFlags::SIGN_CHAR)
|| spec.precision.is_some()
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/class_with_mixed_type_vars.rs | crates/ruff_linter/src/rules/ruff/rules/class_with_mixed_type_vars.rs | use rustc_hash::FxHashSet;
use std::iter;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{
Arguments, Expr, ExprStarred, ExprSubscript, ExprTuple, StmtClassDef, TypeParams,
};
use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::rules::pyupgrade::rules::pep695::{
DisplayTypeVars, TypeParamKind, TypeVar, expr_name_to_type_var, find_generic,
};
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
/// ## What it does
/// Checks for classes that have [PEP 695] [type parameter lists]
/// while also inheriting from `typing.Generic` or `typing_extensions.Generic`.
///
/// ## Why is this bad?
/// Such classes cause errors at runtime:
///
/// ```python
/// from typing import Generic, TypeVar
///
/// U = TypeVar("U")
///
/// # TypeError: Cannot inherit from Generic[...] multiple times.
/// class C[T](Generic[U]): ...
/// ```
///
/// ## Example
///
/// ```python
/// from typing import Generic, ParamSpec, TypeVar, TypeVarTuple
///
/// U = TypeVar("U")
/// P = ParamSpec("P")
/// Ts = TypeVarTuple("Ts")
///
///
/// class C[T](Generic[U, P, *Ts]): ...
/// ```
///
/// Use instead:
///
/// ```python
/// class C[T, U, **P, *Ts]: ...
/// ```
///
/// ## Fix safety
/// As the fix changes runtime behaviour, it is always marked as unsafe.
/// Additionally, comments within the fix range will not be preserved.
///
/// ## References
/// - [Python documentation: User-defined generic types](https://docs.python.org/3/library/typing.html#user-defined-generic-types)
/// - [Python documentation: type parameter lists](https://docs.python.org/3/reference/compound_stmts.html#type-params)
/// - [PEP 695 - Type Parameter Syntax](https://peps.python.org/pep-0695/)
///
/// [PEP 695]: https://peps.python.org/pep-0695/
/// [type parameter lists]: https://docs.python.org/3/reference/compound_stmts.html#type-params
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct ClassWithMixedTypeVars;
impl Violation for ClassWithMixedTypeVars {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Class with type parameter list inherits from `Generic`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Remove `Generic` base class".to_string())
}
}
/// RUF053
pub(crate) fn class_with_mixed_type_vars(checker: &Checker, class_def: &StmtClassDef) {
if checker.target_version() < PythonVersion::PY312 {
return;
}
let StmtClassDef {
type_params,
arguments,
..
} = class_def;
let Some(type_params) = type_params else {
return;
};
let Some(arguments) = arguments else {
return;
};
let Some((generic_base, old_style_type_vars)) =
typing_generic_base_and_arguments(arguments, checker.semantic())
else {
return;
};
let mut diagnostic = checker.report_diagnostic(ClassWithMixedTypeVars, generic_base.range);
diagnostic.try_set_optional_fix(|| {
convert_type_vars(
generic_base,
old_style_type_vars,
type_params,
arguments,
checker,
)
});
}
fn typing_generic_base_and_arguments<'a>(
class_arguments: &'a Arguments,
semantic: &SemanticModel,
) -> Option<(&'a ExprSubscript, &'a Expr)> {
let (_, base @ ExprSubscript { slice, .. }) = find_generic(class_arguments, semantic)?;
Some((base, slice.as_ref()))
}
fn convert_type_vars(
generic_base: &ExprSubscript,
old_style_type_vars: &Expr,
type_params: &TypeParams,
class_arguments: &Arguments,
checker: &Checker,
) -> anyhow::Result<Option<Fix>> {
let mut type_vars: Vec<_> = type_params.type_params.iter().map(TypeVar::from).collect();
let semantic = checker.semantic();
let converted_type_vars = match old_style_type_vars {
Expr::Tuple(ExprTuple { elts, .. }) => {
generic_arguments_to_type_vars(elts.iter(), type_params, semantic)
}
expr @ (Expr::Subscript(_) | Expr::Name(_)) => {
generic_arguments_to_type_vars(iter::once(expr), type_params, semantic)
}
_ => None,
};
let Some(converted_type_vars) = converted_type_vars else {
return Ok(None);
};
type_vars.extend(converted_type_vars);
let source = checker.source();
let new_type_params = DisplayTypeVars {
type_vars: &type_vars,
source,
};
let remove_generic_base = remove_argument(
generic_base,
class_arguments,
Parentheses::Remove,
source,
checker.tokens(),
)?;
let replace_type_params =
Edit::range_replacement(new_type_params.to_string(), type_params.range);
Ok(Some(Fix::unsafe_edits(
remove_generic_base,
[replace_type_params],
)))
}
/// Returns the type variables `exprs` represent.
///
/// If at least one of them cannot be converted to [`TypeVar`],
/// `None` is returned.
fn generic_arguments_to_type_vars<'a>(
exprs: impl Iterator<Item = &'a Expr>,
existing_type_params: &TypeParams,
semantic: &'a SemanticModel,
) -> Option<Vec<TypeVar<'a>>> {
let mut type_vars = vec![];
let mut encountered: FxHashSet<&str> = existing_type_params
.iter()
.map(|tp| tp.name().as_str())
.collect();
for expr in exprs {
let (name, unpacked) = match expr {
Expr::Name(name) => (name, false),
Expr::Starred(ExprStarred { value, .. }) => (value.as_name_expr()?, true),
Expr::Subscript(ExprSubscript { value, slice, .. }) => {
if !semantic.match_typing_expr(value, "Unpack") {
return None;
}
(slice.as_name_expr()?, true)
}
_ => return None,
};
if !encountered.insert(name.id.as_str()) {
continue;
}
let type_var = expr_name_to_type_var(semantic, name)?;
if !type_var_is_valid(&type_var, unpacked) {
return None;
}
// TODO: Type parameter defaults
if type_var.default.is_some() {
return None;
}
type_vars.push(type_var);
}
Some(type_vars)
}
/// Returns true in the following cases:
///
/// * If `type_var` is a `TypeVar`:
/// * It must not be unpacked
/// * If `type_var` is a `TypeVarTuple`:
/// * It must be unpacked
/// * It must not have any restrictions
/// * If `type_var` is a `ParamSpec`:
/// * It must not be unpacked
/// * It must not have any restrictions
fn type_var_is_valid(type_var: &TypeVar, unpacked: bool) -> bool {
let is_type_var_tuple = matches!(&type_var.kind, TypeParamKind::TypeVarTuple);
if is_type_var_tuple && !unpacked || !is_type_var_tuple && unpacked {
return false;
}
if !matches!(&type_var.kind, TypeParamKind::TypeVar) && type_var.restriction.is_some() {
return false;
}
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/ruff/rules/unnecessary_round.rs | crates/ruff_linter/src/rules/ruff/rules/unnecessary_round.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Arguments, Expr, ExprCall, ExprNumberLiteral, Number};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType};
use ruff_python_semantic::analyze::typing;
use ruff_source_file::find_newline;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
/// ## What it does
/// Checks for `round()` calls that have no effect on the input.
///
/// ## Why is this bad?
/// Rounding a value that's already an integer is unnecessary.
/// It's clearer to use the value directly.
///
/// ## Example
///
/// ```python
/// a = round(1, 0)
/// ```
///
/// Use instead:
///
/// ```python
/// a = 1
/// ```
///
/// ## Fix safety
///
/// The fix is marked unsafe if it is not possible to guarantee that the first argument of
/// `round()` is of type `int`, or if the fix deletes comments.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct UnnecessaryRound;
impl AlwaysFixableViolation for UnnecessaryRound {
#[derive_message_formats]
fn message(&self) -> String {
"Value being rounded is already an integer".to_string()
}
fn fix_title(&self) -> String {
"Remove unnecessary `round` call".to_string()
}
}
/// RUF057
pub(crate) fn unnecessary_round(checker: &Checker, call: &ExprCall) {
if !checker.semantic().match_builtin_expr(&call.func, "round") {
return;
}
let Some((rounded, rounded_value, ndigits_value)) =
rounded_and_ndigits(&call.arguments, checker.semantic())
else {
return;
};
if !matches!(
ndigits_value,
NdigitsValue::NotGivenOrNone | NdigitsValue::LiteralInt { is_negative: false }
) {
return;
}
let mut applicability = match rounded_value {
// ```python
// some_int: int
//
// rounded(1)
// rounded(1, None)
// rounded(1, 42)
// rounded(1, 4 + 2)
// rounded(1, some_int)
// ```
RoundedValue::Int(InferredType::Equivalent) => Applicability::Safe,
// ```python
// some_int: int
// some_other_int: int
//
// rounded(some_int)
// rounded(some_int, None)
// rounded(some_int, 42)
// rounded(some_int, 4 + 2)
// rounded(some_int, some_other_int)
// ```
RoundedValue::Int(InferredType::AssignableTo) => Applicability::Unsafe,
_ => return,
};
if checker.comment_ranges().intersects(call.range()) {
applicability = Applicability::Unsafe;
}
let edit = unwrap_round_call(call, rounded, checker.semantic(), checker.locator());
let fix = Fix::applicable_edit(edit, applicability);
checker
.report_diagnostic(UnnecessaryRound, call.range())
.set_fix(fix);
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum InferredType {
/// The value is an exact instance of the type in question.
Equivalent,
/// The value is an instance of the type in question or a subtype thereof.
AssignableTo,
}
/// The type of the first argument to `round()`
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum RoundedValue {
Int(InferredType),
Float(InferredType),
Other,
}
/// The type of the second argument to `round()`
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum NdigitsValue {
NotGivenOrNone,
LiteralInt { is_negative: bool },
Int(InferredType),
Other,
}
/// Extracts the rounded and `ndigits` values from `arguments`.
///
/// Returns a tripled where the first element is the rounded value's expression, the second is the rounded value,
///and the third is the `ndigits` value.
pub(super) fn rounded_and_ndigits<'a>(
arguments: &'a Arguments,
semantic: &'a SemanticModel,
) -> Option<(&'a Expr, RoundedValue, NdigitsValue)> {
if arguments.len() > 2 {
return None;
}
// *args
if arguments.args.iter().any(Expr::is_starred_expr) {
return None;
}
// **kwargs
if arguments.keywords.iter().any(|kw| kw.arg.is_none()) {
return None;
}
let rounded = arguments.find_argument_value("number", 0)?;
let ndigits = arguments.find_argument_value("ndigits", 1);
let rounded_kind = match rounded {
Expr::Name(name) => match semantic.only_binding(name).map(|id| semantic.binding(id)) {
Some(binding) if typing::is_int(binding, semantic) => {
RoundedValue::Int(InferredType::AssignableTo)
}
Some(binding) if typing::is_float(binding, semantic) => {
RoundedValue::Float(InferredType::AssignableTo)
}
_ => RoundedValue::Other,
},
_ => match ResolvedPythonType::from(rounded) {
ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) => {
RoundedValue::Int(InferredType::Equivalent)
}
ResolvedPythonType::Atom(PythonType::Number(NumberLike::Float)) => {
RoundedValue::Float(InferredType::Equivalent)
}
_ => RoundedValue::Other,
},
};
let ndigits_kind = match ndigits {
None | Some(Expr::NoneLiteral(_)) => NdigitsValue::NotGivenOrNone,
Some(Expr::Name(name)) => {
match semantic.only_binding(name).map(|id| semantic.binding(id)) {
Some(binding) if typing::is_int(binding, semantic) => {
NdigitsValue::Int(InferredType::AssignableTo)
}
_ => NdigitsValue::Other,
}
}
Some(Expr::NumberLiteral(ExprNumberLiteral {
value: Number::Int(int),
..
})) => match int.as_i64() {
None => NdigitsValue::Int(InferredType::Equivalent),
Some(value) => NdigitsValue::LiteralInt {
is_negative: value < 0,
},
},
Some(ndigits) => match ResolvedPythonType::from(ndigits) {
ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer)) => {
NdigitsValue::Int(InferredType::Equivalent)
}
_ => NdigitsValue::Other,
},
};
Some((rounded, rounded_kind, ndigits_kind))
}
fn unwrap_round_call(
call: &ExprCall,
rounded: &Expr,
semantic: &SemanticModel,
locator: &Locator,
) -> Edit {
let rounded_expr = locator.slice(rounded.range());
let has_parent_expr = semantic.current_expression_parent().is_some();
let new_content =
if has_parent_expr || rounded.is_named_expr() || find_newline(rounded_expr).is_some() {
format!("({rounded_expr})")
} else {
rounded_expr.to_string()
};
Edit::range_replacement(new_content, 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/ruff/rules/suppression_comment_visitor.rs | crates/ruff_linter/src/rules/ruff/rules/suppression_comment_visitor.rs | use std::iter::Peekable;
use ruff_python_ast::{
AnyNodeRef, Suite,
helpers::comment_indentation_after,
visitor::source_order::{self, SourceOrderVisitor, TraversalSignal},
};
use ruff_python_trivia::{
CommentLinePosition, SimpleTokenizer, SuppressionKind, indentation_at_offset,
};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::Locator;
#[derive(Clone, Copy, Debug)]
pub(super) struct SuppressionComment {
pub(super) range: TextRange,
pub(super) kind: SuppressionKind,
}
/// Visitor that captures AST data for suppression comments. This uses a similar approach
/// to `CommentsVisitor` in the formatter crate.
pub(super) struct SuppressionCommentVisitor<
'src,
'builder,
I: Iterator<Item = SuppressionComment> + 'src,
> {
comments: Peekable<I>,
parents: Vec<AnyNodeRef<'src>>,
preceding_node: Option<AnyNodeRef<'src>>,
builder: &'builder mut (dyn CaptureSuppressionComment<'src> + 'src),
locator: &'src Locator<'src>,
}
impl<'src, 'builder, I> SuppressionCommentVisitor<'src, 'builder, I>
where
I: Iterator<Item = SuppressionComment> + 'src,
{
pub(super) fn new(
comment_ranges: I,
builder: &'builder mut (dyn CaptureSuppressionComment<'src> + 'src),
locator: &'src Locator<'src>,
) -> Self {
Self {
comments: comment_ranges.peekable(),
parents: Vec::default(),
preceding_node: Option::default(),
builder,
locator,
}
}
pub(super) fn visit(mut self, suite: &'src Suite) {
self.visit_body(suite.as_slice());
}
fn can_skip(&mut self, node_end: TextSize) -> bool {
self.comments
.peek()
.is_none_or(|next| next.range.start() >= node_end)
}
}
impl<'ast, I> SourceOrderVisitor<'ast> for SuppressionCommentVisitor<'ast, '_, I>
where
I: Iterator<Item = SuppressionComment> + 'ast,
{
fn enter_node(&mut self, node: AnyNodeRef<'ast>) -> TraversalSignal {
let node_range = node.range();
let enclosing_node = self.parents.last().copied();
// Process all remaining comments that end before this node's start position.
// If the `preceding` node is set, then it process all comments ending after the `preceding` node
// and ending before this node's start position
while let Some(SuppressionComment { range, kind }) = self.comments.peek().copied() {
// Exit if the comment is enclosed by this node or comes after it
if range.end() > node_range.start() {
break;
}
let line_position = CommentLinePosition::for_range(range, self.locator.contents());
let data = SuppressionCommentData {
enclosing: enclosing_node,
preceding: self.preceding_node,
following: Some(node),
line_position,
kind,
range,
};
self.builder.capture(data);
self.comments.next();
}
// From here on, we're inside of `node`, meaning, we're passed the preceding node.
self.preceding_node = None;
self.parents.push(node);
if self.can_skip(node_range.end()) {
TraversalSignal::Skip
} else {
TraversalSignal::Traverse
}
}
fn leave_node(&mut self, node: AnyNodeRef<'ast>) {
self.parents.pop();
let node_end = node.end();
// Process all comments that start after the `preceding` node and end before this node's end.
while let Some(SuppressionComment { range, kind }) = self.comments.peek().copied() {
let line_position = CommentLinePosition::for_range(range, self.locator.contents());
if range.start() >= node_end {
let between = TextRange::new(node_end, range.start());
// Check if a non-trivial token exists between the end of this node and the start of the comment.
// If it doesn't, that means this comment could possibly be a trailing comment that comes after the
// end of this node.
// For example:
// ```
// def func(x):
// pass # fmt: skip
// ```
// We want to make sure that `# fmt: skip` is associated with the `pass` statement,
// even though it comes after the end of that node.
if SimpleTokenizer::new(self.locator.contents(), between)
.skip_trivia()
.next()
.is_some()
{
break;
}
// If the comment is on its own line, it could still be a trailing comment if it has a greater
// level of indentation compared to this node. For example:
// ```
// def func(x):
// # fmt: off
// pass
// # fmt: on
// def func2(y):
// pass
// ```
// We want `# fmt: on` to be considered a trailing comment of `func(x)` instead of a leading comment
// on `func2(y)`.
if line_position.is_own_line() {
let comment_indent =
comment_indentation_after(node, range, self.locator.contents());
let node_indent = TextSize::of(
indentation_at_offset(node.start(), self.locator.contents())
.unwrap_or_default(),
);
if node_indent >= comment_indent {
break;
}
}
}
let data = SuppressionCommentData {
enclosing: Some(node),
preceding: self.preceding_node,
following: None,
line_position,
kind,
range,
};
self.builder.capture(data);
self.comments.next();
}
self.preceding_node = Some(node);
}
fn visit_body(&mut self, body: &'ast [ruff_python_ast::Stmt]) {
match body {
[] => {
// no-op
}
[only] => {
self.visit_stmt(only);
}
[first, .., last] => {
if self.can_skip(last.end()) {
// Skip traversing the body when there's no comment between the first and last statement.
// It is still necessary to visit the first statement to process all comments between
// the previous node and the first statement.
self.visit_stmt(first);
self.preceding_node = Some(last.into());
} else {
source_order::walk_body(self, body);
}
}
}
}
fn visit_identifier(&mut self, _identifier: &'ast ruff_python_ast::Identifier) {
// Skip identifiers, matching the formatter comment extraction
}
}
#[derive(Clone, Debug)]
pub(super) struct SuppressionCommentData<'src> {
/// The AST node that encloses the comment. If `enclosing` is `None`, this comment is a top-level statement.
pub(super) enclosing: Option<AnyNodeRef<'src>>,
/// An AST node that comes directly before the comment. A child of `enclosing`.
pub(super) preceding: Option<AnyNodeRef<'src>>,
/// An AST node that comes directly after the comment. A child of `enclosing`.
pub(super) following: Option<AnyNodeRef<'src>>,
/// The line position of the comment - it can either be on its own line, or at the end of a line.
pub(super) line_position: CommentLinePosition,
/// Whether this comment is `fmt: off`, `fmt: on`, or `fmt: skip` (or `yapf disable` / `yapf enable`)
pub(super) kind: SuppressionKind,
/// The range of text that makes up the comment. This includes the `#` prefix.
pub(super) range: TextRange,
}
pub(super) trait CaptureSuppressionComment<'src> {
/// This is the entrypoint for the capturer to analyze the next comment.
fn capture(&mut self, comment: SuppressionCommentData<'src>);
}
| 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/ruff/rules/sort_dunder_all.rs | crates/ruff_linter/src/rules/ruff/rules/sort_dunder_all.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_source_file::LineRanges;
use ruff_text_size::TextRange;
use crate::checkers::ast::Checker;
use crate::rules::ruff::rules::sequence_sorting::{
MultilineStringSequenceValue, SequenceKind, SortClassification, SortingStyle,
sort_single_line_elements_sequence,
};
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `__all__` definitions that are not ordered
/// according to an "isort-style" sort.
///
/// An isort-style sort orders items first according to their casing:
/// SCREAMING_SNAKE_CASE names (conventionally used for global constants)
/// come first, followed by CamelCase names (conventionally used for
/// classes), followed by anything else. Within each category,
/// a [natural sort](https://en.wikipedia.org/wiki/Natural_sort_order)
/// is used to order the elements.
///
/// ## Why is this bad?
/// Consistency is good. Use a common convention for `__all__` to make your
/// code more readable and idiomatic.
///
/// ## Example
/// ```python
/// import sys
///
/// __all__ = [
/// "b",
/// "c",
/// "a",
/// ]
///
/// if sys.platform == "win32":
/// __all__ += ["z", "y"]
/// ```
///
/// Use instead:
/// ```python
/// import sys
///
/// __all__ = [
/// "a",
/// "b",
/// "c",
/// ]
///
/// if sys.platform == "win32":
/// __all__ += ["y", "z"]
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there are any comments that take up
/// a whole line by themselves inside the `__all__` definition, for example:
/// ```py
/// __all__ = [
/// # eggy things
/// "duck_eggs",
/// "chicken_eggs",
/// # hammy things
/// "country_ham",
/// "parma_ham",
/// ]
/// ```
///
/// This is a common pattern used to delimit categories within a module's API,
/// but it would be out of the scope of this rule to attempt to maintain these
/// categories when alphabetically sorting the items of `__all__`.
///
/// The fix is also marked as unsafe if there are more than two `__all__` items
/// on a single line and that line also has a trailing comment, since here it
/// is impossible to accurately gauge which item the comment should be moved
/// with when sorting `__all__`:
/// ```py
/// __all__ = [
/// "a", "c", "e", # a comment
/// "b", "d", "f", # a second comment
/// ]
/// ```
///
/// Other than this, the rule's fix is marked as always being safe, in that
/// it should very rarely alter the semantics of any Python code.
/// However, note that (although it's rare) the value of `__all__`
/// could be read by code elsewhere that depends on the exact
/// iteration order of the items in `__all__`, in which case this
/// rule's fix could theoretically cause breakage.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.8.0")]
pub(crate) struct UnsortedDunderAll;
impl Violation for UnsortedDunderAll {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`__all__` is not sorted".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Apply an isort-style sorting to `__all__`".to_string())
}
}
const SORTING_STYLE: SortingStyle = SortingStyle::Isort;
/// Sort an `__all__` definition represented by a `StmtAssign` AST node.
/// For example: `__all__ = ["b", "c", "a"]`.
pub(crate) fn sort_dunder_all_assign(
checker: &Checker,
ast::StmtAssign { value, targets, .. }: &ast::StmtAssign,
) {
if let [expr] = targets.as_slice() {
sort_dunder_all(checker, expr, value);
}
}
/// Sort an `__all__` mutation represented by a `StmtAugAssign` AST node.
/// For example: `__all__ += ["b", "c", "a"]`.
pub(crate) fn sort_dunder_all_aug_assign(checker: &Checker, node: &ast::StmtAugAssign) {
if node.op.is_add() {
sort_dunder_all(checker, &node.target, &node.value);
}
}
/// Sort a tuple or list passed to `__all__.extend()`.
pub(crate) fn sort_dunder_all_extend_call(
checker: &Checker,
ast::ExprCall {
func,
arguments: ast::Arguments { args, keywords, .. },
..
}: &ast::ExprCall,
) {
let ([value_passed], []) = (&**args, &**keywords) else {
return;
};
let ast::Expr::Attribute(ast::ExprAttribute {
ref value,
ref attr,
..
}) = **func
else {
return;
};
if attr == "extend" {
sort_dunder_all(checker, value, value_passed);
}
}
/// Sort an `__all__` definition represented by a `StmtAnnAssign` AST node.
/// For example: `__all__: list[str] = ["b", "c", "a"]`.
pub(crate) fn sort_dunder_all_ann_assign(checker: &Checker, node: &ast::StmtAnnAssign) {
if let Some(value) = &node.value {
sort_dunder_all(checker, &node.target, value);
}
}
/// RUF022
/// Sort a tuple or list that defines or mutates the global variable `__all__`.
///
/// This routine checks whether the tuple or list is sorted, and emits a
/// violation if it is not sorted. If the tuple/list was not sorted,
/// it attempts to set a `Fix` on the violation.
fn sort_dunder_all(checker: &Checker, target: &ast::Expr, node: &ast::Expr) {
let ast::Expr::Name(ast::ExprName { id, .. }) = target else {
return;
};
if id != "__all__" {
return;
}
// We're only interested in `__all__` in the global scope
if !checker.semantic().current_scope().kind.is_module() {
return;
}
let (elts, range, kind) = match node {
ast::Expr::List(ast::ExprList { elts, range, .. }) => (elts, *range, SequenceKind::List),
ast::Expr::Tuple(ast::ExprTuple {
elts,
range,
parenthesized,
..
}) => (
elts,
*range,
SequenceKind::Tuple {
parenthesized: *parenthesized,
},
),
_ => return,
};
let elts_analysis = SortClassification::of_elements(elts, SORTING_STYLE);
if elts_analysis.is_not_a_list_of_string_literals() || elts_analysis.is_sorted() {
return;
}
let mut diagnostic = checker.report_diagnostic(UnsortedDunderAll, range);
if let SortClassification::UnsortedAndMaybeFixable { items } = elts_analysis {
if let Some(fix) = create_fix(range, elts, &items, kind, checker) {
diagnostic.set_fix(fix);
}
}
}
/// Attempt to return `Some(fix)`, where `fix` is a `Fix`
/// that can be set on the diagnostic to sort the user's
/// `__all__` definition
///
/// Return `None` if it's a multiline `__all__` definition
/// and the token-based analysis in
/// `MultilineDunderAllValue::from_source_range()` encounters
/// something it doesn't expect, meaning the violation
/// is unfixable in this instance.
fn create_fix(
range: TextRange,
elts: &[ast::Expr],
string_items: &[&str],
kind: SequenceKind,
checker: &Checker,
) -> Option<Fix> {
let locator = checker.locator();
let is_multiline = locator.contains_line_break(range);
// The machinery in the `MultilineDunderAllValue` is actually
// sophisticated enough that it would work just as well for
// single-line `__all__` definitions, and we could reduce
// the number of lines of code in this file by doing that.
// Unfortunately, however, `MultilineDunderAllValue::from_source_range()`
// must process every token in an `__all__` definition as
// part of its analysis, and this is quite slow. For
// single-line `__all__` definitions, it's also unnecessary,
// as it's impossible to have comments in between the
// `__all__` elements if the `__all__` definition is all on
// a single line. Therefore, as an optimisation, we do the
// bare minimum of token-processing for single-line `__all__`
// definitions:
let (sorted_source_code, applicability) = if is_multiline {
let value = MultilineStringSequenceValue::from_source_range(
range,
kind,
locator,
checker.tokens(),
string_items,
)?;
assert_eq!(value.len(), elts.len());
let applicability = if value.comment_complexity().is_complex() {
Applicability::Unsafe
} else {
Applicability::Safe
};
let sorted_source =
value.into_sorted_source_code(SORTING_STYLE, locator, checker.stylist());
(sorted_source, applicability)
} else {
let sorted_source =
sort_single_line_elements_sequence(kind, elts, string_items, locator, SORTING_STYLE);
(sorted_source, Applicability::Safe)
};
let edit = Edit::range_replacement(sorted_source_code, range);
Some(Fix::applicable_edit(edit, applicability))
}
| 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/ruff/rules/falsy_dict_get_fallback.rs | crates/ruff_linter/src/rules/ruff/rules/falsy_dict_get_fallback.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprAttribute, helpers::Truthiness};
use ruff_python_semantic::analyze::typing;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::{Applicability, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `dict.get(key, falsy_value)` calls in boolean test positions.
///
/// ## Why is this bad?
/// The default fallback `None` is already falsy.
///
/// ## Example
///
/// ```python
/// if dict.get(key, False):
/// ...
/// ```
///
/// Use instead:
///
/// ```python
/// if dict.get(key):
/// ...
/// ```
///
/// ## Fix safety
///
/// This rule's fix is marked as safe, unless the `dict.get()` call contains comments between
/// arguments that will be deleted.
///
/// ## Fix availability
///
/// This rule's fix is unavailable in cases where invalid arguments are provided to `dict.get`. As
/// shown in the [documentation], `dict.get` takes two positional-only arguments, so invalid cases
/// are identified by the presence of more than two arguments or any keyword arguments.
///
/// [documentation]: https://docs.python.org/3.13/library/stdtypes.html#dict.get
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.8.5")]
pub(crate) struct FalsyDictGetFallback;
impl Violation for FalsyDictGetFallback {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Avoid providing a falsy fallback to `dict.get()` in boolean test positions. The default fallback `None` is already falsy.".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Remove falsy fallback from `dict.get()`".to_string())
}
}
/// RUF056
pub(crate) fn falsy_dict_get_fallback(checker: &Checker, expr: &Expr) {
let semantic = checker.semantic();
// Check if we are in a boolean test
if !semantic.in_boolean_test() {
return;
}
// Check if the expression is a call
let Expr::Call(call) = expr else {
return;
};
// Check if the function being called is an attribute (e.g. `dict.get`)
let Expr::Attribute(ExprAttribute { value, attr, .. }) = &*call.func else {
return;
};
// Ensure the method called is `get`
if attr != "get" {
return;
}
// Check if the object is a dictionary using the semantic model
if !value
.as_name_expr()
.is_some_and(|name| typing::is_known_to_be_of_type_dict(semantic, name))
{
return;
}
// Get the fallback argument
let Some(fallback_arg) = call.arguments.find_argument("default", 1) else {
return;
};
// Check if the fallback is a falsy value
if Truthiness::from_expr(fallback_arg.value(), |id| semantic.has_builtin_binding(id))
.into_bool()
!= Some(false)
{
return;
}
let mut diagnostic = checker.report_diagnostic(FalsyDictGetFallback, fallback_arg.range());
// All arguments to `dict.get` are positional-only.
if !call.arguments.keywords.is_empty() {
return;
}
// And there are only two of them, at most.
if call.arguments.args.len() > 2 {
return;
}
let comment_ranges = checker.comment_ranges();
// Determine applicability based on the presence of comments
let applicability = if comment_ranges.intersects(call.arguments.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
};
diagnostic.try_set_fix(|| {
remove_argument(
&fallback_arg,
&call.arguments,
Parentheses::Preserve,
checker.locator().contents(),
checker.tokens(),
)
.map(|edit| Fix::applicable_edit(edit, applicability))
});
}
| 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/ruff/rules/used_dummy_variable.rs | crates/ruff_linter/src/rules/ruff/rules/used_dummy_variable.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::is_dunder;
use ruff_python_semantic::{Binding, BindingId, BindingKind, ScopeKind};
use ruff_python_stdlib::identifiers::is_identifier;
use ruff_text_size::Ranged;
use crate::{Fix, FixAvailability, Violation};
use crate::{
checkers::ast::Checker,
renamer::{Renamer, ShadowedKind},
};
/// ## What it does
/// Checks for "dummy variables" (variables that are named as if to indicate they are unused)
/// that are in fact used.
///
/// By default, "dummy variables" are any variables with names that start with leading
/// underscores. However, this is customisable using the [`lint.dummy-variable-rgx`] setting).
///
/// ## Why is this bad?
/// Marking a variable with a leading underscore conveys that it is intentionally unused within the function or method.
/// When these variables are later referenced in the code, it causes confusion and potential misunderstandings about
/// the code's intention. If a variable marked as "unused" is subsequently used, it suggests that either the variable
/// could be given a clearer name, or that the code is accidentally making use of the wrong variable.
///
/// Sometimes leading underscores are used to avoid variables shadowing other variables, Python builtins, or Python
/// keywords. However, [PEP 8] recommends to use trailing underscores for this rather than leading underscores.
///
/// Dunder variables are ignored by this rule, as are variables named `_`.
/// Only local variables in function scopes are flagged by the rule.
///
/// ## Example
/// ```python
/// def function():
/// _variable = 3
/// # important: avoid shadowing the builtin `id()` function!
/// _id = 4
/// return _variable + _id
/// ```
///
/// Use instead:
/// ```python
/// def function():
/// variable = 3
/// # important: avoid shadowing the builtin `id()` function!
/// id_ = 4
/// return variable + id_
/// ```
///
/// ## Fix availability
/// The rule's fix is only available for variables that start with leading underscores.
/// It will also only be available if the "obvious" new name for the variable
/// would not shadow any other known variables already accessible from the scope
/// in which the variable is defined.
///
/// ## Fix safety
/// This rule's fix is marked as unsafe.
///
/// For this rule's fix, Ruff renames the variable and fixes up all known references to
/// it so they point to the renamed variable. However, some renamings also require other
/// changes such as different arguments to constructor calls or alterations to comments.
/// Ruff is aware of some of these cases: `_T = TypeVar("_T")` will be fixed to
/// `T = TypeVar("T")` if the `_T` binding is flagged by this rule. However, in general,
/// cases like these are hard to detect and hard to automatically fix.
///
/// ## Options
/// - [`lint.dummy-variable-rgx`]
///
/// [PEP 8]: https://peps.python.org/pep-0008/
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.8.2")]
pub(crate) struct UsedDummyVariable {
name: String,
shadowed_kind: Option<ShadowedKind>,
}
impl Violation for UsedDummyVariable {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
format!("Local dummy variable `{}` is accessed", self.name)
}
fn fix_title(&self) -> Option<String> {
self.shadowed_kind.map(|kind| match kind {
ShadowedKind::BuiltIn => {
"Prefer using trailing underscores to avoid shadowing a built-in".to_string()
}
ShadowedKind::Keyword => {
"Prefer using trailing underscores to avoid shadowing a keyword".to_string()
}
ShadowedKind::Some => {
"Prefer using trailing underscores to avoid shadowing a variable".to_string()
}
ShadowedKind::None => "Remove leading underscores".to_string(),
})
}
}
/// RUF052
pub(crate) fn used_dummy_variable(checker: &Checker, binding: &Binding, binding_id: BindingId) {
let name = binding.name(checker.source());
// Ignore `_` and dunder variables
if name == "_" || is_dunder(name) {
return;
}
// only used variables
if binding.is_unused() {
return;
}
// We only emit the lint on local variables.
//
// ## Why not also emit the lint on function parameters?
//
// There isn't universal agreement that leading underscores indicate "unused" parameters
// in Python (many people use them for "private" parameters), so this would be a lot more
// controversial than emitting the lint on assignments. Even if it's decided that it's
// desirable to emit a lint on function parameters with "dummy variable" names, it would
// possibly have to be a separate rule or we'd have to put it behind a configuration flag,
// as there's much less community consensus about the issue.
// See <https://github.com/astral-sh/ruff/issues/14796>.
//
// Moreover, autofixing the diagnostic for function parameters is much more troublesome than
// autofixing the diagnostic for assignments. See:
// - <https://github.com/astral-sh/ruff/issues/14790>
// - <https://github.com/astral-sh/ruff/issues/14799>
match binding.kind {
BindingKind::Annotation
| BindingKind::Argument
| BindingKind::NamedExprAssignment
| BindingKind::Assignment
| BindingKind::LoopVar
| BindingKind::WithItemVar
| BindingKind::BoundException
| BindingKind::UnboundException(_) => {}
BindingKind::TypeParam
| BindingKind::Global(_)
| BindingKind::Nonlocal(_, _)
| BindingKind::Builtin
| BindingKind::ClassDefinition(_)
| BindingKind::FunctionDefinition(_)
| BindingKind::Export(_)
| BindingKind::FutureImport
| BindingKind::Import(_)
| BindingKind::FromImport(_)
| BindingKind::SubmoduleImport(_)
| BindingKind::Deletion
| BindingKind::ConditionalDeletion(_)
| BindingKind::DunderClassCell => return,
}
// This excludes `global` and `nonlocal` variables.
if binding.is_global() || binding.is_nonlocal() {
return;
}
let semantic = checker.semantic();
// Only variables defined in function and generator scopes
let scope = &semantic.scopes[binding.scope];
if !matches!(
scope.kind,
ScopeKind::Function(_) | ScopeKind::Generator { .. }
) {
return;
}
// Recall from above that we do not wish to flag "private"
// function parameters. The previous early exit ensured
// that the binding in hand was not a function parameter.
// We now check that, in the body of our function, we are
// not looking at a shadowing of a private parameter.
//
// (Technically this also covers the case in the previous early exit,
// but it is more expensive so we keep both.)
if scope
.shadowed_bindings(binding_id)
.any(|shadow_id| semantic.binding(shadow_id).kind.is_argument())
{
return;
}
if !checker.settings().dummy_variable_rgx.is_match(name) {
return;
}
// If the name doesn't start with an underscore, we don't consider it for a fix
if !name.starts_with('_') {
checker.report_diagnostic(
UsedDummyVariable {
name: name.to_string(),
shadowed_kind: None,
},
binding.range(),
);
return;
}
// Trim the leading underscores for further checks
let trimmed_name = name.trim_start_matches('_');
let shadowed_kind = ShadowedKind::new(binding, trimmed_name, checker);
let mut diagnostic = checker.report_diagnostic(
UsedDummyVariable {
name: name.to_string(),
shadowed_kind: Some(shadowed_kind),
},
binding.range(),
);
// Get the possible fix based on the scope
if let Some(new_name) = get_possible_new_name(binding, trimmed_name, shadowed_kind, checker) {
diagnostic.try_set_fix(|| {
Renamer::rename(name, &new_name, scope, semantic, checker.stylist())
.map(|(edit, rest)| Fix::unsafe_edits(edit, rest))
});
}
}
/// Suggests a potential alternative name to resolve a shadowing conflict.
fn get_possible_new_name(
binding: &Binding,
trimmed_name: &str,
kind: ShadowedKind,
checker: &Checker,
) -> Option<String> {
// Construct the potential fix name based on ShadowedKind
let fix_name = match kind {
ShadowedKind::Some | ShadowedKind::BuiltIn | ShadowedKind::Keyword => {
format!("{trimmed_name}_") // Append an underscore
}
ShadowedKind::None => trimmed_name.to_string(),
};
// Check if the fix name is again dummy identifier
if checker.settings().dummy_variable_rgx.is_match(&fix_name) {
return None;
}
// Ensure the fix name is not already taken in the scope or enclosing scopes
if ShadowedKind::new(binding, &fix_name, checker).shadows_any() {
return None;
}
// Check if the fix name is a valid identifier
is_identifier(&fix_name).then_some(fix_name)
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/ruff/rules/ambiguous_unicode_character.rs | crates/ruff_linter/src/rules/ruff/rules/ambiguous_unicode_character.rs | use std::fmt;
use bitflags::bitflags;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, FString, StringLike, TString};
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use crate::Locator;
use crate::Violation;
use crate::checkers::ast::{Checker, LintContext};
use crate::preview::is_unicode_to_unicode_confusables_enabled;
use crate::rules::ruff::rules::Context;
use crate::rules::ruff::rules::confusables::confusable;
/// ## What it does
/// Checks for ambiguous Unicode characters in strings.
///
/// ## Why is this bad?
/// Some Unicode characters are visually similar to ASCII characters, but have
/// different code points. For example, `GREEK CAPITAL LETTER ALPHA` (`U+0391`)
/// is visually similar, but not identical, to the ASCII character `A`.
///
/// The use of ambiguous Unicode characters can confuse readers, cause subtle
/// bugs, and even make malicious code look harmless.
///
/// In [preview], this rule will also flag Unicode characters that are
/// confusable with other, non-preferred Unicode characters. For example, the
/// spec recommends `GREEK CAPITAL LETTER OMEGA` over `OHM SIGN`.
///
/// You can omit characters from being flagged as ambiguous via the
/// [`lint.allowed-confusables`] setting.
///
/// ## Example
/// ```python
/// print("Ηello, world!") # "Η" is the Greek eta (`U+0397`).
/// ```
///
/// Use instead:
/// ```python
/// print("Hello, world!") # "H" is the Latin capital H (`U+0048`).
/// ```
///
/// ## Options
/// - `lint.allowed-confusables`
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.102")]
pub(crate) struct AmbiguousUnicodeCharacterString {
confusable: char,
representant: char,
}
impl Violation for AmbiguousUnicodeCharacterString {
#[derive_message_formats]
fn message(&self) -> String {
let AmbiguousUnicodeCharacterString {
confusable,
representant,
} = self;
format!(
"String contains ambiguous {}. Did you mean {}?",
NamedUnicode(*confusable),
NamedUnicode(*representant)
)
}
}
/// ## What it does
/// Checks for ambiguous Unicode characters in docstrings.
///
/// ## Why is this bad?
/// Some Unicode characters are visually similar to ASCII characters, but have
/// different code points. For example, `GREEK CAPITAL LETTER ALPHA` (`U+0391`)
/// is visually similar, but not identical, to the ASCII character `A`.
///
/// The use of ambiguous Unicode characters can confuse readers, cause subtle
/// bugs, and even make malicious code look harmless.
///
/// In [preview], this rule will also flag Unicode characters that are
/// confusable with other, non-preferred Unicode characters. For example, the
/// spec recommends `GREEK CAPITAL LETTER OMEGA` over `OHM SIGN`.
///
/// You can omit characters from being flagged as ambiguous via the
/// [`lint.allowed-confusables`] setting.
///
/// ## Example
/// ```python
/// """A lovely docstring (with a `U+FF09` parenthesis)."""
/// ```
///
/// Use instead:
/// ```python
/// """A lovely docstring (with no strange parentheses)."""
/// ```
///
/// ## Options
/// - `lint.allowed-confusables`
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.102")]
pub(crate) struct AmbiguousUnicodeCharacterDocstring {
confusable: char,
representant: char,
}
impl Violation for AmbiguousUnicodeCharacterDocstring {
#[derive_message_formats]
fn message(&self) -> String {
let AmbiguousUnicodeCharacterDocstring {
confusable,
representant,
} = self;
format!(
"Docstring contains ambiguous {}. Did you mean {}?",
NamedUnicode(*confusable),
NamedUnicode(*representant)
)
}
}
/// ## What it does
/// Checks for ambiguous Unicode characters in comments.
///
/// ## Why is this bad?
/// Some Unicode characters are visually similar to ASCII characters, but have
/// different code points. For example, `GREEK CAPITAL LETTER ALPHA` (`U+0391`)
/// is visually similar, but not identical, to the ASCII character `A`.
///
/// The use of ambiguous Unicode characters can confuse readers, cause subtle
/// bugs, and even make malicious code look harmless.
///
/// In [preview], this rule will also flag Unicode characters that are
/// confusable with other, non-preferred Unicode characters. For example, the
/// spec recommends `GREEK CAPITAL LETTER OMEGA` over `OHM SIGN`.
///
/// You can omit characters from being flagged as ambiguous via the
/// [`lint.allowed-confusables`] setting.
///
/// ## Example
/// ```python
/// foo() # nоqa # "о" is Cyrillic (`U+043E`)
/// ```
///
/// Use instead:
/// ```python
/// foo() # noqa # "o" is Latin (`U+006F`)
/// ```
///
/// ## Options
/// - `lint.allowed-confusables`
///
/// [preview]: https://docs.astral.sh/ruff/preview/
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.108")]
pub(crate) struct AmbiguousUnicodeCharacterComment {
confusable: char,
representant: char,
}
impl Violation for AmbiguousUnicodeCharacterComment {
#[derive_message_formats]
fn message(&self) -> String {
let AmbiguousUnicodeCharacterComment {
confusable,
representant,
} = self;
format!(
"Comment contains ambiguous {}. Did you mean {}?",
NamedUnicode(*confusable),
NamedUnicode(*representant)
)
}
}
/// RUF003
pub(crate) fn ambiguous_unicode_character_comment(
context: &LintContext,
locator: &Locator,
range: TextRange,
) {
let text = locator.slice(range);
ambiguous_unicode_character(text, range, Context::Comment, context);
}
/// RUF001, RUF002
pub(crate) fn ambiguous_unicode_character_string(checker: &Checker, string_like: StringLike) {
let semantic = checker.semantic();
if semantic.in_string_type_definition() {
return;
}
let context = if semantic.in_pep_257_docstring() {
Context::Docstring
} else {
Context::String
};
for part in string_like.parts() {
match part {
ast::StringLikePart::String(string_literal) => {
let text = checker.locator().slice(string_literal);
ambiguous_unicode_character(
text,
string_literal.range(),
context,
checker.context(),
);
}
ast::StringLikePart::Bytes(_) => {}
ast::StringLikePart::FString(FString { elements, .. })
| ast::StringLikePart::TString(TString { elements, .. }) => {
for literal in elements.literals() {
let text = checker.locator().slice(literal);
ambiguous_unicode_character(text, literal.range(), context, checker.context());
}
}
}
}
}
fn ambiguous_unicode_character(
text: &str,
range: TextRange,
context: Context,
lint_context: &LintContext,
) {
// Most of the time, we don't need to check for ambiguous unicode characters at all.
if text.is_ascii() {
return;
}
// Iterate over the "words" in the text.
let mut word_flags = WordFlags::empty();
let mut word_candidates: Vec<Candidate> = vec![];
for (relative_offset, current_char) in text.char_indices() {
// Word boundary.
if !current_char.is_alphanumeric() {
if !word_candidates.is_empty() {
if word_flags.is_candidate_word() {
for candidate in word_candidates.drain(..) {
candidate.into_diagnostic(context, lint_context);
}
}
word_candidates.clear();
}
word_flags = WordFlags::empty();
// Check if the boundary character is itself an ambiguous unicode character, in which
// case, it's always included as a diagnostic.
if !current_char.is_ascii() {
if let Some(representant) = confusable(current_char as u32).filter(|representant| {
is_unicode_to_unicode_confusables_enabled(lint_context.settings())
|| representant.is_ascii()
}) {
let candidate = Candidate::new(
TextSize::try_from(relative_offset).unwrap() + range.start(),
current_char,
representant,
);
candidate.into_diagnostic(context, lint_context);
}
}
} else if current_char.is_ascii() {
// The current word contains at least one ASCII character.
word_flags |= WordFlags::ASCII;
} else if let Some(representant) = confusable(current_char as u32).filter(|representant| {
is_unicode_to_unicode_confusables_enabled(lint_context.settings())
|| representant.is_ascii()
}) {
// The current word contains an ambiguous unicode character.
word_candidates.push(Candidate::new(
TextSize::try_from(relative_offset).unwrap() + range.start(),
current_char,
representant,
));
} else {
// The current word contains at least one unambiguous unicode character.
word_flags |= WordFlags::UNAMBIGUOUS_UNICODE;
}
}
// End of the text.
if !word_candidates.is_empty() {
if word_flags.is_candidate_word() {
for candidate in word_candidates.drain(..) {
candidate.into_diagnostic(context, lint_context);
}
}
word_candidates.clear();
}
}
bitflags! {
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
pub struct WordFlags: u8 {
/// The word contains at least one ASCII character (like `B`).
const ASCII = 1 << 0;
/// The word contains at least one unambiguous unicode character (like `β`).
const UNAMBIGUOUS_UNICODE = 1 << 1;
}
}
impl WordFlags {
/// Return `true` if the flags indicate that the word is a candidate for flagging
/// ambiguous unicode characters.
///
/// We follow VS Code's logic for determining whether ambiguous unicode characters within a
/// given word should be flagged, i.e., we flag a word if it contains at least one ASCII
/// character, or is purely unicode but _only_ consists of ambiguous characters.
///
/// See: [VS Code](https://github.com/microsoft/vscode/issues/143720#issuecomment-1048757234)
const fn is_candidate_word(self) -> bool {
self.contains(WordFlags::ASCII) || !self.contains(WordFlags::UNAMBIGUOUS_UNICODE)
}
}
/// An ambiguous unicode character in the text.
struct Candidate {
/// The offset of the candidate in the text.
offset: TextSize,
/// The ambiguous unicode character.
confusable: char,
/// The character with which the ambiguous unicode character is confusable.
representant: char,
}
impl Candidate {
fn new(offset: TextSize, confusable: char, representant: char) -> Self {
Self {
offset,
confusable,
representant,
}
}
fn into_diagnostic(self, context: Context, lint_context: &LintContext) {
if !lint_context
.settings()
.allowed_confusables
.contains(&self.confusable)
{
let char_range = TextRange::at(self.offset, self.confusable.text_len());
match context {
Context::String => lint_context.report_diagnostic_if_enabled(
AmbiguousUnicodeCharacterString {
confusable: self.confusable,
representant: self.representant,
},
char_range,
),
Context::Docstring => lint_context.report_diagnostic_if_enabled(
AmbiguousUnicodeCharacterDocstring {
confusable: self.confusable,
representant: self.representant,
},
char_range,
),
Context::Comment => lint_context.report_diagnostic_if_enabled(
AmbiguousUnicodeCharacterComment {
confusable: self.confusable,
representant: self.representant,
},
char_range,
),
};
}
}
}
struct NamedUnicode(char);
impl fmt::Display for NamedUnicode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let NamedUnicode(c) = self;
if let Some(name) = unicode_names2::name(*c) {
write!(f, "`{c}` ({name})")
} else {
write!(f, "`{c}`")
}
}
}
| 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/ruff/rules/function_call_in_dataclass_default.rs | crates/ruff_linter/src/rules/ruff/rules/function_call_in_dataclass_default.rs | use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::{QualifiedName, UnqualifiedName};
use ruff_python_semantic::analyze::typing::{
is_immutable_annotation, is_immutable_func, is_immutable_newtype_call,
};
use ruff_python_semantic::{ScopeId, SemanticModel};
use ruff_text_size::Ranged;
use crate::Violation;
use crate::checkers::ast::Checker;
use crate::rules::ruff::helpers::{
AttrsAutoAttribs, DataclassKind, dataclass_kind, is_class_var_annotation, is_dataclass_field,
is_descriptor_class, is_frozen_dataclass,
};
/// ## What it does
/// Checks for function calls in dataclass attribute defaults.
///
/// ## Why is this bad?
/// Function calls are only performed once, at definition time. The returned
/// value is then reused by all instances of the dataclass. This can lead to
/// unexpected behavior when the function call returns a mutable object, as
/// changes to the object will be shared across all instances.
///
/// If a field needs to be initialized with a mutable object, use the
/// `field(default_factory=...)` pattern.
///
/// Attributes whose default arguments are `NewType` calls
/// where the original type is immutable are ignored.
///
/// ## Example
/// ```python
/// from dataclasses import dataclass
///
///
/// def simple_list() -> list[int]:
/// return [1, 2, 3, 4]
///
///
/// @dataclass
/// class A:
/// mutable_default: list[int] = simple_list()
/// ```
///
/// Use instead:
/// ```python
/// from dataclasses import dataclass, field
///
///
/// def creating_list() -> list[int]:
/// return [1, 2, 3, 4]
///
///
/// @dataclass
/// class A:
/// mutable_default: list[int] = field(default_factory=creating_list)
/// ```
///
/// ## Options
/// - `lint.flake8-bugbear.extend-immutable-calls`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.262")]
pub(crate) struct FunctionCallInDataclassDefaultArgument {
name: Option<String>,
}
impl Violation for FunctionCallInDataclassDefaultArgument {
#[derive_message_formats]
fn message(&self) -> String {
if let Some(name) = &self.name {
format!("Do not perform function call `{name}` in dataclass defaults")
} else {
"Do not perform function call in dataclass defaults".to_string()
}
}
}
/// RUF009
pub(crate) fn function_call_in_dataclass_default(
checker: &Checker,
class_def: &ast::StmtClassDef,
scope_id: ScopeId,
) {
let semantic = checker.semantic();
let Some((dataclass_kind, _)) = dataclass_kind(class_def, semantic) else {
return;
};
let attrs_auto_attribs = match dataclass_kind {
DataclassKind::Stdlib => None,
DataclassKind::Attrs(auto_attribs) => match auto_attribs {
AttrsAutoAttribs::Unknown => return,
AttrsAutoAttribs::None => {
if any_annotated(&class_def.body) {
Some(AttrsAutoAttribs::True)
} else {
Some(AttrsAutoAttribs::False)
}
}
_ => Some(auto_attribs),
},
};
let dataclass_kind = match attrs_auto_attribs {
None => DataclassKind::Stdlib,
Some(auto_attribs) => DataclassKind::Attrs(auto_attribs),
};
let extend_immutable_calls: Vec<QualifiedName> = checker
.settings()
.flake8_bugbear
.extend_immutable_calls
.iter()
.map(|target| QualifiedName::from_dotted_name(target))
.collect();
for statement in &class_def.body {
let Stmt::AnnAssign(ast::StmtAnnAssign {
annotation,
value: Some(expr),
..
}) = statement
else {
continue;
};
let Expr::Call(ast::ExprCall { func, .. }) = expr.as_ref() else {
continue;
};
let is_field = is_dataclass_field(func, checker.semantic(), dataclass_kind);
// Non-explicit fields in an `attrs` dataclass
// with `auto_attribs=False` are class variables.
if matches!(attrs_auto_attribs, Some(AttrsAutoAttribs::False)) && !is_field {
continue;
}
if is_field
|| is_immutable_annotation(annotation, checker.semantic(), &extend_immutable_calls)
|| is_class_var_annotation(annotation, checker.semantic())
|| is_immutable_func(func, checker.semantic(), &extend_immutable_calls)
|| is_descriptor_class(func, checker.semantic())
|| func.as_name_expr().is_some_and(|name| {
is_immutable_newtype_call(name, checker.semantic(), &extend_immutable_calls)
})
|| is_frozen_dataclass_instantiation(func, semantic, scope_id)
{
continue;
}
let kind = FunctionCallInDataclassDefaultArgument {
name: UnqualifiedName::from_expr(func).map(|name| name.to_string()),
};
checker.report_diagnostic(kind, expr.range());
}
}
#[inline]
fn any_annotated(class_body: &[Stmt]) -> bool {
class_body
.iter()
.any(|stmt| matches!(stmt, Stmt::AnnAssign(..)))
}
/// Checks that the passed function is an instantiation of the class,
/// retrieves the ``StmtClassDef`` and verifies that it is a frozen dataclass
fn is_frozen_dataclass_instantiation(
func: &Expr,
semantic: &SemanticModel,
scope_id: ScopeId,
) -> bool {
semantic
.lookup_attribute_in_scope(func, scope_id)
.is_some_and(|id| {
let binding = &semantic.binding(id);
let Some(Stmt::ClassDef(class_def)) = binding.statement(semantic) else {
return false;
};
let Some((_, dataclass_decorator)) = dataclass_kind(class_def, semantic) else {
return false;
};
is_frozen_dataclass(dataclass_decorator, semantic)
})
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.