refactor: Add Copy implementation to Rule (#3556)

This commit is contained in:
Micha Reiser 2023-03-16 17:50:18 +01:00 committed by GitHub
parent aa51ecedc5
commit eff84442bc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
59 changed files with 835 additions and 965 deletions

File diff suppressed because it is too large Load diff

View file

@ -15,7 +15,7 @@ pub fn check_file_path(
let mut diagnostics: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
// flake8-no-pep420 // flake8-no-pep420
if settings.rules.enabled(&Rule::ImplicitNamespacePackage) { if settings.rules.enabled(Rule::ImplicitNamespacePackage) {
if let Some(diagnostic) = if let Some(diagnostic) =
implicit_namespace_package(path, package, &settings.project_root, &settings.src) implicit_namespace_package(path, package, &settings.project_root, &settings.src)
{ {
@ -24,7 +24,7 @@ pub fn check_file_path(
} }
// pep8-naming // pep8-naming
if settings.rules.enabled(&Rule::InvalidModuleName) { if settings.rules.enabled(Rule::InvalidModuleName) {
if let Some(diagnostic) = invalid_module_name(path, package) { if let Some(diagnostic) = invalid_module_name(path, package) {
diagnostics.push(diagnostic); diagnostics.push(diagnostic);
} }

View file

@ -38,7 +38,7 @@ pub fn check_imports(
// Enforce import rules. // Enforce import rules.
let mut diagnostics = vec![]; let mut diagnostics = vec![];
if settings.rules.enabled(&Rule::UnsortedImports) { if settings.rules.enabled(Rule::UnsortedImports) {
for block in &blocks { for block in &blocks {
if !block.imports.is_empty() { if !block.imports.is_empty() {
if let Some(diagnostic) = isort::rules::organize_imports( if let Some(diagnostic) = isort::rules::organize_imports(
@ -49,7 +49,7 @@ pub fn check_imports(
} }
} }
} }
if settings.rules.enabled(&Rule::MissingRequiredImport) { if settings.rules.enabled(Rule::MissingRequiredImport) {
diagnostics.extend(isort::rules::add_required_imports( diagnostics.extend(isort::rules::add_required_imports(
&blocks, python_ast, locator, stylist, settings, autofix, &blocks, python_ast, locator, stylist, settings, autofix,
)); ));

View file

@ -166,7 +166,7 @@ pub fn check_logical_lines(
} }
#[cfg(feature = "logical_lines")] #[cfg(feature = "logical_lines")]
let should_fix = autofix.into() && settings.rules.should_fix(&Rule::MissingWhitespace); let should_fix = autofix.into() && settings.rules.should_fix(Rule::MissingWhitespace);
#[cfg(not(feature = "logical_lines"))] #[cfg(not(feature = "logical_lines"))]
let should_fix = false; let should_fix = false;
@ -181,7 +181,7 @@ pub fn check_logical_lines(
if line.flags.contains(TokenFlags::BRACKET) { if line.flags.contains(TokenFlags::BRACKET) {
#[cfg(feature = "logical_lines")] #[cfg(feature = "logical_lines")]
let should_fix = let should_fix =
autofix.into() && settings.rules.should_fix(&Rule::WhitespaceBeforeParameters); autofix.into() && settings.rules.should_fix(Rule::WhitespaceBeforeParameters);
#[cfg(not(feature = "logical_lines"))] #[cfg(not(feature = "logical_lines"))]
let should_fix = false; let should_fix = false;

View file

@ -24,7 +24,7 @@ pub fn check_noqa(
settings: &Settings, settings: &Settings,
autofix: flags::Autofix, autofix: flags::Autofix,
) -> Vec<usize> { ) -> Vec<usize> {
let enforce_noqa = settings.rules.enabled(&Rule::UnusedNOQA); let enforce_noqa = settings.rules.enabled(Rule::UnusedNOQA);
// Whether the file is exempted from all checks. // Whether the file is exempted from all checks.
let mut file_exempted = false; let mut file_exempted = false;
@ -188,7 +188,7 @@ pub fn check_noqa(
valid_codes.push(code); valid_codes.push(code);
} else { } else {
if let Ok(rule) = Rule::from_code(code) { if let Ok(rule) = Rule::from_code(code) {
if settings.rules.enabled(&rule) { if settings.rules.enabled(rule) {
unmatched_codes.push(code); unmatched_codes.push(code);
} else { } else {
disabled_codes.push(code); disabled_codes.push(code);

View file

@ -32,28 +32,28 @@ pub fn check_physical_lines(
let mut diagnostics: Vec<Diagnostic> = vec![]; let mut diagnostics: Vec<Diagnostic> = vec![];
let mut has_any_shebang = false; let mut has_any_shebang = false;
let enforce_blanket_noqa = settings.rules.enabled(&Rule::BlanketNOQA); let enforce_blanket_noqa = settings.rules.enabled(Rule::BlanketNOQA);
let enforce_shebang_not_executable = settings.rules.enabled(&Rule::ShebangNotExecutable); let enforce_shebang_not_executable = settings.rules.enabled(Rule::ShebangNotExecutable);
let enforce_shebang_missing = settings.rules.enabled(&Rule::ShebangMissingExecutableFile); let enforce_shebang_missing = settings.rules.enabled(Rule::ShebangMissingExecutableFile);
let enforce_shebang_whitespace = settings.rules.enabled(&Rule::ShebangWhitespace); let enforce_shebang_whitespace = settings.rules.enabled(Rule::ShebangWhitespace);
let enforce_shebang_newline = settings.rules.enabled(&Rule::ShebangNewline); let enforce_shebang_newline = settings.rules.enabled(Rule::ShebangNewline);
let enforce_shebang_python = settings.rules.enabled(&Rule::ShebangPython); let enforce_shebang_python = settings.rules.enabled(Rule::ShebangPython);
let enforce_blanket_type_ignore = settings.rules.enabled(&Rule::BlanketTypeIgnore); let enforce_blanket_type_ignore = settings.rules.enabled(Rule::BlanketTypeIgnore);
let enforce_doc_line_too_long = settings.rules.enabled(&Rule::DocLineTooLong); let enforce_doc_line_too_long = settings.rules.enabled(Rule::DocLineTooLong);
let enforce_line_too_long = settings.rules.enabled(&Rule::LineTooLong); let enforce_line_too_long = settings.rules.enabled(Rule::LineTooLong);
let enforce_no_newline_at_end_of_file = settings.rules.enabled(&Rule::NoNewLineAtEndOfFile); let enforce_no_newline_at_end_of_file = settings.rules.enabled(Rule::NoNewLineAtEndOfFile);
let enforce_unnecessary_coding_comment = settings.rules.enabled(&Rule::UTF8EncodingDeclaration); let enforce_unnecessary_coding_comment = settings.rules.enabled(Rule::UTF8EncodingDeclaration);
let enforce_mixed_spaces_and_tabs = settings.rules.enabled(&Rule::MixedSpacesAndTabs); let enforce_mixed_spaces_and_tabs = settings.rules.enabled(Rule::MixedSpacesAndTabs);
let enforce_bidirectional_unicode = settings.rules.enabled(&Rule::BidirectionalUnicode); let enforce_bidirectional_unicode = settings.rules.enabled(Rule::BidirectionalUnicode);
let enforce_trailing_whitespace = settings.rules.enabled(&Rule::TrailingWhitespace); let enforce_trailing_whitespace = settings.rules.enabled(Rule::TrailingWhitespace);
let enforce_blank_line_contains_whitespace = let enforce_blank_line_contains_whitespace =
settings.rules.enabled(&Rule::BlankLineContainsWhitespace); settings.rules.enabled(Rule::BlankLineContainsWhitespace);
let enforce_indentation_contains_tabs = settings.rules.enabled(&Rule::IndentationContainsTabs); let enforce_indentation_contains_tabs = settings.rules.enabled(Rule::IndentationContainsTabs);
let fix_unnecessary_coding_comment = let fix_unnecessary_coding_comment =
autofix.into() && settings.rules.should_fix(&Rule::UTF8EncodingDeclaration); autofix.into() && settings.rules.should_fix(Rule::UTF8EncodingDeclaration);
let fix_shebang_whitespace = let fix_shebang_whitespace =
autofix.into() && settings.rules.should_fix(&Rule::ShebangWhitespace); autofix.into() && settings.rules.should_fix(Rule::ShebangWhitespace);
let mut commented_lines_iter = commented_lines.iter().peekable(); let mut commented_lines_iter = commented_lines.iter().peekable();
let mut doc_lines_iter = doc_lines.iter().peekable(); let mut doc_lines_iter = doc_lines.iter().peekable();
@ -165,7 +165,7 @@ pub fn check_physical_lines(
if let Some(diagnostic) = no_newline_at_end_of_file( if let Some(diagnostic) = no_newline_at_end_of_file(
locator, locator,
stylist, stylist,
autofix.into() && settings.rules.should_fix(&Rule::NoNewLineAtEndOfFile), autofix.into() && settings.rules.should_fix(Rule::NoNewLineAtEndOfFile),
) { ) {
diagnostics.push(diagnostic); diagnostics.push(diagnostic);
} }

View file

@ -25,39 +25,39 @@ pub fn check_tokens(
let enforce_ambiguous_unicode_character = settings let enforce_ambiguous_unicode_character = settings
.rules .rules
.enabled(&Rule::AmbiguousUnicodeCharacterString) .enabled(Rule::AmbiguousUnicodeCharacterString)
|| settings || settings
.rules .rules
.enabled(&Rule::AmbiguousUnicodeCharacterDocstring) .enabled(Rule::AmbiguousUnicodeCharacterDocstring)
|| settings || settings
.rules .rules
.enabled(&Rule::AmbiguousUnicodeCharacterComment); .enabled(Rule::AmbiguousUnicodeCharacterComment);
let enforce_quotes = settings.rules.enabled(&Rule::BadQuotesInlineString) let enforce_quotes = settings.rules.enabled(Rule::BadQuotesInlineString)
|| settings.rules.enabled(&Rule::BadQuotesMultilineString) || settings.rules.enabled(Rule::BadQuotesMultilineString)
|| settings.rules.enabled(&Rule::BadQuotesDocstring) || settings.rules.enabled(Rule::BadQuotesDocstring)
|| settings.rules.enabled(&Rule::AvoidableEscapedQuote); || settings.rules.enabled(Rule::AvoidableEscapedQuote);
let enforce_commented_out_code = settings.rules.enabled(&Rule::CommentedOutCode); let enforce_commented_out_code = settings.rules.enabled(Rule::CommentedOutCode);
let enforce_compound_statements = settings let enforce_compound_statements = settings
.rules .rules
.enabled(&Rule::MultipleStatementsOnOneLineColon) .enabled(Rule::MultipleStatementsOnOneLineColon)
|| settings || settings
.rules .rules
.enabled(&Rule::MultipleStatementsOnOneLineSemicolon) .enabled(Rule::MultipleStatementsOnOneLineSemicolon)
|| settings.rules.enabled(&Rule::UselessSemicolon); || settings.rules.enabled(Rule::UselessSemicolon);
let enforce_invalid_escape_sequence = settings.rules.enabled(&Rule::InvalidEscapeSequence); let enforce_invalid_escape_sequence = settings.rules.enabled(Rule::InvalidEscapeSequence);
let enforce_implicit_string_concatenation = settings let enforce_implicit_string_concatenation = settings
.rules .rules
.enabled(&Rule::SingleLineImplicitStringConcatenation) .enabled(Rule::SingleLineImplicitStringConcatenation)
|| settings || settings
.rules .rules
.enabled(&Rule::MultiLineImplicitStringConcatenation); .enabled(Rule::MultiLineImplicitStringConcatenation);
let enforce_trailing_comma = settings.rules.enabled(&Rule::TrailingCommaMissing) let enforce_trailing_comma = settings.rules.enabled(Rule::TrailingCommaMissing)
|| settings || settings
.rules .rules
.enabled(&Rule::TrailingCommaOnBareTupleProhibited) .enabled(Rule::TrailingCommaOnBareTupleProhibited)
|| settings.rules.enabled(&Rule::TrailingCommaProhibited); || settings.rules.enabled(Rule::TrailingCommaProhibited);
let enforce_extraneous_parenthesis = settings.rules.enabled(&Rule::ExtraneousParentheses); let enforce_extraneous_parenthesis = settings.rules.enabled(Rule::ExtraneousParentheses);
let enforce_type_comment_in_stub = settings.rules.enabled(&Rule::TypeCommentInStub); let enforce_type_comment_in_stub = settings.rules.enabled(Rule::TypeCommentInStub);
// RUF001, RUF002, RUF003 // RUF001, RUF002, RUF003
if enforce_ambiguous_unicode_character { if enforce_ambiguous_unicode_character {
@ -111,7 +111,7 @@ pub fn check_tokens(
locator, locator,
*start, *start,
*end, *end,
autofix.into() && settings.rules.should_fix(&Rule::InvalidEscapeSequence), autofix.into() && settings.rules.should_fix(Rule::InvalidEscapeSequence),
)); ));
} }
} }

View file

@ -22,11 +22,12 @@ pub fn extract_path_names(path: &Path) -> Result<(&str, &str)> {
} }
/// Create a set with codes matching the pattern/code pairs. /// Create a set with codes matching the pattern/code pairs.
pub(crate) fn ignores_from_path<'a>( pub(crate) fn ignores_from_path(
path: &Path, path: &Path,
pattern_code_pairs: &'a [(GlobMatcher, GlobMatcher, FxHashSet<Rule>)], pattern_code_pairs: &[(GlobMatcher, GlobMatcher, FxHashSet<Rule>)],
) -> FxHashSet<&'a Rule> { ) -> FxHashSet<Rule> {
let (file_path, file_basename) = extract_path_names(path).expect("Unable to parse filename"); let (file_path, file_basename) = extract_path_names(path).expect("Unable to parse filename");
pattern_code_pairs pattern_code_pairs
.iter() .iter()
.filter_map(|(absolute, basename, codes)| { .filter_map(|(absolute, basename, codes)| {
@ -37,20 +38,21 @@ pub(crate) fn ignores_from_path<'a>(
basename.glob().regex(), basename.glob().regex(),
codes codes
); );
return Some(codes.iter()); Some(codes)
} } else if absolute.is_match(file_path) {
if absolute.is_match(file_path) {
debug!( debug!(
"Adding per-file ignores for {:?} due to absolute match on {:?}: {:?}", "Adding per-file ignores for {:?} due to absolute match on {:?}: {:?}",
path, path,
absolute.glob().regex(), absolute.glob().regex(),
codes codes
); );
return Some(codes.iter()); Some(codes)
} } else {
None None
}
}) })
.flatten() .flatten()
.copied()
.collect() .collect()
} }

View file

@ -50,7 +50,7 @@ impl<T> LinterResult<T> {
} }
} }
pub type FixTable = FxHashMap<&'static Rule, usize>; pub type FixTable = FxHashMap<Rule, usize>;
/// Generate `Diagnostic`s from the source code contents at the /// Generate `Diagnostic`s from the source code contents at the
/// given `Path`. /// given `Path`.
@ -74,7 +74,7 @@ pub fn check_path(
// Collect doc lines. This requires a rare mix of tokens (for comments) and AST // Collect doc lines. This requires a rare mix of tokens (for comments) and AST
// (for docstrings), which demands special-casing at this level. // (for docstrings), which demands special-casing at this level.
let use_doc_lines = settings.rules.enabled(&Rule::DocLineTooLong); let use_doc_lines = settings.rules.enabled(Rule::DocLineTooLong);
let mut doc_lines = vec![]; let mut doc_lines = vec![];
if use_doc_lines { if use_doc_lines {
doc_lines.extend(doc_lines_from_tokens(&tokens)); doc_lines.extend(doc_lines_from_tokens(&tokens));
@ -159,14 +159,14 @@ pub fn check_path(
} }
} }
Err(parse_error) => { Err(parse_error) => {
if settings.rules.enabled(&Rule::SyntaxError) { if settings.rules.enabled(Rule::SyntaxError) {
pycodestyle::rules::syntax_error(&mut diagnostics, &parse_error); pycodestyle::rules::syntax_error(&mut diagnostics, &parse_error);
} }
// If the syntax error is ignored, suppress it (regardless of whether // If the syntax error is ignored, suppress it (regardless of whether
// `Rule::SyntaxError` is enabled). // `Rule::SyntaxError` is enabled).
if !rule_is_ignored( if !rule_is_ignored(
&Rule::SyntaxError, Rule::SyntaxError,
parse_error.location.row(), parse_error.location.row(),
&directives.noqa_line_for, &directives.noqa_line_for,
locator, locator,
@ -204,7 +204,7 @@ pub fn check_path(
if !diagnostics.is_empty() && !settings.per_file_ignores.is_empty() { if !diagnostics.is_empty() && !settings.per_file_ignores.is_empty() {
let ignores = fs::ignores_from_path(path, &settings.per_file_ignores); let ignores = fs::ignores_from_path(path, &settings.per_file_ignores);
if !ignores.is_empty() { if !ignores.is_empty() {
diagnostics.retain(|diagnostic| !ignores.contains(diagnostic.kind.rule())); diagnostics.retain(|diagnostic| !ignores.contains(&diagnostic.kind.rule()));
} }
}; };

View file

@ -121,7 +121,7 @@ pub fn extract_noqa_directive(line: &str) -> Directive {
/// Returns `true` if the string list of `codes` includes `code` (or an alias /// Returns `true` if the string list of `codes` includes `code` (or an alias
/// thereof). /// thereof).
pub fn includes(needle: &Rule, haystack: &[&str]) -> bool { pub fn includes(needle: Rule, haystack: &[&str]) -> bool {
let needle = needle.noqa_code(); let needle = needle.noqa_code();
haystack haystack
.iter() .iter()
@ -130,7 +130,7 @@ pub fn includes(needle: &Rule, haystack: &[&str]) -> bool {
/// Returns `true` if the given [`Rule`] is ignored at the specified `lineno`. /// Returns `true` if the given [`Rule`] is ignored at the specified `lineno`.
pub fn rule_is_ignored( pub fn rule_is_ignored(
code: &Rule, code: Rule,
lineno: usize, lineno: usize,
noqa_line_for: &IntMap<usize, usize>, noqa_line_for: &IntMap<usize, usize>,
locator: &Locator, locator: &Locator,
@ -174,7 +174,7 @@ fn add_noqa_inner(
line_ending: &LineEnding, line_ending: &LineEnding,
) -> (usize, String) { ) -> (usize, String) {
// Map of line number to set of (non-ignored) diagnostic codes that are triggered on that line. // Map of line number to set of (non-ignored) diagnostic codes that are triggered on that line.
let mut matches_by_line: FxHashMap<usize, FxHashSet<&Rule>> = FxHashMap::default(); let mut matches_by_line: FxHashMap<usize, FxHashSet<Rule>> = FxHashMap::default();
// Whether the file is exempted from all checks. // Whether the file is exempted from all checks.
let mut file_exempted = false; let mut file_exempted = false;
@ -280,7 +280,7 @@ fn add_noqa_inner(
output.push_str(" # noqa: "); output.push_str(" # noqa: ");
// Add codes. // Add codes.
push_codes(&mut output, rules.iter().map(|r| r.noqa_code())); push_codes(&mut output, rules.iter().map(Rule::noqa_code));
output.push_str(line_ending); output.push_str(line_ending);
count += 1; count += 1;
} }

View file

@ -610,6 +610,10 @@ ruff_macros::register_rules!(
rules::flake8_django::rules::NonLeadingReceiverDecorator, rules::flake8_django::rules::NonLeadingReceiverDecorator,
); );
pub trait AsRule {
fn rule(&self) -> Rule;
}
impl Rule { impl Rule {
pub fn from_code(code: &str) -> Result<Self, FromCodeError> { pub fn from_code(code: &str) -> Result<Self, FromCodeError> {
let (linter, code) = Linter::parse_code(code).ok_or(FromCodeError::Unknown)?; let (linter, code) = Linter::parse_code(code).ok_or(FromCodeError::Unknown)?;
@ -916,6 +920,7 @@ pub const INCOMPATIBLE_CODES: &[(Rule, Rule, &str); 2] = &[
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::mem::size_of;
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
use super::{Linter, Rule, RuleNamespace}; use super::{Linter, Rule, RuleNamespace};
@ -961,4 +966,9 @@ mod tests {
assert_eq!(code, format!("{}{rest}", linter.common_prefix())); assert_eq!(code, format!("{}{rest}", linter.common_prefix()));
} }
} }
#[test]
fn rule_size() {
assert_eq!(2, size_of::<Rule>());
}
} }

View file

@ -61,7 +61,7 @@ pub fn commented_out_code(
// Verify that the comment is on its own line, and that it contains code. // Verify that the comment is on its own line, and that it contains code.
if is_standalone_comment(line) && comment_contains_code(line, &settings.task_tags[..]) { if is_standalone_comment(line) && comment_contains_code(line, &settings.task_tags[..]) {
let mut diagnostic = Diagnostic::new(CommentedOutCode, Range::new(start, end)); let mut diagnostic = Diagnostic::new(CommentedOutCode, Range::new(start, end));
if autofix.into() && settings.rules.should_fix(&Rule::CommentedOutCode) { if autofix.into() && settings.rules.should_fix(Rule::CommentedOutCode) {
diagnostic.amend(Fix::deletion(location, end_location)); diagnostic.amend(Fix::deletion(location, end_location));
} }
Some(diagnostic) Some(diagnostic)

View file

@ -140,7 +140,7 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
&& checker && checker
.settings .settings
.rules .rules
.enabled(&Rule::SysVersionSlice1Referenced) .enabled(Rule::SysVersionSlice1Referenced)
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
SysVersionSlice1Referenced, SysVersionSlice1Referenced,
@ -150,7 +150,7 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
&& checker && checker
.settings .settings
.rules .rules
.enabled(&Rule::SysVersionSlice3Referenced) .enabled(Rule::SysVersionSlice3Referenced)
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
SysVersionSlice3Referenced, SysVersionSlice3Referenced,
@ -165,13 +165,13 @@ pub fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
.. ..
} => { } => {
if *i == BigInt::from(2) if *i == BigInt::from(2)
&& checker.settings.rules.enabled(&Rule::SysVersion2Referenced) && checker.settings.rules.enabled(Rule::SysVersion2Referenced)
{ {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(SysVersion2Referenced, Range::from(value))); .push(Diagnostic::new(SysVersion2Referenced, Range::from(value)));
} else if *i == BigInt::from(0) } else if *i == BigInt::from(0)
&& checker.settings.rules.enabled(&Rule::SysVersion0Referenced) && checker.settings.rules.enabled(Rule::SysVersion0Referenced)
{ {
checker checker
.diagnostics .diagnostics
@ -210,7 +210,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
&& checker && checker
.settings .settings
.rules .rules
.enabled(&Rule::SysVersionInfo0Eq3Referenced) .enabled(Rule::SysVersionInfo0Eq3Referenced)
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
SysVersionInfo0Eq3Referenced, SysVersionInfo0Eq3Referenced,
@ -231,7 +231,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
}], }],
) = (ops, comparators) ) = (ops, comparators)
{ {
if checker.settings.rules.enabled(&Rule::SysVersionInfo1CmpInt) { if checker.settings.rules.enabled(Rule::SysVersionInfo1CmpInt) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(SysVersionInfo1CmpInt, Range::from(left))); .push(Diagnostic::new(SysVersionInfo1CmpInt, Range::from(left)));
@ -259,7 +259,7 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::SysVersionInfoMinorCmpInt) .enabled(Rule::SysVersionInfoMinorCmpInt)
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
SysVersionInfoMinorCmpInt, SysVersionInfoMinorCmpInt,
@ -286,12 +286,12 @@ pub fn compare(checker: &mut Checker, left: &Expr, ops: &[Cmpop], comparators: &
) = (ops, comparators) ) = (ops, comparators)
{ {
if s.len() == 1 { if s.len() == 1 {
if checker.settings.rules.enabled(&Rule::SysVersionCmpStr10) { if checker.settings.rules.enabled(Rule::SysVersionCmpStr10) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(SysVersionCmpStr10, Range::from(left))); .push(Diagnostic::new(SysVersionCmpStr10, Range::from(left)));
} }
} else if checker.settings.rules.enabled(&Rule::SysVersionCmpStr3) { } else if checker.settings.rules.enabled(Rule::SysVersionCmpStr3) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(SysVersionCmpStr3, Range::from(left))); .push(Diagnostic::new(SysVersionCmpStr3, Range::from(left)));

View file

@ -492,7 +492,7 @@ pub fn definition(
// ANN401 for dynamically typed arguments // ANN401 for dynamically typed arguments
if let Some(annotation) = &arg.node.annotation { if let Some(annotation) = &arg.node.annotation {
has_any_typed_arg = true; has_any_typed_arg = true;
if checker.settings.rules.enabled(&Rule::AnyType) { if checker.settings.rules.enabled(Rule::AnyType) {
check_dynamically_typed( check_dynamically_typed(
checker, checker,
annotation, annotation,
@ -507,7 +507,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingTypeFunctionArgument) .enabled(Rule::MissingTypeFunctionArgument)
{ {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingTypeFunctionArgument { MissingTypeFunctionArgument {
@ -525,7 +525,7 @@ pub fn definition(
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
has_any_typed_arg = true; has_any_typed_arg = true;
if !checker.settings.flake8_annotations.allow_star_arg_any { if !checker.settings.flake8_annotations.allow_star_arg_any {
if checker.settings.rules.enabled(&Rule::AnyType) { if checker.settings.rules.enabled(Rule::AnyType) {
let name = &arg.node.arg; let name = &arg.node.arg;
check_dynamically_typed( check_dynamically_typed(
checker, checker,
@ -539,7 +539,7 @@ pub fn definition(
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.rules.enabled(&Rule::MissingTypeArgs) { if checker.settings.rules.enabled(Rule::MissingTypeArgs) {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingTypeArgs { MissingTypeArgs {
name: arg.node.arg.to_string(), name: arg.node.arg.to_string(),
@ -556,7 +556,7 @@ pub fn definition(
if let Some(expr) = &arg.node.annotation { if let Some(expr) = &arg.node.annotation {
has_any_typed_arg = true; has_any_typed_arg = true;
if !checker.settings.flake8_annotations.allow_star_arg_any { if !checker.settings.flake8_annotations.allow_star_arg_any {
if checker.settings.rules.enabled(&Rule::AnyType) { if checker.settings.rules.enabled(Rule::AnyType) {
let name = &arg.node.arg; let name = &arg.node.arg;
check_dynamically_typed( check_dynamically_typed(
checker, checker,
@ -570,7 +570,7 @@ pub fn definition(
if !(checker.settings.flake8_annotations.suppress_dummy_args if !(checker.settings.flake8_annotations.suppress_dummy_args
&& checker.settings.dummy_variable_rgx.is_match(&arg.node.arg)) && checker.settings.dummy_variable_rgx.is_match(&arg.node.arg))
{ {
if checker.settings.rules.enabled(&Rule::MissingTypeKwargs) { if checker.settings.rules.enabled(Rule::MissingTypeKwargs) {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingTypeKwargs { MissingTypeKwargs {
name: arg.node.arg.to_string(), name: arg.node.arg.to_string(),
@ -587,7 +587,7 @@ pub fn definition(
if let Some(arg) = args.posonlyargs.first().or_else(|| args.args.first()) { if let Some(arg) = args.posonlyargs.first().or_else(|| args.args.first()) {
if arg.node.annotation.is_none() { if arg.node.annotation.is_none() {
if visibility::is_classmethod(&checker.ctx, cast::decorator_list(stmt)) { if visibility::is_classmethod(&checker.ctx, cast::decorator_list(stmt)) {
if checker.settings.rules.enabled(&Rule::MissingTypeCls) { if checker.settings.rules.enabled(Rule::MissingTypeCls) {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingTypeCls { MissingTypeCls {
name: arg.node.arg.to_string(), name: arg.node.arg.to_string(),
@ -596,7 +596,7 @@ pub fn definition(
)); ));
} }
} else { } else {
if checker.settings.rules.enabled(&Rule::MissingTypeSelf) { if checker.settings.rules.enabled(Rule::MissingTypeSelf) {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingTypeSelf { MissingTypeSelf {
name: arg.node.arg.to_string(), name: arg.node.arg.to_string(),
@ -614,7 +614,7 @@ pub fn definition(
// ANN201, ANN202, ANN401 // ANN201, ANN202, ANN401
if let Some(expr) = &returns { if let Some(expr) = &returns {
has_typed_return = true; has_typed_return = true;
if checker.settings.rules.enabled(&Rule::AnyType) { if checker.settings.rules.enabled(Rule::AnyType) {
check_dynamically_typed(checker, expr, || name.to_string(), &mut diagnostics); check_dynamically_typed(checker, expr, || name.to_string(), &mut diagnostics);
} }
} else if !( } else if !(
@ -626,7 +626,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingReturnTypeClassMethod) .enabled(Rule::MissingReturnTypeClassMethod)
{ {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingReturnTypeClassMethod { MissingReturnTypeClassMethod {
@ -641,7 +641,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingReturnTypeStaticMethod) .enabled(Rule::MissingReturnTypeStaticMethod)
{ {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingReturnTypeStaticMethod { MissingReturnTypeStaticMethod {
@ -656,7 +656,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingReturnTypeSpecialMethod) .enabled(Rule::MissingReturnTypeSpecialMethod)
{ {
if !(checker.settings.flake8_annotations.mypy_init_return && has_any_typed_arg) if !(checker.settings.flake8_annotations.mypy_init_return && has_any_typed_arg)
{ {
@ -681,7 +681,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingReturnTypeSpecialMethod) .enabled(Rule::MissingReturnTypeSpecialMethod)
{ {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingReturnTypeSpecialMethod { MissingReturnTypeSpecialMethod {
@ -696,7 +696,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingReturnTypePublicFunction) .enabled(Rule::MissingReturnTypePublicFunction)
{ {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingReturnTypePublicFunction { MissingReturnTypePublicFunction {
@ -710,7 +710,7 @@ pub fn definition(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingReturnTypePrivateFunction) .enabled(Rule::MissingReturnTypePrivateFunction)
{ {
diagnostics.push(Diagnostic::new( diagnostics.push(Diagnostic::new(
MissingReturnTypePrivateFunction { MissingReturnTypePrivateFunction {

View file

@ -115,7 +115,7 @@ pub fn abstract_base_class(
if !checker if !checker
.settings .settings
.rules .rules
.enabled(&Rule::EmptyMethodWithoutAbstractDecorator) .enabled(Rule::EmptyMethodWithoutAbstractDecorator)
{ {
continue; continue;
} }
@ -135,7 +135,7 @@ pub fn abstract_base_class(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::AbstractBaseClassWithoutAbstractMethod) .enabled(Rule::AbstractBaseClassWithoutAbstractMethod)
{ {
if !has_abstract_method { if !has_abstract_method {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(

View file

@ -83,7 +83,7 @@ fn duplicate_handler_exceptions<'a>(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::DuplicateHandlerException) .enabled(Rule::DuplicateHandlerException)
{ {
// TODO(charlie): Handle "BaseException" and redundant exception aliases. // TODO(charlie): Handle "BaseException" and redundant exception aliases.
if !duplicates.is_empty() { if !duplicates.is_empty() {
@ -149,7 +149,7 @@ pub fn duplicate_exceptions(checker: &mut Checker, handlers: &[Excepthandler]) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::DuplicateTryBlockException) .enabled(Rule::DuplicateTryBlockException)
{ {
for (name, exprs) in duplicates { for (name, exprs) in duplicates {
for expr in exprs { for expr in exprs {

View file

@ -260,7 +260,7 @@ pub fn trailing_commas(
end_location: comma.2, end_location: comma.2,
}, },
); );
if autofix.into() && settings.rules.should_fix(&Rule::TrailingCommaProhibited) { if autofix.into() && settings.rules.should_fix(Rule::TrailingCommaProhibited) {
diagnostic.amend(Fix::deletion(comma.0, comma.2)); diagnostic.amend(Fix::deletion(comma.0, comma.2));
} }
diagnostics.push(diagnostic); diagnostics.push(diagnostic);
@ -304,7 +304,7 @@ pub fn trailing_commas(
end_location: missing_comma.2, end_location: missing_comma.2,
}, },
); );
if autofix.into() && settings.rules.should_fix(&Rule::TrailingCommaMissing) { if autofix.into() && settings.rules.should_fix(Rule::TrailingCommaMissing) {
// Create a replacement that includes the final bracket (or other token), // Create a replacement that includes the final bracket (or other token),
// rather than just inserting a comma at the end. This prevents the UP034 autofix // rather than just inserting a comma at the end. This prevents the UP034 autofix
// removing any brackets in the same linter pass - doing both at the same time could // removing any brackets in the same linter pass - doing both at the same time could

View file

@ -162,7 +162,7 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) {
value: Constant::Str(string), value: Constant::Str(string),
.. ..
} => { } => {
if checker.settings.rules.enabled(&Rule::RawStringInException) { if checker.settings.rules.enabled(Rule::RawStringInException) {
if string.len() > checker.settings.flake8_errmsg.max_string_length { if string.len() > checker.settings.flake8_errmsg.max_string_length {
checker checker
.diagnostics .diagnostics
@ -172,7 +172,7 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) {
} }
// Check for f-strings // Check for f-strings
ExprKind::JoinedStr { .. } => { ExprKind::JoinedStr { .. } => {
if checker.settings.rules.enabled(&Rule::FStringInException) { if checker.settings.rules.enabled(Rule::FStringInException) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(FStringInException, Range::from(first))); .push(Diagnostic::new(FStringInException, Range::from(first)));
@ -180,7 +180,7 @@ pub fn string_in_exception(checker: &mut Checker, exc: &Expr) {
} }
// Check for .format() calls // Check for .format() calls
ExprKind::Call { func, .. } => { ExprKind::Call { func, .. } => {
if checker.settings.rules.enabled(&Rule::DotFormatInException) { if checker.settings.rules.enabled(Rule::DotFormatInException) {
if let ExprKind::Attribute { value, attr, .. } = &func.node { if let ExprKind::Attribute { value, attr, .. } = &func.node {
if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) { if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(

View file

@ -43,14 +43,14 @@ fn check_msg(checker: &mut Checker, msg: &Expr) {
// Check for string concatenation and percent format. // Check for string concatenation and percent format.
ExprKind::BinOp { op, .. } => match op { ExprKind::BinOp { op, .. } => match op {
Operator::Add => { Operator::Add => {
if checker.settings.rules.enabled(&Rule::LoggingStringConcat) { if checker.settings.rules.enabled(Rule::LoggingStringConcat) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(LoggingStringConcat, Range::from(msg))); .push(Diagnostic::new(LoggingStringConcat, Range::from(msg)));
} }
} }
Operator::Mod => { Operator::Mod => {
if checker.settings.rules.enabled(&Rule::LoggingPercentFormat) { if checker.settings.rules.enabled(Rule::LoggingPercentFormat) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(LoggingPercentFormat, Range::from(msg))); .push(Diagnostic::new(LoggingPercentFormat, Range::from(msg)));
@ -60,7 +60,7 @@ fn check_msg(checker: &mut Checker, msg: &Expr) {
}, },
// Check for f-strings. // Check for f-strings.
ExprKind::JoinedStr { .. } => { ExprKind::JoinedStr { .. } => {
if checker.settings.rules.enabled(&Rule::LoggingFString) { if checker.settings.rules.enabled(Rule::LoggingFString) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(LoggingFString, Range::from(msg))); .push(Diagnostic::new(LoggingFString, Range::from(msg)));
@ -68,7 +68,7 @@ fn check_msg(checker: &mut Checker, msg: &Expr) {
} }
// Check for .format() calls. // Check for .format() calls.
ExprKind::Call { func, .. } => { ExprKind::Call { func, .. } => {
if checker.settings.rules.enabled(&Rule::LoggingStringFormat) { if checker.settings.rules.enabled(Rule::LoggingStringFormat) {
if let ExprKind::Attribute { value, attr, .. } = &func.node { if let ExprKind::Attribute { value, attr, .. } = &func.node {
if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) { if attr == "format" && matches!(value.node, ExprKind::Constant { .. }) {
checker checker
@ -151,7 +151,7 @@ pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
} }
// G010 // G010
if checker.settings.rules.enabled(&Rule::LoggingWarn) if checker.settings.rules.enabled(Rule::LoggingWarn)
&& matches!(logging_level, LoggingLevel::Warn) && matches!(logging_level, LoggingLevel::Warn)
{ {
let mut diagnostic = Diagnostic::new(LoggingWarn, level_call_range); let mut diagnostic = Diagnostic::new(LoggingWarn, level_call_range);
@ -166,18 +166,18 @@ pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
} }
// G101 // G101
if checker.settings.rules.enabled(&Rule::LoggingExtraAttrClash) { if checker.settings.rules.enabled(Rule::LoggingExtraAttrClash) {
if let Some(extra) = find_keyword(keywords, "extra") { if let Some(extra) = find_keyword(keywords, "extra") {
check_log_record_attr_clash(checker, extra); check_log_record_attr_clash(checker, extra);
} }
} }
// G201, G202 // G201, G202
if checker.settings.rules.enabled(&Rule::LoggingExcInfo) if checker.settings.rules.enabled(Rule::LoggingExcInfo)
|| checker || checker
.settings .settings
.rules .rules
.enabled(&Rule::LoggingRedundantExcInfo) .enabled(Rule::LoggingRedundantExcInfo)
{ {
if !checker.ctx.in_exception_handler() { if !checker.ctx.in_exception_handler() {
return; return;
@ -206,7 +206,7 @@ pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
match logging_level { match logging_level {
LoggingLevel::Error => { LoggingLevel::Error => {
if checker.settings.rules.enabled(&Rule::LoggingExcInfo) { if checker.settings.rules.enabled(Rule::LoggingExcInfo) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(LoggingExcInfo, level_call_range)); .push(Diagnostic::new(LoggingExcInfo, level_call_range));
@ -216,7 +216,7 @@ pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::LoggingRedundantExcInfo) .enabled(Rule::LoggingRedundantExcInfo)
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
LoggingRedundantExcInfo, LoggingRedundantExcInfo,

View file

@ -118,7 +118,7 @@ pub fn unrecognized_platform(
&& checker && checker
.settings .settings
.rules .rules
.enabled(&Rule::UnrecognizedPlatformCheck) .enabled(Rule::UnrecognizedPlatformCheck)
{ {
checker checker
.diagnostics .diagnostics
@ -137,7 +137,7 @@ pub fn unrecognized_platform(
&& checker && checker
.settings .settings
.rules .rules
.enabled(&Rule::UnrecognizedPlatformName) .enabled(Rule::UnrecognizedPlatformName)
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
UnrecognizedPlatformName { UnrecognizedPlatformName {
@ -151,7 +151,7 @@ pub fn unrecognized_platform(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::UnrecognizedPlatformCheck) .enabled(Rule::UnrecognizedPlatformCheck)
{ {
checker checker
.diagnostics .diagnostics

View file

@ -277,7 +277,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::IncorrectFixtureParenthesesStyle) .enabled(Rule::IncorrectFixtureParenthesesStyle)
&& !checker.settings.flake8_pytest_style.fixture_parentheses && !checker.settings.flake8_pytest_style.fixture_parentheses
&& args.is_empty() && args.is_empty()
&& keywords.is_empty() && keywords.is_empty()
@ -287,7 +287,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
pytest_fixture_parentheses(checker, decorator, fix, "", "()"); pytest_fixture_parentheses(checker, decorator, fix, "", "()");
} }
if checker.settings.rules.enabled(&Rule::FixturePositionalArgs) && !args.is_empty() { if checker.settings.rules.enabled(Rule::FixturePositionalArgs) && !args.is_empty() {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
FixturePositionalArgs { FixturePositionalArgs {
function: func_name.to_string(), function: func_name.to_string(),
@ -299,7 +299,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::ExtraneousScopeFunction) .enabled(Rule::ExtraneousScopeFunction)
{ {
let scope_keyword = keywords let scope_keyword = keywords
.iter() .iter()
@ -333,7 +333,7 @@ fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &E
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::IncorrectFixtureParenthesesStyle) .enabled(Rule::IncorrectFixtureParenthesesStyle)
&& checker.settings.flake8_pytest_style.fixture_parentheses && checker.settings.flake8_pytest_style.fixture_parentheses
{ {
let fix = Fix::insertion("()".to_string(), decorator.end_location.unwrap()); let fix = Fix::insertion("()".to_string(), decorator.end_location.unwrap());
@ -354,7 +354,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::IncorrectFixtureNameUnderscore) .enabled(Rule::IncorrectFixtureNameUnderscore)
&& visitor.has_return_with_value && visitor.has_return_with_value
&& func_name.starts_with('_') && func_name.starts_with('_')
{ {
@ -367,7 +367,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
} else if checker } else if checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingFixtureNameUnderscore) .enabled(Rule::MissingFixtureNameUnderscore)
&& !visitor.has_return_with_value && !visitor.has_return_with_value
&& !visitor.has_yield_from && !visitor.has_yield_from
&& !func_name.starts_with('_') && !func_name.starts_with('_')
@ -380,7 +380,7 @@ fn check_fixture_returns(checker: &mut Checker, func: &Stmt, func_name: &str, bo
)); ));
} }
if checker.settings.rules.enabled(&Rule::UselessYieldFixture) { if checker.settings.rules.enabled(Rule::UselessYieldFixture) {
if let Some(stmt) = body.last() { if let Some(stmt) = body.last() {
if let StmtKind::Expr { value, .. } = &stmt.node { if let StmtKind::Expr { value, .. } = &stmt.node {
if let ExprKind::Yield { .. } = value.node { if let ExprKind::Yield { .. } = value.node {
@ -462,7 +462,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::UnnecessaryAsyncioMarkOnFixture) .enabled(Rule::UnnecessaryAsyncioMarkOnFixture)
{ {
if name == "asyncio" { if name == "asyncio" {
let mut diagnostic = let mut diagnostic =
@ -479,7 +479,7 @@ fn check_fixture_marks(checker: &mut Checker, decorators: &[Expr]) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::ErroneousUseFixturesOnFixture) .enabled(Rule::ErroneousUseFixturesOnFixture)
{ {
if name == "usefixtures" { if name == "usefixtures" {
let mut diagnostic = let mut diagnostic =
@ -508,20 +508,17 @@ pub fn fixture(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::IncorrectFixtureParenthesesStyle) .enabled(Rule::IncorrectFixtureParenthesesStyle)
|| checker.settings.rules.enabled(&Rule::FixturePositionalArgs) || checker.settings.rules.enabled(Rule::FixturePositionalArgs)
|| checker || checker
.settings .settings
.rules .rules
.enabled(&Rule::ExtraneousScopeFunction) .enabled(Rule::ExtraneousScopeFunction)
{ {
check_fixture_decorator(checker, func_name, decorator); check_fixture_decorator(checker, func_name, decorator);
} }
if checker if checker.settings.rules.enabled(Rule::DeprecatedYieldFixture)
.settings
.rules
.enabled(&Rule::DeprecatedYieldFixture)
&& checker.settings.flake8_pytest_style.fixture_parentheses && checker.settings.flake8_pytest_style.fixture_parentheses
{ {
check_fixture_decorator_name(checker, decorator); check_fixture_decorator_name(checker, decorator);
@ -530,12 +527,12 @@ pub fn fixture(
if (checker if (checker
.settings .settings
.rules .rules
.enabled(&Rule::MissingFixtureNameUnderscore) .enabled(Rule::MissingFixtureNameUnderscore)
|| checker || checker
.settings .settings
.rules .rules
.enabled(&Rule::IncorrectFixtureNameUnderscore) .enabled(Rule::IncorrectFixtureNameUnderscore)
|| checker.settings.rules.enabled(&Rule::UselessYieldFixture)) || checker.settings.rules.enabled(Rule::UselessYieldFixture))
&& !has_abstractmethod_decorator(decorators, checker) && !has_abstractmethod_decorator(decorators, checker)
{ {
check_fixture_returns(checker, func, func_name, body); check_fixture_returns(checker, func, func_name, body);
@ -544,7 +541,7 @@ pub fn fixture(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::FixtureFinalizerCallback) .enabled(Rule::FixtureFinalizerCallback)
{ {
check_fixture_addfinalizer(checker, args, body); check_fixture_addfinalizer(checker, args, body);
} }
@ -552,11 +549,11 @@ pub fn fixture(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::UnnecessaryAsyncioMarkOnFixture) .enabled(Rule::UnnecessaryAsyncioMarkOnFixture)
|| checker || checker
.settings .settings
.rules .rules
.enabled(&Rule::ErroneousUseFixturesOnFixture) .enabled(Rule::ErroneousUseFixturesOnFixture)
{ {
check_fixture_marks(checker, decorators); check_fixture_marks(checker, decorators);
} }
@ -565,7 +562,7 @@ pub fn fixture(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::FixtureParamWithoutValue) .enabled(Rule::FixtureParamWithoutValue)
&& func_name.starts_with("test_") && func_name.starts_with("test_")
{ {
check_test_function_args(checker, args); check_test_function_args(checker, args);

View file

@ -123,11 +123,11 @@ pub fn marks(checker: &mut Checker, decorators: &[Expr]) {
let enforce_parentheses = checker let enforce_parentheses = checker
.settings .settings
.rules .rules
.enabled(&Rule::IncorrectMarkParenthesesStyle); .enabled(Rule::IncorrectMarkParenthesesStyle);
let enforce_useless_usefixtures = checker let enforce_useless_usefixtures = checker
.settings .settings
.rules .rules
.enabled(&Rule::UseFixturesWithoutParameters); .enabled(Rule::UseFixturesWithoutParameters);
for mark in get_mark_decorators(decorators) { for mark in get_mark_decorators(decorators) {
if enforce_parentheses { if enforce_parentheses {

View file

@ -380,7 +380,7 @@ pub fn parametrize(checker: &mut Checker, decorators: &[Expr]) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::ParametrizeNamesWrongType) .enabled(Rule::ParametrizeNamesWrongType)
{ {
if let Some(names) = args.get(0) { if let Some(names) = args.get(0) {
check_names(checker, names); check_names(checker, names);
@ -389,7 +389,7 @@ pub fn parametrize(checker: &mut Checker, decorators: &[Expr]) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::ParametrizeValuesWrongType) .enabled(Rule::ParametrizeValuesWrongType)
{ {
if let Some(names) = args.get(0) { if let Some(names) = args.get(0) {
if let Some(values) = args.get(1) { if let Some(values) = args.get(1) {

View file

@ -67,11 +67,7 @@ const fn is_non_trivial_with_body(body: &[Stmt]) -> bool {
pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) { pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords: &[Keyword]) {
if is_pytest_raises(checker, func) { if is_pytest_raises(checker, func) {
if checker if checker.settings.rules.enabled(Rule::RaisesWithoutException) {
.settings
.rules
.enabled(&Rule::RaisesWithoutException)
{
if args.is_empty() && keywords.is_empty() { if args.is_empty() && keywords.is_empty() {
checker checker
.diagnostics .diagnostics
@ -79,7 +75,7 @@ pub fn raises_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
} }
} }
if checker.settings.rules.enabled(&Rule::RaisesTooBroad) { if checker.settings.rules.enabled(Rule::RaisesTooBroad) {
let match_keyword = keywords let match_keyword = keywords
.iter() .iter()
.find(|kw| kw.node.arg == Some("match".to_string())); .find(|kw| kw.node.arg == Some("match".to_string()));

View file

@ -281,7 +281,7 @@ fn docstring(
}, },
Range::new(start, end), Range::new(start, end),
); );
if autofix.into() && settings.rules.should_fix(&Rule::BadQuotesDocstring) { if autofix.into() && settings.rules.should_fix(Rule::BadQuotesDocstring) {
let quote_count = if trivia.is_multiline { 3 } else { 1 }; let quote_count = if trivia.is_multiline { 3 } else { 1 };
let string_contents = &trivia.raw_text[quote_count..trivia.raw_text.len() - quote_count]; let string_contents = &trivia.raw_text[quote_count..trivia.raw_text.len() - quote_count];
let quote = good_docstring(&quotes_settings.docstring_quotes).repeat(quote_count); let quote = good_docstring(&quotes_settings.docstring_quotes).repeat(quote_count);
@ -356,7 +356,7 @@ fn strings(
Range::new(*start, *end), Range::new(*start, *end),
); );
if autofix.into() && settings.rules.should_fix(&Rule::BadQuotesMultilineString) { if autofix.into() && settings.rules.should_fix(Rule::BadQuotesMultilineString) {
let string_contents = &trivia.raw_text[3..trivia.raw_text.len() - 3]; let string_contents = &trivia.raw_text[3..trivia.raw_text.len() - 3];
let quote = good_multiline(&quotes_settings.multiline_quotes); let quote = good_multiline(&quotes_settings.multiline_quotes);
let mut fixed_contents = String::with_capacity( let mut fixed_contents = String::with_capacity(
@ -386,7 +386,7 @@ fn strings(
{ {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(AvoidableEscapedQuote, Range::new(*start, *end)); Diagnostic::new(AvoidableEscapedQuote, Range::new(*start, *end));
if autofix.into() && settings.rules.should_fix(&Rule::AvoidableEscapedQuote) { if autofix.into() && settings.rules.should_fix(Rule::AvoidableEscapedQuote) {
let quote = bad_single(&quotes_settings.inline_quotes); let quote = bad_single(&quotes_settings.inline_quotes);
let mut fixed_contents = let mut fixed_contents =
@ -445,7 +445,7 @@ fn strings(
}, },
Range::new(*start, *end), Range::new(*start, *end),
); );
if autofix.into() && settings.rules.should_fix(&Rule::BadQuotesInlineString) { if autofix.into() && settings.rules.should_fix(Rule::BadQuotesInlineString) {
let quote = good_single(&quotes_settings.inline_quotes); let quote = good_single(&quotes_settings.inline_quotes);
let mut fixed_contents = let mut fixed_contents =
String::with_capacity(trivia.prefix.len() + string_contents.len() + 2); String::with_capacity(trivia.prefix.len() + string_contents.len() + 2);

View file

@ -514,13 +514,13 @@ pub fn function(checker: &mut Checker, body: &[Stmt]) {
return; return;
} }
if checker.settings.rules.enabled(&Rule::SuperfluousElseReturn) if checker.settings.rules.enabled(Rule::SuperfluousElseReturn)
|| checker.settings.rules.enabled(&Rule::SuperfluousElseRaise) || checker.settings.rules.enabled(Rule::SuperfluousElseRaise)
|| checker || checker
.settings .settings
.rules .rules
.enabled(&Rule::SuperfluousElseContinue) .enabled(Rule::SuperfluousElseContinue)
|| checker.settings.rules.enabled(&Rule::SuperfluousElseBreak) || checker.settings.rules.enabled(Rule::SuperfluousElseBreak)
{ {
if superfluous_elif(checker, &stack) { if superfluous_elif(checker, &stack) {
return; return;
@ -536,20 +536,20 @@ pub fn function(checker: &mut Checker, body: &[Stmt]) {
} }
if !result_exists(&stack.returns) { if !result_exists(&stack.returns) {
if checker.settings.rules.enabled(&Rule::UnnecessaryReturnNone) { if checker.settings.rules.enabled(Rule::UnnecessaryReturnNone) {
unnecessary_return_none(checker, &stack); unnecessary_return_none(checker, &stack);
} }
return; return;
} }
if checker.settings.rules.enabled(&Rule::ImplicitReturnValue) { if checker.settings.rules.enabled(Rule::ImplicitReturnValue) {
implicit_return_value(checker, &stack); implicit_return_value(checker, &stack);
} }
if checker.settings.rules.enabled(&Rule::ImplicitReturn) { if checker.settings.rules.enabled(Rule::ImplicitReturn) {
implicit_return(checker, last_stmt); implicit_return(checker, last_stmt);
} }
if checker.settings.rules.enabled(&Rule::UnnecessaryAssign) { if checker.settings.rules.enabled(Rule::UnnecessaryAssign) {
for (_, expr) in &stack.returns { for (_, expr) in &stack.returns {
if let Some(expr) = expr { if let Some(expr) = expr {
unnecessary_assign(checker, &stack, expr); unnecessary_assign(checker, &stack, expr);

View file

@ -201,7 +201,7 @@ pub fn convert_for_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling:
.or_else(|| sibling.and_then(|sibling| return_values_for_siblings(stmt, sibling))) .or_else(|| sibling.and_then(|sibling| return_values_for_siblings(stmt, sibling)))
{ {
if loop_info.return_value && !loop_info.next_return_value { if loop_info.return_value && !loop_info.next_return_value {
if checker.settings.rules.enabled(&Rule::ReimplementedBuiltin) { if checker.settings.rules.enabled(Rule::ReimplementedBuiltin) {
let contents = return_stmt( let contents = return_stmt(
"any", "any",
loop_info.test, loop_info.test,
@ -233,7 +233,7 @@ pub fn convert_for_loop_to_any_all(checker: &mut Checker, stmt: &Stmt, sibling:
} }
if !loop_info.return_value && loop_info.next_return_value { if !loop_info.return_value && loop_info.next_return_value {
if checker.settings.rules.enabled(&Rule::ReimplementedBuiltin) { if checker.settings.rules.enabled(Rule::ReimplementedBuiltin) {
// Invert the condition. // Invert the condition.
let test = { let test = {
if let ExprKind::UnaryOp { if let ExprKind::UnaryOp {

View file

@ -24,13 +24,13 @@ impl Argumentable {
} }
} }
pub const fn rule_code(&self) -> &Rule { pub const fn rule_code(&self) -> Rule {
match self { match self {
Self::Function => &Rule::UnusedFunctionArgument, Self::Function => Rule::UnusedFunctionArgument,
Self::Method => &Rule::UnusedMethodArgument, Self::Method => Rule::UnusedMethodArgument,
Self::ClassMethod => &Rule::UnusedClassMethodArgument, Self::ClassMethod => Rule::UnusedClassMethodArgument,
Self::StaticMethod => &Rule::UnusedStaticMethodArgument, Self::StaticMethod => Rule::UnusedStaticMethodArgument,
Self::Lambda => &Rule::UnusedLambdaArgument, Self::Lambda => Rule::UnusedLambdaArgument,
} }
} }
} }

View file

@ -168,7 +168,7 @@ fn add_required_import(
MissingRequiredImport(required_import.clone()), MissingRequiredImport(required_import.clone()),
Range::new(Location::default(), Location::default()), Range::new(Location::default(), Location::default()),
); );
if autofix.into() && settings.rules.should_fix(&Rule::MissingRequiredImport) { if autofix.into() && settings.rules.should_fix(Rule::MissingRequiredImport) {
// Determine the location at which the import should be inserted. // Determine the location at which the import should be inserted.
let splice = helpers::find_splice_location(python_ast, locator); let splice = helpers::find_splice_location(python_ast, locator);

View file

@ -47,7 +47,7 @@ mod tests {
); );
let actual: Vec<Rule> = diagnostics let actual: Vec<Rule> = diagnostics
.into_iter() .into_iter()
.map(|diagnostic| diagnostic.kind.rule().clone()) .map(|diagnostic| diagnostic.kind.rule())
.collect(); .collect();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }

View file

@ -52,10 +52,10 @@ impl Violation for UseOfDotValues {
pub fn check_attr(checker: &mut Checker, attr: &str, value: &Expr, attr_expr: &Expr) { pub fn check_attr(checker: &mut Checker, attr: &str, value: &Expr, attr_expr: &Expr) {
let rules = &checker.settings.rules; let rules = &checker.settings.rules;
let violation: DiagnosticKind = match attr { let violation: DiagnosticKind = match attr {
"ix" if rules.enabled(&Rule::UseOfDotIx) => UseOfDotIx.into(), "ix" if rules.enabled(Rule::UseOfDotIx) => UseOfDotIx.into(),
"at" if rules.enabled(&Rule::UseOfDotAt) => UseOfDotAt.into(), "at" if rules.enabled(Rule::UseOfDotAt) => UseOfDotAt.into(),
"iat" if rules.enabled(&Rule::UseOfDotIat) => UseOfDotIat.into(), "iat" if rules.enabled(Rule::UseOfDotIat) => UseOfDotIat.into(),
"values" if rules.enabled(&Rule::UseOfDotValues) => UseOfDotValues.into(), "values" if rules.enabled(Rule::UseOfDotValues) => UseOfDotValues.into(),
_ => return, _ => return,
}; };

View file

@ -65,13 +65,13 @@ pub fn check_call(checker: &mut Checker, func: &Expr) {
let rules = &checker.settings.rules; let rules = &checker.settings.rules;
let ExprKind::Attribute { value, attr, .. } = &func.node else {return}; let ExprKind::Attribute { value, attr, .. } = &func.node else {return};
let violation: DiagnosticKind = match attr.as_str() { let violation: DiagnosticKind = match attr.as_str() {
"isnull" if rules.enabled(&Rule::UseOfDotIsNull) => UseOfDotIsNull.into(), "isnull" if rules.enabled(Rule::UseOfDotIsNull) => UseOfDotIsNull.into(),
"notnull" if rules.enabled(&Rule::UseOfDotNotNull) => UseOfDotNotNull.into(), "notnull" if rules.enabled(Rule::UseOfDotNotNull) => UseOfDotNotNull.into(),
"pivot" | "unstack" if rules.enabled(&Rule::UseOfDotPivotOrUnstack) => { "pivot" | "unstack" if rules.enabled(Rule::UseOfDotPivotOrUnstack) => {
UseOfDotPivotOrUnstack.into() UseOfDotPivotOrUnstack.into()
} }
"read_table" if rules.enabled(&Rule::UseOfDotReadTable) => UseOfDotReadTable.into(), "read_table" if rules.enabled(Rule::UseOfDotReadTable) => UseOfDotReadTable.into(),
"stack" if rules.enabled(&Rule::UseOfDotStack) => UseOfDotStack.into(), "stack" if rules.enabled(Rule::UseOfDotStack) => UseOfDotStack.into(),
_ => return, _ => return,
}; };

View file

@ -162,7 +162,7 @@ pub fn compound_statements(
Tok::Newline => { Tok::Newline => {
if let Some((start, end)) = semi { if let Some((start, end)) = semi {
let mut diagnostic = Diagnostic::new(UselessSemicolon, Range::new(start, end)); let mut diagnostic = Diagnostic::new(UselessSemicolon, Range::new(start, end));
if autofix.into() && settings.rules.should_fix(&Rule::UselessSemicolon) { if autofix.into() && settings.rules.should_fix(Rule::UselessSemicolon) {
diagnostic.amend(Fix::deletion(start, end)); diagnostic.amend(Fix::deletion(start, end));
}; };
diagnostics.push(diagnostic); diagnostics.push(diagnostic);

View file

@ -88,22 +88,20 @@ pub fn trailing_whitespace(
let end = Location::new(lineno + 1, line_char_count); let end = Location::new(lineno + 1, line_char_count);
if whitespace_count == line_char_count { if whitespace_count == line_char_count {
if settings.rules.enabled(&Rule::BlankLineContainsWhitespace) { if settings.rules.enabled(Rule::BlankLineContainsWhitespace) {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(BlankLineContainsWhitespace, Range::new(start, end)); Diagnostic::new(BlankLineContainsWhitespace, Range::new(start, end));
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings && settings.rules.should_fix(Rule::BlankLineContainsWhitespace)
.rules
.should_fix(&Rule::BlankLineContainsWhitespace)
{ {
diagnostic.amend(Fix::deletion(start, end)); diagnostic.amend(Fix::deletion(start, end));
} }
return Some(diagnostic); return Some(diagnostic);
} }
} else if settings.rules.enabled(&Rule::TrailingWhitespace) { } else if settings.rules.enabled(Rule::TrailingWhitespace) {
let mut diagnostic = Diagnostic::new(TrailingWhitespace, Range::new(start, end)); let mut diagnostic = Diagnostic::new(TrailingWhitespace, Range::new(start, end));
if matches!(autofix, flags::Autofix::Enabled) if matches!(autofix, flags::Autofix::Enabled)
&& settings.rules.should_fix(&Rule::TrailingWhitespace) && settings.rules.should_fix(Rule::TrailingWhitespace)
{ {
diagnostic.amend(Fix::deletion(start, end)); diagnostic.amend(Fix::deletion(start, end));
} }

View file

@ -65,11 +65,8 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::OneBlankLineBeforeClass) .enabled(Rule::OneBlankLineBeforeClass)
|| checker || checker.settings.rules.enabled(Rule::NoBlankLineBeforeClass)
.settings
.rules
.enabled(&Rule::NoBlankLineBeforeClass)
{ {
let before = checker let before = checker
.locator .locator
@ -81,11 +78,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
.skip(1) .skip(1)
.take_while(|line| line.trim().is_empty()) .take_while(|line| line.trim().is_empty())
.count(); .count();
if checker if checker.settings.rules.enabled(Rule::NoBlankLineBeforeClass) {
.settings
.rules
.enabled(&Rule::NoBlankLineBeforeClass)
{
if blank_lines_before != 0 { if blank_lines_before != 0 {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
NoBlankLineBeforeClass { NoBlankLineBeforeClass {
@ -106,7 +99,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::OneBlankLineBeforeClass) .enabled(Rule::OneBlankLineBeforeClass)
{ {
if blank_lines_before != 1 { if blank_lines_before != 1 {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
@ -128,11 +121,7 @@ pub fn blank_before_after_class(checker: &mut Checker, docstring: &Docstring) {
} }
} }
if checker if checker.settings.rules.enabled(Rule::OneBlankLineAfterClass) {
.settings
.rules
.enabled(&Rule::OneBlankLineAfterClass)
{
let after = checker.locator.slice(Range::new( let after = checker.locator.slice(Range::new(
docstring.expr.end_location.unwrap(), docstring.expr.end_location.unwrap(),
parent.end_location.unwrap(), parent.end_location.unwrap(),

View file

@ -61,7 +61,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::NoBlankLineBeforeFunction) .enabled(Rule::NoBlankLineBeforeFunction)
{ {
let before = checker let before = checker
.locator .locator
@ -94,7 +94,7 @@ pub fn blank_before_after_function(checker: &mut Checker, docstring: &Docstring)
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::NoBlankLineAfterFunction) .enabled(Rule::NoBlankLineAfterFunction)
{ {
let after = checker.locator.slice(Range::new( let after = checker.locator.slice(Range::new(
docstring.expr.end_location.unwrap(), docstring.expr.end_location.unwrap(),

View file

@ -80,7 +80,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
// yet. // yet.
has_seen_tab = has_seen_tab || line_indent.contains('\t'); has_seen_tab = has_seen_tab || line_indent.contains('\t');
if checker.settings.rules.enabled(&Rule::NoUnderIndentation) { if checker.settings.rules.enabled(Rule::NoUnderIndentation) {
// We report under-indentation on every line. This isn't great, but enables // We report under-indentation on every line. This isn't great, but enables
// autofix. // autofix.
if (i == lines.len() - 1 || !is_blank) if (i == lines.len() - 1 || !is_blank)
@ -119,7 +119,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
} }
} }
if checker.settings.rules.enabled(&Rule::IndentWithSpaces) { if checker.settings.rules.enabled(Rule::IndentWithSpaces) {
if has_seen_tab { if has_seen_tab {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
IndentWithSpaces, IndentWithSpaces,
@ -128,7 +128,7 @@ pub fn indent(checker: &mut Checker, docstring: &Docstring) {
} }
} }
if checker.settings.rules.enabled(&Rule::NoOverIndentation) { if checker.settings.rules.enabled(Rule::NoOverIndentation) {
// If every line (except the last) is over-indented... // If every line (except the last) is over-indented...
if is_over_indented { if is_over_indented {
for i in over_indented_lines { for i in over_indented_lines {

View file

@ -56,7 +56,7 @@ pub fn multi_line_summary_start(checker: &mut Checker, docstring: &Docstring) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MultiLineSummaryFirstLine) .enabled(Rule::MultiLineSummaryFirstLine)
{ {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(MultiLineSummaryFirstLine, Range::from(docstring.expr)); Diagnostic::new(MultiLineSummaryFirstLine, Range::from(docstring.expr));
@ -81,7 +81,7 @@ pub fn multi_line_summary_start(checker: &mut Checker, docstring: &Docstring) {
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MultiLineSummarySecondLine) .enabled(Rule::MultiLineSummarySecondLine)
{ {
let mut diagnostic = let mut diagnostic =
Diagnostic::new(MultiLineSummarySecondLine, Range::from(docstring.expr)); Diagnostic::new(MultiLineSummarySecondLine, Range::from(docstring.expr));

View file

@ -22,7 +22,7 @@ pub fn not_empty(checker: &mut Checker, docstring: &Docstring) -> bool {
return true; return true;
} }
if checker.settings.rules.enabled(&Rule::EmptyDocstring) { if checker.settings.rules.enabled(Rule::EmptyDocstring) {
checker checker
.diagnostics .diagnostics
.push(Diagnostic::new(EmptyDocstring, Range::from(docstring.expr))); .push(Diagnostic::new(EmptyDocstring, Range::from(docstring.expr)));

View file

@ -104,7 +104,7 @@ pub fn not_missing(
match definition.kind { match definition.kind {
DefinitionKind::Module => { DefinitionKind::Module => {
if checker.settings.rules.enabled(&Rule::PublicModule) { if checker.settings.rules.enabled(Rule::PublicModule) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicModule, PublicModule,
Range::new(Location::new(1, 0), Location::new(1, 0)), Range::new(Location::new(1, 0), Location::new(1, 0)),
@ -113,7 +113,7 @@ pub fn not_missing(
false false
} }
DefinitionKind::Package => { DefinitionKind::Package => {
if checker.settings.rules.enabled(&Rule::PublicPackage) { if checker.settings.rules.enabled(Rule::PublicPackage) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicPackage, PublicPackage,
Range::new(Location::new(1, 0), Location::new(1, 0)), Range::new(Location::new(1, 0), Location::new(1, 0)),
@ -122,7 +122,7 @@ pub fn not_missing(
false false
} }
DefinitionKind::Class(stmt) => { DefinitionKind::Class(stmt) => {
if checker.settings.rules.enabled(&Rule::PublicClass) { if checker.settings.rules.enabled(Rule::PublicClass) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicClass, PublicClass,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),
@ -131,7 +131,7 @@ pub fn not_missing(
false false
} }
DefinitionKind::NestedClass(stmt) => { DefinitionKind::NestedClass(stmt) => {
if checker.settings.rules.enabled(&Rule::PublicNestedClass) { if checker.settings.rules.enabled(Rule::PublicNestedClass) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicNestedClass, PublicNestedClass,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),
@ -143,7 +143,7 @@ pub fn not_missing(
if is_overload(&checker.ctx, cast::decorator_list(stmt)) { if is_overload(&checker.ctx, cast::decorator_list(stmt)) {
true true
} else { } else {
if checker.settings.rules.enabled(&Rule::PublicFunction) { if checker.settings.rules.enabled(Rule::PublicFunction) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicFunction, PublicFunction,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),
@ -158,7 +158,7 @@ pub fn not_missing(
{ {
true true
} else if is_init(cast::name(stmt)) { } else if is_init(cast::name(stmt)) {
if checker.settings.rules.enabled(&Rule::PublicInit) { if checker.settings.rules.enabled(Rule::PublicInit) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicInit, PublicInit,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),
@ -166,7 +166,7 @@ pub fn not_missing(
} }
true true
} else if is_new(cast::name(stmt)) || is_call(cast::name(stmt)) { } else if is_new(cast::name(stmt)) || is_call(cast::name(stmt)) {
if checker.settings.rules.enabled(&Rule::PublicMethod) { if checker.settings.rules.enabled(Rule::PublicMethod) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicMethod, PublicMethod,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),
@ -174,7 +174,7 @@ pub fn not_missing(
} }
true true
} else if is_magic(cast::name(stmt)) { } else if is_magic(cast::name(stmt)) {
if checker.settings.rules.enabled(&Rule::MagicMethod) { if checker.settings.rules.enabled(Rule::MagicMethod) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
MagicMethod, MagicMethod,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),
@ -182,7 +182,7 @@ pub fn not_missing(
} }
true true
} else { } else {
if checker.settings.rules.enabled(&Rule::PublicMethod) { if checker.settings.rules.enabled(Rule::PublicMethod) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
PublicMethod, PublicMethod,
identifier_range(stmt, checker.locator), identifier_range(stmt, checker.locator),

View file

@ -353,7 +353,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::DashedUnderlineAfterSection) .enabled(Rule::DashedUnderlineAfterSection)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
DashedUnderlineAfterSection { DashedUnderlineAfterSection {
@ -379,7 +379,7 @@ fn blanks_and_section_underline(
} }
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
if checker.settings.rules.enabled(&Rule::EmptyDocstringSection) { if checker.settings.rules.enabled(Rule::EmptyDocstringSection) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
EmptyDocstringSection { EmptyDocstringSection {
name: context.section_name.to_string(), name: context.section_name.to_string(),
@ -400,7 +400,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::SectionUnderlineAfterName) .enabled(Rule::SectionUnderlineAfterName)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
SectionUnderlineAfterName { SectionUnderlineAfterName {
@ -438,7 +438,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::SectionUnderlineMatchesSectionLength) .enabled(Rule::SectionUnderlineMatchesSectionLength)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
SectionUnderlineMatchesSectionLength { SectionUnderlineMatchesSectionLength {
@ -480,7 +480,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::SectionUnderlineNotOverIndented) .enabled(Rule::SectionUnderlineNotOverIndented)
{ {
let leading_space = whitespace::leading_space(non_empty_line); let leading_space = whitespace::leading_space(non_empty_line);
if leading_space.len() > docstring.indentation.len() { if leading_space.len() > docstring.indentation.len() {
@ -525,7 +525,7 @@ fn blanks_and_section_underline(
.take_while(|line| line.trim().is_empty()) .take_while(|line| line.trim().is_empty())
.count(); .count();
if blank_lines_after_dashes == rest_of_lines.len() { if blank_lines_after_dashes == rest_of_lines.len() {
if checker.settings.rules.enabled(&Rule::EmptyDocstringSection) { if checker.settings.rules.enabled(Rule::EmptyDocstringSection) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
EmptyDocstringSection { EmptyDocstringSection {
name: context.section_name.to_string(), name: context.section_name.to_string(),
@ -537,7 +537,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::NoBlankLinesBetweenHeaderAndContent) .enabled(Rule::NoBlankLinesBetweenHeaderAndContent)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
NoBlankLinesBetweenHeaderAndContent { NoBlankLinesBetweenHeaderAndContent {
@ -570,7 +570,7 @@ fn blanks_and_section_underline(
} }
} }
} else { } else {
if checker.settings.rules.enabled(&Rule::EmptyDocstringSection) { if checker.settings.rules.enabled(Rule::EmptyDocstringSection) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
EmptyDocstringSection { EmptyDocstringSection {
name: context.section_name.to_string(), name: context.section_name.to_string(),
@ -583,7 +583,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::DashedUnderlineAfterSection) .enabled(Rule::DashedUnderlineAfterSection)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
DashedUnderlineAfterSection { DashedUnderlineAfterSection {
@ -613,7 +613,7 @@ fn blanks_and_section_underline(
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::NoBlankLinesBetweenHeaderAndContent) .enabled(Rule::NoBlankLinesBetweenHeaderAndContent)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
NoBlankLinesBetweenHeaderAndContent { NoBlankLinesBetweenHeaderAndContent {
@ -644,7 +644,7 @@ fn blanks_and_section_underline(
} }
fn common_section(checker: &mut Checker, docstring: &Docstring, context: &SectionContext) { fn common_section(checker: &mut Checker, docstring: &Docstring, context: &SectionContext) {
if checker.settings.rules.enabled(&Rule::CapitalizeSectionName) { if checker.settings.rules.enabled(Rule::CapitalizeSectionName) {
let capitalized_section_name = context.kind.as_str(); let capitalized_section_name = context.kind.as_str();
if context.section_name != capitalized_section_name { if context.section_name != capitalized_section_name {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
@ -677,11 +677,7 @@ fn common_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
} }
} }
if checker if checker.settings.rules.enabled(Rule::SectionNotOverIndented) {
.settings
.rules
.enabled(&Rule::SectionNotOverIndented)
{
let leading_space = whitespace::leading_space(context.line); let leading_space = whitespace::leading_space(context.line);
if leading_space.len() > docstring.indentation.len() { if leading_space.len() > docstring.indentation.len() {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
@ -715,7 +711,7 @@ fn common_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::BlankLineAfterLastSection) .enabled(Rule::BlankLineAfterLastSection)
{ {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
BlankLineAfterLastSection { BlankLineAfterLastSection {
@ -739,7 +735,7 @@ fn common_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
} else { } else {
if checker.settings.rules.enabled(&Rule::BlankLineAfterSection) { if checker.settings.rules.enabled(Rule::BlankLineAfterSection) {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
BlankLineAfterSection { BlankLineAfterSection {
name: context.section_name.to_string(), name: context.section_name.to_string(),
@ -764,11 +760,7 @@ fn common_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
} }
} }
if checker if checker.settings.rules.enabled(Rule::BlankLineBeforeSection) {
.settings
.rules
.enabled(&Rule::BlankLineBeforeSection)
{
if !context.previous_line.is_empty() { if !context.previous_line.is_empty() {
let mut diagnostic = Diagnostic::new( let mut diagnostic = Diagnostic::new(
BlankLineBeforeSection { BlankLineBeforeSection {
@ -959,7 +951,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::NewLineAfterSectionName) .enabled(Rule::NewLineAfterSectionName)
{ {
let suffix = context let suffix = context
.line .line
@ -997,7 +989,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
} }
} }
if checker.settings.rules.enabled(&Rule::UndocumentedParam) { if checker.settings.rules.enabled(Rule::UndocumentedParam) {
if matches!(context.kind, SectionKind::Parameters) { if matches!(context.kind, SectionKind::Parameters) {
parameters_section(checker, docstring, context); parameters_section(checker, docstring, context);
} }
@ -1007,11 +999,7 @@ fn numpy_section(checker: &mut Checker, docstring: &Docstring, context: &Section
fn google_section(checker: &mut Checker, docstring: &Docstring, context: &SectionContext) { fn google_section(checker: &mut Checker, docstring: &Docstring, context: &SectionContext) {
common_section(checker, docstring, context); common_section(checker, docstring, context);
if checker if checker.settings.rules.enabled(Rule::SectionNameEndsInColon) {
.settings
.rules
.enabled(&Rule::SectionNameEndsInColon)
{
let suffix = context let suffix = context
.line .line
.trim() .trim()
@ -1049,7 +1037,7 @@ fn google_section(checker: &mut Checker, docstring: &Docstring, context: &Sectio
} }
} }
if checker.settings.rules.enabled(&Rule::UndocumentedParam) { if checker.settings.rules.enabled(Rule::UndocumentedParam) {
if matches!(context.kind, SectionKind::Args | SectionKind::Arguments) { if matches!(context.kind, SectionKind::Args | SectionKind::Arguments) {
args_section(checker, docstring, context); args_section(checker, docstring, context);
} }

View file

@ -272,7 +272,7 @@ mod tests {
diagnostics.sort_by_key(|diagnostic| diagnostic.location); diagnostics.sort_by_key(|diagnostic| diagnostic.location);
let actual = diagnostics let actual = diagnostics
.iter() .iter()
.map(|diagnostic| diagnostic.kind.rule().clone()) .map(|diagnostic| diagnostic.kind.rule())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }

View file

@ -97,7 +97,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Option<Expr>], values: &[Exp
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MultiValueRepeatedKeyLiteral) .enabled(Rule::MultiValueRepeatedKeyLiteral)
{ {
let comparable_value: ComparableExpr = (&values[i]).into(); let comparable_value: ComparableExpr = (&values[i]).into();
let is_duplicate_value = seen_values.contains(&comparable_value); let is_duplicate_value = seen_values.contains(&comparable_value);
@ -125,7 +125,7 @@ pub fn repeated_keys(checker: &mut Checker, keys: &[Option<Expr>], values: &[Exp
if checker if checker
.settings .settings
.rules .rules
.enabled(&Rule::MultiValueRepeatedKeyVariable) .enabled(Rule::MultiValueRepeatedKeyVariable)
{ {
let comparable_value: ComparableExpr = (&values[i]).into(); let comparable_value: ComparableExpr = (&values[i]).into();
let is_duplicate_value = seen_values.contains(&comparable_value); let is_duplicate_value = seen_values.contains(&comparable_value);

View file

@ -123,7 +123,7 @@ pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
let message_args = call_args.args.len() - 1; let message_args = call_args.args.len() - 1;
if checker.settings.rules.enabled(&Rule::LoggingTooManyArgs) { if checker.settings.rules.enabled(Rule::LoggingTooManyArgs) {
if summary.num_positional < message_args { if summary.num_positional < message_args {
checker checker
.diagnostics .diagnostics
@ -131,7 +131,7 @@ pub fn logging_call(checker: &mut Checker, func: &Expr, args: &[Expr], keywords:
} }
} }
if checker.settings.rules.enabled(&Rule::LoggingTooFewArgs) { if checker.settings.rules.enabled(Rule::LoggingTooFewArgs) {
if message_args > 0 if message_args > 0
&& call_args.kwargs.is_empty() && call_args.kwargs.is_empty()
&& summary.num_positional > message_args && summary.num_positional > message_args

View file

@ -550,7 +550,7 @@ pub fn deprecated_import(
}, },
Range::from(stmt), Range::from(stmt),
); );
if checker.patch(&Rule::DeprecatedImport) { if checker.patch(Rule::DeprecatedImport) {
if let Some(content) = fix { if let Some(content) = fix {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
content, content,

View file

@ -137,7 +137,7 @@ pub fn extraneous_parentheses(
}; };
let mut diagnostic = let mut diagnostic =
Diagnostic::new(ExtraneousParentheses, Range::new(*start, *end)); Diagnostic::new(ExtraneousParentheses, Range::new(*start, *end));
if autofix.into() && settings.rules.should_fix(&Rule::ExtraneousParentheses) { if autofix.into() && settings.rules.should_fix(Rule::ExtraneousParentheses) {
let contents = locator.slice(Range::new(*start, *end)); let contents = locator.slice(Range::new(*start, *end));
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
contents[1..contents.len() - 1].to_string(), contents[1..contents.len() - 1].to_string(),

View file

@ -22,7 +22,7 @@ impl AlwaysAutofixableViolation for QuotedAnnotation {
/// UP037 /// UP037
pub fn quoted_annotation(checker: &mut Checker, annotation: &str, range: Range) { pub fn quoted_annotation(checker: &mut Checker, annotation: &str, range: Range) {
let mut diagnostic = Diagnostic::new(QuotedAnnotation, range); let mut diagnostic = Diagnostic::new(QuotedAnnotation, range);
if checker.patch(&Rule::QuotedAnnotation) { if checker.patch(Rule::QuotedAnnotation) {
diagnostic.amend(Fix::replacement( diagnostic.amend(Fix::replacement(
annotation.to_string(), annotation.to_string(),
range.location, range.location,

View file

@ -193,7 +193,7 @@ pub fn redundant_open_modes(checker: &mut Checker, expr: &Expr) {
&keyword.node.value, &keyword.node.value,
mode.replacement_value(), mode.replacement_value(),
checker.locator, checker.locator,
checker.patch(&Rule::RedundantOpenModes), checker.patch(Rule::RedundantOpenModes),
)); ));
} }
} }
@ -210,7 +210,7 @@ pub fn redundant_open_modes(checker: &mut Checker, expr: &Expr) {
mode_param, mode_param,
mode.replacement_value(), mode.replacement_value(),
checker.locator, checker.locator,
checker.patch(&Rule::RedundantOpenModes), checker.patch(Rule::RedundantOpenModes),
)); ));
} }
} }

View file

@ -262,7 +262,7 @@ pub fn rewrite_mock_import(checker: &mut Checker, stmt: &Stmt) {
.any(|name| name.node.name == "mock" || name.node.name == "mock.mock") .any(|name| name.node.name == "mock" || name.node.name == "mock.mock")
{ {
// Generate the fix, if needed, which is shared between all `mock` imports. // Generate the fix, if needed, which is shared between all `mock` imports.
let content = if checker.patch(&Rule::RewriteMockImport) { let content = if checker.patch(Rule::RewriteMockImport) {
if let Some(indent) = indentation(checker.locator, stmt) { if let Some(indent) = indentation(checker.locator, stmt) {
match format_import(stmt, indent, checker.locator, checker.stylist) { match format_import(stmt, indent, checker.locator, checker.stylist) {
Ok(content) => Some(content), Ok(content) => Some(content),

View file

@ -161,7 +161,7 @@ pub fn unnecessary_encode_utf8(
expr, expr,
variable, variable,
checker.locator, checker.locator,
checker.patch(&Rule::UnnecessaryEncodeUTF8), checker.patch(Rule::UnnecessaryEncodeUTF8),
)); ));
} else { } else {
// "unicode text©".encode("utf-8") // "unicode text©".encode("utf-8")
@ -169,7 +169,7 @@ pub fn unnecessary_encode_utf8(
expr, expr,
args, args,
kwargs, kwargs,
checker.patch(&Rule::UnnecessaryEncodeUTF8), checker.patch(Rule::UnnecessaryEncodeUTF8),
) { ) {
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
@ -183,7 +183,7 @@ pub fn unnecessary_encode_utf8(
expr, expr,
args, args,
kwargs, kwargs,
checker.patch(&Rule::UnnecessaryEncodeUTF8), checker.patch(Rule::UnnecessaryEncodeUTF8),
) { ) {
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }

View file

@ -386,16 +386,16 @@ impl From<&Configuration> for RuleTable {
.and_then(|pydocstyle| pydocstyle.convention) .and_then(|pydocstyle| pydocstyle.convention)
{ {
for rule in convention.rules_to_be_ignored() { for rule in convention.rules_to_be_ignored() {
rules.disable(rule); rules.disable(*rule);
} }
} }
// Validate that we didn't enable any incompatible rules. Use this awkward // Validate that we didn't enable any incompatible rules. Use this awkward
// approach to give each pair it's own `warn_user_once`. // approach to give each pair it's own `warn_user_once`.
for (preferred, expendable, message) in INCOMPATIBLE_CODES { for (preferred, expendable, message) in INCOMPATIBLE_CODES {
if rules.enabled(preferred) && rules.enabled(expendable) { if rules.enabled(*preferred) && rules.enabled(*expendable) {
warn_user_once_by_id!(expendable.as_ref(), "{}", message); warn_user_once_by_id!(expendable.as_ref(), "{}", message);
rules.disable(expendable); rules.disable(*expendable);
} }
} }
@ -440,7 +440,7 @@ mod tests {
..Configuration::default() ..Configuration::default()
}) })
.iter_enabled() .iter_enabled()
.cloned() .copied()
.collect() .collect()
} }

View file

@ -22,13 +22,15 @@ impl RuleTable {
} }
/// Returns whether the given rule should be checked. /// Returns whether the given rule should be checked.
pub fn enabled(&self, code: &Rule) -> bool { #[inline]
self.enabled.contains_key(code) pub fn enabled(&self, code: Rule) -> bool {
self.enabled.contains_key(&code)
} }
/// Returns whether violations of the given rule should be autofixed. /// Returns whether violations of the given rule should be autofixed.
pub fn should_fix(&self, code: &Rule) -> bool { #[inline]
*self.enabled.get(code).unwrap_or(&false) pub fn should_fix(&self, code: Rule) -> bool {
*self.enabled.get(&code).unwrap_or(&false)
} }
/// Returns an iterator over all enabled rules. /// Returns an iterator over all enabled rules.
@ -37,13 +39,15 @@ impl RuleTable {
} }
/// Enables the given rule. /// Enables the given rule.
#[inline]
pub fn enable(&mut self, code: Rule, should_fix: bool) { pub fn enable(&mut self, code: Rule, should_fix: bool) {
self.enabled.insert(code, should_fix); self.enabled.insert(code, should_fix);
} }
/// Disables the given rule. /// Disables the given rule.
pub fn disable(&mut self, rule: &Rule) { #[inline]
self.enabled.remove(rule); pub fn disable(&mut self, rule: Rule) {
self.enabled.remove(&rule);
} }
} }

View file

@ -16,7 +16,7 @@ struct Explanation<'a> {
} }
/// Explain a `Rule` to the user. /// Explain a `Rule` to the user.
pub fn rule(rule: &Rule, format: HelpFormat) -> Result<()> { pub fn rule(rule: Rule, format: HelpFormat) -> Result<()> {
let (linter, _) = Linter::parse_code(&rule.noqa_code().to_string()).unwrap(); let (linter, _) = Linter::parse_code(&rule.noqa_code().to_string()).unwrap();
let mut stdout = BufWriter::new(io::stdout().lock()); let mut stdout = BufWriter::new(io::stdout().lock());
let mut output = String::new(); let mut output = String::new();

View file

@ -105,7 +105,7 @@ pub fn run(
":".bold() ":".bold()
); );
let settings = resolver.resolve(path, pyproject_strategy); let settings = resolver.resolve(path, pyproject_strategy);
if settings.rules.enabled(&Rule::IOError) { if settings.rules.enabled(Rule::IOError) {
Diagnostics::new(vec![Message::from_diagnostic( Diagnostics::new(vec![Message::from_diagnostic(
Diagnostic::new( Diagnostic::new(
IOError { message }, IOError { message },

View file

@ -73,7 +73,7 @@ quoting the executed command, along with the relevant file contents and `pyproje
set_up_logging(&log_level)?; set_up_logging(&log_level)?;
match command { match command {
Command::Rule { rule, format } => commands::rule::rule(&rule, format)?, Command::Rule { rule, format } => commands::rule::rule(rule, format)?,
Command::Config { option } => return Ok(commands::config::config(option.as_deref())), Command::Config { option } => return Ok(commands::config::config(option.as_deref())),
Command::Linter { format } => commands::linter::linter(format)?, Command::Linter { format } => commands::linter::linter(format)?,
Command::Clean => commands::clean::clean(log_level)?, Command::Clean => commands::clean::clean(log_level)?,

View file

@ -46,7 +46,7 @@ struct ExpandedFix<'a> {
#[derive(Serialize)] #[derive(Serialize)]
struct ExpandedMessage<'a> { struct ExpandedMessage<'a> {
code: SerializeRuleAsCode<'a>, code: SerializeRuleAsCode,
message: String, message: String,
fix: Option<ExpandedFix<'a>>, fix: Option<ExpandedFix<'a>>,
location: Location, location: Location,
@ -63,9 +63,9 @@ struct ExpandedStatistics {
fixable: bool, fixable: bool,
} }
struct SerializeRuleAsCode<'a>(&'a Rule); struct SerializeRuleAsCode(Rule);
impl Serialize for SerializeRuleAsCode<'_> { impl Serialize for SerializeRuleAsCode {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,
@ -74,8 +74,8 @@ impl Serialize for SerializeRuleAsCode<'_> {
} }
} }
impl<'a> From<&'a Rule> for SerializeRuleAsCode<'a> { impl From<Rule> for SerializeRuleAsCode {
fn from(rule: &'a Rule) -> Self { fn from(rule: Rule) -> Self {
Self(rule) Self(rule)
} }
} }
@ -405,13 +405,13 @@ impl Printer {
} }
pub fn write_statistics(&self, diagnostics: &Diagnostics) -> Result<()> { pub fn write_statistics(&self, diagnostics: &Diagnostics) -> Result<()> {
let violations: Vec<&Rule> = diagnostics let violations: Vec<Rule> = diagnostics
.messages .messages
.iter() .iter()
.map(|message| message.kind.rule()) .map(|message| message.kind.rule())
.sorted() .sorted()
.dedup() .dedup()
.collect::<Vec<_>>(); .collect();
if violations.is_empty() { if violations.is_empty() {
return Ok(()); return Ok(());
} }
@ -537,11 +537,11 @@ impl Printer {
} }
} }
fn group_messages_by_filename(messages: &[Message]) -> BTreeMap<&String, Vec<&Message>> { fn group_messages_by_filename(messages: &[Message]) -> BTreeMap<&str, Vec<&Message>> {
let mut grouped_messages = BTreeMap::default(); let mut grouped_messages = BTreeMap::default();
for message in messages { for message in messages {
grouped_messages grouped_messages
.entry(&message.filename) .entry(message.filename.as_str())
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
.push(message); .push(message);
} }

View file

@ -23,7 +23,7 @@ fn generate_table(table_out: &mut String, rules: impl IntoIterator<Item = Rule>,
table_out.push_str(&format!( table_out.push_str(&format!(
"| {}{} | {} | {} | {} |", "| {}{} | {} | {} | {} |",
linter.common_prefix(), linter.common_prefix(),
linter.code_for_rule(&rule).unwrap(), linter.code_for_rule(rule).unwrap(),
rule.explanation() rule.explanation()
.is_some() .is_some()
.then_some(format_args!("[{rule_name}](rules/{rule_name}.md)")) .then_some(format_args!("[{rule_name}](rules/{rule_name}.md)"))

View file

@ -167,7 +167,7 @@ pub fn map_codes(func: &ItemFn) -> syn::Result<TokenStream> {
}); });
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
let mut rule_to_codes: HashMap<&Path, Vec<(&Ident, &String, &Vec<Attribute>)>> = HashMap::new(); let mut rule_to_codes: HashMap<&Path, Vec<(&Ident, &str, &Vec<Attribute>)>> = HashMap::new();
let mut linter_code_for_rule_match_arms = quote!(); let mut linter_code_for_rule_match_arms = quote!();
for (linter, map) in &linters { for (linter, map) in &linters {
@ -227,7 +227,7 @@ pub fn map_codes(func: &ItemFn) -> syn::Result<TokenStream> {
} }
impl crate::registry::Linter { impl crate::registry::Linter {
pub fn code_for_rule(&self, rule: &Rule) -> Option<&'static str> { pub fn code_for_rule(&self, rule: Rule) -> Option<&'static str> {
match (self, rule) { match (self, rule) {
#linter_code_for_rule_match_arms #linter_code_for_rule_match_arms
_ => None, _ => None,

View file

@ -24,8 +24,7 @@ pub fn register_rules(input: &Input) -> proc_macro2::TokenStream {
rule_explanation_match_arms.extend(quote! {#(#attr)* Self::#name => #path::explanation(),}); rule_explanation_match_arms.extend(quote! {#(#attr)* Self::#name => #path::explanation(),});
// Enable conversion from `DiagnosticKind` to `Rule`. // Enable conversion from `DiagnosticKind` to `Rule`.
from_impls_for_diagnostic_kind from_impls_for_diagnostic_kind.extend(quote! {#(#attr)* stringify!(#name) => Rule::#name,});
.extend(quote! {#(#attr)* stringify!(#name) => &Rule::#name,});
} }
quote! { quote! {
@ -34,6 +33,7 @@ pub fn register_rules(input: &Input) -> proc_macro2::TokenStream {
Debug, Debug,
PartialEq, PartialEq,
Eq, Eq,
Copy,
Clone, Clone,
Hash, Hash,
PartialOrd, PartialOrd,
@ -57,17 +57,13 @@ pub fn register_rules(input: &Input) -> proc_macro2::TokenStream {
} }
/// Returns the autofix status of this rule. /// Returns the autofix status of this rule.
pub fn autofixable(&self) -> Option<ruff_diagnostics::AutofixKind> { pub const fn autofixable(&self) -> Option<ruff_diagnostics::AutofixKind> {
match self { #rule_autofixable_match_arms } match self { #rule_autofixable_match_arms }
} }
} }
pub trait AsRule {
fn rule(&self) -> &'static Rule;
}
impl AsRule for ruff_diagnostics::DiagnosticKind { impl AsRule for ruff_diagnostics::DiagnosticKind {
fn rule(&self) -> &'static Rule { fn rule(&self) -> Rule {
match self.name.as_str() { match self.name.as_str() {
#from_impls_for_diagnostic_kind #from_impls_for_diagnostic_kind
_ => unreachable!("invalid rule name: {}", self.name), _ => unreachable!("invalid rule name: {}", self.name),