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/docstrings/styles.rs | crates/ruff_linter/src/docstrings/styles.rs | use crate::docstrings::google::GOOGLE_SECTIONS;
use crate::docstrings::numpy::NUMPY_SECTIONS;
use crate::docstrings::sections::SectionKind;
#[derive(Copy, Clone, Debug, is_macro::Is)]
pub(crate) enum SectionStyle {
Numpy,
Google,
}
impl SectionStyle {
pub(crate) fn sections(&self) -> &[SectionKind] {
match self {
SectionStyle::Numpy => NUMPY_SECTIONS,
SectionStyle::Google => GOOGLE_SECTIONS,
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/docstrings/extraction.rs | crates/ruff_linter/src/docstrings/extraction.rs | //! Extract docstrings from an AST.
use ruff_python_ast::{self as ast, Stmt};
use ruff_python_semantic::{Definition, DefinitionId, Definitions, Member, MemberKind};
/// Extract a docstring from a function or class body.
pub(crate) fn docstring_from(suite: &[Stmt]) -> Option<&ast::ExprStringLiteral> {
let stmt = suite.first()?;
// Require the docstring to be a standalone expression.
let Stmt::Expr(ast::StmtExpr {
value,
range: _,
node_index: _,
}) = stmt
else {
return None;
};
// Only match strings.
value.as_string_literal_expr()
}
/// Extract a docstring from a `Definition`.
pub(crate) fn extract_docstring<'a>(
definition: &'a Definition<'a>,
) -> Option<&'a ast::ExprStringLiteral> {
match definition {
Definition::Module(module) => docstring_from(module.python_ast),
Definition::Member(member) => docstring_from(member.body()),
}
}
#[derive(Copy, Clone)]
pub(crate) enum ExtractionTarget<'a> {
Class(&'a ast::StmtClassDef),
Function(&'a ast::StmtFunctionDef),
}
/// Extract a `Definition` from the AST node defined by a `Stmt`.
pub(crate) fn extract_definition<'a>(
target: ExtractionTarget<'a>,
parent: DefinitionId,
definitions: &Definitions<'a>,
) -> Member<'a> {
match target {
ExtractionTarget::Function(function) => match &definitions[parent] {
Definition::Module(..) => Member {
parent,
kind: MemberKind::Function(function),
},
Definition::Member(Member {
kind: MemberKind::Class(_) | MemberKind::NestedClass(_),
..
}) => Member {
parent,
kind: MemberKind::Method(function),
},
Definition::Member(_) => Member {
parent,
kind: MemberKind::NestedFunction(function),
},
},
ExtractionTarget::Class(class) => match &definitions[parent] {
Definition::Module(_) => Member {
parent,
kind: MemberKind::Class(class),
},
Definition::Member(_) => Member {
parent,
kind: MemberKind::NestedClass(class),
},
},
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/docstrings/mod.rs | crates/ruff_linter/src/docstrings/mod.rs | use std::fmt::{Debug, Formatter};
use std::ops::Deref;
use ruff_python_ast::{self as ast, StringFlags};
use ruff_python_semantic::Definition;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange, TextSize};
pub(crate) mod extraction;
pub(crate) mod google;
pub(crate) mod numpy;
pub(crate) mod sections;
pub(crate) mod styles;
#[derive(Debug)]
pub(crate) struct Docstring<'a> {
pub(crate) definition: &'a Definition<'a>,
/// The literal AST node representing the docstring.
pub(crate) expr: &'a ast::StringLiteral,
/// The source file the docstring was defined in.
pub(crate) source: &'a str,
}
impl<'a> Docstring<'a> {
fn flags(&self) -> ast::StringLiteralFlags {
self.expr.flags
}
/// The contents of the docstring, including the opening and closing quotes.
pub(crate) fn contents(&self) -> &'a str {
&self.source[self.range()]
}
/// The contents of the docstring, excluding the opening and closing quotes.
pub(crate) fn body(&self) -> DocstringBody<'_> {
DocstringBody { docstring: self }
}
/// Compute the start position of the docstring's opening line
pub(crate) fn line_start(&self) -> TextSize {
self.source.line_start(self.start())
}
/// Return the slice of source code that represents the indentation of the docstring's opening quotes.
pub(crate) fn compute_indentation(&self) -> &'a str {
&self.source[TextRange::new(self.line_start(), self.start())]
}
pub(crate) fn quote_style(&self) -> ast::str::Quote {
self.flags().quote_style()
}
pub(crate) fn is_raw_string(&self) -> bool {
self.flags().prefix().is_raw()
}
pub(crate) fn is_u_string(&self) -> bool {
self.flags().prefix().is_unicode()
}
pub(crate) fn is_triple_quoted(&self) -> bool {
self.flags().is_triple_quoted()
}
/// The docstring's prefixes as they exist in the original source code.
pub(crate) fn prefix_str(&self) -> &'a str {
// N.B. This will normally be exactly the same as what you might get from
// `self.flags().prefix().as_str()`, but doing it this way has a few small advantages.
// For example, the casing of the `u` prefix will be preserved if it's a u-string.
&self.source[TextRange::new(
self.start(),
self.start() + self.flags().prefix().text_len(),
)]
}
/// The docstring's "opener" (the string's prefix, if any, and its opening quotes).
pub(crate) fn opener(&self) -> &'a str {
&self.source[TextRange::new(self.start(), self.start() + self.flags().opener_len())]
}
/// The docstring's closing quotes.
pub(crate) fn closer(&self) -> &'a str {
&self.source[TextRange::new(self.end() - self.flags().closer_len(), self.end())]
}
}
impl Ranged for Docstring<'_> {
fn range(&self) -> TextRange {
self.expr.range()
}
}
#[derive(Copy, Clone)]
pub(crate) struct DocstringBody<'a> {
docstring: &'a Docstring<'a>,
}
impl<'a> DocstringBody<'a> {
pub(crate) fn as_str(self) -> &'a str {
&self.docstring.source[self.range()]
}
}
impl Ranged for DocstringBody<'_> {
fn range(&self) -> TextRange {
self.docstring.expr.content_range()
}
}
impl Deref for DocstringBody<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl Debug for DocstringBody<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DocstringBody")
.field("text", &self.as_str())
.field("range", &self.range())
.finish()
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/docstrings/google.rs | crates/ruff_linter/src/docstrings/google.rs | //! Abstractions for Google-style docstrings.
use crate::docstrings::sections::SectionKind;
pub(crate) static GOOGLE_SECTIONS: &[SectionKind] = &[
SectionKind::Attributes,
SectionKind::Examples,
SectionKind::Methods,
SectionKind::Notes,
SectionKind::Raises,
SectionKind::References,
SectionKind::Returns,
SectionKind::SeeAlso,
SectionKind::Warnings,
SectionKind::Warns,
SectionKind::Yields,
// Google-only
SectionKind::Args,
SectionKind::Arguments,
SectionKind::Attention,
SectionKind::Caution,
SectionKind::Danger,
SectionKind::Error,
SectionKind::Example,
SectionKind::Hint,
SectionKind::Important,
SectionKind::KeywordArgs,
SectionKind::KeywordArguments,
SectionKind::Note,
SectionKind::Notes,
SectionKind::OtherArgs,
SectionKind::OtherArguments,
SectionKind::Return,
SectionKind::Tip,
SectionKind::Todo,
SectionKind::Warning,
SectionKind::Yield,
];
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/docstrings/sections.rs | crates/ruff_linter/src/docstrings/sections.rs | use std::fmt::{Debug, Formatter};
use std::iter::FusedIterator;
use ruff_python_ast::docstrings::{leading_space, leading_words};
use ruff_python_semantic::Definition;
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use strum_macros::EnumIter;
use ruff_source_file::{Line, NewlineWithTrailingNewline, UniversalNewlines};
use crate::docstrings::styles::SectionStyle;
use crate::docstrings::{Docstring, DocstringBody};
#[derive(EnumIter, PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum SectionKind {
Args,
Arguments,
Attention,
Attributes,
Caution,
Danger,
Error,
Example,
Examples,
ExtendedSummary,
Hint,
Important,
KeywordArgs,
KeywordArguments,
Methods,
Note,
Notes,
OtherArgs,
OtherArguments,
OtherParams,
OtherParameters,
Parameters,
Raises,
Receives,
References,
Return,
Returns,
SeeAlso,
ShortSummary,
Tip,
Todo,
Warning,
Warnings,
Warns,
Yield,
Yields,
}
impl SectionKind {
pub(crate) fn from_str(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"args" => Some(Self::Args),
"arguments" => Some(Self::Arguments),
"attention" => Some(Self::Attention),
"attributes" => Some(Self::Attributes),
"caution" => Some(Self::Caution),
"danger" => Some(Self::Danger),
"error" => Some(Self::Error),
"example" => Some(Self::Example),
"examples" => Some(Self::Examples),
"extended summary" => Some(Self::ExtendedSummary),
"hint" => Some(Self::Hint),
"important" => Some(Self::Important),
"keyword args" => Some(Self::KeywordArgs),
"keyword arguments" => Some(Self::KeywordArguments),
"methods" => Some(Self::Methods),
"note" => Some(Self::Note),
"notes" => Some(Self::Notes),
"other args" => Some(Self::OtherArgs),
"other arguments" => Some(Self::OtherArguments),
"other params" => Some(Self::OtherParams),
"other parameters" => Some(Self::OtherParameters),
"parameters" => Some(Self::Parameters),
"raises" => Some(Self::Raises),
"receives" => Some(Self::Receives),
"references" => Some(Self::References),
"return" => Some(Self::Return),
"returns" => Some(Self::Returns),
"see also" => Some(Self::SeeAlso),
"short summary" => Some(Self::ShortSummary),
"tip" => Some(Self::Tip),
"todo" => Some(Self::Todo),
"warning" => Some(Self::Warning),
"warnings" => Some(Self::Warnings),
"warns" => Some(Self::Warns),
"yield" => Some(Self::Yield),
"yields" => Some(Self::Yields),
_ => None,
}
}
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Args => "Args",
Self::Arguments => "Arguments",
Self::Attention => "Attention",
Self::Attributes => "Attributes",
Self::Caution => "Caution",
Self::Danger => "Danger",
Self::Error => "Error",
Self::Example => "Example",
Self::Examples => "Examples",
Self::ExtendedSummary => "Extended Summary",
Self::Hint => "Hint",
Self::Important => "Important",
Self::KeywordArgs => "Keyword Args",
Self::KeywordArguments => "Keyword Arguments",
Self::Methods => "Methods",
Self::Note => "Note",
Self::Notes => "Notes",
Self::OtherArgs => "Other Args",
Self::OtherArguments => "Other Arguments",
Self::OtherParams => "Other Params",
Self::OtherParameters => "Other Parameters",
Self::Parameters => "Parameters",
Self::Raises => "Raises",
Self::Receives => "Receives",
Self::References => "References",
Self::Return => "Return",
Self::Returns => "Returns",
Self::SeeAlso => "See Also",
Self::ShortSummary => "Short Summary",
Self::Tip => "Tip",
Self::Todo => "Todo",
Self::Warning => "Warning",
Self::Warnings => "Warnings",
Self::Warns => "Warns",
Self::Yield => "Yield",
Self::Yields => "Yields",
}
}
}
pub(crate) struct SectionContexts<'a> {
contexts: Vec<SectionContextData>,
docstring: &'a Docstring<'a>,
style: SectionStyle,
}
impl<'a> SectionContexts<'a> {
/// Extract all `SectionContext` values from a docstring.
pub(crate) fn from_docstring(docstring: &'a Docstring<'a>, style: SectionStyle) -> Self {
let contents = docstring.body();
let mut contexts = Vec::new();
let mut last: Option<SectionContextData> = None;
let mut lines = contents.universal_newlines().peekable();
// Skip the first line, which is the summary.
let mut previous_line = lines.next();
while let Some(line) = lines.next() {
if let Some(section_kind) = suspected_as_section(&line, style) {
let indent = leading_space(&line);
let indent_size = indent.text_len();
let section_name = leading_words(&line);
let section_name_size = section_name.text_len();
if is_docstring_section(
&line,
indent_size,
section_name_size,
section_kind,
last.as_ref(),
previous_line.as_ref(),
lines.peek(),
docstring.definition,
) {
if let Some(mut last) = last.take() {
last.range = TextRange::new(last.start(), line.start());
contexts.push(last);
}
last = Some(SectionContextData {
kind: section_kind,
indent_size: indent.text_len(),
name_range: TextRange::at(line.start() + indent_size, section_name_size),
range: TextRange::empty(line.start()),
summary_full_end: line.full_end(),
});
}
}
previous_line = Some(line);
}
if let Some(mut last) = last.take() {
last.range = TextRange::new(last.start(), contents.text_len());
contexts.push(last);
}
Self {
contexts,
docstring,
style,
}
}
pub(crate) fn style(&self) -> SectionStyle {
self.style
}
pub(crate) fn len(&self) -> usize {
self.contexts.len()
}
pub(crate) fn iter(&self) -> SectionContextsIter<'_> {
SectionContextsIter {
docstring_body: self.docstring.body(),
inner: self.contexts.iter(),
}
}
}
impl<'a> IntoIterator for &'a SectionContexts<'a> {
type Item = SectionContext<'a>;
type IntoIter = SectionContextsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Debug for SectionContexts<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
pub(crate) struct SectionContextsIter<'a> {
docstring_body: DocstringBody<'a>,
inner: std::slice::Iter<'a, SectionContextData>,
}
impl<'a> Iterator for SectionContextsIter<'a> {
type Item = SectionContext<'a>;
fn next(&mut self) -> Option<Self::Item> {
let next = self.inner.next()?;
Some(SectionContext {
data: next,
docstring_body: self.docstring_body,
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl DoubleEndedIterator for SectionContextsIter<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
let back = self.inner.next_back()?;
Some(SectionContext {
data: back,
docstring_body: self.docstring_body,
})
}
}
impl FusedIterator for SectionContextsIter<'_> {}
impl ExactSizeIterator for SectionContextsIter<'_> {}
#[derive(Debug)]
struct SectionContextData {
kind: SectionKind,
/// The size of the indentation of the section name.
indent_size: TextSize,
/// Range of the section name, relative to the [`Docstring::body`]
name_range: TextRange,
/// Range from the start to the end of the section, relative to the [`Docstring::body`]
range: TextRange,
/// End of the summary, relative to the [`Docstring::body`]
summary_full_end: TextSize,
}
impl Ranged for SectionContextData {
fn range(&self) -> TextRange {
self.range
}
}
pub(crate) struct SectionContext<'a> {
data: &'a SectionContextData,
docstring_body: DocstringBody<'a>,
}
impl<'a> SectionContext<'a> {
/// The `kind` of the section, e.g. [`SectionKind::Args`] or [`SectionKind::Returns`].
pub(crate) const fn kind(&self) -> SectionKind {
self.data.kind
}
/// The name of the section as it appears in the docstring, e.g. "Args" or "Returns".
pub(crate) fn section_name(&self) -> &'a str {
&self.docstring_body.as_str()[self.data.name_range]
}
/// Returns the rest of the summary line after the section name.
pub(crate) fn summary_after_section_name(&self) -> &'a str {
&self.summary_line()[usize::from(self.data.name_range.end() - self.data.range.start())..]
}
fn offset(&self) -> TextSize {
self.docstring_body.start()
}
/// The absolute range of the section name
pub(crate) fn section_name_range(&self) -> TextRange {
self.data.name_range + self.offset()
}
/// The absolute range of the summary line, excluding any trailing newline character.
pub(crate) fn summary_range(&self) -> TextRange {
TextRange::at(self.range().start(), self.summary_line().text_len())
}
/// Range of the summary line relative to [`Docstring::body`], including the trailing newline character.
fn summary_full_range_relative(&self) -> TextRange {
TextRange::new(self.range_relative().start(), self.data.summary_full_end)
}
/// Returns the range of this section relative to [`Docstring::body`]
const fn range_relative(&self) -> TextRange {
self.data.range
}
/// The absolute range of the full-section.
pub(crate) fn range(&self) -> TextRange {
self.range_relative() + self.offset()
}
/// Summary line without the trailing newline characters
pub(crate) fn summary_line(&self) -> &'a str {
let full_summary = &self.docstring_body.as_str()[self.summary_full_range_relative()];
let mut bytes = full_summary.bytes().rev();
let newline_width = match bytes.next() {
Some(b'\n') => {
if bytes.next() == Some(b'\r') {
2
} else {
1
}
}
Some(b'\r') => 1,
_ => 0,
};
&full_summary[..full_summary.len() - newline_width]
}
/// Returns the text of the last line of the previous section or an empty string if it is the first section.
pub(crate) fn previous_line(&self) -> Option<&'a str> {
let previous =
&self.docstring_body.as_str()[TextRange::up_to(self.range_relative().start())];
previous
.universal_newlines()
.last()
.map(|line| line.as_str())
}
/// Returns the lines belonging to this section after the summary line.
pub(crate) fn following_lines(&self) -> NewlineWithTrailingNewline<'a> {
let lines = self.following_lines_str();
NewlineWithTrailingNewline::with_offset(lines, self.offset() + self.data.summary_full_end)
}
pub(crate) fn following_lines_str(&self) -> &'a str {
&self.docstring_body.as_str()[self.following_range_relative()]
}
/// Returns the range to the following lines relative to [`Docstring::body`].
const fn following_range_relative(&self) -> TextRange {
TextRange::new(self.data.summary_full_end, self.range_relative().end())
}
/// Returns the absolute range of the following lines.
pub(crate) fn following_range(&self) -> TextRange {
self.following_range_relative() + self.offset()
}
}
impl Ranged for SectionContext<'_> {
fn range(&self) -> TextRange {
self.range()
}
}
impl Debug for SectionContext<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SectionContext")
.field("kind", &self.kind())
.field("section_name", &self.section_name())
.field("summary_line", &self.summary_line())
.field("following_lines", &&self.following_lines_str())
.finish()
}
}
fn suspected_as_section(line: &str, style: SectionStyle) -> Option<SectionKind> {
if let Some(kind) = SectionKind::from_str(leading_words(line)) {
if style.sections().contains(&kind) {
return Some(kind);
}
}
None
}
/// Check if the suspected context is really a section header.
#[expect(clippy::too_many_arguments)]
fn is_docstring_section(
line: &Line,
indent_size: TextSize,
section_name_size: TextSize,
section_kind: SectionKind,
previous_section: Option<&SectionContextData>,
previous_line: Option<&Line>,
next_line: Option<&Line>,
definition: &Definition<'_>,
) -> bool {
// for function definitions, track the known argument names for more accurate section detection.
// Determine whether the current line looks like a section header, e.g., "Args:".
let section_name_suffix = line[usize::from(indent_size + section_name_size)..].trim();
let this_looks_like_a_section_name =
section_name_suffix == ":" || section_name_suffix.is_empty();
if !this_looks_like_a_section_name {
return false;
}
// Determine whether the next line is an underline, e.g., "-----".
let next_line_is_underline = next_line.is_some_and(|next_line| {
let next_line = next_line.trim();
if next_line.is_empty() {
false
} else {
next_line.chars().all(|char| matches!(char, '-' | '='))
}
});
if next_line_is_underline {
return true;
}
// Determine whether the previous line looks like the end of a paragraph.
let previous_line_looks_like_end_of_paragraph = previous_line.is_none_or(|previous_line| {
let previous_line = previous_line.trim();
let previous_line_ends_with_punctuation = [',', ';', '.', '-', '\\', '/', ']', '}', ')']
.into_iter()
.any(|char| previous_line.ends_with(char));
previous_line_ends_with_punctuation || previous_line.is_empty()
});
if !previous_line_looks_like_end_of_paragraph {
return false;
}
// Determine if this is a sub-section within another section, like `args` in:
// ```python
// def func(args: tuple[int]):
// """Toggle the gizmo.
//
// Args:
// args: The arguments to the function.
// """
// ```
// Or `parameters` in:
// ```python
// def func(parameters: tuple[int]):
// """Toggle the gizmo.
//
// Parameters:
// -----
// parameters:
// The arguments to the function.
// """
// ```
// However, if the header is an _exact_ match (like `Returns:`, as opposed to `returns:`), then
// continue to treat it as a section header.
if let Some(previous_section) = previous_section {
let verbatim = &line[TextRange::at(indent_size, section_name_size)];
// If the section is more deeply indented, assume it's a subsection, as in:
// ```python
// def func(args: tuple[int]):
// """Toggle the gizmo.
//
// Args:
// args: The arguments to the function.
// """
// ```
// As noted above, an exact match for a section name (like the inner `Args:` below) is
// treated as a section header, unless the enclosing `Definition` is a function and contains
// a parameter with the same name, as in:
// ```python
// def func(Args: tuple[int]):
// """Toggle the gizmo.
//
// Args:
// Args: The arguments to the function.
// """
// ```
if previous_section.indent_size < indent_size {
let section_name = section_kind.as_str();
if section_name != verbatim || has_parameter(definition, section_name) {
return false;
}
}
// If the section has a preceding empty line, assume it's _not_ a subsection, as in:
// ```python
// def func(args: tuple[int]):
// """Toggle the gizmo.
//
// Args:
// args: The arguments to the function.
//
// returns:
// The return value of the function.
// """
// ```
if previous_line.is_some_and(|line| line.trim().is_empty()) {
return true;
}
// If the section isn't underlined, and isn't title-cased, assume it's a subsection,
// as in:
// ```python
// def func(parameters: tuple[int]):
// """Toggle the gizmo.
//
// Parameters:
// -----
// parameters:
// The arguments to the function.
// """
// ```
if !next_line_is_underline && verbatim.chars().next().is_some_and(char::is_lowercase) {
if section_kind.as_str() != verbatim {
return false;
}
}
}
true
}
/// Returns whether or not `definition` is a function definition and contains a parameter with the
/// same name as `section_name`.
fn has_parameter(definition: &Definition, section_name: &str) -> bool {
definition.as_function_def().is_some_and(|func| {
func.parameters
.iter()
.any(|param| param.name() == section_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/linter/float.rs | crates/ruff_linter/src/linter/float.rs | use ruff_python_ast as ast;
/// Checks if `expr` is a string literal that represents NaN.
/// E.g., `"NaN"`, `"-nAn"`, `"+nan"`, or even `" -NaNα\n \t"`
/// Returns `None` if it's not. Else `Some("nan")`, `Some("-nan")`, or `Some("+nan")`.
pub(crate) fn as_nan_float_string_literal(expr: &ast::Expr) -> Option<&'static str> {
find_any_ignore_ascii_case(expr, &["nan", "+nan", "-nan"])
}
/// Returns `true` if `expr` is a string literal that represents a non-finite float.
/// E.g., `"NaN"`, "-inf", `"Infinity"`, or even `" +Infα\n \t"`.
/// Return `None` if it's not. Else the lowercased, trimmed string literal,
/// e.g., `Some("nan")`, `Some("-inf")`, or `Some("+infinity")`.
pub(crate) fn as_non_finite_float_string_literal(expr: &ast::Expr) -> Option<&'static str> {
find_any_ignore_ascii_case(
expr,
&[
"nan",
"+nan",
"-nan",
"inf",
"+inf",
"-inf",
"infinity",
"+infinity",
"-infinity",
],
)
}
fn find_any_ignore_ascii_case(expr: &ast::Expr, patterns: &[&'static str]) -> Option<&'static str> {
let value = &expr.as_string_literal_expr()?.value;
let value = value.to_str().trim();
patterns
.iter()
.find(|other| value.eq_ignore_ascii_case(other))
.copied()
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/imports.rs | crates/ruff_linter/src/checkers/imports.rs | //! Lint rules based on import analysis.
use ruff_notebook::CellOffsets;
use ruff_python_ast::statement_visitor::StatementVisitor;
use ruff_python_ast::{ModModule, PySourceType, PythonVersion};
use ruff_python_codegen::Stylist;
use ruff_python_index::Indexer;
use ruff_python_parser::Parsed;
use crate::Locator;
use crate::directives::IsortDirectives;
use crate::package::PackageRoot;
use crate::registry::Rule;
use crate::rules::isort;
use crate::rules::isort::block::{Block, BlockBuilder};
use crate::settings::LinterSettings;
use super::ast::LintContext;
#[expect(clippy::too_many_arguments)]
pub(crate) fn check_imports(
parsed: &Parsed<ModModule>,
locator: &Locator,
indexer: &Indexer,
directives: &IsortDirectives,
settings: &LinterSettings,
stylist: &Stylist,
package: Option<PackageRoot<'_>>,
source_type: PySourceType,
cell_offsets: Option<&CellOffsets>,
target_version: PythonVersion,
context: &LintContext,
) {
// Extract all import blocks from the AST.
let tracker = {
let mut tracker =
BlockBuilder::new(locator, directives, source_type.is_stub(), cell_offsets);
tracker.visit_body(parsed.suite());
tracker
};
let blocks: Vec<&Block> = tracker.iter().collect();
// Enforce import rules.
if context.is_rule_enabled(Rule::UnsortedImports) {
for block in &blocks {
if !block.imports.is_empty() {
isort::rules::organize_imports(
block,
locator,
stylist,
indexer,
settings,
package,
source_type,
parsed.tokens(),
target_version,
context,
);
}
}
}
if context.is_rule_enabled(Rule::MissingRequiredImport) {
isort::rules::add_required_imports(
parsed,
locator,
stylist,
settings,
source_type,
context,
);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/filesystem.rs | crates/ruff_linter/src/checkers/filesystem.rs | use std::path::Path;
use ruff_python_ast::PythonVersion;
use ruff_python_trivia::CommentRanges;
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::package::PackageRoot;
use crate::preview::is_allow_nested_roots_enabled;
use crate::registry::Rule;
use crate::rules::flake8_builtins::rules::stdlib_module_shadowing;
use crate::rules::flake8_no_pep420::rules::implicit_namespace_package;
use crate::rules::pep8_naming::rules::invalid_module_name;
use crate::settings::LinterSettings;
pub(crate) fn check_file_path(
path: &Path,
package: Option<PackageRoot<'_>>,
locator: &Locator,
comment_ranges: &CommentRanges,
settings: &LinterSettings,
target_version: PythonVersion,
context: &LintContext,
) {
// flake8-no-pep420
if context.is_rule_enabled(Rule::ImplicitNamespacePackage) {
let allow_nested_roots = is_allow_nested_roots_enabled(settings);
implicit_namespace_package(
path,
package,
locator,
comment_ranges,
&settings.project_root,
&settings.src,
allow_nested_roots,
context,
);
}
// pep8-naming
if context.is_rule_enabled(Rule::InvalidModuleName) {
invalid_module_name(path, package, &settings.pep8_naming.ignore_names, context);
}
// flake8-builtins
if context.is_rule_enabled(Rule::StdlibModuleShadowing) {
stdlib_module_shadowing(path, settings, target_version, context);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/tokens.rs | crates/ruff_linter/src/checkers/tokens.rs | //! Lint rules based on token traversal.
use std::path::Path;
use ruff_notebook::CellOffsets;
use ruff_python_ast::PySourceType;
use ruff_python_ast::token::Tokens;
use ruff_python_codegen::Stylist;
use ruff_python_index::Indexer;
use crate::Locator;
use crate::directives::TodoComment;
use crate::registry::Rule;
use crate::rules::pycodestyle::rules::BlankLinesChecker;
use crate::rules::{
eradicate, flake8_commas, flake8_executable, flake8_fixme, flake8_implicit_str_concat,
flake8_pyi, flake8_todos, pycodestyle, pygrep_hooks, pylint, pyupgrade, ruff,
};
use super::ast::LintContext;
#[expect(clippy::too_many_arguments)]
pub(crate) fn check_tokens(
tokens: &Tokens,
path: &Path,
locator: &Locator,
indexer: &Indexer,
stylist: &Stylist,
source_type: PySourceType,
cell_offsets: Option<&CellOffsets>,
context: &mut LintContext,
) {
let comment_ranges = indexer.comment_ranges();
if context.any_rule_enabled(&[
Rule::BlankLineBetweenMethods,
Rule::BlankLinesTopLevel,
Rule::TooManyBlankLines,
Rule::BlankLineAfterDecorator,
Rule::BlankLinesAfterFunctionOrClass,
Rule::BlankLinesBeforeNestedDefinition,
]) {
BlankLinesChecker::new(locator, stylist, source_type, cell_offsets, context)
.check_lines(tokens);
}
if context.is_rule_enabled(Rule::BlanketTypeIgnore) {
pygrep_hooks::rules::blanket_type_ignore(context, comment_ranges, locator);
}
if context.is_rule_enabled(Rule::EmptyComment) {
pylint::rules::empty_comments(context, comment_ranges, locator, indexer);
}
if context.is_rule_enabled(Rule::AmbiguousUnicodeCharacterComment) {
for range in comment_ranges {
ruff::rules::ambiguous_unicode_character_comment(context, locator, range);
}
}
if context.is_rule_enabled(Rule::CommentedOutCode) {
eradicate::rules::commented_out_code(context, locator, comment_ranges);
}
if context.is_rule_enabled(Rule::UTF8EncodingDeclaration) {
pyupgrade::rules::unnecessary_coding_comment(context, locator, comment_ranges);
}
if context.is_rule_enabled(Rule::TabIndentation) {
pycodestyle::rules::tab_indentation(context, locator, indexer);
}
if context.any_rule_enabled(&[
Rule::InvalidCharacterBackspace,
Rule::InvalidCharacterSub,
Rule::InvalidCharacterEsc,
Rule::InvalidCharacterNul,
Rule::InvalidCharacterZeroWidthSpace,
]) {
for token in tokens {
pylint::rules::invalid_string_characters(context, token, locator);
}
}
if context.any_rule_enabled(&[
Rule::MultipleStatementsOnOneLineColon,
Rule::MultipleStatementsOnOneLineSemicolon,
Rule::UselessSemicolon,
]) {
pycodestyle::rules::compound_statements(
context,
tokens,
locator,
indexer,
source_type,
cell_offsets,
);
}
if context.any_rule_enabled(&[
Rule::SingleLineImplicitStringConcatenation,
Rule::MultiLineImplicitStringConcatenation,
]) {
flake8_implicit_str_concat::rules::implicit(context, tokens, locator, indexer);
}
if context.any_rule_enabled(&[
Rule::MissingTrailingComma,
Rule::TrailingCommaOnBareTuple,
Rule::ProhibitedTrailingComma,
]) {
flake8_commas::rules::trailing_commas(context, tokens, locator, indexer);
}
if context.is_rule_enabled(Rule::ExtraneousParentheses) {
pyupgrade::rules::extraneous_parentheses(context, tokens, locator);
}
if source_type.is_stub() && context.is_rule_enabled(Rule::TypeCommentInStub) {
flake8_pyi::rules::type_comment_in_stub(context, locator, comment_ranges);
}
if context.any_rule_enabled(&[
Rule::ShebangNotExecutable,
Rule::ShebangMissingExecutableFile,
Rule::ShebangLeadingWhitespace,
Rule::ShebangNotFirstLine,
Rule::ShebangMissingPython,
]) {
flake8_executable::rules::from_tokens(context, path, locator, comment_ranges);
}
if context.any_rule_enabled(&[
Rule::InvalidTodoTag,
Rule::MissingTodoAuthor,
Rule::MissingTodoLink,
Rule::MissingTodoColon,
Rule::MissingTodoDescription,
Rule::InvalidTodoCapitalization,
Rule::MissingSpaceAfterTodoColon,
Rule::LineContainsFixme,
Rule::LineContainsXxx,
Rule::LineContainsTodo,
Rule::LineContainsHack,
]) {
let todo_comments: Vec<TodoComment> = comment_ranges
.iter()
.enumerate()
.filter_map(|(i, comment_range)| {
let comment = locator.slice(*comment_range);
TodoComment::from_comment(comment, *comment_range, i)
})
.collect();
flake8_todos::rules::todos(context, &todo_comments, locator, comment_ranges);
flake8_fixme::rules::todos(context, &todo_comments);
}
if context.is_rule_enabled(Rule::TooManyNewlinesAtEndOfFile) {
pycodestyle::rules::too_many_newlines_at_end_of_file(context, tokens, cell_offsets);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/noqa.rs | crates/ruff_linter/src/checkers/noqa.rs | //! `NoQA` enforcement and validation.
use std::path::Path;
use itertools::Itertools;
use rustc_hash::FxHashSet;
use ruff_python_trivia::CommentRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::fix::edits::delete_comment;
use crate::noqa::{
Code, Directive, FileExemption, FileNoqaDirectives, NoqaDirectives, NoqaMapping,
};
use crate::preview::is_range_suppressions_enabled;
use crate::registry::Rule;
use crate::rule_redirects::get_redirect_target;
use crate::rules::pygrep_hooks;
use crate::rules::ruff;
use crate::rules::ruff::rules::{UnusedCodes, UnusedNOQA};
use crate::settings::LinterSettings;
use crate::suppression::Suppressions;
use crate::{Edit, Fix, Locator};
use super::ast::LintContext;
/// RUF100
#[expect(clippy::too_many_arguments)]
pub(crate) fn check_noqa(
context: &mut LintContext,
path: &Path,
locator: &Locator,
comment_ranges: &CommentRanges,
noqa_line_for: &NoqaMapping,
analyze_directives: bool,
settings: &LinterSettings,
suppressions: &Suppressions,
) -> Vec<usize> {
// Identify any codes that are globally exempted (within the current file).
let file_noqa_directives =
FileNoqaDirectives::extract(locator, comment_ranges, &settings.external, path);
// Extract all `noqa` directives.
let mut noqa_directives =
NoqaDirectives::from_commented_ranges(comment_ranges, &settings.external, path, locator);
if file_noqa_directives.is_empty() && noqa_directives.is_empty() && suppressions.is_empty() {
return Vec::new();
}
let exemption = FileExemption::from(&file_noqa_directives);
// Indices of diagnostics that were ignored by a `noqa` directive.
let mut ignored_diagnostics = vec![];
// Remove any ignored diagnostics.
'outer: for (index, diagnostic) in context.iter().enumerate() {
// Can't ignore syntax errors.
let Some(code) = diagnostic.secondary_code() else {
continue;
};
if *code == Rule::BlanketNOQA.noqa_code() {
continue;
}
// Apply file-level suppressions first
if exemption.contains_secondary_code(code) {
ignored_diagnostics.push(index);
continue;
}
// Apply ranged suppressions next
if is_range_suppressions_enabled(settings) && suppressions.check_diagnostic(diagnostic) {
ignored_diagnostics.push(index);
continue;
}
// Apply end-of-line noqa suppressions last
let noqa_offsets = diagnostic
.parent()
.into_iter()
.chain(diagnostic.range().map(TextRange::start).into_iter())
.map(|position| noqa_line_for.resolve(position))
.unique();
for noqa_offset in noqa_offsets {
if let Some(directive_line) = noqa_directives.find_line_with_directive_mut(noqa_offset)
{
let suppressed = match &directive_line.directive {
Directive::All(_) => {
let Ok(rule) = Rule::from_code(code) else {
debug_assert!(false, "Invalid secondary code `{code}`");
continue;
};
directive_line.matches.push(rule);
ignored_diagnostics.push(index);
true
}
Directive::Codes(directive) => {
if directive.includes(code) {
let Ok(rule) = Rule::from_code(code) else {
debug_assert!(false, "Invalid secondary code `{code}`");
continue;
};
directive_line.matches.push(rule);
ignored_diagnostics.push(index);
true
} else {
false
}
}
};
if suppressed {
continue 'outer;
}
}
}
}
// Diagnostics for unused/invalid range suppressions
suppressions.check_suppressions(context, locator);
// Enforce that the noqa directive was actually used (RUF100), unless RUF100 was itself
// suppressed.
if context.is_rule_enabled(Rule::UnusedNOQA)
&& analyze_directives
&& !exemption.includes(Rule::UnusedNOQA)
{
let directives = noqa_directives
.lines()
.iter()
.map(|line| (&line.directive, &line.matches, false))
.chain(
file_noqa_directives
.lines()
.iter()
.map(|line| (&line.parsed_file_exemption, &line.matches, true)),
);
for (directive, matches, is_file_level) in directives {
match directive {
Directive::All(directive) => {
if matches.is_empty() {
let edit = delete_comment(directive.range(), locator);
let mut diagnostic = context.report_diagnostic(
UnusedNOQA {
codes: None,
kind: ruff::rules::UnusedNOQAKind::Noqa,
},
directive.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary);
diagnostic.set_fix(Fix::safe_edit(edit));
}
}
Directive::Codes(directive) => {
let mut disabled_codes = vec![];
let mut duplicated_codes = vec![];
let mut unknown_codes = vec![];
let mut unmatched_codes = vec![];
let mut valid_codes = vec![];
let mut seen_codes = FxHashSet::default();
let mut self_ignore = false;
for original_code in directive.iter().map(Code::as_str) {
let code = get_redirect_target(original_code).unwrap_or(original_code);
if Rule::UnusedNOQA.noqa_code() == code {
self_ignore = true;
break;
}
if seen_codes.insert(original_code) {
let is_code_used = if is_file_level {
context.iter().any(|diag| {
diag.secondary_code().is_some_and(|noqa| *noqa == code)
})
} else {
matches.iter().any(|match_| match_.noqa_code() == code)
} || settings
.external
.iter()
.any(|external| code.starts_with(external));
if is_code_used {
valid_codes.push(original_code);
} else if let Ok(rule) = Rule::from_code(code) {
if context.is_rule_enabled(rule) {
unmatched_codes.push(original_code);
} else {
disabled_codes.push(original_code);
}
} else {
unknown_codes.push(original_code);
}
} else {
duplicated_codes.push(original_code);
}
}
if self_ignore {
continue;
}
if !(disabled_codes.is_empty()
&& duplicated_codes.is_empty()
&& unknown_codes.is_empty()
&& unmatched_codes.is_empty())
{
let edit = if valid_codes.is_empty() {
delete_comment(directive.range(), locator)
} else {
let original_text = locator.slice(directive.range());
let prefix = if is_file_level {
if original_text.contains("flake8") {
"# flake8: noqa: "
} else {
"# ruff: noqa: "
}
} else {
"# noqa: "
};
Edit::range_replacement(
format!("{}{}", prefix, valid_codes.join(", ")),
directive.range(),
)
};
let mut diagnostic = context.report_diagnostic(
UnusedNOQA {
codes: Some(UnusedCodes {
disabled: disabled_codes
.iter()
.map(|code| (*code).to_string())
.collect(),
duplicated: duplicated_codes
.iter()
.map(|code| (*code).to_string())
.collect(),
unknown: unknown_codes
.iter()
.map(|code| (*code).to_string())
.collect(),
unmatched: unmatched_codes
.iter()
.map(|code| (*code).to_string())
.collect(),
}),
kind: ruff::rules::UnusedNOQAKind::Noqa,
},
directive.range(),
);
diagnostic.add_primary_tag(ruff_db::diagnostic::DiagnosticTag::Unnecessary);
diagnostic.set_fix(Fix::safe_edit(edit));
}
}
}
}
}
if context.is_rule_enabled(Rule::RedirectedNOQA) && !exemption.includes(Rule::RedirectedNOQA) {
ruff::rules::redirected_noqa(context, &noqa_directives);
ruff::rules::redirected_file_noqa(context, &file_noqa_directives);
}
if context.is_rule_enabled(Rule::BlanketNOQA) && !exemption.enumerates(Rule::BlanketNOQA) {
pygrep_hooks::rules::blanket_noqa(
context,
&noqa_directives,
locator,
&file_noqa_directives,
);
}
if context.is_rule_enabled(Rule::InvalidRuleCode)
&& !exemption.enumerates(Rule::InvalidRuleCode)
{
ruff::rules::invalid_noqa_code(context, &noqa_directives, locator, &settings.external);
}
ignored_diagnostics.sort_unstable();
ignored_diagnostics
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/mod.rs | crates/ruff_linter/src/checkers/mod.rs | pub(crate) mod ast;
pub(crate) mod filesystem;
pub(crate) mod imports;
pub(crate) mod logical_lines;
pub(crate) mod noqa;
pub(crate) mod physical_lines;
pub(crate) mod tokens;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/logical_lines.rs | crates/ruff_linter/src/checkers/logical_lines.rs | use ruff_python_ast::token::{TokenKind, Tokens};
use ruff_python_codegen::Stylist;
use ruff_python_index::Indexer;
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::line_width::IndentWidth;
use crate::registry::Rule;
use crate::rules::pycodestyle::rules::logical_lines::{
LogicalLines, TokenFlags, extraneous_whitespace, indentation, missing_whitespace,
missing_whitespace_after_keyword, missing_whitespace_around_operator, redundant_backslash,
space_after_comma, space_around_operator, whitespace_around_keywords,
whitespace_around_named_parameter_equals, whitespace_before_comment,
whitespace_before_parameters,
};
use crate::settings::LinterSettings;
use super::ast::LintContext;
/// Return the amount of indentation, expanding tabs to the next multiple of the settings' tab size.
pub(crate) fn expand_indent(line: &str, indent_width: IndentWidth) -> usize {
let line = line.trim_end_matches(['\n', '\r']);
let mut indent = 0;
let tab_size = indent_width.as_usize();
for c in line.bytes() {
match c {
b'\t' => indent = (indent / tab_size) * tab_size + tab_size,
b' ' => indent += 1,
_ => break,
}
}
indent
}
pub(crate) fn check_logical_lines(
tokens: &Tokens,
locator: &Locator,
indexer: &Indexer,
stylist: &Stylist,
settings: &LinterSettings,
context: &LintContext,
) {
let mut prev_line = None;
let mut prev_indent_level = None;
let indent_char = stylist.indentation().as_char();
let enforce_space_around_operator = context.any_rule_enabled(&[
Rule::MultipleSpacesBeforeOperator,
Rule::MultipleSpacesAfterOperator,
Rule::TabBeforeOperator,
Rule::TabAfterOperator,
]);
let enforce_whitespace_around_named_parameter_equals = context.any_rule_enabled(&[
Rule::UnexpectedSpacesAroundKeywordParameterEquals,
Rule::MissingWhitespaceAroundParameterEquals,
]);
let enforce_missing_whitespace_around_operator = context.any_rule_enabled(&[
Rule::MissingWhitespaceAroundOperator,
Rule::MissingWhitespaceAroundArithmeticOperator,
Rule::MissingWhitespaceAroundBitwiseOrShiftOperator,
Rule::MissingWhitespaceAroundModuloOperator,
]);
let enforce_missing_whitespace = context.is_rule_enabled(Rule::MissingWhitespace);
let enforce_space_after_comma =
context.any_rule_enabled(&[Rule::MultipleSpacesAfterComma, Rule::TabAfterComma]);
let enforce_extraneous_whitespace = context.any_rule_enabled(&[
Rule::WhitespaceAfterOpenBracket,
Rule::WhitespaceBeforeCloseBracket,
Rule::WhitespaceBeforePunctuation,
]);
let enforce_whitespace_around_keywords = context.any_rule_enabled(&[
Rule::MultipleSpacesAfterKeyword,
Rule::MultipleSpacesBeforeKeyword,
Rule::TabAfterKeyword,
Rule::TabBeforeKeyword,
]);
let enforce_missing_whitespace_after_keyword =
context.is_rule_enabled(Rule::MissingWhitespaceAfterKeyword);
let enforce_whitespace_before_comment = context.any_rule_enabled(&[
Rule::TooFewSpacesBeforeInlineComment,
Rule::NoSpaceAfterInlineComment,
Rule::NoSpaceAfterBlockComment,
Rule::MultipleLeadingHashesForBlockComment,
]);
let enforce_whitespace_before_parameters =
context.is_rule_enabled(Rule::WhitespaceBeforeParameters);
let enforce_redundant_backslash = context.is_rule_enabled(Rule::RedundantBackslash);
let enforce_indentation = context.any_rule_enabled(&[
Rule::IndentationWithInvalidMultiple,
Rule::NoIndentedBlock,
Rule::UnexpectedIndentation,
Rule::IndentationWithInvalidMultipleComment,
Rule::NoIndentedBlockComment,
Rule::UnexpectedIndentationComment,
Rule::OverIndented,
]);
for line in &LogicalLines::from_tokens(tokens, locator) {
if line.flags().contains(TokenFlags::OPERATOR) {
if enforce_space_around_operator {
space_around_operator(&line, context);
}
if enforce_whitespace_around_named_parameter_equals {
whitespace_around_named_parameter_equals(&line, context);
}
if enforce_missing_whitespace_around_operator {
missing_whitespace_around_operator(&line, context);
}
if enforce_missing_whitespace {
missing_whitespace(&line, context);
}
}
if line.flags().contains(TokenFlags::PUNCTUATION) && enforce_space_after_comma {
space_after_comma(&line, context);
}
if line
.flags()
.intersects(TokenFlags::OPERATOR | TokenFlags::BRACKET | TokenFlags::PUNCTUATION)
&& enforce_extraneous_whitespace
{
extraneous_whitespace(&line, context);
}
if line.flags().contains(TokenFlags::KEYWORD) {
if enforce_whitespace_around_keywords {
whitespace_around_keywords(&line, context);
}
if enforce_missing_whitespace_after_keyword {
missing_whitespace_after_keyword(&line, context);
}
}
if line.flags().contains(TokenFlags::COMMENT) && enforce_whitespace_before_comment {
whitespace_before_comment(&line, locator, context);
}
if line.flags().contains(TokenFlags::BRACKET) {
if enforce_whitespace_before_parameters {
whitespace_before_parameters(&line, context);
}
if enforce_redundant_backslash {
redundant_backslash(&line, locator, indexer, context);
}
}
// Extract the indentation level.
let Some(first_token) = line.first_token() else {
continue;
};
let range = if first_token.kind() == TokenKind::Indent {
first_token.range()
} else {
TextRange::new(locator.line_start(first_token.start()), first_token.start())
};
let indent_level = expand_indent(locator.slice(range), settings.tab_size);
let indent_size = 4;
if enforce_indentation {
indentation(
&line,
prev_line.as_ref(),
indent_char,
indent_level,
prev_indent_level,
indent_size,
range,
context,
);
}
if !line.is_comment_only() {
prev_line = Some(line);
prev_indent_level = Some(indent_level);
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/physical_lines.rs | crates/ruff_linter/src/checkers/physical_lines.rs | //! Lint rules based on checking physical lines.
use ruff_python_codegen::Stylist;
use ruff_python_index::Indexer;
use ruff_source_file::UniversalNewlines;
use ruff_text_size::TextSize;
use crate::Locator;
use crate::registry::Rule;
use crate::rules::flake8_copyright::rules::missing_copyright_notice;
use crate::rules::pycodestyle::rules::{
doc_line_too_long, line_too_long, mixed_spaces_and_tabs, no_newline_at_end_of_file,
trailing_whitespace,
};
use crate::rules::pylint;
use crate::rules::ruff::rules::indented_form_feed;
use crate::settings::LinterSettings;
use super::ast::LintContext;
pub(crate) fn check_physical_lines(
locator: &Locator,
stylist: &Stylist,
indexer: &Indexer,
doc_lines: &[TextSize],
settings: &LinterSettings,
context: &LintContext,
) {
let enforce_doc_line_too_long = context.is_rule_enabled(Rule::DocLineTooLong);
let enforce_line_too_long = context.is_rule_enabled(Rule::LineTooLong);
let enforce_no_newline_at_end_of_file =
context.is_rule_enabled(Rule::MissingNewlineAtEndOfFile);
let enforce_mixed_spaces_and_tabs = context.is_rule_enabled(Rule::MixedSpacesAndTabs);
let enforce_bidirectional_unicode = context.is_rule_enabled(Rule::BidirectionalUnicode);
let enforce_trailing_whitespace = context.is_rule_enabled(Rule::TrailingWhitespace);
let enforce_blank_line_contains_whitespace =
context.is_rule_enabled(Rule::BlankLineWithWhitespace);
let enforce_copyright_notice = context.is_rule_enabled(Rule::MissingCopyrightNotice);
let mut doc_lines_iter = doc_lines.iter().peekable();
let comment_ranges = indexer.comment_ranges();
for line in locator.contents().universal_newlines() {
while doc_lines_iter
.next_if(|doc_line_start| line.range().contains_inclusive(**doc_line_start))
.is_some()
{
if enforce_doc_line_too_long {
doc_line_too_long(&line, comment_ranges, settings, context);
}
}
if enforce_mixed_spaces_and_tabs {
mixed_spaces_and_tabs(&line, context);
}
if enforce_line_too_long {
line_too_long(&line, comment_ranges, settings, context);
}
if enforce_bidirectional_unicode {
pylint::rules::bidirectional_unicode(&line, context);
}
if enforce_trailing_whitespace || enforce_blank_line_contains_whitespace {
trailing_whitespace(&line, locator, indexer, context);
}
if context.is_rule_enabled(Rule::IndentedFormFeed) {
indented_form_feed(&line, context);
}
}
if enforce_no_newline_at_end_of_file {
no_newline_at_end_of_file(locator, stylist, context);
}
if enforce_copyright_notice {
missing_copyright_notice(locator, settings, context);
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use ruff_python_codegen::Stylist;
use ruff_python_index::Indexer;
use ruff_python_parser::parse_module;
use crate::Locator;
use crate::checkers::ast::LintContext;
use crate::line_width::LineLength;
use crate::registry::Rule;
use crate::rules::pycodestyle;
use crate::settings::LinterSettings;
use super::check_physical_lines;
#[test]
fn e501_non_ascii_char() {
let line = "'\u{4e9c}' * 2"; // 7 in UTF-32, 9 in UTF-8.
let locator = Locator::new(line);
let parsed = parse_module(line).unwrap();
let indexer = Indexer::from_tokens(parsed.tokens(), locator.contents());
let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents());
let check_with_max_line_length = |line_length: LineLength| {
let settings = LinterSettings {
pycodestyle: pycodestyle::settings::Settings {
max_line_length: line_length,
..pycodestyle::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::LineTooLong)
};
let diagnostics = LintContext::new(Path::new("<filename>"), line, &settings);
check_physical_lines(&locator, &stylist, &indexer, &[], &settings, &diagnostics);
diagnostics.into_parts().0
};
let line_length = LineLength::try_from(8).unwrap();
assert_eq!(check_with_max_line_length(line_length), vec![]);
assert_eq!(check_with_max_line_length(line_length), vec![]);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/annotation.rs | crates/ruff_linter/src/checkers/ast/annotation.rs | use ruff_python_ast::{PythonVersion, StmtFunctionDef};
use ruff_python_semantic::{ScopeKind, SemanticModel};
use crate::rules::flake8_type_checking;
use crate::settings::LinterSettings;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum AnnotationContext {
/// Python will evaluate the annotation at runtime, but it's not _required_ and, as such, could
/// be quoted to convert it into a typing-only annotation.
///
/// For example:
/// ```python
/// from pandas import DataFrame
///
/// def foo() -> DataFrame:
/// ...
/// ```
///
/// Above, Python will evaluate `DataFrame` at runtime in order to add it to `__annotations__`.
RuntimeEvaluated,
/// Python will evaluate the annotation at runtime, and it's required to be available at
/// runtime, as a library (like Pydantic) needs access to it.
RuntimeRequired,
/// The annotation is only evaluated at type-checking time.
TypingOnly,
}
impl AnnotationContext {
/// Determine the [`AnnotationContext`] for an annotation based on the current scope of the
/// semantic model.
pub(super) fn from_model(
semantic: &SemanticModel,
settings: &LinterSettings,
version: PythonVersion,
) -> Self {
// If the annotation is in a class scope (e.g., an annotated assignment for a
// class field) or a function scope, and that class or function is marked as
// runtime-required, treat the annotation as runtime-required.
match semantic.current_scope().kind {
ScopeKind::Class(class_def)
if flake8_type_checking::helpers::runtime_required_class(
class_def,
&settings.flake8_type_checking.runtime_required_base_classes,
&settings.flake8_type_checking.runtime_required_decorators,
semantic,
) =>
{
return Self::RuntimeRequired;
}
ScopeKind::Function(function_def)
if flake8_type_checking::helpers::runtime_required_function(
function_def,
&settings.flake8_type_checking.runtime_required_decorators,
semantic,
) =>
{
return Self::RuntimeRequired;
}
_ => {}
}
// If `__future__` annotations are enabled or it's a stub file,
// then annotations are never evaluated at runtime,
// so we can treat them as typing-only.
if semantic.future_annotations_or_stub() || version.defers_annotations() {
return Self::TypingOnly;
}
// Otherwise, if we're in a class or module scope, then the annotation needs to
// be available at runtime.
// See: https://docs.python.org/3/reference/simple_stmts.html#annotated-assignment-statements
if matches!(
semantic.current_scope().kind,
ScopeKind::Class(_) | ScopeKind::Module
) {
return Self::RuntimeEvaluated;
}
Self::TypingOnly
}
/// Determine the [`AnnotationContext`] to use for annotations in a function signature.
pub(super) fn from_function(
function_def: &StmtFunctionDef,
semantic: &SemanticModel,
settings: &LinterSettings,
version: PythonVersion,
) -> Self {
if flake8_type_checking::helpers::runtime_required_function(
function_def,
&settings.flake8_type_checking.runtime_required_decorators,
semantic,
) {
Self::RuntimeRequired
} else if semantic.future_annotations_or_stub() || version.defers_annotations() {
Self::TypingOnly
} else {
Self::RuntimeEvaluated
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/mod.rs | crates/ruff_linter/src/checkers/ast/mod.rs | //! [`Checker`] for AST-based lint rules.
//!
//! The [`Checker`] is responsible for traversing over the AST, building up the [`SemanticModel`],
//! and running any enabled [`Rule`]s at the appropriate place and time.
//!
//! The [`Checker`] is structured as a single pass over the AST that proceeds in "evaluation" order.
//! That is: the [`Checker`] typically iterates over nodes in the order in which they're evaluated
//! by the Python interpreter. This includes, e.g., deferring function body traversal until after
//! parent scopes have been fully traversed. Individual rules may also perform internal traversals
//! of the AST.
//!
//! The individual [`Visitor`] implementations within the [`Checker`] typically proceed in four
//! steps:
//!
//! 1. Binding: Bind any names introduced by the current node.
//! 2. Traversal: Recurse into the children of the current node.
//! 3. Clean-up: Perform any necessary clean-up after the current node has been fully traversed.
//! 4. Analysis: Run any relevant lint rules on the current node.
//!
//! The first three steps together compose the semantic analysis phase, while the last step
//! represents the lint-rule analysis phase. In the future, these steps may be separated into
//! distinct passes over the AST.
use std::cell::{OnceCell, RefCell};
use std::path::Path;
use itertools::Itertools;
use log::debug;
use rustc_hash::{FxHashMap, FxHashSet};
use ruff_db::diagnostic::{Annotation, Diagnostic, DiagnosticTag, IntoDiagnosticMessage, Span};
use ruff_diagnostics::{Applicability, Fix, IsolationLevel};
use ruff_notebook::{CellOffsets, NotebookIndex};
use ruff_python_ast::helpers::{collect_import_from_member, is_docstring_stmt, to_module_path};
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::name::QualifiedName;
use ruff_python_ast::str::Quote;
use ruff_python_ast::token::Tokens;
use ruff_python_ast::visitor::{Visitor, walk_except_handler, walk_pattern};
use ruff_python_ast::{
self as ast, AnyParameterRef, ArgOrKeyword, Comprehension, ElifElseClause, ExceptHandler, Expr,
ExprContext, ExprFString, ExprTString, InterpolatedStringElement, Keyword, MatchCase,
ModModule, Parameter, Parameters, Pattern, PythonVersion, Stmt, Suite, UnaryOp,
};
use ruff_python_ast::{PySourceType, helpers, str, visitor};
use ruff_python_codegen::{Generator, Stylist};
use ruff_python_index::Indexer;
use ruff_python_parser::semantic_errors::{
SemanticSyntaxChecker, SemanticSyntaxContext, SemanticSyntaxError, SemanticSyntaxErrorKind,
};
use ruff_python_parser::typing::{AnnotationKind, ParsedAnnotation, parse_type_annotation};
use ruff_python_parser::{ParseError, Parsed};
use ruff_python_semantic::all::{DunderAllDefinition, DunderAllFlags};
use ruff_python_semantic::analyze::{imports, typing};
use ruff_python_semantic::{
BindingFlags, BindingId, BindingKind, Exceptions, Export, FromImport, GeneratorKind, Globals,
Import, Module, ModuleKind, ModuleSource, NodeId, ScopeId, ScopeKind, SemanticModel,
SemanticModelFlags, StarImport, SubmoduleImport,
};
use ruff_python_stdlib::builtins::{python_builtins, python_magic_globals};
use ruff_python_trivia::CommentRanges;
use ruff_source_file::{OneIndexed, SourceFile, SourceFileBuilder, SourceRow};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::annotation::AnnotationContext;
use crate::docstrings::extraction::ExtractionTarget;
use crate::importer::{ImportRequest, Importer, ResolutionError};
use crate::noqa::NoqaMapping;
use crate::package::PackageRoot;
use crate::preview::is_undefined_export_in_dunder_init_enabled;
use crate::registry::Rule;
use crate::rules::flake8_bugbear::rules::ReturnInGenerator;
use crate::rules::pyflakes::rules::{
LateFutureImport, MultipleStarredExpressions, ReturnOutsideFunction,
UndefinedLocalWithNestedImportStarUsage, YieldOutsideFunction,
};
use crate::rules::pylint::rules::{
AwaitOutsideAsync, LoadBeforeGlobalDeclaration, NonlocalWithoutBinding,
YieldFromInAsyncFunction,
};
use crate::rules::{flake8_pyi, flake8_type_checking, pyflakes, pyupgrade};
use crate::settings::rule_table::RuleTable;
use crate::settings::{LinterSettings, TargetVersion, flags};
use crate::{Edit, Violation};
use crate::{Locator, docstrings, noqa};
mod analyze;
mod annotation;
mod deferred;
/// State representing whether a docstring is expected or not for the next statement.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) enum DocstringState {
/// The next statement is expected to be a docstring, but not necessarily so.
///
/// For example, in the following code:
///
/// ```python
/// class Foo:
/// pass
///
///
/// def bar(x, y):
/// """Docstring."""
/// return x + y
/// ```
///
/// For `Foo`, the state is expected when the checker is visiting the class
/// body but isn't going to be present. While, for `bar` function, the docstring
/// is expected and present.
Expected(ExpectedDocstringKind),
Other,
}
impl Default for DocstringState {
/// Returns the default docstring state which is to expect a module-level docstring.
fn default() -> Self {
Self::Expected(ExpectedDocstringKind::Module)
}
}
impl DocstringState {
/// Returns the docstring kind if the state is expecting a docstring.
const fn expected_kind(self) -> Option<ExpectedDocstringKind> {
match self {
DocstringState::Expected(kind) => Some(kind),
DocstringState::Other => None,
}
}
}
/// The kind of an expected docstring.
#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) enum ExpectedDocstringKind {
/// A module-level docstring.
///
/// For example,
/// ```python
/// """This is a module-level docstring."""
///
/// a = 1
/// ```
Module,
/// A class-level docstring.
///
/// For example,
/// ```python
/// class Foo:
/// """This is the docstring for `Foo` class."""
///
/// def __init__(self) -> None:
/// ...
/// ```
Class,
/// A function-level docstring.
///
/// For example,
/// ```python
/// def foo():
/// """This is the docstring for `foo` function."""
/// pass
/// ```
Function,
/// An attribute-level docstring.
///
/// For example,
/// ```python
/// a = 1
/// """This is the docstring for `a` variable."""
///
///
/// class Foo:
/// b = 1
/// """This is the docstring for `Foo.b` class variable."""
/// ```
Attribute,
}
impl ExpectedDocstringKind {
/// Returns the semantic model flag that represents the current docstring state.
const fn as_flag(self) -> SemanticModelFlags {
match self {
ExpectedDocstringKind::Attribute => SemanticModelFlags::ATTRIBUTE_DOCSTRING,
_ => SemanticModelFlags::PEP_257_DOCSTRING,
}
}
}
pub(crate) struct Checker<'a> {
/// The [`Parsed`] output for the source code.
parsed: &'a Parsed<ModModule>,
/// An internal cache for parsed string annotations
parsed_annotations_cache: ParsedAnnotationsCache<'a>,
/// The [`Parsed`] output for the type annotation the checker is currently in.
parsed_type_annotation: Option<&'a ParsedAnnotation>,
/// The [`Path`] to the file under analysis.
path: &'a Path,
/// Whether `path` points to an `__init__.py` file.
in_init_module: OnceCell<bool>,
/// The [`Path`] to the package containing the current file.
package: Option<PackageRoot<'a>>,
/// The module representation of the current file (e.g., `foo.bar`).
pub(crate) module: Module<'a>,
/// The [`PySourceType`] of the current file.
pub(crate) source_type: PySourceType,
/// The [`CellOffsets`] for the current file, if it's a Jupyter notebook.
cell_offsets: Option<&'a CellOffsets>,
/// The [`NotebookIndex`] for the current file, if it's a Jupyter notebook.
notebook_index: Option<&'a NotebookIndex>,
/// The [`flags::Noqa`] for the current analysis (i.e., whether to respect suppression
/// comments).
noqa: flags::Noqa,
/// The [`NoqaMapping`] for the current analysis (i.e., the mapping from line number to
/// suppression commented line number).
noqa_line_for: &'a NoqaMapping,
/// The [`Locator`] for the current file, which enables extraction of source code from byte
/// offsets.
locator: &'a Locator<'a>,
/// The [`Stylist`] for the current file, which detects the current line ending, quote, and
/// indentation style.
stylist: &'a Stylist<'a>,
/// The [`Indexer`] for the current file, which contains the offsets of all comments and more.
indexer: &'a Indexer,
/// The [`Importer`] for the current file, which enables importing of other modules.
importer: Importer<'a>,
/// The [`SemanticModel`], built up over the course of the AST traversal.
semantic: SemanticModel<'a>,
/// A set of deferred nodes to be visited after the current traversal (e.g., function bodies).
visit: deferred::Visit<'a>,
/// A set of deferred nodes to be analyzed after the AST traversal (e.g., `for` loops).
analyze: deferred::Analyze,
/// The list of names already seen by flake8-bugbear diagnostics, to avoid duplicate violations.
flake8_bugbear_seen: RefCell<FxHashSet<TextRange>>,
/// The end offset of the last visited statement.
last_stmt_end: TextSize,
/// A state describing if a docstring is expected or not.
docstring_state: DocstringState,
/// The target [`PythonVersion`] for version-dependent checks.
target_version: TargetVersion,
/// Helper visitor for detecting semantic syntax errors.
#[expect(clippy::struct_field_names)]
semantic_checker: SemanticSyntaxChecker,
/// Errors collected by the `semantic_checker`.
semantic_errors: RefCell<Vec<SemanticSyntaxError>>,
context: &'a LintContext<'a>,
}
impl<'a> Checker<'a> {
#[expect(clippy::too_many_arguments)]
pub(crate) fn new(
parsed: &'a Parsed<ModModule>,
parsed_annotations_arena: &'a typed_arena::Arena<Result<ParsedAnnotation, ParseError>>,
settings: &'a LinterSettings,
noqa_line_for: &'a NoqaMapping,
noqa: flags::Noqa,
path: &'a Path,
package: Option<PackageRoot<'a>>,
module: Module<'a>,
locator: &'a Locator,
stylist: &'a Stylist,
indexer: &'a Indexer,
source_type: PySourceType,
cell_offsets: Option<&'a CellOffsets>,
notebook_index: Option<&'a NotebookIndex>,
target_version: TargetVersion,
context: &'a LintContext<'a>,
) -> Self {
let semantic = SemanticModel::new(&settings.typing_modules, path, module);
Self {
parsed,
parsed_type_annotation: None,
parsed_annotations_cache: ParsedAnnotationsCache::new(parsed_annotations_arena),
noqa_line_for,
noqa,
path,
in_init_module: OnceCell::new(),
package,
module,
source_type,
locator,
stylist,
indexer,
importer: Importer::new(parsed, locator.contents(), stylist),
semantic,
visit: deferred::Visit::default(),
analyze: deferred::Analyze::default(),
flake8_bugbear_seen: RefCell::default(),
cell_offsets,
notebook_index,
last_stmt_end: TextSize::default(),
docstring_state: DocstringState::default(),
target_version,
semantic_checker: SemanticSyntaxChecker::new(),
semantic_errors: RefCell::default(),
context,
}
}
}
impl<'a> Checker<'a> {
/// Return `true` if a [`Rule`] is disabled by a `noqa` directive.
pub(crate) fn rule_is_ignored(&self, code: Rule, offset: TextSize) -> bool {
// TODO(charlie): `noqa` directives are mostly enforced in `check_lines.rs`.
// However, in rare cases, we need to check them here. For example, when
// removing unused imports, we create a single fix that's applied to all
// unused members on a single import. We need to preemptively omit any
// members from the fix that will eventually be excluded by a `noqa`.
// Unfortunately, we _do_ want to register a `Diagnostic` for each
// eventually-ignored import, so that our `noqa` counts are accurate.
if !self.noqa.is_enabled() {
return false;
}
noqa::rule_is_ignored(
code,
offset,
self.noqa_line_for,
self.comment_ranges(),
self.locator,
)
}
/// Create a [`Generator`] to generate source code based on the current AST state.
pub(crate) fn generator(&self) -> Generator<'_> {
Generator::new(self.stylist.indentation(), self.stylist.line_ending())
}
/// Return the preferred quote for a generated `StringLiteral` node, given where we are in the
/// AST.
fn preferred_quote(&self) -> Quote {
self.interpolated_string_quote_style()
.unwrap_or(self.stylist.quote())
}
/// Return the default string flags a generated `StringLiteral` node should use, given where we
/// are in the AST.
pub(crate) fn default_string_flags(&self) -> ast::StringLiteralFlags {
ast::StringLiteralFlags::empty().with_quote_style(self.preferred_quote())
}
/// Return the default bytestring flags a generated `ByteStringLiteral` node should use, given
/// where we are in the AST.
pub(crate) fn default_bytes_flags(&self) -> ast::BytesLiteralFlags {
ast::BytesLiteralFlags::empty().with_quote_style(self.preferred_quote())
}
// TODO(dylan) add similar method for t-strings
/// Return the default f-string flags a generated `FString` node should use, given where we are
/// in the AST.
pub(crate) fn default_fstring_flags(&self) -> ast::FStringFlags {
ast::FStringFlags::empty().with_quote_style(self.preferred_quote())
}
/// Returns the appropriate quoting for interpolated strings by reversing the one used outside of
/// the interpolated string.
///
/// If the current expression in the context is not an interpolated string, returns ``None``.
pub(crate) fn interpolated_string_quote_style(&self) -> Option<Quote> {
if !self.semantic.in_interpolated_string() {
return None;
}
// Find the quote character used to start the containing interpolated string.
self.semantic
.current_expressions()
.find_map(|expr| match expr {
Expr::FString(ExprFString { value, .. }) => {
Some(value.iter().next()?.quote_style().opposite())
}
Expr::TString(ExprTString { value, .. }) => {
Some(value.iter().next()?.quote_style().opposite())
}
_ => None,
})
}
/// Returns the [`SourceRow`] for the given offset.
pub(crate) fn compute_source_row(&self, offset: TextSize) -> SourceRow {
#[expect(deprecated)]
let line = self.locator.compute_line_index(offset);
if let Some(notebook_index) = self.notebook_index {
let cell = notebook_index.cell(line).unwrap_or(OneIndexed::MIN);
let line = notebook_index.cell_row(line).unwrap_or(OneIndexed::MIN);
SourceRow::Notebook { cell, line }
} else {
SourceRow::SourceFile { line }
}
}
/// Returns the [`CommentRanges`] for the parsed source code.
pub(crate) fn comment_ranges(&self) -> &'a CommentRanges {
self.indexer.comment_ranges()
}
/// Return a [`DiagnosticGuard`] for reporting a diagnostic.
///
/// The guard derefs to a [`Diagnostic`], so it can be used to further modify the diagnostic
/// before it is added to the collection in the checker on `Drop`.
pub(crate) fn report_diagnostic<'chk, T: Violation>(
&'chk self,
kind: T,
range: TextRange,
) -> DiagnosticGuard<'chk, 'a> {
self.context.report_diagnostic(kind, range)
}
/// Return a [`DiagnosticGuard`] for reporting a diagnostic if the corresponding rule is
/// enabled.
///
/// The guard derefs to a [`Diagnostic`], so it can be used to further modify the diagnostic
/// before it is added to the collection in the checker on `Drop`.
pub(crate) fn report_diagnostic_if_enabled<'chk, T: Violation>(
&'chk self,
kind: T,
range: TextRange,
) -> Option<DiagnosticGuard<'chk, 'a>> {
self.context.report_diagnostic_if_enabled(kind, range)
}
/// Adds a [`TextRange`] to the set of ranges of variable names
/// flagged in `flake8-bugbear` violations so far.
///
/// Returns whether the value was newly inserted.
pub(crate) fn insert_flake8_bugbear_range(&self, range: TextRange) -> bool {
let mut ranges = self.flake8_bugbear_seen.borrow_mut();
ranges.insert(range)
}
/// Returns the [`Tokens`] for the parsed type annotation if the checker is in a typing context
/// or the parsed source code.
pub(crate) fn tokens(&self) -> &'a Tokens {
if let Some(type_annotation) = self.parsed_type_annotation {
type_annotation.parsed().tokens()
} else {
self.parsed.tokens()
}
}
/// Returns the [`Tokens`] for the parsed source file.
///
///
/// Unlike [`Self::tokens`], this method always returns
/// the tokens for the current file, even when within a parsed type annotation.
pub(crate) fn source_tokens(&self) -> &'a Tokens {
self.parsed.tokens()
}
/// The [`Locator`] for the current file, which enables extraction of source code from byte
/// offsets.
pub(crate) const fn locator(&self) -> &'a Locator<'a> {
self.locator
}
pub(crate) const fn source(&self) -> &'a str {
self.locator.contents()
}
/// The [`Stylist`] for the current file, which detects the current line ending, quote, and
/// indentation style.
pub(crate) const fn stylist(&self) -> &'a Stylist<'a> {
self.stylist
}
/// The [`Indexer`] for the current file, which contains the offsets of all comments and more.
pub(crate) const fn indexer(&self) -> &'a Indexer {
self.indexer
}
/// The [`Importer`] for the current file, which enables importing of other modules.
pub(crate) const fn importer(&self) -> &Importer<'a> {
&self.importer
}
/// The [`SemanticModel`], built up over the course of the AST traversal.
pub(crate) const fn semantic(&self) -> &SemanticModel<'a> {
&self.semantic
}
/// The [`LinterSettings`] for the current analysis, including the enabled rules.
pub(crate) const fn settings(&self) -> &'a LinterSettings {
self.context.settings
}
/// Returns whether the file under analysis is an `__init__.py` file.
pub(crate) fn in_init_module(&self) -> bool {
*self
.in_init_module
.get_or_init(|| self.path.ends_with("__init__.py"))
}
/// The [`Path`] to the package containing the current file.
pub(crate) const fn package(&self) -> Option<PackageRoot<'_>> {
self.package
}
/// The [`CellOffsets`] for the current file, if it's a Jupyter notebook.
pub(crate) const fn cell_offsets(&self) -> Option<&'a CellOffsets> {
self.cell_offsets
}
/// Returns whether the given rule should be checked.
#[inline]
pub(crate) const fn is_rule_enabled(&self, rule: Rule) -> bool {
self.context.is_rule_enabled(rule)
}
/// Returns whether any of the given rules should be checked.
#[inline]
pub(crate) const fn any_rule_enabled(&self, rules: &[Rule]) -> bool {
self.context.any_rule_enabled(rules)
}
/// Returns the [`IsolationLevel`] to isolate fixes for a given node.
///
/// The primary use-case for fix isolation is to ensure that we don't delete all statements
/// in a given indented block, which would cause a syntax error. We therefore need to ensure
/// that we delete at most one statement per indented block per fixer pass. Fix isolation should
/// thus be applied whenever we delete a statement, but can otherwise be omitted.
pub(crate) fn isolation(node_id: Option<NodeId>) -> IsolationLevel {
node_id
.map(|node_id| IsolationLevel::Group(node_id.into()))
.unwrap_or_default()
}
/// Parse a stringified type annotation as an AST expression,
/// e.g. `"List[str]"` in `x: "List[str]"`
///
/// This method is a wrapper around [`ruff_python_parser::typing::parse_type_annotation`]
/// that adds caching.
pub(crate) fn parse_type_annotation(
&self,
annotation: &ast::ExprStringLiteral,
) -> Result<&'a ParsedAnnotation, &'a ParseError> {
self.parsed_annotations_cache
.lookup_or_parse(annotation, self.locator.contents())
}
/// Apply a test to an annotation expression,
/// abstracting over the fact that the annotation expression might be "stringized".
///
/// A stringized annotation is one enclosed in string quotes:
/// `foo: "typing.Any"` means the same thing to a type checker as `foo: typing.Any`.
pub(crate) fn match_maybe_stringized_annotation(
&self,
expr: &ast::Expr,
match_fn: impl FnOnce(&ast::Expr) -> bool,
) -> bool {
if let ast::Expr::StringLiteral(string_annotation) = expr {
let Some(parsed_annotation) = self.parse_type_annotation(string_annotation).ok() else {
return false;
};
match_fn(parsed_annotation.expression())
} else {
match_fn(expr)
}
}
/// Push `diagnostic` if the checker is not in a `@no_type_check` context.
pub(crate) fn report_type_diagnostic<T: Violation>(&self, kind: T, range: TextRange) {
if !self.semantic.in_no_type_check() {
self.report_diagnostic(kind, range);
}
}
/// Return the [`PythonVersion`] to use for version-related lint rules.
///
/// If the user did not provide a target version, this defaults to the lowest supported Python
/// version ([`PythonVersion::default`]).
///
/// Note that this method should not be used for version-related syntax errors emitted by the
/// parser or the [`SemanticSyntaxChecker`], which should instead default to the _latest_
/// supported Python version.
pub(crate) fn target_version(&self) -> PythonVersion {
self.target_version.linter_version()
}
fn with_semantic_checker(&mut self, f: impl FnOnce(&mut SemanticSyntaxChecker, &Checker)) {
let mut checker = std::mem::take(&mut self.semantic_checker);
f(&mut checker, self);
self.semantic_checker = checker;
}
/// Create a [`TypingImporter`] that will import `member` from either `typing` or
/// `typing_extensions`.
///
/// On Python <`version_added_to_typing`, `member` is imported from `typing_extensions`, while
/// on Python >=`version_added_to_typing`, it is imported from `typing`.
///
/// If the Python version is less than `version_added_to_typing` but
/// `LinterSettings::typing_extensions` is `false`, this method returns `None`.
pub(crate) fn typing_importer<'b>(
&'b self,
member: &'b str,
version_added_to_typing: PythonVersion,
) -> Option<TypingImporter<'b, 'a>> {
let source_module = if self.target_version() >= version_added_to_typing {
"typing"
} else if !self.settings().typing_extensions {
return None;
} else {
"typing_extensions"
};
Some(TypingImporter {
checker: self,
source_module,
member,
})
}
/// Return the [`LintContext`] for the current analysis.
///
/// Note that you should always prefer calling methods like `settings`, `report_diagnostic`, or
/// `is_rule_enabled` directly on [`Checker`] when possible. This method exists only for the
/// rare cases where rules or helper functions need to be accessed by both a `Checker` and a
/// `LintContext` in different analysis phases.
pub(crate) const fn context(&self) -> &'a LintContext<'a> {
self.context
}
/// Return the current [`DocstringState`].
pub(crate) fn docstring_state(&self) -> DocstringState {
self.docstring_state
}
}
pub(crate) struct TypingImporter<'a, 'b> {
checker: &'a Checker<'b>,
source_module: &'static str,
member: &'a str,
}
impl TypingImporter<'_, '_> {
/// Create an [`Edit`] that makes the requested symbol available at `position`.
///
/// See [`Importer::get_or_import_symbol`] for more details on the returned values and
/// [`Checker::typing_importer`] for a way to construct a [`TypingImporter`].
pub(crate) fn import(&self, position: TextSize) -> Result<(Edit, String), ResolutionError> {
let request = ImportRequest::import_from(self.source_module, self.member);
self.checker
.importer
.get_or_import_symbol(&request, position, self.checker.semantic())
}
}
impl SemanticSyntaxContext for Checker<'_> {
fn python_version(&self) -> PythonVersion {
// Reuse `parser_version` here, which should default to `PythonVersion::latest` instead of
// `PythonVersion::default` to minimize version-related semantic syntax errors when
// `target_version` is unset.
self.target_version.parser_version()
}
fn global(&self, name: &str) -> Option<TextRange> {
self.semantic.global(name)
}
fn has_nonlocal_binding(&self, name: &str) -> bool {
self.semantic.nonlocal(name).is_some()
}
fn report_semantic_error(&self, error: SemanticSyntaxError) {
match error.kind {
SemanticSyntaxErrorKind::LateFutureImport => {
// F404
if self.is_rule_enabled(Rule::LateFutureImport) {
self.report_diagnostic(LateFutureImport, error.range);
}
}
SemanticSyntaxErrorKind::LoadBeforeGlobalDeclaration { name, start } => {
if self.is_rule_enabled(Rule::LoadBeforeGlobalDeclaration) {
self.report_diagnostic(
LoadBeforeGlobalDeclaration {
name,
row: self.compute_source_row(start),
},
error.range,
);
}
}
SemanticSyntaxErrorKind::YieldOutsideFunction(kind) => {
if self.is_rule_enabled(Rule::YieldOutsideFunction) {
self.report_diagnostic(YieldOutsideFunction::new(kind), error.range);
}
}
SemanticSyntaxErrorKind::NonModuleImportStar(name) => {
if self.is_rule_enabled(Rule::UndefinedLocalWithNestedImportStarUsage) {
self.report_diagnostic(
UndefinedLocalWithNestedImportStarUsage { name },
error.range,
);
}
}
SemanticSyntaxErrorKind::ReturnOutsideFunction => {
// F706
if self.is_rule_enabled(Rule::ReturnOutsideFunction) {
self.report_diagnostic(ReturnOutsideFunction, error.range);
}
}
SemanticSyntaxErrorKind::AwaitOutsideAsyncFunction(_) => {
if self.is_rule_enabled(Rule::AwaitOutsideAsync) {
self.report_diagnostic(AwaitOutsideAsync, error.range);
}
}
SemanticSyntaxErrorKind::YieldFromInAsyncFunction => {
// PLE1700
if self.is_rule_enabled(Rule::YieldFromInAsyncFunction) {
self.report_diagnostic(YieldFromInAsyncFunction, error.range);
}
}
SemanticSyntaxErrorKind::MultipleStarredExpressions => {
// F622
if self.is_rule_enabled(Rule::MultipleStarredExpressions) {
self.report_diagnostic(MultipleStarredExpressions, error.range);
}
}
SemanticSyntaxErrorKind::FutureFeatureNotDefined(name) => {
// F407
if self.is_rule_enabled(Rule::FutureFeatureNotDefined) {
self.report_diagnostic(
pyflakes::rules::FutureFeatureNotDefined { name },
error.range,
);
}
}
SemanticSyntaxErrorKind::BreakOutsideLoop => {
// F701
if self.is_rule_enabled(Rule::BreakOutsideLoop) {
self.report_diagnostic(pyflakes::rules::BreakOutsideLoop, error.range);
}
}
SemanticSyntaxErrorKind::ContinueOutsideLoop => {
// F702
if self.is_rule_enabled(Rule::ContinueOutsideLoop) {
self.report_diagnostic(pyflakes::rules::ContinueOutsideLoop, error.range);
}
}
SemanticSyntaxErrorKind::NonlocalWithoutBinding(name) => {
// PLE0117
if self.is_rule_enabled(Rule::NonlocalWithoutBinding) {
self.report_diagnostic(NonlocalWithoutBinding { name }, error.range);
}
}
SemanticSyntaxErrorKind::ReturnInGenerator => {
// B901
if self.is_rule_enabled(Rule::ReturnInGenerator) {
self.report_diagnostic(ReturnInGenerator, error.range);
}
}
SemanticSyntaxErrorKind::ReboundComprehensionVariable
| SemanticSyntaxErrorKind::DuplicateTypeParameter
| SemanticSyntaxErrorKind::MultipleCaseAssignment(_)
| SemanticSyntaxErrorKind::IrrefutableCasePattern(_)
| SemanticSyntaxErrorKind::SingleStarredAssignment
| SemanticSyntaxErrorKind::WriteToDebug(_)
| SemanticSyntaxErrorKind::DifferentMatchPatternBindings
| SemanticSyntaxErrorKind::InvalidExpression(..)
| SemanticSyntaxErrorKind::GlobalParameter(_)
| SemanticSyntaxErrorKind::DuplicateMatchKey(_)
| SemanticSyntaxErrorKind::DuplicateMatchClassAttribute(_)
| SemanticSyntaxErrorKind::InvalidStarExpression
| SemanticSyntaxErrorKind::AsyncComprehensionInSyncComprehension(_)
| SemanticSyntaxErrorKind::DuplicateParameter(_)
| SemanticSyntaxErrorKind::NonlocalDeclarationAtModuleLevel
| SemanticSyntaxErrorKind::LoadBeforeNonlocalDeclaration { .. }
| SemanticSyntaxErrorKind::NonlocalAndGlobal(_)
| SemanticSyntaxErrorKind::AnnotatedGlobal(_)
| SemanticSyntaxErrorKind::TypeParameterDefaultOrder(_)
| SemanticSyntaxErrorKind::AnnotatedNonlocal(_) => {
self.semantic_errors.borrow_mut().push(error);
}
}
}
fn source(&self) -> &str {
self.source()
}
fn future_annotations_or_stub(&self) -> bool {
self.semantic.future_annotations_or_stub()
}
fn in_async_context(&self) -> bool {
for scope in self.semantic.current_scopes() {
match scope.kind {
ScopeKind::Class(_) | ScopeKind::Lambda(_) => return false,
ScopeKind::Function(ast::StmtFunctionDef { is_async, .. }) => return *is_async,
ScopeKind::Generator { .. }
| ScopeKind::Module
| ScopeKind::Type
| ScopeKind::DunderClassCell => {}
}
}
false
}
fn in_await_allowed_context(&self) -> bool {
for scope in self.semantic.current_scopes() {
match scope.kind {
ScopeKind::Class(_) => return false,
ScopeKind::Function(_) | ScopeKind::Lambda(_) => return true,
ScopeKind::Generator {
kind: GeneratorKind::Generator,
..
} => return true,
ScopeKind::Generator { .. }
| ScopeKind::Module
| ScopeKind::Type
| 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/checkers/ast/deferred.rs | crates/ruff_linter/src/checkers/ast/deferred.rs | use ruff_python_ast::{Expr, ExprStringLiteral};
use ruff_python_semantic::{ScopeId, Snapshot};
/// A collection of AST nodes that are deferred for later visitation. Used to, e.g., store
/// functions, whose bodies shouldn't be visited until all module-level definitions have been
/// visited.
#[derive(Debug, Default)]
pub(crate) struct Visit<'a> {
pub(crate) string_type_definitions: Vec<(&'a ExprStringLiteral, Snapshot)>,
pub(crate) future_type_definitions: Vec<(&'a Expr, Snapshot)>,
pub(crate) type_param_definitions: Vec<(&'a Expr, Snapshot)>,
pub(crate) functions: Vec<Snapshot>,
pub(crate) lambdas: Vec<Snapshot>,
/// N.B. This field should always be empty unless it's a stub file
pub(crate) class_bases: Vec<(&'a Expr, Snapshot)>,
}
impl Visit<'_> {
/// Returns `true` if there are no deferred nodes.
pub(crate) fn is_empty(&self) -> bool {
self.string_type_definitions.is_empty()
&& self.future_type_definitions.is_empty()
&& self.type_param_definitions.is_empty()
&& self.functions.is_empty()
&& self.lambdas.is_empty()
&& self.class_bases.is_empty()
}
}
/// A collection of AST nodes to be analyzed after the AST traversal. Used to, e.g., store
/// all `for` loops, so that they can be analyzed after the entire AST has been visited.
#[derive(Debug, Default)]
pub(crate) struct Analyze {
pub(crate) scopes: Vec<ScopeId>,
pub(crate) lambdas: Vec<Snapshot>,
pub(crate) for_loops: Vec<Snapshot>,
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs | crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs | use ruff_python_ast::{self as ast, ExceptHandler};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::rules::{
flake8_bandit, flake8_blind_except, flake8_bugbear, flake8_builtins, pycodestyle, pylint,
};
/// Run lint rules over an [`ExceptHandler`] syntax node.
pub(crate) fn except_handler(except_handler: &ExceptHandler, checker: &Checker) {
match except_handler {
ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
type_,
name,
body,
range: _,
node_index: _,
}) => {
if checker.is_rule_enabled(Rule::BareExcept) {
pycodestyle::rules::bare_except(checker, type_.as_deref(), body, except_handler);
}
if checker.is_rule_enabled(Rule::RaiseWithoutFromInsideExcept) {
flake8_bugbear::rules::raise_without_from_inside_except(
checker,
name.as_deref(),
body,
);
}
if checker.is_rule_enabled(Rule::BlindExcept) {
flake8_blind_except::rules::blind_except(
checker,
type_.as_deref(),
name.as_deref(),
body,
);
}
if checker.is_rule_enabled(Rule::TryExceptPass) {
flake8_bandit::rules::try_except_pass(
checker,
except_handler,
type_.as_deref(),
body,
checker.settings().flake8_bandit.check_typed_exception,
);
}
if checker.is_rule_enabled(Rule::TryExceptContinue) {
flake8_bandit::rules::try_except_continue(
checker,
except_handler,
type_.as_deref(),
body,
checker.settings().flake8_bandit.check_typed_exception,
);
}
if checker.is_rule_enabled(Rule::ExceptWithEmptyTuple) {
flake8_bugbear::rules::except_with_empty_tuple(checker, except_handler);
}
if checker.is_rule_enabled(Rule::ExceptWithNonExceptionClasses) {
flake8_bugbear::rules::except_with_non_exception_classes(checker, except_handler);
}
if checker.is_rule_enabled(Rule::BinaryOpException) {
pylint::rules::binary_op_exception(checker, except_handler);
}
if let Some(name) = name {
if checker.is_rule_enabled(Rule::AmbiguousVariableName) {
pycodestyle::rules::ambiguous_variable_name(
checker,
name.as_str(),
name.range(),
);
}
if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(checker, name, name.range());
}
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs | crates/ruff_linter/src/checkers/ast/analyze/bindings.rs | use ruff_text_size::Ranged;
use crate::Fix;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{
flake8_import_conventions, flake8_pyi, flake8_pytest_style, flake8_return,
flake8_type_checking, pyflakes, pylint, pyupgrade, refurb, ruff,
};
/// Run lint rules over the [`Binding`]s.
pub(crate) fn bindings(checker: &Checker) {
if !checker.any_rule_enabled(&[
Rule::AssignmentInAssert,
Rule::InvalidAllFormat,
Rule::InvalidAllObject,
Rule::NonAsciiName,
Rule::UnaliasedCollectionsAbcSetImport,
Rule::UnconventionalImportAlias,
Rule::UnsortedDunderSlots,
Rule::UnusedVariable,
Rule::UnquotedTypeAlias,
Rule::UsedDummyVariable,
Rule::PytestUnittestRaisesAssertion,
Rule::ForLoopWrites,
Rule::CustomTypeVarForSelf,
Rule::PrivateTypeParameter,
Rule::UnnecessaryAssign,
]) {
return;
}
for (binding_id, binding) in checker.semantic.bindings.iter_enumerated() {
if checker.is_rule_enabled(Rule::UnnecessaryAssign) {
if binding.kind.is_function_definition() {
flake8_return::rules::unnecessary_assign(
checker,
binding.statement(checker.semantic()).unwrap(),
);
}
}
if checker.is_rule_enabled(Rule::UnusedVariable) {
if binding.kind.is_bound_exception()
&& binding.is_unused()
&& !checker
.settings()
.dummy_variable_rgx
.is_match(binding.name(checker.source()))
{
checker
.report_diagnostic(
pyflakes::rules::UnusedVariable {
name: binding.name(checker.source()).to_string(),
},
binding.range(),
)
.try_set_fix(|| {
pyflakes::fixes::remove_exception_handler_assignment(
binding,
checker.locator,
)
.map(Fix::safe_edit)
});
}
}
if checker.is_rule_enabled(Rule::InvalidAllFormat) {
pylint::rules::invalid_all_format(checker, binding);
}
if checker.is_rule_enabled(Rule::InvalidAllObject) {
pylint::rules::invalid_all_object(checker, binding);
}
if checker.is_rule_enabled(Rule::NonAsciiName) {
pylint::rules::non_ascii_name(checker, binding);
}
if checker.is_rule_enabled(Rule::UnconventionalImportAlias) {
flake8_import_conventions::rules::unconventional_import_alias(
checker,
binding,
&checker.settings().flake8_import_conventions.aliases,
);
}
if checker.is_rule_enabled(Rule::UnaliasedCollectionsAbcSetImport) {
flake8_pyi::rules::unaliased_collections_abc_set_import(checker, binding);
}
if !checker.source_type.is_stub() && checker.is_rule_enabled(Rule::UnquotedTypeAlias) {
flake8_type_checking::rules::unquoted_type_alias(checker, binding);
}
if checker.is_rule_enabled(Rule::UnsortedDunderSlots) {
ruff::rules::sort_dunder_slots(checker, binding);
}
if checker.is_rule_enabled(Rule::UsedDummyVariable) {
ruff::rules::used_dummy_variable(checker, binding, binding_id);
}
if checker.is_rule_enabled(Rule::AssignmentInAssert) {
ruff::rules::assignment_in_assert(checker, binding);
}
if checker.is_rule_enabled(Rule::PytestUnittestRaisesAssertion) {
flake8_pytest_style::rules::unittest_raises_assertion_binding(checker, binding);
}
if checker.is_rule_enabled(Rule::ForLoopWrites) {
refurb::rules::for_loop_writes_binding(checker, binding);
}
if checker.is_rule_enabled(Rule::CustomTypeVarForSelf) {
flake8_pyi::rules::custom_type_var_instead_of_self(checker, binding);
}
if checker.is_rule_enabled(Rule::PrivateTypeParameter) {
pyupgrade::rules::private_type_parameter(checker, binding);
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/parameters.rs | crates/ruff_linter/src/checkers/ast/analyze/parameters.rs | use ruff_python_ast::Parameters;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_bugbear, flake8_pyi, ruff};
/// Run lint rules over a [`Parameters`] syntax node.
pub(crate) fn parameters(parameters: &Parameters, checker: &Checker) {
if checker.is_rule_enabled(Rule::FunctionCallInDefaultArgument) {
flake8_bugbear::rules::function_call_in_argument_default(checker, parameters);
}
if checker.is_rule_enabled(Rule::ImplicitOptional) {
ruff::rules::implicit_optional(checker, parameters);
}
if checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::TypedArgumentDefaultInStub) {
flake8_pyi::rules::typed_argument_simple_defaults(checker, parameters);
}
if checker.is_rule_enabled(Rule::ArgumentDefaultInStub) {
flake8_pyi::rules::argument_simple_defaults(checker, parameters);
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/string_like.rs | crates/ruff_linter/src/checkers/ast/analyze/string_like.rs | use ruff_python_ast::StringLike;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_bandit, flake8_pyi, flake8_quotes, pycodestyle, ruff};
/// Run lint rules over a [`StringLike`] syntax nodes.
pub(crate) fn string_like(string_like: StringLike, checker: &Checker) {
if checker.any_rule_enabled(&[
Rule::AmbiguousUnicodeCharacterString,
Rule::AmbiguousUnicodeCharacterDocstring,
]) {
ruff::rules::ambiguous_unicode_character_string(checker, string_like);
}
if checker.is_rule_enabled(Rule::HardcodedBindAllInterfaces) {
flake8_bandit::rules::hardcoded_bind_all_interfaces(checker, string_like);
}
if checker.is_rule_enabled(Rule::HardcodedTempFile) {
flake8_bandit::rules::hardcoded_tmp_directory(checker, string_like);
}
if checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::StringOrBytesTooLong) {
flake8_pyi::rules::string_or_bytes_too_long(checker, string_like);
}
}
if checker.any_rule_enabled(&[
Rule::BadQuotesInlineString,
Rule::BadQuotesMultilineString,
Rule::BadQuotesDocstring,
]) {
flake8_quotes::rules::check_string_quotes(checker, string_like);
}
if checker.is_rule_enabled(Rule::UnnecessaryEscapedQuote) {
flake8_quotes::rules::unnecessary_escaped_quote(checker, string_like);
}
if checker.is_rule_enabled(Rule::AvoidableEscapedQuote)
&& checker.settings().flake8_quotes.avoid_escape
{
flake8_quotes::rules::avoidable_escaped_quote(checker, string_like);
}
if checker.is_rule_enabled(Rule::InvalidEscapeSequence) {
pycodestyle::rules::invalid_escape_sequence(checker, string_like);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/suite.rs | crates/ruff_linter/src/checkers/ast/analyze/suite.rs | use ruff_python_ast::Stmt;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::refurb;
use crate::rules::{flake8_pie, flake8_pyi};
/// Run lint rules over a suite of [`Stmt`] syntax nodes.
pub(crate) fn suite(suite: &[Stmt], checker: &Checker) {
if checker.is_rule_enabled(Rule::UnnecessaryPlaceholder) {
flake8_pie::rules::unnecessary_placeholder(checker, suite);
}
if checker.source_type.is_stub() && checker.is_rule_enabled(Rule::DocstringInStub) {
flake8_pyi::rules::docstring_in_stubs(checker, suite);
}
if checker.is_rule_enabled(Rule::RepeatedGlobal) {
refurb::rules::repeated_global(checker, suite);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/deferred_lambdas.rs | crates/ruff_linter/src/checkers/ast/analyze/deferred_lambdas.rs | use ruff_python_ast::Expr;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_builtins, flake8_pie, pylint};
/// Run lint rules over all deferred lambdas in the [`SemanticModel`].
pub(crate) fn deferred_lambdas(checker: &mut Checker) {
while !checker.analyze.lambdas.is_empty() {
let lambdas = std::mem::take(&mut checker.analyze.lambdas);
for snapshot in lambdas {
checker.semantic.restore(snapshot);
let Some(Expr::Lambda(lambda)) = checker.semantic.current_expression() else {
unreachable!("Expected Expr::Lambda");
};
if checker.is_rule_enabled(Rule::UnnecessaryLambda) {
pylint::rules::unnecessary_lambda(checker, lambda);
}
if checker.is_rule_enabled(Rule::ReimplementedContainerBuiltin) {
flake8_pie::rules::reimplemented_container_builtin(checker, lambda);
}
if checker.is_rule_enabled(Rule::BuiltinLambdaArgumentShadowing) {
flake8_builtins::rules::builtin_lambda_argument_shadowing(checker, lambda);
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/module.rs | crates/ruff_linter/src/checkers/ast/analyze/module.rs | use ruff_python_ast::Suite;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_bugbear, ruff};
/// Run lint rules over a module.
pub(crate) fn module(suite: &Suite, checker: &Checker) {
if checker.is_rule_enabled(Rule::FStringDocstring) {
flake8_bugbear::rules::f_string_docstring(checker, suite);
}
if checker.is_rule_enabled(Rule::InvalidFormatterSuppressionComment) {
ruff::rules::ignored_formatter_suppression_comment(checker, suite);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs | crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs | use ruff_python_semantic::Exceptions;
use ruff_python_stdlib::builtins::version_builtin_was_added;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::pyflakes;
/// Run lint rules over all [`UnresolvedReference`] entities in the [`SemanticModel`].
pub(crate) fn unresolved_references(checker: &Checker) {
if !checker.any_rule_enabled(&[Rule::UndefinedLocalWithImportStarUsage, Rule::UndefinedName]) {
return;
}
for reference in checker.semantic.unresolved_references() {
if reference.is_wildcard_import() {
// F405
checker.report_diagnostic_if_enabled(
pyflakes::rules::UndefinedLocalWithImportStarUsage {
name: reference.name(checker.source()).to_string(),
},
reference.range(),
);
} else {
// F821
if checker.is_rule_enabled(Rule::UndefinedName) {
if checker.semantic.in_no_type_check() {
continue;
}
// Avoid flagging if `NameError` is handled.
if reference.exceptions().contains(Exceptions::NAME_ERROR) {
continue;
}
// Allow __path__.
if checker.in_init_module() {
if reference.name(checker.source()) == "__path__" {
continue;
}
}
let symbol_name = reference.name(checker.source());
checker.report_diagnostic(
pyflakes::rules::UndefinedName {
name: symbol_name.to_string(),
minor_version_builtin_added: version_builtin_was_added(symbol_name),
},
reference.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/checkers/ast/analyze/deferred_for_loops.rs | crates/ruff_linter/src/checkers/ast/analyze/deferred_for_loops.rs | use ruff_python_ast::Stmt;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_bugbear, flake8_simplify, perflint, pylint, pyupgrade, refurb};
/// Run lint rules over all deferred for-loops in the [`SemanticModel`].
pub(crate) fn deferred_for_loops(checker: &mut Checker) {
while !checker.analyze.for_loops.is_empty() {
let for_loops = std::mem::take(&mut checker.analyze.for_loops);
for snapshot in for_loops {
checker.semantic.restore(snapshot);
let Stmt::For(stmt_for) = checker.semantic.current_statement() else {
unreachable!("Expected Stmt::For");
};
if checker.is_rule_enabled(Rule::UnusedLoopControlVariable) {
flake8_bugbear::rules::unused_loop_control_variable(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::IncorrectDictIterator) {
perflint::rules::incorrect_dict_iterator(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::YieldInForLoop) {
pyupgrade::rules::yield_in_for_loop(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::UnnecessaryEnumerate) {
refurb::rules::unnecessary_enumerate(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::EnumerateForLoop) {
flake8_simplify::rules::enumerate_for_loop(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::LoopIteratorMutation) {
flake8_bugbear::rules::loop_iterator_mutation(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::DictIndexMissingItems) {
pylint::rules::dict_index_missing_items(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::ManualDictComprehension) {
perflint::rules::manual_dict_comprehension(checker, stmt_for);
}
if checker.is_rule_enabled(Rule::ManualListComprehension) {
perflint::rules::manual_list_comprehension(checker, stmt_for);
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/expression.rs | crates/ruff_linter/src/checkers/ast/analyze/expression.rs | use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Operator};
use ruff_python_literal::cformat::{CFormatError, CFormatErrorType};
use ruff_python_ast::types::Node;
use ruff_python_semantic::ScopeKind;
use ruff_python_semantic::analyze::typing;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::preview::{
is_future_required_preview_generics_enabled, is_optional_as_none_in_union_enabled,
is_unnecessary_default_type_args_stubs_enabled,
};
use crate::registry::Rule;
use crate::rules::{
airflow, flake8_2020, flake8_async, flake8_bandit, flake8_boolean_trap, flake8_bugbear,
flake8_builtins, flake8_comprehensions, flake8_datetimez, flake8_debugger, flake8_django,
flake8_future_annotations, flake8_gettext, flake8_implicit_str_concat, flake8_logging,
flake8_logging_format, flake8_pie, flake8_print, flake8_pyi, flake8_pytest_style, flake8_self,
flake8_simplify, flake8_tidy_imports, flake8_type_checking, flake8_use_pathlib, flynt, numpy,
pandas_vet, pep8_naming, pycodestyle, pyflakes, pylint, pyupgrade, refurb, ruff,
};
use ruff_python_ast::PythonVersion;
/// Run lint rules over an [`Expr`] syntax node.
pub(crate) fn expression(expr: &Expr, checker: &Checker) {
match expr {
Expr::Subscript(subscript @ ast::ExprSubscript { value, slice, .. }) => {
// Ex) Optional[...], Union[...]
if checker.any_rule_enabled(&[
Rule::FutureRewritableTypeAnnotation,
Rule::NonPEP604AnnotationUnion,
Rule::NonPEP604AnnotationOptional,
]) {
if let Some(operator) = typing::to_pep604_operator(value, slice, &checker.semantic)
{
if checker.is_rule_enabled(Rule::FutureRewritableTypeAnnotation) {
if !checker.semantic.future_annotations_or_stub()
&& checker.target_version() < PythonVersion::PY310
&& checker.target_version() >= PythonVersion::PY37
&& checker.semantic.in_annotation()
&& !checker.settings().pyupgrade.keep_runtime_typing
{
flake8_future_annotations::rules::future_rewritable_type_annotation(
checker, value,
);
}
}
if checker.any_rule_enabled(&[
Rule::NonPEP604AnnotationUnion,
Rule::NonPEP604AnnotationOptional,
]) {
if checker.source_type.is_stub()
|| checker.target_version() >= PythonVersion::PY310
|| (checker.target_version() >= PythonVersion::PY37
&& checker.semantic.future_annotations_or_stub()
&& checker.semantic.in_annotation()
&& !checker.settings().pyupgrade.keep_runtime_typing)
{
pyupgrade::rules::non_pep604_annotation(checker, expr, slice, operator);
}
}
}
}
// Ex) list[...]
if checker.is_rule_enabled(Rule::FutureRequiredTypeAnnotation) {
if !checker.semantic.future_annotations_or_stub()
&& checker.target_version() < PythonVersion::PY39
&& checker.semantic.in_annotation()
&& checker.semantic.in_runtime_evaluated_annotation()
&& !checker.semantic.in_string_type_definition()
&& typing::is_pep585_generic(
value,
&checker.semantic,
is_future_required_preview_generics_enabled(checker.settings()),
)
{
flake8_future_annotations::rules::future_required_type_annotation(
checker,
expr,
flake8_future_annotations::rules::Reason::PEP585,
);
}
}
// Ex) Union[...]
if checker.any_rule_enabled(&[
Rule::UnnecessaryLiteralUnion,
Rule::DuplicateUnionMember,
Rule::RedundantLiteralUnion,
Rule::UnnecessaryTypeUnion,
Rule::NoneNotAtEndOfUnion,
]) {
// Avoid duplicate checks if the parent is a union, since these rules already
// traverse nested unions.
if !checker.semantic.in_nested_union() {
if checker.is_rule_enabled(Rule::UnnecessaryLiteralUnion) {
flake8_pyi::rules::unnecessary_literal_union(checker, expr);
}
if checker.is_rule_enabled(Rule::DuplicateUnionMember)
// Avoid duplicate checks inside `Optional`
&& !(
is_optional_as_none_in_union_enabled(checker.settings())
&& checker.semantic.inside_optional()
)
{
flake8_pyi::rules::duplicate_union_member(checker, expr);
}
if checker.is_rule_enabled(Rule::RedundantLiteralUnion) {
flake8_pyi::rules::redundant_literal_union(checker, expr);
}
if checker.is_rule_enabled(Rule::UnnecessaryTypeUnion) {
flake8_pyi::rules::unnecessary_type_union(checker, expr);
}
if checker.is_rule_enabled(Rule::NoneNotAtEndOfUnion) {
ruff::rules::none_not_at_end_of_union(checker, expr);
}
}
}
// Ex) Literal[...]
if checker.any_rule_enabled(&[
Rule::DuplicateLiteralMember,
Rule::RedundantBoolLiteral,
Rule::RedundantNoneLiteral,
Rule::UnnecessaryNestedLiteral,
]) {
if !checker.semantic.in_nested_literal() {
if checker.is_rule_enabled(Rule::DuplicateLiteralMember) {
flake8_pyi::rules::duplicate_literal_member(checker, expr);
}
if checker.is_rule_enabled(Rule::RedundantBoolLiteral) {
ruff::rules::redundant_bool_literal(checker, expr);
}
if checker.is_rule_enabled(Rule::RedundantNoneLiteral) {
flake8_pyi::rules::redundant_none_literal(checker, expr);
}
if checker.is_rule_enabled(Rule::UnnecessaryNestedLiteral) {
ruff::rules::unnecessary_nested_literal(checker, expr);
}
}
}
if checker.is_rule_enabled(Rule::NeverUnion) {
ruff::rules::never_union(checker, expr);
}
if checker.is_rule_enabled(Rule::UnnecessaryDefaultTypeArgs) {
if checker.target_version() >= PythonVersion::PY313
|| is_unnecessary_default_type_args_stubs_enabled(checker.settings())
&& checker.semantic().in_stub_file()
{
pyupgrade::rules::unnecessary_default_type_args(checker, expr);
}
}
if checker.any_rule_enabled(&[
Rule::SysVersionSlice3,
Rule::SysVersion2,
Rule::SysVersion0,
Rule::SysVersionSlice1,
]) {
flake8_2020::rules::subscript(checker, value, slice);
}
if checker.is_rule_enabled(Rule::UncapitalizedEnvironmentVariables) {
flake8_simplify::rules::use_capital_environment_variables(checker, expr);
}
if checker.is_rule_enabled(Rule::UnnecessaryIterableAllocationForFirstElement) {
ruff::rules::unnecessary_iterable_allocation_for_first_element(checker, expr);
}
if checker.is_rule_enabled(Rule::InvalidIndexType) {
ruff::rules::invalid_index_type(checker, subscript);
}
if checker.is_rule_enabled(Rule::SliceCopy) {
refurb::rules::slice_copy(checker, subscript);
}
if checker.is_rule_enabled(Rule::PotentialIndexError) {
pylint::rules::potential_index_error(checker, value, slice);
}
if checker.is_rule_enabled(Rule::SortedMinMax) {
refurb::rules::sorted_min_max(checker, subscript);
}
if checker.is_rule_enabled(Rule::FStringNumberFormat) {
refurb::rules::fstring_number_format(checker, subscript);
}
if checker.is_rule_enabled(Rule::IncorrectlyParenthesizedTupleInSubscript) {
ruff::rules::subscript_with_parenthesized_tuple(checker, subscript);
}
if checker.is_rule_enabled(Rule::NonPEP646Unpack) {
pyupgrade::rules::use_pep646_unpack(checker, subscript);
}
if checker.is_rule_enabled(Rule::Airflow3Removal) {
airflow::rules::airflow_3_removal_expr(checker, expr);
}
if checker.is_rule_enabled(Rule::MissingMaxsplitArg) {
pylint::rules::missing_maxsplit_arg(checker, value, slice, expr);
}
if checker.is_rule_enabled(Rule::AccessAnnotationsFromClassDict) {
ruff::rules::access_annotations_from_class_dict_by_key(checker, subscript);
}
pandas_vet::rules::subscript(checker, value, expr);
}
Expr::Tuple(ast::ExprTuple {
elts,
ctx,
range: _,
node_index: _,
parenthesized: _,
})
| Expr::List(ast::ExprList {
elts,
ctx,
range: _,
node_index: _,
}) => {
if checker.is_rule_enabled(Rule::ImplicitStringConcatenationInCollectionLiteral) {
flake8_implicit_str_concat::rules::implicit_string_concatenation_in_collection_literal(
checker,
expr,
elts,
);
}
if ctx.is_store() {
let check_too_many_expressions =
checker.is_rule_enabled(Rule::ExpressionsInStarAssignment);
pyflakes::rules::starred_expressions(
checker,
elts,
check_too_many_expressions,
expr.range(),
);
}
}
Expr::Name(ast::ExprName {
id,
ctx,
range,
node_index: _,
}) => {
match ctx {
ExprContext::Load => {
if checker.is_rule_enabled(Rule::TypingTextStrAlias) {
pyupgrade::rules::typing_text_str_alias(checker, expr);
}
if checker.is_rule_enabled(Rule::NumpyDeprecatedTypeAlias) {
numpy::rules::deprecated_type_alias(checker, expr);
}
if checker.is_rule_enabled(Rule::NumpyDeprecatedFunction) {
numpy::rules::deprecated_function(checker, expr);
}
if checker.is_rule_enabled(Rule::Numpy2Deprecation) {
numpy::rules::numpy_2_0_deprecation(checker, expr);
}
if checker.is_rule_enabled(Rule::CollectionsNamedTuple) {
flake8_pyi::rules::collections_named_tuple(checker, expr);
}
if checker.is_rule_enabled(Rule::RegexFlagAlias) {
refurb::rules::regex_flag_alias(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3Removal) {
airflow::rules::airflow_3_removal_expr(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3SuggestedUpdate) {
airflow::rules::airflow_3_0_suggested_update_expr(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3MovedToProvider) {
airflow::rules::moved_to_provider_in_3(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3SuggestedToMoveToProvider) {
airflow::rules::suggested_to_move_to_provider_in_3(checker, expr);
}
if checker.any_rule_enabled(&[
Rule::SuspiciousPickleUsage,
Rule::SuspiciousMarshalUsage,
Rule::SuspiciousInsecureHashUsage,
Rule::SuspiciousInsecureCipherUsage,
Rule::SuspiciousInsecureCipherModeUsage,
Rule::SuspiciousMktempUsage,
Rule::SuspiciousEvalUsage,
Rule::SuspiciousMarkSafeUsage,
Rule::SuspiciousURLOpenUsage,
Rule::SuspiciousNonCryptographicRandomUsage,
Rule::SuspiciousTelnetUsage,
Rule::SuspiciousXMLCElementTreeUsage,
Rule::SuspiciousXMLElementTreeUsage,
Rule::SuspiciousXMLExpatReaderUsage,
Rule::SuspiciousXMLExpatBuilderUsage,
Rule::SuspiciousXMLSaxUsage,
Rule::SuspiciousXMLMiniDOMUsage,
Rule::SuspiciousXMLPullDOMUsage,
Rule::SuspiciousXMLETreeUsage,
Rule::SuspiciousFTPLibUsage,
Rule::SuspiciousUnverifiedContextUsage,
]) {
flake8_bandit::rules::suspicious_function_reference(checker, expr);
}
// Ex) List[...]
if checker.any_rule_enabled(&[
Rule::FutureRewritableTypeAnnotation,
Rule::NonPEP585Annotation,
]) {
if let Some(replacement) =
typing::to_pep585_generic(expr, &checker.semantic)
{
if checker.is_rule_enabled(Rule::FutureRewritableTypeAnnotation) {
if !checker.semantic.future_annotations_or_stub()
&& checker.target_version() < PythonVersion::PY39
&& checker.target_version() >= PythonVersion::PY37
&& checker.semantic.in_annotation()
&& !checker.settings().pyupgrade.keep_runtime_typing
{
flake8_future_annotations::rules::future_rewritable_type_annotation(checker, expr);
}
}
if checker.is_rule_enabled(Rule::NonPEP585Annotation) {
if checker.source_type.is_stub()
|| checker.target_version() >= PythonVersion::PY39
|| (checker.target_version() >= PythonVersion::PY37
&& checker.semantic.future_annotations_or_stub()
&& checker.semantic.in_annotation()
&& !checker.settings().pyupgrade.keep_runtime_typing)
{
pyupgrade::rules::use_pep585_annotation(
checker,
expr,
&replacement,
);
}
}
}
}
}
ExprContext::Store => {
if checker.is_rule_enabled(Rule::NonLowercaseVariableInFunction) {
if checker.semantic.current_scope().kind.is_function() {
pep8_naming::rules::non_lowercase_variable_in_function(
checker, expr, id,
);
}
}
if checker.is_rule_enabled(Rule::MixedCaseVariableInClassScope) {
if let ScopeKind::Class(class_def) = &checker.semantic.current_scope().kind
{
pep8_naming::rules::mixed_case_variable_in_class_scope(
checker, expr, id, class_def,
);
}
}
if checker.is_rule_enabled(Rule::Airflow3Removal) {
airflow::rules::airflow_3_removal_expr(checker, expr);
}
if checker.is_rule_enabled(Rule::MixedCaseVariableInGlobalScope) {
if matches!(checker.semantic.current_scope().kind, ScopeKind::Module) {
pep8_naming::rules::mixed_case_variable_in_global_scope(
checker, expr, id,
);
}
}
if checker.is_rule_enabled(Rule::AmbiguousVariableName) {
pycodestyle::rules::ambiguous_variable_name(checker, id, expr.range());
}
if !checker.semantic.current_scope().kind.is_class() {
if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(checker, id, *range);
}
}
}
_ => {}
}
if checker.is_rule_enabled(Rule::SixPY3) {
flake8_2020::rules::name_or_attribute(checker, expr);
}
if checker.is_rule_enabled(Rule::UndocumentedWarn) {
flake8_logging::rules::undocumented_warn(checker, expr);
}
}
Expr::Attribute(attribute) => {
if attribute.ctx == ExprContext::Load {
if checker.any_rule_enabled(&[
Rule::SuspiciousPickleUsage,
Rule::SuspiciousMarshalUsage,
Rule::SuspiciousInsecureHashUsage,
Rule::SuspiciousInsecureCipherUsage,
Rule::SuspiciousInsecureCipherModeUsage,
Rule::SuspiciousMktempUsage,
Rule::SuspiciousEvalUsage,
Rule::SuspiciousMarkSafeUsage,
Rule::SuspiciousURLOpenUsage,
Rule::SuspiciousNonCryptographicRandomUsage,
Rule::SuspiciousTelnetUsage,
Rule::SuspiciousXMLCElementTreeUsage,
Rule::SuspiciousXMLElementTreeUsage,
Rule::SuspiciousXMLExpatReaderUsage,
Rule::SuspiciousXMLExpatBuilderUsage,
Rule::SuspiciousXMLSaxUsage,
Rule::SuspiciousXMLMiniDOMUsage,
Rule::SuspiciousXMLPullDOMUsage,
Rule::SuspiciousXMLETreeUsage,
Rule::SuspiciousFTPLibUsage,
Rule::SuspiciousUnverifiedContextUsage,
]) {
flake8_bandit::rules::suspicious_function_reference(checker, expr);
}
}
// Ex) typing.List[...]
if checker.any_rule_enabled(&[
Rule::FutureRewritableTypeAnnotation,
Rule::NonPEP585Annotation,
]) {
if let Some(replacement) = typing::to_pep585_generic(expr, &checker.semantic) {
if checker.is_rule_enabled(Rule::FutureRewritableTypeAnnotation) {
if !checker.semantic.future_annotations_or_stub()
&& checker.target_version() < PythonVersion::PY39
&& checker.target_version() >= PythonVersion::PY37
&& checker.semantic.in_annotation()
&& !checker.settings().pyupgrade.keep_runtime_typing
{
flake8_future_annotations::rules::future_rewritable_type_annotation(
checker, expr,
);
}
}
if checker.is_rule_enabled(Rule::NonPEP585Annotation) {
if checker.source_type.is_stub()
|| checker.target_version() >= PythonVersion::PY39
|| (checker.target_version() >= PythonVersion::PY37
&& checker.semantic.future_annotations_or_stub()
&& checker.semantic.in_annotation()
&& !checker.settings().pyupgrade.keep_runtime_typing)
{
pyupgrade::rules::use_pep585_annotation(checker, expr, &replacement);
}
}
}
}
if checker.is_rule_enabled(Rule::RegexFlagAlias) {
refurb::rules::regex_flag_alias(checker, expr);
}
if checker.is_rule_enabled(Rule::DatetimeTimezoneUTC) {
if checker.target_version() >= PythonVersion::PY311 {
pyupgrade::rules::datetime_utc_alias(checker, expr);
}
}
if checker.is_rule_enabled(Rule::TypingTextStrAlias) {
pyupgrade::rules::typing_text_str_alias(checker, expr);
}
if checker.is_rule_enabled(Rule::NumpyDeprecatedTypeAlias) {
numpy::rules::deprecated_type_alias(checker, expr);
}
if checker.is_rule_enabled(Rule::NumpyDeprecatedFunction) {
numpy::rules::deprecated_function(checker, expr);
}
if checker.is_rule_enabled(Rule::Numpy2Deprecation) {
numpy::rules::numpy_2_0_deprecation(checker, expr);
}
if checker.is_rule_enabled(Rule::DeprecatedMockImport) {
pyupgrade::rules::deprecated_mock_attribute(checker, attribute);
}
if checker.is_rule_enabled(Rule::SixPY3) {
flake8_2020::rules::name_or_attribute(checker, expr);
}
if checker.is_rule_enabled(Rule::DatetimeMinMax) {
flake8_datetimez::rules::datetime_min_max(checker, expr);
}
if checker.is_rule_enabled(Rule::BannedApi) {
flake8_tidy_imports::rules::banned_attribute_access(checker, expr);
}
if checker.is_rule_enabled(Rule::PrivateMemberAccess) {
flake8_self::rules::private_member_access(checker, expr);
}
if checker.is_rule_enabled(Rule::CollectionsNamedTuple) {
flake8_pyi::rules::collections_named_tuple(checker, expr);
}
if checker.is_rule_enabled(Rule::UndocumentedWarn) {
flake8_logging::rules::undocumented_warn(checker, expr);
}
if checker.is_rule_enabled(Rule::PandasUseOfDotValues) {
pandas_vet::rules::attr(checker, attribute);
}
if checker.is_rule_enabled(Rule::ByteStringUsage) {
flake8_pyi::rules::bytestring_attribute(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3Removal) {
airflow::rules::airflow_3_removal_expr(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3SuggestedUpdate) {
airflow::rules::airflow_3_0_suggested_update_expr(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3MovedToProvider) {
airflow::rules::moved_to_provider_in_3(checker, expr);
}
if checker.is_rule_enabled(Rule::Airflow3SuggestedToMoveToProvider) {
airflow::rules::suggested_to_move_to_provider_in_3(checker, expr);
}
}
Expr::Call(
call @ ast::ExprCall {
func,
arguments:
Arguments {
args,
keywords,
range: _,
node_index: _,
},
range: _,
node_index: _,
},
) => {
if checker.any_rule_enabled(&[
// pylint
Rule::BadStringFormatCharacter,
// pyflakes
Rule::StringDotFormatInvalidFormat,
Rule::StringDotFormatExtraNamedArguments,
Rule::StringDotFormatExtraPositionalArguments,
Rule::StringDotFormatMissingArguments,
Rule::StringDotFormatMixingAutomatic,
// pyupgrade
Rule::FormatLiterals,
Rule::FString,
// flynt
Rule::StaticJoinToFString,
// refurb
Rule::HashlibDigestHex,
// flake8-simplify
Rule::SplitStaticString,
]) {
if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() {
let attr = attr.as_str();
if let Expr::StringLiteral(ast::ExprStringLiteral {
value: string_value,
..
}) = value.as_ref()
{
if attr == "join" {
// "...".join(...) call
if checker.is_rule_enabled(Rule::StaticJoinToFString) {
flynt::rules::static_join_to_fstring(
checker,
expr,
string_value.to_str(),
);
}
} else if matches!(attr, "split" | "rsplit") {
// "...".split(...) call
if checker.is_rule_enabled(Rule::SplitStaticString) {
flake8_simplify::rules::split_static_string(
checker,
attr,
call,
string_value,
);
}
} else if attr == "format" {
// "...".format(...) call
let location = expr.range();
match pyflakes::format::FormatSummary::try_from(string_value.to_str()) {
Err(e) => {
// F521
checker.report_diagnostic_if_enabled(
pyflakes::rules::StringDotFormatInvalidFormat {
message: pyflakes::format::error_to_string(&e),
},
location,
);
}
Ok(summary) => {
if checker
.is_rule_enabled(Rule::StringDotFormatExtraNamedArguments)
{
pyflakes::rules::string_dot_format_extra_named_arguments(
checker, call, &summary, keywords,
);
}
if checker.is_rule_enabled(
Rule::StringDotFormatExtraPositionalArguments,
) {
pyflakes::rules::string_dot_format_extra_positional_arguments(
checker, call, &summary, args,
);
}
if checker
.is_rule_enabled(Rule::StringDotFormatMissingArguments)
{
pyflakes::rules::string_dot_format_missing_argument(
checker, call, &summary, args, keywords,
);
}
if checker.is_rule_enabled(Rule::StringDotFormatMixingAutomatic)
{
pyflakes::rules::string_dot_format_mixing_automatic(
checker, call, &summary,
);
}
if checker.is_rule_enabled(Rule::FormatLiterals) {
pyupgrade::rules::format_literals(checker, call, &summary);
}
if checker.is_rule_enabled(Rule::FString) {
pyupgrade::rules::f_strings(checker, call, &summary);
}
}
}
if checker.is_rule_enabled(Rule::BadStringFormatCharacter) {
pylint::rules::bad_string_format_character::call(
checker,
string_value.to_str(),
location,
);
}
}
}
}
}
if checker.is_rule_enabled(Rule::SuperWithoutBrackets) {
pylint::rules::super_without_brackets(checker, func);
}
if checker.is_rule_enabled(Rule::LenTest) {
pylint::rules::len_test(checker, call);
}
if checker.is_rule_enabled(Rule::BitCount) {
refurb::rules::bit_count(checker, call);
}
if checker.is_rule_enabled(Rule::TypeOfPrimitive) {
pyupgrade::rules::type_of_primitive(checker, expr, func, args);
}
if checker.is_rule_enabled(Rule::DeprecatedUnittestAlias) {
pyupgrade::rules::deprecated_unittest_alias(checker, func);
}
if checker.is_rule_enabled(Rule::SuperCallWithParameters) {
pyupgrade::rules::super_call_with_parameters(checker, call);
}
if checker.is_rule_enabled(Rule::UnnecessaryEncodeUTF8) {
pyupgrade::rules::unnecessary_encode_utf8(checker, call);
}
if checker.is_rule_enabled(Rule::RedundantOpenModes) {
pyupgrade::rules::redundant_open_modes(checker, call);
}
if checker.is_rule_enabled(Rule::NativeLiterals) {
pyupgrade::rules::native_literals(
checker,
call,
checker.semantic().current_expression_parent(),
);
}
if checker.is_rule_enabled(Rule::OpenAlias) {
pyupgrade::rules::open_alias(checker, expr, func);
}
if checker.is_rule_enabled(Rule::ReplaceUniversalNewlines) {
pyupgrade::rules::replace_universal_newlines(checker, call);
}
| 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/checkers/ast/analyze/mod.rs | crates/ruff_linter/src/checkers/ast/analyze/mod.rs | pub(super) use bindings::bindings;
pub(super) use comprehension::comprehension;
pub(super) use deferred_for_loops::deferred_for_loops;
pub(super) use deferred_lambdas::deferred_lambdas;
pub(super) use deferred_scopes::deferred_scopes;
pub(super) use definitions::definitions;
pub(super) use except_handler::except_handler;
pub(super) use expression::expression;
pub(super) use module::module;
pub(super) use parameter::parameter;
pub(super) use parameters::parameters;
pub(super) use statement::statement;
pub(super) use string_like::string_like;
pub(super) use suite::suite;
pub(super) use unresolved_references::unresolved_references;
mod bindings;
mod comprehension;
mod deferred_for_loops;
mod deferred_lambdas;
mod deferred_scopes;
mod definitions;
mod except_handler;
mod expression;
mod module;
mod parameter;
mod parameters;
mod statement;
mod string_like;
mod suite;
mod unresolved_references;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/statement.rs | crates/ruff_linter/src/checkers/ast/analyze/statement.rs | use ruff_python_ast::helpers;
use ruff_python_ast::types::Node;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::rules::{
airflow, fastapi, flake8_async, flake8_bandit, flake8_boolean_trap, flake8_bugbear,
flake8_builtins, flake8_debugger, flake8_django, flake8_errmsg, flake8_import_conventions,
flake8_pie, flake8_pyi, flake8_pytest_style, flake8_raise, flake8_return, flake8_simplify,
flake8_slots, flake8_tidy_imports, flake8_type_checking, mccabe, pandas_vet, pep8_naming,
perflint, pycodestyle, pyflakes, pygrep_hooks, pylint, pyupgrade, refurb, ruff, tryceratops,
};
use ruff_python_ast::PythonVersion;
/// Run lint rules over a [`Stmt`] syntax node.
pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
match stmt {
Stmt::Global(ast::StmtGlobal {
names,
range: _,
node_index: _,
}) => {
if checker.is_rule_enabled(Rule::GlobalAtModuleLevel) {
pylint::rules::global_at_module_level(checker, stmt);
}
if checker.is_rule_enabled(Rule::AmbiguousVariableName) {
for name in names {
pycodestyle::rules::ambiguous_variable_name(checker, name, name.range());
}
}
}
Stmt::Nonlocal(
nonlocal @ ast::StmtNonlocal {
names,
range: _,
node_index: _,
},
) => {
if checker.is_rule_enabled(Rule::AmbiguousVariableName) {
for name in names {
pycodestyle::rules::ambiguous_variable_name(checker, name, name.range());
}
}
if checker.is_rule_enabled(Rule::NonlocalAndGlobal) {
pylint::rules::nonlocal_and_global(checker, nonlocal);
}
}
Stmt::FunctionDef(
function_def @ ast::StmtFunctionDef {
is_async,
name,
decorator_list,
returns,
parameters,
body,
type_params: _,
range: _,
node_index: _,
},
) => {
if checker.is_rule_enabled(Rule::DjangoNonLeadingReceiverDecorator) {
flake8_django::rules::non_leading_receiver_decorator(checker, decorator_list);
}
if checker.is_rule_enabled(Rule::FastApiRedundantResponseModel) {
fastapi::rules::fastapi_redundant_response_model(checker, function_def);
}
if checker.is_rule_enabled(Rule::FastApiNonAnnotatedDependency) {
fastapi::rules::fastapi_non_annotated_dependency(checker, function_def);
}
if checker.is_rule_enabled(Rule::FastApiUnusedPathParameter) {
fastapi::rules::fastapi_unused_path_parameter(checker, function_def);
}
if checker.is_rule_enabled(Rule::AmbiguousFunctionName) {
pycodestyle::rules::ambiguous_function_name(checker, name);
}
if checker.is_rule_enabled(Rule::InvalidBoolReturnType) {
pylint::rules::invalid_bool_return(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidLengthReturnType) {
pylint::rules::invalid_length_return(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidBytesReturnType) {
pylint::rules::invalid_bytes_return(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidIndexReturnType) {
pylint::rules::invalid_index_return(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidHashReturnType) {
pylint::rules::invalid_hash_return(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidStrReturnType) {
pylint::rules::invalid_str_return(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidFunctionName) {
pep8_naming::rules::invalid_function_name(
checker,
stmt,
name,
decorator_list,
&checker.settings().pep8_naming.ignore_names,
&checker.semantic,
);
}
if checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::PassStatementStubBody) {
flake8_pyi::rules::pass_statement_stub_body(checker, body);
}
if checker.is_rule_enabled(Rule::NonEmptyStubBody) {
flake8_pyi::rules::non_empty_stub_body(checker, body);
}
if checker.is_rule_enabled(Rule::StubBodyMultipleStatements) {
flake8_pyi::rules::stub_body_multiple_statements(checker, stmt, body);
}
}
if checker.is_rule_enabled(Rule::AnyEqNeAnnotation) {
flake8_pyi::rules::any_eq_ne_annotation(checker, name, parameters);
}
if checker.is_rule_enabled(Rule::NonSelfReturnType) {
flake8_pyi::rules::non_self_return_type(
checker,
stmt,
*is_async,
name,
decorator_list,
returns.as_ref().map(AsRef::as_ref),
parameters,
);
}
if checker.is_rule_enabled(Rule::GeneratorReturnFromIterMethod) {
flake8_pyi::rules::bad_generator_return_type(function_def, checker);
}
if checker.is_rule_enabled(Rule::StopIterationReturn) {
pylint::rules::stop_iteration_return(checker, function_def);
}
if checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::StrOrReprDefinedInStub) {
flake8_pyi::rules::str_or_repr_defined_in_stub(checker, stmt);
}
}
if checker.source_type.is_stub() || checker.target_version() >= PythonVersion::PY311 {
if checker.is_rule_enabled(Rule::NoReturnArgumentAnnotationInStub) {
flake8_pyi::rules::no_return_argument_annotation(checker, parameters);
}
}
if checker.is_rule_enabled(Rule::BadExitAnnotation) {
flake8_pyi::rules::bad_exit_annotation(checker, function_def);
}
if checker.is_rule_enabled(Rule::RedundantNumericUnion) {
flake8_pyi::rules::redundant_numeric_union(checker, parameters);
}
if checker.is_rule_enabled(Rule::Pep484StylePositionalOnlyParameter) {
flake8_pyi::rules::pep_484_positional_parameter(checker, function_def);
}
if checker.is_rule_enabled(Rule::DunderFunctionName) {
pep8_naming::rules::dunder_function_name(
checker,
checker.semantic.current_scope(),
stmt,
name,
&checker.settings().pep8_naming.ignore_names,
);
}
if checker.is_rule_enabled(Rule::GlobalStatement) {
pylint::rules::global_statement(checker, name);
}
if checker.is_rule_enabled(Rule::LRUCacheWithoutParameters) {
if checker.target_version() >= PythonVersion::PY38 {
pyupgrade::rules::lru_cache_without_parameters(checker, decorator_list);
}
}
if checker.is_rule_enabled(Rule::LRUCacheWithMaxsizeNone) {
if checker.target_version() >= PythonVersion::PY39 {
pyupgrade::rules::lru_cache_with_maxsize_none(checker, decorator_list);
}
}
if checker.is_rule_enabled(Rule::CachedInstanceMethod) {
flake8_bugbear::rules::cached_instance_method(checker, function_def);
}
if checker.is_rule_enabled(Rule::MutableArgumentDefault) {
flake8_bugbear::rules::mutable_argument_default(checker, function_def);
}
if checker.is_rule_enabled(Rule::ReturnInGenerator) {
flake8_bugbear::rules::return_in_generator(checker, function_def);
}
if checker.any_rule_enabled(&[
Rule::UnnecessaryReturnNone,
Rule::ImplicitReturnValue,
Rule::ImplicitReturn,
Rule::SuperfluousElseReturn,
Rule::SuperfluousElseRaise,
Rule::SuperfluousElseContinue,
Rule::SuperfluousElseBreak,
]) {
flake8_return::rules::function(checker, function_def);
}
if checker.is_rule_enabled(Rule::UselessReturn) {
pylint::rules::useless_return(
checker,
stmt,
body,
returns.as_ref().map(AsRef::as_ref),
);
}
if checker.is_rule_enabled(Rule::ComplexStructure) {
mccabe::rules::function_is_too_complex(
checker,
stmt,
name,
body,
checker.settings().mccabe.max_complexity,
);
}
if checker.is_rule_enabled(Rule::HardcodedPasswordDefault) {
flake8_bandit::rules::hardcoded_password_default(checker, parameters);
}
if checker.is_rule_enabled(Rule::SuspiciousMarkSafeUsage) {
for decorator in decorator_list {
flake8_bandit::rules::suspicious_function_decorator(checker, decorator);
}
}
if checker.is_rule_enabled(Rule::PropertyWithParameters) {
pylint::rules::property_with_parameters(checker, stmt, decorator_list, parameters);
}
if checker.is_rule_enabled(Rule::TooManyArguments) {
pylint::rules::too_many_arguments(checker, function_def);
}
if checker.is_rule_enabled(Rule::TooManyPositionalArguments) {
pylint::rules::too_many_positional_arguments(checker, function_def);
}
if checker.is_rule_enabled(Rule::TooManyReturnStatements) {
pylint::rules::too_many_return_statements(
checker,
stmt,
body,
checker.settings().pylint.max_returns,
);
}
if checker.is_rule_enabled(Rule::TooManyBranches) {
pylint::rules::too_many_branches(
checker,
stmt,
body,
checker.settings().pylint.max_branches,
);
}
if checker.is_rule_enabled(Rule::TooManyStatements) {
pylint::rules::too_many_statements(
checker,
stmt,
body,
checker.settings().pylint.max_statements,
);
}
if checker.any_rule_enabled(&[
Rule::PytestFixtureIncorrectParenthesesStyle,
Rule::PytestFixturePositionalArgs,
Rule::PytestExtraneousScopeFunction,
Rule::PytestFixtureParamWithoutValue,
Rule::PytestDeprecatedYieldFixture,
Rule::PytestFixtureFinalizerCallback,
Rule::PytestUselessYieldFixture,
Rule::PytestUnnecessaryAsyncioMarkOnFixture,
Rule::PytestErroneousUseFixturesOnFixture,
]) {
flake8_pytest_style::rules::fixture(
checker,
name,
parameters,
returns.as_deref(),
decorator_list,
body,
);
}
if checker.any_rule_enabled(&[
Rule::PytestIncorrectMarkParenthesesStyle,
Rule::PytestUseFixturesWithoutParameters,
]) {
flake8_pytest_style::rules::marks(checker, decorator_list);
}
if checker.is_rule_enabled(Rule::BooleanTypeHintPositionalArgument) {
flake8_boolean_trap::rules::boolean_type_hint_positional_argument(
checker,
name,
decorator_list,
parameters,
);
}
if checker.is_rule_enabled(Rule::BooleanDefaultValuePositionalArgument) {
flake8_boolean_trap::rules::boolean_default_value_positional_argument(
checker,
name,
decorator_list,
parameters,
);
}
if checker.is_rule_enabled(Rule::UnexpectedSpecialMethodSignature) {
pylint::rules::unexpected_special_method_signature(
checker,
stmt,
name,
decorator_list,
parameters,
);
}
if checker.is_rule_enabled(Rule::FStringDocstring) {
flake8_bugbear::rules::f_string_docstring(checker, body);
}
if !checker.semantic.current_scope().kind.is_class() {
if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(checker, name, name.range());
}
}
if checker.is_rule_enabled(Rule::AsyncFunctionWithTimeout) {
flake8_async::rules::async_function_with_timeout(checker, function_def);
}
#[cfg(any(feature = "test-rules", test))]
if checker.is_rule_enabled(Rule::UnreachableCode) {
pylint::rules::in_function(checker, name, body);
}
if checker.is_rule_enabled(Rule::ReimplementedOperator) {
refurb::rules::reimplemented_operator(checker, &function_def.into());
}
if checker.is_rule_enabled(Rule::SslWithBadDefaults) {
flake8_bandit::rules::ssl_with_bad_defaults(checker, function_def);
}
if checker.is_rule_enabled(Rule::UnusedAsync) {
ruff::rules::unused_async(checker, function_def);
}
if checker.is_rule_enabled(Rule::WhitespaceAfterDecorator) {
pycodestyle::rules::whitespace_after_decorator(checker, decorator_list);
}
if checker.is_rule_enabled(Rule::PostInitDefault) {
ruff::rules::post_init_default(checker, function_def);
}
if checker.is_rule_enabled(Rule::PytestParameterWithDefaultArgument) {
flake8_pytest_style::rules::parameter_with_default_argument(checker, function_def);
}
if checker.is_rule_enabled(Rule::Airflow3Removal) {
airflow::rules::airflow_3_removal_function_def(checker, function_def);
}
if checker.is_rule_enabled(Rule::NonPEP695GenericFunction) {
pyupgrade::rules::non_pep695_generic_function(checker, function_def);
}
if checker.is_rule_enabled(Rule::InvalidArgumentName) {
pep8_naming::rules::invalid_argument_name_function(checker, function_def);
}
if checker.is_rule_enabled(Rule::PropertyWithoutReturn) {
ruff::rules::property_without_return(checker, function_def);
}
}
Stmt::Return(_) => {
if checker.is_rule_enabled(Rule::ReturnInInit) {
pylint::rules::return_in_init(checker, stmt);
}
}
Stmt::ClassDef(
class_def @ ast::StmtClassDef {
name,
arguments,
type_params: _,
decorator_list,
body,
range: _,
node_index: _,
},
) => {
if checker.is_rule_enabled(Rule::NoClassmethodDecorator) {
pylint::rules::no_classmethod_decorator(checker, stmt);
}
if checker.is_rule_enabled(Rule::NoStaticmethodDecorator) {
pylint::rules::no_staticmethod_decorator(checker, stmt);
}
if checker.is_rule_enabled(Rule::DjangoNullableModelStringField) {
flake8_django::rules::nullable_model_string_field(checker, body);
}
if checker.is_rule_enabled(Rule::DjangoExcludeWithModelForm) {
flake8_django::rules::exclude_with_model_form(checker, class_def);
}
if checker.is_rule_enabled(Rule::DjangoAllWithModelForm) {
flake8_django::rules::all_with_model_form(checker, class_def);
}
if checker.is_rule_enabled(Rule::DjangoUnorderedBodyContentInModel) {
flake8_django::rules::unordered_body_content_in_model(checker, class_def);
}
if !checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::DjangoModelWithoutDunderStr) {
flake8_django::rules::model_without_dunder_str(checker, class_def);
}
}
if checker.is_rule_enabled(Rule::EqWithoutHash) {
pylint::rules::object_without_hash_method(checker, class_def);
}
if checker.is_rule_enabled(Rule::ClassAsDataStructure) {
flake8_bugbear::rules::class_as_data_structure(checker, class_def);
}
if checker.is_rule_enabled(Rule::RedefinedSlotsInSubclass) {
pylint::rules::redefined_slots_in_subclass(checker, class_def);
}
if checker.is_rule_enabled(Rule::TooManyPublicMethods) {
pylint::rules::too_many_public_methods(
checker,
class_def,
checker.settings().pylint.max_public_methods,
);
}
if checker.is_rule_enabled(Rule::GlobalStatement) {
pylint::rules::global_statement(checker, name);
}
if checker.is_rule_enabled(Rule::UselessObjectInheritance) {
pyupgrade::rules::useless_object_inheritance(checker, class_def);
}
if checker.is_rule_enabled(Rule::UselessClassMetaclassType) {
pyupgrade::rules::useless_class_metaclass_type(checker, class_def);
}
if checker.is_rule_enabled(Rule::ReplaceStrEnum) {
if checker.target_version() >= PythonVersion::PY311 {
pyupgrade::rules::replace_str_enum(checker, class_def);
}
}
if checker.is_rule_enabled(Rule::UnnecessaryClassParentheses) {
pyupgrade::rules::unnecessary_class_parentheses(checker, class_def);
}
if checker.is_rule_enabled(Rule::AmbiguousClassName) {
pycodestyle::rules::ambiguous_class_name(checker, name);
}
if checker.is_rule_enabled(Rule::InvalidClassName) {
pep8_naming::rules::invalid_class_name(
checker,
stmt,
name,
&checker.settings().pep8_naming.ignore_names,
);
}
if checker.is_rule_enabled(Rule::ErrorSuffixOnExceptionName) {
pep8_naming::rules::error_suffix_on_exception_name(
checker,
stmt,
arguments.as_deref(),
name,
&checker.settings().pep8_naming.ignore_names,
);
}
if !checker.source_type.is_stub() {
if checker.any_rule_enabled(&[
Rule::AbstractBaseClassWithoutAbstractMethod,
Rule::EmptyMethodWithoutAbstractDecorator,
]) {
flake8_bugbear::rules::abstract_base_class(
checker,
stmt,
name,
arguments.as_deref(),
body,
);
}
}
if checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::PassStatementStubBody) {
flake8_pyi::rules::pass_statement_stub_body(checker, body);
}
if checker.is_rule_enabled(Rule::PassInClassBody) {
flake8_pyi::rules::pass_in_class_body(checker, class_def);
}
}
if checker.is_rule_enabled(Rule::EllipsisInNonEmptyClassBody) {
flake8_pyi::rules::ellipsis_in_non_empty_class_body(checker, body);
}
if checker.is_rule_enabled(Rule::GenericNotLastBaseClass) {
flake8_pyi::rules::generic_not_last_base_class(checker, class_def);
}
if checker.is_rule_enabled(Rule::PytestIncorrectMarkParenthesesStyle) {
flake8_pytest_style::rules::marks(checker, decorator_list);
}
if checker.is_rule_enabled(Rule::DuplicateClassFieldDefinition) {
flake8_pie::rules::duplicate_class_field_definition(checker, body);
}
if checker.is_rule_enabled(Rule::NonUniqueEnums) {
flake8_pie::rules::non_unique_enums(checker, stmt, body);
}
if checker.is_rule_enabled(Rule::FStringDocstring) {
flake8_bugbear::rules::f_string_docstring(checker, body);
}
if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(checker, name, name.range());
}
if checker.is_rule_enabled(Rule::DuplicateBases) {
pylint::rules::duplicate_bases(checker, name, arguments.as_deref());
}
if checker.is_rule_enabled(Rule::NoSlotsInStrSubclass) {
flake8_slots::rules::no_slots_in_str_subclass(checker, stmt, class_def);
}
if checker.is_rule_enabled(Rule::NoSlotsInTupleSubclass) {
flake8_slots::rules::no_slots_in_tuple_subclass(checker, stmt, class_def);
}
if checker.is_rule_enabled(Rule::NoSlotsInNamedtupleSubclass) {
flake8_slots::rules::no_slots_in_namedtuple_subclass(checker, stmt, class_def);
}
if checker.is_rule_enabled(Rule::NonSlotAssignment) {
pylint::rules::non_slot_assignment(checker, class_def);
}
if checker.is_rule_enabled(Rule::SingleStringSlots) {
pylint::rules::single_string_slots(checker, class_def);
}
if checker.is_rule_enabled(Rule::MetaClassABCMeta) {
refurb::rules::metaclass_abcmeta(checker, class_def);
}
if checker.is_rule_enabled(Rule::WhitespaceAfterDecorator) {
pycodestyle::rules::whitespace_after_decorator(checker, decorator_list);
}
if checker.is_rule_enabled(Rule::SubclassBuiltin) {
refurb::rules::subclass_builtin(checker, class_def);
}
if checker.is_rule_enabled(Rule::DataclassEnum) {
ruff::rules::dataclass_enum(checker, class_def);
}
if checker.is_rule_enabled(Rule::NonPEP695GenericClass) {
pyupgrade::rules::non_pep695_generic_class(checker, class_def);
}
if checker.is_rule_enabled(Rule::ClassWithMixedTypeVars) {
ruff::rules::class_with_mixed_type_vars(checker, class_def);
}
if checker.is_rule_enabled(Rule::ImplicitClassVarInDataclass) {
ruff::rules::implicit_class_var_in_dataclass(checker, class_def);
}
}
Stmt::Import(ast::StmtImport {
names,
range: _,
node_index: _,
}) => {
if checker.is_rule_enabled(Rule::MultipleImportsOnOneLine) {
pycodestyle::rules::multiple_imports_on_one_line(checker, stmt, names);
}
if checker.is_rule_enabled(Rule::ModuleImportNotAtTopOfFile) {
pycodestyle::rules::module_import_not_at_top_of_file(checker, stmt);
}
if checker.is_rule_enabled(Rule::ImportOutsideTopLevel) {
pylint::rules::import_outside_top_level(checker, stmt);
}
if checker.is_rule_enabled(Rule::GlobalStatement) {
for name in names {
if let Some(asname) = name.asname.as_ref() {
pylint::rules::global_statement(checker, asname);
} else {
pylint::rules::global_statement(checker, &name.name);
}
}
}
if checker.is_rule_enabled(Rule::DeprecatedCElementTree) {
pyupgrade::rules::deprecated_c_element_tree(checker, stmt);
}
if checker.is_rule_enabled(Rule::DeprecatedMockImport) {
pyupgrade::rules::deprecated_mock_import(checker, stmt);
}
if checker.any_rule_enabled(&[
Rule::SuspiciousTelnetlibImport,
Rule::SuspiciousFtplibImport,
Rule::SuspiciousPickleImport,
Rule::SuspiciousSubprocessImport,
Rule::SuspiciousXmlEtreeImport,
Rule::SuspiciousXmlSaxImport,
Rule::SuspiciousXmlExpatImport,
Rule::SuspiciousXmlMinidomImport,
Rule::SuspiciousXmlPulldomImport,
Rule::SuspiciousLxmlImport,
Rule::SuspiciousXmlrpcImport,
Rule::SuspiciousHttpoxyImport,
Rule::SuspiciousPycryptoImport,
Rule::SuspiciousPyghmiImport,
]) {
flake8_bandit::rules::suspicious_imports(checker, stmt);
}
if checker.is_rule_enabled(Rule::BannedModuleLevelImports) {
flake8_tidy_imports::rules::banned_module_level_imports(checker, stmt);
}
for alias in names {
if checker.is_rule_enabled(Rule::NonAsciiImportName) {
pylint::rules::non_ascii_module_import(checker, alias);
}
if checker.is_rule_enabled(Rule::Debugger) {
flake8_debugger::rules::debugger_import(checker, stmt, None, &alias.name);
}
if checker.is_rule_enabled(Rule::BannedApi) {
flake8_tidy_imports::rules::banned_api(
checker,
&flake8_tidy_imports::matchers::NameMatchPolicy::MatchNameOrParent(
flake8_tidy_imports::matchers::MatchNameOrParent {
module: &alias.name,
},
),
&alias,
);
}
if !checker.source_type.is_stub() {
if checker.is_rule_enabled(Rule::UselessImportAlias) {
pylint::rules::useless_import_alias(checker, alias);
}
}
if checker.is_rule_enabled(Rule::ManualFromImport) {
pylint::rules::manual_from_import(checker, stmt, alias, names);
}
if checker.is_rule_enabled(Rule::ImportSelf) {
pylint::rules::import_self(checker, alias, checker.module.qualified_name());
}
if let Some(asname) = &alias.asname {
let name = alias.name.split('.').next_back().unwrap();
if checker.is_rule_enabled(Rule::ConstantImportedAsNonConstant) {
pep8_naming::rules::constant_imported_as_non_constant(
checker,
name,
asname,
alias,
stmt,
&checker.settings().pep8_naming.ignore_names,
);
}
if checker.is_rule_enabled(Rule::LowercaseImportedAsNonLowercase) {
pep8_naming::rules::lowercase_imported_as_non_lowercase(
checker,
name,
asname,
alias,
stmt,
&checker.settings().pep8_naming.ignore_names,
);
}
if checker.is_rule_enabled(Rule::CamelcaseImportedAsLowercase) {
pep8_naming::rules::camelcase_imported_as_lowercase(
checker,
name,
asname,
alias,
stmt,
&checker.settings().pep8_naming.ignore_names,
);
}
if checker.is_rule_enabled(Rule::CamelcaseImportedAsConstant) {
pep8_naming::rules::camelcase_imported_as_constant(
checker,
name,
asname,
alias,
stmt,
&checker.settings().pep8_naming.ignore_names,
);
}
if checker.is_rule_enabled(Rule::CamelcaseImportedAsAcronym) {
pep8_naming::rules::camelcase_imported_as_acronym(
name, asname, alias, stmt, checker,
);
}
}
if checker.is_rule_enabled(Rule::BannedImportAlias) {
if let Some(asname) = &alias.asname {
flake8_import_conventions::rules::banned_import_alias(
checker,
stmt,
&alias.name,
asname,
&checker.settings().flake8_import_conventions.banned_aliases,
);
}
}
if checker.is_rule_enabled(Rule::PytestIncorrectPytestImport) {
flake8_pytest_style::rules::import(
checker,
stmt,
&alias.name,
alias.asname.as_deref(),
);
}
if checker.is_rule_enabled(Rule::BuiltinImportShadowing) {
flake8_builtins::rules::builtin_import_shadowing(checker, alias);
}
}
}
Stmt::ImportFrom(
import_from @ ast::StmtImportFrom {
names,
module,
level,
range: _,
node_index: _,
},
) => {
let level = *level;
let module = module.as_deref();
if checker.is_rule_enabled(Rule::ModuleImportNotAtTopOfFile) {
pycodestyle::rules::module_import_not_at_top_of_file(checker, stmt);
}
if checker.is_rule_enabled(Rule::ImportOutsideTopLevel) {
pylint::rules::import_outside_top_level(checker, stmt);
}
if checker.is_rule_enabled(Rule::GlobalStatement) {
for name in names {
if let Some(asname) = name.asname.as_ref() {
pylint::rules::global_statement(checker, asname);
} else {
pylint::rules::global_statement(checker, &name.name);
}
}
}
if checker.is_rule_enabled(Rule::NonAsciiImportName) {
for alias in names {
| 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/checkers/ast/analyze/definitions.rs | crates/ruff_linter/src/checkers/ast/analyze/definitions.rs | use ruff_python_semantic::all::DunderAllName;
use ruff_python_semantic::{
BindingKind, ContextualizedDefinition, Definition, Export, Member, MemberKind,
};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::docstrings::Docstring;
use crate::fs::relativize_path;
use crate::rules::{flake8_annotations, flake8_pyi, pydoclint, pydocstyle, pylint};
use crate::{docstrings, warn_user};
/// Run lint rules over all [`Definition`] nodes in the [`SemanticModel`].
///
/// This phase is expected to run after the AST has been traversed in its entirety; as such,
/// it is expected that all [`Definition`] nodes have been visited by the time, and that this
/// method will not recurse into any other nodes.
pub(crate) fn definitions(checker: &mut Checker) {
let enforce_annotations = checker.any_rule_enabled(&[
Rule::AnyType,
Rule::MissingReturnTypeClassMethod,
Rule::MissingReturnTypePrivateFunction,
Rule::MissingReturnTypeSpecialMethod,
Rule::MissingReturnTypeStaticMethod,
Rule::MissingReturnTypeUndocumentedPublicFunction,
Rule::MissingTypeArgs,
Rule::MissingTypeFunctionArgument,
Rule::MissingTypeKwargs,
]);
let enforce_stubs =
checker.source_type.is_stub() && checker.is_rule_enabled(Rule::DocstringInStub);
let enforce_stubs_and_runtime = checker.is_rule_enabled(Rule::IterMethodReturnIterable);
let enforce_dunder_method = checker.is_rule_enabled(Rule::BadDunderMethodName);
let enforce_docstrings = checker.any_rule_enabled(&[
Rule::MissingBlankLineAfterLastSection,
Rule::MissingBlankLineAfterSummary,
Rule::BlankLineBeforeClass,
Rule::BlankLinesBetweenHeaderAndContent,
Rule::NonCapitalizedSectionName,
Rule::MissingDashedUnderlineAfterSection,
Rule::DocstringStartsWithThis,
Rule::EmptyDocstring,
Rule::EmptyDocstringSection,
Rule::MissingTrailingPeriod,
Rule::MissingTerminalPunctuation,
Rule::EscapeSequenceInDocstring,
Rule::FirstWordUncapitalized,
Rule::UnnecessaryMultilineDocstring,
Rule::DocstringTabIndentation,
Rule::MultiLineSummaryFirstLine,
Rule::MultiLineSummarySecondLine,
Rule::NewLineAfterLastParagraph,
Rule::MissingNewLineAfterSectionName,
Rule::BlankLineAfterFunction,
Rule::NoBlankLineAfterSection,
Rule::BlankLineBeforeFunction,
Rule::NoBlankLineBeforeSection,
Rule::SignatureInDocstring,
Rule::NonImperativeMood,
Rule::IncorrectBlankLineAfterClass,
Rule::IncorrectBlankLineBeforeClass,
Rule::OverIndentation,
Rule::OverloadWithDocstring,
Rule::MissingSectionNameColon,
Rule::OverindentedSection,
Rule::MissingSectionUnderlineAfterName,
Rule::MismatchedSectionUnderlineLength,
Rule::OverindentedSectionUnderline,
Rule::SurroundingWhitespace,
Rule::TripleSingleQuotes,
Rule::UnderIndentation,
Rule::UndocumentedMagicMethod,
Rule::UndocumentedParam,
Rule::UndocumentedPublicClass,
Rule::UndocumentedPublicFunction,
Rule::UndocumentedPublicInit,
Rule::UndocumentedPublicMethod,
Rule::UndocumentedPublicModule,
Rule::UndocumentedPublicNestedClass,
Rule::UndocumentedPublicPackage,
]);
let enforce_pydoclint = checker.any_rule_enabled(&[
Rule::DocstringExtraneousParameter,
Rule::DocstringMissingReturns,
Rule::DocstringExtraneousReturns,
Rule::DocstringMissingYields,
Rule::DocstringExtraneousYields,
Rule::DocstringMissingException,
Rule::DocstringExtraneousException,
]);
if !enforce_annotations
&& !enforce_docstrings
&& !enforce_stubs
&& !enforce_stubs_and_runtime
&& !enforce_dunder_method
&& !enforce_pydoclint
{
return;
}
// Compute visibility of all definitions.
let exports: Option<Vec<DunderAllName>> = {
checker
.semantic
.global_scope()
.get_all("__all__")
.map(|binding_id| &checker.semantic.bindings[binding_id])
.filter_map(|binding| match &binding.kind {
BindingKind::Export(Export { names }) => Some(names.iter().copied()),
_ => None,
})
.fold(None, |acc, names| {
Some(acc.into_iter().flatten().chain(names).collect())
})
};
let definitions = std::mem::take(&mut checker.semantic.definitions);
let mut overloaded_name: Option<&str> = None;
for ContextualizedDefinition {
definition,
visibility,
} in definitions.resolve(exports.as_deref()).iter()
{
let docstring = docstrings::extraction::extract_docstring(definition);
// flake8-annotations
if enforce_annotations {
// TODO(charlie): This should be even stricter, in that an overload
// implementation should come immediately after the overloaded
// interfaces, without any AST nodes in between. Right now, we
// only error when traversing definition boundaries (functions,
// classes, etc.).
if !overloaded_name.is_some_and(|overloaded_name| {
flake8_annotations::helpers::is_overload_impl(
definition,
overloaded_name,
&checker.semantic,
)
}) {
flake8_annotations::rules::definition(checker, definition, *visibility);
}
overloaded_name =
flake8_annotations::helpers::overloaded_name(definition, &checker.semantic);
}
// flake8-pyi
if enforce_stubs_and_runtime {
flake8_pyi::rules::iter_method_return_iterable(checker, definition);
}
// pylint
if enforce_dunder_method {
if let Definition::Member(Member {
kind: MemberKind::Method(method),
..
}) = definition
{
pylint::rules::bad_dunder_method_name(checker, method);
}
}
// pydocstyle, pydoclint
if enforce_docstrings || enforce_pydoclint {
if pydocstyle::helpers::should_ignore_definition(
definition,
&checker.settings().pydocstyle,
&checker.semantic,
) {
continue;
}
// Extract a `Docstring` from a `Definition`.
let Some(string_literal) = docstring else {
pydocstyle::rules::not_missing(checker, definition, *visibility);
continue;
};
// We don't recognise implicitly concatenated strings as valid docstrings in our model currently.
let Some(sole_string_part) = string_literal.as_single_part_string() else {
#[expect(deprecated)]
let location = checker
.locator
.compute_source_location(string_literal.start());
warn_user!(
"Docstring at {}:{}:{} contains implicit string concatenation; ignoring...",
relativize_path(checker.path),
location.line,
location.column
);
continue;
};
let docstring = Docstring {
definition,
expr: sole_string_part,
source: checker.source(),
};
if !pydocstyle::rules::not_empty(checker, &docstring) {
continue;
}
if checker.is_rule_enabled(Rule::UnnecessaryMultilineDocstring) {
pydocstyle::rules::one_liner(checker, &docstring);
}
if checker
.any_rule_enabled(&[Rule::BlankLineAfterFunction, Rule::BlankLineBeforeFunction])
{
pydocstyle::rules::blank_before_after_function(checker, &docstring);
}
if checker.any_rule_enabled(&[
Rule::BlankLineBeforeClass,
Rule::IncorrectBlankLineAfterClass,
Rule::IncorrectBlankLineBeforeClass,
]) {
pydocstyle::rules::blank_before_after_class(checker, &docstring);
}
if checker.is_rule_enabled(Rule::MissingBlankLineAfterSummary) {
pydocstyle::rules::blank_after_summary(checker, &docstring);
}
if checker.any_rule_enabled(&[
Rule::DocstringTabIndentation,
Rule::OverIndentation,
Rule::UnderIndentation,
]) {
pydocstyle::rules::indent(checker, &docstring);
}
if checker.is_rule_enabled(Rule::NewLineAfterLastParagraph) {
pydocstyle::rules::newline_after_last_paragraph(checker, &docstring);
}
if checker.is_rule_enabled(Rule::SurroundingWhitespace) {
pydocstyle::rules::no_surrounding_whitespace(checker, &docstring);
}
if checker.any_rule_enabled(&[
Rule::MultiLineSummaryFirstLine,
Rule::MultiLineSummarySecondLine,
]) {
pydocstyle::rules::multi_line_summary_start(checker, &docstring);
}
if checker.is_rule_enabled(Rule::TripleSingleQuotes) {
pydocstyle::rules::triple_quotes(checker, &docstring);
}
if checker.is_rule_enabled(Rule::EscapeSequenceInDocstring) {
pydocstyle::rules::backslashes(checker, &docstring);
}
if checker.is_rule_enabled(Rule::MissingTrailingPeriod) {
pydocstyle::rules::ends_with_period(checker, &docstring);
}
if checker.is_rule_enabled(Rule::NonImperativeMood) {
pydocstyle::rules::non_imperative_mood(
checker,
&docstring,
&checker.settings().pydocstyle,
);
}
if checker.is_rule_enabled(Rule::SignatureInDocstring) {
pydocstyle::rules::no_signature(checker, &docstring);
}
if checker.is_rule_enabled(Rule::FirstWordUncapitalized) {
pydocstyle::rules::capitalized(checker, &docstring);
}
if checker.is_rule_enabled(Rule::DocstringStartsWithThis) {
pydocstyle::rules::starts_with_this(checker, &docstring);
}
if checker.is_rule_enabled(Rule::MissingTerminalPunctuation) {
pydocstyle::rules::ends_with_punctuation(checker, &docstring);
}
if checker.is_rule_enabled(Rule::OverloadWithDocstring) {
pydocstyle::rules::if_needed(checker, &docstring);
}
let enforce_sections = checker.any_rule_enabled(&[
Rule::MissingBlankLineAfterLastSection,
Rule::BlankLinesBetweenHeaderAndContent,
Rule::NonCapitalizedSectionName,
Rule::MissingDashedUnderlineAfterSection,
Rule::EmptyDocstringSection,
Rule::MultiLineSummaryFirstLine,
Rule::MissingNewLineAfterSectionName,
Rule::NoBlankLineAfterSection,
Rule::NoBlankLineBeforeSection,
Rule::MissingSectionNameColon,
Rule::OverindentedSection,
Rule::MissingSectionUnderlineAfterName,
Rule::MismatchedSectionUnderlineLength,
Rule::OverindentedSectionUnderline,
Rule::UndocumentedParam,
]);
if enforce_sections || enforce_pydoclint {
let section_contexts = pydocstyle::helpers::get_section_contexts(
&docstring,
checker.settings().pydocstyle.convention(),
);
if enforce_sections {
pydocstyle::rules::sections(
checker,
&docstring,
§ion_contexts,
checker.settings().pydocstyle.convention(),
);
}
if enforce_pydoclint {
pydoclint::rules::check_docstring(
checker,
definition,
&docstring,
§ion_contexts,
checker.settings().pydocstyle.convention(),
);
}
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs | crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs | use ruff_python_ast::PythonVersion;
use ruff_python_semantic::{Binding, ScopeKind};
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{
flake8_builtins, flake8_pyi, flake8_type_checking, flake8_unused_arguments, pep8_naming,
pyflakes, pylint, pyupgrade, ruff,
};
/// Run lint rules over all deferred scopes in the [`SemanticModel`].
pub(crate) fn deferred_scopes(checker: &Checker) {
if !checker.any_rule_enabled(&[
Rule::AsyncioDanglingTask,
Rule::BadStaticmethodArgument,
Rule::BuiltinAttributeShadowing,
Rule::FunctionCallInDataclassDefaultArgument,
Rule::GlobalVariableNotAssigned,
Rule::ImportPrivateName,
Rule::ImportShadowedByLoopVar,
Rule::InvalidFirstArgumentNameForClassMethod,
Rule::InvalidFirstArgumentNameForMethod,
Rule::MutableClassDefault,
Rule::MutableDataclassDefault,
Rule::NoSelfUse,
Rule::RedefinedArgumentFromLocal,
Rule::RedefinedWhileUnused,
Rule::RuntimeImportInTypeCheckingBlock,
Rule::SingledispatchMethod,
Rule::SingledispatchmethodFunction,
Rule::TooManyLocals,
Rule::TypingOnlyFirstPartyImport,
Rule::TypingOnlyStandardLibraryImport,
Rule::TypingOnlyThirdPartyImport,
Rule::UndefinedLocal,
Rule::UnusedAnnotation,
Rule::UnusedClassMethodArgument,
Rule::UnusedFunctionArgument,
Rule::UnusedImport,
Rule::UnusedLambdaArgument,
Rule::UnusedMethodArgument,
Rule::UnusedPrivateProtocol,
Rule::UnusedPrivateTypeAlias,
Rule::UnusedPrivateTypedDict,
Rule::UnusedPrivateTypeVar,
Rule::UnusedStaticMethodArgument,
Rule::UnusedUnpackedVariable,
Rule::UnusedVariable,
Rule::UnnecessaryFutureImport,
]) {
return;
}
// Identify any valid runtime imports. If a module is imported at runtime, and
// used at runtime, then by default, we avoid flagging any other
// imports from that model as typing-only.
let enforce_typing_only_imports = !checker.source_type.is_stub()
&& checker.any_rule_enabled(&[
Rule::TypingOnlyFirstPartyImport,
Rule::TypingOnlyStandardLibraryImport,
Rule::TypingOnlyThirdPartyImport,
]);
let runtime_imports: Vec<Vec<&Binding>> = if enforce_typing_only_imports {
checker
.semantic
.scopes
.iter()
.map(|scope| {
scope
.binding_ids()
.map(|binding_id| checker.semantic.binding(binding_id))
.filter(|binding| {
flake8_type_checking::helpers::is_valid_runtime_import(
binding,
&checker.semantic,
checker.settings(),
)
})
.collect()
})
.collect::<Vec<_>>()
} else {
vec![]
};
for scope_id in checker.analyze.scopes.iter().rev().copied() {
let scope = &checker.semantic.scopes[scope_id];
if checker.is_rule_enabled(Rule::UndefinedLocal) {
pyflakes::rules::undefined_local(checker, scope_id, scope);
}
if checker.is_rule_enabled(Rule::GlobalVariableNotAssigned) {
pylint::rules::global_variable_not_assigned(checker, scope);
}
if checker.is_rule_enabled(Rule::RedefinedArgumentFromLocal) {
pylint::rules::redefined_argument_from_local(checker, scope_id, scope);
}
if checker.is_rule_enabled(Rule::ImportShadowedByLoopVar) {
pyflakes::rules::import_shadowed_by_loop_var(checker, scope_id, scope);
}
if checker.is_rule_enabled(Rule::RedefinedWhileUnused) {
pyflakes::rules::redefined_while_unused(checker, scope_id, scope);
}
if checker.source_type.is_stub()
|| matches!(scope.kind, ScopeKind::Module | ScopeKind::Function(_))
{
if checker.is_rule_enabled(Rule::UnusedPrivateTypeVar) {
flake8_pyi::rules::unused_private_type_var(checker, scope);
}
if checker.is_rule_enabled(Rule::UnusedPrivateProtocol) {
flake8_pyi::rules::unused_private_protocol(checker, scope);
}
if checker.is_rule_enabled(Rule::UnusedPrivateTypeAlias) {
flake8_pyi::rules::unused_private_type_alias(checker, scope);
}
if checker.is_rule_enabled(Rule::UnusedPrivateTypedDict) {
flake8_pyi::rules::unused_private_typed_dict(checker, scope);
}
}
if checker.is_rule_enabled(Rule::AsyncioDanglingTask) {
ruff::rules::asyncio_dangling_binding(scope, checker);
}
if let Some(class_def) = scope.kind.as_class() {
if checker.is_rule_enabled(Rule::BuiltinAttributeShadowing) {
flake8_builtins::rules::builtin_attribute_shadowing(
checker, scope_id, scope, class_def,
);
}
if checker.is_rule_enabled(Rule::FunctionCallInDataclassDefaultArgument) {
ruff::rules::function_call_in_dataclass_default(checker, class_def, scope_id);
}
if checker.is_rule_enabled(Rule::MutableClassDefault) {
ruff::rules::mutable_class_default(checker, class_def);
}
if checker.is_rule_enabled(Rule::MutableDataclassDefault) {
ruff::rules::mutable_dataclass_default(checker, class_def);
}
}
if matches!(scope.kind, ScopeKind::Function(_) | ScopeKind::Lambda(_)) {
if checker.any_rule_enabled(&[Rule::UnusedVariable, Rule::UnusedUnpackedVariable])
&& !(scope.uses_locals() && scope.kind.is_function())
{
let unused_bindings = scope
.bindings()
.map(|(name, binding_id)| (name, checker.semantic().binding(binding_id)))
.filter_map(|(name, binding)| {
if (binding.kind.is_assignment()
|| binding.kind.is_named_expr_assignment()
|| binding.kind.is_with_item_var())
&& binding.is_unused()
&& !binding.is_nonlocal()
&& !binding.is_global()
&& !checker.settings().dummy_variable_rgx.is_match(name)
&& !matches!(
name,
"__tracebackhide__"
| "__traceback_info__"
| "__traceback_supplement__"
| "__debuggerskip__"
)
{
return Some((name, binding));
}
None
});
for (unused_name, unused_binding) in unused_bindings {
if checker.is_rule_enabled(Rule::UnusedVariable) {
pyflakes::rules::unused_variable(checker, unused_name, unused_binding);
}
if checker.is_rule_enabled(Rule::UnusedUnpackedVariable) {
ruff::rules::unused_unpacked_variable(checker, unused_name, unused_binding);
}
}
}
if checker.is_rule_enabled(Rule::UnusedAnnotation) {
pyflakes::rules::unused_annotation(checker, scope);
}
if !checker.source_type.is_stub() {
if checker.any_rule_enabled(&[
Rule::UnusedClassMethodArgument,
Rule::UnusedFunctionArgument,
Rule::UnusedLambdaArgument,
Rule::UnusedMethodArgument,
Rule::UnusedStaticMethodArgument,
]) {
flake8_unused_arguments::rules::unused_arguments(checker, scope);
}
}
}
if matches!(scope.kind, ScopeKind::Function(_) | ScopeKind::Module) {
if !checker.source_type.is_stub()
&& checker.is_rule_enabled(Rule::RuntimeImportInTypeCheckingBlock)
{
flake8_type_checking::rules::runtime_import_in_type_checking_block(checker, scope);
}
if enforce_typing_only_imports {
let runtime_imports: Vec<&Binding> = checker
.semantic
.scopes
.ancestor_ids(scope_id)
.flat_map(|scope_id| runtime_imports[scope_id.as_usize()].iter())
.copied()
.collect();
flake8_type_checking::rules::typing_only_runtime_import(
checker,
scope,
&runtime_imports,
);
}
if checker.is_rule_enabled(Rule::UnusedImport) {
pyflakes::rules::unused_import(checker, scope);
}
if checker.is_rule_enabled(Rule::UnnecessaryFutureImport) {
if checker.target_version() >= PythonVersion::PY37 {
pyupgrade::rules::unnecessary_future_import(checker, scope);
}
}
if checker.is_rule_enabled(Rule::ImportPrivateName) {
pylint::rules::import_private_name(checker, scope);
}
}
if scope.kind.is_function() {
if checker.is_rule_enabled(Rule::NoSelfUse) {
pylint::rules::no_self_use(checker, scope_id, scope);
}
if checker.is_rule_enabled(Rule::TooManyLocals) {
pylint::rules::too_many_locals(checker, scope);
}
if checker.is_rule_enabled(Rule::SingledispatchMethod) {
pylint::rules::singledispatch_method(checker, scope);
}
if checker.is_rule_enabled(Rule::SingledispatchmethodFunction) {
pylint::rules::singledispatchmethod_function(checker, scope);
}
if checker.is_rule_enabled(Rule::BadStaticmethodArgument) {
pylint::rules::bad_staticmethod_argument(checker, scope);
}
if checker.any_rule_enabled(&[
Rule::InvalidFirstArgumentNameForClassMethod,
Rule::InvalidFirstArgumentNameForMethod,
]) {
pep8_naming::rules::invalid_first_argument_name(checker, scope);
}
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/comprehension.rs | crates/ruff_linter/src/checkers/ast/analyze/comprehension.rs | use ruff_python_ast::Comprehension;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_simplify, refurb};
/// Run lint rules over a [`Comprehension`] syntax nodes.
pub(crate) fn comprehension(comprehension: &Comprehension, checker: &Checker) {
if checker.is_rule_enabled(Rule::InDictKeys) {
flake8_simplify::rules::key_in_dict_comprehension(checker, comprehension);
}
if checker.is_rule_enabled(Rule::ReadlinesInFor) {
refurb::rules::readlines_in_comprehension(checker, comprehension);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/checkers/ast/analyze/parameter.rs | crates/ruff_linter/src/checkers/ast/analyze/parameter.rs | use ruff_python_ast::Parameter;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_builtins, pycodestyle};
/// Run lint rules over a [`Parameter`] syntax node.
pub(crate) fn parameter(parameter: &Parameter, checker: &Checker) {
if checker.is_rule_enabled(Rule::AmbiguousVariableName) {
pycodestyle::rules::ambiguous_variable_name(
checker,
¶meter.name,
parameter.name.range(),
);
}
if checker.is_rule_enabled(Rule::BuiltinArgumentShadowing) {
flake8_builtins::rules::builtin_argument_shadowing(checker, parameter);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/settings/rule_table.rs | crates/ruff_linter/src/settings/rule_table.rs | use std::fmt::{Debug, Display, Formatter};
use crate::display_settings;
use ruff_macros::CacheKey;
use crate::registry::{Rule, RuleSet, RuleSetIterator};
/// A table to keep track of which rules are enabled and whether they should be fixed.
#[derive(Debug, Clone, CacheKey, Default)]
pub struct RuleTable {
/// Maps rule codes to a boolean indicating if the rule should be fixed.
enabled: RuleSet,
should_fix: RuleSet,
}
impl RuleTable {
/// Creates a new empty rule table.
pub const fn empty() -> Self {
Self {
enabled: RuleSet::empty(),
should_fix: RuleSet::empty(),
}
}
/// Returns whether the given rule should be checked.
#[inline]
pub const fn enabled(&self, rule: Rule) -> bool {
self.enabled.contains(rule)
}
/// Returns whether any of the given rules should be checked.
#[inline]
pub const fn any_enabled(&self, rules: &[Rule]) -> bool {
self.enabled.any(rules)
}
/// Returns whether violations of the given rule should be fixed.
#[inline]
pub const fn should_fix(&self, rule: Rule) -> bool {
self.should_fix.contains(rule)
}
/// Returns an iterator over all enabled rules.
pub fn iter_enabled(&self) -> RuleSetIterator {
self.enabled.iter()
}
/// Enables the given rule.
#[inline]
pub fn enable(&mut self, rule: Rule, should_fix: bool) {
self.enabled.insert(rule);
if should_fix {
self.should_fix.insert(rule);
}
}
/// Disables the given rule.
#[inline]
pub fn disable(&mut self, rule: Rule) {
self.enabled.remove(rule);
self.should_fix.remove(rule);
}
}
impl Display for RuleTable {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.rules",
fields = [
self.enabled,
self.should_fix
]
}
Ok(())
}
}
impl FromIterator<Rule> for RuleTable {
fn from_iter<T: IntoIterator<Item = Rule>>(iter: T) -> Self {
let rules = RuleSet::from_iter(iter);
Self {
enabled: rules.clone(),
should_fix: rules,
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/settings/flags.rs | crates/ruff_linter/src/settings/flags.rs | #[derive(Debug, Copy, Clone, Hash, is_macro::Is)]
pub enum FixMode {
Generate,
Apply,
Diff,
}
#[derive(Debug, Copy, Clone, Hash)]
pub enum Noqa {
Enabled,
Disabled,
}
impl Noqa {
pub const fn is_enabled(self) -> bool {
matches!(self, Noqa::Enabled)
}
}
impl From<bool> for Noqa {
fn from(value: bool) -> Self {
if value { Noqa::Enabled } else { Noqa::Disabled }
}
}
#[derive(Debug, Copy, Clone, Hash)]
pub enum Cache {
Enabled,
Disabled,
}
impl Cache {
pub const fn is_enabled(self) -> bool {
matches!(self, Cache::Enabled)
}
}
impl From<bool> for Cache {
fn from(value: bool) -> Self {
if value {
Cache::Enabled
} else {
Cache::Disabled
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/settings/fix_safety_table.rs | crates/ruff_linter/src/settings/fix_safety_table.rs | use std::fmt::{Debug, Display, Formatter};
use ruff_macros::CacheKey;
use rustc_hash::FxHashMap;
use strum::IntoEnumIterator;
use crate::Applicability;
use crate::{
RuleSelector, display_settings,
registry::{Rule, RuleSet},
rule_selector::{PreviewOptions, Specificity},
};
/// A table to keep track of which rules fixes should have
/// their safety overridden.
#[derive(Debug, Clone, CacheKey, Default)]
pub struct FixSafetyTable {
forced_safe: RuleSet,
forced_unsafe: RuleSet,
}
impl FixSafetyTable {
pub const fn resolve_applicability(
&self,
rule: Rule,
applicability: Applicability,
) -> Applicability {
match applicability {
// If applicability is display-only we don't change it
Applicability::DisplayOnly => applicability,
Applicability::Safe | Applicability::Unsafe => {
if self.forced_unsafe.contains(rule) {
Applicability::Unsafe
} else if self.forced_safe.contains(rule) {
Applicability::Safe
} else {
applicability
}
}
}
}
pub const fn is_empty(&self) -> bool {
self.forced_safe.is_empty() && self.forced_unsafe.is_empty()
}
pub fn from_rule_selectors(
extend_safe_fixes: &[RuleSelector],
extend_unsafe_fixes: &[RuleSelector],
preview_options: &PreviewOptions,
) -> Self {
enum Override {
Safe,
Unsafe,
}
let safety_override_map: FxHashMap<Rule, Override> = {
Specificity::iter()
.flat_map(|spec| {
let safe_overrides = extend_safe_fixes
.iter()
.filter(|selector| selector.specificity() == spec)
.flat_map(|selector| selector.rules(preview_options))
.map(|rule| (rule, Override::Safe));
let unsafe_overrides = extend_unsafe_fixes
.iter()
.filter(|selector| selector.specificity() == spec)
.flat_map(|selector| selector.rules(preview_options))
.map(|rule| (rule, Override::Unsafe));
// Unsafe overrides take precedence over safe overrides
safe_overrides.chain(unsafe_overrides).collect::<Vec<_>>()
})
// More specified selectors take precedence over less specified selectors
.collect()
};
FixSafetyTable {
forced_safe: safety_override_map
.iter()
.filter_map(|(rule, o)| match o {
Override::Safe => Some(*rule),
Override::Unsafe => None,
})
.collect(),
forced_unsafe: safety_override_map
.iter()
.filter_map(|(rule, o)| match o {
Override::Unsafe => Some(*rule),
Override::Safe => None,
})
.collect(),
}
}
}
impl Display for FixSafetyTable {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.safety_table",
fields = [
self.forced_safe,
self.forced_unsafe
]
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_resolve_applicability() {
let table = FixSafetyTable {
forced_safe: RuleSet::from_iter([Rule::RedefinedWhileUnused]),
forced_unsafe: RuleSet::from_iter([Rule::UnusedImport]),
};
for applicability in &[Applicability::Safe, Applicability::Unsafe] {
assert_eq!(
table.resolve_applicability(Rule::RedefinedWhileUnused, *applicability),
Applicability::Safe // It is forced to Safe
);
}
for applicability in &[Applicability::Safe, Applicability::Unsafe] {
assert_eq!(
table.resolve_applicability(Rule::UnusedImport, *applicability),
Applicability::Unsafe // It is forced to Unsafe
);
}
for applicability in &[Applicability::Safe, Applicability::Unsafe] {
assert_eq!(
table.resolve_applicability(Rule::UndefinedName, *applicability),
*applicability // Remains unchanged
);
}
for rule in &[
Rule::RedefinedWhileUnused,
Rule::UnusedImport,
Rule::UndefinedName,
] {
assert_eq!(
table.resolve_applicability(*rule, Applicability::DisplayOnly),
Applicability::DisplayOnly // Display is never changed
);
}
}
fn mk_table(safe_fixes: &[&str], unsafe_fixes: &[&str]) -> FixSafetyTable {
FixSafetyTable::from_rule_selectors(
&safe_fixes
.iter()
.map(|s| s.parse().unwrap())
.collect::<Vec<_>>(),
&unsafe_fixes
.iter()
.map(|s| s.parse().unwrap())
.collect::<Vec<_>>(),
&PreviewOptions::default(),
)
}
fn assert_rules_safety(
table: &FixSafetyTable,
assertions: &[(&str, Applicability, Applicability)],
) {
for (code, applicability, expected) in assertions {
assert_eq!(
table.resolve_applicability(Rule::from_code(code).unwrap(), *applicability),
*expected
);
}
}
#[test]
fn test_from_rule_selectors_specificity() {
use Applicability::{Safe, Unsafe};
let table = mk_table(&["UP"], &["ALL", "UP001"]);
assert_rules_safety(
&table,
&[
("E101", Safe, Unsafe),
("UP001", Safe, Unsafe),
("UP003", Unsafe, Safe),
],
);
}
#[test]
fn test_from_rule_selectors_unsafe_over_safe() {
use Applicability::{Safe, Unsafe};
let table = mk_table(&["UP"], &["UP"]);
assert_rules_safety(&table, &[("E101", Safe, Safe), ("UP001", Safe, Unsafe)]);
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/settings/types.rs | crates/ruff_linter/src/settings/types.rs | use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use anyhow::{Context, Result, bail};
use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
use log::debug;
use pep440_rs::{VersionSpecifier, VersionSpecifiers};
use ruff_db::diagnostic::DiagnosticFormat;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Deserializer, Serialize, de};
use strum_macros::EnumIter;
use ruff_cache::{CacheKey, CacheKeyHasher};
use ruff_macros::CacheKey;
use ruff_python_ast::{self as ast, PySourceType};
use crate::Applicability;
use crate::registry::RuleSet;
use crate::rule_selector::RuleSelector;
use crate::{display_settings, fs};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, EnumIter)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum PythonVersion {
Py37,
Py38,
Py39,
Py310,
Py311,
Py312,
Py313,
Py314,
}
impl Default for PythonVersion {
fn default() -> Self {
// SAFETY: the unit test `default_python_version_works()` checks that this doesn't panic
Self::try_from(ast::PythonVersion::default()).unwrap()
}
}
impl TryFrom<ast::PythonVersion> for PythonVersion {
type Error = String;
fn try_from(value: ast::PythonVersion) -> Result<Self, Self::Error> {
match value {
ast::PythonVersion::PY37 => Ok(Self::Py37),
ast::PythonVersion::PY38 => Ok(Self::Py38),
ast::PythonVersion::PY39 => Ok(Self::Py39),
ast::PythonVersion::PY310 => Ok(Self::Py310),
ast::PythonVersion::PY311 => Ok(Self::Py311),
ast::PythonVersion::PY312 => Ok(Self::Py312),
ast::PythonVersion::PY313 => Ok(Self::Py313),
ast::PythonVersion::PY314 => Ok(Self::Py314),
_ => Err(format!("unrecognized python version {value}")),
}
}
}
impl From<PythonVersion> for ast::PythonVersion {
fn from(value: PythonVersion) -> Self {
let (major, minor) = value.as_tuple();
Self { major, minor }
}
}
impl From<PythonVersion> for pep440_rs::Version {
fn from(version: PythonVersion) -> Self {
let (major, minor) = version.as_tuple();
Self::new([u64::from(major), u64::from(minor)])
}
}
impl PythonVersion {
pub const fn as_tuple(&self) -> (u8, u8) {
match self {
Self::Py37 => (3, 7),
Self::Py38 => (3, 8),
Self::Py39 => (3, 9),
Self::Py310 => (3, 10),
Self::Py311 => (3, 11),
Self::Py312 => (3, 12),
Self::Py313 => (3, 13),
Self::Py314 => (3, 14),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, CacheKey, is_macro::Is)]
pub enum PreviewMode {
#[default]
Disabled,
Enabled,
}
impl From<bool> for PreviewMode {
fn from(version: bool) -> Self {
if version {
PreviewMode::Enabled
} else {
PreviewMode::Disabled
}
}
}
impl Display for PreviewMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Disabled => write!(f, "disabled"),
Self::Enabled => write!(f, "enabled"),
}
}
}
/// Toggle for unsafe fixes.
/// `Hint` will not apply unsafe fixes but a message will be shown when they are available.
/// `Disabled` will not apply unsafe fixes or show a message.
/// `Enabled` will apply unsafe fixes.
#[derive(Debug, Copy, Clone, CacheKey, Default, PartialEq, Eq, is_macro::Is)]
pub enum UnsafeFixes {
#[default]
Hint,
Disabled,
Enabled,
}
impl Display for UnsafeFixes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Hint => "hint",
Self::Disabled => "disabled",
Self::Enabled => "enabled",
}
)
}
}
impl From<bool> for UnsafeFixes {
fn from(value: bool) -> Self {
if value {
UnsafeFixes::Enabled
} else {
UnsafeFixes::Disabled
}
}
}
impl UnsafeFixes {
pub fn required_applicability(&self) -> Applicability {
match self {
Self::Enabled => Applicability::Unsafe,
Self::Disabled | Self::Hint => Applicability::Safe,
}
}
}
/// Represents a path to be passed to [`Glob::new`].
#[derive(Debug, Clone, CacheKey, PartialEq, PartialOrd, Eq, Ord)]
pub struct GlobPath {
path: PathBuf,
}
impl GlobPath {
/// Constructs a [`GlobPath`] by escaping any glob metacharacters in `root` and normalizing
/// `path` to the escaped `root`.
///
/// See [`fs::normalize_path_to`] for details of the normalization.
pub fn normalize(path: impl AsRef<Path>, root: impl AsRef<Path>) -> Self {
let root = root.as_ref().to_string_lossy();
let escaped = globset::escape(&root);
let absolute = fs::normalize_path_to(path, escaped);
Self { path: absolute }
}
pub fn into_inner(self) -> PathBuf {
self.path
}
}
impl Deref for GlobPath {
type Target = PathBuf;
fn deref(&self) -> &Self::Target {
&self.path
}
}
#[derive(Debug, Clone, CacheKey, PartialEq, PartialOrd, Eq, Ord)]
pub enum FilePattern {
Builtin(&'static str),
User(String, GlobPath),
}
impl FilePattern {
pub fn add_to(self, builder: &mut GlobSetBuilder) -> Result<()> {
match self {
FilePattern::Builtin(pattern) => {
builder.add(Glob::from_str(pattern)?);
}
FilePattern::User(pattern, absolute) => {
// Add the absolute path.
builder.add(Glob::new(&absolute.to_string_lossy())?);
// Add basename path.
if !pattern.contains(std::path::MAIN_SEPARATOR) {
builder.add(Glob::new(&pattern)?);
}
}
}
Ok(())
}
}
impl Display for FilePattern {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{:?}",
match self {
Self::Builtin(pattern) => pattern,
Self::User(pattern, _) => pattern.as_str(),
}
)
}
}
impl FromStr for FilePattern {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::User(
s.to_string(),
GlobPath::normalize(s, fs::get_cwd()),
))
}
}
#[derive(Debug, Clone, Default)]
pub struct FilePatternSet {
set: GlobSet,
cache_key: u64,
// This field is only for displaying the internals
// of `set`.
#[expect(clippy::used_underscore_binding)]
_set_internals: Vec<FilePattern>,
}
impl FilePatternSet {
#[expect(clippy::used_underscore_binding)]
pub fn try_from_iter<I>(patterns: I) -> Result<Self, anyhow::Error>
where
I: IntoIterator<Item = FilePattern>,
{
let mut builder = GlobSetBuilder::new();
let mut hasher = CacheKeyHasher::new();
let mut _set_internals = vec![];
for pattern in patterns {
_set_internals.push(pattern.clone());
pattern.cache_key(&mut hasher);
pattern.add_to(&mut builder)?;
}
let set = builder.build()?;
Ok(FilePatternSet {
set,
cache_key: hasher.finish(),
_set_internals,
})
}
}
impl Display for FilePatternSet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self._set_internals.is_empty() {
write!(f, "[]")?;
} else {
writeln!(f, "[")?;
for pattern in &self._set_internals {
writeln!(f, "\t{pattern},")?;
}
write!(f, "]")?;
}
Ok(())
}
}
impl Deref for FilePatternSet {
type Target = GlobSet;
fn deref(&self) -> &Self::Target {
&self.set
}
}
impl CacheKey for FilePatternSet {
fn cache_key(&self, state: &mut CacheKeyHasher) {
state.write_usize(self.set.len());
state.write_u64(self.cache_key);
}
}
/// A glob pattern and associated data for matching file paths.
#[derive(Debug, Clone)]
pub struct PerFile<T> {
/// The glob pattern used to construct the [`PerFile`].
basename: String,
/// The same pattern as `basename` but normalized to the project root directory.
absolute: GlobPath,
/// Whether the glob pattern should be negated (e.g. `!*.ipynb`)
negated: bool,
/// The per-file data associated with these glob patterns.
data: T,
}
impl<T> PerFile<T> {
/// Construct a new [`PerFile`] from the given glob `pattern` and containing `data`.
///
/// If provided, `project_root` is used to construct a second glob pattern normalized to the
/// project root directory. See [`fs::normalize_path_to`] for more details.
fn new(mut pattern: String, project_root: Option<&Path>, data: T) -> Self {
let negated = pattern.starts_with('!');
if negated {
pattern.drain(..1);
}
let project_root = project_root.unwrap_or(fs::get_cwd());
Self {
absolute: GlobPath::normalize(&pattern, project_root),
basename: pattern,
negated,
data,
}
}
}
/// Per-file ignored linting rules.
///
/// See [`PerFile`] for details of the representation.
#[derive(Debug, Clone)]
pub struct PerFileIgnore(PerFile<RuleSet>);
impl PerFileIgnore {
pub fn new(pattern: String, prefixes: &[RuleSelector], project_root: Option<&Path>) -> Self {
// Rules in preview are included here even if preview mode is disabled; it's safe to ignore
// disabled rules
let rules: RuleSet = prefixes.iter().flat_map(RuleSelector::all_rules).collect();
Self(PerFile::new(pattern, project_root, rules))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PatternPrefixPair {
pub pattern: String,
pub prefix: RuleSelector,
}
impl PatternPrefixPair {
const EXPECTED_PATTERN: &'static str = "<FilePattern>:<RuleCode> pattern";
}
impl<'de> Deserialize<'de> for PatternPrefixPair {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let str_result = String::deserialize(deserializer)?;
Self::from_str(str_result.as_str()).map_err(|_| {
de::Error::invalid_value(
de::Unexpected::Str(str_result.as_str()),
&Self::EXPECTED_PATTERN,
)
})
}
}
impl FromStr for PatternPrefixPair {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (pattern_str, code_string) = {
let tokens = s.split(':').collect::<Vec<_>>();
if tokens.len() != 2 {
bail!("Expected {}", Self::EXPECTED_PATTERN);
}
(tokens[0].trim(), tokens[1].trim())
};
let pattern = pattern_str.into();
let prefix = RuleSelector::from_str(code_string)?;
Ok(Self { pattern, prefix })
}
}
#[derive(
Clone,
Copy,
Debug,
PartialOrd,
Ord,
PartialEq,
Eq,
Default,
Serialize,
Deserialize,
CacheKey,
EnumIter,
)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum Language {
#[default]
Python,
Pyi,
Ipynb,
}
impl FromStr for Language {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"python" => Ok(Self::Python),
"pyi" => Ok(Self::Pyi),
"ipynb" => Ok(Self::Ipynb),
_ => {
bail!("Unrecognized language: `{s}`. Expected one of `python`, `pyi`, or `ipynb`.")
}
}
}
}
impl From<Language> for PySourceType {
fn from(value: Language) -> Self {
match value {
Language::Python => Self::Python,
Language::Ipynb => Self::Ipynb,
Language::Pyi => Self::Stub,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtensionPair {
pub extension: String,
pub language: Language,
}
impl ExtensionPair {
const EXPECTED_PATTERN: &'static str = "<Extension>:<LanguageCode> pattern";
}
impl FromStr for ExtensionPair {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let (extension_str, language_str) = {
let tokens = s.split(':').collect::<Vec<_>>();
if tokens.len() != 2 {
bail!("Expected {}", Self::EXPECTED_PATTERN);
}
(tokens[0].trim(), tokens[1].trim())
};
let extension = extension_str.into();
let language = Language::from_str(language_str)?;
Ok(Self {
extension,
language,
})
}
}
impl From<ExtensionPair> for (String, Language) {
fn from(value: ExtensionPair) -> Self {
(value.extension, value.language)
}
}
#[derive(Debug, Clone, Default, CacheKey)]
pub struct ExtensionMapping(FxHashMap<String, Language>);
impl ExtensionMapping {
/// Return the [`Language`] for the given file.
pub fn get(&self, path: &Path) -> Option<Language> {
let ext = path.extension()?.to_str()?;
self.0.get(ext).copied()
}
}
impl From<FxHashMap<String, Language>> for ExtensionMapping {
fn from(value: FxHashMap<String, Language>) -> Self {
Self(value)
}
}
impl FromIterator<ExtensionPair> for ExtensionMapping {
fn from_iter<T: IntoIterator<Item = ExtensionPair>>(iter: T) -> Self {
Self(
iter.into_iter()
.map(|pair| (pair.extension, pair.language))
.collect(),
)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug, Hash, Default)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum OutputFormat {
Concise,
#[default]
Full,
Json,
JsonLines,
Junit,
Grouped,
Github,
Gitlab,
Pylint,
Rdjson,
Azure,
Sarif,
}
impl OutputFormat {
/// Returns `true` if this format is intended for users to read directly, in contrast to
/// machine-readable or structured formats.
///
/// This can be used to check whether information beyond the diagnostics, such as a header or
/// `Found N diagnostics` footer, should be included.
pub const fn is_human_readable(&self) -> bool {
matches!(
self,
OutputFormat::Full | OutputFormat::Concise | OutputFormat::Grouped
)
}
}
impl Display for OutputFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Concise => write!(f, "concise"),
Self::Full => write!(f, "full"),
Self::Json => write!(f, "json"),
Self::JsonLines => write!(f, "json_lines"),
Self::Junit => write!(f, "junit"),
Self::Grouped => write!(f, "grouped"),
Self::Github => write!(f, "github"),
Self::Gitlab => write!(f, "gitlab"),
Self::Pylint => write!(f, "pylint"),
Self::Rdjson => write!(f, "rdjson"),
Self::Azure => write!(f, "azure"),
Self::Sarif => write!(f, "sarif"),
}
}
}
/// The subset of output formats only implemented in Ruff, not in `ruff_db` via `DisplayDiagnostics`.
pub enum RuffOutputFormat {
Github,
Grouped,
Sarif,
}
impl TryFrom<OutputFormat> for DiagnosticFormat {
type Error = RuffOutputFormat;
fn try_from(format: OutputFormat) -> std::result::Result<Self, Self::Error> {
match format {
OutputFormat::Concise => Ok(DiagnosticFormat::Concise),
OutputFormat::Full => Ok(DiagnosticFormat::Full),
OutputFormat::Json => Ok(DiagnosticFormat::Json),
OutputFormat::JsonLines => Ok(DiagnosticFormat::JsonLines),
OutputFormat::Junit => Ok(DiagnosticFormat::Junit),
OutputFormat::Gitlab => Ok(DiagnosticFormat::Gitlab),
OutputFormat::Pylint => Ok(DiagnosticFormat::Pylint),
OutputFormat::Rdjson => Ok(DiagnosticFormat::Rdjson),
OutputFormat::Azure => Ok(DiagnosticFormat::Azure),
OutputFormat::Github => Err(RuffOutputFormat::Github),
OutputFormat::Grouped => Err(RuffOutputFormat::Grouped),
OutputFormat::Sarif => Err(RuffOutputFormat::Sarif),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(try_from = "String")]
pub struct RequiredVersion(VersionSpecifiers);
impl TryFrom<String> for RequiredVersion {
type Error = pep440_rs::VersionSpecifiersParseError;
fn try_from(value: String) -> Result<Self, Self::Error> {
// Treat `0.3.1` as `==0.3.1`, for backwards compatibility.
if let Ok(version) = pep440_rs::Version::from_str(&value) {
Ok(Self(VersionSpecifiers::from(
VersionSpecifier::equals_version(version),
)))
} else {
Ok(Self(VersionSpecifiers::from_str(&value)?))
}
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for RequiredVersion {
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("RequiredVersion")
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<String as schemars::JsonSchema>::json_schema(generator)
}
}
impl RequiredVersion {
/// Return `true` if the given version is required.
pub fn contains(&self, version: &pep440_rs::Version) -> bool {
self.0.contains(version)
}
}
impl Display for RequiredVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
/// Pattern to match an identifier.
///
/// # Notes
///
/// [`glob::Pattern`] matches a little differently than we ideally want to.
/// Specifically it uses `**` to match an arbitrary number of subdirectories,
/// luckily this not relevant since identifiers don't contains slashes.
///
/// For reference pep8-naming uses
/// [`fnmatch`](https://docs.python.org/3/library/fnmatch.html) for
/// pattern matching.
pub type IdentifierPattern = glob::Pattern;
/// Like [`PerFile`] but with string globs compiled to [`GlobMatcher`]s for more efficient usage.
#[derive(Debug, Clone)]
pub struct CompiledPerFile<T> {
pub absolute_matcher: GlobMatcher,
pub basename_matcher: GlobMatcher,
pub negated: bool,
pub data: T,
}
impl<T> CompiledPerFile<T> {
fn new(
absolute_matcher: GlobMatcher,
basename_matcher: GlobMatcher,
negated: bool,
data: T,
) -> Self {
Self {
absolute_matcher,
basename_matcher,
negated,
data,
}
}
}
impl<T> CacheKey for CompiledPerFile<T>
where
T: CacheKey,
{
fn cache_key(&self, state: &mut CacheKeyHasher) {
self.absolute_matcher.cache_key(state);
self.basename_matcher.cache_key(state);
self.negated.cache_key(state);
self.data.cache_key(state);
}
}
impl<T> Display for CompiledPerFile<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
fields = [
self.absolute_matcher | globmatcher,
self.basename_matcher | globmatcher,
self.negated,
self.data,
]
}
Ok(())
}
}
/// A sequence of [`CompiledPerFile<T>`].
#[derive(Debug, Clone, Default)]
pub struct CompiledPerFileList<T> {
inner: Vec<CompiledPerFile<T>>,
}
impl<T> CacheKey for CompiledPerFileList<T>
where
T: CacheKey,
{
fn cache_key(&self, state: &mut CacheKeyHasher) {
self.inner.cache_key(state);
}
}
impl<T> CompiledPerFileList<T> {
/// Given a list of [`PerFile`] patterns, create a compiled set of globs.
///
/// Returns an error if either of the glob patterns cannot be parsed.
fn resolve(per_file_items: impl IntoIterator<Item = PerFile<T>>) -> Result<Self> {
let inner: Result<Vec<_>> = per_file_items
.into_iter()
.map(|per_file_ignore| {
// Construct absolute path matcher.
let absolute_matcher = Glob::new(&per_file_ignore.absolute.to_string_lossy())
.with_context(|| format!("invalid glob {:?}", per_file_ignore.absolute))?
.compile_matcher();
// Construct basename matcher.
let basename_matcher = Glob::new(&per_file_ignore.basename)
.with_context(|| format!("invalid glob {:?}", per_file_ignore.basename))?
.compile_matcher();
Ok(CompiledPerFile::new(
absolute_matcher,
basename_matcher,
per_file_ignore.negated,
per_file_ignore.data,
))
})
.collect();
Ok(Self { inner: inner? })
}
pub(crate) fn is_empty(&self) -> bool {
self.inner.is_empty()
}
}
impl<T: std::fmt::Debug> CompiledPerFileList<T> {
/// Return an iterator over the entries in `self` that match the input `path`.
///
/// `debug_label` is used for [`debug!`] messages explaining why certain patterns were matched.
pub(crate) fn iter_matches<'a, 'p>(
&'a self,
path: &'p Path,
debug_label: &'static str,
) -> impl Iterator<Item = &'p T>
where
'a: 'p,
{
let file_name = path.file_name().expect("Unable to parse filename");
self.inner.iter().filter_map(move |entry| {
if entry.basename_matcher.is_match(file_name) {
if entry.negated {
None
} else {
debug!(
"{} for {:?} due to basename match on {:?}: {:?}",
debug_label,
path,
entry.basename_matcher.glob().regex(),
entry.data
);
Some(&entry.data)
}
} else if entry.absolute_matcher.is_match(path) {
if entry.negated {
None
} else {
debug!(
"{} for {:?} due to absolute match on {:?}: {:?}",
debug_label,
path,
entry.absolute_matcher.glob().regex(),
entry.data
);
Some(&entry.data)
}
} else if entry.negated {
debug!(
"{} for {:?} due to negated pattern matching neither {:?} nor {:?}: {:?}",
debug_label,
path,
entry.basename_matcher.glob().regex(),
entry.absolute_matcher.glob().regex(),
entry.data
);
Some(&entry.data)
} else {
None
}
})
}
}
impl<T> Display for CompiledPerFileList<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.inner.is_empty() {
write!(f, "{{}}")?;
} else {
writeln!(f, "{{")?;
for value in &self.inner {
writeln!(f, "\t{value}")?;
}
write!(f, "}}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, CacheKey, Default)]
pub struct CompiledPerFileIgnoreList(CompiledPerFileList<RuleSet>);
impl CompiledPerFileIgnoreList {
/// Given a list of [`PerFileIgnore`] patterns, create a compiled set of globs.
///
/// Returns an error if either of the glob patterns cannot be parsed.
pub fn resolve(per_file_ignores: Vec<PerFileIgnore>) -> Result<Self> {
Ok(Self(CompiledPerFileList::resolve(
per_file_ignores.into_iter().map(|ignore| ignore.0),
)?))
}
}
impl Deref for CompiledPerFileIgnoreList {
type Target = CompiledPerFileList<RuleSet>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Display for CompiledPerFileIgnoreList {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
/// Contains the target Python version for a given glob pattern.
///
/// See [`PerFile`] for details of the representation.
#[derive(Debug, Clone)]
pub struct PerFileTargetVersion(PerFile<ast::PythonVersion>);
impl PerFileTargetVersion {
pub fn new(pattern: String, version: ast::PythonVersion, project_root: Option<&Path>) -> Self {
Self(PerFile::new(pattern, project_root, version))
}
}
#[derive(CacheKey, Clone, Debug, Default)]
pub struct CompiledPerFileTargetVersionList(CompiledPerFileList<ast::PythonVersion>);
impl CompiledPerFileTargetVersionList {
/// Given a list of [`PerFileTargetVersion`] patterns, create a compiled set of globs.
///
/// Returns an error if either of the glob patterns cannot be parsed.
pub fn resolve(per_file_versions: Vec<PerFileTargetVersion>) -> Result<Self> {
Ok(Self(CompiledPerFileList::resolve(
per_file_versions.into_iter().map(|version| version.0),
)?))
}
pub fn is_match(&self, path: &Path) -> Option<ast::PythonVersion> {
self.0
.iter_matches(path, "Setting Python version")
.next()
.copied()
}
}
impl Display for CompiledPerFileTargetVersionList {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[cfg(test)]
mod tests {
#[test]
fn default_python_version_works() {
super::PythonVersion::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/settings/mod.rs | crates/ruff_linter/src/settings/mod.rs | //! Effective program settings, taking into account pyproject.toml and
//! command-line options. Structure is optimized for internal usage, as opposed
//! to external visibility or parsing.
use regex::Regex;
use rustc_hash::FxHashSet;
use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use types::CompiledPerFileTargetVersionList;
use crate::codes::RuleCodePrefix;
use ruff_macros::CacheKey;
use ruff_python_ast::PythonVersion;
use crate::line_width::LineLength;
use crate::registry::{Linter, Rule};
use crate::rules::{
flake8_annotations, flake8_bandit, flake8_boolean_trap, flake8_bugbear, flake8_builtins,
flake8_comprehensions, flake8_copyright, flake8_errmsg, flake8_gettext,
flake8_implicit_str_concat, flake8_import_conventions, flake8_pytest_style, flake8_quotes,
flake8_self, flake8_tidy_imports, flake8_type_checking, flake8_unused_arguments, isort, mccabe,
pep8_naming, pycodestyle, pydoclint, pydocstyle, pyflakes, pylint, pyupgrade, ruff,
};
use crate::settings::types::{CompiledPerFileIgnoreList, ExtensionMapping, FilePatternSet};
use crate::{RuleSelector, codes, fs};
use super::line_width::IndentWidth;
use self::fix_safety_table::FixSafetyTable;
use self::rule_table::RuleTable;
use self::types::PreviewMode;
use crate::rule_selector::PreviewOptions;
pub mod fix_safety_table;
pub mod flags;
pub mod rule_table;
pub mod types;
/// `display_settings!` is a macro that can display and format struct fields in a readable,
/// namespaced format. It's particularly useful at generating `Display` implementations
/// for types used in settings.
///
/// # Example
/// ```
/// use std::fmt;
/// use ruff_linter::display_settings;
/// #[derive(Default)]
/// struct Settings {
/// option_a: bool,
/// sub_settings: SubSettings,
/// option_b: String,
/// }
///
/// struct SubSettings {
/// name: String
/// }
///
/// impl Default for SubSettings {
/// fn default() -> Self {
/// Self { name: "Default Name".into() }
/// }
///
/// }
///
/// impl fmt::Display for SubSettings {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// display_settings! {
/// formatter = f,
/// namespace = "sub_settings",
/// fields = [
/// self.name | quoted
/// ]
/// }
/// Ok(())
/// }
///
/// }
///
/// impl fmt::Display for Settings {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// display_settings! {
/// formatter = f,
/// fields = [
/// self.option_a,
/// self.sub_settings | nested,
/// self.option_b | quoted,
/// ]
/// }
/// Ok(())
/// }
///
/// }
///
/// const EXPECTED_OUTPUT: &str = r#"option_a = false
/// sub_settings.name = "Default Name"
/// option_b = ""
/// "#;
///
/// fn main() {
/// let settings = Settings::default();
/// assert_eq!(format!("{settings}"), EXPECTED_OUTPUT);
/// }
/// ```
#[macro_export]
macro_rules! display_settings {
(formatter = $fmt:ident, namespace = $namespace:literal, fields = [$($settings:ident.$field:ident $(| $modifier:tt)?),* $(,)?]) => {
{
const _PREFIX: &str = concat!($namespace, ".");
$(
display_settings!(@field $fmt, _PREFIX, $settings.$field $(| $modifier)?);
)*
}
};
(formatter = $fmt:ident, fields = [$($settings:ident.$field:ident $(| $modifier:tt)?),* $(,)?]) => {
{
const _PREFIX: &str = "";
$(
display_settings!(@field $fmt, _PREFIX, $settings.$field $(| $modifier)?);
)*
}
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | debug) => {
writeln!($fmt, "{}{} = {:?}", $prefix, stringify!($field), $settings.$field)?;
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | path) => {
writeln!($fmt, "{}{} = \"{}\"", $prefix, stringify!($field), $settings.$field.display())?;
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | quoted) => {
writeln!($fmt, "{}{} = \"{}\"", $prefix, stringify!($field), $settings.$field)?;
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | globmatcher) => {
writeln!($fmt, "{}{} = \"{}\"", $prefix, stringify!($field), $settings.$field.glob())?;
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | nested) => {
write!($fmt, "{}", $settings.$field)?;
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | optional) => {
{
write!($fmt, "{}{} = ", $prefix, stringify!($field))?;
match &$settings.$field {
Some(value) => writeln!($fmt, "{}", value)?,
None => writeln!($fmt, "none")?
};
}
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | array) => {
{
write!($fmt, "{}{} = ", $prefix, stringify!($field))?;
if $settings.$field.is_empty() {
writeln!($fmt, "[]")?;
} else {
writeln!($fmt, "[")?;
for elem in &$settings.$field {
writeln!($fmt, "\t{elem},")?;
}
writeln!($fmt, "]")?;
}
}
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | map) => {
{
use itertools::Itertools;
write!($fmt, "{}{} = ", $prefix, stringify!($field))?;
if $settings.$field.is_empty() {
writeln!($fmt, "{{}}")?;
} else {
writeln!($fmt, "{{")?;
for (key, value) in $settings.$field.iter().sorted_by(|(left, _), (right, _)| left.cmp(right)) {
writeln!($fmt, "\t{key} = {value},")?;
}
writeln!($fmt, "}}")?;
}
}
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | set) => {
{
use itertools::Itertools;
write!($fmt, "{}{} = ", $prefix, stringify!($field))?;
if $settings.$field.is_empty() {
writeln!($fmt, "[]")?;
} else {
writeln!($fmt, "[")?;
for elem in $settings.$field.iter().sorted_by(|left, right| left.cmp(right)) {
writeln!($fmt, "\t{elem},")?;
}
writeln!($fmt, "]")?;
}
}
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident | paths) => {
{
write!($fmt, "{}{} = ", $prefix, stringify!($field))?;
if $settings.$field.is_empty() {
writeln!($fmt, "[]")?;
} else {
writeln!($fmt, "[")?;
for elem in &$settings.$field {
writeln!($fmt, "\t\"{}\",", elem.display())?;
}
writeln!($fmt, "]")?;
}
}
};
(@field $fmt:ident, $prefix:ident, $settings:ident.$field:ident) => {
writeln!($fmt, "{}{} = {}", $prefix, stringify!($field), $settings.$field)?;
};
}
#[derive(Debug, Clone, CacheKey)]
#[expect(clippy::struct_excessive_bools)]
pub struct LinterSettings {
pub exclude: FilePatternSet,
pub extension: ExtensionMapping,
pub project_root: PathBuf,
pub rules: RuleTable,
pub per_file_ignores: CompiledPerFileIgnoreList,
pub fix_safety: FixSafetyTable,
/// The non-path-resolved Python version specified by the `target-version` input option.
///
/// If you have a `Checker` available, see its `target_version` method instead.
///
/// Otherwise, see [`LinterSettings::resolve_target_version`] for a way to obtain the Python
/// version for a given file, while respecting the overrides in `per_file_target_version`.
pub unresolved_target_version: TargetVersion,
/// Path-specific overrides to `unresolved_target_version`.
///
/// If you have a `Checker` available, see its `target_version` method instead.
///
/// Otherwise, see [`LinterSettings::resolve_target_version`] for a way to check a given
/// [`Path`] against these patterns, while falling back to `unresolved_target_version` if none
/// of them match.
pub per_file_target_version: CompiledPerFileTargetVersionList,
pub preview: PreviewMode,
pub explicit_preview_rules: bool,
// Rule-specific settings
pub allowed_confusables: FxHashSet<char>,
pub builtins: Vec<String>,
pub dummy_variable_rgx: Regex,
pub external: Vec<String>,
pub ignore_init_module_imports: bool,
pub logger_objects: Vec<String>,
pub namespace_packages: Vec<PathBuf>,
pub src: Vec<PathBuf>,
pub tab_size: IndentWidth,
pub line_length: LineLength,
pub task_tags: Vec<String>,
pub typing_modules: Vec<String>,
pub typing_extensions: bool,
pub future_annotations: bool,
// Plugins
pub flake8_annotations: flake8_annotations::settings::Settings,
pub flake8_bandit: flake8_bandit::settings::Settings,
pub flake8_boolean_trap: flake8_boolean_trap::settings::Settings,
pub flake8_bugbear: flake8_bugbear::settings::Settings,
pub flake8_builtins: flake8_builtins::settings::Settings,
pub flake8_comprehensions: flake8_comprehensions::settings::Settings,
pub flake8_copyright: flake8_copyright::settings::Settings,
pub flake8_errmsg: flake8_errmsg::settings::Settings,
pub flake8_gettext: flake8_gettext::settings::Settings,
pub flake8_implicit_str_concat: flake8_implicit_str_concat::settings::Settings,
pub flake8_import_conventions: flake8_import_conventions::settings::Settings,
pub flake8_pytest_style: flake8_pytest_style::settings::Settings,
pub flake8_quotes: flake8_quotes::settings::Settings,
pub flake8_self: flake8_self::settings::Settings,
pub flake8_tidy_imports: flake8_tidy_imports::settings::Settings,
pub flake8_type_checking: flake8_type_checking::settings::Settings,
pub flake8_unused_arguments: flake8_unused_arguments::settings::Settings,
pub isort: isort::settings::Settings,
pub mccabe: mccabe::settings::Settings,
pub pep8_naming: pep8_naming::settings::Settings,
pub pycodestyle: pycodestyle::settings::Settings,
pub pydoclint: pydoclint::settings::Settings,
pub pydocstyle: pydocstyle::settings::Settings,
pub pyflakes: pyflakes::settings::Settings,
pub pylint: pylint::settings::Settings,
pub pyupgrade: pyupgrade::settings::Settings,
pub ruff: ruff::settings::Settings,
}
impl Display for LinterSettings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "\n# Linter Settings")?;
display_settings! {
formatter = f,
namespace = "linter",
fields = [
self.exclude,
self.project_root | path,
self.rules | nested,
self.per_file_ignores,
self.fix_safety | nested,
self.unresolved_target_version,
self.per_file_target_version,
self.preview,
self.explicit_preview_rules,
self.extension | debug,
self.allowed_confusables | array,
self.builtins | array,
self.dummy_variable_rgx,
self.external | array,
self.ignore_init_module_imports,
self.logger_objects | array,
self.namespace_packages | debug,
self.src | paths,
self.tab_size,
self.line_length,
self.task_tags | array,
self.typing_modules | array,
self.typing_extensions,
]
}
writeln!(f, "\n# Linter Plugins")?;
display_settings! {
formatter = f,
namespace = "linter",
fields = [
self.flake8_annotations | nested,
self.flake8_bandit | nested,
self.flake8_bugbear | nested,
self.flake8_builtins | nested,
self.flake8_comprehensions | nested,
self.flake8_copyright | nested,
self.flake8_errmsg | nested,
self.flake8_gettext | nested,
self.flake8_implicit_str_concat | nested,
self.flake8_import_conventions | nested,
self.flake8_pytest_style | nested,
self.flake8_quotes | nested,
self.flake8_self | nested,
self.flake8_tidy_imports | nested,
self.flake8_type_checking | nested,
self.flake8_unused_arguments | nested,
self.isort | nested,
self.mccabe | nested,
self.pep8_naming | nested,
self.pycodestyle | nested,
self.pyflakes | nested,
self.pylint | nested,
self.pyupgrade | nested,
self.ruff | nested,
]
}
Ok(())
}
}
pub const DEFAULT_SELECTORS: &[RuleSelector] = &[
RuleSelector::Linter(Linter::Pyflakes),
// Only include pycodestyle rules that do not overlap with the formatter
RuleSelector::Prefix {
prefix: RuleCodePrefix::Pycodestyle(codes::Pycodestyle::E4),
redirected_from: None,
},
RuleSelector::Prefix {
prefix: RuleCodePrefix::Pycodestyle(codes::Pycodestyle::E7),
redirected_from: None,
},
RuleSelector::Prefix {
prefix: RuleCodePrefix::Pycodestyle(codes::Pycodestyle::E9),
redirected_from: None,
},
];
pub const TASK_TAGS: &[&str] = &["TODO", "FIXME", "XXX"];
pub static DUMMY_VARIABLE_RGX: LazyLock<Regex> =
LazyLock::new(|| Regex::new("^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$").unwrap());
impl LinterSettings {
pub fn for_rule(rule_code: Rule) -> Self {
Self {
rules: RuleTable::from_iter([rule_code]),
unresolved_target_version: PythonVersion::latest().into(),
..Self::default()
}
}
pub fn for_rules(rules: impl IntoIterator<Item = Rule>) -> Self {
Self {
rules: RuleTable::from_iter(rules),
unresolved_target_version: PythonVersion::latest().into(),
..Self::default()
}
}
pub fn new(project_root: &Path) -> Self {
Self {
exclude: FilePatternSet::default(),
unresolved_target_version: TargetVersion(None),
per_file_target_version: CompiledPerFileTargetVersionList::default(),
project_root: project_root.to_path_buf(),
rules: DEFAULT_SELECTORS
.iter()
.flat_map(|selector| selector.rules(&PreviewOptions::default()))
.collect(),
allowed_confusables: FxHashSet::from_iter([]),
// Needs duplicating
builtins: vec![],
dummy_variable_rgx: DUMMY_VARIABLE_RGX.clone(),
external: vec![],
ignore_init_module_imports: true,
logger_objects: vec![],
namespace_packages: vec![],
per_file_ignores: CompiledPerFileIgnoreList::default(),
fix_safety: FixSafetyTable::default(),
src: vec![fs::get_cwd().to_path_buf(), fs::get_cwd().join("src")],
// Needs duplicating
tab_size: IndentWidth::default(),
line_length: LineLength::default(),
task_tags: TASK_TAGS.iter().map(ToString::to_string).collect(),
typing_modules: vec![],
flake8_annotations: flake8_annotations::settings::Settings::default(),
flake8_bandit: flake8_bandit::settings::Settings::default(),
flake8_boolean_trap: flake8_boolean_trap::settings::Settings::default(),
flake8_bugbear: flake8_bugbear::settings::Settings::default(),
flake8_builtins: flake8_builtins::settings::Settings::default(),
flake8_comprehensions: flake8_comprehensions::settings::Settings::default(),
flake8_copyright: flake8_copyright::settings::Settings::default(),
flake8_errmsg: flake8_errmsg::settings::Settings::default(),
flake8_gettext: flake8_gettext::settings::Settings::default(),
flake8_implicit_str_concat: flake8_implicit_str_concat::settings::Settings::default(),
flake8_import_conventions: flake8_import_conventions::settings::Settings::default(),
flake8_pytest_style: flake8_pytest_style::settings::Settings::default(),
flake8_quotes: flake8_quotes::settings::Settings::default(),
flake8_self: flake8_self::settings::Settings::default(),
flake8_tidy_imports: flake8_tidy_imports::settings::Settings::default(),
flake8_type_checking: flake8_type_checking::settings::Settings::default(),
flake8_unused_arguments: flake8_unused_arguments::settings::Settings::default(),
isort: isort::settings::Settings::default(),
mccabe: mccabe::settings::Settings::default(),
pep8_naming: pep8_naming::settings::Settings::default(),
pycodestyle: pycodestyle::settings::Settings::default(),
pydoclint: pydoclint::settings::Settings::default(),
pydocstyle: pydocstyle::settings::Settings::default(),
pyflakes: pyflakes::settings::Settings::default(),
pylint: pylint::settings::Settings::default(),
pyupgrade: pyupgrade::settings::Settings::default(),
ruff: ruff::settings::Settings::default(),
preview: PreviewMode::default(),
explicit_preview_rules: false,
extension: ExtensionMapping::default(),
typing_extensions: true,
future_annotations: false,
}
}
#[must_use]
pub fn with_target_version(mut self, target_version: PythonVersion) -> Self {
self.unresolved_target_version = target_version.into();
self
}
#[must_use]
pub fn with_preview_mode(mut self) -> Self {
self.preview = PreviewMode::Enabled;
self
}
#[must_use]
pub fn with_external_rules(mut self, rules: &[&str]) -> Self {
self.external
.extend(rules.iter().map(std::string::ToString::to_string));
self
}
/// Resolve the [`TargetVersion`] to use for linting.
///
/// This method respects the per-file version overrides in
/// [`LinterSettings::per_file_target_version`] and falls back on
/// [`LinterSettings::unresolved_target_version`] if none of the override patterns match.
pub fn resolve_target_version(&self, path: &Path) -> TargetVersion {
self.per_file_target_version
.is_match(path)
.map_or(self.unresolved_target_version, TargetVersion::from)
}
}
impl Default for LinterSettings {
fn default() -> Self {
Self::new(fs::get_cwd())
}
}
/// A thin wrapper around `Option<PythonVersion>` to clarify the reason for different `unwrap`
/// calls in various places.
///
/// For example, we want to default to `PythonVersion::latest()` for parsing and detecting semantic
/// syntax errors because this will minimize version-related diagnostics when the Python version is
/// unset. In contrast, we want to default to `PythonVersion::default()` for lint rules. These
/// correspond to the [`TargetVersion::parser_version`] and [`TargetVersion::linter_version`]
/// methods, respectively.
#[derive(Debug, Clone, Copy, CacheKey)]
pub struct TargetVersion(pub Option<PythonVersion>);
impl TargetVersion {
/// Return the [`PythonVersion`] to use for parsing.
///
/// This will be either the Python version specified by the user or the latest supported
/// version if unset.
pub fn parser_version(&self) -> PythonVersion {
self.0.unwrap_or_else(PythonVersion::latest)
}
/// Return the [`PythonVersion`] to use for version-dependent lint rules.
///
/// This will either be the Python version specified by the user or the default Python version
/// if unset.
pub fn linter_version(&self) -> PythonVersion {
self.0.unwrap_or_default()
}
}
impl From<PythonVersion> for TargetVersion {
fn from(value: PythonVersion) -> Self {
Self(Some(value))
}
}
impl Display for TargetVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// manual inlining of display_settings!
match self.0 {
Some(value) => write!(f, "{value}"),
None => f.write_str("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/mod.rs | crates/ruff_linter/src/rules/mod.rs | pub mod airflow;
pub mod eradicate;
pub mod fastapi;
pub mod flake8_2020;
pub mod flake8_annotations;
pub mod flake8_async;
pub mod flake8_bandit;
pub mod flake8_blind_except;
pub mod flake8_boolean_trap;
pub mod flake8_bugbear;
pub mod flake8_builtins;
pub mod flake8_commas;
pub mod flake8_comprehensions;
pub mod flake8_copyright;
pub mod flake8_datetimez;
pub mod flake8_debugger;
pub mod flake8_django;
pub mod flake8_errmsg;
pub mod flake8_executable;
pub mod flake8_fixme;
pub mod flake8_future_annotations;
pub mod flake8_gettext;
pub mod flake8_implicit_str_concat;
pub mod flake8_import_conventions;
pub mod flake8_logging;
pub mod flake8_logging_format;
pub mod flake8_no_pep420;
pub mod flake8_pie;
pub mod flake8_print;
pub mod flake8_pyi;
pub mod flake8_pytest_style;
pub mod flake8_quotes;
pub mod flake8_raise;
pub mod flake8_return;
pub mod flake8_self;
pub mod flake8_simplify;
pub mod flake8_slots;
pub mod flake8_tidy_imports;
pub mod flake8_todos;
pub mod flake8_type_checking;
pub mod flake8_unused_arguments;
pub mod flake8_use_pathlib;
pub mod flynt;
pub mod isort;
pub mod mccabe;
pub mod numpy;
pub mod pandas_vet;
pub mod pep8_naming;
pub mod perflint;
pub mod pycodestyle;
pub mod pydoclint;
pub mod pydocstyle;
pub mod pyflakes;
pub mod pygrep_hooks;
pub mod pylint;
pub mod pyupgrade;
pub mod refurb;
pub mod ruff;
pub mod tryceratops;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/helpers.rs | crates/ruff_linter/src/rules/refurb/helpers.rs | use std::borrow::Cow;
use ruff_python_ast::PythonVersion;
use ruff_python_ast::{self as ast, Expr, name::Name, token::parenthesized_range};
use ruff_python_codegen::Generator;
use ruff_python_semantic::{ResolvedReference, SemanticModel};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::rules::flake8_async::rules::blocking_open_call::is_open_call_from_pathlib;
use crate::{Applicability, Edit, Fix};
/// Format a code snippet to call `name.method()`.
pub(super) fn generate_method_call(name: Name, method: &str, generator: Generator) -> String {
// Construct `name`.
let var = ast::ExprName {
id: name,
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// Construct `name.method`.
let attr = ast::ExprAttribute {
value: Box::new(var.into()),
attr: ast::Identifier::new(method.to_string(), TextRange::default()),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// Make it into a call `name.method()`
let call = ast::ExprCall {
func: Box::new(attr.into()),
arguments: ast::Arguments {
args: Box::from([]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// And finally, turn it into a statement.
let stmt = ast::StmtExpr {
value: Box::new(call.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
generator.stmt(&stmt.into())
}
/// Returns a fix that replace `range` with
/// a generated `a is None`/`a is not None` check.
pub(super) fn replace_with_identity_check(
left: &Expr,
range: TextRange,
negate: bool,
checker: &Checker,
) -> Fix {
let (semantic, generator) = (checker.semantic(), checker.generator());
let op = if negate {
ast::CmpOp::IsNot
} else {
ast::CmpOp::Is
};
let new_expr = Expr::Compare(ast::ExprCompare {
left: left.clone().into(),
ops: [op].into(),
comparators: [ast::ExprNoneLiteral::default().into()].into(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
});
let new_content = generator.expr(&new_expr);
let new_content = if semantic.current_expression_parent().is_some() {
format!("({new_content})")
} else {
new_content
};
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let edit = Edit::range_replacement(new_content, range);
Fix::applicable_edit(edit, applicability)
}
// Helpers for read-whole-file and write-whole-file
#[derive(Debug, Copy, Clone)]
pub(super) enum OpenMode {
/// "r"
ReadText,
/// "rb"
ReadBytes,
/// "w"
WriteText,
/// "wb"
WriteBytes,
}
impl OpenMode {
pub(super) fn pathlib_method(self) -> Name {
match self {
OpenMode::ReadText => Name::new_static("read_text"),
OpenMode::ReadBytes => Name::new_static("read_bytes"),
OpenMode::WriteText => Name::new_static("write_text"),
OpenMode::WriteBytes => Name::new_static("write_bytes"),
}
}
}
/// A grab bag struct that joins together every piece of information we need to track
/// about a file open operation.
#[derive(Debug)]
pub(super) struct FileOpen<'a> {
/// With item where the open happens, we use it for the reporting range.
pub(super) item: &'a ast::WithItem,
/// The file open mode.
pub(super) mode: OpenMode,
/// The file open keywords.
pub(super) keywords: Vec<&'a ast::Keyword>,
/// We only check `open` operations whose file handles are used exactly once.
pub(super) reference: &'a ResolvedReference,
pub(super) argument: OpenArgument<'a>,
}
impl FileOpen<'_> {
/// Determine whether an expression is a reference to the file handle, by comparing
/// their ranges. If two expressions have the same range, they must be the same expression.
pub(super) fn is_ref(&self, expr: &Expr) -> bool {
expr.range() == self.reference.range()
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum OpenArgument<'a> {
/// The filename argument to `open`, e.g. "foo.txt" in:
///
/// ```py
/// f = open("foo.txt")
/// ```
Builtin { filename: &'a Expr },
/// The `Path` receiver of a `pathlib.Path.open` call, e.g. the `p` in the
/// context manager in:
///
/// ```py
/// p = Path("foo.txt")
/// with p.open() as f: ...
/// ```
///
/// or `Path("foo.txt")` in
///
/// ```py
/// with Path("foo.txt").open() as f: ...
/// ```
Pathlib { path: &'a Expr },
}
impl OpenArgument<'_> {
pub(super) fn display<'src>(&self, source: &'src str) -> &'src str {
&source[self.range()]
}
}
impl Ranged for OpenArgument<'_> {
fn range(&self) -> TextRange {
match self {
OpenArgument::Builtin { filename } => filename.range(),
OpenArgument::Pathlib { path } => path.range(),
}
}
}
/// Find and return all `open` operations in the given `with` statement.
pub(super) fn find_file_opens<'a>(
with: &'a ast::StmtWith,
semantic: &'a SemanticModel<'a>,
read_mode: bool,
python_version: PythonVersion,
) -> Vec<FileOpen<'a>> {
with.items
.iter()
.filter_map(|item| {
find_file_open(item, with, semantic, read_mode, python_version)
.or_else(|| find_path_open(item, with, semantic, read_mode, python_version))
})
.collect()
}
fn resolve_file_open<'a>(
item: &'a ast::WithItem,
with: &'a ast::StmtWith,
semantic: &'a SemanticModel<'a>,
read_mode: bool,
mode: OpenMode,
keywords: Vec<&'a ast::Keyword>,
argument: OpenArgument<'a>,
) -> Option<FileOpen<'a>> {
match mode {
OpenMode::ReadText | OpenMode::ReadBytes => {
if !read_mode {
return None;
}
}
OpenMode::WriteText | OpenMode::WriteBytes => {
if read_mode {
return None;
}
}
}
if matches!(mode, OpenMode::ReadBytes | OpenMode::WriteBytes) && !keywords.is_empty() {
return None;
}
let var = item.optional_vars.as_deref()?.as_name_expr()?;
let scope = semantic.current_scope();
let binding = scope.get_all(var.id.as_str()).find_map(|id| {
let b = semantic.binding(id);
(b.range() == var.range()).then_some(b)
})?;
let references: Vec<&ResolvedReference> = binding
.references
.iter()
.map(|id| semantic.reference(*id))
.filter(|reference| with.range().contains_range(reference.range()))
.collect();
let [reference] = references.as_slice() else {
return None;
};
Some(FileOpen {
item,
mode,
keywords,
reference,
argument,
})
}
/// Find `open` operation in the given `with` item.
fn find_file_open<'a>(
item: &'a ast::WithItem,
with: &'a ast::StmtWith,
semantic: &'a SemanticModel<'a>,
read_mode: bool,
python_version: PythonVersion,
) -> Option<FileOpen<'a>> {
// We want to match `open(...) as var`.
let ast::ExprCall {
func,
arguments: ast::Arguments { args, keywords, .. },
..
} = item.context_expr.as_call_expr()?;
// Ignore calls with `*args` and `**kwargs`. In the exact case of `open(*filename, mode="w")`,
// it could be a match; but in all other cases, the call _could_ contain unsupported keyword
// arguments, like `buffering`.
if args.iter().any(Expr::is_starred_expr)
|| keywords.iter().any(|keyword| keyword.arg.is_none())
{
return None;
}
if !semantic.match_builtin_expr(func, "open") {
return None;
}
// Match positional arguments, get filename and mode.
let (filename, pos_mode) = match_open_args(args)?;
// Match keyword arguments, get keyword arguments to forward and possibly mode.
let (keywords, kw_mode) = match_open_keywords(keywords, read_mode, python_version)?;
let mode = kw_mode.unwrap_or(pos_mode);
resolve_file_open(
item,
with,
semantic,
read_mode,
mode,
keywords,
OpenArgument::Builtin { filename },
)
}
fn find_path_open<'a>(
item: &'a ast::WithItem,
with: &'a ast::StmtWith,
semantic: &'a SemanticModel<'a>,
read_mode: bool,
python_version: PythonVersion,
) -> Option<FileOpen<'a>> {
let ast::ExprCall {
func,
arguments: ast::Arguments { args, keywords, .. },
..
} = item.context_expr.as_call_expr()?;
if args.iter().any(Expr::is_starred_expr)
|| keywords.iter().any(|keyword| keyword.arg.is_none())
{
return None;
}
if !is_open_call_from_pathlib(func, semantic) {
return None;
}
let attr = func.as_attribute_expr()?;
let mode = if args.is_empty() {
OpenMode::ReadText
} else {
match_open_mode(args.first()?)?
};
let (keywords, kw_mode) = match_open_keywords(keywords, read_mode, python_version)?;
let mode = kw_mode.unwrap_or(mode);
resolve_file_open(
item,
with,
semantic,
read_mode,
mode,
keywords,
OpenArgument::Pathlib {
path: attr.value.as_ref(),
},
)
}
/// Match positional arguments. Return expression for the file name and open mode.
fn match_open_args(args: &[Expr]) -> Option<(&Expr, OpenMode)> {
match args {
[filename] => Some((filename, OpenMode::ReadText)),
[filename, mode_literal] => match_open_mode(mode_literal).map(|mode| (filename, mode)),
// The third positional argument is `buffering` and the pathlib methods don't support it.
_ => None,
}
}
/// Match keyword arguments. Return keyword arguments to forward and mode.
fn match_open_keywords(
keywords: &[ast::Keyword],
read_mode: bool,
target_version: PythonVersion,
) -> Option<(Vec<&ast::Keyword>, Option<OpenMode>)> {
let mut result: Vec<&ast::Keyword> = vec![];
let mut mode: Option<OpenMode> = None;
for keyword in keywords {
match keyword.arg.as_ref()?.as_str() {
"encoding" | "errors" => result.push(keyword),
"newline" => {
if read_mode {
// newline is only valid for write_text
return None;
} else if target_version < PythonVersion::PY310 {
// `pathlib` doesn't support `newline` until Python 3.10.
return None;
}
result.push(keyword);
}
// This might look bizarre, - why do we re-wrap this optional?
//
// The answer is quite simple, in the result of the current function
// mode being `None` is a possible and correct option meaning that there
// was NO "mode" keyword argument.
//
// The result of `match_open_mode` on the other hand is None
// in the cases when the mode is not compatible with `write_text`/`write_bytes`.
//
// So, here we return None from this whole function if the mode
// is incompatible.
"mode" => mode = Some(match_open_mode(&keyword.value)?),
// All other keywords cannot be directly forwarded.
_ => return None,
}
}
Some((result, mode))
}
/// Match open mode to see if it is supported.
fn match_open_mode(mode: &Expr) -> Option<OpenMode> {
let mode = mode.as_string_literal_expr()?.as_single_part_string()?;
match &*mode.value {
"r" => Some(OpenMode::ReadText),
"rb" => Some(OpenMode::ReadBytes),
"w" => Some(OpenMode::WriteText),
"wb" => Some(OpenMode::WriteBytes),
_ => None,
}
}
/// A helper function that extracts the `iter` from a [`ast::StmtFor`] node and
/// adds parentheses if needed.
///
/// These cases are okay and will not be modified:
///
/// - `for x in z: ...` -> `"z"`
/// - `for x in (y, z): ...` -> `"(y, z)"`
/// - `for x in [y, z]: ...` -> `"[y, z]"`
///
/// While these cases require parentheses:
///
/// - `for x in y, z: ...` -> `"(y, z)"`
/// - `for x in lambda: 0: ...` -> `"(lambda: 0)"`
/// - `for x in (1,) if True else (2,): ...` -> `"((1,) if True else (2,))"`
pub(super) fn parenthesize_loop_iter_if_necessary<'a>(
for_stmt: &'a ast::StmtFor,
checker: &'a Checker,
location: IterLocation,
) -> Cow<'a, str> {
let locator = checker.locator();
let iter = for_stmt.iter.as_ref();
let original_parenthesized_range =
parenthesized_range(iter.into(), for_stmt.into(), checker.tokens());
if let Some(range) = original_parenthesized_range {
return Cow::Borrowed(locator.slice(range));
}
let iter_in_source = locator.slice(iter);
match iter {
Expr::Tuple(tuple) if !tuple.parenthesized => Cow::Owned(format!("({iter_in_source})")),
Expr::Lambda(_) | Expr::If(_) if matches!(location, IterLocation::Comprehension) => {
Cow::Owned(format!("({iter_in_source})"))
}
_ => Cow::Borrowed(iter_in_source),
}
}
#[derive(Copy, Clone)]
pub(super) enum IterLocation {
Call,
Comprehension,
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/mod.rs | crates/ruff_linter/src/rules/refurb/mod.rs | //! Rules from [refurb](https://pypi.org/project/refurb/)/
mod helpers;
pub(crate) mod rules;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use ruff_python_ast::PythonVersion;
use test_case::test_case;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test_case(Rule::ReadWholeFile, Path::new("FURB101_0.py"))]
#[test_case(Rule::ReadWholeFile, Path::new("FURB101_1.py"))]
#[test_case(Rule::RepeatedAppend, Path::new("FURB113.py"))]
#[test_case(Rule::IfExpInsteadOfOrOperator, Path::new("FURB110.py"))]
#[test_case(Rule::ReimplementedOperator, Path::new("FURB118.py"))]
#[test_case(Rule::ForLoopWrites, Path::new("FURB122.py"))]
#[test_case(Rule::ReadlinesInFor, Path::new("FURB129.py"))]
#[test_case(Rule::DeleteFullSlice, Path::new("FURB131.py"))]
#[test_case(Rule::CheckAndRemoveFromSet, Path::new("FURB132.py"))]
#[test_case(Rule::IfExprMinMax, Path::new("FURB136.py"))]
#[test_case(Rule::ReimplementedStarmap, Path::new("FURB140.py"))]
#[test_case(Rule::ForLoopSetMutations, Path::new("FURB142.py"))]
#[test_case(Rule::SliceCopy, Path::new("FURB145.py"))]
#[test_case(Rule::UnnecessaryEnumerate, Path::new("FURB148.py"))]
#[test_case(Rule::MathConstant, Path::new("FURB152.py"))]
#[test_case(Rule::RepeatedGlobal, Path::new("FURB154.py"))]
#[test_case(Rule::HardcodedStringCharset, Path::new("FURB156.py"))]
#[test_case(Rule::VerboseDecimalConstructor, Path::new("FURB157.py"))]
#[test_case(Rule::UnnecessaryFromFloat, Path::new("FURB164.py"))]
#[test_case(Rule::PrintEmptyString, Path::new("FURB105.py"))]
#[test_case(Rule::ImplicitCwd, Path::new("FURB177.py"))]
#[test_case(Rule::SingleItemMembershipTest, Path::new("FURB171_0.py"))]
#[test_case(Rule::SingleItemMembershipTest, Path::new("FURB171_1.py"))]
#[test_case(Rule::BitCount, Path::new("FURB161.py"))]
#[test_case(Rule::IntOnSlicedStr, Path::new("FURB166.py"))]
#[test_case(Rule::RegexFlagAlias, Path::new("FURB167.py"))]
#[test_case(Rule::IsinstanceTypeNone, Path::new("FURB168.py"))]
#[test_case(Rule::TypeNoneComparison, Path::new("FURB169.py"))]
#[test_case(Rule::RedundantLogBase, Path::new("FURB163.py"))]
#[test_case(Rule::MetaClassABCMeta, Path::new("FURB180.py"))]
#[test_case(Rule::HashlibDigestHex, Path::new("FURB181.py"))]
#[test_case(Rule::ListReverseCopy, Path::new("FURB187.py"))]
#[test_case(Rule::WriteWholeFile, Path::new("FURB103_0.py"))]
#[test_case(Rule::WriteWholeFile, Path::new("FURB103_1.py"))]
#[test_case(Rule::FStringNumberFormat, Path::new("FURB116.py"))]
#[test_case(Rule::SortedMinMax, Path::new("FURB192.py"))]
#[test_case(Rule::SliceToRemovePrefixOrSuffix, Path::new("FURB188.py"))]
#[test_case(Rule::SubclassBuiltin, Path::new("FURB189.py"))]
#[test_case(Rule::FromisoformatReplaceZ, Path::new("FURB162.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("refurb").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test]
fn write_whole_file_python_39() -> Result<()> {
let diagnostics = test_path(
Path::new("refurb/FURB103_0.py"),
&settings::LinterSettings::for_rule(Rule::WriteWholeFile)
.with_target_version(PythonVersion::PY39),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
#[test]
fn fstring_number_format_python_311() -> Result<()> {
let diagnostics = test_path(
Path::new("refurb/FURB116.py"),
&settings::LinterSettings::for_rule(Rule::FStringNumberFormat)
.with_target_version(PythonVersion::PY311),
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/type_none_comparison.rs | crates/ruff_linter/src/rules/refurb/rules/type_none_comparison.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, CmpOp, Expr};
use ruff_python_semantic::SemanticModel;
use crate::AlwaysFixableViolation;
use crate::checkers::ast::Checker;
use crate::rules::refurb::helpers::replace_with_identity_check;
/// ## What it does
/// Checks for uses of `type` that compare the type of an object to the type of `None`.
///
/// ## Why is this bad?
/// There is only ever one instance of `None`, so it is more efficient and
/// readable to use the `is` operator to check if an object is `None`.
///
/// ## Example
/// ```python
/// type(obj) is type(None)
/// ```
///
/// Use instead:
/// ```python
/// obj is None
/// ```
///
/// ## Fix safety
/// If the fix might remove comments, it will be marked as unsafe.
///
/// ## References
/// - [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)
/// - [Python documentation: `None`](https://docs.python.org/3/library/constants.html#None)
/// - [Python documentation: `type`](https://docs.python.org/3/library/functions.html#type)
/// - [Python documentation: Identity comparisons](https://docs.python.org/3/reference/expressions.html#is-not)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct TypeNoneComparison {
replacement: IdentityCheck,
}
impl AlwaysFixableViolation for TypeNoneComparison {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"When checking against `None`, use `{}` instead of comparison with `type(None)`",
self.replacement.op()
)
}
fn fix_title(&self) -> String {
format!("Replace with `{} None`", self.replacement.op())
}
}
/// FURB169
pub(crate) fn type_none_comparison(checker: &Checker, compare: &ast::ExprCompare) {
let ([op], [right]) = (&*compare.ops, &*compare.comparators) else {
return;
};
let replacement = match op {
CmpOp::Is | CmpOp::Eq => IdentityCheck::Is,
CmpOp::IsNot | CmpOp::NotEq => IdentityCheck::IsNot,
_ => return,
};
let Some(left_arg) = type_call_arg(&compare.left, checker.semantic()) else {
return;
};
let Some(right_arg) = type_call_arg(right, checker.semantic()) else {
return;
};
let other_arg = match (left_arg, right_arg) {
(Expr::NoneLiteral(_), _) => right_arg,
(_, Expr::NoneLiteral(_)) => left_arg,
_ => return,
};
let negate = replacement == IdentityCheck::IsNot;
let fix = replace_with_identity_check(other_arg, compare.range, negate, checker);
checker
.report_diagnostic(TypeNoneComparison { replacement }, compare.range)
.set_fix(fix);
}
/// Returns the object passed to the function, if the expression is a call to
/// `type` with a single argument.
fn type_call_arg<'a>(expr: &'a Expr, semantic: &'a SemanticModel) -> Option<&'a Expr> {
// The expression must be a single-argument call to `type`.
let ast::ExprCall {
func, arguments, ..
} = expr.as_call_expr()?;
if arguments.len() != 1 {
return None;
}
// The function itself must be the builtin `type`.
if !semantic.match_builtin_expr(func, "type") {
return None;
}
arguments.find_positional(0)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IdentityCheck {
Is,
IsNot,
}
impl IdentityCheck {
fn op(self) -> CmpOp {
match self {
Self::Is => CmpOp::Is,
Self::IsNot => CmpOp::IsNot,
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/if_expr_min_max.rs | crates/ruff_linter/src/rules/refurb/rules/if_expr_min_max.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::{self as ast, CmpOp, Expr};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `if` expressions that can be replaced with `min()` or `max()`
/// calls.
///
/// ## Why is this bad?
/// An `if` expression that selects the lesser or greater of two
/// sub-expressions can be replaced with a `min()` or `max()` call
/// respectively. When possible, prefer `min()` and `max()`, as they're more
/// concise and readable than the equivalent `if` expression.
///
/// ## Example
/// ```python
/// highest_score = score1 if score1 > score2 else score2
/// ```
///
/// Use instead:
/// ```python
/// highest_score = max(score2, score1)
/// ```
///
/// ## References
/// - [Python documentation: `min`](https://docs.python.org/3.11/library/functions.html#min)
/// - [Python documentation: `max`](https://docs.python.org/3.11/library/functions.html#max)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct IfExprMinMax {
min_max: MinMax,
expression: SourceCodeSnippet,
replacement: SourceCodeSnippet,
}
impl Violation for IfExprMinMax {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let Self {
min_max,
expression,
replacement,
} = self;
match (expression.full_display(), replacement.full_display()) {
(_, None) => {
format!("Replace `if` expression with `{min_max}` call")
}
(None, Some(replacement)) => {
format!("Replace `if` expression with `{replacement}`")
}
(Some(expression), Some(replacement)) => {
format!("Replace `{expression}` with `{replacement}`")
}
}
}
fn fix_title(&self) -> Option<String> {
let Self {
replacement,
min_max,
..
} = self;
if let Some(replacement) = replacement.full_display() {
Some(format!("Replace with `{replacement}`"))
} else {
Some(format!("Replace with `{min_max}` call"))
}
}
}
/// FURB136
pub(crate) fn if_expr_min_max(checker: &Checker, if_exp: &ast::ExprIf) {
let Expr::Compare(ast::ExprCompare {
left,
ops,
comparators,
..
}) = if_exp.test.as_ref()
else {
return;
};
// Ignore, e.g., `foo < bar < baz`.
let [op] = &**ops else {
return;
};
// Determine whether to use `min()` or `max()`, and whether to flip the
// order of the arguments, which is relevant for breaking ties.
let (mut min_max, mut flip_args) = match op {
CmpOp::Gt => (MinMax::Max, true),
CmpOp::GtE => (MinMax::Max, false),
CmpOp::Lt => (MinMax::Min, true),
CmpOp::LtE => (MinMax::Min, false),
_ => return,
};
let [right] = &**comparators else {
return;
};
let body_cmp = ComparableExpr::from(if_exp.body.as_ref());
let orelse_cmp = ComparableExpr::from(if_exp.orelse.as_ref());
let left_cmp = ComparableExpr::from(left);
let right_cmp = ComparableExpr::from(right);
if body_cmp == right_cmp && orelse_cmp == left_cmp {
min_max = min_max.reverse();
flip_args = !flip_args;
} else if body_cmp != left_cmp || orelse_cmp != right_cmp {
return;
}
let (arg1, arg2) = if flip_args {
(right, left.as_ref())
} else {
(left.as_ref(), right)
};
let replacement = format!(
"{min_max}({}, {})",
checker.generator().expr(arg1),
checker.generator().expr(arg2),
);
let mut diagnostic = checker.report_diagnostic(
IfExprMinMax {
min_max,
expression: SourceCodeSnippet::from_str(checker.locator().slice(if_exp)),
replacement: SourceCodeSnippet::from_str(replacement.as_str()),
},
if_exp.range(),
);
if checker.semantic().has_builtin_binding(min_max.as_str()) {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
replacement,
if_exp.range(),
)));
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum MinMax {
Min,
Max,
}
impl MinMax {
#[must_use]
const fn reverse(self) -> Self {
match self {
Self::Min => Self::Max,
Self::Max => Self::Min,
}
}
#[must_use]
const fn as_str(self) -> &'static str {
match self {
Self::Min => "min",
Self::Max => "max",
}
}
}
impl std::fmt::Display for MinMax {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(fmt, "{}", 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/refurb/rules/bit_count.rs | crates/ruff_linter/src/rules/refurb/rules/bit_count.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::PythonVersion;
use ruff_python_ast::{self as ast, Expr, ExprAttribute, ExprCall};
use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
/// ## What it does
/// Checks for uses of `bin(...).count("1")` to perform a population count.
///
/// ## Why is this bad?
/// In Python 3.10, a `bit_count()` method was added to the `int` class,
/// which is more concise and efficient than converting to a binary
/// representation via `bin(...)`.
///
/// ## Example
/// ```python
/// x = bin(123).count("1")
/// y = bin(0b1111011).count("1")
/// ```
///
/// Use instead:
/// ```python
/// x = (123).bit_count()
/// y = 0b1111011.bit_count()
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe unless the argument to `bin` can be inferred as
/// an instance of a type that implements the `__index__` and `bit_count` methods because this can
/// change the exception raised at runtime for an invalid argument.
///
/// ## Options
/// - `target-version`
///
/// ## References
/// - [Python documentation:`int.bit_count`](https://docs.python.org/3/library/stdtypes.html#int.bit_count)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct BitCount {
existing: SourceCodeSnippet,
replacement: SourceCodeSnippet,
}
impl AlwaysFixableViolation for BitCount {
#[derive_message_formats]
fn message(&self) -> String {
let BitCount { existing, .. } = self;
let existing = existing.truncated_display();
format!("Use of `bin({existing}).count('1')`")
}
fn fix_title(&self) -> String {
let BitCount { replacement, .. } = self;
if let Some(replacement) = replacement.full_display() {
format!("Replace with `{replacement}`")
} else {
"Replace with `.bit_count()`".to_string()
}
}
}
/// FURB161
pub(crate) fn bit_count(checker: &Checker, call: &ExprCall) {
// `int.bit_count()` was added in Python 3.10
if checker.target_version() < PythonVersion::PY310 {
return;
}
let Expr::Attribute(ExprAttribute { attr, value, .. }) = call.func.as_ref() else {
return;
};
// Ensure that we're performing a `.count(...)`.
if attr.as_str() != "count" {
return;
}
if !call.arguments.keywords.is_empty() {
return;
}
let [arg] = &*call.arguments.args else {
return;
};
let Expr::StringLiteral(ast::ExprStringLiteral {
value: count_value, ..
}) = arg
else {
return;
};
// Ensure that we're performing a `.count("1")`.
if count_value != "1" {
return;
}
let Expr::Call(ExprCall {
func, arguments, ..
}) = value.as_ref()
else {
return;
};
if !arguments.keywords.is_empty() {
return;
}
let [arg] = &*arguments.args else {
return;
};
// Ensure that we're performing a `bin(...)`.
if !checker.semantic().match_builtin_expr(func, "bin") {
return;
}
// If is a starred expression, it returns.
if arg.is_starred_expr() {
return;
}
// Extract, e.g., `x` in `bin(x)`.
let literal_text = checker.locator().slice(arg);
// If we're calling a method on an integer, or an expression with lower precedence, parenthesize
// it.
let parenthesize = match arg {
Expr::NumberLiteral(ast::ExprNumberLiteral { .. }) => {
let mut chars = literal_text.chars();
!matches!(
(chars.next(), chars.next()),
(Some('0'), Some('b' | 'B' | 'x' | 'X' | 'o' | 'O'))
)
}
Expr::StringLiteral(inner) => inner.value.is_implicit_concatenated(),
Expr::BytesLiteral(inner) => inner.value.is_implicit_concatenated(),
Expr::FString(inner) => inner.value.is_implicit_concatenated(),
Expr::TString(inner) => inner.value.is_implicit_concatenated(),
Expr::Await(_)
| Expr::Starred(_)
| Expr::UnaryOp(_)
| Expr::BinOp(_)
| Expr::BoolOp(_)
| Expr::If(_)
| Expr::Named(_)
| Expr::Lambda(_)
| Expr::Slice(_)
| Expr::Yield(_)
| Expr::YieldFrom(_)
| Expr::Name(_)
| Expr::List(_)
| Expr::Compare(_)
| Expr::Tuple(_)
| Expr::Generator(_)
| Expr::IpyEscapeCommand(_) => true,
Expr::Call(_)
| Expr::Dict(_)
| Expr::Set(_)
| Expr::ListComp(_)
| Expr::SetComp(_)
| Expr::DictComp(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_)
| Expr::Attribute(_)
| Expr::Subscript(_) => false,
};
// check if the fix is safe or not
let applicability: Applicability = match ResolvedPythonType::from(arg) {
ResolvedPythonType::Atom(PythonType::Number(NumberLike::Integer | NumberLike::Bool)) => {
Applicability::Safe
}
_ => Applicability::Unsafe,
};
let replacement = if parenthesize {
format!("({literal_text}).bit_count()")
} else {
format!("{literal_text}.bit_count()")
};
let mut diagnostic = checker.report_diagnostic(
BitCount {
existing: SourceCodeSnippet::from_str(literal_text),
replacement: SourceCodeSnippet::new(replacement.clone()),
},
call.range(),
);
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(replacement, call.range()),
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/refurb/rules/repeated_global.rs | crates/ruff_linter/src/rules/refurb/rules/repeated_global.rs | use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Stmt;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for consecutive `global` (or `nonlocal`) statements.
///
/// ## Why is this bad?
/// The `global` and `nonlocal` keywords accepts multiple comma-separated names.
/// Instead of using multiple `global` (or `nonlocal`) statements for separate
/// variables, you can use a single statement to declare multiple variables at
/// once.
///
/// ## Example
/// ```python
/// def func():
/// global x
/// global y
///
/// print(x, y)
/// ```
///
/// Use instead:
/// ```python
/// def func():
/// global x, y
///
/// print(x, y)
/// ```
///
/// ## References
/// - [Python documentation: the `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement)
/// - [Python documentation: the `nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.4.9")]
pub(crate) struct RepeatedGlobal {
global_kind: GlobalKind,
}
impl AlwaysFixableViolation for RepeatedGlobal {
#[derive_message_formats]
fn message(&self) -> String {
format!("Use of repeated consecutive `{}`", self.global_kind)
}
fn fix_title(&self) -> String {
format!("Merge `{}` statements", self.global_kind)
}
}
/// FURB154
pub(crate) fn repeated_global(checker: &Checker, mut suite: &[Stmt]) {
while let Some(idx) = suite
.iter()
.position(|stmt| GlobalKind::from_stmt(stmt).is_some())
{
let global_kind = GlobalKind::from_stmt(&suite[idx]).unwrap();
suite = &suite[idx..];
// Collect until we see a non-`global` (or non-`nonlocal`) statement.
let (globals_sequence, next_suite) = suite.split_at(
suite
.iter()
.position(|stmt| GlobalKind::from_stmt(stmt) != Some(global_kind))
.unwrap_or(suite.len()),
);
// If there are at least two consecutive `global` (or `nonlocal`) statements, raise a
// diagnostic.
if let [first, .., last] = globals_sequence {
let range = first.range().cover(last.range());
checker
.report_diagnostic(RepeatedGlobal { global_kind }, range)
.set_fix(Fix::safe_edit(Edit::range_replacement(
format!(
"{global_kind} {}",
globals_sequence
.iter()
.flat_map(|stmt| match stmt {
Stmt::Global(stmt) => &stmt.names,
Stmt::Nonlocal(stmt) => &stmt.names,
_ => unreachable!(),
})
.map(ruff_python_ast::Identifier::id)
.format(", ")
),
range,
)));
}
suite = next_suite;
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum GlobalKind {
Global,
NonLocal,
}
impl GlobalKind {
fn from_stmt(stmt: &Stmt) -> Option<Self> {
match stmt {
Stmt::Global(_) => Some(GlobalKind::Global),
Stmt::Nonlocal(_) => Some(GlobalKind::NonLocal),
_ => None,
}
}
}
impl std::fmt::Display for GlobalKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GlobalKind::Global => write!(f, "global"),
GlobalKind::NonLocal => write!(f, "nonlocal"),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/redundant_log_base.rs | crates/ruff_linter/src/rules/refurb/rules/redundant_log_base.rs | use anyhow::Result;
use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{self as ast, Expr, Number};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `math.log` calls with a redundant base.
///
/// ## Why is this bad?
/// The default base of `math.log` is `e`, so specifying it explicitly is
/// redundant.
///
/// Instead of passing 2 or 10 as the base, use `math.log2` or `math.log10`
/// respectively, as these dedicated variants are typically more accurate
/// than `math.log`.
///
/// ## Example
/// ```python
/// import math
///
/// math.log(4, math.e)
/// math.log(4, 2)
/// math.log(4, 10)
/// ```
///
/// Use instead:
/// ```python
/// import math
///
/// math.log(4)
/// math.log2(4)
/// math.log10(4)
/// ```
///
/// ## Fix safety
/// This fix is marked unsafe when the argument is a starred expression, as this changes
/// the call semantics and may raise runtime errors. It is also unsafe if comments are
/// present within the call, as they will be removed. Additionally, `math.log(x, base)`
/// and `math.log2(x)` / `math.log10(x)` may differ due to floating-point rounding, so
/// the fix is also unsafe when making this transformation.
///
/// ## References
/// - [Python documentation: `math.log`](https://docs.python.org/3/library/math.html#math.log)
/// - [Python documentation: `math.log2`](https://docs.python.org/3/library/math.html#math.log2)
/// - [Python documentation: `math.log10`](https://docs.python.org/3/library/math.html#math.log10)
/// - [Python documentation: `math.e`](https://docs.python.org/3/library/math.html#math.e)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct RedundantLogBase {
base: Base,
arg: String,
}
impl Violation for RedundantLogBase {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let RedundantLogBase { base, arg } = self;
let log_function = base.to_log_function();
format!("Prefer `math.{log_function}({arg})` over `math.log` with a redundant base")
}
fn fix_title(&self) -> Option<String> {
let RedundantLogBase { base, arg } = self;
let log_function = base.to_log_function();
Some(format!("Replace with `math.{log_function}({arg})`"))
}
}
/// FURB163
pub(crate) fn redundant_log_base(checker: &Checker, call: &ast::ExprCall) {
if !call.arguments.keywords.is_empty() {
return;
}
let [arg, base] = &*call.arguments.args else {
return;
};
if !checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["math", "log"]))
{
return;
}
let base = if is_number_literal(base, 2) {
Base::Two
} else if is_number_literal(base, 10) {
Base::Ten
} else if checker
.semantic()
.resolve_qualified_name(base)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["math", "e"]))
{
Base::E
} else {
return;
};
let mut diagnostic = checker.report_diagnostic(
RedundantLogBase {
base,
arg: checker.locator().slice(arg).into(),
},
call.range(),
);
diagnostic.try_set_fix(|| generate_fix(checker, call, base, arg));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Base {
E,
Two,
Ten,
}
impl Base {
fn to_log_function(self) -> &'static str {
match self {
Base::E => "log",
Base::Two => "log2",
Base::Ten => "log10",
}
}
}
fn is_number_literal(expr: &Expr, value: i8) -> bool {
if let Expr::NumberLiteral(number_literal) = expr {
if let Number::Int(number) = &number_literal.value {
return number.as_i8().is_some_and(|number| number == value);
} else if let Number::Float(number) = number_literal.value {
#[expect(clippy::float_cmp)]
return number == f64::from(value);
}
}
false
}
fn generate_fix(checker: &Checker, call: &ast::ExprCall, base: Base, arg: &Expr) -> Result<Fix> {
let (edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("math", base.to_log_function()),
call.start(),
checker.semantic(),
)?;
let arg_range =
parenthesized_range(arg.into(), call.into(), checker.tokens()).unwrap_or(arg.range());
let arg_str = checker.locator().slice(arg_range);
Ok(Fix::applicable_edits(
Edit::range_replacement(format!("{binding}({arg_str})"), call.range()),
[edit],
if (matches!(base, Base::Two | Base::Ten))
|| arg.is_starred_expr()
|| 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/refurb/rules/single_item_membership_test.rs | crates/ruff_linter/src/rules/refurb/rules/single_item_membership_test.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::generate_comparison;
use ruff_python_ast::{self as ast, CmpOp, Expr, ExprStringLiteral};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for membership tests against single-item containers.
///
/// ## Why is this bad?
/// Performing a membership test against a container (like a `list` or `set`)
/// with a single item is less readable and less efficient than comparing
/// against the item directly.
///
/// ## Example
/// ```python
/// 1 in [1]
/// ```
///
/// Use instead:
/// ```python
/// 1 == 1
/// ```
///
/// ## Fix safety
/// The fix is always marked as unsafe.
///
/// When the right-hand side is a string, this fix can change the behavior of your program.
/// This is because `c in "a"` is true both when `c` is `"a"` and when `c` is the empty string.
///
/// Additionally, converting `in`/`not in` against a single-item container to `==`/`!=` can
/// change runtime behavior: `in` may consider identity (e.g., `NaN`) and always
/// yields a `bool`.
///
/// Comments within the replacement range will also be removed.
///
/// ## References
/// - [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)
/// - [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.1.0")]
pub(crate) struct SingleItemMembershipTest {
membership_test: MembershipTest,
}
impl Violation for SingleItemMembershipTest {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Membership test against single-item container".to_string()
}
fn fix_title(&self) -> Option<String> {
let SingleItemMembershipTest { membership_test } = self;
match membership_test {
MembershipTest::In => Some("Convert to equality test".to_string()),
MembershipTest::NotIn => Some("Convert to inequality test".to_string()),
}
}
}
/// FURB171
pub(crate) fn single_item_membership_test(
checker: &Checker,
expr: &Expr,
left: &Expr,
ops: &[CmpOp],
comparators: &[Expr],
) {
let ([op], [right]) = (ops, comparators) else {
return;
};
// Ensure that the comparison is a membership test.
let membership_test = match op {
CmpOp::In => MembershipTest::In,
CmpOp::NotIn => MembershipTest::NotIn,
_ => return,
};
// Check if the right-hand side is a single-item object
let Some(item) = single_item(right, checker.semantic()) else {
return;
};
let edit = Edit::range_replacement(
pad(
generate_comparison(
left,
&[membership_test.replacement_op()],
std::slice::from_ref(item),
expr.into(),
checker.tokens(),
checker.source(),
),
expr.range(),
checker.locator(),
),
expr.range(),
);
// All supported cases can change runtime behavior; mark as unsafe.
let fix = Fix::unsafe_edit(edit);
checker
.report_diagnostic(SingleItemMembershipTest { membership_test }, expr.range())
.set_fix(fix);
}
/// Return the single item wrapped in `Some` if the expression contains a single
/// item, otherwise return `None`.
fn single_item<'a>(expr: &'a Expr, semantic: &'a SemanticModel) -> Option<&'a Expr> {
match expr {
Expr::List(ast::ExprList { elts, .. })
| Expr::Tuple(ast::ExprTuple { elts, .. })
| Expr::Set(ast::ExprSet { elts, .. }) => match elts.as_slice() {
[Expr::Starred(_)] => None,
[item] => Some(item),
_ => None,
},
Expr::Call(ast::ExprCall {
func,
arguments,
range: _,
node_index: _,
}) => {
if arguments.len() != 1 || !is_set_method(func, semantic) {
return None;
}
arguments
.find_positional(0)
.and_then(|arg| single_item(arg, semantic))
}
string_expr @ Expr::StringLiteral(ExprStringLiteral { value: string, .. })
if string.chars().count() == 1 =>
{
Some(string_expr)
}
_ => None,
}
}
fn is_set_method(func: &Expr, semantic: &SemanticModel) -> bool {
["set", "frozenset"]
.iter()
.any(|s| semantic.match_builtin_expr(func, s))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MembershipTest {
/// Ex) `1 in [1]`
In,
/// Ex) `1 not in [1]`
NotIn,
}
impl MembershipTest {
/// Returns the replacement comparison operator for this membership test.
fn replacement_op(self) -> CmpOp {
match self {
MembershipTest::In => CmpOp::Eq,
MembershipTest::NotIn => CmpOp::NotEq,
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/fromisoformat_replace_z.rs | crates/ruff_linter/src/rules/refurb/rules/fromisoformat_replace_z.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{
Expr, ExprAttribute, ExprBinOp, ExprCall, ExprStringLiteral, ExprSubscript, ExprUnaryOp,
Number, Operator, PythonVersion, UnaryOp,
};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for `datetime.fromisoformat()` calls
/// where the only argument is an inline replacement
/// of `Z` with a zero offset timezone.
///
/// ## Why is this bad?
/// On Python 3.11 and later, `datetime.fromisoformat()` can handle most [ISO 8601][iso-8601]
/// formats including ones affixed with `Z`, so such an operation is unnecessary.
///
/// More information on unsupported formats
/// can be found in [the official documentation][fromisoformat].
///
/// ## Example
///
/// ```python
/// from datetime import datetime
///
///
/// date = "2025-01-01T00:00:00Z"
///
/// datetime.fromisoformat(date.replace("Z", "+00:00"))
/// datetime.fromisoformat(date[:-1] + "-00")
/// datetime.fromisoformat(date.strip("Z", "-0000"))
/// datetime.fromisoformat(date.rstrip("Z", "-00:00"))
/// ```
///
/// Use instead:
///
/// ```python
/// from datetime import datetime
///
///
/// date = "2025-01-01T00:00:00Z"
///
/// datetime.fromisoformat(date)
/// ```
///
/// ## Fix safety
/// The fix is always marked as unsafe,
/// as it might change the program's behaviour.
///
/// For example, working code might become non-working:
///
/// ```python
/// d = "Z2025-01-01T00:00:00Z" # Note the leading `Z`
///
/// datetime.fromisoformat(d.strip("Z") + "+00:00") # Fine
/// datetime.fromisoformat(d) # Runtime error
/// ```
///
/// ## References
/// * [Whatβs New In Python 3.11 § `datetime`](https://docs.python.org/3/whatsnew/3.11.html#datetime)
/// * [`fromisoformat`](https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat)
///
/// [iso-8601]: https://www.iso.org/obp/ui/#iso:std:iso:8601
/// [fromisoformat]: https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct FromisoformatReplaceZ;
impl AlwaysFixableViolation for FromisoformatReplaceZ {
#[derive_message_formats]
fn message(&self) -> String {
r#"Unnecessary timezone replacement with zero offset"#.to_string()
}
fn fix_title(&self) -> String {
"Remove `.replace()` call".to_string()
}
}
/// FURB162
pub(crate) fn fromisoformat_replace_z(checker: &Checker, call: &ExprCall) {
if checker.target_version() < PythonVersion::PY311 {
return;
}
let (func, arguments) = (&*call.func, &call.arguments);
if !arguments.keywords.is_empty() {
return;
}
let [argument] = &*arguments.args else {
return;
};
if !func_is_fromisoformat(func, checker.semantic()) {
return;
}
let Some(replace_time_zone) = ReplaceTimeZone::from_expr(argument) else {
return;
};
if !is_zero_offset_timezone(replace_time_zone.zero_offset.value.to_str()) {
return;
}
let value_full_range = parenthesized_range(
replace_time_zone.date.into(),
replace_time_zone.parent.into(),
checker.tokens(),
)
.unwrap_or(replace_time_zone.date.range());
let range_to_remove = TextRange::new(value_full_range.end(), argument.end());
let fix = Fix::unsafe_edit(Edit::range_deletion(range_to_remove));
checker
.report_diagnostic(FromisoformatReplaceZ, argument.range())
.set_fix(fix);
}
fn func_is_fromisoformat(func: &Expr, semantic: &SemanticModel) -> bool {
semantic
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["datetime", "datetime", "fromisoformat"]
)
})
}
/// A `datetime.replace` call that replaces the timezone with a zero offset.
struct ReplaceTimeZone<'a> {
/// The date expression
date: &'a Expr,
/// The `date` expression's parent.
parent: &'a Expr,
/// The zero offset string literal
zero_offset: &'a ExprStringLiteral,
}
impl<'a> ReplaceTimeZone<'a> {
fn from_expr(expr: &'a Expr) -> Option<Self> {
match expr {
Expr::Call(call) => Self::from_call(call),
Expr::BinOp(bin_op) => Self::from_bin_op(bin_op),
_ => None,
}
}
/// Returns `Some` if the call expression is a call to `str.replace` and matches `date.replace("Z", "+00:00")`
fn from_call(call: &'a ExprCall) -> Option<Self> {
let arguments = &call.arguments;
if !arguments.keywords.is_empty() {
return None;
}
let ExprAttribute { value, attr, .. } = call.func.as_attribute_expr()?;
if attr != "replace" {
return None;
}
let [z, Expr::StringLiteral(zero_offset)] = &*arguments.args else {
return None;
};
if !is_upper_case_z_string(z) {
return None;
}
Some(Self {
date: &**value,
parent: &*call.func,
zero_offset,
})
}
/// Returns `Some` for binary expressions matching `date[:-1] + "-00"` or
/// `date.strip("Z") + "+00"`
fn from_bin_op(bin_op: &'a ExprBinOp) -> Option<Self> {
let ExprBinOp {
left, op, right, ..
} = bin_op;
if *op != Operator::Add {
return None;
}
let (date, parent) = match &**left {
Expr::Call(call) => strip_z_date(call)?,
Expr::Subscript(subscript) => (slice_minus_1_date(subscript)?, &**left),
_ => return None,
};
Some(Self {
date,
parent,
zero_offset: right.as_string_literal_expr()?,
})
}
}
/// Returns `Some` if `call` is a call to `date.strip("Z")`.
///
/// It returns the value of the `date` argument and its parent.
fn strip_z_date(call: &ExprCall) -> Option<(&Expr, &Expr)> {
let ExprCall {
func, arguments, ..
} = call;
let Expr::Attribute(ExprAttribute { value, attr, .. }) = &**func else {
return None;
};
if !matches!(attr.as_str(), "strip" | "rstrip") {
return None;
}
if !arguments.keywords.is_empty() {
return None;
}
let [z] = &*arguments.args else {
return None;
};
if !is_upper_case_z_string(z) {
return None;
}
Some((value, func))
}
/// Returns `Some` if this is a subscript with the form `date[:-1] + "-00"`.
fn slice_minus_1_date(subscript: &ExprSubscript) -> Option<&Expr> {
let ExprSubscript { value, slice, .. } = subscript;
let slice = slice.as_slice_expr()?;
if slice.lower.is_some() || slice.step.is_some() {
return None;
}
let Some(ExprUnaryOp {
operand,
op: UnaryOp::USub,
..
}) = slice.upper.as_ref()?.as_unary_op_expr()
else {
return None;
};
let Number::Int(int) = &operand.as_number_literal_expr()?.value else {
return None;
};
if *int != 1 {
return None;
}
Some(value)
}
fn is_upper_case_z_string(expr: &Expr) -> bool {
expr.as_string_literal_expr()
.is_some_and(|string| string.value.to_str() == "Z")
}
fn is_zero_offset_timezone(value: &str) -> bool {
matches!(
value,
"+00:00" | "+0000" | "+00" | "-00:00" | "-0000" | "-00"
)
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/int_on_sliced_str.rs | crates/ruff_linter/src/rules/refurb/rules/int_on_sliced_str.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprCall, Identifier};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `int` with an explicit base in which a string expression
/// is stripped of its leading prefix (i.e., `0b`, `0o`, or `0x`).
///
/// ## Why is this bad?
/// Given an integer string with a prefix (e.g., `0xABC`), Python can automatically
/// determine the base of the integer by the prefix without needing to specify
/// it explicitly.
///
/// Instead of `int(num[2:], 16)`, use `int(num, 0)`, which will automatically
/// deduce the base based on the prefix.
///
/// ## Example
/// ```python
/// num = "0xABC"
///
/// if num.startswith("0b"):
/// i = int(num[2:], 2)
/// elif num.startswith("0o"):
/// i = int(num[2:], 8)
/// elif num.startswith("0x"):
/// i = int(num[2:], 16)
///
/// print(i)
/// ```
///
/// Use instead:
/// ```python
/// num = "0xABC"
///
/// i = int(num, 0)
///
/// print(i)
/// ```
///
/// ## Fix safety
/// The rule's fix is marked as unsafe, as Ruff cannot guarantee that the
/// argument to `int` will remain valid when its base is included in the
/// function call.
///
/// ## References
/// - [Python documentation: `int`](https://docs.python.org/3/library/functions.html#int)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct IntOnSlicedStr {
base: u8,
}
impl AlwaysFixableViolation for IntOnSlicedStr {
#[derive_message_formats]
fn message(&self) -> String {
let IntOnSlicedStr { base } = self;
format!("Use of `int` with explicit `base={base}` after removing prefix")
}
fn fix_title(&self) -> String {
"Replace with `base=0`".to_string()
}
}
/// FURB166
pub(crate) fn int_on_sliced_str(checker: &Checker, call: &ExprCall) {
// Verify that the function is `int`.
if !checker.semantic().match_builtin_expr(&call.func, "int") {
return;
}
// There must be exactly two arguments (e.g., `int(num[2:], 16)`).
let (expression, base) = match (
call.arguments.args.as_ref(),
call.arguments.keywords.as_ref(),
) {
([expression], [base]) if base.arg.as_ref().map(Identifier::as_str) == Some("base") => {
(expression, &base.value)
}
([expression, base], []) => (expression, base),
_ => {
return;
}
};
// The base must be a number literal with a value of 2, 8, or 16.
let Some(base_u8) = base
.as_number_literal_expr()
.and_then(|base| base.value.as_int())
.and_then(ruff_python_ast::Int::as_u8)
else {
return;
};
if !matches!(base_u8, 2 | 8 | 16) {
return;
}
// Determine whether the expression is a slice of a string (e.g., `num[2:]`).
let Expr::Subscript(expr_subscript) = expression else {
return;
};
let Expr::Slice(expr_slice) = expr_subscript.slice.as_ref() else {
return;
};
if expr_slice.upper.is_some() || expr_slice.step.is_some() {
return;
}
if expr_slice
.lower
.as_ref()
.and_then(|expr| expr.as_number_literal_expr())
.and_then(|expr| expr.value.as_int())
.is_none_or(|expr| expr.as_u8() != Some(2))
{
return;
}
let mut diagnostic = checker.report_diagnostic(IntOnSlicedStr { base: base_u8 }, call.range());
diagnostic.set_fix(Fix::unsafe_edits(
Edit::range_replacement(
checker.locator().slice(&*expr_subscript.value).to_string(),
expression.range(),
),
[Edit::range_replacement("0".to_string(), base.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/refurb/rules/subclass_builtin.rs | crates/ruff_linter/src/rules/refurb/rules/subclass_builtin.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Arguments, StmtClassDef, helpers::map_subscript};
use ruff_text_size::Ranged;
use crate::{AlwaysFixableViolation, Edit, Fix};
use crate::{checkers::ast::Checker, importer::ImportRequest};
/// ## What it does
/// Checks for subclasses of `dict`, `list` or `str`.
///
/// ## Why is this bad?
/// Built-in types don't consistently use their own dunder methods. For example,
/// `dict.__init__` and `dict.update()` bypass `__setitem__`, making inheritance unreliable.
///
/// Use the `UserDict`, `UserList`, and `UserString` objects from the `collections` module
/// instead.
///
/// ## Example
///
/// ```python
/// class UppercaseDict(dict):
/// def __setitem__(self, key, value):
/// super().__setitem__(key.upper(), value)
///
///
/// d = UppercaseDict({"a": 1, "b": 2}) # Bypasses __setitem__
/// print(d) # {'a': 1, 'b': 2}
/// ```
///
/// Use instead:
///
/// ```python
/// from collections import UserDict
///
///
/// class UppercaseDict(UserDict):
/// def __setitem__(self, key, value):
/// super().__setitem__(key.upper(), value)
///
///
/// d = UppercaseDict({"a": 1, "b": 2}) # Uses __setitem__
/// print(d) # {'A': 1, 'B': 2}
/// ```
///
/// ## Fix safety
/// This fix is marked as unsafe because `isinstance()` checks for `dict`,
/// `list`, and `str` types will fail when using the corresponding User class.
/// If you need to pass custom `dict` or `list` objects to code you don't
/// control, ignore this check. If you do control the code, consider using
/// the following type checks instead:
///
/// * `dict` -> `collections.abc.MutableMapping`
/// * `list` -> `collections.abc.MutableSequence`
/// * `str` -> No such conversion exists
///
/// ## References
///
/// - [Python documentation: `collections`](https://docs.python.org/3/library/collections.html)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.7.3")]
pub(crate) struct SubclassBuiltin {
subclass: String,
replacement: String,
}
impl AlwaysFixableViolation for SubclassBuiltin {
#[derive_message_formats]
fn message(&self) -> String {
let SubclassBuiltin {
subclass,
replacement,
} = self;
format!(
"Subclassing `{subclass}` can be error prone, use `collections.{replacement}` instead"
)
}
fn fix_title(&self) -> String {
let SubclassBuiltin { replacement, .. } = self;
format!("Replace with `collections.{replacement}`")
}
}
/// FURB189
pub(crate) fn subclass_builtin(checker: &Checker, class: &StmtClassDef) {
let Some(Arguments { args: bases, .. }) = class.arguments.as_deref() else {
return;
};
// Expect only one base class else return
let [base] = &**bases else {
return;
};
// Check if the base class is a subscript expression so that only the name expr
// is checked and modified.
let base_expr = map_subscript(base);
let Some(symbol) = checker.semantic().resolve_builtin_symbol(base_expr) else {
return;
};
let Some(supported_builtin) = SupportedBuiltins::from_symbol(symbol) else {
return;
};
let user_symbol = supported_builtin.user_symbol();
let mut diagnostic = checker.report_diagnostic(
SubclassBuiltin {
subclass: symbol.to_string(),
replacement: user_symbol.to_string(),
},
base_expr.range(),
);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from("collections", user_symbol),
base.start(),
checker.semantic(),
)?;
let other_edit = Edit::range_replacement(binding, base_expr.range());
Ok(Fix::unsafe_edits(import_edit, [other_edit]))
});
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum SupportedBuiltins {
Str,
List,
Dict,
}
impl SupportedBuiltins {
fn from_symbol(value: &str) -> Option<SupportedBuiltins> {
match value {
"str" => Some(Self::Str),
"dict" => Some(Self::Dict),
"list" => Some(Self::List),
_ => None,
}
}
const fn user_symbol(self) -> &'static str {
match self {
SupportedBuiltins::Dict => "UserDict",
SupportedBuiltins::List => "UserList",
SupportedBuiltins::Str => "UserString",
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/regex_flag_alias.rs | crates/ruff_linter/src/rules/refurb/rules/regex_flag_alias.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Expr;
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for the use of shorthand aliases for regular expression flags
/// (e.g., `re.I` instead of `re.IGNORECASE`).
///
/// ## Why is this bad?
/// The regular expression module provides descriptive names for each flag,
/// along with single-letter aliases. Prefer the descriptive names, as they
/// are more readable and self-documenting.
///
/// ## Example
/// ```python
/// import re
///
/// if re.match("^hello", "hello world", re.I):
/// ...
/// ```
///
/// Use instead:
/// ```python
/// import re
///
/// if re.match("^hello", "hello world", re.IGNORECASE):
/// ...
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct RegexFlagAlias {
flag: RegexFlag,
}
impl AlwaysFixableViolation for RegexFlagAlias {
#[derive_message_formats]
fn message(&self) -> String {
let RegexFlagAlias { flag } = self;
format!("Use of regular expression alias `re.{}`", flag.alias())
}
fn fix_title(&self) -> String {
let RegexFlagAlias { flag } = self;
format!("Replace with `re.{}`", flag.full_name())
}
}
/// FURB167
pub(crate) fn regex_flag_alias(checker: &Checker, expr: &Expr) {
if !checker.semantic().seen_module(Modules::RE) {
return;
}
let Some(flag) = checker
.semantic()
.resolve_qualified_name(expr)
.and_then(|qualified_name| match qualified_name.segments() {
["re", "A"] => Some(RegexFlag::Ascii),
["re", "I"] => Some(RegexFlag::IgnoreCase),
["re", "L"] => Some(RegexFlag::Locale),
["re", "M"] => Some(RegexFlag::Multiline),
["re", "S"] => Some(RegexFlag::DotAll),
["re", "T"] => Some(RegexFlag::Template),
["re", "U"] => Some(RegexFlag::Unicode),
["re", "X"] => Some(RegexFlag::Verbose),
_ => None,
})
else {
return;
};
let mut diagnostic = checker.report_diagnostic(RegexFlagAlias { flag }, expr.range());
diagnostic.try_set_fix(|| {
let (edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("re", flag.full_name()),
expr.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, expr.range()),
[edit],
))
});
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RegexFlag {
Ascii,
IgnoreCase,
Locale,
Multiline,
DotAll,
Template,
Unicode,
Verbose,
}
impl RegexFlag {
#[must_use]
const fn alias(self) -> &'static str {
match self {
Self::Ascii => "A",
Self::IgnoreCase => "I",
Self::Locale => "L",
Self::Multiline => "M",
Self::DotAll => "S",
Self::Template => "T",
Self::Unicode => "U",
Self::Verbose => "X",
}
}
#[must_use]
const fn full_name(self) -> &'static str {
match self {
Self::Ascii => "ASCII",
Self::IgnoreCase => "IGNORECASE",
Self::Locale => "LOCALE",
Self::Multiline => "MULTILINE",
Self::DotAll => "DOTALL",
Self::Template => "TEMPLATE",
Self::Unicode => "UNICODE",
Self::Verbose => "VERBOSE",
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/write_whole_file.rs | crates/ruff_linter/src/rules/refurb/rules/write_whole_file.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{
self as ast, Expr, Stmt,
visitor::{self, Visitor},
};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::importer::ImportRequest;
use crate::rules::refurb::helpers::{FileOpen, OpenArgument, find_file_opens};
use crate::{FixAvailability, Locator, Violation};
/// ## What it does
/// Checks for uses of `open` and `write` that can be replaced by `pathlib`
/// methods, like `Path.write_text` and `Path.write_bytes`.
///
/// ## Why is this bad?
/// When writing a single string to a file, it's simpler and more concise
/// to use `pathlib` methods like `Path.write_text` and `Path.write_bytes`
/// instead of `open` and `write` calls via `with` statements.
///
/// ## Example
/// ```python
/// with open(filename, "w") as f:
/// f.write(contents)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(filename).write_text(contents)
/// ```
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.write_bytes`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_bytes)
/// - [Python documentation: `Path.write_text`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_text)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.3.6")]
pub(crate) struct WriteWholeFile<'a> {
filename: SourceCodeSnippet,
suggestion: SourceCodeSnippet,
argument: OpenArgument<'a>,
}
impl Violation for WriteWholeFile<'_> {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let filename = self.filename.truncated_display();
let suggestion = self.suggestion.truncated_display();
match self.argument {
OpenArgument::Pathlib { .. } => {
format!(
"`Path.open()` followed by `write()` can be replaced by `{filename}.{suggestion}`"
)
}
OpenArgument::Builtin { .. } => {
format!("`open` and `write` should be replaced by `Path({filename}).{suggestion}`")
}
}
}
fn fix_title(&self) -> Option<String> {
let filename = self.filename.truncated_display();
let suggestion = self.suggestion.truncated_display();
match self.argument {
OpenArgument::Pathlib { .. } => Some(format!("Replace with `{filename}.{suggestion}`")),
OpenArgument::Builtin { .. } => {
Some(format!("Replace with `Path({filename}).{suggestion}`"))
}
}
}
}
/// FURB103
pub(crate) fn write_whole_file(checker: &Checker, with: &ast::StmtWith) {
// `async` check here is more of a precaution.
if with.is_async {
return;
}
// First we go through all the items in the statement and find all `open` operations.
let candidates = find_file_opens(with, checker.semantic(), false, checker.target_version());
if candidates.is_empty() {
return;
}
// Then we need to match each `open` operation with exactly one `write` call.
let mut matcher = WriteMatcher::new(checker, candidates, with);
visitor::walk_body(&mut matcher, &with.body);
}
/// AST visitor that matches `open` operations with the corresponding `write` calls.
struct WriteMatcher<'a, 'b> {
checker: &'a Checker<'b>,
candidates: Vec<FileOpen<'a>>,
loop_counter: u32,
with_stmt: &'a ast::StmtWith,
}
impl<'a, 'b> WriteMatcher<'a, 'b> {
fn new(
checker: &'a Checker<'b>,
candidates: Vec<FileOpen<'a>>,
with_stmt: &'a ast::StmtWith,
) -> Self {
Self {
checker,
candidates,
loop_counter: 0,
with_stmt,
}
}
}
impl<'a> Visitor<'a> for WriteMatcher<'a, '_> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
if matches!(stmt, Stmt::While(_) | Stmt::For(_)) {
self.loop_counter += 1;
visitor::walk_stmt(self, stmt);
self.loop_counter -= 1;
} else {
visitor::walk_stmt(self, stmt);
}
}
fn visit_expr(&mut self, expr: &'a Expr) {
if let Some((write_to, content)) = match_write_call(expr) {
if let Some(open) = self
.candidates
.iter()
.position(|open| open.is_ref(write_to))
{
let open = self.candidates.remove(open);
if self.loop_counter == 0 {
let filename_display = open.argument.display(self.checker.source());
let suggestion = make_suggestion(&open, content, self.checker.locator());
let mut diagnostic = self.checker.report_diagnostic(
WriteWholeFile {
filename: SourceCodeSnippet::from_str(filename_display),
suggestion: SourceCodeSnippet::from_str(&suggestion),
argument: open.argument,
},
open.item.range(),
);
if let Some(fix) =
generate_fix(self.checker, &open, self.with_stmt, &suggestion)
{
diagnostic.set_fix(fix);
}
}
}
return;
}
visitor::walk_expr(self, expr);
}
}
/// Match `x.write(foo)` expression and return expression `x` and `foo` on success.
fn match_write_call(expr: &Expr) -> Option<(&Expr, &Expr)> {
let call = expr.as_call_expr()?;
let attr = call.func.as_attribute_expr()?;
let method_name = &attr.attr;
if method_name != "write"
|| !attr.value.is_name_expr()
|| call.arguments.args.len() != 1
|| !call.arguments.keywords.is_empty()
{
return None;
}
// `write` only takes in a single positional argument.
Some((&*attr.value, call.arguments.args.first()?))
}
fn make_suggestion(open: &FileOpen<'_>, arg: &Expr, locator: &Locator) -> String {
let method_name = open.mode.pathlib_method();
let arg_code = locator.slice(arg.range());
if open.keywords.is_empty() {
format!("{method_name}({arg_code})")
} else {
format!(
"{method_name}({arg_code}, {})",
itertools::join(
open.keywords.iter().map(|kw| locator.slice(kw.range())),
", "
)
)
}
}
fn generate_fix(
checker: &Checker,
open: &FileOpen,
with_stmt: &ast::StmtWith,
suggestion: &str,
) -> Option<Fix> {
if !(with_stmt.items.len() == 1 && matches!(with_stmt.body.as_slice(), [Stmt::Expr(_)])) {
return None;
}
let locator = checker.locator();
let (import_edit, binding) = checker
.importer()
.get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
with_stmt.start(),
checker.semantic(),
)
.ok()?;
let target = match open.argument {
OpenArgument::Builtin { filename } => {
let filename_code = locator.slice(filename.range());
format!("{binding}({filename_code})")
}
OpenArgument::Pathlib { path } => locator.slice(path.range()).to_string(),
};
let replacement = format!("{target}.{suggestion}");
let applicability = if checker.comment_ranges().intersects(with_stmt.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Some(Fix::applicable_edits(
Edit::range_replacement(replacement, with_stmt.range()),
[import_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/refurb/rules/print_empty_string.rs | crates/ruff_linter/src/rules/refurb/rules/print_empty_string.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::{contains_effect, is_empty_f_string};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_codegen::Generator;
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for `print` calls with unnecessary empty strings as positional
/// arguments and unnecessary `sep` keyword arguments.
///
/// ## Why is this bad?
/// Prefer calling `print` without any positional arguments, which is
/// equivalent and more concise.
///
/// Similarly, when printing one or fewer items, the `sep` keyword argument,
/// (used to define the string that separates the `print` arguments) can be
/// omitted, as it's redundant when there are no items to separate.
///
/// ## Example
/// ```python
/// print("")
/// ```
///
/// Use instead:
/// ```python
/// print()
/// ```
///
/// ## Fix safety
/// This fix is marked as unsafe if it removes an unused `sep` keyword argument
/// that may have side effects. Removing such arguments may change the program's
/// behavior by skipping the execution of those side effects.
///
/// ## References
/// - [Python documentation: `print`](https://docs.python.org/3/library/functions.html#print)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct PrintEmptyString {
reason: Reason,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reason {
/// Ex) `print("")`
EmptyArgument,
/// Ex) `print("foo", sep="\t")`
UselessSeparator,
/// Ex) `print("", sep="\t")`
Both,
}
impl Violation for PrintEmptyString {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
match self.reason {
Reason::EmptyArgument => "Unnecessary empty string passed to `print`".to_string(),
Reason::UselessSeparator => "Unnecessary separator passed to `print`".to_string(),
Reason::Both => "Unnecessary empty string and separator passed to `print`".to_string(),
}
}
fn fix_title(&self) -> Option<String> {
let title = match self.reason {
Reason::EmptyArgument => "Remove empty string",
Reason::UselessSeparator => "Remove separator",
Reason::Both => "Remove empty string and separator",
};
Some(title.to_string())
}
}
/// FURB105
pub(crate) fn print_empty_string(checker: &Checker, call: &ast::ExprCall) {
if !checker.semantic().match_builtin_expr(&call.func, "print") {
return;
}
match &*call.arguments.args {
// Ex) `print("")` or `print("", sep="\t")`
[arg] if is_empty_string(arg) => {
let reason = if call.arguments.find_keyword("sep").is_some() {
Reason::Both
} else {
Reason::EmptyArgument
};
let mut diagnostic =
checker.report_diagnostic(PrintEmptyString { reason }, call.range());
diagnostic.set_fix(
EmptyStringFix::from_call(
call,
Separator::Remove,
checker.semantic(),
checker.generator(),
)
.into_fix(),
);
}
[arg] if arg.is_starred_expr() => {
// If there's a starred argument, we can't remove the empty string.
}
// Ex) `print(sep="\t")` or `print(obj, sep="\t")`
[] | [_] => {
// If there's a `sep` argument, remove it, regardless of what it is.
if call.arguments.find_keyword("sep").is_some() {
let mut diagnostic = checker.report_diagnostic(
PrintEmptyString {
reason: Reason::UselessSeparator,
},
call.range(),
);
diagnostic.set_fix(
EmptyStringFix::from_call(
call,
Separator::Remove,
checker.semantic(),
checker.generator(),
)
.into_fix(),
);
}
}
// Ex) `print("foo", "", "bar", sep="")`
_ => {
// Ignore `**kwargs`.
let has_kwargs = call
.arguments
.keywords
.iter()
.any(|keyword| keyword.arg.is_none());
if has_kwargs {
return;
}
// Require an empty `sep` argument.
let empty_separator = call
.arguments
.find_keyword("sep")
.is_some_and(|keyword| is_empty_string(&keyword.value));
if !empty_separator {
return;
}
// Count the number of empty and non-empty arguments.
let empty_arguments = call
.arguments
.args
.iter()
.filter(|arg| is_empty_string(arg))
.count();
if empty_arguments == 0 {
return;
}
// If removing the arguments would leave us with one or fewer, then we can remove the
// separator too.
let separator = if call.arguments.args.len() - empty_arguments > 1
|| call.arguments.args.iter().any(Expr::is_starred_expr)
{
Separator::Retain
} else {
Separator::Remove
};
let mut diagnostic = checker.report_diagnostic(
PrintEmptyString {
reason: if separator == Separator::Retain {
Reason::EmptyArgument
} else {
Reason::Both
},
},
call.range(),
);
diagnostic.set_fix(
EmptyStringFix::from_call(call, separator, checker.semantic(), checker.generator())
.into_fix(),
);
}
}
}
/// Check if an expression is a constant empty string.
fn is_empty_string(expr: &Expr) -> bool {
match expr {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => value.is_empty(),
Expr::FString(f_string) => is_empty_f_string(f_string),
_ => false,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Separator {
Remove,
Retain,
}
#[derive(Debug, Clone)]
struct EmptyStringFix(Fix);
impl EmptyStringFix {
/// Generate a suggestion to remove the empty string positional argument and
/// the `sep` keyword argument, if it exists.
fn from_call(
call: &ast::ExprCall,
separator: Separator,
semantic: &SemanticModel,
generator: Generator,
) -> Self {
let range = call.range();
let mut call = call.clone();
let mut applicability = Applicability::Safe;
// Remove all empty string positional arguments.
call.arguments.args = call
.arguments
.args
.iter()
.filter(|arg| !is_empty_string(arg))
.cloned()
.collect::<Vec<_>>()
.into_boxed_slice();
// Remove the `sep` keyword argument if it exists.
if separator == Separator::Remove {
call.arguments.keywords = call
.arguments
.keywords
.iter()
.filter(|keyword| {
let Some(arg) = keyword.arg.as_ref() else {
return true;
};
if arg.as_str() != "sep" {
return true;
}
if contains_effect(&keyword.value, |id| semantic.has_builtin_binding(id)) {
applicability = Applicability::Unsafe;
}
false
})
.cloned()
.collect::<Vec<_>>()
.into_boxed_slice();
}
let contents = generator.expr(&call.into());
Self(Fix::applicable_edit(
Edit::range_replacement(contents, range),
applicability,
))
}
/// Return the [`Fix`] contained in this [`EmptyStringFix`].
fn into_fix(self) -> Fix {
self.0
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/math_constant.rs | crates/ruff_linter/src/rules/refurb/rules/math_constant.rs | use anyhow::Result;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Number};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for literals that are similar to constants in `math` module.
///
/// ## Why is this bad?
/// Hard-coding mathematical constants like Ο increases code duplication,
/// reduces readability, and may lead to a lack of precision.
///
/// ## Example
/// ```python
/// A = 3.141592 * r**2
/// ```
///
/// Use instead:
/// ```python
/// A = math.pi * r**2
/// ```
///
/// ## References
/// - [Python documentation: `math` constants](https://docs.python.org/3/library/math.html#constants)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.1.6")]
pub(crate) struct MathConstant {
literal: String,
constant: &'static str,
}
impl Violation for MathConstant {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let MathConstant { literal, constant } = self;
format!("Replace `{literal}` with `math.{constant}`")
}
fn fix_title(&self) -> Option<String> {
let MathConstant { constant, .. } = self;
Some(format!("Use `math.{constant}`"))
}
}
/// FURB152
pub(crate) fn math_constant(checker: &Checker, literal: &ast::ExprNumberLiteral) {
let Number::Float(value) = literal.value else {
return;
};
if let Some(constant) = Constant::from_value(value) {
let mut diagnostic = checker.report_diagnostic(
MathConstant {
literal: checker.locator().slice(literal).into(),
constant: constant.name(),
},
literal.range(),
);
diagnostic.try_set_fix(|| convert_to_constant(literal, constant.name(), checker));
}
}
fn convert_to_constant(
literal: &ast::ExprNumberLiteral,
constant: &'static str,
checker: &Checker,
) -> Result<Fix> {
let (edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("math", constant),
literal.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, literal.range()),
[edit],
))
}
fn matches_constant(constant: f64, value: f64) -> bool {
for point in 2..=15 {
let rounded = (constant * 10_f64.powi(point)).round() / 10_f64.powi(point);
if (rounded - value).abs() < f64::EPSILON {
return true;
}
let rounded = (constant * 10_f64.powi(point)).floor() / 10_f64.powi(point);
if (rounded - value).abs() < f64::EPSILON {
return true;
}
}
false
}
#[derive(Debug, Clone, Copy)]
enum Constant {
Pi,
E,
Tau,
}
impl Constant {
#[expect(clippy::approx_constant)]
fn from_value(value: f64) -> Option<Self> {
if (3.14..3.15).contains(&value) {
matches_constant(std::f64::consts::PI, value).then_some(Self::Pi)
} else if (2.71..2.72).contains(&value) {
matches_constant(std::f64::consts::E, value).then_some(Self::E)
} else if (6.28..6.29).contains(&value) {
matches_constant(std::f64::consts::TAU, value).then_some(Self::Tau)
} else {
None
}
}
fn name(self) -> &'static str {
match self {
Constant::Pi => "pi",
Constant::E => "e",
Constant::Tau => "tau",
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/slice_copy.rs | crates/ruff_linter/src/rules/refurb/rules/slice_copy.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::name::Name;
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::analyze::typing::is_list;
use ruff_python_semantic::{Binding, SemanticModel};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
use crate::rules::refurb::helpers::generate_method_call;
/// ## What it does
/// Checks for unbounded slice expressions to copy a list.
///
/// ## Why is this bad?
/// The `list.copy` method is more readable and consistent with copying other
/// types.
///
/// ## Known problems
/// This rule is prone to false negatives due to type inference limitations,
/// as it will only detect lists that are instantiated as literals or annotated
/// with a type annotation.
///
/// ## Example
/// ```python
/// a = [1, 2, 3]
/// b = a[:]
/// ```
///
/// Use instead:
/// ```python
/// a = [1, 2, 3]
/// b = a.copy()
/// ```
///
/// ## References
/// - [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.0.290")]
pub(crate) struct SliceCopy;
impl Violation for SliceCopy {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `copy` method over slicing".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `copy()`".to_string())
}
}
/// FURB145
pub(crate) fn slice_copy(checker: &Checker, subscript: &ast::ExprSubscript) {
if subscript.ctx.is_store() || subscript.ctx.is_del() {
return;
}
let Some(name) = match_list_full_slice(subscript, checker.semantic()) else {
return;
};
let mut diagnostic = checker.report_diagnostic(SliceCopy, subscript.range());
let replacement = generate_method_call(name.clone(), "copy", checker.generator());
diagnostic.set_fix(Fix::safe_edit(Edit::replacement(
replacement,
subscript.start(),
subscript.end(),
)));
}
/// Matches `obj[:]` where `obj` is a list.
fn match_list_full_slice<'a>(
subscript: &'a ast::ExprSubscript,
semantic: &SemanticModel,
) -> Option<&'a Name> {
// Check that it is `obj[:]`.
if !matches!(
subscript.slice.as_ref(),
Expr::Slice(ast::ExprSlice {
lower: None,
upper: None,
step: None,
range: _,
node_index: _,
})
) {
return None;
}
let ast::ExprName { id, .. } = subscript.value.as_name_expr()?;
// Check that `obj` is a list.
let scope = semantic.current_scope();
let bindings: Vec<&Binding> = scope
.get_all(id)
.map(|binding_id| semantic.binding(binding_id))
.collect();
let [binding] = bindings.as_slice() else {
return None;
};
if !is_list(binding, semantic) {
return None;
}
Some(id)
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/hashlib_digest_hex.rs | crates/ruff_linter/src/rules/refurb/rules/hashlib_digest_hex.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprAttribute, ExprCall};
use ruff_python_semantic::Modules;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for the use of `.digest().hex()` on a hashlib hash, like `sha512`.
///
/// ## Why is this bad?
/// When generating a hex digest from a hash, it's preferable to use the
/// `.hexdigest()` method, rather than calling `.digest()` and then `.hex()`,
/// as the former is more concise and readable.
///
/// ## Example
/// ```python
/// from hashlib import sha512
///
/// hashed = sha512(b"some data").digest().hex()
/// ```
///
/// Use instead:
/// ```python
/// from hashlib import sha512
///
/// hashed = sha512(b"some data").hexdigest()
/// ```
///
/// ## References
/// - [Python documentation: `hashlib`](https://docs.python.org/3/library/hashlib.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct HashlibDigestHex;
impl Violation for HashlibDigestHex {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use of hashlib's `.digest().hex()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `.hexdigest()`".to_string())
}
}
/// FURB181
pub(crate) fn hashlib_digest_hex(checker: &Checker, call: &ExprCall) {
if !checker.semantic().seen_module(Modules::HASHLIB) {
return;
}
if !call.arguments.is_empty() {
return;
}
let Expr::Attribute(ExprAttribute { attr, value, .. }) = call.func.as_ref() else {
return;
};
if attr.as_str() != "hex" {
return;
}
let Expr::Call(ExprCall {
func, arguments, ..
}) = value.as_ref()
else {
return;
};
let Expr::Attribute(ExprAttribute { attr, value, .. }) = func.as_ref() else {
return;
};
if attr.as_str() != "digest" {
return;
}
let Expr::Call(ExprCall { func, .. }) = value.as_ref() else {
return;
};
if checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
[
"hashlib",
"md5"
| "sha1"
| "sha224"
| "sha256"
| "sha384"
| "sha512"
| "blake2b"
| "blake2s"
| "sha3_224"
| "sha3_256"
| "sha3_384"
| "sha3_512"
| "shake_128"
| "shake_256"
]
)
})
{
let mut diagnostic = checker.report_diagnostic(HashlibDigestHex, call.range());
if arguments.is_empty() {
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
".hexdigest".to_string(),
TextRange::new(value.end(), call.func.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/refurb/rules/check_and_remove_from_set.rs | crates/ruff_linter/src/rules/refurb/rules/check_and_remove_from_set.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, CmpOp, Expr, Stmt};
use ruff_python_codegen::Generator;
use ruff_python_semantic::analyze::typing::is_set;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `set.remove` that can be replaced with `set.discard`.
///
/// ## Why is this bad?
/// If an element should be removed from a set if it is present, it is more
/// succinct and idiomatic to use `discard`.
///
/// ## Known problems
/// This rule is prone to false negatives due to type inference limitations,
/// as it will only detect sets that are instantiated as literals or annotated
/// with a type annotation.
///
/// ## Example
/// ```python
/// nums = {123, 456}
///
/// if 123 in nums:
/// nums.remove(123)
/// ```
///
/// Use instead:
/// ```python
/// nums = {123, 456}
///
/// nums.discard(123)
/// ```
///
/// ## References
/// - [Python documentation: `set.discard()`](https://docs.python.org/3/library/stdtypes.html?highlight=list#frozenset.discard)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct CheckAndRemoveFromSet {
element: SourceCodeSnippet,
set: String,
}
impl CheckAndRemoveFromSet {
fn suggestion(&self) -> String {
let set = &self.set;
let element = self.element.truncated_display();
format!("{set}.discard({element})")
}
}
impl AlwaysFixableViolation for CheckAndRemoveFromSet {
#[derive_message_formats]
fn message(&self) -> String {
let suggestion = self.suggestion();
format!("Use `{suggestion}` instead of check and `remove`")
}
fn fix_title(&self) -> String {
let suggestion = self.suggestion();
format!("Replace with `{suggestion}`")
}
}
/// FURB132
pub(crate) fn check_and_remove_from_set(checker: &Checker, if_stmt: &ast::StmtIf) {
// In order to fit the profile, we need if without else clauses and with only one statement in its body.
if if_stmt.body.len() != 1 || !if_stmt.elif_else_clauses.is_empty() {
return;
}
// The `if` test should be `element in set`.
let Some((check_element, check_set)) = match_check(if_stmt) else {
return;
};
// The `if` body should be `set.remove(element)`.
let Some((remove_element, remove_set)) = match_remove(if_stmt) else {
return;
};
// `
// `set` in the check should be the same as `set` in the body
if check_set.id != remove_set.id
// `element` in the check should be the same as `element` in the body
|| !compare(&check_element.into(), &remove_element.into())
// `element` shouldn't have a side effect, otherwise we might change the semantics of the program.
|| contains_effect(check_element, |id| checker.semantic().has_builtin_binding(id))
{
return;
}
// Check if what we assume is set is indeed a set.
if !checker
.semantic()
.only_binding(check_set)
.map(|id| checker.semantic().binding(id))
.is_some_and(|binding| is_set(binding, checker.semantic()))
{
return;
}
let mut diagnostic = checker.report_diagnostic(
CheckAndRemoveFromSet {
element: SourceCodeSnippet::from_str(checker.locator().slice(check_element)),
set: check_set.id.to_string(),
},
if_stmt.range(),
);
diagnostic.set_fix(Fix::unsafe_edit(Edit::replacement(
make_suggestion(check_set, check_element, checker.generator()),
if_stmt.start(),
if_stmt.end(),
)));
}
fn compare(lhs: &ComparableExpr, rhs: &ComparableExpr) -> bool {
lhs == rhs
}
/// Match `if` condition to be `expr in name`, returns a tuple of (`expr`, `name`) on success.
fn match_check(if_stmt: &ast::StmtIf) -> Option<(&Expr, &ast::ExprName)> {
let ast::ExprCompare {
ops,
left,
comparators,
..
} = if_stmt.test.as_compare_expr()?;
if **ops != [CmpOp::In] {
return None;
}
let [Expr::Name(right @ ast::ExprName { .. })] = &**comparators else {
return None;
};
Some((left.as_ref(), right))
}
/// Match `if` body to be `name.remove(expr)`, returns a tuple of (`expr`, `name`) on success.
fn match_remove(if_stmt: &ast::StmtIf) -> Option<(&Expr, &ast::ExprName)> {
let [Stmt::Expr(ast::StmtExpr { value: expr, .. })] = if_stmt.body.as_slice() else {
return None;
};
let ast::ExprCall {
func: attr,
arguments: ast::Arguments { args, keywords, .. },
..
} = expr.as_call_expr()?;
let ast::ExprAttribute {
value: receiver,
attr: func_name,
..
} = attr.as_attribute_expr()?;
let Expr::Name(set @ ast::ExprName { .. }) = receiver.as_ref() else {
return None;
};
let [arg] = &**args else {
return None;
};
if func_name != "remove" || !keywords.is_empty() {
return None;
}
Some((arg, set))
}
/// Construct the fix suggestion, ie `set.discard(element)`.
fn make_suggestion(set: &ast::ExprName, element: &Expr, generator: Generator) -> String {
// Here we construct `set.discard(element)`
//
// Let's make `set.discard`.
let attr = ast::ExprAttribute {
value: Box::new(set.clone().into()),
attr: ast::Identifier::new("discard".to_string(), TextRange::default()),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// Make the actual call `set.discard(element)`
let call = ast::ExprCall {
func: Box::new(attr.into()),
arguments: ast::Arguments {
args: Box::from([element.clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// And finally, turn it into a statement.
let stmt = ast::StmtExpr {
value: Box::new(call.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
generator.stmt(&stmt.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/refurb/rules/metaclass_abcmeta.rs | crates/ruff_linter/src/rules/refurb/rules/metaclass_abcmeta.rs | use itertools::Itertools;
use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::StmtClassDef;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `metaclass=abc.ABCMeta` to define abstract base classes
/// (ABCs).
///
/// ## Why is this bad?
///
/// Instead of `class C(metaclass=abc.ABCMeta): ...`, use `class C(ABC): ...`
/// to define an abstract base class. Inheriting from the `ABC` wrapper class
/// is semantically identical to setting `metaclass=abc.ABCMeta`, but more
/// succinct.
///
/// ## Example
/// ```python
/// import abc
///
///
/// class C(metaclass=abc.ABCMeta):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// import abc
///
///
/// class C(abc.ABC):
/// pass
/// ```
///
/// ## Fix safety
/// The rule's fix is unsafe if the class has base classes. This is because the base classes might
/// be validating the class's other base classes (e.g., `typing.Protocol` does this) or otherwise
/// alter runtime behavior if more base classes are added.
///
/// ## References
/// - [Python documentation: `abc.ABC`](https://docs.python.org/3/library/abc.html#abc.ABC)
/// - [Python documentation: `abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.2.0")]
pub(crate) struct MetaClassABCMeta;
impl AlwaysFixableViolation for MetaClassABCMeta {
#[derive_message_formats]
fn message(&self) -> String {
"Use of `metaclass=abc.ABCMeta` to define abstract base class".to_string()
}
fn fix_title(&self) -> String {
"Replace with `abc.ABC`".to_string()
}
}
/// FURB180
pub(crate) fn metaclass_abcmeta(checker: &Checker, class_def: &StmtClassDef) {
// Identify the `metaclass` keyword.
let Some((position, keyword)) = class_def.keywords().iter().find_position(|&keyword| {
keyword
.arg
.as_ref()
.is_some_and(|arg| arg.as_str() == "metaclass")
}) else {
return;
};
// Determine whether it's assigned to `abc.ABCMeta`.
if !checker
.semantic()
.resolve_qualified_name(&keyword.value)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["abc", "ABCMeta"]))
{
return;
}
let applicability = if class_def.bases().is_empty() {
Applicability::Safe
} else {
Applicability::Unsafe
};
let mut diagnostic = checker.report_diagnostic(MetaClassABCMeta, keyword.range);
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("abc", "ABC"),
keyword.range.start(),
checker.semantic(),
)?;
Ok(if position > 0 {
// When the `abc.ABCMeta` is not the first keyword, put `abc.ABC` before the first
// keyword.
Fix::applicable_edits(
// Delete from the previous argument, to the end of the `metaclass` argument.
Edit::range_deletion(TextRange::new(
class_def.keywords()[position - 1].end(),
keyword.end(),
)),
// Insert `abc.ABC` before the first keyword.
[
Edit::insertion(format!("{binding}, "), class_def.keywords()[0].start()),
import_edit,
],
applicability,
)
} else {
Fix::applicable_edits(
Edit::range_replacement(binding, keyword.range),
[import_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/refurb/rules/reimplemented_starmap.rs | crates/ruff_linter/src/rules/refurb/rules/reimplemented_starmap.rs | use anyhow::{Result, bail};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::name::Name;
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for generator expressions, list and set comprehensions that can
/// be replaced with `itertools.starmap`.
///
/// ## Why is this bad?
/// When unpacking values from iterators to pass them directly to
/// a function, prefer `itertools.starmap`.
///
/// Using `itertools.starmap` is more concise and readable. Furthermore, it is
/// more efficient than generator expressions, and in some versions of Python,
/// it is more efficient than comprehensions.
///
/// ## Known problems
/// Since Python 3.12, `itertools.starmap` is less efficient than
/// comprehensions ([#7771]). This is due to [PEP 709], which made
/// comprehensions faster.
///
/// ## Example
/// ```python
/// all(predicate(a, b) for a, b in some_iterable)
/// ```
///
/// Use instead:
/// ```python
/// from itertools import starmap
///
///
/// all(starmap(predicate, some_iterable))
/// ```
///
/// ## References
/// - [Python documentation: `itertools.starmap`](https://docs.python.org/3/library/itertools.html#itertools.starmap)
///
/// [PEP 709]: https://peps.python.org/pep-0709/
/// [#7771]: https://github.com/astral-sh/ruff/issues/7771
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.0.291")]
pub(crate) struct ReimplementedStarmap;
impl Violation for ReimplementedStarmap {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Use `itertools.starmap` instead of the generator".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `itertools.starmap`".to_string())
}
}
/// FURB140
pub(crate) fn reimplemented_starmap(checker: &Checker, target: &StarmapCandidate) {
// Generator should have exactly one comprehension.
let [comprehension] = target.generators() else {
return;
};
// This comprehension should have a form:
// ```python
// (x, y, z, ...) in iter
// ```
//
// `x, y, z, ...` are what we call `elts` for short.
let Some(value) = match_comprehension_target(comprehension) else {
return;
};
// Generator should produce one element that should look like:
// ```python
// func(a, b, c, ...)
// ```
//
// here we refer to `a, b, c, ...` as `args`.
//
// NOTE: `func` is not necessarily just a function name, it can be an attribute access,
// or even a call itself.
let Some((args, func)) = match_call(target.element()) else {
return;
};
match value {
// Ex) `f(*x) for x in iter`
ComprehensionTarget::Name(name) => {
let [arg] = args else {
return;
};
let Expr::Starred(ast::ExprStarred { value, .. }) = arg else {
return;
};
if ComparableExpr::from(value.as_ref()) != ComparableExpr::from(name) {
return;
}
// If the argument is used outside the function call, we can't replace it.
if any_over_expr(func, &|expr| {
expr.as_name_expr().is_some_and(|expr| expr.id == name.id)
}) {
return;
}
}
// Ex) `f(x, y, z) for x, y, z in iter`
ComprehensionTarget::Tuple(tuple) => {
if tuple.len() != args.len()
|| std::iter::zip(tuple, args)
.any(|(x, y)| ComparableExpr::from(x) != ComparableExpr::from(y))
{
return;
}
// If any of the members are used outside the function call, we can't replace it.
if any_over_expr(func, &|expr| {
tuple
.iter()
.any(|elem| ComparableExpr::from(expr) == ComparableExpr::from(elem))
}) {
return;
}
}
}
let mut diagnostic = checker.report_diagnostic(ReimplementedStarmap, target.range());
diagnostic.try_set_fix(|| {
// Import `starmap` from `itertools`.
let (import_edit, starmap_name) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from("itertools", "starmap"),
target.start(),
checker.semantic(),
)?;
// The actual fix suggestion depends on what type of expression we were looking at:
// - For generator expressions, we use `starmap` call directly.
// - For list and set comprehensions, we'd want to wrap it with `list` and `set`
// correspondingly.
let main_edit = Edit::range_replacement(
target.try_make_suggestion(
Name::from(starmap_name),
&comprehension.iter,
func,
checker,
)?,
target.range(),
);
Ok(Fix::safe_edits(import_edit, [main_edit]))
});
}
/// An enum for a node that can be considered a candidate for replacement with `starmap`.
#[derive(Debug)]
pub(crate) enum StarmapCandidate<'a> {
Generator(&'a ast::ExprGenerator),
ListComp(&'a ast::ExprListComp),
SetComp(&'a ast::ExprSetComp),
}
impl<'a> From<&'a ast::ExprGenerator> for StarmapCandidate<'a> {
fn from(generator: &'a ast::ExprGenerator) -> Self {
Self::Generator(generator)
}
}
impl<'a> From<&'a ast::ExprListComp> for StarmapCandidate<'a> {
fn from(list_comp: &'a ast::ExprListComp) -> Self {
Self::ListComp(list_comp)
}
}
impl<'a> From<&'a ast::ExprSetComp> for StarmapCandidate<'a> {
fn from(set_comp: &'a ast::ExprSetComp) -> Self {
Self::SetComp(set_comp)
}
}
impl Ranged for StarmapCandidate<'_> {
fn range(&self) -> TextRange {
match self {
Self::Generator(generator) => generator.range(),
Self::ListComp(list_comp) => list_comp.range(),
Self::SetComp(set_comp) => set_comp.range(),
}
}
}
impl StarmapCandidate<'_> {
/// Return the generated element for the candidate.
pub(crate) fn element(&self) -> &Expr {
match self {
Self::Generator(generator) => generator.elt.as_ref(),
Self::ListComp(list_comp) => list_comp.elt.as_ref(),
Self::SetComp(set_comp) => set_comp.elt.as_ref(),
}
}
/// Return the generator comprehensions for the candidate.
pub(crate) fn generators(&self) -> &[ast::Comprehension] {
match self {
Self::Generator(generator) => generator.generators.as_slice(),
Self::ListComp(list_comp) => list_comp.generators.as_slice(),
Self::SetComp(set_comp) => set_comp.generators.as_slice(),
}
}
/// Try to produce a fix suggestion transforming this node into a call to `starmap`.
pub(crate) fn try_make_suggestion(
&self,
name: Name,
iter: &Expr,
func: &Expr,
checker: &Checker,
) -> Result<String> {
match self {
Self::Generator(_) => {
// For generator expressions, we replace:
// ```python
// (foo(...) for ... in iter)
// ```
//
// with:
// ```python
// itertools.starmap(foo, iter)
// ```
let call = construct_starmap_call(name, iter, func);
Ok(checker.generator().expr(&call.into()))
}
Self::ListComp(_) => {
// For list comprehensions, we replace:
// ```python
// [foo(...) for ... in iter]
// ```
//
// with:
// ```python
// list(itertools.starmap(foo, iter))
// ```
try_construct_call(name, iter, func, Name::new_static("list"), checker)
}
Self::SetComp(_) => {
// For set comprehensions, we replace:
// ```python
// {foo(...) for ... in iter}
// ```
//
// with:
// ```python
// set(itertools.starmap(foo, iter))
// ```
try_construct_call(name, iter, func, Name::new_static("set"), checker)
}
}
}
}
/// Try constructing the call to `itertools.starmap` and wrapping it with the given builtin.
fn try_construct_call(
name: Name,
iter: &Expr,
func: &Expr,
builtin: Name,
checker: &Checker,
) -> Result<String> {
// We can only do our fix if `builtin` identifier is still bound to
// the built-in type.
if !checker.semantic().has_builtin_binding(&builtin) {
bail!("Can't use built-in `{builtin}` constructor")
}
// In general, we replace:
// ```python
// foo(...) for ... in iter
// ```
//
// with:
// ```python
// builtin(itertools.starmap(foo, iter))
// ```
// where `builtin` is a constructor for a target collection.
let call = construct_starmap_call(name, iter, func);
let wrapped = wrap_with_call_to(call, builtin);
Ok(checker.generator().expr(&wrapped.into()))
}
/// Construct the call to `itertools.starmap` for suggestion.
fn construct_starmap_call(starmap_binding: Name, iter: &Expr, func: &Expr) -> ast::ExprCall {
let starmap = ast::ExprName {
id: starmap_binding,
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
ast::ExprCall {
func: Box::new(starmap.into()),
arguments: ast::Arguments {
args: Box::from([func.clone(), iter.clone()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
}
/// Wrap given function call with yet another call.
fn wrap_with_call_to(call: ast::ExprCall, func_name: Name) -> ast::ExprCall {
let name = ast::ExprName {
id: func_name,
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
ast::ExprCall {
func: Box::new(name.into()),
arguments: ast::Arguments {
args: Box::from([call.into()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
}
#[derive(Debug)]
enum ComprehensionTarget<'a> {
/// E.g., `(x, y, z, ...)` in `(x, y, z, ...) in iter`.
Tuple(&'a ast::ExprTuple),
/// E.g., `x` in `x in iter`.
Name(&'a ast::ExprName),
}
/// Extract the target from the comprehension (e.g., `(x, y, z)` in `(x, y, z, ...) in iter`).
fn match_comprehension_target(
comprehension: &ast::Comprehension,
) -> Option<ComprehensionTarget<'_>> {
if comprehension.is_async || !comprehension.ifs.is_empty() {
return None;
}
match &comprehension.target {
Expr::Tuple(tuple) => Some(ComprehensionTarget::Tuple(tuple)),
Expr::Name(name) => Some(ComprehensionTarget::Name(name)),
_ => None,
}
}
/// Match that the given expression is `func(x, y, z, ...)`.
fn match_call(element: &Expr) -> Option<(&[Expr], &Expr)> {
let ast::ExprCall {
func,
arguments: ast::Arguments { args, keywords, .. },
..
} = element.as_call_expr()?;
if !keywords.is_empty() {
return None;
}
Some((args, func))
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.rs | crates/ruff_linter/src/rules/refurb/rules/unnecessary_from_float.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprCall};
use ruff_python_semantic::analyze::type_inference::{NumberLike, PythonType, ResolvedPythonType};
use ruff_python_semantic::analyze::typing;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::linter::float::as_non_finite_float_string_literal;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for unnecessary `from_float` and `from_decimal` usages to construct
/// `Decimal` and `Fraction` instances.
///
/// ## Why is this bad?
/// Since Python 3.2, the `Fraction` and `Decimal` classes can be constructed
/// by passing float or decimal instances to the constructor directly. As such,
/// the use of `from_float` and `from_decimal` methods is unnecessary, and
/// should be avoided in favor of the more concise constructor syntax.
///
/// However, there are important behavioral differences between the `from_*` methods
/// and the constructors:
/// - The `from_*` methods validate their argument types and raise `TypeError` for invalid types
/// - The constructors accept broader argument types without validation
/// - The `from_*` methods have different parameter names than the constructors
///
/// ## Example
/// ```python
/// from decimal import Decimal
/// from fractions import Fraction
///
/// Decimal.from_float(4.2)
/// Decimal.from_float(float("inf"))
/// Fraction.from_float(4.2)
/// Fraction.from_decimal(Decimal("4.2"))
/// ```
///
/// Use instead:
/// ```python
/// from decimal import Decimal
/// from fractions import Fraction
///
/// Decimal(4.2)
/// Decimal("inf")
/// Fraction(4.2)
/// Fraction(Decimal("4.2"))
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe by default because:
/// - The `from_*` methods provide type validation that the constructors don't
/// - Removing type validation can change program behavior
/// - The parameter names are different between methods and constructors
///
/// The fix is marked as safe only when:
/// - The argument type is known to be valid for the target constructor
/// - No keyword arguments are used, or they match the constructor's parameters
///
/// ## References
/// - [Python documentation: `decimal`](https://docs.python.org/3/library/decimal.html)
/// - [Python documentation: `fractions`](https://docs.python.org/3/library/fractions.html)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.3.5")]
pub(crate) struct UnnecessaryFromFloat {
method_name: MethodName,
constructor: Constructor,
}
impl Violation for UnnecessaryFromFloat {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UnnecessaryFromFloat {
method_name,
constructor,
} = self;
format!("Verbose method `{method_name}` in `{constructor}` construction",)
}
fn fix_title(&self) -> Option<String> {
let UnnecessaryFromFloat { constructor, .. } = self;
Some(format!("Replace with `{constructor}` constructor"))
}
}
/// FURB164
pub(crate) fn unnecessary_from_float(checker: &Checker, call: &ExprCall) {
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = &*call.func else {
return;
};
// The method name must be either `from_float` or `from_decimal`.
let method_name = match attr.as_str() {
"from_float" => MethodName::FromFloat,
"from_decimal" => MethodName::FromDecimal,
_ => return,
};
let semantic = checker.semantic();
// The value must be either `decimal.Decimal` or `fractions.Fraction`.
let Some(qualified_name) = semantic.resolve_qualified_name(value) else {
return;
};
let constructor = match qualified_name.segments() {
["decimal", "Decimal"] => Constructor::Decimal,
["fractions", "Fraction"] => Constructor::Fraction,
_ => return,
};
// `Decimal.from_decimal` doesn't exist.
if matches!(
(method_name, constructor),
(MethodName::FromDecimal, Constructor::Decimal)
) {
return;
}
let mut diagnostic = checker.report_diagnostic(
UnnecessaryFromFloat {
method_name,
constructor,
},
call.range(),
);
// Validate that the method call has correct arguments and get the argument value
let Some(arg_value) = has_valid_method_arguments(call, method_name, constructor) else {
// Don't suggest a fix for invalid calls
return;
};
let constructor_name = checker.locator().slice(&**value).to_string();
// Special case for non-finite float literals: Decimal.from_float(float("inf")) -> Decimal("inf")
if let Some(replacement) = handle_non_finite_float_special_case(
call,
method_name,
constructor,
arg_value,
&constructor_name,
checker,
) {
diagnostic.set_fix(Fix::safe_edit(replacement));
return;
}
// Check if we should suppress the fix due to type validation concerns
let is_type_safe = is_valid_argument_type(arg_value, method_name, constructor, checker);
// Determine fix safety
let applicability = if is_type_safe {
Applicability::Safe
} else {
Applicability::Unsafe
};
// Build the replacement
let arg_text = checker.locator().slice(arg_value);
let replacement_text = format!("{constructor_name}({arg_text})");
let edit = Edit::range_replacement(replacement_text, call.range());
diagnostic.set_fix(Fix::applicable_edit(edit, applicability));
}
/// Check if the argument would be valid for the target constructor
fn is_valid_argument_type(
arg_expr: &Expr,
method_name: MethodName,
constructor: Constructor,
checker: &Checker,
) -> bool {
let semantic = checker.semantic();
let resolved_type = ResolvedPythonType::from(arg_expr);
let (is_int, is_float) = if let ResolvedPythonType::Unknown = resolved_type {
arg_expr
.as_name_expr()
.and_then(|name| semantic.only_binding(name).map(|id| semantic.binding(id)))
.map(|binding| {
(
typing::is_int(binding, semantic),
typing::is_float(binding, semantic),
)
})
.unwrap_or((false, false))
} else {
(false, false)
};
match (method_name, constructor) {
// Decimal.from_float: Only int or bool are safe (float is unsafe due to FloatOperation trap)
(MethodName::FromFloat, Constructor::Decimal) => match resolved_type {
ResolvedPythonType::Atom(PythonType::Number(
NumberLike::Integer | NumberLike::Bool,
)) => true,
ResolvedPythonType::Unknown => is_int,
_ => false,
},
// Fraction.from_float accepts int, bool, float
(MethodName::FromFloat, Constructor::Fraction) => match resolved_type {
ResolvedPythonType::Atom(PythonType::Number(
NumberLike::Integer | NumberLike::Bool | NumberLike::Float,
)) => true,
ResolvedPythonType::Unknown => is_int || is_float,
_ => false,
},
// Fraction.from_decimal accepts int, bool, Decimal
(MethodName::FromDecimal, Constructor::Fraction) => {
// First check if it's a Decimal constructor call
let is_decimal_call = arg_expr
.as_call_expr()
.and_then(|call| semantic.resolve_qualified_name(&call.func))
.is_some_and(|qualified_name| {
matches!(qualified_name.segments(), ["decimal", "Decimal"])
});
if is_decimal_call {
return true;
}
match resolved_type {
ResolvedPythonType::Atom(PythonType::Number(
NumberLike::Integer | NumberLike::Bool,
)) => true,
ResolvedPythonType::Unknown => is_int,
_ => false,
}
}
_ => false,
}
}
/// Check if the call has valid arguments for the from_* method
fn has_valid_method_arguments(
call: &ExprCall,
method_name: MethodName,
constructor: Constructor,
) -> Option<&Expr> {
if call.arguments.len() != 1 {
return None;
}
match method_name {
MethodName::FromFloat => {
// Decimal.from_float is positional-only; Fraction.from_float allows keyword 'f'.
if constructor == Constructor::Decimal {
// Only allow positional argument for Decimal.from_float
call.arguments.find_positional(0)
} else {
// Fraction.from_float allows either positional or 'f' keyword
call.arguments.find_argument_value("f", 0)
}
}
MethodName::FromDecimal => {
// from_decimal(dec) - should have exactly one positional argument or 'dec' keyword
call.arguments.find_argument_value("dec", 0)
}
}
}
/// Handle the special case for non-finite float literals
fn handle_non_finite_float_special_case(
call: &ExprCall,
method_name: MethodName,
constructor: Constructor,
arg_value: &Expr,
constructor_name: &str,
checker: &Checker,
) -> Option<Edit> {
// Only applies to Decimal.from_float
if !matches!(
(method_name, constructor),
(MethodName::FromFloat, Constructor::Decimal)
) {
return None;
}
let Expr::Call(ExprCall {
func, arguments, ..
}) = arg_value
else {
return None;
};
// Must be a call to the `float` builtin.
if !checker.semantic().match_builtin_expr(func, "float") {
return None;
}
// Must have exactly one argument, which is a string literal.
if !arguments.keywords.is_empty() {
return None;
}
let [float_arg] = arguments.args.as_ref() else {
return None;
};
let normalized = as_non_finite_float_string_literal(float_arg)?;
let replacement_text = format!(
r#"{constructor_name}("{}")"#,
// `Decimal.from_float(float(" -nan")) == Decimal("nan")`
if normalized == "-nan" {
// Here we do not attempt to remove just the '-' character.
// It may have been encoded (e.g. as '\N{hyphen-minus}')
// in the original source slice, and the added complexity
// does not make sense for this edge case.
"nan"
} else {
normalized
}
);
Some(Edit::range_replacement(replacement_text, call.range()))
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum MethodName {
FromFloat,
FromDecimal,
}
impl std::fmt::Display for MethodName {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
MethodName::FromFloat => fmt.write_str("from_float"),
MethodName::FromDecimal => fmt.write_str("from_decimal"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Constructor {
Decimal,
Fraction,
}
impl std::fmt::Display for Constructor {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Constructor::Decimal => fmt.write_str("Decimal"),
Constructor::Fraction => fmt.write_str("Fraction"),
}
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/for_loop_set_mutations.rs | crates/ruff_linter/src/rules/refurb/rules/for_loop_set_mutations.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, Stmt, StmtFor};
use ruff_python_semantic::analyze::typing;
use crate::checkers::ast::Checker;
use crate::rules::refurb::helpers::IterLocation;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
use crate::rules::refurb::helpers::parenthesize_loop_iter_if_necessary;
/// ## What it does
/// Checks for code that updates a set with the contents of an iterable by
/// using a `for` loop to call `.add()` or `.discard()` on each element
/// separately.
///
/// ## Why is this bad?
/// When adding or removing a batch of elements to or from a set, it's more
/// idiomatic to use a single method call rather than adding or removing
/// elements one by one.
///
/// ## Example
/// ```python
/// s = set()
///
/// for x in (1, 2, 3):
/// s.add(x)
///
/// for x in (1, 2, 3):
/// s.discard(x)
/// ```
///
/// Use instead:
/// ```python
/// s = set()
///
/// s.update((1, 2, 3))
/// s.difference_update((1, 2, 3))
/// ```
///
/// ## Fix safety
/// The fix will be marked as unsafe if applying the fix would delete any comments.
/// Otherwise, it is marked as safe.
///
/// ## References
/// - [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.3.5")]
pub(crate) struct ForLoopSetMutations {
method_name: &'static str,
batch_method_name: &'static str,
}
impl AlwaysFixableViolation for ForLoopSetMutations {
#[derive_message_formats]
fn message(&self) -> String {
format!("Use of `set.{}()` in a for loop", self.method_name)
}
fn fix_title(&self) -> String {
format!("Replace with `.{}()`", self.batch_method_name)
}
}
/// FURB142
pub(crate) fn for_loop_set_mutations(checker: &Checker, for_stmt: &StmtFor) {
if !for_stmt.orelse.is_empty() {
return;
}
let [Stmt::Expr(stmt_expr)] = for_stmt.body.as_slice() else {
return;
};
let Expr::Call(expr_call) = stmt_expr.value.as_ref() else {
return;
};
let Expr::Attribute(expr_attr) = expr_call.func.as_ref() else {
return;
};
if !expr_call.arguments.keywords.is_empty() {
return;
}
let (method_name, batch_method_name) = match expr_attr.attr.as_str() {
"add" => ("add", "update"),
"discard" => ("discard", "difference_update"),
_ => {
return;
}
};
let Expr::Name(set) = expr_attr.value.as_ref() else {
return;
};
if !checker
.semantic()
.resolve_name(set)
.is_some_and(|s| typing::is_set(checker.semantic().binding(s), checker.semantic()))
{
return;
}
let [arg] = expr_call.arguments.args.as_ref() else {
return;
};
let locator = checker.locator();
let content = match (for_stmt.target.as_ref(), arg) {
(Expr::Name(for_target), Expr::Name(arg)) if for_target.id == arg.id => {
format!(
"{}.{batch_method_name}({})",
set.id,
parenthesize_loop_iter_if_necessary(for_stmt, checker, IterLocation::Call),
)
}
(for_target, arg) => format!(
"{}.{batch_method_name}({} for {} in {})",
set.id,
locator.slice(arg),
locator.slice(for_target),
parenthesize_loop_iter_if_necessary(for_stmt, checker, IterLocation::Comprehension),
),
};
let applicability = if checker.comment_ranges().intersects(for_stmt.range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let fix = Fix::applicable_edit(
Edit::range_replacement(content, for_stmt.range),
applicability,
);
checker
.report_diagnostic(
ForLoopSetMutations {
method_name,
batch_method_name,
},
for_stmt.range,
)
.set_fix(fix);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/reimplemented_operator.rs | crates/ruff_linter/src/rules/refurb/rules/reimplemented_operator.rs | use std::borrow::Cow;
use std::fmt::{Debug, Display, Formatter};
use anyhow::Result;
use itertools::Itertools;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::helpers::any_over_expr;
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::{self as ast, Expr, ExprSlice, ExprSubscript, ExprTuple, Parameters, Stmt};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::{Ranged, TextRange};
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::importer::{ImportRequest, Importer};
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for lambda expressions and function definitions that can be replaced with a function from
/// the `operator` module.
///
/// ## Why is this bad?
/// The `operator` module provides functions that implement the same functionality as the
/// corresponding operators. For example, `operator.add` is often equivalent to `lambda x, y: x + y`.
/// Using the functions from the `operator` module is more concise and communicates the intent of
/// the code more clearly.
///
/// ## Example
/// ```python
/// import functools
///
/// nums = [1, 2, 3]
/// total = functools.reduce(lambda x, y: x + y, nums)
/// ```
///
/// Use instead:
/// ```python
/// import functools
/// import operator
///
/// nums = [1, 2, 3]
/// total = functools.reduce(operator.add, nums)
/// ```
///
/// ## Fix safety
/// The fix offered by this rule is always marked as unsafe. While the changes the fix would make
/// would rarely break your code, there are two ways in which functions from the `operator` module
/// differ from user-defined functions. It would be non-trivial for Ruff to detect whether or not
/// these differences would matter in a specific situation where Ruff is emitting a diagnostic for
/// this rule.
///
/// The first difference is that `operator` functions cannot be called with keyword arguments, but
/// most user-defined functions can. If an `add` function is defined as `add = lambda x, y: x + y`,
/// replacing this function with `operator.add` will cause the later call to raise `TypeError` if
/// the function is later called with keyword arguments, e.g. `add(x=1, y=2)`.
///
/// The second difference is that user-defined functions are [descriptors], but this is not true of
/// the functions defined in the `operator` module. Practically speaking, this means that defining
/// a function in a class body (either by using a `def` statement or assigning a `lambda` function
/// to a variable) is a valid way of defining an instance method on that class; monkeypatching a
/// user-defined function onto a class after the class has been created also has the same effect.
/// The same is not true of an `operator` function: assigning an `operator` function to a variable
/// in a class body or monkeypatching one onto a class will not create a valid instance method.
/// Ruff will refrain from emitting diagnostics for this rule on function definitions in class
/// bodies; however, it does not currently have sophisticated enough type inference to avoid
/// emitting this diagnostic if a user-defined function is being monkeypatched onto a class after
/// the class has been constructed.
///
/// [descriptors]: https://docs.python.org/3/howto/descriptor.html
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.1.9")]
pub(crate) struct ReimplementedOperator {
operator: Operator,
target: FunctionLikeKind,
}
impl Violation for ReimplementedOperator {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let ReimplementedOperator { operator, target } = self;
format!("Use `operator.{operator}` instead of defining a {target}")
}
fn fix_title(&self) -> Option<String> {
let ReimplementedOperator { operator, .. } = self;
Some(format!("Replace with `operator.{operator}`"))
}
}
/// FURB118
pub(crate) fn reimplemented_operator(checker: &Checker, target: &FunctionLike) {
// Ignore methods.
// Methods can be defined via a `def` statement in a class scope,
// or via a lambda appearing on the right-hand side of an assignment in a class scope.
if checker.semantic().current_scope().kind.is_class()
&& (target.is_function_def()
|| checker
.semantic()
.current_statements()
.any(|stmt| matches!(stmt, Stmt::AnnAssign(_) | Stmt::Assign(_))))
{
return;
}
// Skip decorated functions
if let FunctionLike::Function(func) = target {
if !func.decorator_list.is_empty() {
return;
}
}
let Some(params) = target.parameters() else {
return;
};
let Some(body) = target.body() else { return };
let Some(operator) = get_operator(body, params, checker.locator()) else {
return;
};
let fix = target.try_fix(&operator, checker.importer(), checker.semantic());
let mut diagnostic = checker.report_diagnostic(
ReimplementedOperator {
operator,
target: target.kind(),
},
target.range(),
);
diagnostic.try_set_optional_fix(|| fix);
}
/// Candidate for lambda expression or function definition consisting of a return statement.
#[derive(Debug)]
pub(crate) enum FunctionLike<'a> {
Lambda(&'a ast::ExprLambda),
Function(&'a ast::StmtFunctionDef),
}
impl<'a> From<&'a ast::ExprLambda> for FunctionLike<'a> {
fn from(lambda: &'a ast::ExprLambda) -> Self {
Self::Lambda(lambda)
}
}
impl<'a> From<&'a ast::StmtFunctionDef> for FunctionLike<'a> {
fn from(function: &'a ast::StmtFunctionDef) -> Self {
Self::Function(function)
}
}
impl Ranged for FunctionLike<'_> {
fn range(&self) -> TextRange {
match self {
Self::Lambda(expr) => expr.range(),
Self::Function(stmt) => stmt.identifier(),
}
}
}
impl FunctionLike<'_> {
/// Return the [`Parameters`] of the function-like node.
fn parameters(&self) -> Option<&Parameters> {
match self {
Self::Lambda(expr) => expr.parameters.as_deref(),
Self::Function(stmt) => Some(&stmt.parameters),
}
}
const fn is_function_def(&self) -> bool {
matches!(self, Self::Function(_))
}
/// Return the body of the function-like node.
///
/// If the node is a function definition that consists of more than a single return statement,
/// returns `None`.
fn body(&self) -> Option<&Expr> {
match self {
Self::Lambda(expr) => Some(&expr.body),
Self::Function(stmt) => match stmt.body.as_slice() {
[Stmt::Return(ast::StmtReturn { value, .. })] => value.as_deref(),
_ => None,
},
}
}
/// Return the display kind of the function-like node.
fn kind(&self) -> FunctionLikeKind {
match self {
Self::Lambda(_) => FunctionLikeKind::Lambda,
Self::Function(_) => FunctionLikeKind::Function,
}
}
/// Attempt to fix the function-like node by replacing it with a call to the corresponding
/// function from `operator` module.
fn try_fix(
&self,
operator: &Operator,
importer: &Importer,
semantic: &SemanticModel,
) -> Result<Option<Fix>> {
match self {
Self::Lambda(_) => {
let (edit, binding) = importer.get_or_import_symbol(
&ImportRequest::import("operator", operator.name),
self.start(),
semantic,
)?;
let content = if operator.args.is_empty() {
binding
} else {
format!("{binding}({})", operator.args.join(", "))
};
Ok(Some(Fix::unsafe_edits(
Edit::range_replacement(content, self.range()),
[edit],
)))
}
Self::Function(_) => Ok(None),
}
}
}
/// Convert the slice expression to the string representation of `slice` call.
/// For example, expression `1:2` will be `slice(1, 2)`, and `:` will be `slice(None)`.
fn slice_expr_to_slice_call(slice: &ExprSlice, locator: &Locator) -> String {
let stringify = |expr: Option<&Expr>| expr.map_or("None", |expr| locator.slice(expr));
match (
slice.lower.as_deref(),
slice.upper.as_deref(),
slice.step.as_deref(),
) {
(lower, upper, step @ Some(_)) => format!(
"slice({}, {}, {})",
stringify(lower),
stringify(upper),
stringify(step)
),
(None, upper, None) => format!("slice({})", stringify(upper)),
(lower @ Some(_), upper, None) => {
format!("slice({}, {})", stringify(lower), stringify(upper))
}
}
}
/// Convert the given expression to a string representation, suitable to be a function argument.
fn subscript_slice_to_string<'a>(expr: &Expr, locator: &Locator<'a>) -> Cow<'a, str> {
if let Expr::Slice(expr_slice) = expr {
Cow::Owned(slice_expr_to_slice_call(expr_slice, locator))
} else if let Expr::Tuple(tuple) = expr {
if locator.slice(tuple).contains(':') {
// We cannot perform a trivial replacement if there's a `:` in the expression
let inner = tuple
.iter()
.map(|expr| match expr {
Expr::Slice(expr) => Cow::Owned(slice_expr_to_slice_call(expr, locator)),
_ => Cow::Borrowed(locator.slice(expr)),
})
.join(", ");
Cow::Owned(format!("({inner})"))
} else if tuple.parenthesized {
Cow::Borrowed(locator.slice(expr))
} else {
Cow::Owned(format!("({})", locator.slice(tuple)))
}
} else {
Cow::Borrowed(locator.slice(expr))
}
}
/// Return the `operator` implemented by given subscript expression.
fn itemgetter_op(expr: &ExprSubscript, params: &Parameters, locator: &Locator) -> Option<Operator> {
let [arg] = params.args.as_slice() else {
return None;
};
// The argument to the lambda must match the subscripted value, as in: `lambda x: x[1]`.
if !is_same_expression(arg, &expr.value) {
return None;
}
// The subscripted expression can't contain references to the argument, as in: `lambda x: x[x]`.
if any_over_expr(expr.slice.as_ref(), &|expr| is_same_expression(arg, expr)) {
return None;
}
Some(Operator {
name: "itemgetter",
args: vec![subscript_slice_to_string(expr.slice.as_ref(), locator).to_string()],
})
}
/// Return the `operator` implemented by given tuple expression.
fn itemgetter_op_tuple(
expr: &ExprTuple,
params: &Parameters,
locator: &Locator,
) -> Option<Operator> {
let [arg] = params.args.as_slice() else {
return None;
};
if expr.len() <= 1 {
return None;
}
Some(Operator {
name: "itemgetter",
args: expr
.iter()
.map(|expr| {
expr.as_subscript_expr()
.filter(|expr| is_same_expression(arg, &expr.value))
.map(|expr| expr.slice.as_ref())
.map(|slice| subscript_slice_to_string(slice, locator).to_string())
})
.collect::<Option<Vec<_>>>()?,
})
}
#[derive(Eq, PartialEq, Debug)]
struct Operator {
name: &'static str,
args: Vec<String>,
}
impl From<&'static str> for Operator {
fn from(value: &'static str) -> Self {
Self {
name: value,
args: vec![],
}
}
}
impl Display for Operator {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)?;
if self.args.is_empty() {
Ok(())
} else {
write!(f, "({})", self.args.join(", "))
}
}
}
/// Return the `operator` implemented by the given expression.
fn get_operator(expr: &Expr, params: &Parameters, locator: &Locator) -> Option<Operator> {
match expr {
Expr::UnaryOp(expr) => unary_op(expr, params).map(Operator::from),
Expr::BinOp(expr) => bin_op(expr, params).map(Operator::from),
Expr::Compare(expr) => cmp_op(expr, params).map(Operator::from),
Expr::Subscript(expr) => itemgetter_op(expr, params, locator),
Expr::Tuple(expr) => itemgetter_op_tuple(expr, params, locator),
_ => None,
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum FunctionLikeKind {
Lambda,
Function,
}
impl FunctionLikeKind {
const fn as_str(self) -> &'static str {
match self {
Self::Lambda => "lambda",
Self::Function => "function",
}
}
}
impl Display for FunctionLikeKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// Return the name of the `operator` implemented by the given unary expression.
fn unary_op(expr: &ast::ExprUnaryOp, params: &Parameters) -> Option<&'static str> {
let [arg] = params.args.as_slice() else {
return None;
};
if !is_same_expression(arg, &expr.operand) {
return None;
}
Some(match expr.op {
ast::UnaryOp::Invert => "invert",
ast::UnaryOp::Not => "not_",
ast::UnaryOp::UAdd => "pos",
ast::UnaryOp::USub => "neg",
})
}
/// Return the name of the `operator` implemented by the given binary expression.
fn bin_op(expr: &ast::ExprBinOp, params: &Parameters) -> Option<&'static str> {
let [arg1, arg2] = params.args.as_slice() else {
return None;
};
if !is_same_expression(arg1, &expr.left) || !is_same_expression(arg2, &expr.right) {
return None;
}
Some(match expr.op {
ast::Operator::Add => "add",
ast::Operator::Sub => "sub",
ast::Operator::Mult => "mul",
ast::Operator::MatMult => "matmul",
ast::Operator::Div => "truediv",
ast::Operator::Mod => "mod",
ast::Operator::Pow => "pow",
ast::Operator::LShift => "lshift",
ast::Operator::RShift => "rshift",
ast::Operator::BitOr => "or_",
ast::Operator::BitXor => "xor",
ast::Operator::BitAnd => "and_",
ast::Operator::FloorDiv => "floordiv",
})
}
/// Return the name of the `operator` implemented by the given comparison expression.
fn cmp_op(expr: &ast::ExprCompare, params: &Parameters) -> Option<&'static str> {
let [arg1, arg2] = params.args.as_slice() else {
return None;
};
let [op] = &*expr.ops else {
return None;
};
let [right] = &*expr.comparators else {
return None;
};
match op {
ast::CmpOp::Eq => match_arguments(arg1, arg2, &expr.left, right).then_some("eq"),
ast::CmpOp::NotEq => match_arguments(arg1, arg2, &expr.left, right).then_some("ne"),
ast::CmpOp::Lt => match_arguments(arg1, arg2, &expr.left, right).then_some("lt"),
ast::CmpOp::LtE => match_arguments(arg1, arg2, &expr.left, right).then_some("le"),
ast::CmpOp::Gt => match_arguments(arg1, arg2, &expr.left, right).then_some("gt"),
ast::CmpOp::GtE => match_arguments(arg1, arg2, &expr.left, right).then_some("ge"),
ast::CmpOp::Is => match_arguments(arg1, arg2, &expr.left, right).then_some("is_"),
ast::CmpOp::IsNot => match_arguments(arg1, arg2, &expr.left, right).then_some("is_not"),
ast::CmpOp::In => {
// Note: `operator.contains` reverses the order of arguments. That is:
// `operator.contains` is equivalent to `lambda x, y: y in x`, rather than
// `lambda x, y: x in y`.
match_arguments(arg1, arg2, right, &expr.left).then_some("contains")
}
ast::CmpOp::NotIn => None,
}
}
/// Returns `true` if the given arguments match the expected operands.
fn match_arguments(
arg1: &ast::ParameterWithDefault,
arg2: &ast::ParameterWithDefault,
operand1: &Expr,
operand2: &Expr,
) -> bool {
is_same_expression(arg1, operand1) && is_same_expression(arg2, operand2)
}
/// Returns `true` if the given argument is the "same" as the given expression. For example, if
/// the argument has a default, it is not considered the same as any expression; if both match the
/// same name, they are considered the same.
fn is_same_expression(param: &ast::ParameterWithDefault, expr: &Expr) -> bool {
if param.default.is_some() {
false
} else if let Expr::Name(name) = expr {
name.id == param.name().as_str()
} else {
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/refurb/rules/verbose_decimal_constructor.rs | crates/ruff_linter/src/rules/refurb/rules/verbose_decimal_constructor.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use itertools::Itertools;
use ruff_python_ast::{self as ast, Expr};
use ruff_python_trivia::PythonWhitespace;
use ruff_text_size::Ranged;
use std::borrow::Cow;
use crate::checkers::ast::Checker;
use crate::linter::float::as_non_finite_float_string_literal;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for unnecessary string literal or float casts in `Decimal`
/// constructors.
///
/// ## Why is this bad?
/// The `Decimal` constructor accepts a variety of arguments, including
/// integers, floats, and strings. However, it's not necessary to cast
/// integer literals to strings when passing them to the `Decimal`.
///
/// Similarly, `Decimal` accepts `inf`, `-inf`, and `nan` as string literals,
/// so there's no need to wrap those values in a `float` call when passing
/// them to the `Decimal` constructor.
///
/// Prefer the more concise form of argument passing for `Decimal`
/// constructors, as it's more readable and idiomatic.
///
/// Note that this rule does not flag quoted float literals such as `Decimal("0.1")`, which will
/// produce a more precise `Decimal` value than the unquoted `Decimal(0.1)`.
///
/// ## Example
/// ```python
/// from decimal import Decimal
///
/// Decimal("0")
/// Decimal(float("Infinity"))
/// ```
///
/// Use instead:
/// ```python
/// from decimal import Decimal
///
/// Decimal(0)
/// Decimal("Infinity")
/// ```
///
/// ## References
/// - [Python documentation: `decimal`](https://docs.python.org/3/library/decimal.html)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct VerboseDecimalConstructor {
replacement: String,
}
impl Violation for VerboseDecimalConstructor {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Always;
#[derive_message_formats]
fn message(&self) -> String {
"Verbose expression in `Decimal` constructor".to_string()
}
fn fix_title(&self) -> Option<String> {
let VerboseDecimalConstructor { replacement } = self;
Some(format!("Replace with `{replacement}`"))
}
}
/// FURB157
pub(crate) fn verbose_decimal_constructor(checker: &Checker, call: &ast::ExprCall) {
if !checker
.semantic()
.resolve_qualified_name(&call.func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["decimal", "Decimal"]))
{
return;
}
// Decimal accepts arguments of the form: `Decimal(value='0', context=None)`
let Some(value) = call.arguments.find_argument_value("value", 0) else {
return;
};
match value {
Expr::StringLiteral(ast::ExprStringLiteral {
value: str_literal, ..
}) => {
// Parse the inner string as an integer.
//
// For reference, a string argument to `Decimal` is parsed in CPython
// using this regex:
// https://github.com/python/cpython/blob/ac556a2ad1213b8bb81372fe6fb762f5fcb076de/Lib/_pydecimal.py#L6060-L6077
// _after_ trimming whitespace from the string and removing all occurrences of "_".
let original_str = str_literal.to_str().trim_whitespace();
// Strip leading underscores before extracting the sign, as Python's Decimal parser
// removes underscores before parsing the sign.
let sign_check_str = original_str.trim_start_matches('_');
// Extract the unary sign, if any.
let (unary, sign_check_str) = if let Some(trimmed) = sign_check_str.strip_prefix('+') {
("+", trimmed)
} else if let Some(trimmed) = sign_check_str.strip_prefix('-') {
("-", trimmed)
} else {
("", sign_check_str)
};
// Save the string after the sign for normalization (before removing underscores)
let str_after_sign_for_normalization = sign_check_str;
let mut rest = Cow::from(sign_check_str);
let has_digit_separators = memchr::memchr(b'_', original_str.as_bytes()).is_some();
if has_digit_separators {
rest = Cow::from(rest.replace('_', ""));
}
// Early return if we now have an empty string
// or a very long string:
if (rest.len() > PYTHONINTMAXSTRDIGITS) || (rest.is_empty()) {
return;
}
// Skip leading zeros.
let rest = rest.trim_start_matches('0');
// Verify that the rest of the string is a valid integer.
if !rest.bytes().all(|c| c.is_ascii_digit()) {
return;
}
// If the original string had digit separators, normalize them
let rest = if has_digit_separators {
Cow::from(normalize_digit_separators(str_after_sign_for_normalization))
} else {
Cow::from(rest)
};
// If all the characters are zeros, then the value is zero.
let rest = match (unary, rest.is_empty()) {
// `Decimal("-0")` is not the same as `Decimal("0")`
// so we return early.
("-", true) => {
return;
}
(_, true) => "0",
_ => &rest,
};
let replacement = format!("{unary}{rest}");
let mut diagnostic = checker.report_diagnostic(
VerboseDecimalConstructor {
replacement: replacement.clone(),
},
value.range(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
replacement,
value.range(),
)));
}
Expr::Call(ast::ExprCall {
func, arguments, ..
}) => {
// Must be a call to the `float` builtin.
if !checker.semantic().match_builtin_expr(func, "float") {
return;
}
// Must have exactly one argument, which is a string literal.
if !arguments.keywords.is_empty() {
return;
}
let [float] = arguments.args.as_ref() else {
return;
};
let Some(float_str) = as_non_finite_float_string_literal(float) else {
return;
};
let mut replacement = checker.locator().slice(float).to_string();
// `Decimal(float("-nan")) == Decimal("nan")`
if float_str == "-nan" {
// Here we do not attempt to remove just the '-' character.
// It may have been encoded (e.g. as '\N{hyphen-minus}')
// in the original source slice, and the added complexity
// does not make sense for this edge case.
replacement = "\"nan\"".to_string();
}
let mut diagnostic = checker.report_diagnostic(
VerboseDecimalConstructor {
replacement: replacement.clone(),
},
value.range(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
replacement,
value.range(),
)));
}
_ => {}
}
}
/// Normalizes digit separators in a numeric string by:
/// - Stripping leading and trailing underscores
/// - Collapsing medial underscore sequences to single underscores
fn normalize_digit_separators(original_str: &str) -> String {
// Strip leading and trailing underscores
let trimmed = original_str
.trim_start_matches(['_', '0'])
.trim_end_matches('_');
// Collapse medial underscore sequences to single underscores
trimmed
.chars()
.dedup_by(|a, b| *a == '_' && a == b)
.collect()
}
// ```console
// $ python
// >>> import sys
// >>> sys.int_info.str_digits_check_threshold
// 640
// ```
const PYTHONINTMAXSTRDIGITS: usize = 640;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs | crates/ruff_linter/src/rules/refurb/rules/slice_to_remove_prefix_or_suffix.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, PythonVersion};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for code that could be written more idiomatically using
/// [`str.removeprefix()`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)
/// or [`str.removesuffix()`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix).
///
/// Specifically, the rule flags code that conditionally removes a prefix or suffix
/// using a slice operation following an `if` test that uses `str.startswith()` or `str.endswith()`.
///
/// The rule is only applied if your project targets Python 3.9 or later.
///
/// ## Why is this bad?
/// The methods [`str.removeprefix()`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)
/// and [`str.removesuffix()`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix),
/// introduced in Python 3.9, have the same behavior while being more readable and efficient.
///
/// ## Example
/// ```python
/// def example(filename: str, text: str):
/// filename = filename[:-4] if filename.endswith(".txt") else filename
///
/// if text.startswith("pre"):
/// text = text[3:]
/// ```
///
/// Use instead:
/// ```python
/// def example(filename: str, text: str):
/// filename = filename.removesuffix(".txt")
/// text = text.removeprefix("pre")
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.9.0")]
pub(crate) struct SliceToRemovePrefixOrSuffix {
affix_kind: AffixKind,
stmt_or_expression: StmtOrExpr,
}
impl AlwaysFixableViolation for SliceToRemovePrefixOrSuffix {
#[derive_message_formats]
fn message(&self) -> String {
match self.affix_kind {
AffixKind::StartsWith => {
"Prefer `str.removeprefix()` over conditionally replacing with slice.".to_string()
}
AffixKind::EndsWith => {
"Prefer `str.removesuffix()` over conditionally replacing with slice.".to_string()
}
}
}
fn fix_title(&self) -> String {
let method_name = self.affix_kind.as_str();
let replacement = self.affix_kind.replacement();
let context = match self.stmt_or_expression {
StmtOrExpr::Statement => "assignment",
StmtOrExpr::Expression => "ternary expression",
};
format!("Use {replacement} instead of {context} conditional upon {method_name}.")
}
}
/// FURB188
pub(crate) fn slice_to_remove_affix_expr(checker: &Checker, if_expr: &ast::ExprIf) {
if checker.target_version() < PythonVersion::PY39 {
return;
}
if let Some(removal_data) = affix_removal_data_expr(if_expr) {
if affix_matches_slice_bound(&removal_data, checker.semantic()) {
let kind = removal_data.affix_query.kind;
let text = removal_data.text;
let mut diagnostic = checker.report_diagnostic(
SliceToRemovePrefixOrSuffix {
affix_kind: kind,
stmt_or_expression: StmtOrExpr::Expression,
},
if_expr.range,
);
let replacement =
generate_removeaffix_expr(text, &removal_data.affix_query, checker.locator());
diagnostic.set_fix(Fix::safe_edit(Edit::replacement(
replacement,
if_expr.start(),
if_expr.end(),
)));
}
}
}
/// FURB188
pub(crate) fn slice_to_remove_affix_stmt(checker: &Checker, if_stmt: &ast::StmtIf) {
if checker.target_version() < PythonVersion::PY39 {
return;
}
if let Some(removal_data) = affix_removal_data_stmt(if_stmt) {
if affix_matches_slice_bound(&removal_data, checker.semantic()) {
let kind = removal_data.affix_query.kind;
let text = removal_data.text;
let mut diagnostic = checker.report_diagnostic(
SliceToRemovePrefixOrSuffix {
affix_kind: kind,
stmt_or_expression: StmtOrExpr::Statement,
},
if_stmt.range,
);
let replacement = generate_assignment_with_removeaffix(
text,
&removal_data.affix_query,
checker.locator(),
);
diagnostic.set_fix(Fix::safe_edit(Edit::replacement(
replacement,
if_stmt.start(),
if_stmt.end(),
)));
}
}
}
/// Given an expression of the form:
///
/// ```python
/// text[slice] if text.func(affix) else text
/// ```
///
/// where `func` is either `startswith` or `endswith`,
/// this function collects `text`,`func`, `affix`, and the non-null
/// bound of the slice. Otherwise, returns `None`.
fn affix_removal_data_expr(if_expr: &ast::ExprIf) -> Option<RemoveAffixData<'_>> {
let ast::ExprIf {
test,
body,
orelse,
range: _,
node_index: _,
} = if_expr;
let ast::ExprSubscript { value, slice, .. } = body.as_subscript_expr()?;
// Variable names correspond to:
// ```python
// value[slice] if test else orelse
// ```
affix_removal_data(value, test, orelse, slice)
}
/// Given a statement of the form:
///
/// ```python
/// if text.func(affix):
/// text = text[slice]
/// ```
///
/// where `func` is either `startswith` or `endswith`,
/// this function collects `text`,`func`, `affix`, and the non-null
/// bound of the slice. Otherwise, returns `None`.
fn affix_removal_data_stmt(if_stmt: &ast::StmtIf) -> Option<RemoveAffixData<'_>> {
let ast::StmtIf {
test,
body,
elif_else_clauses,
range: _,
node_index: _,
} = if_stmt;
// Cannot safely transform, e.g.,
// ```python
// if text.startswith(prefix):
// text = text[len(prefix):]
// else:
// text = "something completely different"
// ```
if !elif_else_clauses.is_empty() {
return None;
}
// Cannot safely transform, e.g.,
// ```python
// if text.startswith(prefix):
// text = f"{prefix} something completely different"
// text = text[len(prefix):]
// ```
let [statement] = body.as_slice() else {
return None;
};
// Variable names correspond to:
// ```python
// if test:
// else_or_target_name = value[slice]
// ```
let ast::StmtAssign {
value,
targets,
range: _,
node_index: _,
} = statement.as_assign_stmt()?;
let [target] = targets.as_slice() else {
return None;
};
let ast::ExprSubscript { value, slice, .. } = value.as_subscript_expr()?;
affix_removal_data(value, test, target, slice)
}
/// Suppose given a statement of the form:
/// ```python
/// if test:
/// else_or_target_name = value[slice]
/// ```
/// or an expression of the form:
/// ```python
/// value[slice] if test else else_or_target_name
/// ```
/// This function verifies that
/// - `value` and `else_or_target_name`
/// are equal to a common name `text`
/// - `test` is of the form `text.startswith(prefix)`
/// or `text.endswith(suffix)`
/// - `slice` has no upper bound in the case of a prefix,
/// and no lower bound in the case of a suffix
///
/// If these conditions are satisfied, the function
/// returns the corresponding `RemoveAffixData` object;
/// otherwise it returns `None`.
fn affix_removal_data<'a>(
value: &'a ast::Expr,
test: &'a ast::Expr,
else_or_target: &'a ast::Expr,
slice: &'a ast::Expr,
) -> Option<RemoveAffixData<'a>> {
let compr_value = ast::comparable::ComparableExpr::from(value);
let compr_else_or_target = ast::comparable::ComparableExpr::from(else_or_target);
if compr_value != compr_else_or_target {
return None;
}
let slice = slice.as_slice_expr()?;
// Exit early if slice step is...
if slice
.step
.as_deref()
// present and
.is_some_and(|step| match step {
// not equal to 1
ast::Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(x),
..
}) => x.as_u8() != Some(1),
// and not equal to `None` or `True`
ast::Expr::NoneLiteral(_)
| ast::Expr::BooleanLiteral(ast::ExprBooleanLiteral { value: true, .. }) => false,
_ => true,
})
{
return None;
}
let compr_test_expr = ast::comparable::ComparableExpr::from(
&test.as_call_expr()?.func.as_attribute_expr()?.value,
);
let func_name = test
.as_call_expr()?
.func
.as_attribute_expr()?
.attr
.id
.as_str();
let func_args = &test.as_call_expr()?.arguments.args;
let [affix] = func_args.as_ref() else {
return None;
};
if compr_value != compr_test_expr || compr_test_expr != compr_else_or_target {
return None;
}
let (affix_kind, bound) = match func_name {
"startswith" if slice.upper.is_none() => (AffixKind::StartsWith, slice.lower.as_ref()?),
"endswith" if slice.lower.is_none() => (AffixKind::EndsWith, slice.upper.as_ref()?),
_ => return None,
};
Some(RemoveAffixData {
text: value,
bound,
affix_query: AffixQuery {
kind: affix_kind,
affix,
},
})
}
/// Tests whether the slice of the given string actually removes the
/// detected affix.
///
/// For example, in the situation
///
/// ```python
/// text[:bound] if text.endswith(suffix) else text
/// ```
///
/// This function verifies that `bound == -len(suffix)` in two cases:
/// - `suffix` is a string literal and `bound` is a number literal
/// - `suffix` is an expression and `bound` is
/// exactly `-len(suffix)` (as AST nodes, prior to evaluation.)
fn affix_matches_slice_bound(data: &RemoveAffixData, semantic: &SemanticModel) -> bool {
let RemoveAffixData {
text: _,
bound,
affix_query: AffixQuery { kind, affix },
} = *data;
match (kind, bound, affix) {
(
AffixKind::StartsWith,
ast::Expr::NumberLiteral(ast::ExprNumberLiteral {
value: num,
range: _,
node_index: _,
}),
ast::Expr::StringLiteral(ast::ExprStringLiteral {
range: _,
node_index: _,
value: string_val,
}),
) => num
.as_int()
// Only support prefix removal for size at most `usize::MAX`
.and_then(ast::Int::as_usize)
.is_some_and(|x| x == string_val.chars().count()),
(
AffixKind::StartsWith,
ast::Expr::Call(ast::ExprCall {
range: _,
node_index: _,
func,
arguments,
}),
_,
) => {
arguments.len() == 1
&& arguments.find_positional(0).is_some_and(|arg| {
let compr_affix = ast::comparable::ComparableExpr::from(affix);
let compr_arg = ast::comparable::ComparableExpr::from(arg);
compr_affix == compr_arg
})
&& semantic.match_builtin_expr(func, "len")
}
(
AffixKind::EndsWith,
ast::Expr::UnaryOp(ast::ExprUnaryOp {
op: ast::UnaryOp::USub,
operand,
range: _,
node_index: _,
}),
ast::Expr::StringLiteral(ast::ExprStringLiteral {
range: _,
node_index: _,
value: string_val,
}),
) if operand.is_number_literal_expr() => operand.as_number_literal_expr().is_some_and(
|ast::ExprNumberLiteral { value, .. }| {
// Only support prefix removal for size at most `u32::MAX`
value
.as_int()
.and_then(ast::Int::as_usize)
.is_some_and(|x| x == string_val.chars().count())
},
),
(
AffixKind::EndsWith,
ast::Expr::UnaryOp(ast::ExprUnaryOp {
op: ast::UnaryOp::USub,
operand,
range: _,
node_index: _,
}),
_,
) => operand.as_call_expr().is_some_and(
|ast::ExprCall {
range: _,
node_index: _,
func,
arguments,
}| {
arguments.len() == 1
&& arguments.find_positional(0).is_some_and(|arg| {
let compr_affix = ast::comparable::ComparableExpr::from(affix);
let compr_arg = ast::comparable::ComparableExpr::from(arg);
compr_affix == compr_arg
})
&& semantic.match_builtin_expr(func, "len")
},
),
_ => false,
}
}
/// Generates the source code string
/// ```python
/// text = text.removeprefix(prefix)
/// ```
/// or
/// ```python
/// text = text.removesuffix(prefix)
/// ```
/// as appropriate.
fn generate_assignment_with_removeaffix(
text: &ast::Expr,
affix_query: &AffixQuery,
locator: &Locator,
) -> String {
let text_str = locator.slice(text);
let affix_str = locator.slice(affix_query.affix);
let replacement = affix_query.kind.replacement();
format!("{text_str} = {text_str}.{replacement}({affix_str})")
}
/// Generates the source code string
/// ```python
/// text.removeprefix(prefix)
/// ```
/// or
///
/// ```python
/// text.removesuffix(suffix)
/// ```
/// as appropriate.
fn generate_removeaffix_expr(
text: &ast::Expr,
affix_query: &AffixQuery,
locator: &Locator,
) -> String {
let text_str = locator.slice(text);
let affix_str = locator.slice(affix_query.affix);
let replacement = affix_query.kind.replacement();
format!("{text_str}.{replacement}({affix_str})")
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum StmtOrExpr {
Statement,
Expression,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum AffixKind {
StartsWith,
EndsWith,
}
impl AffixKind {
const fn as_str(self) -> &'static str {
match self {
Self::StartsWith => "startswith",
Self::EndsWith => "endswith",
}
}
const fn replacement(self) -> &'static str {
match self {
Self::StartsWith => "removeprefix",
Self::EndsWith => "removesuffix",
}
}
}
/// Components of `startswith(prefix)` or `endswith(suffix)`.
#[derive(Debug)]
struct AffixQuery<'a> {
/// Whether the method called is `startswith` or `endswith`.
kind: AffixKind,
/// Node representing the prefix or suffix being passed to the string method.
affix: &'a ast::Expr,
}
/// Ingredients for a statement or expression
/// which potentially removes a prefix or suffix from a string.
///
/// Specifically
#[derive(Debug)]
struct RemoveAffixData<'a> {
/// Node representing the string whose prefix or suffix we want to remove
text: &'a ast::Expr,
/// Node representing the bound used to slice the string
bound: &'a ast::Expr,
/// Contains the prefix or suffix used in `text.startswith(prefix)` or `text.endswith(suffix)`
affix_query: AffixQuery<'a>,
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/fstring_number_format.rs | crates/ruff_linter/src/rules/refurb/rules/fstring_number_format.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprCall, Number, PythonVersion, UnaryOp};
use ruff_source_file::find_newline;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `bin(...)[2:]` (or `hex`, or `oct`) to convert
/// an integer into a string.
///
/// ## Why is this bad?
/// When converting an integer to a baseless binary, hexadecimal, or octal
/// string, using f-strings is more concise and readable than using the
/// `bin`, `hex`, or `oct` functions followed by a slice.
///
/// ## Example
/// ```python
/// print(bin(1337)[2:])
/// ```
///
/// Use instead:
/// ```python
/// print(f"{1337:b}")
/// ```
///
/// ## Fix safety
/// The fix is only marked as safe for integer literals, all other cases
/// are display-only, as they may change the runtime behaviour of the program
/// or introduce syntax errors.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.13.0")]
pub(crate) struct FStringNumberFormat {
replacement: Option<SourceCodeSnippet>,
base: Base,
}
impl Violation for FStringNumberFormat {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let FStringNumberFormat { replacement, base } = self;
let function_name = base.function_name();
if let Some(display) = replacement
.as_ref()
.and_then(SourceCodeSnippet::full_display)
{
format!("Replace `{function_name}` call with `{display}`")
} else {
format!("Replace `{function_name}` call with f-string")
}
}
fn fix_title(&self) -> Option<String> {
if let Some(display) = self
.replacement
.as_ref()
.and_then(SourceCodeSnippet::full_display)
{
Some(format!("Replace with `{display}`"))
} else {
Some("Replace with f-string".to_string())
}
}
}
/// FURB116
pub(crate) fn fstring_number_format(checker: &Checker, subscript: &ast::ExprSubscript) {
// The slice must be exactly `[2:]`.
let Expr::Slice(ast::ExprSlice {
lower: Some(lower),
upper: None,
step: None,
..
}) = subscript.slice.as_ref()
else {
return;
};
let Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(int),
..
}) = lower.as_ref()
else {
return;
};
if *int != 2 {
return;
}
// The call must be exactly `hex(...)`, `bin(...)`, or `oct(...)`.
let Expr::Call(ExprCall {
func, arguments, ..
}) = subscript.value.as_ref()
else {
return;
};
if !arguments.keywords.is_empty() {
return;
}
let [arg] = &*arguments.args else {
return;
};
let Some(id) = checker.semantic().resolve_builtin_symbol(func) else {
return;
};
let Some(base) = Base::from_str(id) else {
return;
};
// float and complex numbers are false positives, ignore them.
if matches!(
arg,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: Number::Float(_) | Number::Complex { .. },
..
})
) {
return;
}
let maybe_number = if let Some(maybe_number) = arg
.as_unary_op_expr()
.filter(|unary_expr| unary_expr.op == UnaryOp::UAdd)
.map(|unary_expr| &unary_expr.operand)
{
maybe_number
} else {
arg
};
let applicability = if matches!(maybe_number, Expr::NumberLiteral(_)) {
Applicability::Safe
} else {
Applicability::DisplayOnly
};
let replacement = try_create_replacement(checker, arg, base);
let mut diagnostic = checker.report_diagnostic(
FStringNumberFormat {
replacement: replacement.as_deref().map(SourceCodeSnippet::from_str),
base,
},
subscript.range(),
);
if let Some(replacement) = replacement {
let edit = Edit::range_replacement(replacement, subscript.range());
diagnostic.set_fix(Fix::applicable_edit(edit, applicability));
}
}
/// Generate a replacement, if possible.
fn try_create_replacement(checker: &Checker, arg: &Expr, base: Base) -> Option<String> {
if !matches!(
arg,
Expr::NumberLiteral(_) | Expr::Name(_) | Expr::Attribute(_) | Expr::UnaryOp(_)
) {
return None;
}
let inner_source = checker.locator().slice(arg);
// On Python 3.11 and earlier, trying to replace an `arg` that contains a backslash
// would create a `SyntaxError` in the f-string.
if checker.target_version() <= PythonVersion::PY311 && inner_source.contains('\\') {
return None;
}
// On Python 3.11 and earlier, trying to replace an `arg` that spans multiple lines
// would create a `SyntaxError` in the f-string.
if checker.target_version() <= PythonVersion::PY311 && find_newline(inner_source).is_some() {
return None;
}
let quote = checker.stylist().quote();
let shorthand = base.shorthand();
// If the `arg` contains double quotes we need to create the f-string with single quotes
// to avoid a `SyntaxError` in Python 3.11 and earlier.
if checker.target_version() <= PythonVersion::PY311 && inner_source.contains(quote.as_str()) {
return None;
}
// If the `arg` contains a brace add an space before it to avoid a `SyntaxError`
// in the f-string.
if inner_source.starts_with('{') {
Some(format!("f{quote}{{ {inner_source}:{shorthand}}}{quote}"))
} else {
Some(format!("f{quote}{{{inner_source}:{shorthand}}}{quote}"))
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Base {
Hex,
Bin,
Oct,
}
impl Base {
/// Returns the shorthand for the base.
fn shorthand(self) -> &'static str {
match self {
Base::Hex => "x",
Base::Bin => "b",
Base::Oct => "o",
}
}
/// Returns the builtin function name for the base.
fn function_name(self) -> &'static str {
match self {
Base::Hex => "hex",
Base::Bin => "bin",
Base::Oct => "oct",
}
}
/// Parses the base from a string.
fn from_str(s: &str) -> Option<Self> {
match s {
"hex" => Some(Base::Hex),
"bin" => Some(Base::Bin),
"oct" => Some(Base::Oct),
_ => 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/refurb/rules/isinstance_type_none.rs | crates/ruff_linter/src/rules/refurb/rules/isinstance_type_none.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, Operator};
use ruff_python_semantic::SemanticModel;
use crate::checkers::ast::Checker;
use crate::rules::refurb::helpers::replace_with_identity_check;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `isinstance` that check if an object is of type `None`.
///
/// ## Why is this bad?
/// There is only ever one instance of `None`, so it is more efficient and
/// readable to use the `is` operator to check if an object is `None`.
///
/// ## Example
/// ```python
/// isinstance(obj, type(None))
/// ```
///
/// Use instead:
/// ```python
/// obj is None
/// ```
///
/// ## Fix safety
/// The fix will be marked as unsafe if there are any comments within the call.
///
/// ## References
/// - [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)
/// - [Python documentation: `None`](https://docs.python.org/3/library/constants.html#None)
/// - [Python documentation: `type`](https://docs.python.org/3/library/functions.html#type)
/// - [Python documentation: Identity comparisons](https://docs.python.org/3/reference/expressions.html#is-not)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct IsinstanceTypeNone;
impl Violation for IsinstanceTypeNone {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `is` operator over `isinstance` to check if an object is `None`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `is` operator".to_string())
}
}
/// FURB168
pub(crate) fn isinstance_type_none(checker: &Checker, call: &ast::ExprCall) {
let semantic = checker.semantic();
let (func, arguments) = (&call.func, &call.arguments);
if !arguments.keywords.is_empty() {
return;
}
let [expr, types] = arguments.args.as_ref() else {
return;
};
if !semantic.match_builtin_expr(func, "isinstance") {
return;
}
if !is_none(types, semantic) {
return;
}
let fix = replace_with_identity_check(expr, call.range, false, checker);
checker
.report_diagnostic(IsinstanceTypeNone, call.range)
.set_fix(fix);
}
/// Returns `true` if the given expression is equivalent to checking if the
/// object type is `None` when used with the `isinstance` builtin.
fn is_none(expr: &Expr, semantic: &SemanticModel) -> bool {
fn inner(expr: &Expr, in_union_context: bool, semantic: &SemanticModel) -> bool {
match expr {
// Ex) `None`
// Note: `isinstance` only accepts `None` as a type when used with
// the union operator, so we need to check if we're in a union.
Expr::NoneLiteral(_) if in_union_context => true,
// Ex) `type(None)`
Expr::Call(ast::ExprCall {
func, arguments, ..
}) => {
if !semantic.match_builtin_expr(func, "type") {
return false;
}
if !arguments.keywords.is_empty() {
return false;
}
matches!(arguments.args.as_ref(), [Expr::NoneLiteral(_)])
}
// Ex) `(type(None),)`
Expr::Tuple(tuple) => {
!tuple.is_empty() && tuple.iter().all(|element| inner(element, false, semantic))
}
// Ex) `type(None) | type(None)`
Expr::BinOp(ast::ExprBinOp {
left,
op: Operator::BitOr,
right,
..
}) => {
// `None | None` is a `TypeError` at runtime
if left.is_none_literal_expr() && right.is_none_literal_expr() {
return false;
}
inner(left, true, semantic) && inner(right, true, semantic)
}
// Ex) `Union[None, ...]`
Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => {
if !semantic.match_typing_expr(value, "Union") {
return false;
}
match slice.as_ref() {
Expr::Tuple(ast::ExprTuple { elts, .. }) => {
!elts.is_empty()
&& elts.iter().all(|element| inner(element, true, semantic))
}
slice => inner(slice, true, semantic),
}
}
// Otherwise, return false.
_ => false,
}
}
inner(expr, false, 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/refurb/rules/hardcoded_string_charset.rs | crates/ruff_linter/src/rules/refurb/rules/hardcoded_string_charset.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprStringLiteral;
use ruff_text_size::TextRange;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of hardcoded charsets, which are defined in Python string module.
///
/// ## Why is this bad?
/// Usage of named charsets from the standard library is more readable and less error-prone.
///
/// ## Example
/// ```python
/// x = "0123456789"
/// y in "abcdefghijklmnopqrstuvwxyz"
/// ```
///
/// Use instead
/// ```python
/// import string
///
/// x = string.digits
/// y in string.ascii_lowercase
/// ```
///
/// ## References
/// - [Python documentation: String constants](https://docs.python.org/3/library/string.html#string-constants)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "0.7.0")]
pub(crate) struct HardcodedStringCharset {
name: &'static str,
}
impl AlwaysFixableViolation for HardcodedStringCharset {
#[derive_message_formats]
fn message(&self) -> String {
"Use of hardcoded string charset".to_string()
}
fn fix_title(&self) -> String {
let HardcodedStringCharset { name } = self;
format!("Replace hardcoded charset with `string.{name}`")
}
}
/// FURB156
pub(crate) fn hardcoded_string_charset_literal(checker: &Checker, expr: &ExprStringLiteral) {
// if the string literal is a docstring, the rule is not applied
if checker.semantic().in_pep_257_docstring() {
return;
}
if let Some(charset) = check_charset_exact(expr.value.to_str().as_bytes()) {
push_diagnostic(checker, expr.range, charset);
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct NamedCharset {
name: &'static str,
bytes: &'static [u8],
}
impl NamedCharset {
const fn new(name: &'static str, bytes: &'static [u8]) -> Self {
Self { name, bytes }
}
}
const KNOWN_NAMED_CHARSETS: [NamedCharset; 9] = [
NamedCharset::new(
"ascii_letters",
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
),
NamedCharset::new("ascii_lowercase", b"abcdefghijklmnopqrstuvwxyz"),
NamedCharset::new("ascii_uppercase", b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
NamedCharset::new("digits", b"0123456789"),
NamedCharset::new("hexdigits", b"0123456789abcdefABCDEF"),
NamedCharset::new("octdigits", b"01234567"),
NamedCharset::new("punctuation", b"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"),
NamedCharset::new(
"printable",
b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"\
#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c",
),
NamedCharset::new("whitespace", b" \t\n\r\x0b\x0c"),
];
fn check_charset_exact(bytes: &[u8]) -> Option<&NamedCharset> {
KNOWN_NAMED_CHARSETS
.iter()
.find(|&charset| charset.bytes == bytes)
}
fn push_diagnostic(checker: &Checker, range: TextRange, charset: &NamedCharset) {
let name = charset.name;
let mut diagnostic = checker.report_diagnostic(HardcodedStringCharset { name }, range);
diagnostic.try_set_fix(|| {
let (edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("string", name),
range.start(),
checker.semantic(),
)?;
Ok(Fix::safe_edits(
Edit::range_replacement(binding, range),
[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/refurb/rules/mod.rs | crates/ruff_linter/src/rules/refurb/rules/mod.rs | pub(crate) use bit_count::*;
pub(crate) use check_and_remove_from_set::*;
pub(crate) use delete_full_slice::*;
pub(crate) use for_loop_set_mutations::*;
pub(crate) use for_loop_writes::*;
pub(crate) use fromisoformat_replace_z::*;
pub(crate) use fstring_number_format::*;
pub(crate) use hardcoded_string_charset::*;
pub(crate) use hashlib_digest_hex::*;
pub(crate) use if_exp_instead_of_or_operator::*;
pub(crate) use if_expr_min_max::*;
pub(crate) use implicit_cwd::*;
pub(crate) use int_on_sliced_str::*;
pub(crate) use isinstance_type_none::*;
pub(crate) use list_reverse_copy::*;
pub(crate) use math_constant::*;
pub(crate) use metaclass_abcmeta::*;
pub(crate) use print_empty_string::*;
pub(crate) use read_whole_file::*;
pub(crate) use readlines_in_for::*;
pub(crate) use redundant_log_base::*;
pub(crate) use regex_flag_alias::*;
pub(crate) use reimplemented_operator::*;
pub(crate) use reimplemented_starmap::*;
pub(crate) use repeated_append::*;
pub(crate) use repeated_global::*;
pub(crate) use single_item_membership_test::*;
pub(crate) use slice_copy::*;
pub(crate) use slice_to_remove_prefix_or_suffix::*;
pub(crate) use sorted_min_max::*;
pub(crate) use subclass_builtin::*;
pub(crate) use type_none_comparison::*;
pub(crate) use unnecessary_enumerate::*;
pub(crate) use unnecessary_from_float::*;
pub(crate) use verbose_decimal_constructor::*;
pub(crate) use write_whole_file::*;
mod bit_count;
mod check_and_remove_from_set;
mod delete_full_slice;
mod for_loop_set_mutations;
mod for_loop_writes;
mod fromisoformat_replace_z;
mod fstring_number_format;
mod hardcoded_string_charset;
mod hashlib_digest_hex;
mod if_exp_instead_of_or_operator;
mod if_expr_min_max;
mod implicit_cwd;
mod int_on_sliced_str;
mod isinstance_type_none;
mod list_reverse_copy;
mod math_constant;
mod metaclass_abcmeta;
mod print_empty_string;
mod read_whole_file;
mod readlines_in_for;
mod redundant_log_base;
mod regex_flag_alias;
mod reimplemented_operator;
mod reimplemented_starmap;
mod repeated_append;
mod repeated_global;
mod single_item_membership_test;
mod slice_copy;
mod slice_to_remove_prefix_or_suffix;
mod sorted_min_max;
mod subclass_builtin;
mod type_none_comparison;
mod unnecessary_enumerate;
mod unnecessary_from_float;
mod verbose_decimal_constructor;
mod write_whole_file;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/delete_full_slice.rs | crates/ruff_linter/src/rules/refurb/rules/delete_full_slice.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::{is_dict, is_list};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
use crate::rules::refurb::helpers::generate_method_call;
/// ## What it does
/// Checks for `del` statements that delete the entire slice of a list or
/// dictionary.
///
/// ## Why is this bad?
/// It is faster and more succinct to remove all items via the `clear()`
/// method.
///
/// ## Known problems
/// This rule is prone to false negatives due to type inference limitations,
/// as it will only detect lists and dictionaries that are instantiated as
/// literals or annotated with a type annotation.
///
/// ## Example
/// ```python
/// names = {"key": "value"}
/// nums = [1, 2, 3]
///
/// del names[:]
/// del nums[:]
/// ```
///
/// Use instead:
/// ```python
/// names = {"key": "value"}
/// nums = [1, 2, 3]
///
/// names.clear()
/// nums.clear()
/// ```
///
/// ## References
/// - [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html?highlight=list#mutable-sequence-types)
/// - [Python documentation: `dict.clear()`](https://docs.python.org/3/library/stdtypes.html?highlight=list#dict.clear)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.0.287")]
pub(crate) struct DeleteFullSlice;
impl Violation for DeleteFullSlice {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `clear` over deleting a full slice".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `clear()`".to_string())
}
}
/// FURB131
pub(crate) fn delete_full_slice(checker: &Checker, delete: &ast::StmtDelete) {
for target in &delete.targets {
let Some(name) = match_full_slice(target, checker.semantic()) else {
continue;
};
let mut diagnostic = checker.report_diagnostic(DeleteFullSlice, delete.range);
// Fix is only supported for single-target deletions.
if delete.targets.len() == 1 {
let replacement = generate_method_call(name.id.clone(), "clear", checker.generator());
diagnostic.set_fix(Fix::unsafe_edit(Edit::replacement(
replacement,
delete.start(),
delete.end(),
)));
}
}
}
/// Match `del expr[:]` where `expr` is a list or a dict.
fn match_full_slice<'a>(expr: &'a Expr, semantic: &SemanticModel) -> Option<&'a ast::ExprName> {
// Check that it is `del expr[...]`.
let subscript = expr.as_subscript_expr()?;
// Check that it is` `del expr[:]`.
if !matches!(
subscript.slice.as_ref(),
Expr::Slice(ast::ExprSlice {
lower: None,
upper: None,
step: None,
range: _,
node_index: _,
})
) {
return None;
}
// It should only apply to variables that are known to be lists or dicts.
let name = subscript.value.as_name_expr()?;
let binding = semantic.binding(semantic.only_binding(name)?);
if !(is_dict(binding, semantic) || is_list(binding, semantic)) {
return None;
}
// Name is needed for the fix suggestion.
Some(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/refurb/rules/unnecessary_enumerate.rs | crates/ruff_linter/src/rules/refurb/rules/unnecessary_enumerate.rs | use std::fmt;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::name::Name;
use ruff_python_ast::{Arguments, Expr, Int};
use ruff_python_codegen::Generator;
use ruff_python_semantic::analyze::typing::{is_dict, is_list, is_set, is_tuple};
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::pad;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `enumerate` that discard either the index or the value
/// when iterating over a sequence.
///
/// ## Why is this bad?
/// The built-in `enumerate` function is useful when you need both the index and
/// value of a sequence.
///
/// If you only need the index or values of a sequence, you should iterate over
/// `range(len(...))` or the sequence itself, respectively, instead. This is
/// more efficient and communicates the intent of the code more clearly.
///
/// ## Known problems
/// This rule is prone to false negatives due to type inference limitations;
/// namely, it will only suggest a fix using the `len` builtin function if the
/// sequence passed to `enumerate` is an instantiated as a list, set, dict, or
/// tuple literal, or annotated as such with a type annotation.
///
/// The `len` builtin function is not defined for all object types (such as
/// generators), and so refactoring to use `len` over `enumerate` is not always
/// safe.
///
/// ## Example
/// ```python
/// for index, _ in enumerate(sequence):
/// print(index)
///
/// for _, value in enumerate(sequence):
/// print(value)
/// ```
///
/// Use instead:
/// ```python
/// for index in range(len(sequence)):
/// print(index)
///
/// for value in sequence:
/// print(value)
/// ```
///
/// ## References
/// - [Python documentation: `enumerate`](https://docs.python.org/3/library/functions.html#enumerate)
/// - [Python documentation: `range`](https://docs.python.org/3/library/stdtypes.html#range)
/// - [Python documentation: `len`](https://docs.python.org/3/library/functions.html#len)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.0.291")]
pub(crate) struct UnnecessaryEnumerate {
subset: EnumerateSubset,
}
impl Violation for UnnecessaryEnumerate {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
match self.subset {
EnumerateSubset::Indices => {
"`enumerate` value is unused, use `for x in range(len(y))` instead".to_string()
}
EnumerateSubset::Values => {
"`enumerate` index is unused, use `for x in y` instead".to_string()
}
}
}
fn fix_title(&self) -> Option<String> {
let title = match self.subset {
EnumerateSubset::Indices => "Replace with `range(len(...))`",
EnumerateSubset::Values => "Remove `enumerate`",
};
Some(title.to_string())
}
}
/// FURB148
pub(crate) fn unnecessary_enumerate(checker: &Checker, stmt_for: &ast::StmtFor) {
// Check the for statement is of the form `for x, y in func(...)`.
let Expr::Tuple(ast::ExprTuple { elts, .. }) = stmt_for.target.as_ref() else {
return;
};
let [index, value] = elts.as_slice() else {
return;
};
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = stmt_for.iter.as_ref()
else {
return;
};
// Get the first argument, which is the sequence to iterate over.
let Some(Expr::Name(sequence)) = arguments.args.first() else {
return;
};
// Check that the function is the `enumerate` builtin.
if !checker.semantic().match_builtin_expr(func, "enumerate") {
return;
}
// Check if the index and value are used.
match (
checker.semantic().is_unused(index),
checker.semantic().is_unused(value),
) {
(true, true) => {
// Both the index and the value are unused.
}
(false, false) => {
// Both the index and the value are used.
}
(true, false) => {
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEnumerate {
subset: EnumerateSubset::Values,
},
func.range(),
);
// The index is unused, so replace with `for value in sequence`.
let replace_iter =
Edit::range_replacement(sequence.id.to_string(), stmt_for.iter.range());
let replace_target = Edit::range_replacement(
pad(
checker.locator().slice(value).to_string(),
stmt_for.target.range(),
checker.locator(),
),
stmt_for.target.range(),
);
diagnostic.set_fix(Fix::unsafe_edits(replace_iter, [replace_target]));
}
(false, true) => {
// Ensure the sequence object works with `len`. If it doesn't, the
// fix is unclear.
let Some(binding) = checker
.semantic()
.only_binding(sequence)
.map(|id| checker.semantic().binding(id))
else {
return;
};
// This will lead to a lot of false negatives, but it is the best
// we can do with the current type inference.
if !is_list(binding, checker.semantic())
&& !is_dict(binding, checker.semantic())
&& !is_set(binding, checker.semantic())
&& !is_tuple(binding, checker.semantic())
{
return;
}
// The value is unused, so replace with `for index in range(len(sequence))`.
let mut diagnostic = checker.report_diagnostic(
UnnecessaryEnumerate {
subset: EnumerateSubset::Indices,
},
func.range(),
);
if checker.semantic().has_builtin_binding("range")
&& checker.semantic().has_builtin_binding("len")
{
// If the `start` argument is set to something other than the `range` default,
// there's no clear fix.
let start = arguments.find_argument_value("start", 1);
if start.is_none_or(|start| {
matches!(
start,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(Int::ZERO),
..
})
)
}) {
let replace_iter = Edit::range_replacement(
generate_range_len_call(sequence.id.clone(), checker.generator()),
stmt_for.iter.range(),
);
let replace_target = Edit::range_replacement(
pad(
checker.locator().slice(index).to_string(),
stmt_for.target.range(),
checker.locator(),
),
stmt_for.target.range(),
);
diagnostic.set_fix(Fix::unsafe_edits(replace_iter, [replace_target]));
}
}
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum EnumerateSubset {
/// E.g., `for _, value in enumerate(sequence):`.
Indices,
/// E.g., `for index, _ in enumerate(sequence):`.
Values,
}
impl fmt::Display for EnumerateSubset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
EnumerateSubset::Indices => write!(f, "indices"),
EnumerateSubset::Values => write!(f, "values"),
}
}
}
/// Format a code snippet to call `range(len(name))`, where `name` is the given
/// sequence name.
fn generate_range_len_call(name: Name, generator: Generator) -> String {
// Construct `name`.
let var = ast::ExprName {
id: name,
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// Construct `len(name)`.
let len = ast::ExprCall {
func: Box::new(
ast::ExprName {
id: Name::new_static("len"),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
arguments: Arguments {
args: Box::from([var.into()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// Construct `range(len(name))`.
let range = ast::ExprCall {
func: Box::new(
ast::ExprName {
id: Name::new_static("range"),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
}
.into(),
),
arguments: Arguments {
args: Box::from([len.into()]),
keywords: Box::from([]),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// And finally, turn it into a statement.
let stmt = ast::StmtExpr {
value: Box::new(range.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
generator.stmt(&stmt.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/refurb/rules/if_exp_instead_of_or_operator.rs | crates/ruff_linter/src/rules/refurb/rules/if_exp_instead_of_or_operator.rs | use std::borrow::Cow;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast as ast;
use ruff_python_ast::Expr;
use ruff_python_ast::comparable::ComparableExpr;
use ruff_python_ast::helpers::contains_effect;
use ruff_python_ast::token::{Tokens, parenthesized_range};
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::{Applicability, Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for ternary `if` expressions that can be replaced with the `or`
/// operator.
///
/// ## Why is this bad?
/// Ternary `if` expressions are more verbose than `or` expressions while
/// providing the same functionality.
///
/// ## Example
/// ```python
/// z = x if x else y
/// ```
///
/// Use instead:
/// ```python
/// z = x or y
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe in the event that the body of the
/// `if` expression contains side effects.
///
/// For example, `foo` will be called twice in `foo() if foo() else bar()`
/// (assuming `foo()` returns a truthy value), but only once in
/// `foo() or bar()`.
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.3.6")]
pub(crate) struct IfExpInsteadOfOrOperator;
impl Violation for IfExpInsteadOfOrOperator {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Replace ternary `if` expression with `or` operator".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `or` operator".to_string())
}
}
/// FURB110
pub(crate) fn if_exp_instead_of_or_operator(checker: &Checker, if_expr: &ast::ExprIf) {
let ast::ExprIf {
test,
body,
orelse,
range,
node_index: _,
} = if_expr;
if ComparableExpr::from(test) != ComparableExpr::from(body) {
return;
}
let mut diagnostic = checker.report_diagnostic(IfExpInsteadOfOrOperator, *range);
// Replace with `{test} or {orelse}`.
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_replacement(
format!(
"{} or {}",
parenthesize_test(test, if_expr, checker.tokens(), checker.locator()),
parenthesize_test(orelse, if_expr, checker.tokens(), checker.locator()),
),
if_expr.range(),
),
if contains_effect(body, |id| checker.semantic().has_builtin_binding(id)) {
Applicability::Unsafe
} else {
Applicability::Safe
},
));
}
/// Parenthesize an expression for use in an `or` operator (e.g., parenthesize `x` in `x or y`),
/// if it's required to maintain the correct order of operations.
///
/// If the expression is already parenthesized, it will be returned as-is regardless of whether
/// the parentheses are required.
///
/// See: <https://docs.python.org/3/reference/expressions.html#operator-precedence>
fn parenthesize_test<'a>(
expr: &Expr,
if_expr: &ast::ExprIf,
tokens: &Tokens,
locator: &Locator<'a>,
) -> Cow<'a, str> {
if let Some(range) = parenthesized_range(expr.into(), if_expr.into(), tokens) {
Cow::Borrowed(locator.slice(range))
} else if matches!(expr, Expr::If(_) | Expr::Lambda(_) | Expr::Named(_)) {
Cow::Owned(format!("({})", locator.slice(expr.range())))
} else {
Cow::Borrowed(locator.slice(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/refurb/rules/list_reverse_copy.rs | crates/ruff_linter/src/rules/refurb/rules/list_reverse_copy.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{
Expr, ExprCall, ExprName, ExprSlice, ExprSubscript, ExprUnaryOp, Int, StmtAssign, UnaryOp,
};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::typing;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for list reversals that can be performed in-place in lieu of
/// creating a new list.
///
/// ## Why is this bad?
/// When reversing a list, it's more efficient to use the in-place method
/// `.reverse()` instead of creating a new list, if the original list is
/// no longer needed.
///
/// ## Example
/// ```python
/// l = [1, 2, 3]
/// l = reversed(l)
///
/// l = [1, 2, 3]
/// l = list(reversed(l))
///
/// l = [1, 2, 3]
/// l = l[::-1]
/// ```
///
/// Use instead:
/// ```python
/// l = [1, 2, 3]
/// l.reverse()
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe, as calling `.reverse()` on a list
/// will mutate the list in-place, unlike `reversed`, which creates a new list
/// and leaves the original list unchanged.
///
/// If the list is referenced elsewhere, this could lead to unexpected
/// behavior.
///
/// ## References
/// - [Python documentation: More on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct ListReverseCopy {
name: String,
}
impl AlwaysFixableViolation for ListReverseCopy {
#[derive_message_formats]
fn message(&self) -> String {
let ListReverseCopy { name } = self;
format!("Use of assignment of `reversed` on list `{name}`")
}
fn fix_title(&self) -> String {
let ListReverseCopy { name } = self;
format!("Replace with `{name}.reverse()`")
}
}
/// FURB187
pub(crate) fn list_assign_reversed(checker: &Checker, assign: &StmtAssign) {
let [Expr::Name(target_expr)] = assign.targets.as_slice() else {
return;
};
let Some(reversed_expr) = extract_reversed(assign.value.as_ref(), checker.semantic()) else {
return;
};
if reversed_expr.id != target_expr.id {
return;
}
let Some(binding) = checker
.semantic()
.only_binding(reversed_expr)
.map(|id| checker.semantic().binding(id))
else {
return;
};
if !typing::is_list(binding, checker.semantic()) {
return;
}
checker
.report_diagnostic(
ListReverseCopy {
name: target_expr.id.to_string(),
},
assign.range(),
)
.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("{}.reverse()", target_expr.id),
assign.range(),
)));
}
/// Recursively removes any `list` wrappers from the expression.
///
/// For example, given `list(list(list([1, 2, 3])))`, this function
/// would return the inner `[1, 2, 3]` expression.
fn peel_lists(expr: &Expr) -> &Expr {
let Some(ExprCall {
func, arguments, ..
}) = expr.as_call_expr()
else {
return expr;
};
if !arguments.keywords.is_empty() {
return expr;
}
if func.as_name_expr().is_none_or(|name| name.id != "list") {
return expr;
}
let [arg] = arguments.args.as_ref() else {
return expr;
};
peel_lists(arg)
}
/// Given a call to `reversed`, returns the inner argument.
///
/// For example, given `reversed(l)`, this function would return `l`.
fn extract_name_from_reversed<'a>(
expr: &'a Expr,
semantic: &SemanticModel,
) -> Option<&'a ExprName> {
let ExprCall {
func, arguments, ..
} = expr.as_call_expr()?;
if !arguments.keywords.is_empty() {
return None;
}
let [arg] = arguments.args.as_ref() else {
return None;
};
if !semantic.match_builtin_expr(func, "reversed") {
return None;
}
arg.as_name_expr()
}
/// Given a slice expression, returns the inner argument if it's a reversed slice.
///
/// For example, given `l[::-1]`, this function would return `l`.
fn extract_name_from_sliced_reversed(expr: &Expr) -> Option<&ExprName> {
let ExprSubscript { value, slice, .. } = expr.as_subscript_expr()?;
let ExprSlice {
lower, upper, step, ..
} = slice.as_slice_expr()?;
if lower.is_some() || upper.is_some() {
return None;
}
let Some(ExprUnaryOp {
op: UnaryOp::USub,
operand,
..
}) = step.as_ref().and_then(|expr| expr.as_unary_op_expr())
else {
return None;
};
if operand
.as_number_literal_expr()
.and_then(|num| num.value.as_int())
.and_then(Int::as_u8)
.is_none_or(|value| value != 1)
{
return None;
}
value.as_name_expr()
}
fn extract_reversed<'a>(expr: &'a Expr, semantic: &SemanticModel) -> Option<&'a ExprName> {
let expr = peel_lists(expr);
extract_name_from_reversed(expr, semantic).or_else(|| extract_name_from_sliced_reversed(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/refurb/rules/read_whole_file.rs | crates/ruff_linter/src/rules/refurb/rules/read_whole_file.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{
self as ast, Expr, Stmt,
visitor::{self, Visitor},
};
use ruff_python_codegen::Generator;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::snippet::SourceCodeSnippet;
use crate::importer::ImportRequest;
use crate::rules::refurb::helpers::{FileOpen, OpenArgument, find_file_opens};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `open` and `read` that can be replaced by `pathlib`
/// methods, like `Path.read_text` and `Path.read_bytes`.
///
/// ## Why is this bad?
/// When reading the entire contents of a file into a variable, it's simpler
/// and more concise to use `pathlib` methods like `Path.read_text` and
/// `Path.read_bytes` instead of `open` and `read` calls via `with` statements.
///
/// ## Example
/// ```python
/// with open(filename) as f:
/// contents = f.read()
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// contents = Path(filename).read_text()
/// ```
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.read_bytes`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_bytes)
/// - [Python documentation: `Path.read_text`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_text)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.1.2")]
pub(crate) struct ReadWholeFile<'a> {
filename: SourceCodeSnippet,
suggestion: SourceCodeSnippet,
argument: OpenArgument<'a>,
}
impl Violation for ReadWholeFile<'_> {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let filename = self.filename.truncated_display();
let suggestion = self.suggestion.truncated_display();
match self.argument {
OpenArgument::Pathlib { .. } => {
format!(
"`Path.open()` followed by `read()` can be replaced by `{filename}.{suggestion}`"
)
}
OpenArgument::Builtin { .. } => {
format!("`open` and `read` should be replaced by `Path({filename}).{suggestion}`")
}
}
}
fn fix_title(&self) -> Option<String> {
let filename = self.filename.truncated_display();
let suggestion = self.suggestion.truncated_display();
match self.argument {
OpenArgument::Pathlib { .. } => Some(format!("Replace with `{filename}.{suggestion}`")),
OpenArgument::Builtin { .. } => {
Some(format!("Replace with `Path({filename}).{suggestion}`"))
}
}
}
}
/// FURB101
pub(crate) fn read_whole_file(checker: &Checker, with: &ast::StmtWith) {
// `async` check here is more of a precaution.
if with.is_async {
return;
}
// First we go through all the items in the statement and find all `open` operations.
let candidates = find_file_opens(with, checker.semantic(), true, checker.target_version());
if candidates.is_empty() {
return;
}
// Then we need to match each `open` operation with exactly one `read` call.
let mut matcher = ReadMatcher::new(checker, candidates, with);
visitor::walk_body(&mut matcher, &with.body);
}
/// AST visitor that matches `open` operations with the corresponding `read` calls.
struct ReadMatcher<'a, 'b> {
checker: &'a Checker<'b>,
candidates: Vec<FileOpen<'a>>,
with_stmt: &'a ast::StmtWith,
}
impl<'a, 'b> ReadMatcher<'a, 'b> {
fn new(
checker: &'a Checker<'b>,
candidates: Vec<FileOpen<'a>>,
with_stmt: &'a ast::StmtWith,
) -> Self {
Self {
checker,
candidates,
with_stmt,
}
}
}
impl<'a> Visitor<'a> for ReadMatcher<'a, '_> {
fn visit_expr(&mut self, expr: &'a Expr) {
if let Some(read_from) = match_read_call(expr) {
if let Some(open) = self
.candidates
.iter()
.position(|open| open.is_ref(read_from))
{
let open = self.candidates.remove(open);
let filename_display = open.argument.display(self.checker.source());
let suggestion = make_suggestion(&open, self.checker.generator());
let mut diagnostic = self.checker.report_diagnostic(
ReadWholeFile {
filename: SourceCodeSnippet::from_str(filename_display),
suggestion: SourceCodeSnippet::from_str(&suggestion),
argument: open.argument,
},
open.item.range(),
);
if let Some(fix) =
generate_fix(self.checker, &open, expr, self.with_stmt, &suggestion)
{
diagnostic.set_fix(fix);
}
}
return;
}
visitor::walk_expr(self, expr);
}
}
/// Match `x.read()` expression and return expression `x` on success.
fn match_read_call(expr: &Expr) -> Option<&Expr> {
let call = expr.as_call_expr()?;
let attr = call.func.as_attribute_expr()?;
let method_name = &attr.attr;
if method_name != "read"
|| !attr.value.is_name_expr()
|| !call.arguments.args.is_empty()
|| !call.arguments.keywords.is_empty()
{
return None;
}
Some(&*attr.value)
}
fn make_suggestion(open: &FileOpen<'_>, generator: Generator) -> String {
let name = ast::ExprName {
id: open.mode.pathlib_method(),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
let call = ast::ExprCall {
func: Box::new(name.into()),
arguments: ast::Arguments {
args: Box::from([]),
keywords: open.keywords.iter().copied().cloned().collect(),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
},
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
generator.expr(&call.into())
}
fn generate_fix(
checker: &Checker,
open: &FileOpen,
expr: &Expr,
with_stmt: &ast::StmtWith,
suggestion: &str,
) -> Option<Fix> {
if with_stmt.items.len() != 1 {
return None;
}
let locator = checker.locator();
let (import_edit, binding) = checker
.importer()
.get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
with_stmt.start(),
checker.semantic(),
)
.ok()?;
// Only replace context managers with a single assignment or annotated assignment in the body.
// The assignment's RHS must also be the same as the `read` call in `expr`, otherwise this fix
// would remove the rest of the expression.
let replacement = match with_stmt.body.as_slice() {
[Stmt::Assign(ast::StmtAssign { targets, value, .. })] if value.range() == expr.range() => {
match targets.as_slice() {
[Expr::Name(name)] => {
let target = match open.argument {
OpenArgument::Builtin { filename } => {
let filename_code = locator.slice(filename.range());
format!("{binding}({filename_code})")
}
OpenArgument::Pathlib { path } => locator.slice(path.range()).to_string(),
};
format!("{name} = {target}.{suggestion}", name = name.id)
}
_ => return None,
}
}
[
Stmt::AnnAssign(ast::StmtAnnAssign {
target,
annotation,
value: Some(value),
..
}),
] if value.range() == expr.range() => match target.as_ref() {
Expr::Name(name) => {
let target = match open.argument {
OpenArgument::Builtin { filename } => {
let filename_code = locator.slice(filename.range());
format!("{binding}({filename_code})")
}
OpenArgument::Pathlib { path } => locator.slice(path.range()).to_string(),
};
format!(
"{var}: {ann} = {target}.{suggestion}",
var = name.id,
ann = locator.slice(annotation.range())
)
}
_ => return None,
},
_ => return None,
};
let applicability = if checker.comment_ranges().intersects(with_stmt.range()) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Some(Fix::applicable_edits(
Edit::range_replacement(replacement, with_stmt.range()),
[import_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/refurb/rules/repeated_append.rs | crates/ruff_linter/src/rules/refurb/rules/repeated_append.rs | use rustc_hash::FxHashMap;
use ast::traversal;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::traversal::EnclosingSuite;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_codegen::Generator;
use ruff_python_semantic::analyze::typing::is_list;
use ruff_python_semantic::{Binding, BindingId, SemanticModel};
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 consecutive calls to `append`.
///
/// ## Why is this bad?
/// Consecutive calls to `append` can be less efficient than batching them into
/// a single `extend`. Each `append` resizes the list individually, whereas an
/// `extend` can resize the list once for all elements.
///
/// ## Known problems
/// This rule is prone to false negatives due to type inference limitations,
/// as it will only detect lists that are instantiated as literals or annotated
/// with a type annotation.
///
/// ## Example
/// ```python
/// nums = [1, 2, 3]
///
/// nums.append(4)
/// nums.append(5)
/// nums.append(6)
/// ```
///
/// Use instead:
/// ```python
/// nums = [1, 2, 3]
///
/// nums.extend((4, 5, 6))
/// ```
///
/// ## References
/// - [Python documentation: More on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.0.287")]
pub(crate) struct RepeatedAppend {
name: String,
replacement: SourceCodeSnippet,
}
impl RepeatedAppend {
fn suggestion(&self) -> String {
let name = &self.name;
self.replacement
.full_display()
.map_or(format!("{name}.extend(...)"), ToString::to_string)
}
}
impl Violation for RepeatedAppend {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let name = &self.name;
let suggestion = self.suggestion();
format!("Use `{suggestion}` instead of repeatedly calling `{name}.append()`")
}
fn fix_title(&self) -> Option<String> {
let suggestion = self.suggestion();
Some(format!("Replace with `{suggestion}`"))
}
}
/// FURB113
pub(crate) fn repeated_append(checker: &Checker, stmt: &Stmt) {
let Some(appends) = match_consecutive_appends(stmt, checker.semantic()) else {
return;
};
// No need to proceed if we have less than 1 `append` to work with.
if appends.len() <= 1 {
return;
}
for group in group_appends(appends) {
// Groups with just one element are fine, and shouldn't be replaced by `extend`.
if group.appends.len() <= 1 {
continue;
}
let replacement = make_suggestion(&group, checker.generator());
let mut diagnostic = checker.report_diagnostic(
RepeatedAppend {
name: group.name().to_string(),
replacement: SourceCodeSnippet::new(replacement.clone()),
},
group.range(),
);
// We only suggest a fix when all appends in a group are clumped together. If they're
// non-consecutive, fixing them is much more difficult.
//
// Avoid fixing if there are comments in between the appends:
//
// ```python
// a.append(1)
// # comment
// a.append(2)
// ```
if group.is_consecutive && !checker.comment_ranges().intersects(group.range()) {
diagnostic.set_fix(Fix::unsafe_edit(Edit::replacement(
replacement,
group.start(),
group.end(),
)));
}
}
}
#[derive(Debug, Clone)]
struct Append<'a> {
/// Receiver of the `append` call (aka `self` argument).
receiver: &'a ast::ExprName,
/// [`BindingId`] that the receiver references.
binding_id: BindingId,
/// [`Binding`] that the receiver references.
binding: &'a Binding<'a>,
/// [`Expr`] serving as a sole argument to `append`.
argument: &'a Expr,
/// The statement containing the `append` call.
stmt: &'a Stmt,
}
#[derive(Debug)]
struct AppendGroup<'a> {
/// A sequence of `appends` connected to the same binding.
appends: Vec<Append<'a>>,
/// `true` when all appends in the group follow one another and don't have other statements in
/// between. It is much easier to make fix suggestions for consecutive groups.
is_consecutive: bool,
}
impl AppendGroup<'_> {
fn name(&self) -> &str {
assert!(!self.appends.is_empty());
&self.appends.first().unwrap().receiver.id
}
}
impl Ranged for AppendGroup<'_> {
fn range(&self) -> TextRange {
assert!(!self.appends.is_empty());
TextRange::new(
self.appends.first().unwrap().stmt.start(),
self.appends.last().unwrap().stmt.end(),
)
}
}
/// Match consecutive calls to `append` on list variables starting from the given statement.
fn match_consecutive_appends<'a>(
stmt: &'a Stmt,
semantic: &'a SemanticModel,
) -> Option<Vec<Append<'a>>> {
// Match the current statement, to see if it's an append.
let append = match_append(semantic, stmt)?;
// In order to match consecutive statements, we need to go to the tree ancestor of the
// given statement, find its position there, and match all 'appends' from there.
let suite = if semantic.at_top_level() {
// If the statement is at the top level, we should go to the parent module.
// Module is available in the definitions list.
EnclosingSuite::new(semantic.definitions.python_ast()?, stmt.into())?
} else {
// Otherwise, go to the parent, and take its body as a sequence of siblings.
semantic
.current_statement_parent()
.and_then(|parent| traversal::suite(stmt, parent))?
};
// We shouldn't repeat the same work for many 'appends' that go in a row. Let's check
// that this statement is at the beginning of such a group.
if suite
.previous_sibling()
.is_some_and(|previous_stmt| match_append(semantic, previous_stmt).is_some())
{
return None;
}
// Starting from the next statement, let's match all appends and make a vector.
Some(
std::iter::once(append)
.chain(
suite
.next_siblings()
.iter()
.map_while(|sibling| match_append(semantic, sibling)),
)
.collect(),
)
}
/// Group the given appends by the associated bindings.
fn group_appends(appends: Vec<Append<'_>>) -> Vec<AppendGroup<'_>> {
// We want to go over the given list of appends and group the by receivers.
let mut map: FxHashMap<BindingId, AppendGroup> = FxHashMap::default();
let mut iter = appends.into_iter();
let mut last_binding = {
let first_append = iter.next().unwrap();
let binding_id = first_append.binding_id;
let _ = get_or_add(&mut map, first_append);
binding_id
};
for append in iter {
let binding_id = append.binding_id;
let group = get_or_add(&mut map, append);
if binding_id != last_binding {
// If the group is not brand new, and the previous group was different,
// we should mark it as "non-consecutive".
//
// We are catching the following situation:
// ```python
// a.append(1)
// a.append(2)
// b.append(1)
// a.append(3) # <- we are currently here
// ```
//
// So, `a` != `b` and group for `a` already contains appends 1 and 2.
// It is only possible if this group got interrupted by at least one
// other group and, thus, it is non-consecutive.
if group.appends.len() > 1 {
group.is_consecutive = false;
}
last_binding = binding_id;
}
}
map.into_values().collect()
}
#[inline]
fn get_or_add<'a, 'b>(
map: &'b mut FxHashMap<BindingId, AppendGroup<'a>>,
append: Append<'a>,
) -> &'b mut AppendGroup<'a> {
let group = map.entry(append.binding_id).or_insert(AppendGroup {
appends: vec![],
is_consecutive: true,
});
group.appends.push(append);
group
}
/// Matches that the given statement is a call to `append` on a list variable.
fn match_append<'a>(semantic: &'a SemanticModel, stmt: &'a Stmt) -> Option<Append<'a>> {
let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else {
return None;
};
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = value.as_ref()
else {
return None;
};
// `append` should have just one argument, an element to be added.
let [argument] = &*arguments.args else {
return None;
};
// The called function should be an attribute, ie `value.attr`.
let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() else {
return None;
};
// `attr` should be `append` and it shouldn't have any keyword arguments.
if attr != "append" || !arguments.keywords.is_empty() {
return None;
}
// We match only variable references, i.e. `value` should be a name expression.
let Expr::Name(receiver @ ast::ExprName { id: name, .. }) = value.as_ref() else {
return None;
};
// Now we need to find what is this variable bound to...
let scope = semantic.current_scope();
let bindings: Vec<BindingId> = scope.get_all(name).collect();
// Maybe it is too strict of a limitation, but it seems reasonable.
let [binding_id] = bindings.as_slice() else {
return None;
};
let binding = semantic.binding(*binding_id);
// ...and whether this something is a list.
if !is_list(binding, semantic) {
return None;
}
Some(Append {
receiver,
binding_id: *binding_id,
binding,
stmt,
argument,
})
}
/// Make fix suggestion for the given group of appends.
fn make_suggestion(group: &AppendGroup, generator: Generator) -> String {
let appends = &group.appends;
assert!(!appends.is_empty());
let first = appends.first().unwrap();
assert!(
appends
.iter()
.all(|append| append.binding.source == first.binding.source)
);
// Here we construct `var.extend((elt1, elt2, ..., eltN))
//
// Each eltK comes from an individual `var.append(eltK)`.
let elts: Vec<Expr> = appends
.iter()
.map(|append| append.argument.clone())
.collect();
// Join all elements into a tuple: `(elt1, elt2, ..., eltN)`
let tuple = ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
parenthesized: true,
};
// Make `var.extend`.
// NOTE: receiver is the same for all appends and that's why we can take the first.
let attr = ast::ExprAttribute {
value: Box::new(first.receiver.clone().into()),
attr: ast::Identifier::new("extend".to_string(), TextRange::default()),
ctx: ast::ExprContext::Load,
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
// Make the actual call `var.extend((elt1, elt2, ..., eltN))`
let call = ast::ExprCall {
func: Box::new(attr.into()),
arguments: ast::Arguments {
args: Box::from([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,
};
// And finally, turn it into a statement.
let stmt = ast::StmtExpr {
value: Box::new(call.into()),
range: TextRange::default(),
node_index: ruff_python_ast::AtomicNodeIndex::NONE,
};
generator.stmt(&stmt.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/refurb/rules/for_loop_writes.rs | crates/ruff_linter/src/rules/refurb/rules/for_loop_writes.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{Expr, ExprList, ExprName, ExprTuple, Stmt, StmtFor};
use ruff_python_semantic::analyze::typing;
use ruff_python_semantic::{Binding, ScopeId, SemanticModel, TypingOnlyBindingsStatus};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::checkers::ast::Checker;
use crate::rules::refurb::helpers::IterLocation;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
use crate::rules::refurb::helpers::parenthesize_loop_iter_if_necessary;
/// ## What it does
/// Checks for the use of `IOBase.write` in a for loop.
///
/// ## Why is this bad?
/// When writing a batch of elements, it's more idiomatic to use a single method call to
/// `IOBase.writelines`, rather than write elements one by one.
///
/// ## Example
/// ```python
/// from pathlib import Path
///
/// with Path("file").open("w") as f:
/// for line in lines:
/// f.write(line)
///
/// with Path("file").open("wb") as f_b:
/// for line_b in lines_b:
/// f_b.write(line_b.encode())
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// with Path("file").open("w") as f:
/// f.writelines(lines)
///
/// with Path("file").open("wb") as f_b:
/// f_b.writelines(line_b.encode() for line_b in lines_b)
/// ```
///
/// ## Fix safety
/// This fix is marked as unsafe if it would cause comments to be deleted.
///
/// ## References
/// - [Python documentation: `io.IOBase.writelines`](https://docs.python.org/3/library/io.html#io.IOBase.writelines)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.12.0")]
pub(crate) struct ForLoopWrites {
name: String,
}
impl AlwaysFixableViolation for ForLoopWrites {
#[derive_message_formats]
fn message(&self) -> String {
format!("Use of `{}.write` in a for loop", self.name)
}
fn fix_title(&self) -> String {
format!("Replace with `{}.writelines`", self.name)
}
}
/// FURB122
pub(crate) fn for_loop_writes_binding(checker: &Checker, binding: &Binding) {
if !binding.kind.is_loop_var() {
return;
}
let semantic = checker.semantic();
let Some(for_stmt) = binding
.statement(semantic)
.and_then(|stmt| stmt.as_for_stmt())
else {
return;
};
if for_stmt.is_async {
return;
}
let binding_names = binding_names(&for_stmt.target);
if !binding_names
.first()
.is_some_and(|name| name.range().contains_range(binding.range))
{
return;
}
for_loop_writes(checker, for_stmt, binding.scope, &binding_names);
}
/// FURB122
pub(crate) fn for_loop_writes_stmt(checker: &Checker, for_stmt: &StmtFor) {
// Loops with bindings are handled later.
if !binding_names(&for_stmt.target).is_empty() {
return;
}
let scope_id = checker.semantic().scope_id;
for_loop_writes(checker, for_stmt, scope_id, &[]);
}
/// Find the names in a `for` loop target
/// that are assigned to during iteration.
///
/// ```python
/// for ((), [(a,), [[b]]], c.d, e[f], *[*g]) in h:
/// # ^ ^ ^
/// ...
/// ```
fn binding_names(for_target: &Expr) -> Vec<&ExprName> {
fn collect_names<'a>(expr: &'a Expr, names: &mut Vec<&'a ExprName>) {
match expr {
Expr::Name(name) => names.push(name),
Expr::Starred(starred) => collect_names(&starred.value, names),
Expr::List(ExprList { elts, .. }) | Expr::Tuple(ExprTuple { elts, .. }) => elts
.iter()
.for_each(|element| collect_names(element, names)),
_ => {}
}
}
let mut names = vec![];
collect_names(for_target, &mut names);
names
}
/// FURB122
fn for_loop_writes(
checker: &Checker,
for_stmt: &StmtFor,
scope_id: ScopeId,
binding_names: &[&ExprName],
) {
if !for_stmt.orelse.is_empty() {
return;
}
let [Stmt::Expr(stmt_expr)] = for_stmt.body.as_slice() else {
return;
};
let Some(call_expr) = stmt_expr.value.as_call_expr() else {
return;
};
let Some(expr_attr) = call_expr.func.as_attribute_expr() else {
return;
};
if &expr_attr.attr != "write" {
return;
}
if !call_expr.arguments.keywords.is_empty() {
return;
}
let [write_arg] = call_expr.arguments.args.as_ref() else {
return;
};
let Some(io_object_name) = expr_attr.value.as_name_expr() else {
return;
};
let semantic = checker.semantic();
// Determine whether `f` in `f.write()` was bound to a file object.
let Some(name) = semantic.resolve_name(io_object_name) else {
return;
};
let binding = semantic.binding(name);
if !typing::is_io_base(binding, semantic) {
return;
}
if loop_variables_are_used_outside_loop(binding_names, for_stmt.range, semantic, scope_id) {
return;
}
let locator = checker.locator();
let content = match (for_stmt.target.as_ref(), write_arg) {
(Expr::Name(for_target), Expr::Name(write_arg)) if for_target.id == write_arg.id => {
format!(
"{}.writelines({})",
locator.slice(io_object_name),
parenthesize_loop_iter_if_necessary(for_stmt, checker, IterLocation::Call),
)
}
(for_target, write_arg) => {
format!(
"{}.writelines({} for {} in {})",
locator.slice(io_object_name),
locator.slice(write_arg),
locator.slice(for_target),
parenthesize_loop_iter_if_necessary(for_stmt, checker, IterLocation::Comprehension),
)
}
};
let applicability = if checker.comment_ranges().intersects(for_stmt.range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let fix = Fix::applicable_edit(
Edit::range_replacement(content, for_stmt.range),
applicability,
);
checker
.report_diagnostic(
ForLoopWrites {
name: io_object_name.id.to_string(),
},
for_stmt.range,
)
.set_fix(fix);
}
fn loop_variables_are_used_outside_loop(
binding_names: &[&ExprName],
loop_range: TextRange,
semantic: &SemanticModel,
scope_id: ScopeId,
) -> bool {
let find_binding_id = |name: &ExprName, offset: TextSize| {
semantic.simulate_runtime_load_at_location_in_scope(
name.id.as_str(),
TextRange::at(offset, 0.into()),
scope_id,
TypingOnlyBindingsStatus::Disallowed,
)
};
// If the load simulation succeeds at the position right before the loop,
// that binding is shadowed.
// ```python
// a = 1
// for a in b: ...
// # ^ Load here
// ```
let name_overwrites_outer =
|name: &ExprName| find_binding_id(name, loop_range.start()).is_some();
let name_is_used_later = |name: &ExprName| {
let Some(binding_id) = find_binding_id(name, loop_range.end()) else {
return false;
};
for reference_id in semantic.binding(binding_id).references() {
let reference = semantic.reference(reference_id);
if !loop_range.contains_range(reference.range()) {
return true;
}
}
false
};
binding_names
.iter()
.any(|name| name_overwrites_outer(name) || name_is_used_later(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/refurb/rules/sorted_min_max.rs | crates/ruff_linter/src/rules/refurb/rules/sorted_min_max.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::Number;
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged;
use crate::Edit;
use crate::Fix;
use crate::FixAvailability;
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for uses of `sorted()` to retrieve the minimum or maximum value in
/// a sequence.
///
/// ## Why is this bad?
/// Using `sorted()` to compute the minimum or maximum value in a sequence is
/// inefficient and less readable than using `min()` or `max()` directly.
///
/// ## Example
/// ```python
/// nums = [3, 1, 4, 1, 5]
/// lowest = sorted(nums)[0]
/// highest = sorted(nums)[-1]
/// highest = sorted(nums, reverse=True)[0]
/// ```
///
/// Use instead:
/// ```python
/// nums = [3, 1, 4, 1, 5]
/// lowest = min(nums)
/// highest = max(nums)
/// ```
///
/// ## Fix safety
/// In some cases, migrating to `min` or `max` can lead to a change in behavior,
/// notably when breaking ties.
///
/// As an example, `sorted(data, key=itemgetter(0), reverse=True)[0]` will return
/// the _last_ "minimum" element in the list, if there are multiple elements with
/// the same key. However, `min(data, key=itemgetter(0))` will return the _first_
/// "minimum" element in the list in the same scenario.
///
/// As such, this rule's fix is marked as unsafe.
///
/// ## References
/// - [Python documentation: `min`](https://docs.python.org/3/library/functions.html#min)
/// - [Python documentation: `max`](https://docs.python.org/3/library/functions.html#max)
#[derive(ViolationMetadata)]
#[violation_metadata(preview_since = "v0.4.2")]
pub(crate) struct SortedMinMax {
min_max: MinMax,
}
impl Violation for SortedMinMax {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
match self.min_max {
MinMax::Min => {
"Prefer `min` over `sorted()` to compute the minimum value in a sequence"
.to_string()
}
MinMax::Max => {
"Prefer `max` over `sorted()` to compute the maximum value in a sequence"
.to_string()
}
}
}
fn fix_title(&self) -> Option<String> {
let title = match self.min_max {
MinMax::Min => "Replace with `min`",
MinMax::Max => "Replace with `max`",
};
Some(title.to_string())
}
}
/// FURB192
pub(crate) fn sorted_min_max(checker: &Checker, subscript: &ast::ExprSubscript) {
if subscript.ctx.is_store() || subscript.ctx.is_del() {
return;
}
let ast::ExprSubscript { slice, value, .. } = &subscript;
// Early return if index is not unary or a number literal.
if !(slice.is_number_literal_expr() || slice.is_unary_op_expr()) {
return;
}
// Early return if the value is not a call expression.
let Expr::Call(ast::ExprCall {
func, arguments, ..
}) = value.as_ref()
else {
return;
};
// Check if the index is either 0 or -1.
let index = match slice.as_ref() {
// [0]
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: Number::Int(index),
..
}) if *index == 0 => Index::First,
// [-1]
Expr::UnaryOp(ast::ExprUnaryOp {
op: ast::UnaryOp::USub,
operand,
..
}) => {
match operand.as_ref() {
// [-1]
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: Number::Int(index),
..
}) if *index == 1 => Index::Last,
_ => return,
}
}
_ => return,
};
// Check if the value is a call to `sorted()`.
if !checker.semantic().match_builtin_expr(func, "sorted") {
return;
}
// Check if the call to `sorted()` has a single argument.
let [list_expr] = arguments.args.as_ref() else {
return;
};
let mut reverse_keyword = None;
let mut key_keyword_expr = None;
// Check if the call to `sorted()` has the `reverse` and `key` keywords.
for keyword in &*arguments.keywords {
// If the call contains `**kwargs`, return.
let Some(arg) = keyword.arg.as_ref() else {
return;
};
match arg.as_str() {
"reverse" => {
reverse_keyword = Some(keyword);
}
"key" => {
key_keyword_expr = Some(keyword);
}
_ => {
// If unexpected keyword is found, return.
return;
}
}
}
let is_reversed = if let Some(reverse_keyword) = reverse_keyword {
match reverse_keyword.value.as_boolean_literal_expr() {
Some(ast::ExprBooleanLiteral { value, .. }) => *value,
// If the value is not a boolean literal, we can't determine if it is reversed.
_ => return,
}
} else {
// No reverse keyword, so it is not reversed.
false
};
// Determine whether the operation is computing a minimum or maximum value.
let min_max = match (index, is_reversed) {
(Index::First, false) => MinMax::Min,
(Index::First, true) => MinMax::Max,
(Index::Last, false) => MinMax::Max,
(Index::Last, true) => MinMax::Min,
};
let mut diagnostic = checker.report_diagnostic(SortedMinMax { min_max }, subscript.range());
if checker.semantic().has_builtin_binding(min_max.as_str()) {
diagnostic.set_fix({
let replacement = if let Some(key) = key_keyword_expr {
format!(
"{min_max}({}, {})",
checker.locator().slice(list_expr),
checker.locator().slice(key),
)
} else {
format!("{min_max}({})", checker.locator().slice(list_expr))
};
let replacement = Edit::range_replacement(replacement, subscript.range());
Fix::unsafe_edit(replacement)
});
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum MinMax {
/// E.g., `min(nums)`
Min,
/// E.g., `max(nums)`
Max,
}
impl MinMax {
fn as_str(self) -> &'static str {
match self {
Self::Min => "min",
Self::Max => "max",
}
}
}
impl std::fmt::Display for MinMax {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Min => write!(f, "min"),
Self::Max => write!(f, "max"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Index {
/// E.g., `sorted(nums)[0]`
First,
/// E.g., `sorted(nums)[-1]`
Last,
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/implicit_cwd.rs | crates/ruff_linter/src/rules/refurb/rules/implicit_cwd.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, Expr, ExprAttribute, ExprCall};
use ruff_text_size::Ranged;
use crate::{Edit, Fix, FixAvailability, Violation};
use crate::{checkers::ast::Checker, importer::ImportRequest};
/// ## What it does
/// Checks for current-directory lookups using `Path().resolve()`.
///
/// ## Why is this bad?
/// When looking up the current directory, prefer `Path.cwd()` over
/// `Path().resolve()`, as `Path.cwd()` is more explicit in its intent.
///
/// ## Example
/// ```python
/// from pathlib import Path
///
/// cwd = Path().resolve()
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// cwd = Path.cwd()
/// ```
///
/// ## References
/// - [Python documentation: `Path.cwd`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.cwd)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct ImplicitCwd;
impl Violation for ImplicitCwd {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace `Path().resolve()` with `Path.cwd()`".to_string())
}
}
/// FURB177
pub(crate) fn no_implicit_cwd(checker: &Checker, call: &ExprCall) {
if !call.arguments.is_empty() {
return;
}
let Expr::Attribute(ExprAttribute { attr, value, .. }) = call.func.as_ref() else {
return;
};
if attr != "resolve" {
return;
}
let Expr::Call(ExprCall {
func, arguments, ..
}) = value.as_ref()
else {
return;
};
// Match on arguments, but ignore keyword arguments. `Path()` accepts keyword arguments, but
// ignores them. See: https://github.com/python/cpython/issues/98094.
match &*arguments.args {
// Ex) `Path().resolve()`
[] => {}
// Ex) `Path(".").resolve()`
[arg] => {
let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = arg else {
return;
};
if !matches!(value.to_str(), "" | ".") {
return;
}
}
// Ex) `Path("foo", "bar").resolve()`
_ => return,
}
if !checker
.semantic()
.resolve_qualified_name(func)
.is_some_and(|qualified_name| matches!(qualified_name.segments(), ["pathlib", "Path"]))
{
return;
}
let mut diagnostic = checker.report_diagnostic(ImplicitCwd, call.range());
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
Ok(Fix::unsafe_edits(
Edit::range_replacement(format!("{binding}.cwd()"), call.range()),
[import_edit],
))
});
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/refurb/rules/readlines_in_for.rs | crates/ruff_linter/src/rules/refurb/rules/readlines_in_for.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{Comprehension, Expr, StmtFor};
use ruff_python_semantic::analyze::typing;
use ruff_python_semantic::analyze::typing::is_io_base_expr;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits::pad_end;
use crate::{AlwaysFixableViolation, Edit, Fix};
/// ## What it does
/// Checks for uses of `readlines()` when iterating over a file line-by-line.
///
/// ## Why is this bad?
/// Rather than iterating over all lines in a file by calling `readlines()`,
/// it's more convenient and performant to iterate over the file object
/// directly.
///
/// ## Example
/// ```python
/// with open("file.txt") as fp:
/// for line in fp.readlines():
/// ...
/// ```
///
/// Use instead:
/// ```python
/// with open("file.txt") as fp:
/// for line in fp:
/// ...
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe if there's comments in the
/// `readlines()` call, as comments may be removed.
///
/// For example, the fix would be marked as unsafe in the following case:
/// ```python
/// with open("file.txt") as fp:
/// for line in ( # comment
/// fp.readlines() # comment
/// ):
/// ...
/// ```
///
/// ## References
/// - [Python documentation: `io.IOBase.readlines`](https://docs.python.org/3/library/io.html#io.IOBase.readlines)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.5.0")]
pub(crate) struct ReadlinesInFor;
impl AlwaysFixableViolation for ReadlinesInFor {
#[derive_message_formats]
fn message(&self) -> String {
"Instead of calling `readlines()`, iterate over file object directly".to_string()
}
fn fix_title(&self) -> String {
"Remove `readlines()`".into()
}
}
/// FURB129
pub(crate) fn readlines_in_for(checker: &Checker, for_stmt: &StmtFor) {
readlines_in_iter(checker, for_stmt.iter.as_ref());
}
/// FURB129
pub(crate) fn readlines_in_comprehension(checker: &Checker, comprehension: &Comprehension) {
readlines_in_iter(checker, &comprehension.iter);
}
fn readlines_in_iter(checker: &Checker, iter_expr: &Expr) {
let Expr::Call(expr_call) = iter_expr else {
return;
};
let Expr::Attribute(expr_attr) = expr_call.func.as_ref() else {
return;
};
if expr_attr.attr.as_str() != "readlines" || !expr_call.arguments.is_empty() {
return;
}
// Determine whether `fp` in `fp.readlines()` was bound to a file object.
if let Expr::Name(name) = expr_attr.value.as_ref() {
if !checker
.semantic()
.resolve_name(name)
.map(|id| checker.semantic().binding(id))
.is_some_and(|binding| typing::is_io_base(binding, checker.semantic()))
{
return;
}
} else {
if !is_io_base_expr(expr_attr.value.as_ref(), checker.semantic()) {
return;
}
}
let deletion_range = if let Some(parenthesized_range) = parenthesized_range(
expr_attr.value.as_ref().into(),
expr_attr.into(),
checker.tokens(),
) {
expr_call.range().add_start(parenthesized_range.len())
} else {
expr_call.range().add_start(expr_attr.value.range().len())
};
let padded = pad_end(String::new(), deletion_range.end(), checker.locator());
let edit = if padded.is_empty() {
Edit::range_deletion(deletion_range)
} else {
Edit::range_replacement(padded, deletion_range)
};
let mut diagnostic = checker.report_diagnostic(ReadlinesInFor, expr_call.range());
diagnostic.set_fix(Fix::applicable_edit(
edit,
if checker.comment_ranges().intersects(iter_expr.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_errmsg/settings.rs | crates/ruff_linter/src/rules/flake8_errmsg/settings.rs | //! Settings for the `flake8-errmsg` plugin.
use crate::display_settings;
use ruff_macros::CacheKey;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Default, CacheKey)]
pub struct Settings {
pub max_string_length: usize,
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.flake8_errmsg",
fields = [
self.max_string_length
]
}
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_errmsg/mod.rs | crates/ruff_linter/src/rules/flake8_errmsg/mod.rs | //! Rules from [flake8-errmsg](https://pypi.org/project/flake8-errmsg/).
pub(crate) mod rules;
pub mod settings;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_diagnostics, settings};
#[test]
fn defaults() -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_errmsg/EM.py"),
&settings::LinterSettings::for_rules(vec![
Rule::RawStringInException,
Rule::FStringInException,
Rule::DotFormatInException,
]),
)?;
assert_diagnostics!("defaults", diagnostics);
Ok(())
}
#[test]
fn custom() -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_errmsg/EM.py"),
&settings::LinterSettings {
flake8_errmsg: super::settings::Settings {
max_string_length: 20,
},
..settings::LinterSettings::for_rules(vec![
Rule::RawStringInException,
Rule::FStringInException,
Rule::DotFormatInException,
])
},
)?;
assert_diagnostics!("custom", diagnostics);
Ok(())
}
#[test]
fn string_exception() -> Result<()> {
let diagnostics = test_path(
Path::new("flake8_errmsg/EM101_byte_string.py"),
&settings::LinterSettings {
..settings::LinterSettings::for_rule(Rule::RawStringInException)
},
)?;
assert_diagnostics!(diagnostics);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_errmsg/rules/string_in_exception.rs | crates/ruff_linter/src/rules/flake8_errmsg/rules/string_in_exception.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::whitespace;
use ruff_python_ast::{self as ast, Arguments, Expr, Stmt};
use ruff_python_codegen::Stylist;
use ruff_source_file::LineRanges;
use ruff_text_size::Ranged;
use crate::Locator;
use crate::checkers::ast::Checker;
use crate::registry::Rule;
use crate::{Edit, Fix, FixAvailability, Violation};
/// ## What it does
/// Checks for the use of string literals in exception constructors.
///
/// ## Why is this bad?
/// Python includes the `raise` in the default traceback (and formatters
/// like Rich and IPython do too).
///
/// By using a string literal, the error message will be duplicated in the
/// traceback, which can make the traceback less readable.
///
/// ## Example
/// Given:
/// ```python
/// raise RuntimeError("'Some value' is incorrect")
/// ```
///
/// Python will produce a traceback like:
/// ```console
/// Traceback (most recent call last):
/// File "tmp.py", line 2, in <module>
/// raise RuntimeError("'Some value' is incorrect")
/// RuntimeError: 'Some value' is incorrect
/// ```
///
/// Instead, assign the string to a variable:
/// ```python
/// msg = "'Some value' is incorrect"
/// raise RuntimeError(msg)
/// ```
///
/// Which will produce a traceback like:
/// ```console
/// Traceback (most recent call last):
/// File "tmp.py", line 3, in <module>
/// raise RuntimeError(msg)
/// RuntimeError: 'Some value' is incorrect
/// ```
///
/// ## Options
///
/// - `lint.flake8-errmsg.max-string-length`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.183")]
pub(crate) struct RawStringInException;
impl Violation for RawStringInException {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Exception must not use a string literal, assign to variable first".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove string literal".to_string())
}
}
/// ## What it does
/// Checks for the use of f-strings in exception constructors.
///
/// ## Why is this bad?
/// Python includes the `raise` in the default traceback (and formatters
/// like Rich and IPython do too).
///
/// By using an f-string, the error message will be duplicated in the
/// traceback, which can make the traceback less readable.
///
/// ## Example
/// Given:
/// ```python
/// sub = "Some value"
/// raise RuntimeError(f"{sub!r} is incorrect")
/// ```
///
/// Python will produce a traceback like:
/// ```console
/// Traceback (most recent call last):
/// File "tmp.py", line 2, in <module>
/// raise RuntimeError(f"{sub!r} is incorrect")
/// RuntimeError: 'Some value' is incorrect
/// ```
///
/// Instead, assign the string to a variable:
/// ```python
/// sub = "Some value"
/// msg = f"{sub!r} is incorrect"
/// raise RuntimeError(msg)
/// ```
///
/// Which will produce a traceback like:
/// ```console
/// Traceback (most recent call last):
/// File "tmp.py", line 3, in <module>
/// raise RuntimeError(msg)
/// RuntimeError: 'Some value' is incorrect
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.183")]
pub(crate) struct FStringInException;
impl Violation for FStringInException {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Exception must not use an f-string literal, assign to variable first".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove f-string literal".to_string())
}
}
/// ## What it does
/// Checks for the use of `.format` calls on string literals in exception
/// constructors.
///
/// ## Why is this bad?
/// Python includes the `raise` in the default traceback (and formatters
/// like Rich and IPython do too).
///
/// By using a `.format` call, the error message will be duplicated in the
/// traceback, which can make the traceback less readable.
///
/// ## Example
/// Given:
/// ```python
/// sub = "Some value"
/// raise RuntimeError("'{}' is incorrect".format(sub))
/// ```
///
/// Python will produce a traceback like:
/// ```console
/// Traceback (most recent call last):
/// File "tmp.py", line 2, in <module>
/// raise RuntimeError("'{}' is incorrect".format(sub))
/// RuntimeError: 'Some value' is incorrect
/// ```
///
/// Instead, assign the string to a variable:
/// ```python
/// sub = "Some value"
/// msg = "'{}' is incorrect".format(sub)
/// raise RuntimeError(msg)
/// ```
///
/// Which will produce a traceback like:
/// ```console
/// Traceback (most recent call last):
/// File "tmp.py", line 3, in <module>
/// raise RuntimeError(msg)
/// RuntimeError: 'Some value' is incorrect
/// ```
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.183")]
pub(crate) struct DotFormatInException;
impl Violation for DotFormatInException {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"Exception must not use a `.format()` string directly, assign to variable first".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Assign to variable; remove `.format()` string".to_string())
}
}
/// EM101, EM102, EM103
pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) {
let Expr::Call(ast::ExprCall {
func,
arguments: Arguments { args, .. },
..
}) = exc
else {
return;
};
if checker.semantic().match_typing_expr(func, "cast") {
return;
}
if let Some(first) = args.first() {
match first {
// Check for string literals.
Expr::StringLiteral(ast::ExprStringLiteral { value: string, .. }) => {
if checker.is_rule_enabled(Rule::RawStringInException) {
if string.len() >= checker.settings().flake8_errmsg.max_string_length {
let mut diagnostic =
checker.report_diagnostic(RawStringInException, first.range());
if let Some(indentation) = whitespace::indentation(checker.source(), stmt) {
diagnostic.set_fix(generate_fix(
stmt,
first,
indentation,
checker.stylist(),
checker.locator(),
));
}
}
}
}
// Check for byte string literals.
Expr::BytesLiteral(ast::ExprBytesLiteral { value: bytes, .. }) => {
if checker.settings().rules.enabled(Rule::RawStringInException) {
if bytes.len() >= checker.settings().flake8_errmsg.max_string_length {
let mut diagnostic =
checker.report_diagnostic(RawStringInException, first.range());
if let Some(indentation) = whitespace::indentation(checker.source(), stmt) {
diagnostic.set_fix(generate_fix(
stmt,
first,
indentation,
checker.stylist(),
checker.locator(),
));
}
}
}
}
// Check for f-strings.
Expr::FString(_) => {
if checker.is_rule_enabled(Rule::FStringInException) {
let mut diagnostic =
checker.report_diagnostic(FStringInException, first.range());
if let Some(indentation) = whitespace::indentation(checker.source(), stmt) {
diagnostic.set_fix(generate_fix(
stmt,
first,
indentation,
checker.stylist(),
checker.locator(),
));
}
}
}
// Check for .format() calls.
Expr::Call(ast::ExprCall { func, .. }) => {
if checker.is_rule_enabled(Rule::DotFormatInException) {
if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() {
if attr == "format" && value.is_literal_expr() {
let mut diagnostic =
checker.report_diagnostic(DotFormatInException, first.range());
if let Some(indentation) =
whitespace::indentation(checker.source(), stmt)
{
diagnostic.set_fix(generate_fix(
stmt,
first,
indentation,
checker.stylist(),
checker.locator(),
));
}
}
}
}
}
_ => {}
}
}
}
/// Generate the [`Fix`] for EM001, EM002, and EM003 violations.
///
/// This assumes that the violation is fixable and that the patch should
/// be generated. The exception argument should be either a string literal,
/// an f-string, or a `.format` string.
///
/// The fix includes two edits:
/// 1. Insert the exception argument into a variable assignment before the
/// `raise` statement. The variable name is `msg`.
/// 2. Replace the exception argument with the variable name.
fn generate_fix(
stmt: &Stmt,
exc_arg: &Expr,
stmt_indentation: &str,
stylist: &Stylist,
locator: &Locator,
) -> Fix {
Fix::unsafe_edits(
Edit::insertion(
if locator.contains_line_break(exc_arg.range()) {
format!(
"msg = ({line_ending}{stmt_indentation}{indentation}{}{line_ending}{stmt_indentation}){line_ending}{stmt_indentation}",
locator.slice(exc_arg.range()),
line_ending = stylist.line_ending().as_str(),
indentation = stylist.indentation().as_str(),
)
} else {
format!(
"msg = {}{}{}",
locator.slice(exc_arg.range()),
stylist.line_ending().as_str(),
stmt_indentation,
)
},
stmt.start(),
),
[Edit::range_replacement(
String::from("msg"),
exc_arg.range(),
)],
)
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_errmsg/rules/mod.rs | crates/ruff_linter/src/rules/flake8_errmsg/rules/mod.rs | pub(crate) use string_in_exception::*;
mod string_in_exception;
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/mccabe/settings.rs | crates/ruff_linter/src/rules/mccabe/settings.rs | //! Settings for the `mccabe` plugin.
use crate::display_settings;
use ruff_macros::CacheKey;
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, CacheKey)]
pub struct Settings {
pub max_complexity: usize,
}
pub const DEFAULT_MAX_COMPLEXITY: usize = 10;
impl Default for Settings {
fn default() -> Self {
Self {
max_complexity: DEFAULT_MAX_COMPLEXITY,
}
}
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
display_settings! {
formatter = f,
namespace = "linter.mccabe",
fields = [
self.max_complexity
]
}
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/mccabe/mod.rs | crates/ruff_linter/src/rules/mccabe/mod.rs | //! Rules from [mccabe](https://pypi.org/project/mccabe/).
pub(crate) mod rules;
pub mod settings;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use test_case::test_case;
use crate::assert_diagnostics;
use crate::registry::Rule;
use crate::settings::LinterSettings;
use crate::test::test_path;
#[test_case(0)]
#[test_case(3)]
#[test_case(10)]
fn max_complexity_zero(max_complexity: usize) -> Result<()> {
let snapshot = format!("max_complexity_{max_complexity}");
let diagnostics = test_path(
Path::new("mccabe/C901.py"),
&LinterSettings {
mccabe: super::settings::Settings { max_complexity },
..LinterSettings::for_rules(vec![Rule::ComplexStructure])
},
)?;
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/mccabe/rules/function_is_too_complex.rs | crates/ruff_linter/src/rules/mccabe/rules/function_is_too_complex.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::{self as ast, ExceptHandler, Stmt};
use crate::Violation;
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for functions with a high `McCabe` complexity.
///
/// ## Why is this bad?
/// The `McCabe` complexity of a function is a measure of the complexity of
/// the control flow graph of the function. It is calculated by adding
/// one to the number of decision points in the function. A decision
/// point is a place in the code where the program has a choice of two
/// or more paths to follow.
///
/// Functions with a high complexity are hard to understand and maintain.
///
/// ## Example
/// ```python
/// def foo(a, b, c):
/// if a:
/// if b:
/// if c:
/// return 1
/// else:
/// return 2
/// else:
/// return 3
/// else:
/// return 4
/// ```
///
/// Use instead:
/// ```python
/// def foo(a, b, c):
/// if not a:
/// return 4
/// if not b:
/// return 3
/// if not c:
/// return 2
/// return 1
/// ```
///
/// ## Options
/// - `lint.mccabe.max-complexity`
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.127")]
pub(crate) struct ComplexStructure {
name: String,
complexity: usize,
max_complexity: usize,
}
impl Violation for ComplexStructure {
#[derive_message_formats]
fn message(&self) -> String {
let ComplexStructure {
name,
complexity,
max_complexity,
} = self;
format!("`{name}` is too complex ({complexity} > {max_complexity})")
}
}
fn get_complexity_number(stmts: &[Stmt]) -> usize {
let mut complexity = 0;
for stmt in stmts {
match stmt {
Stmt::If(ast::StmtIf {
body,
elif_else_clauses,
..
}) => {
complexity += 1;
complexity += get_complexity_number(body);
for clause in elif_else_clauses {
if clause.test.is_some() {
complexity += 1;
}
complexity += get_complexity_number(&clause.body);
}
}
Stmt::For(ast::StmtFor { body, orelse, .. }) => {
complexity += 1;
complexity += get_complexity_number(body);
complexity += get_complexity_number(orelse);
}
Stmt::With(ast::StmtWith { body, .. }) => {
complexity += get_complexity_number(body);
}
Stmt::While(ast::StmtWhile { body, orelse, .. }) => {
complexity += 1;
complexity += get_complexity_number(body);
complexity += get_complexity_number(orelse);
}
Stmt::Match(ast::StmtMatch { cases, .. }) => {
for case in cases {
complexity += 1;
complexity += get_complexity_number(&case.body);
}
if let Some(last_case) = cases.last() {
// The complexity of an irrefutable pattern is similar to an `else` block of an `if` statement.
//
// For example:
// ```python
// match subject:
// case 1: ...
// case _: ...
//
// match subject:
// case 1: ...
// case foo: ...
// ```
if last_case.guard.is_none() && last_case.pattern.is_irrefutable() {
complexity -= 1;
}
}
}
Stmt::Try(ast::StmtTry {
body,
handlers,
orelse,
finalbody,
..
}) => {
complexity += get_complexity_number(body);
if !orelse.is_empty() {
complexity += 1;
}
complexity += get_complexity_number(orelse);
complexity += get_complexity_number(finalbody);
for handler in handlers {
complexity += 1;
let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
body, ..
}) = handler;
complexity += get_complexity_number(body);
}
}
Stmt::FunctionDef(ast::StmtFunctionDef { body, .. }) => {
complexity += 1;
complexity += get_complexity_number(body);
}
Stmt::ClassDef(ast::StmtClassDef { body, .. }) => {
complexity += get_complexity_number(body);
}
_ => {}
}
}
complexity
}
/// C901
pub(crate) fn function_is_too_complex(
checker: &Checker,
stmt: &Stmt,
name: &str,
body: &[Stmt],
max_complexity: usize,
) {
let complexity = get_complexity_number(body) + 1;
if complexity > max_complexity {
checker.report_diagnostic(
ComplexStructure {
name: name.to_string(),
complexity,
max_complexity,
},
stmt.identifier(),
);
}
}
#[cfg(test)]
mod tests {
use anyhow::Result;
use ruff_python_ast::Suite;
use ruff_python_parser::parse_module;
use super::get_complexity_number;
fn parse_suite(source: &str) -> Result<Suite> {
Ok(parse_module(source)?.into_suite())
}
#[test]
fn trivial() -> Result<()> {
let source = r"
def trivial():
pass
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}
#[test]
fn expr_as_statement() -> Result<()> {
let source = r"
def expr_as_statement():
0xF00D
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}
#[test]
fn sequential() -> Result<()> {
let source = r"
def sequential(n):
k = n + 4
s = k + n
return s
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}
#[test]
fn if_elif_else_dead_path() -> Result<()> {
let source = r#"
def if_elif_else_dead_path(n):
if n > 3:
return "bigger than three"
elif n > 4:
return "is never executed"
else:
return "smaller than or equal to three"
"#;
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 3);
Ok(())
}
#[test]
fn nested_ifs() -> Result<()> {
let source = r#"
def nested_ifs():
if n > 3:
if n > 4:
return "bigger than four"
else:
return "bigger than three"
else:
return "smaller than or equal to three"
"#;
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 3);
Ok(())
}
#[test]
fn for_loop() -> Result<()> {
let source = r"
def for_loop():
for i in range(10):
print(i)
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn for_else() -> Result<()> {
let source = r"
def for_else(mylist):
for i in mylist:
print(i)
else:
print(None)
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn recursive() -> Result<()> {
let source = r"
def recursive(n):
if n > 4:
return f(n - 1)
else:
return n
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn nested_functions() -> Result<()> {
let source = r"
def nested_functions():
def a():
def b():
pass
b()
a()
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 3);
Ok(())
}
#[test]
fn try_else() -> Result<()> {
let source = r"
def try_else():
try:
print(1)
except TypeA:
print(2)
except TypeB:
print(3)
else:
print(4)
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 4);
Ok(())
}
#[test]
fn nested_try_finally() -> Result<()> {
let source = r"
def nested_try_finally():
try:
try:
print(1)
finally:
print(2)
finally:
print(3)
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}
#[test]
fn foobar() -> Result<()> {
let source = r"
async def foobar(a, b, c):
await whatever(a, b, c)
if await b:
pass
async with c:
pass
async for x in a:
pass
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 3);
Ok(())
}
#[test]
fn annotated_assign() -> Result<()> {
let source = r"
def annotated_assign():
x: Any = None
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}
#[test]
fn class() -> Result<()> {
let source = r"
class Class:
def handle(self, *args, **options):
if args:
return
class ServiceProvider:
def a(self):
pass
def b(self, data):
if not args:
pass
class Logger:
def c(*args, **kwargs):
pass
def error(self, message):
pass
def info(self, message):
pass
def exception(self):
pass
return ServiceProvider(Logger())
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 9);
Ok(())
}
#[test]
fn finally() -> Result<()> {
let source = r"
def process_detect_lines():
try:
pass
finally:
pass
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 1);
Ok(())
}
#[test]
fn if_in_finally() -> Result<()> {
let source = r#"
def process_detect_lines():
try:
pass
finally:
if res:
errors.append(f"Non-zero exit code {res}")
"#;
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn with() -> Result<()> {
let source = r"
def with_lock():
with lock:
if foo:
print('bar')
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn simple_match_case() -> Result<()> {
let source = r"
def f():
match subject:
case 2:
print('foo')
case _:
print('bar')
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn multiple_match_case() -> Result<()> {
let source = r"
def f():
match subject:
case 2:
print('foo')
case 2:
print('bar')
case _:
print('baz')
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 3);
Ok(())
}
#[test]
fn named_catch_all_match_case() -> Result<()> {
let source = r"
def f():
match subject:
case 2:
print('hello')
case x:
print(x)
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
#[test]
fn match_case_catch_all_with_sequence() -> Result<()> {
let source = r"
def f():
match subject:
case 2:
print('hello')
case 5 | _:
print(x)
";
let stmts = parse_suite(source)?;
assert_eq!(get_complexity_number(&stmts), 2);
Ok(())
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/mccabe/rules/mod.rs | crates/ruff_linter/src/rules/mccabe/rules/mod.rs | pub(crate) use function_is_too_complex::*;
mod function_is_too_complex;
| rust | MIT | 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_use_pathlib/helpers.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/helpers.rs | use ruff_python_ast::{self as ast, Arguments, Expr, ExprCall};
use ruff_python_semantic::{SemanticModel, analyze::typing};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::{Applicability, Edit, Fix, Violation};
pub(crate) fn is_keyword_only_argument_non_default(arguments: &Arguments, name: &str) -> bool {
arguments
.find_keyword(name)
.is_some_and(|keyword| !keyword.value.is_none_literal_expr())
}
pub(crate) fn is_pathlib_path_call(checker: &Checker, expr: &Expr) -> bool {
expr.as_call_expr().is_some_and(|expr_call| {
checker
.semantic()
.resolve_qualified_name(&expr_call.func)
.is_some_and(|name| matches!(name.segments(), ["pathlib", "Path"]))
})
}
/// Check if the given segments represent a pathlib Path subclass or `PackagePath` with preview mode support.
/// In stable mode, only checks for `Path` and `PurePath`. In preview mode, also checks for
/// `PosixPath`, `PurePosixPath`, `WindowsPath`, `PureWindowsPath`, and `PackagePath`.
pub(crate) fn is_pure_path_subclass_with_preview(checker: &Checker, segments: &[&str]) -> bool {
let is_core_pathlib = matches!(segments, ["pathlib", "Path" | "PurePath"]);
if is_core_pathlib {
return true;
}
if checker.settings().preview.is_enabled() {
let is_expanded_pathlib = matches!(
segments,
[
"pathlib",
"PosixPath" | "PurePosixPath" | "WindowsPath" | "PureWindowsPath"
]
);
let is_packagepath = matches!(segments, ["importlib", "metadata", "PackagePath"]);
return is_expanded_pathlib || is_packagepath;
}
false
}
/// We check functions that take only 1 argument, this does not apply to functions
/// with `dir_fd` argument, because `dir_fd` is not supported by pathlib,
/// so check if it's set to non-default values
pub(crate) fn check_os_pathlib_single_arg_calls(
checker: &Checker,
call: &ExprCall,
attr: &str,
fn_argument: &str,
fix_enabled: bool,
violation: impl Violation,
applicability: Applicability,
) {
if call.arguments.len() != 1 {
return;
}
let Some(arg) = call.arguments.find_argument_value(fn_argument, 0) else {
return;
};
let arg_code = checker.locator().slice(arg.range());
let range = call.range();
let mut diagnostic = checker.report_diagnostic(violation, call.func.range());
if !fix_enabled {
return;
}
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let replacement = if is_pathlib_path_call(checker, arg) {
format!("{arg_code}.{attr}")
} else {
format!("{binding}({arg_code}).{attr}")
};
let edit = Edit::range_replacement(replacement, range);
let applicability = match applicability {
Applicability::DisplayOnly => Applicability::DisplayOnly,
_ if checker.comment_ranges().intersects(range) => Applicability::Unsafe,
_ => applicability,
};
let fix = Fix::applicable_edits(edit, [import_edit], applicability);
Ok(fix)
});
}
pub(crate) fn get_name_expr(expr: &Expr) -> Option<&ast::ExprName> {
match expr {
Expr::Name(name) => Some(name),
Expr::Call(ExprCall { func, .. }) => get_name_expr(func),
_ => None,
}
}
/// Returns `true` if the given expression looks like a file descriptor, i.e., if it is an integer.
pub(crate) fn is_file_descriptor(expr: &Expr, semantic: &SemanticModel) -> bool {
if matches!(
expr,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(_),
..
})
) {
return true;
}
let Some(name) = get_name_expr(expr) else {
return false;
};
let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else {
return false;
};
typing::is_int(binding, semantic)
}
#[expect(clippy::too_many_arguments)]
pub(crate) fn check_os_pathlib_two_arg_calls(
checker: &Checker,
call: &ExprCall,
attr: &str,
path_arg: &str,
second_arg: &str,
fix_enabled: bool,
violation: impl Violation,
applicability: Applicability,
) {
let range = call.range();
let mut diagnostic = checker.report_diagnostic(violation, call.func.range());
let (Some(path_expr), Some(second_expr)) = (
call.arguments.find_argument_value(path_arg, 0),
call.arguments.find_argument_value(second_arg, 1),
) else {
return;
};
let path_code = checker.locator().slice(path_expr.range());
let second_code = checker.locator().slice(second_expr.range());
if fix_enabled {
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let replacement = if is_pathlib_path_call(checker, path_expr) {
format!("{path_code}.{attr}({second_code})")
} else {
format!("{binding}({path_code}).{attr}({second_code})")
};
let applicability = match applicability {
Applicability::DisplayOnly => Applicability::DisplayOnly,
_ if checker.comment_ranges().intersects(range) => Applicability::Unsafe,
_ => applicability,
};
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_edit],
applicability,
))
});
}
}
pub(crate) fn has_unknown_keywords_or_starred_expr(
arguments: &Arguments,
allowed: &[&str],
) -> bool {
if arguments.args.iter().any(Expr::is_starred_expr) {
return true;
}
arguments.keywords.iter().any(|kw| match &kw.arg {
Some(arg) => !allowed.contains(&arg.as_str()),
None => true,
})
}
/// Returns `true` if argument `name` is set to a non-default `None` value.
pub(crate) fn is_argument_non_default(arguments: &Arguments, name: &str, position: usize) -> bool {
arguments
.find_argument_value(name, position)
.is_some_and(|expr| !expr.is_none_literal_expr())
}
/// Returns `true` if the given call is a top-level expression in its statement.
/// This means the call's return value is not used, so return type changes don't matter.
pub(crate) fn is_top_level_expression_in_statement(checker: &Checker) -> bool {
checker.semantic().current_expression_parent().is_none()
&& checker.semantic().current_statement().is_expr_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_use_pathlib/violations.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/violations.rs | use ruff_macros::{ViolationMetadata, derive_message_formats};
use crate::Violation;
/// ## What it does
/// Checks for uses of `os.stat`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.stat()` can improve readability over the `os`
/// module's counterparts (e.g., `os.path.stat()`).
///
/// ## Examples
/// ```python
/// import os
/// from pwd import getpwuid
/// from grp import getgrgid
///
/// stat = os.stat(file_name)
/// owner_name = getpwuid(stat.st_uid).pw_name
/// group_name = getgrgid(stat.st_gid).gr_name
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// file_path = Path(file_name)
/// stat = file_path.stat()
/// owner_name = file_path.owner()
/// group_name = file_path.group()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)
/// - [Python documentation: `Path.group`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.group)
/// - [Python documentation: `Path.owner`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.owner)
/// - [Python documentation: `os.stat`](https://docs.python.org/3/library/os.html#os.stat)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsStat;
impl Violation for OsStat {
#[derive_message_formats]
fn message(&self) -> String {
"`os.stat()` should be replaced by `Path.stat()`, `Path.owner()`, or `Path.group()`"
.to_string()
}
}
/// ## What it does
/// Checks for uses of `os.path.join`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.joinpath()` or the `/` operator can improve
/// readability over the `os.path` module's counterparts (e.g., `os.path.join()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.join(os.path.join(ROOT_PATH, "folder"), "file.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(ROOT_PATH) / "folder" / "file.py"
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `PurePath.joinpath`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.joinpath)
/// - [Python documentation: `os.path.join`](https://docs.python.org/3/library/os.path.html#os.path.join)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathJoin {
pub(crate) module: String,
pub(crate) joiner: Joiner,
}
impl Violation for OsPathJoin {
#[derive_message_formats]
fn message(&self) -> String {
let OsPathJoin { module, joiner } = self;
match joiner {
Joiner::Slash => {
format!("`os.{module}.join()` should be replaced by `Path` with `/` operator")
}
Joiner::Joinpath => {
format!("`os.{module}.join()` should be replaced by `Path.joinpath()`")
}
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Joiner {
Slash,
Joinpath,
}
/// ## What it does
/// Checks for uses of `os.path.splitext`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.suffix` and `Path.stem` can improve readability over
/// the `os.path` module's counterparts (e.g., `os.path.splitext()`).
///
/// `os.path.splitext()` specifically returns a tuple of the file root and
/// extension (e.g., given `splitext('/foo/bar.py')`, `os.path.splitext()`
/// returns `("foo/bar", ".py")`. These outputs can be reconstructed through a
/// combination of `Path.suffix` (`".py"`), `Path.stem` (`"bar"`), and
/// `Path.parent` (`"foo"`).
///
/// ## Examples
/// ```python
/// import os
///
/// (root, ext) = os.path.splitext("foo/bar.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// path = Path("foo/bar.py")
/// root = path.parent / path.stem
/// ext = path.suffix
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `Path.suffix`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix)
/// - [Python documentation: `Path.suffixes`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffixes)
/// - [Python documentation: `os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathSplitext;
impl Violation for OsPathSplitext {
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.splitext()` should be replaced by `Path.suffix`, `Path.stem`, and `Path.parent`"
.to_string()
}
}
/// ## What it does
/// Checks for uses of the `py.path` library.
///
/// ## Why is this bad?
/// The `py.path` library is in maintenance mode. Instead, prefer the standard
/// library's `pathlib` module, or third-party modules like `path` (formerly
/// `py.path`).
///
/// ## Examples
/// ```python
/// import py.path
///
/// p = py.path.local("/foo/bar").join("baz/qux")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// p = Path("/foo/bar") / "bar" / "qux"
/// ```
///
/// ## References
/// - [Python documentation: `Pathlib`](https://docs.python.org/3/library/pathlib.html)
/// - [Path repository](https://github.com/jaraco/path)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct PyPath;
impl Violation for PyPath {
#[derive_message_formats]
fn message(&self) -> String {
"`py.path` is in maintenance mode, use `pathlib` instead".to_string()
}
}
/// ## What it does
/// Checks for uses of `os.listdir`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `pathlib`'s
/// `Path.iterdir()` can improve readability over `os.listdir()`.
///
/// ## Example
///
/// ```python
/// p = "."
/// for d in os.listdir(p):
/// ...
///
/// if os.listdir(p):
/// ...
///
/// if "file" in os.listdir(p):
/// ...
/// ```
///
/// Use instead:
///
/// ```python
/// p = Path(".")
/// for d in p.iterdir():
/// ...
///
/// if any(p.iterdir()):
/// ...
///
/// if (p / "file").exists():
/// ...
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `Path.iterdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir)
/// - [Python documentation: `os.listdir`](https://docs.python.org/3/library/os.html#os.listdir)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct OsListdir;
impl Violation for OsListdir {
#[derive_message_formats]
fn message(&self) -> String {
"Use `pathlib.Path.iterdir()` instead.".to_string()
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/mod.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/mod.rs | //! Rules from [flake8-use-pathlib](https://pypi.org/project/flake8-use-pathlib/).
mod helpers;
pub(crate) mod rules;
pub(crate) mod violations;
#[cfg(test)]
mod tests {
use std::path::Path;
use anyhow::Result;
use ruff_python_ast::PythonVersion;
use test_case::test_case;
use crate::registry::Rule;
use crate::settings;
use crate::settings::types::PreviewMode;
use crate::test::test_path;
use crate::{assert_diagnostics, assert_diagnostics_diff};
#[test_case(Path::new("full_name.py"))]
#[test_case(Path::new("import_as.py"))]
#[test_case(Path::new("import_from_as.py"))]
#[test_case(Path::new("import_from.py"))]
#[test_case(Path::new("use_pathlib.py"))]
fn rules(path: &Path) -> Result<()> {
let snapshot = format!("{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_use_pathlib").join(path).as_path(),
&settings::LinterSettings::for_rules(vec![
Rule::OsPathAbspath,
Rule::OsChmod,
Rule::OsMkdir,
Rule::OsMakedirs,
Rule::OsRename,
Rule::OsReplace,
Rule::OsRmdir,
Rule::OsRemove,
Rule::OsUnlink,
Rule::OsGetcwd,
Rule::OsPathExists,
Rule::OsPathExpanduser,
Rule::OsPathIsdir,
Rule::OsPathIsfile,
Rule::OsPathIslink,
Rule::OsReadlink,
Rule::OsStat,
Rule::OsPathIsabs,
Rule::OsPathJoin,
Rule::OsPathBasename,
Rule::OsPathDirname,
Rule::OsPathSamefile,
Rule::OsPathSplitext,
Rule::BuiltinOpen,
]),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::PyPath, Path::new("py_path_1.py"))]
#[test_case(Rule::PyPath, Path::new("py_path_2.py"))]
#[test_case(Rule::BuiltinOpen, Path::new("PTH123.py"))]
#[test_case(Rule::PathConstructorCurrentDirectory, Path::new("PTH201.py"))]
#[test_case(Rule::OsPathGetsize, Path::new("PTH202.py"))]
#[test_case(Rule::OsPathGetsize, Path::new("PTH202_2.py"))]
#[test_case(Rule::OsPathGetatime, Path::new("PTH203.py"))]
#[test_case(Rule::OsPathGetmtime, Path::new("PTH204.py"))]
#[test_case(Rule::OsPathGetctime, Path::new("PTH205.py"))]
#[test_case(Rule::OsSepSplit, Path::new("PTH206.py"))]
#[test_case(Rule::Glob, Path::new("PTH207.py"))]
#[test_case(Rule::OsListdir, Path::new("PTH208.py"))]
#[test_case(Rule::InvalidPathlibWithSuffix, Path::new("PTH210.py"))]
#[test_case(Rule::InvalidPathlibWithSuffix, Path::new("PTH210_1.py"))]
#[test_case(Rule::OsSymlink, Path::new("PTH211.py"))]
fn rules_pypath(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_use_pathlib").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::InvalidPathlibWithSuffix, Path::new("PTH210.py"))]
#[test_case(Rule::InvalidPathlibWithSuffix, Path::new("PTH210_1.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("flake8_use_pathlib").join(path).as_path(),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY313.into(),
..settings::LinterSettings::for_rule(rule_code)
},
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY314.into(),
..settings::LinterSettings::for_rule(rule_code)
},
);
Ok(())
}
#[test_case(Path::new("full_name.py"))]
#[test_case(Path::new("import_as.py"))]
#[test_case(Path::new("import_from_as.py"))]
#[test_case(Path::new("import_from.py"))]
fn preview_rules(path: &Path) -> Result<()> {
let snapshot = format!("preview_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_use_pathlib").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rules(vec![
Rule::OsPathAbspath,
Rule::OsChmod,
Rule::OsMkdir,
Rule::OsMakedirs,
Rule::OsRename,
Rule::OsReplace,
Rule::OsRmdir,
Rule::OsRemove,
Rule::OsUnlink,
Rule::OsGetcwd,
Rule::OsPathExists,
Rule::OsPathExpanduser,
Rule::OsPathIsdir,
Rule::OsPathIsfile,
Rule::OsPathIslink,
Rule::OsReadlink,
Rule::OsStat,
Rule::OsPathIsabs,
Rule::OsPathJoin,
Rule::OsPathBasename,
Rule::OsPathDirname,
Rule::OsPathSamefile,
Rule::OsPathSplitext,
Rule::BuiltinOpen,
])
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::BuiltinOpen, Path::new("PTH123.py"))]
#[test_case(Rule::PathConstructorCurrentDirectory, Path::new("PTH201.py"))]
#[test_case(Rule::OsPathGetsize, Path::new("PTH202.py"))]
#[test_case(Rule::OsPathGetsize, Path::new("PTH202_2.py"))]
#[test_case(Rule::OsPathGetatime, Path::new("PTH203.py"))]
#[test_case(Rule::OsPathGetmtime, Path::new("PTH204.py"))]
#[test_case(Rule::OsPathGetctime, Path::new("PTH205.py"))]
fn preview_flake8_use_pathlib(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_use_pathlib").join(path).as_path(),
&settings::LinterSettings {
preview: PreviewMode::Enabled,
..settings::LinterSettings::for_rule(rule_code)
},
)?;
assert_diagnostics!(snapshot, diagnostics);
Ok(())
}
#[test_case(Rule::InvalidPathlibWithSuffix, Path::new("PTH210_2.py"))]
fn pathlib_with_suffix_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("flake8_use_pathlib").join(path).as_path(),
&settings::LinterSettings {
unresolved_target_version: PythonVersion::PY314.into(),
..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_use_pathlib/rules/os_chmod.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_chmod.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{ArgOrKeyword, ExprCall};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::preview::is_fix_os_chmod_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
has_unknown_keywords_or_starred_expr, is_file_descriptor, is_keyword_only_argument_non_default,
is_pathlib_path_call,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.chmod`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.chmod()` can improve readability over the `os`
/// module's counterparts (e.g., `os.chmod()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.chmod("file.py", 0o444)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("file.py").chmod(0o444)
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.chmod`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.chmod)
/// - [Python documentation: `os.chmod`](https://docs.python.org/3/library/os.html#os.chmod)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsChmod;
impl Violation for OsChmod {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.chmod()` should be replaced by `Path.chmod()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).chmod(...)`".to_string())
}
}
/// PTH101
pub(crate) fn os_chmod(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "chmod"] {
return;
}
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.chmod)
// ```text
// 0 1 2 3
// os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
// ```
let path_arg = call.arguments.find_argument_value("path", 0);
if path_arg.is_some_and(|expr| is_file_descriptor(expr, checker.semantic()))
|| is_keyword_only_argument_non_default(&call.arguments, "dir_fd")
{
return;
}
let range = call.range();
let mut diagnostic = checker.report_diagnostic(OsChmod, call.func.range());
if !is_fix_os_chmod_enabled(checker.settings()) {
return;
}
if call.arguments.len() < 2 {
return;
}
if has_unknown_keywords_or_starred_expr(
&call.arguments,
&["path", "mode", "dir_fd", "follow_symlinks"],
) {
return;
}
let (Some(path_arg), Some(_)) = (path_arg, call.arguments.find_argument_value("mode", 1))
else {
return;
};
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let locator = checker.locator();
let path_code = locator.slice(path_arg.range());
let args = |arg: ArgOrKeyword| match arg {
ArgOrKeyword::Arg(expr) if expr.range() != path_arg.range() => {
Some(locator.slice(expr.range()))
}
ArgOrKeyword::Keyword(kw)
if matches!(kw.arg.as_deref(), Some("mode" | "follow_symlinks")) =>
{
Some(locator.slice(kw.range()))
}
_ => None,
};
let chmod_args = itertools::join(
call.arguments.arguments_source_order().filter_map(args),
", ",
);
let replacement = if is_pathlib_path_call(checker, path_arg) {
format!("{path_code}.chmod({chmod_args})")
} else {
format!("{binding}({path_code}).chmod({chmod_args})")
};
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_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/flake8_use_pathlib/rules/os_readlink.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_readlink.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{ExprCall, PythonVersion};
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_readlink_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_single_arg_calls, is_keyword_only_argument_non_default,
is_top_level_expression_in_statement,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.readlink`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.readlink()` can improve readability over the `os`
/// module's counterparts (e.g., `os.readlink()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.readlink(file_name)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(file_name).readlink()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
/// Additionally, the fix is marked as unsafe when the return value is used because the type changes
/// from `str` or `bytes` (`AnyStr`) to a `Path` object.
///
/// ## References
/// - [Python documentation: `Path.readlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.readline)
/// - [Python documentation: `os.readlink`](https://docs.python.org/3/library/os.html#os.readlink)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsReadlink;
impl Violation for OsReadlink {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.readlink()` should be replaced by `Path.readlink()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).readlink()`".to_string())
}
}
/// PTH115
pub(crate) fn os_readlink(checker: &Checker, call: &ExprCall, segments: &[&str]) {
// Python 3.9+
if checker.target_version() < PythonVersion::PY39 {
return;
}
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.readlink)
// ```text
// 0 1
// os.readlink(path, *, dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
if segments != ["os", "readlink"] {
return;
}
let applicability = if !is_top_level_expression_in_statement(checker) {
// Unsafe because the return type changes (str/bytes -> Path)
Applicability::Unsafe
} else {
Applicability::Safe
};
check_os_pathlib_single_arg_calls(
checker,
call,
"readlink()",
"path",
is_fix_os_readlink_enabled(checker.settings()),
OsReadlink,
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/flake8_use_pathlib/rules/path_constructor_current_directory.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/path_constructor_current_directory.rs | use std::ops::Range;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::token::parenthesized_range;
use ruff_python_ast::{Expr, ExprBinOp, ExprCall, Operator};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::{Ranged, TextRange};
use crate::checkers::ast::Checker;
use crate::fix::edits::{Parentheses, remove_argument};
use crate::rules::flake8_use_pathlib::helpers::is_pure_path_subclass_with_preview;
use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
/// ## What it does
/// Checks for `pathlib.Path` objects that are initialized with the current
/// directory.
///
/// ## Why is this bad?
/// The `Path()` constructor defaults to the current directory, so passing it
/// in explicitly (as `"."`) is unnecessary.
///
/// ## Example
/// ```python
/// from pathlib import Path
///
/// _ = Path(".")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// _ = Path()
/// ```
///
/// ## Fix safety
/// This fix is marked unsafe if there are comments inside the parentheses, as applying
/// the fix will delete them.
///
/// ## References
/// - [Python documentation: `Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct PathConstructorCurrentDirectory;
impl AlwaysFixableViolation for PathConstructorCurrentDirectory {
#[derive_message_formats]
fn message(&self) -> String {
"Do not pass the current directory explicitly to `Path`".to_string()
}
fn fix_title(&self) -> String {
"Remove the current directory argument".to_string()
}
}
/// PTH201
pub(crate) fn path_constructor_current_directory(
checker: &Checker,
call: &ExprCall,
segments: &[&str],
) {
let applicability = |range| {
if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
}
};
let arguments = &call.arguments;
if !is_pure_path_subclass_with_preview(checker, segments) {
return;
}
if !arguments.keywords.is_empty() {
return;
}
let [Expr::StringLiteral(arg)] = &*arguments.args else {
return;
};
if !matches!(arg.value.to_str(), "" | ".") {
return;
}
let mut diagnostic = checker.report_diagnostic(PathConstructorCurrentDirectory, arg.range());
match parent_and_next_path_fragment_range(checker.semantic(), checker.tokens()) {
Some((parent_range, next_fragment_range)) => {
let next_fragment_expr = checker.locator().slice(next_fragment_range);
let call_expr = checker.locator().slice(call.range());
let relative_argument_range: Range<usize> = {
let range = arg.range() - call.start();
range.start().into()..range.end().into()
};
let mut new_call_expr = call_expr.to_string();
new_call_expr.replace_range(relative_argument_range, next_fragment_expr);
let edit = Edit::range_replacement(new_call_expr, parent_range);
diagnostic.set_fix(Fix::applicable_edit(edit, applicability(parent_range)));
}
None => diagnostic.try_set_fix(|| {
let edit = remove_argument(
arg,
arguments,
Parentheses::Preserve,
checker.source(),
checker.tokens(),
)?;
Ok(Fix::applicable_edit(edit, applicability(call.range())))
}),
}
}
fn parent_and_next_path_fragment_range(
semantic: &SemanticModel,
tokens: &ruff_python_ast::token::Tokens,
) -> Option<(TextRange, TextRange)> {
let parent = semantic.current_expression_parent()?;
let Expr::BinOp(parent @ ExprBinOp { op, right, .. }) = parent else {
return None;
};
let range = right.range();
if !matches!(op, Operator::Div) {
return None;
}
Some((
parent.range(),
parenthesized_range(right.into(), parent.into(), tokens).unwrap_or(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_use_pathlib/rules/os_getcwd.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_getcwd.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::preview::is_fix_os_getcwd_enabled;
use crate::rules::flake8_use_pathlib::helpers::is_top_level_expression_in_statement;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.getcwd` and `os.getcwdb`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.cwd()` can improve readability over the `os`
/// module's counterparts (e.g., `os.getcwd()`).
///
/// ## Examples
/// ```python
/// import os
///
/// cwd = os.getcwd()
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// cwd = Path.cwd()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
/// Additionally, the fix is marked as unsafe when the return value is used because the type changes
/// from `str` or `bytes` to a `Path` object.
///
/// ## References
/// - [Python documentation: `Path.cwd`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.cwd)
/// - [Python documentation: `os.getcwd`](https://docs.python.org/3/library/os.html#os.getcwd)
/// - [Python documentation: `os.getcwdb`](https://docs.python.org/3/library/os.html#os.getcwdb)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsGetcwd;
impl Violation for OsGetcwd {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.getcwd()` should be replaced by `Path.cwd()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path.cwd()`".to_string())
}
}
/// PTH109
pub(crate) fn os_getcwd(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if !matches!(segments, ["os", "getcwd" | "getcwdb"]) {
return;
}
let range = call.range();
let mut diagnostic = checker.report_diagnostic(OsGetcwd, call.func.range());
if !call.arguments.is_empty() {
return;
}
if is_fix_os_getcwd_enabled(checker.settings()) {
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
// Unsafe when the fix would delete comments or change a used return value
let applicability = if checker.comment_ranges().intersects(range)
|| !is_top_level_expression_in_statement(checker)
{
Applicability::Unsafe
} else {
Applicability::Safe
};
let replacement = format!("{binding}.cwd()");
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_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/flake8_use_pathlib/rules/os_remove.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_remove.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_remove_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
check_os_pathlib_single_arg_calls, is_keyword_only_argument_non_default,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.remove`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.unlink()` can improve readability over the `os`
/// module's counterparts (e.g., `os.remove()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.remove("file.py")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("file.py").unlink()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.unlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink)
/// - [Python documentation: `os.remove`](https://docs.python.org/3/library/os.html#os.remove)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsRemove;
impl Violation for OsRemove {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.remove()` should be replaced by `Path.unlink()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).unlink()`".to_string())
}
}
/// PTH107
pub(crate) fn os_remove(checker: &Checker, call: &ExprCall, segments: &[&str]) {
// `dir_fd` is not supported by pathlib, so check if it's set to non-default values.
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.remove)
// ```text
// 0 1
// os.remove(path, *, dir_fd=None)
// ```
if is_keyword_only_argument_non_default(&call.arguments, "dir_fd") {
return;
}
if segments != ["os", "remove"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"unlink()",
"path",
is_fix_os_remove_enabled(checker.settings()),
OsRemove,
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_use_pathlib/rules/os_path_islink.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_islink.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_islink_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.islink`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.is_symlink()` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.islink()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.islink("docs")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("docs").is_symlink()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.is_symlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_symlink)
/// - [Python documentation: `os.path.islink`](https://docs.python.org/3/library/os.path.html#os.path.islink)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathIslink;
impl Violation for OsPathIslink {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.islink()` should be replaced by `Path.is_symlink()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).is_symlink()`".to_string())
}
}
/// PTH114
pub(crate) fn os_path_islink(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "islink"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"is_symlink()",
"path",
is_fix_os_path_islink_enabled(checker.settings()),
OsPathIslink,
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_use_pathlib/rules/os_path_expanduser.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_expanduser.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_expanduser_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.expanduser`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.expanduser()` can improve readability over the `os.path`
/// module's counterparts (e.g., as `os.path.expanduser()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.expanduser("~/films/Monty Python")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("~/films/Monty Python").expanduser()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is always marked as unsafe because the behaviors of
/// `os.path.expanduser` and `Path.expanduser` differ when a user's home
/// directory can't be resolved: `os.path.expanduser` returns the
/// input unchanged, while `Path.expanduser` raises `RuntimeError`.
///
/// Additionally, the fix is marked as unsafe because `os.path.expanduser()` returns `str` or `bytes` (`AnyStr`),
/// while `Path.expanduser()` returns a `Path` object. This change in return type can break code that uses
/// the return value.
///
/// ## References
/// - [Python documentation: `Path.expanduser`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.expanduser)
/// - [Python documentation: `os.path.expanduser`](https://docs.python.org/3/library/os.path.html#os.path.expanduser)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathExpanduser;
impl Violation for OsPathExpanduser {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.expanduser()` should be replaced by `Path.expanduser()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).expanduser()`".to_string())
}
}
/// PTH111
pub(crate) fn os_path_expanduser(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "expanduser"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"expanduser()",
"path",
is_fix_os_path_expanduser_enabled(checker.settings()),
OsPathExpanduser,
Applicability::Unsafe,
);
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_isabs.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_isabs.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_isabs_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.isabs`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.is_absolute()` can improve readability over the `os.path`
/// module's counterparts (e.g., as `os.path.isabs()`).
///
/// ## Examples
/// ```python
/// import os
///
/// if os.path.isabs(file_name):
/// print("Absolute path!")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// if Path(file_name).is_absolute():
/// print("Absolute path!")
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## References
/// - [Python documentation: `PurePath.is_absolute`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.is_absolute)
/// - [Python documentation: `os.path.isabs`](https://docs.python.org/3/library/os.path.html#os.path.isabs)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathIsabs;
impl Violation for OsPathIsabs {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.isabs()` should be replaced by `Path.is_absolute()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).is_absolute()`".to_string())
}
}
/// PTH117
pub(crate) fn os_path_isabs(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "isabs"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"is_absolute()",
"s",
is_fix_os_path_isabs_enabled(checker.settings()),
OsPathIsabs,
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_use_pathlib/rules/os_path_getmtime.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_getmtime.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_getmtime_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.getmtime`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`.
///
/// When possible, using `Path` object methods such as `Path.stat()` can
/// improve readability over the `os.path` module's counterparts (e.g.,
/// `os.path.getmtime()`).
///
/// ## Example
/// ```python
/// import os
///
/// os.path.getmtime(__file__)
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path(__file__).stat().st_mtime
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)
/// - [Python documentation: `os.path.getmtime`](https://docs.python.org/3/library/os.path.html#os.path.getmtime)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.279")]
pub(crate) struct OsPathGetmtime;
impl Violation for OsPathGetmtime {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.getmtime` should be replaced by `Path.stat().st_mtime`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path.stat(...).st_mtime`".to_string())
}
}
/// PTH204
pub(crate) fn os_path_getmtime(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "getmtime"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"stat().st_mtime",
"filename",
is_fix_os_path_getmtime_enabled(checker.settings()),
OsPathGetmtime,
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_use_pathlib/rules/invalid_pathlib_with_suffix.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/invalid_pathlib_with_suffix.rs | use crate::checkers::ast::Checker;
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{self as ast, PythonVersion, StringFlags};
use ruff_python_semantic::SemanticModel;
use ruff_python_semantic::analyze::typing::{self, PathlibPathChecker, TypeChecker};
use ruff_text_size::Ranged;
/// ## What it does
/// Checks for `pathlib.Path.with_suffix()` calls where
/// the given suffix does not have a leading dot
/// or the given suffix is a single dot `"."` and the
/// Python version is less than 3.14.
///
/// ## Why is this bad?
/// `Path.with_suffix()` will raise an error at runtime
/// if the given suffix is not prefixed with a dot
/// or, in versions prior to Python 3.14, if it is a single dot `"."`.
///
/// ## Example
///
/// ```python
/// from pathlib import Path
///
/// path = Path()
///
/// path.with_suffix("py")
/// ```
///
/// Use instead:
///
/// ```python
/// from pathlib import Path
///
/// path = Path()
///
/// path.with_suffix(".py")
/// ```
///
/// ## Known problems
/// This rule is likely to have false negatives, as Ruff can only emit the
/// lint if it can say for sure that a binding refers to a `Path` object at
/// runtime. Due to type inference limitations, Ruff is currently only
/// confident about this if it can see that the binding originates from a
/// function parameter annotated with `Path` or from a direct assignment to a
/// `Path()` constructor call.
///
/// ## Fix safety
/// The fix for this rule adds a leading period to the string passed
/// to the `with_suffix()` call. This fix is marked as unsafe, as it
/// changes runtime behaviour: the call would previously always have
/// raised an exception, but no longer will.
///
/// Moreover, it's impossible to determine if this is the correct fix
/// for a given situation (it's possible that the string was correct
/// but was being passed to the wrong method entirely, for example).
///
/// No fix is offered if the suffix `"."` is given, since the intent is unclear.
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "0.10.0")]
pub(crate) struct InvalidPathlibWithSuffix {
single_dot: bool,
}
impl Violation for InvalidPathlibWithSuffix {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
if self.single_dot {
"Invalid suffix passed to `.with_suffix()`".to_string()
} else {
"Dotless suffix passed to `.with_suffix()`".to_string()
}
}
fn fix_title(&self) -> Option<String> {
let title = if self.single_dot {
"Remove \".\" or extend to valid suffix"
} else {
"Add a leading dot"
};
Some(title.to_string())
}
}
/// PTH210
pub(crate) fn invalid_pathlib_with_suffix(checker: &Checker, call: &ast::ExprCall) {
let (func, arguments) = (&call.func, &call.arguments);
if !is_path_with_suffix_call(checker.semantic(), func) {
return;
}
if arguments.len() > 1 {
return;
}
let Some(ast::Expr::StringLiteral(string)) = arguments.find_argument_value("suffix", 0) else {
return;
};
let string_value = string.value.to_str();
if string_value.is_empty() {
return;
}
if string_value.starts_with('.') && string_value.len() > 1 {
return;
}
let [first_part, ..] = string.value.as_slice() else {
return;
};
let single_dot = string_value == ".";
// As of Python 3.14, a single dot is considered a valid suffix.
// https://docs.python.org/3.14/library/pathlib.html#pathlib.PurePath.with_suffix
if single_dot && checker.target_version() >= PythonVersion::PY314 {
return;
}
let mut diagnostic =
checker.report_diagnostic(InvalidPathlibWithSuffix { single_dot }, call.range);
if !single_dot {
let after_leading_quote = string.start() + first_part.flags.opener_len();
diagnostic.set_fix(Fix::unsafe_edit(Edit::insertion(
".".to_string(),
after_leading_quote,
)));
}
}
fn is_path_with_suffix_call(semantic: &SemanticModel, func: &ast::Expr) -> bool {
let ast::Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func else {
return false;
};
if attr != "with_suffix" {
return false;
}
match &**value {
ast::Expr::Name(name) => {
let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else {
return false;
};
typing::is_pathlib_path(binding, semantic)
}
expr => PathlibPathChecker::match_initializer(expr, semantic),
}
}
| rust | MIT | 8464aca795bc3580ca15fcb52b21616939cea9a9 | 2026-01-04T15:31:59.413821Z | false |
astral-sh/ruff | https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_isfile.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_path_isfile.rs | use ruff_diagnostics::Applicability;
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::ExprCall;
use crate::checkers::ast::Checker;
use crate::preview::is_fix_os_path_isfile_enabled;
use crate::rules::flake8_use_pathlib::helpers::check_os_pathlib_single_arg_calls;
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.path.isfile`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os.path`. When possible, using `Path` object
/// methods such as `Path.is_file()` can improve readability over the `os.path`
/// module's counterparts (e.g., `os.path.isfile()`).
///
/// ## Examples
/// ```python
/// import os
///
/// os.path.isfile("docs")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("docs").is_file()
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.is_file`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file)
/// - [Python documentation: `os.path.isfile`](https://docs.python.org/3/library/os.path.html#os.path.isfile)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsPathIsfile;
impl Violation for OsPathIsfile {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.path.isfile()` should be replaced by `Path.is_file()`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).is_file()`".to_string())
}
}
/// PTH113
pub(crate) fn os_path_isfile(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "path", "isfile"] {
return;
}
check_os_pathlib_single_arg_calls(
checker,
call,
"is_file()",
"path",
is_fix_os_path_isfile_enabled(checker.settings()),
OsPathIsfile,
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_use_pathlib/rules/os_makedirs.rs | crates/ruff_linter/src/rules/flake8_use_pathlib/rules/os_makedirs.rs | use ruff_diagnostics::{Applicability, Edit, Fix};
use ruff_macros::{ViolationMetadata, derive_message_formats};
use ruff_python_ast::{ArgOrKeyword, ExprCall};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;
use crate::preview::is_fix_os_makedirs_enabled;
use crate::rules::flake8_use_pathlib::helpers::{
has_unknown_keywords_or_starred_expr, is_pathlib_path_call,
};
use crate::{FixAvailability, Violation};
/// ## What it does
/// Checks for uses of `os.makedirs`.
///
/// ## Why is this bad?
/// `pathlib` offers a high-level API for path manipulation, as compared to
/// the lower-level API offered by `os`. When possible, using `Path` object
/// methods such as `Path.mkdir(parents=True)` can improve readability over the
/// `os` module's counterparts (e.g., `os.makedirs()`.
///
/// ## Examples
/// ```python
/// import os
///
/// os.makedirs("./nested/directory/")
/// ```
///
/// Use instead:
/// ```python
/// from pathlib import Path
///
/// Path("./nested/directory/").mkdir(parents=True)
/// ```
///
/// ## Known issues
/// While using `pathlib` can improve the readability and type safety of your code,
/// it can be less performant than the lower-level alternatives that work directly with strings,
/// especially on older versions of Python.
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.
///
/// ## References
/// - [Python documentation: `Path.mkdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir)
/// - [Python documentation: `os.makedirs`](https://docs.python.org/3/library/os.html#os.makedirs)
/// - [PEP 428 β The pathlib module β object-oriented filesystem paths](https://peps.python.org/pep-0428/)
/// - [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)
/// - [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)
/// - [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)
#[derive(ViolationMetadata)]
#[violation_metadata(stable_since = "v0.0.231")]
pub(crate) struct OsMakedirs;
impl Violation for OsMakedirs {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
"`os.makedirs()` should be replaced by `Path.mkdir(parents=True)`".to_string()
}
fn fix_title(&self) -> Option<String> {
Some("Replace with `Path(...).mkdir(parents=True)`".to_string())
}
}
/// PTH103
pub(crate) fn os_makedirs(checker: &Checker, call: &ExprCall, segments: &[&str]) {
if segments != ["os", "makedirs"] {
return;
}
let range = call.range();
let mut diagnostic = checker.report_diagnostic(OsMakedirs, call.func.range());
let Some(name) = call.arguments.find_argument_value("name", 0) else {
return;
};
if !is_fix_os_makedirs_enabled(checker.settings()) {
return;
}
// Signature as of Python 3.13 (https://docs.python.org/3/library/os.html#os.makedirs)
// ```text
// 0 1 2
// os.makedirs(name, mode=0o777, exist_ok=False)
// ```
// We should not offer autofixes if there are more arguments
// than in the original signature
if call.arguments.len() > 3 {
return;
}
// We should not offer autofixes if there are keyword arguments
// that don't match the original function signature
if has_unknown_keywords_or_starred_expr(&call.arguments, &["name", "mode", "exist_ok"]) {
return;
}
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import("pathlib", "Path"),
call.start(),
checker.semantic(),
)?;
let applicability = if checker.comment_ranges().intersects(range) {
Applicability::Unsafe
} else {
Applicability::Safe
};
let locator = checker.locator();
let name_code = locator.slice(name.range());
let mode = call.arguments.find_argument("mode", 1);
let exist_ok = call.arguments.find_argument("exist_ok", 2);
let mkdir_args = match (mode, exist_ok) {
// Default to a keyword argument when alone.
(None, None) => "parents=True".to_string(),
// If either argument is missing, it's safe to add `parents` at the end.
(None, Some(arg)) | (Some(arg), None) => {
format!("{}, parents=True", locator.slice(arg))
}
// If they're all positional, `parents` has to be positional too.
(Some(ArgOrKeyword::Arg(mode)), Some(ArgOrKeyword::Arg(exist_ok))) => {
format!("{}, True, {}", locator.slice(mode), locator.slice(exist_ok))
}
// If either argument is a keyword, we can put `parents` at the end again.
(Some(mode), Some(exist_ok)) => format!(
"{}, {}, parents=True",
locator.slice(mode),
locator.slice(exist_ok)
),
};
let replacement = if is_pathlib_path_call(checker, name) {
format!("{name_code}.mkdir({mkdir_args})")
} else {
format!("{binding}({name_code}).mkdir({mkdir_args})")
};
Ok(Fix::applicable_edits(
Edit::range_replacement(replacement, range),
[import_edit],
applicability,
))
});
}
| 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.