diff --git a/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs b/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs index 59b1757f66..52cdfc12d0 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/bindings.rs @@ -10,7 +10,7 @@ use crate::rules::{ /// Run lint rules over the [`Binding`]s. pub(crate) fn bindings(checker: &Checker) { - if !checker.any_enabled(&[ + if !checker.any_rule_enabled(&[ Rule::AssignmentInAssert, Rule::InvalidAllFormat, Rule::InvalidAllObject, @@ -30,7 +30,7 @@ pub(crate) fn bindings(checker: &Checker) { } for (binding_id, binding) in checker.semantic.bindings.iter_enumerated() { - if checker.enabled(Rule::UnusedVariable) { + if checker.is_rule_enabled(Rule::UnusedVariable) { if binding.kind.is_bound_exception() && binding.is_unused() && !checker @@ -54,47 +54,47 @@ pub(crate) fn bindings(checker: &Checker) { }); } } - if checker.enabled(Rule::InvalidAllFormat) { + if checker.is_rule_enabled(Rule::InvalidAllFormat) { pylint::rules::invalid_all_format(checker, binding); } - if checker.enabled(Rule::InvalidAllObject) { + if checker.is_rule_enabled(Rule::InvalidAllObject) { pylint::rules::invalid_all_object(checker, binding); } - if checker.enabled(Rule::NonAsciiName) { + if checker.is_rule_enabled(Rule::NonAsciiName) { pylint::rules::non_ascii_name(checker, binding); } - if checker.enabled(Rule::UnconventionalImportAlias) { + if checker.is_rule_enabled(Rule::UnconventionalImportAlias) { flake8_import_conventions::rules::unconventional_import_alias( checker, binding, &checker.settings.flake8_import_conventions.aliases, ); } - if checker.enabled(Rule::UnaliasedCollectionsAbcSetImport) { + if checker.is_rule_enabled(Rule::UnaliasedCollectionsAbcSetImport) { flake8_pyi::rules::unaliased_collections_abc_set_import(checker, binding); } - if !checker.source_type.is_stub() && checker.enabled(Rule::UnquotedTypeAlias) { + if !checker.source_type.is_stub() && checker.is_rule_enabled(Rule::UnquotedTypeAlias) { flake8_type_checking::rules::unquoted_type_alias(checker, binding); } - if checker.enabled(Rule::UnsortedDunderSlots) { + if checker.is_rule_enabled(Rule::UnsortedDunderSlots) { ruff::rules::sort_dunder_slots(checker, binding); } - if checker.enabled(Rule::UsedDummyVariable) { + if checker.is_rule_enabled(Rule::UsedDummyVariable) { ruff::rules::used_dummy_variable(checker, binding, binding_id); } - if checker.enabled(Rule::AssignmentInAssert) { + if checker.is_rule_enabled(Rule::AssignmentInAssert) { ruff::rules::assignment_in_assert(checker, binding); } - if checker.enabled(Rule::PytestUnittestRaisesAssertion) { + if checker.is_rule_enabled(Rule::PytestUnittestRaisesAssertion) { flake8_pytest_style::rules::unittest_raises_assertion_binding(checker, binding); } - if checker.enabled(Rule::ForLoopWrites) { + if checker.is_rule_enabled(Rule::ForLoopWrites) { refurb::rules::for_loop_writes_binding(checker, binding); } - if checker.enabled(Rule::CustomTypeVarForSelf) { + if checker.is_rule_enabled(Rule::CustomTypeVarForSelf) { flake8_pyi::rules::custom_type_var_instead_of_self(checker, binding); } - if checker.enabled(Rule::PrivateTypeParameter) { + if checker.is_rule_enabled(Rule::PrivateTypeParameter) { pyupgrade::rules::private_type_parameter(checker, binding); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/comprehension.rs b/crates/ruff_linter/src/checkers/ast/analyze/comprehension.rs index 356c0ca899..46b74c13f0 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/comprehension.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/comprehension.rs @@ -6,10 +6,10 @@ use crate::rules::{flake8_simplify, refurb}; /// Run lint rules over a [`Comprehension`] syntax nodes. pub(crate) fn comprehension(comprehension: &Comprehension, checker: &Checker) { - if checker.enabled(Rule::InDictKeys) { + if checker.is_rule_enabled(Rule::InDictKeys) { flake8_simplify::rules::key_in_dict_comprehension(checker, comprehension); } - if checker.enabled(Rule::ReadlinesInFor) { + if checker.is_rule_enabled(Rule::ReadlinesInFor) { refurb::rules::readlines_in_comprehension(checker, comprehension); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/deferred_for_loops.rs b/crates/ruff_linter/src/checkers/ast/analyze/deferred_for_loops.rs index abb9110b6e..d337081c61 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/deferred_for_loops.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/deferred_for_loops.rs @@ -14,31 +14,31 @@ pub(crate) fn deferred_for_loops(checker: &mut Checker) { let Stmt::For(stmt_for) = checker.semantic.current_statement() else { unreachable!("Expected Stmt::For"); }; - if checker.enabled(Rule::UnusedLoopControlVariable) { + if checker.is_rule_enabled(Rule::UnusedLoopControlVariable) { flake8_bugbear::rules::unused_loop_control_variable(checker, stmt_for); } - if checker.enabled(Rule::IncorrectDictIterator) { + if checker.is_rule_enabled(Rule::IncorrectDictIterator) { perflint::rules::incorrect_dict_iterator(checker, stmt_for); } - if checker.enabled(Rule::YieldInForLoop) { + if checker.is_rule_enabled(Rule::YieldInForLoop) { pyupgrade::rules::yield_in_for_loop(checker, stmt_for); } - if checker.enabled(Rule::UnnecessaryEnumerate) { + if checker.is_rule_enabled(Rule::UnnecessaryEnumerate) { refurb::rules::unnecessary_enumerate(checker, stmt_for); } - if checker.enabled(Rule::EnumerateForLoop) { + if checker.is_rule_enabled(Rule::EnumerateForLoop) { flake8_simplify::rules::enumerate_for_loop(checker, stmt_for); } - if checker.enabled(Rule::LoopIteratorMutation) { + if checker.is_rule_enabled(Rule::LoopIteratorMutation) { flake8_bugbear::rules::loop_iterator_mutation(checker, stmt_for); } - if checker.enabled(Rule::DictIndexMissingItems) { + if checker.is_rule_enabled(Rule::DictIndexMissingItems) { pylint::rules::dict_index_missing_items(checker, stmt_for); } - if checker.enabled(Rule::ManualDictComprehension) { + if checker.is_rule_enabled(Rule::ManualDictComprehension) { perflint::rules::manual_dict_comprehension(checker, stmt_for); } - if checker.enabled(Rule::ManualListComprehension) { + if checker.is_rule_enabled(Rule::ManualListComprehension) { perflint::rules::manual_list_comprehension(checker, stmt_for); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/deferred_lambdas.rs b/crates/ruff_linter/src/checkers/ast/analyze/deferred_lambdas.rs index 2ec55d4850..c2738492ed 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/deferred_lambdas.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/deferred_lambdas.rs @@ -15,13 +15,13 @@ pub(crate) fn deferred_lambdas(checker: &mut Checker) { unreachable!("Expected Expr::Lambda"); }; - if checker.enabled(Rule::UnnecessaryLambda) { + if checker.is_rule_enabled(Rule::UnnecessaryLambda) { pylint::rules::unnecessary_lambda(checker, lambda); } - if checker.enabled(Rule::ReimplementedContainerBuiltin) { + if checker.is_rule_enabled(Rule::ReimplementedContainerBuiltin) { flake8_pie::rules::reimplemented_container_builtin(checker, lambda); } - if checker.enabled(Rule::BuiltinLambdaArgumentShadowing) { + if checker.is_rule_enabled(Rule::BuiltinLambdaArgumentShadowing) { flake8_builtins::rules::builtin_lambda_argument_shadowing(checker, lambda); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs b/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs index 338c0c7657..69bc5866ab 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/deferred_scopes.rs @@ -14,7 +14,7 @@ use crate::rules::{ /// Run lint rules over all deferred scopes in the [`SemanticModel`]. pub(crate) fn deferred_scopes(checker: &Checker) { - if !checker.any_enabled(&[ + if !checker.any_rule_enabled(&[ Rule::AsyncioDanglingTask, Rule::BadStaticmethodArgument, Rule::BuiltinAttributeShadowing, @@ -58,7 +58,7 @@ pub(crate) fn deferred_scopes(checker: &Checker) { // 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_enabled(&[ + && checker.any_rule_enabled(&[ Rule::TypingOnlyFirstPartyImport, Rule::TypingOnlyStandardLibraryImport, Rule::TypingOnlyThirdPartyImport, @@ -89,11 +89,11 @@ pub(crate) fn deferred_scopes(checker: &Checker) { for scope_id in checker.analyze.scopes.iter().rev().copied() { let scope = &checker.semantic.scopes[scope_id]; - if checker.enabled(Rule::UndefinedLocal) { + if checker.is_rule_enabled(Rule::UndefinedLocal) { pyflakes::rules::undefined_local(checker, scope_id, scope); } - if checker.enabled(Rule::GlobalVariableNotAssigned) { + if checker.is_rule_enabled(Rule::GlobalVariableNotAssigned) { for (name, binding_id) in scope.bindings() { let binding = checker.semantic.binding(binding_id); // If the binding is a `global`, then it's a top-level `global` that was never @@ -123,7 +123,7 @@ pub(crate) fn deferred_scopes(checker: &Checker) { } } - if checker.enabled(Rule::RedefinedArgumentFromLocal) { + if checker.is_rule_enabled(Rule::RedefinedArgumentFromLocal) { for (name, binding_id) in scope.bindings() { for shadow in checker.semantic.shadowed_bindings(scope_id, binding_id) { let binding = &checker.semantic.bindings[shadow.binding_id()]; @@ -156,7 +156,7 @@ pub(crate) fn deferred_scopes(checker: &Checker) { } } - if checker.enabled(Rule::ImportShadowedByLoopVar) { + if checker.is_rule_enabled(Rule::ImportShadowedByLoopVar) { for (name, binding_id) in scope.bindings() { for shadow in checker.semantic.shadowed_bindings(scope_id, binding_id) { // If the shadowing binding isn't a loop variable, abort. @@ -197,7 +197,7 @@ pub(crate) fn deferred_scopes(checker: &Checker) { } } - if checker.enabled(Rule::RedefinedWhileUnused) { + if checker.is_rule_enabled(Rule::RedefinedWhileUnused) { // Index the redefined bindings by statement. let mut redefinitions = FxHashMap::default(); @@ -353,43 +353,43 @@ pub(crate) fn deferred_scopes(checker: &Checker) { if checker.source_type.is_stub() || matches!(scope.kind, ScopeKind::Module | ScopeKind::Function(_)) { - if checker.enabled(Rule::UnusedPrivateTypeVar) { + if checker.is_rule_enabled(Rule::UnusedPrivateTypeVar) { flake8_pyi::rules::unused_private_type_var(checker, scope); } - if checker.enabled(Rule::UnusedPrivateProtocol) { + if checker.is_rule_enabled(Rule::UnusedPrivateProtocol) { flake8_pyi::rules::unused_private_protocol(checker, scope); } - if checker.enabled(Rule::UnusedPrivateTypeAlias) { + if checker.is_rule_enabled(Rule::UnusedPrivateTypeAlias) { flake8_pyi::rules::unused_private_type_alias(checker, scope); } - if checker.enabled(Rule::UnusedPrivateTypedDict) { + if checker.is_rule_enabled(Rule::UnusedPrivateTypedDict) { flake8_pyi::rules::unused_private_typed_dict(checker, scope); } } - if checker.enabled(Rule::AsyncioDanglingTask) { + 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.enabled(Rule::BuiltinAttributeShadowing) { + if checker.is_rule_enabled(Rule::BuiltinAttributeShadowing) { flake8_builtins::rules::builtin_attribute_shadowing( checker, scope_id, scope, class_def, ); } - if checker.enabled(Rule::FunctionCallInDataclassDefaultArgument) { + if checker.is_rule_enabled(Rule::FunctionCallInDataclassDefaultArgument) { ruff::rules::function_call_in_dataclass_default(checker, class_def); } - if checker.enabled(Rule::MutableClassDefault) { + if checker.is_rule_enabled(Rule::MutableClassDefault) { ruff::rules::mutable_class_default(checker, class_def); } - if checker.enabled(Rule::MutableDataclassDefault) { + 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_enabled(&[Rule::UnusedVariable, Rule::UnusedUnpackedVariable]) + if checker.any_rule_enabled(&[Rule::UnusedVariable, Rule::UnusedUnpackedVariable]) && !(scope.uses_locals() && scope.kind.is_function()) { let unused_bindings = scope @@ -418,22 +418,22 @@ pub(crate) fn deferred_scopes(checker: &Checker) { }); for (unused_name, unused_binding) in unused_bindings { - if checker.enabled(Rule::UnusedVariable) { + if checker.is_rule_enabled(Rule::UnusedVariable) { pyflakes::rules::unused_variable(checker, unused_name, unused_binding); } - if checker.enabled(Rule::UnusedUnpackedVariable) { + if checker.is_rule_enabled(Rule::UnusedUnpackedVariable) { ruff::rules::unused_unpacked_variable(checker, unused_name, unused_binding); } } } - if checker.enabled(Rule::UnusedAnnotation) { + if checker.is_rule_enabled(Rule::UnusedAnnotation) { pyflakes::rules::unused_annotation(checker, scope); } if !checker.source_type.is_stub() { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::UnusedClassMethodArgument, Rule::UnusedFunctionArgument, Rule::UnusedLambdaArgument, @@ -447,7 +447,7 @@ pub(crate) fn deferred_scopes(checker: &Checker) { if matches!(scope.kind, ScopeKind::Function(_) | ScopeKind::Module) { if !checker.source_type.is_stub() - && checker.enabled(Rule::RuntimeImportInTypeCheckingBlock) + && checker.is_rule_enabled(Rule::RuntimeImportInTypeCheckingBlock) { flake8_type_checking::rules::runtime_import_in_type_checking_block(checker, scope); } @@ -467,37 +467,37 @@ pub(crate) fn deferred_scopes(checker: &Checker) { ); } - if checker.enabled(Rule::UnusedImport) { + if checker.is_rule_enabled(Rule::UnusedImport) { pyflakes::rules::unused_import(checker, scope); } - if checker.enabled(Rule::ImportPrivateName) { + if checker.is_rule_enabled(Rule::ImportPrivateName) { pylint::rules::import_private_name(checker, scope); } } if scope.kind.is_function() { - if checker.enabled(Rule::NoSelfUse) { + if checker.is_rule_enabled(Rule::NoSelfUse) { pylint::rules::no_self_use(checker, scope_id, scope); } - if checker.enabled(Rule::TooManyLocals) { + if checker.is_rule_enabled(Rule::TooManyLocals) { pylint::rules::too_many_locals(checker, scope); } - if checker.enabled(Rule::SingledispatchMethod) { + if checker.is_rule_enabled(Rule::SingledispatchMethod) { pylint::rules::singledispatch_method(checker, scope); } - if checker.enabled(Rule::SingledispatchmethodFunction) { + if checker.is_rule_enabled(Rule::SingledispatchmethodFunction) { pylint::rules::singledispatchmethod_function(checker, scope); } - if checker.enabled(Rule::BadStaticmethodArgument) { + if checker.is_rule_enabled(Rule::BadStaticmethodArgument) { pylint::rules::bad_staticmethod_argument(checker, scope); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::InvalidFirstArgumentNameForClassMethod, Rule::InvalidFirstArgumentNameForMethod, ]) { diff --git a/crates/ruff_linter/src/checkers/ast/analyze/definitions.rs b/crates/ruff_linter/src/checkers/ast/analyze/definitions.rs index a1f85de2e9..3044223468 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/definitions.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/definitions.rs @@ -17,7 +17,7 @@ use crate::{docstrings, warn_user}; /// 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_enabled(&[ + let enforce_annotations = checker.any_rule_enabled(&[ Rule::AnyType, Rule::MissingReturnTypeClassMethod, Rule::MissingReturnTypePrivateFunction, @@ -28,10 +28,11 @@ pub(crate) fn definitions(checker: &mut Checker) { Rule::MissingTypeFunctionArgument, Rule::MissingTypeKwargs, ]); - let enforce_stubs = checker.source_type.is_stub() && checker.enabled(Rule::DocstringInStub); - let enforce_stubs_and_runtime = checker.enabled(Rule::IterMethodReturnIterable); - let enforce_dunder_method = checker.enabled(Rule::BadDunderMethodName); - let enforce_docstrings = checker.any_enabled(&[ + 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, @@ -79,7 +80,7 @@ pub(crate) fn definitions(checker: &mut Checker) { Rule::UndocumentedPublicNestedClass, Rule::UndocumentedPublicPackage, ]); - let enforce_pydoclint = checker.any_enabled(&[ + let enforce_pydoclint = checker.any_rule_enabled(&[ Rule::DocstringMissingReturns, Rule::DocstringExtraneousReturns, Rule::DocstringMissingYields, @@ -202,74 +203,76 @@ pub(crate) fn definitions(checker: &mut Checker) { if !pydocstyle::rules::not_empty(checker, &docstring) { continue; } - if checker.enabled(Rule::UnnecessaryMultilineDocstring) { + if checker.is_rule_enabled(Rule::UnnecessaryMultilineDocstring) { pydocstyle::rules::one_liner(checker, &docstring); } - if checker.any_enabled(&[Rule::BlankLineAfterFunction, Rule::BlankLineBeforeFunction]) { + if checker + .any_rule_enabled(&[Rule::BlankLineAfterFunction, Rule::BlankLineBeforeFunction]) + { pydocstyle::rules::blank_before_after_function(checker, &docstring); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::BlankLineBeforeClass, Rule::IncorrectBlankLineAfterClass, Rule::IncorrectBlankLineBeforeClass, ]) { pydocstyle::rules::blank_before_after_class(checker, &docstring); } - if checker.enabled(Rule::MissingBlankLineAfterSummary) { + if checker.is_rule_enabled(Rule::MissingBlankLineAfterSummary) { pydocstyle::rules::blank_after_summary(checker, &docstring); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::DocstringTabIndentation, Rule::OverIndentation, Rule::UnderIndentation, ]) { pydocstyle::rules::indent(checker, &docstring); } - if checker.enabled(Rule::NewLineAfterLastParagraph) { + if checker.is_rule_enabled(Rule::NewLineAfterLastParagraph) { pydocstyle::rules::newline_after_last_paragraph(checker, &docstring); } - if checker.enabled(Rule::SurroundingWhitespace) { + if checker.is_rule_enabled(Rule::SurroundingWhitespace) { pydocstyle::rules::no_surrounding_whitespace(checker, &docstring); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::MultiLineSummaryFirstLine, Rule::MultiLineSummarySecondLine, ]) { pydocstyle::rules::multi_line_summary_start(checker, &docstring); } - if checker.enabled(Rule::TripleSingleQuotes) { + if checker.is_rule_enabled(Rule::TripleSingleQuotes) { pydocstyle::rules::triple_quotes(checker, &docstring); } - if checker.enabled(Rule::EscapeSequenceInDocstring) { + if checker.is_rule_enabled(Rule::EscapeSequenceInDocstring) { pydocstyle::rules::backslashes(checker, &docstring); } - if checker.enabled(Rule::MissingTrailingPeriod) { + if checker.is_rule_enabled(Rule::MissingTrailingPeriod) { pydocstyle::rules::ends_with_period(checker, &docstring); } - if checker.enabled(Rule::NonImperativeMood) { + if checker.is_rule_enabled(Rule::NonImperativeMood) { pydocstyle::rules::non_imperative_mood( checker, &docstring, &checker.settings.pydocstyle, ); } - if checker.enabled(Rule::SignatureInDocstring) { + if checker.is_rule_enabled(Rule::SignatureInDocstring) { pydocstyle::rules::no_signature(checker, &docstring); } - if checker.enabled(Rule::FirstWordUncapitalized) { + if checker.is_rule_enabled(Rule::FirstWordUncapitalized) { pydocstyle::rules::capitalized(checker, &docstring); } - if checker.enabled(Rule::DocstringStartsWithThis) { + if checker.is_rule_enabled(Rule::DocstringStartsWithThis) { pydocstyle::rules::starts_with_this(checker, &docstring); } - if checker.enabled(Rule::MissingTerminalPunctuation) { + if checker.is_rule_enabled(Rule::MissingTerminalPunctuation) { pydocstyle::rules::ends_with_punctuation(checker, &docstring); } - if checker.enabled(Rule::OverloadWithDocstring) { + if checker.is_rule_enabled(Rule::OverloadWithDocstring) { pydocstyle::rules::if_needed(checker, &docstring); } - let enforce_sections = checker.any_enabled(&[ + let enforce_sections = checker.any_rule_enabled(&[ Rule::MissingBlankLineAfterLastSection, Rule::BlankLinesBetweenHeaderAndContent, Rule::NonCapitalizedSectionName, diff --git a/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs b/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs index 3a7e3a4f5b..4d7b03a37a 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/except_handler.rs @@ -17,17 +17,17 @@ pub(crate) fn except_handler(except_handler: &ExceptHandler, checker: &Checker) range: _, node_index: _, }) => { - if checker.enabled(Rule::BareExcept) { + if checker.is_rule_enabled(Rule::BareExcept) { pycodestyle::rules::bare_except(checker, type_.as_deref(), body, except_handler); } - if checker.enabled(Rule::RaiseWithoutFromInsideExcept) { + if checker.is_rule_enabled(Rule::RaiseWithoutFromInsideExcept) { flake8_bugbear::rules::raise_without_from_inside_except( checker, name.as_deref(), body, ); } - if checker.enabled(Rule::BlindExcept) { + if checker.is_rule_enabled(Rule::BlindExcept) { flake8_blind_except::rules::blind_except( checker, type_.as_deref(), @@ -35,7 +35,7 @@ pub(crate) fn except_handler(except_handler: &ExceptHandler, checker: &Checker) body, ); } - if checker.enabled(Rule::TryExceptPass) { + if checker.is_rule_enabled(Rule::TryExceptPass) { flake8_bandit::rules::try_except_pass( checker, except_handler, @@ -44,7 +44,7 @@ pub(crate) fn except_handler(except_handler: &ExceptHandler, checker: &Checker) checker.settings.flake8_bandit.check_typed_exception, ); } - if checker.enabled(Rule::TryExceptContinue) { + if checker.is_rule_enabled(Rule::TryExceptContinue) { flake8_bandit::rules::try_except_continue( checker, except_handler, @@ -53,24 +53,24 @@ pub(crate) fn except_handler(except_handler: &ExceptHandler, checker: &Checker) checker.settings.flake8_bandit.check_typed_exception, ); } - if checker.enabled(Rule::ExceptWithEmptyTuple) { + if checker.is_rule_enabled(Rule::ExceptWithEmptyTuple) { flake8_bugbear::rules::except_with_empty_tuple(checker, except_handler); } - if checker.enabled(Rule::ExceptWithNonExceptionClasses) { + if checker.is_rule_enabled(Rule::ExceptWithNonExceptionClasses) { flake8_bugbear::rules::except_with_non_exception_classes(checker, except_handler); } - if checker.enabled(Rule::BinaryOpException) { + if checker.is_rule_enabled(Rule::BinaryOpException) { pylint::rules::binary_op_exception(checker, except_handler); } if let Some(name) = name { - if checker.enabled(Rule::AmbiguousVariableName) { + if checker.is_rule_enabled(Rule::AmbiguousVariableName) { pycodestyle::rules::ambiguous_variable_name( checker, name.as_str(), name.range(), ); } - if checker.enabled(Rule::BuiltinVariableShadowing) { + if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) { flake8_builtins::rules::builtin_variable_shadowing(checker, name, name.range()); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/expression.rs b/crates/ruff_linter/src/checkers/ast/analyze/expression.rs index 79b5be716e..51c88aea87 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/expression.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/expression.rs @@ -23,14 +23,14 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { match expr { Expr::Subscript(subscript @ ast::ExprSubscript { value, slice, .. }) => { // Ex) Optional[...], Union[...] - if checker.any_enabled(&[ + 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.enabled(Rule::FutureRewritableTypeAnnotation) { + if checker.is_rule_enabled(Rule::FutureRewritableTypeAnnotation) { if !checker.semantic.future_annotations_or_stub() && checker.target_version() < PythonVersion::PY310 && checker.target_version() >= PythonVersion::PY37 @@ -42,7 +42,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::NonPEP604AnnotationUnion, Rule::NonPEP604AnnotationOptional, ]) { @@ -60,7 +60,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } // Ex) list[...] - if checker.enabled(Rule::FutureRequiredTypeAnnotation) { + if checker.is_rule_enabled(Rule::FutureRequiredTypeAnnotation) { if !checker.semantic.future_annotations_or_stub() && checker.target_version() < PythonVersion::PY39 && checker.semantic.in_annotation() @@ -77,7 +77,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } // Ex) Union[...] - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::UnnecessaryLiteralUnion, Rule::DuplicateUnionMember, Rule::RedundantLiteralUnion, @@ -87,58 +87,58 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { // Avoid duplicate checks if the parent is a union, since these rules already // traverse nested unions. if !checker.semantic.in_nested_union() { - if checker.enabled(Rule::UnnecessaryLiteralUnion) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralUnion) { flake8_pyi::rules::unnecessary_literal_union(checker, expr); } - if checker.enabled(Rule::DuplicateUnionMember) { + if checker.is_rule_enabled(Rule::DuplicateUnionMember) { flake8_pyi::rules::duplicate_union_member(checker, expr); } - if checker.enabled(Rule::RedundantLiteralUnion) { + if checker.is_rule_enabled(Rule::RedundantLiteralUnion) { flake8_pyi::rules::redundant_literal_union(checker, expr); } - if checker.enabled(Rule::UnnecessaryTypeUnion) { + if checker.is_rule_enabled(Rule::UnnecessaryTypeUnion) { flake8_pyi::rules::unnecessary_type_union(checker, expr); } - if checker.enabled(Rule::NoneNotAtEndOfUnion) { + if checker.is_rule_enabled(Rule::NoneNotAtEndOfUnion) { ruff::rules::none_not_at_end_of_union(checker, expr); } } } // Ex) Literal[...] - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::DuplicateLiteralMember, Rule::RedundantBoolLiteral, Rule::RedundantNoneLiteral, Rule::UnnecessaryNestedLiteral, ]) { if !checker.semantic.in_nested_literal() { - if checker.enabled(Rule::DuplicateLiteralMember) { + if checker.is_rule_enabled(Rule::DuplicateLiteralMember) { flake8_pyi::rules::duplicate_literal_member(checker, expr); } - if checker.enabled(Rule::RedundantBoolLiteral) { + if checker.is_rule_enabled(Rule::RedundantBoolLiteral) { ruff::rules::redundant_bool_literal(checker, expr); } - if checker.enabled(Rule::RedundantNoneLiteral) { + if checker.is_rule_enabled(Rule::RedundantNoneLiteral) { flake8_pyi::rules::redundant_none_literal(checker, expr); } - if checker.enabled(Rule::UnnecessaryNestedLiteral) { + if checker.is_rule_enabled(Rule::UnnecessaryNestedLiteral) { ruff::rules::unnecessary_nested_literal(checker, expr); } } } - if checker.enabled(Rule::NeverUnion) { + if checker.is_rule_enabled(Rule::NeverUnion) { ruff::rules::never_union(checker, expr); } - if checker.enabled(Rule::UnnecessaryDefaultTypeArgs) { + if checker.is_rule_enabled(Rule::UnnecessaryDefaultTypeArgs) { if checker.target_version() >= PythonVersion::PY313 { pyupgrade::rules::unnecessary_default_type_args(checker, expr); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SysVersionSlice3, Rule::SysVersion2, Rule::SysVersion0, @@ -146,40 +146,40 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ]) { flake8_2020::rules::subscript(checker, value, slice); } - if checker.enabled(Rule::UncapitalizedEnvironmentVariables) { + if checker.is_rule_enabled(Rule::UncapitalizedEnvironmentVariables) { flake8_simplify::rules::use_capital_environment_variables(checker, expr); } - if checker.enabled(Rule::UnnecessaryIterableAllocationForFirstElement) { + if checker.is_rule_enabled(Rule::UnnecessaryIterableAllocationForFirstElement) { ruff::rules::unnecessary_iterable_allocation_for_first_element(checker, expr); } - if checker.enabled(Rule::InvalidIndexType) { + if checker.is_rule_enabled(Rule::InvalidIndexType) { ruff::rules::invalid_index_type(checker, subscript); } - if checker.enabled(Rule::SliceCopy) { + if checker.is_rule_enabled(Rule::SliceCopy) { refurb::rules::slice_copy(checker, subscript); } - if checker.enabled(Rule::PotentialIndexError) { + if checker.is_rule_enabled(Rule::PotentialIndexError) { pylint::rules::potential_index_error(checker, value, slice); } - if checker.enabled(Rule::SortedMinMax) { + if checker.is_rule_enabled(Rule::SortedMinMax) { refurb::rules::sorted_min_max(checker, subscript); } - if checker.enabled(Rule::FStringNumberFormat) { + if checker.is_rule_enabled(Rule::FStringNumberFormat) { refurb::rules::fstring_number_format(checker, subscript); } - if checker.enabled(Rule::IncorrectlyParenthesizedTupleInSubscript) { + if checker.is_rule_enabled(Rule::IncorrectlyParenthesizedTupleInSubscript) { ruff::rules::subscript_with_parenthesized_tuple(checker, subscript); } - if checker.enabled(Rule::NonPEP646Unpack) { + if checker.is_rule_enabled(Rule::NonPEP646Unpack) { pyupgrade::rules::use_pep646_unpack(checker, subscript); } - if checker.enabled(Rule::Airflow3Removal) { + if checker.is_rule_enabled(Rule::Airflow3Removal) { airflow::rules::airflow_3_removal_expr(checker, expr); } - if checker.enabled(Rule::MissingMaxsplitArg) { + if checker.is_rule_enabled(Rule::MissingMaxsplitArg) { pylint::rules::missing_maxsplit_arg(checker, value, slice, expr); } - if checker.enabled(Rule::AccessAnnotationsFromClassDict) { + 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); @@ -198,9 +198,10 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }) => { if ctx.is_store() { - let check_too_many_expressions = checker.enabled(Rule::ExpressionsInStarAssignment); + let check_too_many_expressions = + checker.is_rule_enabled(Rule::ExpressionsInStarAssignment); let check_two_starred_expressions = - checker.enabled(Rule::MultipleStarredExpressions); + checker.is_rule_enabled(Rule::MultipleStarredExpressions); pyflakes::rules::starred_expressions( checker, elts, @@ -218,37 +219,37 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { }) => { match ctx { ExprContext::Load => { - if checker.enabled(Rule::TypingTextStrAlias) { + if checker.is_rule_enabled(Rule::TypingTextStrAlias) { pyupgrade::rules::typing_text_str_alias(checker, expr); } - if checker.enabled(Rule::NumpyDeprecatedTypeAlias) { + if checker.is_rule_enabled(Rule::NumpyDeprecatedTypeAlias) { numpy::rules::deprecated_type_alias(checker, expr); } - if checker.enabled(Rule::NumpyDeprecatedFunction) { + if checker.is_rule_enabled(Rule::NumpyDeprecatedFunction) { numpy::rules::deprecated_function(checker, expr); } - if checker.enabled(Rule::Numpy2Deprecation) { + if checker.is_rule_enabled(Rule::Numpy2Deprecation) { numpy::rules::numpy_2_0_deprecation(checker, expr); } - if checker.enabled(Rule::CollectionsNamedTuple) { + if checker.is_rule_enabled(Rule::CollectionsNamedTuple) { flake8_pyi::rules::collections_named_tuple(checker, expr); } - if checker.enabled(Rule::RegexFlagAlias) { + if checker.is_rule_enabled(Rule::RegexFlagAlias) { refurb::rules::regex_flag_alias(checker, expr); } - if checker.enabled(Rule::Airflow3Removal) { + if checker.is_rule_enabled(Rule::Airflow3Removal) { airflow::rules::airflow_3_removal_expr(checker, expr); } - if checker.enabled(Rule::Airflow3SuggestedUpdate) { + if checker.is_rule_enabled(Rule::Airflow3SuggestedUpdate) { airflow::rules::airflow_3_0_suggested_update_expr(checker, expr); } - if checker.enabled(Rule::Airflow3MovedToProvider) { + if checker.is_rule_enabled(Rule::Airflow3MovedToProvider) { airflow::rules::moved_to_provider_in_3(checker, expr); } - if checker.enabled(Rule::Airflow3SuggestedToMoveToProvider) { + if checker.is_rule_enabled(Rule::Airflow3SuggestedToMoveToProvider) { airflow::rules::suggested_to_move_to_provider_in_3(checker, expr); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SuspiciousPickleUsage, Rule::SuspiciousMarshalUsage, Rule::SuspiciousInsecureHashUsage, @@ -275,14 +276,14 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } // Ex) List[...] - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::FutureRewritableTypeAnnotation, Rule::NonPEP585Annotation, ]) { if let Some(replacement) = typing::to_pep585_generic(expr, &checker.semantic) { - if checker.enabled(Rule::FutureRewritableTypeAnnotation) { + if checker.is_rule_enabled(Rule::FutureRewritableTypeAnnotation) { if !checker.semantic.future_annotations_or_stub() && checker.target_version() < PythonVersion::PY39 && checker.target_version() >= PythonVersion::PY37 @@ -292,7 +293,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { flake8_future_annotations::rules::future_rewritable_type_annotation(checker, expr); } } - if checker.enabled(Rule::NonPEP585Annotation) { + if checker.is_rule_enabled(Rule::NonPEP585Annotation) { if checker.source_type.is_stub() || checker.target_version() >= PythonVersion::PY39 || (checker.target_version() >= PythonVersion::PY37 @@ -311,14 +312,14 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } ExprContext::Store => { - if checker.enabled(Rule::NonLowercaseVariableInFunction) { + 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.enabled(Rule::MixedCaseVariableInClassScope) { + 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( @@ -326,37 +327,37 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ); } } - if checker.enabled(Rule::Airflow3Removal) { + if checker.is_rule_enabled(Rule::Airflow3Removal) { airflow::rules::airflow_3_removal_expr(checker, expr); } - if checker.enabled(Rule::MixedCaseVariableInGlobalScope) { + 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.enabled(Rule::AmbiguousVariableName) { + 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.enabled(Rule::BuiltinVariableShadowing) { + if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) { flake8_builtins::rules::builtin_variable_shadowing(checker, id, *range); } } } _ => {} } - if checker.enabled(Rule::SixPY3) { + if checker.is_rule_enabled(Rule::SixPY3) { flake8_2020::rules::name_or_attribute(checker, expr); } - if checker.enabled(Rule::UndocumentedWarn) { + 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_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SuspiciousPickleUsage, Rule::SuspiciousMarshalUsage, Rule::SuspiciousInsecureHashUsage, @@ -384,12 +385,12 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } // Ex) typing.List[...] - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::FutureRewritableTypeAnnotation, Rule::NonPEP585Annotation, ]) { if let Some(replacement) = typing::to_pep585_generic(expr, &checker.semantic) { - if checker.enabled(Rule::FutureRewritableTypeAnnotation) { + if checker.is_rule_enabled(Rule::FutureRewritableTypeAnnotation) { if !checker.semantic.future_annotations_or_stub() && checker.target_version() < PythonVersion::PY39 && checker.target_version() >= PythonVersion::PY37 @@ -401,7 +402,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ); } } - if checker.enabled(Rule::NonPEP585Annotation) { + if checker.is_rule_enabled(Rule::NonPEP585Annotation) { if checker.source_type.is_stub() || checker.target_version() >= PythonVersion::PY39 || (checker.target_version() >= PythonVersion::PY37 @@ -414,63 +415,63 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } } - if checker.enabled(Rule::RegexFlagAlias) { + if checker.is_rule_enabled(Rule::RegexFlagAlias) { refurb::rules::regex_flag_alias(checker, expr); } - if checker.enabled(Rule::DatetimeTimezoneUTC) { + if checker.is_rule_enabled(Rule::DatetimeTimezoneUTC) { if checker.target_version() >= PythonVersion::PY311 { pyupgrade::rules::datetime_utc_alias(checker, expr); } } - if checker.enabled(Rule::TypingTextStrAlias) { + if checker.is_rule_enabled(Rule::TypingTextStrAlias) { pyupgrade::rules::typing_text_str_alias(checker, expr); } - if checker.enabled(Rule::NumpyDeprecatedTypeAlias) { + if checker.is_rule_enabled(Rule::NumpyDeprecatedTypeAlias) { numpy::rules::deprecated_type_alias(checker, expr); } - if checker.enabled(Rule::NumpyDeprecatedFunction) { + if checker.is_rule_enabled(Rule::NumpyDeprecatedFunction) { numpy::rules::deprecated_function(checker, expr); } - if checker.enabled(Rule::Numpy2Deprecation) { + if checker.is_rule_enabled(Rule::Numpy2Deprecation) { numpy::rules::numpy_2_0_deprecation(checker, expr); } - if checker.enabled(Rule::DeprecatedMockImport) { + if checker.is_rule_enabled(Rule::DeprecatedMockImport) { pyupgrade::rules::deprecated_mock_attribute(checker, attribute); } - if checker.enabled(Rule::SixPY3) { + if checker.is_rule_enabled(Rule::SixPY3) { flake8_2020::rules::name_or_attribute(checker, expr); } - if checker.enabled(Rule::DatetimeMinMax) { + if checker.is_rule_enabled(Rule::DatetimeMinMax) { flake8_datetimez::rules::datetime_min_max(checker, expr); } - if checker.enabled(Rule::BannedApi) { + if checker.is_rule_enabled(Rule::BannedApi) { flake8_tidy_imports::rules::banned_attribute_access(checker, expr); } - if checker.enabled(Rule::PrivateMemberAccess) { + if checker.is_rule_enabled(Rule::PrivateMemberAccess) { flake8_self::rules::private_member_access(checker, expr); } - if checker.enabled(Rule::CollectionsNamedTuple) { + if checker.is_rule_enabled(Rule::CollectionsNamedTuple) { flake8_pyi::rules::collections_named_tuple(checker, expr); } - if checker.enabled(Rule::UndocumentedWarn) { + if checker.is_rule_enabled(Rule::UndocumentedWarn) { flake8_logging::rules::undocumented_warn(checker, expr); } - if checker.enabled(Rule::PandasUseOfDotValues) { + if checker.is_rule_enabled(Rule::PandasUseOfDotValues) { pandas_vet::rules::attr(checker, attribute); } - if checker.enabled(Rule::ByteStringUsage) { + if checker.is_rule_enabled(Rule::ByteStringUsage) { flake8_pyi::rules::bytestring_attribute(checker, expr); } - if checker.enabled(Rule::Airflow3Removal) { + if checker.is_rule_enabled(Rule::Airflow3Removal) { airflow::rules::airflow_3_removal_expr(checker, expr); } - if checker.enabled(Rule::Airflow3SuggestedUpdate) { + if checker.is_rule_enabled(Rule::Airflow3SuggestedUpdate) { airflow::rules::airflow_3_0_suggested_update_expr(checker, expr); } - if checker.enabled(Rule::Airflow3MovedToProvider) { + if checker.is_rule_enabled(Rule::Airflow3MovedToProvider) { airflow::rules::moved_to_provider_in_3(checker, expr); } - if checker.enabled(Rule::Airflow3SuggestedToMoveToProvider) { + if checker.is_rule_enabled(Rule::Airflow3SuggestedToMoveToProvider) { airflow::rules::suggested_to_move_to_provider_in_3(checker, expr); } } @@ -488,7 +489,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ // pylint Rule::BadStringFormatCharacter, // pyflakes @@ -516,7 +517,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { { if attr == "join" { // "...".join(...) call - if checker.enabled(Rule::StaticJoinToFString) { + if checker.is_rule_enabled(Rule::StaticJoinToFString) { flynt::rules::static_join_to_fstring( checker, expr, @@ -525,7 +526,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } else if matches!(attr, "split" | "rsplit") { // "...".split(...) call - if checker.enabled(Rule::SplitStaticString) { + if checker.is_rule_enabled(Rule::SplitStaticString) { flake8_simplify::rules::split_static_string( checker, attr, @@ -538,7 +539,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { let location = expr.range(); match pyflakes::format::FormatSummary::try_from(string_value.to_str()) { Err(e) => { - if checker.enabled(Rule::StringDotFormatInvalidFormat) { + if checker.is_rule_enabled(Rule::StringDotFormatInvalidFormat) { checker.report_diagnostic( pyflakes::rules::StringDotFormatInvalidFormat { message: pyflakes::format::error_to_string(&e), @@ -548,38 +549,43 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } Ok(summary) => { - if checker.enabled(Rule::StringDotFormatExtraNamedArguments) { + if checker + .is_rule_enabled(Rule::StringDotFormatExtraNamedArguments) + { pyflakes::rules::string_dot_format_extra_named_arguments( checker, call, &summary, keywords, ); } - if checker - .enabled(Rule::StringDotFormatExtraPositionalArguments) - { + if checker.is_rule_enabled( + Rule::StringDotFormatExtraPositionalArguments, + ) { pyflakes::rules::string_dot_format_extra_positional_arguments( checker, call, &summary, args, ); } - if checker.enabled(Rule::StringDotFormatMissingArguments) { + if checker + .is_rule_enabled(Rule::StringDotFormatMissingArguments) + { pyflakes::rules::string_dot_format_missing_argument( checker, call, &summary, args, keywords, ); } - if checker.enabled(Rule::StringDotFormatMixingAutomatic) { + if checker.is_rule_enabled(Rule::StringDotFormatMixingAutomatic) + { pyflakes::rules::string_dot_format_mixing_automatic( checker, call, &summary, ); } - if checker.enabled(Rule::FormatLiterals) { + if checker.is_rule_enabled(Rule::FormatLiterals) { pyupgrade::rules::format_literals(checker, call, &summary); } - if checker.enabled(Rule::FString) { + if checker.is_rule_enabled(Rule::FString) { pyupgrade::rules::f_strings(checker, call, &summary); } } } - if checker.enabled(Rule::BadStringFormatCharacter) { + if checker.is_rule_enabled(Rule::BadStringFormatCharacter) { pylint::rules::bad_string_format_character::call( checker, string_value.to_str(), @@ -590,82 +596,82 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } } - if checker.enabled(Rule::SuperWithoutBrackets) { + if checker.is_rule_enabled(Rule::SuperWithoutBrackets) { pylint::rules::super_without_brackets(checker, func); } - if checker.enabled(Rule::LenTest) { + if checker.is_rule_enabled(Rule::LenTest) { pylint::rules::len_test(checker, call); } - if checker.enabled(Rule::BitCount) { + if checker.is_rule_enabled(Rule::BitCount) { refurb::rules::bit_count(checker, call); } - if checker.enabled(Rule::TypeOfPrimitive) { + if checker.is_rule_enabled(Rule::TypeOfPrimitive) { pyupgrade::rules::type_of_primitive(checker, expr, func, args); } - if checker.enabled(Rule::DeprecatedUnittestAlias) { + if checker.is_rule_enabled(Rule::DeprecatedUnittestAlias) { pyupgrade::rules::deprecated_unittest_alias(checker, func); } - if checker.enabled(Rule::SuperCallWithParameters) { + if checker.is_rule_enabled(Rule::SuperCallWithParameters) { pyupgrade::rules::super_call_with_parameters(checker, call); } - if checker.enabled(Rule::UnnecessaryEncodeUTF8) { + if checker.is_rule_enabled(Rule::UnnecessaryEncodeUTF8) { pyupgrade::rules::unnecessary_encode_utf8(checker, call); } - if checker.enabled(Rule::RedundantOpenModes) { + if checker.is_rule_enabled(Rule::RedundantOpenModes) { pyupgrade::rules::redundant_open_modes(checker, call); } - if checker.enabled(Rule::NativeLiterals) { + if checker.is_rule_enabled(Rule::NativeLiterals) { pyupgrade::rules::native_literals( checker, call, checker.semantic().current_expression_parent(), ); } - if checker.enabled(Rule::OpenAlias) { + if checker.is_rule_enabled(Rule::OpenAlias) { pyupgrade::rules::open_alias(checker, expr, func); } - if checker.enabled(Rule::ReplaceUniversalNewlines) { + if checker.is_rule_enabled(Rule::ReplaceUniversalNewlines) { pyupgrade::rules::replace_universal_newlines(checker, call); } - if checker.enabled(Rule::ReplaceStdoutStderr) { + if checker.is_rule_enabled(Rule::ReplaceStdoutStderr) { pyupgrade::rules::replace_stdout_stderr(checker, call); } - if checker.enabled(Rule::OSErrorAlias) { + if checker.is_rule_enabled(Rule::OSErrorAlias) { pyupgrade::rules::os_error_alias_call(checker, func); } - if checker.enabled(Rule::TimeoutErrorAlias) { + if checker.is_rule_enabled(Rule::TimeoutErrorAlias) { if checker.target_version() >= PythonVersion::PY310 { pyupgrade::rules::timeout_error_alias_call(checker, func); } } - if checker.enabled(Rule::NonPEP604Isinstance) { + if checker.is_rule_enabled(Rule::NonPEP604Isinstance) { if checker.target_version() >= PythonVersion::PY310 { pyupgrade::rules::use_pep604_isinstance(checker, expr, func, args); } } - if checker.enabled(Rule::BlockingHttpCallInAsyncFunction) { + if checker.is_rule_enabled(Rule::BlockingHttpCallInAsyncFunction) { flake8_async::rules::blocking_http_call(checker, call); } - if checker.enabled(Rule::BlockingOpenCallInAsyncFunction) { + if checker.is_rule_enabled(Rule::BlockingOpenCallInAsyncFunction) { flake8_async::rules::blocking_open_call(checker, call); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::CreateSubprocessInAsyncFunction, Rule::RunProcessInAsyncFunction, Rule::WaitForProcessInAsyncFunction, ]) { flake8_async::rules::blocking_process_invocation(checker, call); } - if checker.enabled(Rule::BlockingSleepInAsyncFunction) { + if checker.is_rule_enabled(Rule::BlockingSleepInAsyncFunction) { flake8_async::rules::blocking_sleep(checker, call); } - if checker.enabled(Rule::LongSleepNotForever) { + if checker.is_rule_enabled(Rule::LongSleepNotForever) { flake8_async::rules::long_sleep_not_forever(checker, call); } - if checker.any_enabled(&[Rule::Print, Rule::PPrint]) { + if checker.any_rule_enabled(&[Rule::Print, Rule::PPrint]) { flake8_print::rules::print_call(checker, call); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SuspiciousPickleUsage, Rule::SuspiciousMarshalUsage, Rule::SuspiciousInsecureHashUsage, @@ -690,101 +696,101 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ]) { flake8_bandit::rules::suspicious_function_call(checker, call); } - if checker.enabled(Rule::ReSubPositionalArgs) { + if checker.is_rule_enabled(Rule::ReSubPositionalArgs) { flake8_bugbear::rules::re_sub_positional_args(checker, call); } - if checker.enabled(Rule::UnreliableCallableCheck) { + if checker.is_rule_enabled(Rule::UnreliableCallableCheck) { flake8_bugbear::rules::unreliable_callable_check(checker, expr, func, args); } - if checker.enabled(Rule::StripWithMultiCharacters) { + if checker.is_rule_enabled(Rule::StripWithMultiCharacters) { flake8_bugbear::rules::strip_with_multi_characters(checker, expr, func, args); } - if checker.enabled(Rule::GetAttrWithConstant) { + if checker.is_rule_enabled(Rule::GetAttrWithConstant) { flake8_bugbear::rules::getattr_with_constant(checker, expr, func, args); } - if checker.enabled(Rule::SetAttrWithConstant) { + if checker.is_rule_enabled(Rule::SetAttrWithConstant) { flake8_bugbear::rules::setattr_with_constant(checker, expr, func, args); } - if checker.enabled(Rule::UselessContextlibSuppress) { + if checker.is_rule_enabled(Rule::UselessContextlibSuppress) { flake8_bugbear::rules::useless_contextlib_suppress(checker, expr, func, args); } - if checker.enabled(Rule::StarArgUnpackingAfterKeywordArg) { + if checker.is_rule_enabled(Rule::StarArgUnpackingAfterKeywordArg) { flake8_bugbear::rules::star_arg_unpacking_after_keyword_arg( checker, args, keywords, ); } - if checker.enabled(Rule::ZipWithoutExplicitStrict) { + if checker.is_rule_enabled(Rule::ZipWithoutExplicitStrict) { if checker.target_version() >= PythonVersion::PY310 { flake8_bugbear::rules::zip_without_explicit_strict(checker, call); } } - if checker.enabled(Rule::NoExplicitStacklevel) { + if checker.is_rule_enabled(Rule::NoExplicitStacklevel) { flake8_bugbear::rules::no_explicit_stacklevel(checker, call); } - if checker.enabled(Rule::MutableContextvarDefault) { + if checker.is_rule_enabled(Rule::MutableContextvarDefault) { flake8_bugbear::rules::mutable_contextvar_default(checker, call); } - if checker.enabled(Rule::UnnecessaryDictKwargs) { + if checker.is_rule_enabled(Rule::UnnecessaryDictKwargs) { flake8_pie::rules::unnecessary_dict_kwargs(checker, call); } - if checker.enabled(Rule::UnnecessaryRangeStart) { + if checker.is_rule_enabled(Rule::UnnecessaryRangeStart) { flake8_pie::rules::unnecessary_range_start(checker, call); } - if checker.enabled(Rule::ExecBuiltin) { + if checker.is_rule_enabled(Rule::ExecBuiltin) { flake8_bandit::rules::exec_used(checker, func); } - if checker.enabled(Rule::BadFilePermissions) { + if checker.is_rule_enabled(Rule::BadFilePermissions) { flake8_bandit::rules::bad_file_permissions(checker, call); } - if checker.enabled(Rule::RequestWithNoCertValidation) { + if checker.is_rule_enabled(Rule::RequestWithNoCertValidation) { flake8_bandit::rules::request_with_no_cert_validation(checker, call); } - if checker.enabled(Rule::UnsafeYAMLLoad) { + if checker.is_rule_enabled(Rule::UnsafeYAMLLoad) { flake8_bandit::rules::unsafe_yaml_load(checker, call); } - if checker.enabled(Rule::SnmpInsecureVersion) { + if checker.is_rule_enabled(Rule::SnmpInsecureVersion) { flake8_bandit::rules::snmp_insecure_version(checker, call); } - if checker.enabled(Rule::SnmpWeakCryptography) { + if checker.is_rule_enabled(Rule::SnmpWeakCryptography) { flake8_bandit::rules::snmp_weak_cryptography(checker, call); } - if checker.enabled(Rule::Jinja2AutoescapeFalse) { + if checker.is_rule_enabled(Rule::Jinja2AutoescapeFalse) { flake8_bandit::rules::jinja2_autoescape_false(checker, call); } - if checker.enabled(Rule::MakoTemplates) { + if checker.is_rule_enabled(Rule::MakoTemplates) { flake8_bandit::rules::mako_templates(checker, call); } - if checker.enabled(Rule::HardcodedPasswordFuncArg) { + if checker.is_rule_enabled(Rule::HardcodedPasswordFuncArg) { flake8_bandit::rules::hardcoded_password_func_arg(checker, keywords); } - if checker.enabled(Rule::HardcodedSQLExpression) { + if checker.is_rule_enabled(Rule::HardcodedSQLExpression) { flake8_bandit::rules::hardcoded_sql_expression(checker, expr); } - if checker.enabled(Rule::HashlibInsecureHashFunction) { + if checker.is_rule_enabled(Rule::HashlibInsecureHashFunction) { flake8_bandit::rules::hashlib_insecure_hash_functions(checker, call); } - if checker.enabled(Rule::HashlibDigestHex) { + if checker.is_rule_enabled(Rule::HashlibDigestHex) { refurb::rules::hashlib_digest_hex(checker, call); } - if checker.enabled(Rule::RequestWithoutTimeout) { + if checker.is_rule_enabled(Rule::RequestWithoutTimeout) { flake8_bandit::rules::request_without_timeout(checker, call); } - if checker.enabled(Rule::ParamikoCall) { + if checker.is_rule_enabled(Rule::ParamikoCall) { flake8_bandit::rules::paramiko_call(checker, func); } - if checker.enabled(Rule::SSHNoHostKeyVerification) { + if checker.is_rule_enabled(Rule::SSHNoHostKeyVerification) { flake8_bandit::rules::ssh_no_host_key_verification(checker, call); } - if checker.enabled(Rule::LoggingConfigInsecureListen) { + if checker.is_rule_enabled(Rule::LoggingConfigInsecureListen) { flake8_bandit::rules::logging_config_insecure_listen(checker, call); } - if checker.enabled(Rule::FlaskDebugTrue) { + if checker.is_rule_enabled(Rule::FlaskDebugTrue) { flake8_bandit::rules::flask_debug_true(checker, call); } - if checker.enabled(Rule::WeakCryptographicKey) { + if checker.is_rule_enabled(Rule::WeakCryptographicKey) { flake8_bandit::rules::weak_cryptographic_key(checker, call); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SubprocessWithoutShellEqualsTrue, Rule::SubprocessPopenWithShellEqualsTrue, Rule::CallWithShellEqualsTrue, @@ -795,204 +801,206 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ]) { flake8_bandit::rules::shell_injection(checker, call); } - if checker.enabled(Rule::DjangoExtra) { + if checker.is_rule_enabled(Rule::DjangoExtra) { flake8_bandit::rules::django_extra(checker, call); } - if checker.enabled(Rule::DjangoRawSql) { + if checker.is_rule_enabled(Rule::DjangoRawSql) { flake8_bandit::rules::django_raw_sql(checker, call); } - if checker.enabled(Rule::TarfileUnsafeMembers) { + if checker.is_rule_enabled(Rule::TarfileUnsafeMembers) { flake8_bandit::rules::tarfile_unsafe_members(checker, call); } - if checker.enabled(Rule::UnnecessaryGeneratorList) { + if checker.is_rule_enabled(Rule::UnnecessaryGeneratorList) { flake8_comprehensions::rules::unnecessary_generator_list(checker, call); } - if checker.enabled(Rule::UnnecessaryGeneratorSet) { + if checker.is_rule_enabled(Rule::UnnecessaryGeneratorSet) { flake8_comprehensions::rules::unnecessary_generator_set(checker, call); } - if checker.enabled(Rule::UnnecessaryGeneratorDict) { + if checker.is_rule_enabled(Rule::UnnecessaryGeneratorDict) { flake8_comprehensions::rules::unnecessary_generator_dict( checker, expr, func, args, keywords, ); } - if checker.enabled(Rule::UnnecessaryListComprehensionSet) { + if checker.is_rule_enabled(Rule::UnnecessaryListComprehensionSet) { flake8_comprehensions::rules::unnecessary_list_comprehension_set(checker, call); } - if checker.enabled(Rule::UnnecessaryListComprehensionDict) { + if checker.is_rule_enabled(Rule::UnnecessaryListComprehensionDict) { flake8_comprehensions::rules::unnecessary_list_comprehension_dict( checker, expr, func, args, keywords, ); } - if checker.enabled(Rule::UnnecessaryLiteralSet) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralSet) { flake8_comprehensions::rules::unnecessary_literal_set(checker, call); } - if checker.enabled(Rule::UnnecessaryLiteralDict) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralDict) { flake8_comprehensions::rules::unnecessary_literal_dict( checker, expr, func, args, keywords, ); } - if checker.enabled(Rule::UnnecessaryCollectionCall) { + if checker.is_rule_enabled(Rule::UnnecessaryCollectionCall) { flake8_comprehensions::rules::unnecessary_collection_call( checker, call, &checker.settings.flake8_comprehensions, ); } - if checker.enabled(Rule::UnnecessaryLiteralWithinTupleCall) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralWithinTupleCall) { flake8_comprehensions::rules::unnecessary_literal_within_tuple_call( checker, expr, call, ); } - if checker.enabled(Rule::UnnecessaryLiteralWithinListCall) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralWithinListCall) { flake8_comprehensions::rules::unnecessary_literal_within_list_call(checker, call); } - if checker.enabled(Rule::UnnecessaryLiteralWithinDictCall) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralWithinDictCall) { flake8_comprehensions::rules::unnecessary_literal_within_dict_call(checker, call); } - if checker.enabled(Rule::UnnecessaryListCall) { + if checker.is_rule_enabled(Rule::UnnecessaryListCall) { flake8_comprehensions::rules::unnecessary_list_call(checker, expr, call); } - if checker.enabled(Rule::UnnecessaryCallAroundSorted) { + if checker.is_rule_enabled(Rule::UnnecessaryCallAroundSorted) { flake8_comprehensions::rules::unnecessary_call_around_sorted( checker, expr, func, args, ); } - if checker.enabled(Rule::UnnecessaryDoubleCastOrProcess) { + if checker.is_rule_enabled(Rule::UnnecessaryDoubleCastOrProcess) { flake8_comprehensions::rules::unnecessary_double_cast_or_process( checker, expr, func, args, keywords, ); } - if checker.enabled(Rule::UnnecessarySubscriptReversal) { + if checker.is_rule_enabled(Rule::UnnecessarySubscriptReversal) { flake8_comprehensions::rules::unnecessary_subscript_reversal(checker, call); } - if checker.enabled(Rule::UnnecessaryMap) { + if checker.is_rule_enabled(Rule::UnnecessaryMap) { flake8_comprehensions::rules::unnecessary_map(checker, call); } - if checker.enabled(Rule::UnnecessaryComprehensionInCall) { + if checker.is_rule_enabled(Rule::UnnecessaryComprehensionInCall) { flake8_comprehensions::rules::unnecessary_comprehension_in_call( checker, expr, func, args, keywords, ); } - if checker.enabled(Rule::BooleanPositionalValueInCall) { + if checker.is_rule_enabled(Rule::BooleanPositionalValueInCall) { flake8_boolean_trap::rules::boolean_positional_value_in_call(checker, call); } - if checker.enabled(Rule::Debugger) { + if checker.is_rule_enabled(Rule::Debugger) { flake8_debugger::rules::debugger_call(checker, expr, func); } - if checker.enabled(Rule::PandasUseOfInplaceArgument) { + if checker.is_rule_enabled(Rule::PandasUseOfInplaceArgument) { pandas_vet::rules::inplace_argument(checker, call); } pandas_vet::rules::call(checker, func); - if checker.enabled(Rule::PandasUseOfDotReadTable) { + if checker.is_rule_enabled(Rule::PandasUseOfDotReadTable) { pandas_vet::rules::use_of_read_table(checker, call); } - if checker.enabled(Rule::PandasUseOfPdMerge) { + if checker.is_rule_enabled(Rule::PandasUseOfPdMerge) { pandas_vet::rules::use_of_pd_merge(checker, func); } - if checker.enabled(Rule::CallDatetimeWithoutTzinfo) { + if checker.is_rule_enabled(Rule::CallDatetimeWithoutTzinfo) { flake8_datetimez::rules::call_datetime_without_tzinfo(checker, call); } - if checker.enabled(Rule::CallDatetimeToday) { + if checker.is_rule_enabled(Rule::CallDatetimeToday) { flake8_datetimez::rules::call_datetime_today(checker, func, expr.range()); } - if checker.enabled(Rule::CallDatetimeUtcnow) { + if checker.is_rule_enabled(Rule::CallDatetimeUtcnow) { flake8_datetimez::rules::call_datetime_utcnow(checker, func, expr.range()); } - if checker.enabled(Rule::CallDatetimeUtcfromtimestamp) { + if checker.is_rule_enabled(Rule::CallDatetimeUtcfromtimestamp) { flake8_datetimez::rules::call_datetime_utcfromtimestamp( checker, func, expr.range(), ); } - if checker.enabled(Rule::CallDatetimeNowWithoutTzinfo) { + if checker.is_rule_enabled(Rule::CallDatetimeNowWithoutTzinfo) { flake8_datetimez::rules::call_datetime_now_without_tzinfo(checker, call); } - if checker.enabled(Rule::CallDatetimeFromtimestamp) { + if checker.is_rule_enabled(Rule::CallDatetimeFromtimestamp) { flake8_datetimez::rules::call_datetime_fromtimestamp(checker, call); } - if checker.enabled(Rule::CallDatetimeStrptimeWithoutZone) { + if checker.is_rule_enabled(Rule::CallDatetimeStrptimeWithoutZone) { flake8_datetimez::rules::call_datetime_strptime_without_zone(checker, call); } - if checker.enabled(Rule::CallDateToday) { + if checker.is_rule_enabled(Rule::CallDateToday) { flake8_datetimez::rules::call_date_today(checker, func, expr.range()); } - if checker.enabled(Rule::CallDateFromtimestamp) { + if checker.is_rule_enabled(Rule::CallDateFromtimestamp) { flake8_datetimez::rules::call_date_fromtimestamp(checker, func, expr.range()); } - if checker.enabled(Rule::UnnecessaryDirectLambdaCall) { + if checker.is_rule_enabled(Rule::UnnecessaryDirectLambdaCall) { pylint::rules::unnecessary_direct_lambda_call(checker, expr, func); } - if checker.enabled(Rule::SysExitAlias) { + if checker.is_rule_enabled(Rule::SysExitAlias) { pylint::rules::sys_exit_alias(checker, call); } - if checker.enabled(Rule::BadOpenMode) { + if checker.is_rule_enabled(Rule::BadOpenMode) { pylint::rules::bad_open_mode(checker, call); } - if checker.enabled(Rule::BadStrStripCall) { + if checker.is_rule_enabled(Rule::BadStrStripCall) { pylint::rules::bad_str_strip_call(checker, call); } - if checker.enabled(Rule::ShallowCopyEnviron) { + if checker.is_rule_enabled(Rule::ShallowCopyEnviron) { pylint::rules::shallow_copy_environ(checker, call); } - if checker.enabled(Rule::InvalidEnvvarDefault) { + if checker.is_rule_enabled(Rule::InvalidEnvvarDefault) { pylint::rules::invalid_envvar_default(checker, call); } - if checker.enabled(Rule::InvalidEnvvarValue) { + if checker.is_rule_enabled(Rule::InvalidEnvvarValue) { pylint::rules::invalid_envvar_value(checker, call); } - if checker.enabled(Rule::NestedMinMax) { + if checker.is_rule_enabled(Rule::NestedMinMax) { pylint::rules::nested_min_max(checker, expr, func, args, keywords); } - if checker.enabled(Rule::RepeatedKeywordArgument) { + if checker.is_rule_enabled(Rule::RepeatedKeywordArgument) { pylint::rules::repeated_keyword_argument(checker, call); } - if checker.enabled(Rule::PytestPatchWithLambda) { + if checker.is_rule_enabled(Rule::PytestPatchWithLambda) { flake8_pytest_style::rules::patch_with_lambda(checker, call); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::PytestParametrizeNamesWrongType, Rule::PytestParametrizeValuesWrongType, Rule::PytestDuplicateParametrizeTestCases, ]) { flake8_pytest_style::rules::parametrize(checker, call); } - if checker.enabled(Rule::PytestUnittestAssertion) { + if checker.is_rule_enabled(Rule::PytestUnittestAssertion) { flake8_pytest_style::rules::unittest_assertion(checker, expr, func, args, keywords); } - if checker.enabled(Rule::PytestUnittestRaisesAssertion) { + if checker.is_rule_enabled(Rule::PytestUnittestRaisesAssertion) { flake8_pytest_style::rules::unittest_raises_assertion_call(checker, call); } - if checker.enabled(Rule::SubprocessPopenPreexecFn) { + if checker.is_rule_enabled(Rule::SubprocessPopenPreexecFn) { pylint::rules::subprocess_popen_preexec_fn(checker, call); } - if checker.enabled(Rule::SubprocessRunWithoutCheck) { + if checker.is_rule_enabled(Rule::SubprocessRunWithoutCheck) { pylint::rules::subprocess_run_without_check(checker, call); } - if checker.enabled(Rule::UnspecifiedEncoding) { + if checker.is_rule_enabled(Rule::UnspecifiedEncoding) { pylint::rules::unspecified_encoding(checker, call); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::PytestRaisesWithoutException, Rule::PytestRaisesTooBroad, ]) { flake8_pytest_style::rules::raises_call(checker, call); } - if checker.enabled(Rule::LegacyFormPytestRaises) { + if checker.is_rule_enabled(Rule::LegacyFormPytestRaises) { ruff::rules::legacy_raises_warns_deprecated_call(checker, call); } - if checker.any_enabled(&[Rule::PytestWarnsWithoutWarning, Rule::PytestWarnsTooBroad]) { + if checker + .any_rule_enabled(&[Rule::PytestWarnsWithoutWarning, Rule::PytestWarnsTooBroad]) + { flake8_pytest_style::rules::warns_call(checker, call); } - if checker.enabled(Rule::PytestFailWithoutMessage) { + if checker.is_rule_enabled(Rule::PytestFailWithoutMessage) { flake8_pytest_style::rules::fail_call(checker, call); } - if checker.enabled(Rule::ZipInsteadOfPairwise) { + if checker.is_rule_enabled(Rule::ZipInsteadOfPairwise) { if checker.target_version() >= PythonVersion::PY310 { ruff::rules::zip_instead_of_pairwise(checker, call); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::FStringInGetTextFuncCall, Rule::FormatInGetTextFuncCall, Rule::PrintfInGetTextFuncCall, @@ -1000,29 +1008,29 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { func, &checker.settings.flake8_gettext.functions_names, ) { - if checker.enabled(Rule::FStringInGetTextFuncCall) { + if checker.is_rule_enabled(Rule::FStringInGetTextFuncCall) { flake8_gettext::rules::f_string_in_gettext_func_call(checker, args); } - if checker.enabled(Rule::FormatInGetTextFuncCall) { + if checker.is_rule_enabled(Rule::FormatInGetTextFuncCall) { flake8_gettext::rules::format_in_gettext_func_call(checker, args); } - if checker.enabled(Rule::PrintfInGetTextFuncCall) { + if checker.is_rule_enabled(Rule::PrintfInGetTextFuncCall) { flake8_gettext::rules::printf_in_gettext_func_call(checker, args); } } - if checker.enabled(Rule::UncapitalizedEnvironmentVariables) { + if checker.is_rule_enabled(Rule::UncapitalizedEnvironmentVariables) { flake8_simplify::rules::use_capital_environment_variables(checker, expr); } - if checker.enabled(Rule::OpenFileWithContextHandler) { + if checker.is_rule_enabled(Rule::OpenFileWithContextHandler) { flake8_simplify::rules::open_file_with_context_handler(checker, call); } - if checker.enabled(Rule::DictGetWithNoneDefault) { + if checker.is_rule_enabled(Rule::DictGetWithNoneDefault) { flake8_simplify::rules::dict_get_with_none_default(checker, expr); } - if checker.enabled(Rule::ZipDictKeysAndValues) { + if checker.is_rule_enabled(Rule::ZipDictKeysAndValues) { flake8_simplify::rules::zip_dict_keys_and_values(checker, call); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::OsPathAbspath, Rule::OsChmod, Rule::OsMkdir, @@ -1058,16 +1066,16 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ]) { flake8_use_pathlib::rules::replaceable_by_pathlib(checker, call); } - if checker.enabled(Rule::PathConstructorCurrentDirectory) { + if checker.is_rule_enabled(Rule::PathConstructorCurrentDirectory) { flake8_use_pathlib::rules::path_constructor_current_directory(checker, call); } - if checker.enabled(Rule::OsSepSplit) { + if checker.is_rule_enabled(Rule::OsSepSplit) { flake8_use_pathlib::rules::os_sep_split(checker, call); } - if checker.enabled(Rule::NumpyLegacyRandom) { + if checker.is_rule_enabled(Rule::NumpyLegacyRandom) { numpy::rules::legacy_random(checker, func); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::LoggingStringFormat, Rule::LoggingPercentFormat, Rule::LoggingStringConcat, @@ -1079,189 +1087,189 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ]) { flake8_logging_format::rules::logging_call(checker, call); } - if checker.any_enabled(&[Rule::LoggingTooFewArgs, Rule::LoggingTooManyArgs]) { + if checker.any_rule_enabled(&[Rule::LoggingTooFewArgs, Rule::LoggingTooManyArgs]) { pylint::rules::logging_call(checker, call); } - if checker.enabled(Rule::DjangoLocalsInRenderFunction) { + if checker.is_rule_enabled(Rule::DjangoLocalsInRenderFunction) { flake8_django::rules::locals_in_render_function(checker, call); } - if checker.enabled(Rule::UnsupportedMethodCallOnAll) { + if checker.is_rule_enabled(Rule::UnsupportedMethodCallOnAll) { flake8_pyi::rules::unsupported_method_call_on_all(checker, func); } - if checker.enabled(Rule::PrintEmptyString) { + if checker.is_rule_enabled(Rule::PrintEmptyString) { refurb::rules::print_empty_string(checker, call); } - if checker.enabled(Rule::RedundantLogBase) { + if checker.is_rule_enabled(Rule::RedundantLogBase) { refurb::rules::redundant_log_base(checker, call); } - if checker.enabled(Rule::VerboseDecimalConstructor) { + if checker.is_rule_enabled(Rule::VerboseDecimalConstructor) { refurb::rules::verbose_decimal_constructor(checker, call); } - if checker.enabled(Rule::UnnecessaryFromFloat) { + if checker.is_rule_enabled(Rule::UnnecessaryFromFloat) { refurb::rules::unnecessary_from_float(checker, call); } - if checker.enabled(Rule::QuadraticListSummation) { + if checker.is_rule_enabled(Rule::QuadraticListSummation) { ruff::rules::quadratic_list_summation(checker, call); } - if checker.enabled(Rule::DirectLoggerInstantiation) { + if checker.is_rule_enabled(Rule::DirectLoggerInstantiation) { flake8_logging::rules::direct_logger_instantiation(checker, call); } - if checker.enabled(Rule::InvalidGetLoggerArgument) { + if checker.is_rule_enabled(Rule::InvalidGetLoggerArgument) { flake8_logging::rules::invalid_get_logger_argument(checker, call); } - if checker.enabled(Rule::ExceptionWithoutExcInfo) { + if checker.is_rule_enabled(Rule::ExceptionWithoutExcInfo) { flake8_logging::rules::exception_without_exc_info(checker, call); } - if checker.enabled(Rule::RootLoggerCall) { + if checker.is_rule_enabled(Rule::RootLoggerCall) { flake8_logging::rules::root_logger_call(checker, call); } - if checker.enabled(Rule::IsinstanceTypeNone) { + if checker.is_rule_enabled(Rule::IsinstanceTypeNone) { refurb::rules::isinstance_type_none(checker, call); } - if checker.enabled(Rule::ImplicitCwd) { + if checker.is_rule_enabled(Rule::ImplicitCwd) { refurb::rules::no_implicit_cwd(checker, call); } - if checker.enabled(Rule::TrioSyncCall) { + if checker.is_rule_enabled(Rule::TrioSyncCall) { flake8_async::rules::sync_call(checker, call); } - if checker.enabled(Rule::AsyncZeroSleep) { + if checker.is_rule_enabled(Rule::AsyncZeroSleep) { flake8_async::rules::async_zero_sleep(checker, call); } - if checker.enabled(Rule::UnnecessaryDunderCall) { + if checker.is_rule_enabled(Rule::UnnecessaryDunderCall) { pylint::rules::unnecessary_dunder_call(checker, call); } - if checker.enabled(Rule::SslWithNoVersion) { + if checker.is_rule_enabled(Rule::SslWithNoVersion) { flake8_bandit::rules::ssl_with_no_version(checker, call); } - if checker.enabled(Rule::SslInsecureVersion) { + if checker.is_rule_enabled(Rule::SslInsecureVersion) { flake8_bandit::rules::ssl_insecure_version(checker, call); } - if checker.enabled(Rule::MutableFromkeysValue) { + if checker.is_rule_enabled(Rule::MutableFromkeysValue) { ruff::rules::mutable_fromkeys_value(checker, call); } - if checker.enabled(Rule::UnsortedDunderAll) { + if checker.is_rule_enabled(Rule::UnsortedDunderAll) { ruff::rules::sort_dunder_all_extend_call(checker, call); } - if checker.enabled(Rule::DefaultFactoryKwarg) { + if checker.is_rule_enabled(Rule::DefaultFactoryKwarg) { ruff::rules::default_factory_kwarg(checker, call); } - if checker.enabled(Rule::UnnecessaryIterableAllocationForFirstElement) { + if checker.is_rule_enabled(Rule::UnnecessaryIterableAllocationForFirstElement) { ruff::rules::unnecessary_iterable_allocation_for_first_element(checker, expr); } - if checker.enabled(Rule::DecimalFromFloatLiteral) { + if checker.is_rule_enabled(Rule::DecimalFromFloatLiteral) { ruff::rules::decimal_from_float_literal_syntax(checker, call); } - if checker.enabled(Rule::IntOnSlicedStr) { + if checker.is_rule_enabled(Rule::IntOnSlicedStr) { refurb::rules::int_on_sliced_str(checker, call); } - if checker.enabled(Rule::UnsafeMarkupUse) { + if checker.is_rule_enabled(Rule::UnsafeMarkupUse) { flake8_bandit::rules::unsafe_markup_call(checker, call); } - if checker.enabled(Rule::MapIntVersionParsing) { + if checker.is_rule_enabled(Rule::MapIntVersionParsing) { ruff::rules::map_int_version_parsing(checker, call); } - if checker.enabled(Rule::UnrawRePattern) { + if checker.is_rule_enabled(Rule::UnrawRePattern) { ruff::rules::unraw_re_pattern(checker, call); } - if checker.enabled(Rule::AirflowDagNoScheduleArgument) { + if checker.is_rule_enabled(Rule::AirflowDagNoScheduleArgument) { airflow::rules::dag_no_schedule_argument(checker, expr); } - if checker.enabled(Rule::UnnecessaryRegularExpression) { + if checker.is_rule_enabled(Rule::UnnecessaryRegularExpression) { ruff::rules::unnecessary_regular_expression(checker, call); } - if checker.enabled(Rule::Airflow3Removal) { + if checker.is_rule_enabled(Rule::Airflow3Removal) { airflow::rules::airflow_3_removal_expr(checker, expr); } - if checker.enabled(Rule::Airflow3SuggestedUpdate) { + if checker.is_rule_enabled(Rule::Airflow3SuggestedUpdate) { airflow::rules::airflow_3_0_suggested_update_expr(checker, expr); } - if checker.enabled(Rule::UnnecessaryCastToInt) { + if checker.is_rule_enabled(Rule::UnnecessaryCastToInt) { ruff::rules::unnecessary_cast_to_int(checker, call); } - if checker.enabled(Rule::InvalidPathlibWithSuffix) { + if checker.is_rule_enabled(Rule::InvalidPathlibWithSuffix) { flake8_use_pathlib::rules::invalid_pathlib_with_suffix(checker, call); } - if checker.enabled(Rule::BatchedWithoutExplicitStrict) { + if checker.is_rule_enabled(Rule::BatchedWithoutExplicitStrict) { flake8_bugbear::rules::batched_without_explicit_strict(checker, call); } - if checker.enabled(Rule::PytestRaisesAmbiguousPattern) { + if checker.is_rule_enabled(Rule::PytestRaisesAmbiguousPattern) { ruff::rules::pytest_raises_ambiguous_pattern(checker, call); } - if checker.enabled(Rule::FalsyDictGetFallback) { + if checker.is_rule_enabled(Rule::FalsyDictGetFallback) { ruff::rules::falsy_dict_get_fallback(checker, expr); } - if checker.enabled(Rule::UnnecessaryRound) { + if checker.is_rule_enabled(Rule::UnnecessaryRound) { ruff::rules::unnecessary_round(checker, call); } - if checker.enabled(Rule::UnnecessaryEmptyIterableWithinDequeCall) { + if checker.is_rule_enabled(Rule::UnnecessaryEmptyIterableWithinDequeCall) { ruff::rules::unnecessary_literal_within_deque_call(checker, call); } - if checker.enabled(Rule::StarmapZip) { + if checker.is_rule_enabled(Rule::StarmapZip) { ruff::rules::starmap_zip(checker, call); } - if checker.enabled(Rule::AccessAnnotationsFromClassDict) { + if checker.is_rule_enabled(Rule::AccessAnnotationsFromClassDict) { ruff::rules::access_annotations_from_class_dict_with_get(checker, call); } - if checker.enabled(Rule::LogExceptionOutsideExceptHandler) { + if checker.is_rule_enabled(Rule::LogExceptionOutsideExceptHandler) { flake8_logging::rules::log_exception_outside_except_handler(checker, call); } - if checker.enabled(Rule::ExcInfoOutsideExceptHandler) { + if checker.is_rule_enabled(Rule::ExcInfoOutsideExceptHandler) { flake8_logging::rules::exc_info_outside_except_handler(checker, call); } - if checker.enabled(Rule::FromisoformatReplaceZ) { + if checker.is_rule_enabled(Rule::FromisoformatReplaceZ) { refurb::rules::fromisoformat_replace_z(checker, call); } - if checker.enabled(Rule::NonOctalPermissions) { + if checker.is_rule_enabled(Rule::NonOctalPermissions) { ruff::rules::non_octal_permissions(checker, call); } } Expr::Dict(dict) => { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::MultiValueRepeatedKeyLiteral, Rule::MultiValueRepeatedKeyVariable, ]) { pyflakes::rules::repeated_keys(checker, dict); } - if checker.enabled(Rule::UnnecessarySpread) { + if checker.is_rule_enabled(Rule::UnnecessarySpread) { flake8_pie::rules::unnecessary_spread(checker, dict); } } Expr::Set(set) => { - if checker.enabled(Rule::DuplicateValue) { + if checker.is_rule_enabled(Rule::DuplicateValue) { flake8_bugbear::rules::duplicate_value(checker, set); } } Expr::Yield(_) => { - if checker.enabled(Rule::YieldInInit) { + if checker.is_rule_enabled(Rule::YieldInInit) { pylint::rules::yield_in_init(checker, expr); } } Expr::YieldFrom(yield_from) => { - if checker.enabled(Rule::YieldInInit) { + if checker.is_rule_enabled(Rule::YieldInInit) { pylint::rules::yield_in_init(checker, expr); } - if checker.enabled(Rule::YieldFromInAsyncFunction) { + if checker.is_rule_enabled(Rule::YieldFromInAsyncFunction) { pylint::rules::yield_from_in_async_function(checker, yield_from); } } Expr::FString(f_string_expr @ ast::ExprFString { value, .. }) => { - if checker.enabled(Rule::FStringMissingPlaceholders) { + if checker.is_rule_enabled(Rule::FStringMissingPlaceholders) { pyflakes::rules::f_string_missing_placeholders(checker, f_string_expr); } - if checker.enabled(Rule::ExplicitFStringTypeConversion) { + if checker.is_rule_enabled(Rule::ExplicitFStringTypeConversion) { for f_string in value.f_strings() { ruff::rules::explicit_f_string_type_conversion(checker, f_string); } } - if checker.enabled(Rule::HardcodedSQLExpression) { + if checker.is_rule_enabled(Rule::HardcodedSQLExpression) { flake8_bandit::rules::hardcoded_sql_expression(checker, expr); } - if checker.enabled(Rule::UnicodeKindPrefix) { + if checker.is_rule_enabled(Rule::UnicodeKindPrefix) { for string_literal in value.literals() { pyupgrade::rules::unicode_kind_prefix(checker, string_literal); } } - if checker.enabled(Rule::MissingFStringSyntax) { + if checker.is_rule_enabled(Rule::MissingFStringSyntax) { for string_literal in value.literals() { ruff::rules::missing_fstring_syntax(checker, string_literal); } @@ -1272,7 +1280,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { op: Operator::RShift, .. }) => { - if checker.enabled(Rule::InvalidPrintSyntax) { + if checker.is_rule_enabled(Rule::InvalidPrintSyntax) { pyflakes::rules::invalid_print_syntax(checker, left); } } @@ -1288,7 +1296,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { if let Expr::StringLiteral(format_string @ ast::ExprStringLiteral { value, .. }) = left.as_ref() { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::PercentFormatInvalidFormat, Rule::PercentFormatExpectedMapping, Rule::PercentFormatExpectedSequence, @@ -1305,7 +1313,9 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { typ: CFormatErrorType::UnsupportedFormatChar(c), .. }) => { - if checker.enabled(Rule::PercentFormatUnsupportedFormatCharacter) { + if checker + .is_rule_enabled(Rule::PercentFormatUnsupportedFormatCharacter) + { checker.report_diagnostic( pyflakes::rules::PercentFormatUnsupportedFormatCharacter { char: c, @@ -1315,7 +1325,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } Err(e) => { - if checker.enabled(Rule::PercentFormatInvalidFormat) { + if checker.is_rule_enabled(Rule::PercentFormatInvalidFormat) { checker.report_diagnostic( pyflakes::rules::PercentFormatInvalidFormat { message: e.to_string(), @@ -1325,37 +1335,37 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } Ok(summary) => { - if checker.enabled(Rule::PercentFormatExpectedMapping) { + if checker.is_rule_enabled(Rule::PercentFormatExpectedMapping) { pyflakes::rules::percent_format_expected_mapping( checker, &summary, right, location, ); } - if checker.enabled(Rule::PercentFormatExpectedSequence) { + if checker.is_rule_enabled(Rule::PercentFormatExpectedSequence) { pyflakes::rules::percent_format_expected_sequence( checker, &summary, right, location, ); } - if checker.enabled(Rule::PercentFormatExtraNamedArguments) { + if checker.is_rule_enabled(Rule::PercentFormatExtraNamedArguments) { pyflakes::rules::percent_format_extra_named_arguments( checker, &summary, right, location, ); } - if checker.enabled(Rule::PercentFormatMissingArgument) { + if checker.is_rule_enabled(Rule::PercentFormatMissingArgument) { pyflakes::rules::percent_format_missing_arguments( checker, &summary, right, location, ); } - if checker.enabled(Rule::PercentFormatMixedPositionalAndNamed) { + if checker.is_rule_enabled(Rule::PercentFormatMixedPositionalAndNamed) { pyflakes::rules::percent_format_mixed_positional_and_named( checker, &summary, location, ); } - if checker.enabled(Rule::PercentFormatPositionalCountMismatch) { + if checker.is_rule_enabled(Rule::PercentFormatPositionalCountMismatch) { pyflakes::rules::percent_format_positional_count_mismatch( checker, &summary, right, location, ); } - if checker.enabled(Rule::PercentFormatStarRequiresSequence) { + if checker.is_rule_enabled(Rule::PercentFormatStarRequiresSequence) { pyflakes::rules::percent_format_star_requires_sequence( checker, &summary, right, location, ); @@ -1363,20 +1373,20 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } } - if checker.enabled(Rule::PrintfStringFormatting) { + if checker.is_rule_enabled(Rule::PrintfStringFormatting) { pyupgrade::rules::printf_string_formatting(checker, bin_op, format_string); } - if checker.enabled(Rule::BadStringFormatCharacter) { + if checker.is_rule_enabled(Rule::BadStringFormatCharacter) { pylint::rules::bad_string_format_character::percent( checker, expr, format_string, ); } - if checker.enabled(Rule::BadStringFormatType) { + if checker.is_rule_enabled(Rule::BadStringFormatType) { pylint::rules::bad_string_format_type(checker, bin_op, format_string); } - if checker.enabled(Rule::HardcodedSQLExpression) { + if checker.is_rule_enabled(Rule::HardcodedSQLExpression) { flake8_bandit::rules::hardcoded_sql_expression(checker, expr); } } @@ -1384,13 +1394,13 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { Expr::BinOp(ast::ExprBinOp { op: Operator::Add, .. }) => { - if checker.enabled(Rule::ExplicitStringConcatenation) { + if checker.is_rule_enabled(Rule::ExplicitStringConcatenation) { flake8_implicit_str_concat::rules::explicit(checker, expr); } - if checker.enabled(Rule::CollectionLiteralConcatenation) { + if checker.is_rule_enabled(Rule::CollectionLiteralConcatenation) { ruff::rules::collection_literal_concatenation(checker, expr); } - if checker.enabled(Rule::HardcodedSQLExpression) { + if checker.is_rule_enabled(Rule::HardcodedSQLExpression) { flake8_bandit::rules::hardcoded_sql_expression(checker, expr); } } @@ -1399,7 +1409,7 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { .. }) => { // Ex) `str | None` - if checker.enabled(Rule::FutureRequiredTypeAnnotation) { + if checker.is_rule_enabled(Rule::FutureRequiredTypeAnnotation) { if !checker.semantic.future_annotations_or_stub() && checker.target_version() < PythonVersion::PY310 && checker.semantic.in_annotation() @@ -1414,31 +1424,31 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { } } - if checker.enabled(Rule::NeverUnion) { + if checker.is_rule_enabled(Rule::NeverUnion) { ruff::rules::never_union(checker, expr); } // Avoid duplicate checks if the parent is a union, since these rules already // traverse nested unions. if !checker.semantic.in_nested_union() { - if checker.enabled(Rule::DuplicateUnionMember) + if checker.is_rule_enabled(Rule::DuplicateUnionMember) && checker.semantic.in_type_definition() { flake8_pyi::rules::duplicate_union_member(checker, expr); } - if checker.enabled(Rule::UnnecessaryLiteralUnion) { + if checker.is_rule_enabled(Rule::UnnecessaryLiteralUnion) { flake8_pyi::rules::unnecessary_literal_union(checker, expr); } - if checker.enabled(Rule::RedundantLiteralUnion) { + if checker.is_rule_enabled(Rule::RedundantLiteralUnion) { flake8_pyi::rules::redundant_literal_union(checker, expr); } - if checker.enabled(Rule::UnnecessaryTypeUnion) { + if checker.is_rule_enabled(Rule::UnnecessaryTypeUnion) { flake8_pyi::rules::unnecessary_type_union(checker, expr); } - if checker.enabled(Rule::RuntimeStringUnion) { + if checker.is_rule_enabled(Rule::RuntimeStringUnion) { flake8_type_checking::rules::runtime_string_union(checker, expr); } - if checker.enabled(Rule::NoneNotAtEndOfUnion) { + if checker.is_rule_enabled(Rule::NoneNotAtEndOfUnion) { ruff::rules::none_not_at_end_of_union(checker, expr); } } @@ -1451,21 +1461,21 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.any_enabled(&[Rule::NotInTest, Rule::NotIsTest]) { + if checker.any_rule_enabled(&[Rule::NotInTest, Rule::NotIsTest]) { pycodestyle::rules::not_tests(checker, unary_op); } - if checker.enabled(Rule::UnaryPrefixIncrementDecrement) { + if checker.is_rule_enabled(Rule::UnaryPrefixIncrementDecrement) { flake8_bugbear::rules::unary_prefix_increment_decrement( checker, expr, *op, operand, ); } - if checker.enabled(Rule::NegateEqualOp) { + if checker.is_rule_enabled(Rule::NegateEqualOp) { flake8_simplify::rules::negation_with_equal_op(checker, expr, *op, operand); } - if checker.enabled(Rule::NegateNotEqualOp) { + if checker.is_rule_enabled(Rule::NegateNotEqualOp) { flake8_simplify::rules::negation_with_not_equal_op(checker, expr, *op, operand); } - if checker.enabled(Rule::DoubleNegation) { + if checker.is_rule_enabled(Rule::DoubleNegation) { flake8_simplify::rules::double_negation(checker, expr, *op, operand); } } @@ -1478,16 +1488,16 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.any_enabled(&[Rule::NoneComparison, Rule::TrueFalseComparison]) { + if checker.any_rule_enabled(&[Rule::NoneComparison, Rule::TrueFalseComparison]) { pycodestyle::rules::literal_comparisons(checker, compare); } - if checker.enabled(Rule::IsLiteral) { + if checker.is_rule_enabled(Rule::IsLiteral) { pyflakes::rules::invalid_literal_comparison(checker, left, ops, comparators, expr); } - if checker.enabled(Rule::TypeComparison) { + if checker.is_rule_enabled(Rule::TypeComparison) { pycodestyle::rules::type_comparison(checker, compare); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SysVersionCmpStr3, Rule::SysVersionInfo0Eq3, Rule::SysVersionInfo1CmpInt, @@ -1496,41 +1506,41 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { ]) { flake8_2020::rules::compare(checker, left, ops, comparators); } - if checker.enabled(Rule::HardcodedPasswordString) { + if checker.is_rule_enabled(Rule::HardcodedPasswordString) { flake8_bandit::rules::compare_to_hardcoded_password_string( checker, left, comparators, ); } - if checker.enabled(Rule::ComparisonWithItself) { + if checker.is_rule_enabled(Rule::ComparisonWithItself) { pylint::rules::comparison_with_itself(checker, left, ops, comparators); } - if checker.enabled(Rule::LiteralMembership) { + if checker.is_rule_enabled(Rule::LiteralMembership) { pylint::rules::literal_membership(checker, compare); } - if checker.enabled(Rule::ComparisonOfConstant) { + if checker.is_rule_enabled(Rule::ComparisonOfConstant) { pylint::rules::comparison_of_constant(checker, left, ops, comparators); } - if checker.enabled(Rule::CompareToEmptyString) { + if checker.is_rule_enabled(Rule::CompareToEmptyString) { pylint::rules::compare_to_empty_string(checker, left, ops, comparators); } - if checker.enabled(Rule::MagicValueComparison) { + if checker.is_rule_enabled(Rule::MagicValueComparison) { pylint::rules::magic_value_comparison(checker, left, comparators); } - if checker.enabled(Rule::NanComparison) { + if checker.is_rule_enabled(Rule::NanComparison) { pylint::rules::nan_comparison(checker, left, comparators); } - if checker.enabled(Rule::InEmptyCollection) { + if checker.is_rule_enabled(Rule::InEmptyCollection) { ruff::rules::in_empty_collection(checker, compare); } - if checker.enabled(Rule::InDictKeys) { + if checker.is_rule_enabled(Rule::InDictKeys) { flake8_simplify::rules::key_in_dict_compare(checker, compare); } - if checker.enabled(Rule::YodaConditions) { + if checker.is_rule_enabled(Rule::YodaConditions) { flake8_simplify::rules::yoda_conditions(checker, expr, left, ops, comparators); } - if checker.enabled(Rule::PandasNuniqueConstantSeriesCheck) { + if checker.is_rule_enabled(Rule::PandasNuniqueConstantSeriesCheck) { pandas_vet::rules::nunique_constant_series_check( checker, expr, @@ -1539,18 +1549,19 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { comparators, ); } - if checker.enabled(Rule::TypeNoneComparison) { + if checker.is_rule_enabled(Rule::TypeNoneComparison) { refurb::rules::type_none_comparison(checker, compare); } - if checker.enabled(Rule::SingleItemMembershipTest) { + if checker.is_rule_enabled(Rule::SingleItemMembershipTest) { refurb::rules::single_item_membership_test(checker, expr, left, ops, comparators); } } Expr::NumberLiteral(number_literal @ ast::ExprNumberLiteral { .. }) => { - if checker.source_type.is_stub() && checker.enabled(Rule::NumericLiteralTooLong) { + if checker.source_type.is_stub() && checker.is_rule_enabled(Rule::NumericLiteralTooLong) + { flake8_pyi::rules::numeric_literal_too_long(checker, expr); } - if checker.enabled(Rule::MathConstant) { + if checker.is_rule_enabled(Rule::MathConstant) { refurb::rules::math_constant(checker, number_literal); } } @@ -1561,17 +1572,17 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::UnicodeKindPrefix) { + if checker.is_rule_enabled(Rule::UnicodeKindPrefix) { for string_part in value { pyupgrade::rules::unicode_kind_prefix(checker, string_part); } } - if checker.enabled(Rule::MissingFStringSyntax) { + if checker.is_rule_enabled(Rule::MissingFStringSyntax) { for string_literal in value { ruff::rules::missing_fstring_syntax(checker, string_literal); } } - if checker.enabled(Rule::HardcodedStringCharset) { + if checker.is_rule_enabled(Rule::HardcodedStringCharset) { refurb::rules::hardcoded_string_charset_literal(checker, string_like); } } @@ -1584,30 +1595,30 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::IfElseBlockInsteadOfDictGet) { + if checker.is_rule_enabled(Rule::IfElseBlockInsteadOfDictGet) { flake8_simplify::rules::if_exp_instead_of_dict_get( checker, expr, test, body, orelse, ); } - if checker.enabled(Rule::IfExprWithTrueFalse) { + if checker.is_rule_enabled(Rule::IfExprWithTrueFalse) { flake8_simplify::rules::if_expr_with_true_false(checker, expr, test, body, orelse); } - if checker.enabled(Rule::IfExprWithFalseTrue) { + if checker.is_rule_enabled(Rule::IfExprWithFalseTrue) { flake8_simplify::rules::if_expr_with_false_true(checker, expr, test, body, orelse); } - if checker.enabled(Rule::IfExprWithTwistedArms) { + if checker.is_rule_enabled(Rule::IfExprWithTwistedArms) { flake8_simplify::rules::twisted_arms_in_ifexpr(checker, expr, test, body, orelse); } - if checker.enabled(Rule::IfExprMinMax) { + if checker.is_rule_enabled(Rule::IfExprMinMax) { refurb::rules::if_expr_min_max(checker, if_exp); } - if checker.enabled(Rule::IfExpInsteadOfOrOperator) { + if checker.is_rule_enabled(Rule::IfExpInsteadOfOrOperator) { refurb::rules::if_exp_instead_of_or_operator(checker, if_exp); } - if checker.enabled(Rule::UselessIfElse) { + if checker.is_rule_enabled(Rule::UselessIfElse) { ruff::rules::useless_if_else(checker, if_exp); } - if checker.enabled(Rule::SliceToRemovePrefixOrSuffix) { + if checker.is_rule_enabled(Rule::SliceToRemovePrefixOrSuffix) { refurb::rules::slice_to_remove_affix_expr(checker, if_exp); } } @@ -1619,26 +1630,26 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::UnnecessaryListIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryListIndexLookup) { pylint::rules::unnecessary_list_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryDictIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryDictIndexLookup) { pylint::rules::unnecessary_dict_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryComprehension) { + if checker.is_rule_enabled(Rule::UnnecessaryComprehension) { flake8_comprehensions::rules::unnecessary_list_set_comprehension( checker, expr, elt, generators, ); } - if checker.enabled(Rule::FunctionUsesLoopVariable) { + if checker.is_rule_enabled(Rule::FunctionUsesLoopVariable) { flake8_bugbear::rules::function_uses_loop_variable(checker, &Node::Expr(expr)); } - if checker.enabled(Rule::IterationOverSet) { + if checker.is_rule_enabled(Rule::IterationOverSet) { for generator in generators { pylint::rules::iteration_over_set(checker, &generator.iter); } } - if checker.enabled(Rule::ReimplementedStarmap) { + if checker.is_rule_enabled(Rule::ReimplementedStarmap) { refurb::rules::reimplemented_starmap(checker, &comp.into()); } } @@ -1650,26 +1661,26 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::UnnecessaryListIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryListIndexLookup) { pylint::rules::unnecessary_list_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryDictIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryDictIndexLookup) { pylint::rules::unnecessary_dict_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryComprehension) { + if checker.is_rule_enabled(Rule::UnnecessaryComprehension) { flake8_comprehensions::rules::unnecessary_list_set_comprehension( checker, expr, elt, generators, ); } - if checker.enabled(Rule::FunctionUsesLoopVariable) { + if checker.is_rule_enabled(Rule::FunctionUsesLoopVariable) { flake8_bugbear::rules::function_uses_loop_variable(checker, &Node::Expr(expr)); } - if checker.enabled(Rule::IterationOverSet) { + if checker.is_rule_enabled(Rule::IterationOverSet) { for generator in generators { pylint::rules::iteration_over_set(checker, &generator.iter); } } - if checker.enabled(Rule::ReimplementedStarmap) { + if checker.is_rule_enabled(Rule::ReimplementedStarmap) { refurb::rules::reimplemented_starmap(checker, &comp.into()); } } @@ -1682,34 +1693,34 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::UnnecessaryListIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryListIndexLookup) { pylint::rules::unnecessary_list_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryDictIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryDictIndexLookup) { pylint::rules::unnecessary_dict_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryComprehension) { + if checker.is_rule_enabled(Rule::UnnecessaryComprehension) { flake8_comprehensions::rules::unnecessary_dict_comprehension( checker, expr, key, value, generators, ); } - if checker.enabled(Rule::UnnecessaryDictComprehensionForIterable) { + if checker.is_rule_enabled(Rule::UnnecessaryDictComprehensionForIterable) { flake8_comprehensions::rules::unnecessary_dict_comprehension_for_iterable( checker, dict_comp, ); } - if checker.enabled(Rule::FunctionUsesLoopVariable) { + if checker.is_rule_enabled(Rule::FunctionUsesLoopVariable) { flake8_bugbear::rules::function_uses_loop_variable(checker, &Node::Expr(expr)); } - if checker.enabled(Rule::IterationOverSet) { + if checker.is_rule_enabled(Rule::IterationOverSet) { for generator in generators { pylint::rules::iteration_over_set(checker, &generator.iter); } } - if checker.enabled(Rule::StaticKeyDictComprehension) { + if checker.is_rule_enabled(Rule::StaticKeyDictComprehension) { flake8_bugbear::rules::static_key_dict_comprehension(checker, dict_comp); } } @@ -1722,64 +1733,64 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) { parenthesized: _, }, ) => { - if checker.enabled(Rule::UnnecessaryListIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryListIndexLookup) { pylint::rules::unnecessary_list_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::UnnecessaryDictIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryDictIndexLookup) { pylint::rules::unnecessary_dict_index_lookup_comprehension(checker, expr); } - if checker.enabled(Rule::FunctionUsesLoopVariable) { + if checker.is_rule_enabled(Rule::FunctionUsesLoopVariable) { flake8_bugbear::rules::function_uses_loop_variable(checker, &Node::Expr(expr)); } - if checker.enabled(Rule::IterationOverSet) { + if checker.is_rule_enabled(Rule::IterationOverSet) { for generator in generators { pylint::rules::iteration_over_set(checker, &generator.iter); } } - if checker.enabled(Rule::ReimplementedStarmap) { + if checker.is_rule_enabled(Rule::ReimplementedStarmap) { refurb::rules::reimplemented_starmap(checker, &generator.into()); } } Expr::BoolOp(bool_op) => { - if checker.enabled(Rule::BooleanChainedComparison) { + if checker.is_rule_enabled(Rule::BooleanChainedComparison) { pylint::rules::boolean_chained_comparison(checker, bool_op); } - if checker.enabled(Rule::MultipleStartsEndsWith) { + if checker.is_rule_enabled(Rule::MultipleStartsEndsWith) { flake8_pie::rules::multiple_starts_ends_with(checker, expr); } - if checker.enabled(Rule::DuplicateIsinstanceCall) { + if checker.is_rule_enabled(Rule::DuplicateIsinstanceCall) { flake8_simplify::rules::duplicate_isinstance_call(checker, expr); } - if checker.enabled(Rule::CompareWithTuple) { + if checker.is_rule_enabled(Rule::CompareWithTuple) { flake8_simplify::rules::compare_with_tuple(checker, expr); } - if checker.enabled(Rule::ExprAndNotExpr) { + if checker.is_rule_enabled(Rule::ExprAndNotExpr) { flake8_simplify::rules::expr_and_not_expr(checker, expr); } - if checker.enabled(Rule::ExprOrNotExpr) { + if checker.is_rule_enabled(Rule::ExprOrNotExpr) { flake8_simplify::rules::expr_or_not_expr(checker, expr); } - if checker.enabled(Rule::ExprOrTrue) { + if checker.is_rule_enabled(Rule::ExprOrTrue) { flake8_simplify::rules::expr_or_true(checker, expr); } - if checker.enabled(Rule::ExprAndFalse) { + if checker.is_rule_enabled(Rule::ExprAndFalse) { flake8_simplify::rules::expr_and_false(checker, expr); } - if checker.enabled(Rule::RepeatedEqualityComparison) { + if checker.is_rule_enabled(Rule::RepeatedEqualityComparison) { pylint::rules::repeated_equality_comparison(checker, bool_op); } - if checker.enabled(Rule::UnnecessaryKeyCheck) { + if checker.is_rule_enabled(Rule::UnnecessaryKeyCheck) { ruff::rules::unnecessary_key_check(checker, expr); } - if checker.enabled(Rule::ParenthesizeChainedOperators) { + if checker.is_rule_enabled(Rule::ParenthesizeChainedOperators) { ruff::rules::parenthesize_chained_logical_operators(checker, bool_op); } } Expr::Lambda(lambda) => { - if checker.enabled(Rule::ReimplementedOperator) { + if checker.is_rule_enabled(Rule::ReimplementedOperator) { refurb::rules::reimplemented_operator(checker, &lambda.into()); } - if checker.enabled(Rule::InvalidArgumentName) { + if checker.is_rule_enabled(Rule::InvalidArgumentName) { pep8_naming::rules::invalid_argument_name_lambda(checker, lambda); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/module.rs b/crates/ruff_linter/src/checkers/ast/analyze/module.rs index cb897ebf26..e4d0a346aa 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/module.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/module.rs @@ -6,10 +6,10 @@ use crate::rules::{flake8_bugbear, ruff}; /// Run lint rules over a module. pub(crate) fn module(suite: &Suite, checker: &Checker) { - if checker.enabled(Rule::FStringDocstring) { + if checker.is_rule_enabled(Rule::FStringDocstring) { flake8_bugbear::rules::f_string_docstring(checker, suite); } - if checker.enabled(Rule::InvalidFormatterSuppressionComment) { + if checker.is_rule_enabled(Rule::InvalidFormatterSuppressionComment) { ruff::rules::ignored_formatter_suppression_comment(checker, suite); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/parameter.rs b/crates/ruff_linter/src/checkers/ast/analyze/parameter.rs index 253dc60351..831f164e8a 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/parameter.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/parameter.rs @@ -7,14 +7,14 @@ use crate::rules::{flake8_builtins, pycodestyle}; /// Run lint rules over a [`Parameter`] syntax node. pub(crate) fn parameter(parameter: &Parameter, checker: &Checker) { - if checker.enabled(Rule::AmbiguousVariableName) { + if checker.is_rule_enabled(Rule::AmbiguousVariableName) { pycodestyle::rules::ambiguous_variable_name( checker, ¶meter.name, parameter.name.range(), ); } - if checker.enabled(Rule::BuiltinArgumentShadowing) { + if checker.is_rule_enabled(Rule::BuiltinArgumentShadowing) { flake8_builtins::rules::builtin_argument_shadowing(checker, parameter); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/parameters.rs b/crates/ruff_linter/src/checkers/ast/analyze/parameters.rs index a9d2c949b7..cc7a2479b2 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/parameters.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/parameters.rs @@ -6,17 +6,17 @@ 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.enabled(Rule::FunctionCallInDefaultArgument) { + if checker.is_rule_enabled(Rule::FunctionCallInDefaultArgument) { flake8_bugbear::rules::function_call_in_argument_default(checker, parameters); } - if checker.settings.rules.enabled(Rule::ImplicitOptional) { + if checker.is_rule_enabled(Rule::ImplicitOptional) { ruff::rules::implicit_optional(checker, parameters); } if checker.source_type.is_stub() { - if checker.enabled(Rule::TypedArgumentDefaultInStub) { + if checker.is_rule_enabled(Rule::TypedArgumentDefaultInStub) { flake8_pyi::rules::typed_argument_simple_defaults(checker, parameters); } - if checker.enabled(Rule::ArgumentDefaultInStub) { + if checker.is_rule_enabled(Rule::ArgumentDefaultInStub) { flake8_pyi::rules::argument_simple_defaults(checker, parameters); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/statement.rs b/crates/ruff_linter/src/checkers/ast/analyze/statement.rs index 4effbce61d..4e00591aff 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/statement.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/statement.rs @@ -23,10 +23,10 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { range: _, node_index: _, }) => { - if checker.enabled(Rule::GlobalAtModuleLevel) { + if checker.is_rule_enabled(Rule::GlobalAtModuleLevel) { pylint::rules::global_at_module_level(checker, stmt); } - if checker.enabled(Rule::AmbiguousVariableName) { + if checker.is_rule_enabled(Rule::AmbiguousVariableName) { for name in names { pycodestyle::rules::ambiguous_variable_name(checker, name, name.range()); } @@ -39,12 +39,12 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::AmbiguousVariableName) { + if checker.is_rule_enabled(Rule::AmbiguousVariableName) { for name in names { pycodestyle::rules::ambiguous_variable_name(checker, name, name.range()); } } - if checker.enabled(Rule::NonlocalWithoutBinding) { + if checker.is_rule_enabled(Rule::NonlocalWithoutBinding) { if !checker.semantic.scope_id.is_global() { for name in names { if checker.semantic.nonlocal(name).is_none() { @@ -58,12 +58,12 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } - if checker.enabled(Rule::NonlocalAndGlobal) { + if checker.is_rule_enabled(Rule::NonlocalAndGlobal) { pylint::rules::nonlocal_and_global(checker, nonlocal); } } Stmt::Break(_) => { - if checker.enabled(Rule::BreakOutsideLoop) { + if checker.is_rule_enabled(Rule::BreakOutsideLoop) { pyflakes::rules::break_outside_loop( checker, stmt, @@ -72,7 +72,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } Stmt::Continue(_) => { - if checker.enabled(Rule::ContinueOutsideLoop) { + if checker.is_rule_enabled(Rule::ContinueOutsideLoop) { pyflakes::rules::continue_outside_loop( checker, stmt, @@ -93,40 +93,40 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::DjangoNonLeadingReceiverDecorator) { + if checker.is_rule_enabled(Rule::DjangoNonLeadingReceiverDecorator) { flake8_django::rules::non_leading_receiver_decorator(checker, decorator_list); } - if checker.enabled(Rule::FastApiRedundantResponseModel) { + if checker.is_rule_enabled(Rule::FastApiRedundantResponseModel) { fastapi::rules::fastapi_redundant_response_model(checker, function_def); } - if checker.enabled(Rule::FastApiNonAnnotatedDependency) { + if checker.is_rule_enabled(Rule::FastApiNonAnnotatedDependency) { fastapi::rules::fastapi_non_annotated_dependency(checker, function_def); } - if checker.enabled(Rule::FastApiUnusedPathParameter) { + if checker.is_rule_enabled(Rule::FastApiUnusedPathParameter) { fastapi::rules::fastapi_unused_path_parameter(checker, function_def); } - if checker.enabled(Rule::AmbiguousFunctionName) { + if checker.is_rule_enabled(Rule::AmbiguousFunctionName) { pycodestyle::rules::ambiguous_function_name(checker, name); } - if checker.enabled(Rule::InvalidBoolReturnType) { + if checker.is_rule_enabled(Rule::InvalidBoolReturnType) { pylint::rules::invalid_bool_return(checker, function_def); } - if checker.enabled(Rule::InvalidLengthReturnType) { + if checker.is_rule_enabled(Rule::InvalidLengthReturnType) { pylint::rules::invalid_length_return(checker, function_def); } - if checker.enabled(Rule::InvalidBytesReturnType) { + if checker.is_rule_enabled(Rule::InvalidBytesReturnType) { pylint::rules::invalid_bytes_return(checker, function_def); } - if checker.enabled(Rule::InvalidIndexReturnType) { + if checker.is_rule_enabled(Rule::InvalidIndexReturnType) { pylint::rules::invalid_index_return(checker, function_def); } - if checker.enabled(Rule::InvalidHashReturnType) { + if checker.is_rule_enabled(Rule::InvalidHashReturnType) { pylint::rules::invalid_hash_return(checker, function_def); } - if checker.enabled(Rule::InvalidStrReturnType) { + if checker.is_rule_enabled(Rule::InvalidStrReturnType) { pylint::rules::invalid_str_return(checker, function_def); } - if checker.enabled(Rule::InvalidFunctionName) { + if checker.is_rule_enabled(Rule::InvalidFunctionName) { pep8_naming::rules::invalid_function_name( checker, stmt, @@ -137,20 +137,20 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } if checker.source_type.is_stub() { - if checker.enabled(Rule::PassStatementStubBody) { + if checker.is_rule_enabled(Rule::PassStatementStubBody) { flake8_pyi::rules::pass_statement_stub_body(checker, body); } - if checker.enabled(Rule::NonEmptyStubBody) { + if checker.is_rule_enabled(Rule::NonEmptyStubBody) { flake8_pyi::rules::non_empty_stub_body(checker, body); } - if checker.enabled(Rule::StubBodyMultipleStatements) { + if checker.is_rule_enabled(Rule::StubBodyMultipleStatements) { flake8_pyi::rules::stub_body_multiple_statements(checker, stmt, body); } } - if checker.enabled(Rule::AnyEqNeAnnotation) { + if checker.is_rule_enabled(Rule::AnyEqNeAnnotation) { flake8_pyi::rules::any_eq_ne_annotation(checker, name, parameters); } - if checker.enabled(Rule::NonSelfReturnType) { + if checker.is_rule_enabled(Rule::NonSelfReturnType) { flake8_pyi::rules::non_self_return_type( checker, stmt, @@ -161,29 +161,29 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { parameters, ); } - if checker.enabled(Rule::GeneratorReturnFromIterMethod) { + if checker.is_rule_enabled(Rule::GeneratorReturnFromIterMethod) { flake8_pyi::rules::bad_generator_return_type(function_def, checker); } if checker.source_type.is_stub() { - if checker.enabled(Rule::StrOrReprDefinedInStub) { + 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.enabled(Rule::NoReturnArgumentAnnotationInStub) { + if checker.is_rule_enabled(Rule::NoReturnArgumentAnnotationInStub) { flake8_pyi::rules::no_return_argument_annotation(checker, parameters); } } - if checker.enabled(Rule::BadExitAnnotation) { + if checker.is_rule_enabled(Rule::BadExitAnnotation) { flake8_pyi::rules::bad_exit_annotation(checker, function_def); } - if checker.enabled(Rule::RedundantNumericUnion) { + if checker.is_rule_enabled(Rule::RedundantNumericUnion) { flake8_pyi::rules::redundant_numeric_union(checker, parameters); } - if checker.enabled(Rule::Pep484StylePositionalOnlyParameter) { + if checker.is_rule_enabled(Rule::Pep484StylePositionalOnlyParameter) { flake8_pyi::rules::pep_484_positional_parameter(checker, function_def); } - if checker.enabled(Rule::DunderFunctionName) { + if checker.is_rule_enabled(Rule::DunderFunctionName) { pep8_naming::rules::dunder_function_name( checker, checker.semantic.current_scope(), @@ -192,29 +192,29 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::GlobalStatement) { + if checker.is_rule_enabled(Rule::GlobalStatement) { pylint::rules::global_statement(checker, name); } - if checker.enabled(Rule::LRUCacheWithoutParameters) { + if checker.is_rule_enabled(Rule::LRUCacheWithoutParameters) { if checker.target_version() >= PythonVersion::PY38 { pyupgrade::rules::lru_cache_without_parameters(checker, decorator_list); } } - if checker.enabled(Rule::LRUCacheWithMaxsizeNone) { + 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.enabled(Rule::CachedInstanceMethod) { + if checker.is_rule_enabled(Rule::CachedInstanceMethod) { flake8_bugbear::rules::cached_instance_method(checker, function_def); } - if checker.enabled(Rule::MutableArgumentDefault) { + if checker.is_rule_enabled(Rule::MutableArgumentDefault) { flake8_bugbear::rules::mutable_argument_default(checker, function_def); } - if checker.enabled(Rule::ReturnInGenerator) { + if checker.is_rule_enabled(Rule::ReturnInGenerator) { flake8_bugbear::rules::return_in_generator(checker, function_def); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::UnnecessaryReturnNone, Rule::ImplicitReturnValue, Rule::ImplicitReturn, @@ -226,7 +226,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ]) { flake8_return::rules::function(checker, function_def); } - if checker.enabled(Rule::UselessReturn) { + if checker.is_rule_enabled(Rule::UselessReturn) { pylint::rules::useless_return( checker, stmt, @@ -234,7 +234,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { returns.as_ref().map(AsRef::as_ref), ); } - if checker.enabled(Rule::ComplexStructure) { + if checker.is_rule_enabled(Rule::ComplexStructure) { mccabe::rules::function_is_too_complex( checker, stmt, @@ -243,24 +243,24 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { checker.settings.mccabe.max_complexity, ); } - if checker.enabled(Rule::HardcodedPasswordDefault) { + if checker.is_rule_enabled(Rule::HardcodedPasswordDefault) { flake8_bandit::rules::hardcoded_password_default(checker, parameters); } - if checker.enabled(Rule::SuspiciousMarkSafeUsage) { + if checker.is_rule_enabled(Rule::SuspiciousMarkSafeUsage) { for decorator in decorator_list { flake8_bandit::rules::suspicious_function_decorator(checker, decorator); } } - if checker.enabled(Rule::PropertyWithParameters) { + if checker.is_rule_enabled(Rule::PropertyWithParameters) { pylint::rules::property_with_parameters(checker, stmt, decorator_list, parameters); } - if checker.enabled(Rule::TooManyArguments) { + if checker.is_rule_enabled(Rule::TooManyArguments) { pylint::rules::too_many_arguments(checker, function_def); } - if checker.enabled(Rule::TooManyPositionalArguments) { + if checker.is_rule_enabled(Rule::TooManyPositionalArguments) { pylint::rules::too_many_positional_arguments(checker, function_def); } - if checker.enabled(Rule::TooManyReturnStatements) { + if checker.is_rule_enabled(Rule::TooManyReturnStatements) { pylint::rules::too_many_return_statements( checker, stmt, @@ -268,7 +268,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { checker.settings.pylint.max_returns, ); } - if checker.enabled(Rule::TooManyBranches) { + if checker.is_rule_enabled(Rule::TooManyBranches) { pylint::rules::too_many_branches( checker, stmt, @@ -276,7 +276,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { checker.settings.pylint.max_branches, ); } - if checker.enabled(Rule::TooManyStatements) { + if checker.is_rule_enabled(Rule::TooManyStatements) { pylint::rules::too_many_statements( checker, stmt, @@ -284,7 +284,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { checker.settings.pylint.max_statements, ); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::PytestFixtureIncorrectParenthesesStyle, Rule::PytestFixturePositionalArgs, Rule::PytestExtraneousScopeFunction, @@ -305,13 +305,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::PytestIncorrectMarkParenthesesStyle, Rule::PytestUseFixturesWithoutParameters, ]) { flake8_pytest_style::rules::marks(checker, decorator_list); } - if checker.enabled(Rule::BooleanTypeHintPositionalArgument) { + if checker.is_rule_enabled(Rule::BooleanTypeHintPositionalArgument) { flake8_boolean_trap::rules::boolean_type_hint_positional_argument( checker, name, @@ -319,7 +319,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { parameters, ); } - if checker.enabled(Rule::BooleanDefaultValuePositionalArgument) { + if checker.is_rule_enabled(Rule::BooleanDefaultValuePositionalArgument) { flake8_boolean_trap::rules::boolean_default_value_positional_argument( checker, name, @@ -327,7 +327,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { parameters, ); } - if checker.enabled(Rule::UnexpectedSpecialMethodSignature) { + if checker.is_rule_enabled(Rule::UnexpectedSpecialMethodSignature) { pylint::rules::unexpected_special_method_signature( checker, stmt, @@ -336,51 +336,51 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { parameters, ); } - if checker.enabled(Rule::FStringDocstring) { + 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.enabled(Rule::BuiltinVariableShadowing) { + if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) { flake8_builtins::rules::builtin_variable_shadowing(checker, name, name.range()); } } - if checker.enabled(Rule::AsyncFunctionWithTimeout) { + 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.enabled(Rule::UnreachableCode) { + if checker.is_rule_enabled(Rule::UnreachableCode) { pylint::rules::in_function(checker, name, body); } - if checker.enabled(Rule::ReimplementedOperator) { + if checker.is_rule_enabled(Rule::ReimplementedOperator) { refurb::rules::reimplemented_operator(checker, &function_def.into()); } - if checker.enabled(Rule::SslWithBadDefaults) { + if checker.is_rule_enabled(Rule::SslWithBadDefaults) { flake8_bandit::rules::ssl_with_bad_defaults(checker, function_def); } - if checker.enabled(Rule::UnusedAsync) { + if checker.is_rule_enabled(Rule::UnusedAsync) { ruff::rules::unused_async(checker, function_def); } - if checker.enabled(Rule::WhitespaceAfterDecorator) { + if checker.is_rule_enabled(Rule::WhitespaceAfterDecorator) { pycodestyle::rules::whitespace_after_decorator(checker, decorator_list); } - if checker.enabled(Rule::PostInitDefault) { + if checker.is_rule_enabled(Rule::PostInitDefault) { ruff::rules::post_init_default(checker, function_def); } - if checker.enabled(Rule::PytestParameterWithDefaultArgument) { + if checker.is_rule_enabled(Rule::PytestParameterWithDefaultArgument) { flake8_pytest_style::rules::parameter_with_default_argument(checker, function_def); } - if checker.enabled(Rule::Airflow3Removal) { + if checker.is_rule_enabled(Rule::Airflow3Removal) { airflow::rules::airflow_3_removal_function_def(checker, function_def); } - if checker.enabled(Rule::NonPEP695GenericFunction) { + if checker.is_rule_enabled(Rule::NonPEP695GenericFunction) { pyupgrade::rules::non_pep695_generic_function(checker, function_def); } - if checker.enabled(Rule::InvalidArgumentName) { + if checker.is_rule_enabled(Rule::InvalidArgumentName) { pep8_naming::rules::invalid_argument_name_function(checker, function_def); } } Stmt::Return(_) => { - if checker.enabled(Rule::ReturnInInit) { + if checker.is_rule_enabled(Rule::ReturnInInit) { pylint::rules::return_in_init(checker, stmt); } } @@ -395,66 +395,66 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::NoClassmethodDecorator) { + if checker.is_rule_enabled(Rule::NoClassmethodDecorator) { pylint::rules::no_classmethod_decorator(checker, stmt); } - if checker.enabled(Rule::NoStaticmethodDecorator) { + if checker.is_rule_enabled(Rule::NoStaticmethodDecorator) { pylint::rules::no_staticmethod_decorator(checker, stmt); } - if checker.enabled(Rule::DjangoNullableModelStringField) { + if checker.is_rule_enabled(Rule::DjangoNullableModelStringField) { flake8_django::rules::nullable_model_string_field(checker, body); } - if checker.enabled(Rule::DjangoExcludeWithModelForm) { + if checker.is_rule_enabled(Rule::DjangoExcludeWithModelForm) { flake8_django::rules::exclude_with_model_form(checker, class_def); } - if checker.enabled(Rule::DjangoAllWithModelForm) { + if checker.is_rule_enabled(Rule::DjangoAllWithModelForm) { flake8_django::rules::all_with_model_form(checker, class_def); } - if checker.enabled(Rule::DjangoUnorderedBodyContentInModel) { + 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.enabled(Rule::DjangoModelWithoutDunderStr) { + if checker.is_rule_enabled(Rule::DjangoModelWithoutDunderStr) { flake8_django::rules::model_without_dunder_str(checker, class_def); } } - if checker.enabled(Rule::EqWithoutHash) { + if checker.is_rule_enabled(Rule::EqWithoutHash) { pylint::rules::object_without_hash_method(checker, class_def); } - if checker.enabled(Rule::ClassAsDataStructure) { + if checker.is_rule_enabled(Rule::ClassAsDataStructure) { flake8_bugbear::rules::class_as_data_structure(checker, class_def); } - if checker.enabled(Rule::RedefinedSlotsInSubclass) { + if checker.is_rule_enabled(Rule::RedefinedSlotsInSubclass) { pylint::rules::redefined_slots_in_subclass(checker, class_def); } - if checker.enabled(Rule::TooManyPublicMethods) { + if checker.is_rule_enabled(Rule::TooManyPublicMethods) { pylint::rules::too_many_public_methods( checker, class_def, checker.settings.pylint.max_public_methods, ); } - if checker.enabled(Rule::GlobalStatement) { + if checker.is_rule_enabled(Rule::GlobalStatement) { pylint::rules::global_statement(checker, name); } - if checker.enabled(Rule::UselessObjectInheritance) { + if checker.is_rule_enabled(Rule::UselessObjectInheritance) { pyupgrade::rules::useless_object_inheritance(checker, class_def); } - if checker.enabled(Rule::UselessClassMetaclassType) { + if checker.is_rule_enabled(Rule::UselessClassMetaclassType) { pyupgrade::rules::useless_class_metaclass_type(checker, class_def); } - if checker.enabled(Rule::ReplaceStrEnum) { + if checker.is_rule_enabled(Rule::ReplaceStrEnum) { if checker.target_version() >= PythonVersion::PY311 { pyupgrade::rules::replace_str_enum(checker, class_def); } } - if checker.enabled(Rule::UnnecessaryClassParentheses) { + if checker.is_rule_enabled(Rule::UnnecessaryClassParentheses) { pyupgrade::rules::unnecessary_class_parentheses(checker, class_def); } - if checker.enabled(Rule::AmbiguousClassName) { + if checker.is_rule_enabled(Rule::AmbiguousClassName) { pycodestyle::rules::ambiguous_class_name(checker, name); } - if checker.enabled(Rule::InvalidClassName) { + if checker.is_rule_enabled(Rule::InvalidClassName) { pep8_naming::rules::invalid_class_name( checker, stmt, @@ -462,7 +462,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::ErrorSuffixOnExceptionName) { + if checker.is_rule_enabled(Rule::ErrorSuffixOnExceptionName) { pep8_naming::rules::error_suffix_on_exception_name( checker, stmt, @@ -472,7 +472,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } if !checker.source_type.is_stub() { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::AbstractBaseClassWithoutAbstractMethod, Rule::EmptyMethodWithoutAbstractDecorator, ]) { @@ -486,71 +486,71 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } if checker.source_type.is_stub() { - if checker.enabled(Rule::PassStatementStubBody) { + if checker.is_rule_enabled(Rule::PassStatementStubBody) { flake8_pyi::rules::pass_statement_stub_body(checker, body); } - if checker.enabled(Rule::PassInClassBody) { + if checker.is_rule_enabled(Rule::PassInClassBody) { flake8_pyi::rules::pass_in_class_body(checker, class_def); } } - if checker.enabled(Rule::EllipsisInNonEmptyClassBody) { + if checker.is_rule_enabled(Rule::EllipsisInNonEmptyClassBody) { flake8_pyi::rules::ellipsis_in_non_empty_class_body(checker, body); } - if checker.enabled(Rule::GenericNotLastBaseClass) { + if checker.is_rule_enabled(Rule::GenericNotLastBaseClass) { flake8_pyi::rules::generic_not_last_base_class(checker, class_def); } - if checker.enabled(Rule::PytestIncorrectMarkParenthesesStyle) { + if checker.is_rule_enabled(Rule::PytestIncorrectMarkParenthesesStyle) { flake8_pytest_style::rules::marks(checker, decorator_list); } - if checker.enabled(Rule::DuplicateClassFieldDefinition) { + if checker.is_rule_enabled(Rule::DuplicateClassFieldDefinition) { flake8_pie::rules::duplicate_class_field_definition(checker, body); } - if checker.enabled(Rule::NonUniqueEnums) { + if checker.is_rule_enabled(Rule::NonUniqueEnums) { flake8_pie::rules::non_unique_enums(checker, stmt, body); } - if checker.enabled(Rule::FStringDocstring) { + if checker.is_rule_enabled(Rule::FStringDocstring) { flake8_bugbear::rules::f_string_docstring(checker, body); } - if checker.enabled(Rule::BuiltinVariableShadowing) { + if checker.is_rule_enabled(Rule::BuiltinVariableShadowing) { flake8_builtins::rules::builtin_variable_shadowing(checker, name, name.range()); } - if checker.enabled(Rule::DuplicateBases) { + if checker.is_rule_enabled(Rule::DuplicateBases) { pylint::rules::duplicate_bases(checker, name, arguments.as_deref()); } - if checker.enabled(Rule::NoSlotsInStrSubclass) { + if checker.is_rule_enabled(Rule::NoSlotsInStrSubclass) { flake8_slots::rules::no_slots_in_str_subclass(checker, stmt, class_def); } - if checker.enabled(Rule::NoSlotsInTupleSubclass) { + if checker.is_rule_enabled(Rule::NoSlotsInTupleSubclass) { flake8_slots::rules::no_slots_in_tuple_subclass(checker, stmt, class_def); } - if checker.enabled(Rule::NoSlotsInNamedtupleSubclass) { + if checker.is_rule_enabled(Rule::NoSlotsInNamedtupleSubclass) { flake8_slots::rules::no_slots_in_namedtuple_subclass(checker, stmt, class_def); } - if checker.enabled(Rule::NonSlotAssignment) { + if checker.is_rule_enabled(Rule::NonSlotAssignment) { pylint::rules::non_slot_assignment(checker, class_def); } - if checker.enabled(Rule::SingleStringSlots) { + if checker.is_rule_enabled(Rule::SingleStringSlots) { pylint::rules::single_string_slots(checker, class_def); } - if checker.enabled(Rule::MetaClassABCMeta) { + if checker.is_rule_enabled(Rule::MetaClassABCMeta) { refurb::rules::metaclass_abcmeta(checker, class_def); } - if checker.enabled(Rule::WhitespaceAfterDecorator) { + if checker.is_rule_enabled(Rule::WhitespaceAfterDecorator) { pycodestyle::rules::whitespace_after_decorator(checker, decorator_list); } - if checker.enabled(Rule::SubclassBuiltin) { + if checker.is_rule_enabled(Rule::SubclassBuiltin) { refurb::rules::subclass_builtin(checker, class_def); } - if checker.enabled(Rule::DataclassEnum) { + if checker.is_rule_enabled(Rule::DataclassEnum) { ruff::rules::dataclass_enum(checker, class_def); } - if checker.enabled(Rule::NonPEP695GenericClass) { + if checker.is_rule_enabled(Rule::NonPEP695GenericClass) { pyupgrade::rules::non_pep695_generic_class(checker, class_def); } - if checker.enabled(Rule::ClassWithMixedTypeVars) { + if checker.is_rule_enabled(Rule::ClassWithMixedTypeVars) { ruff::rules::class_with_mixed_type_vars(checker, class_def); } - if checker.enabled(Rule::ImplicitClassVarInDataclass) { + if checker.is_rule_enabled(Rule::ImplicitClassVarInDataclass) { ruff::rules::implicit_class_var_in_dataclass(checker, class_def); } } @@ -559,16 +559,16 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { range: _, node_index: _, }) => { - if checker.enabled(Rule::MultipleImportsOnOneLine) { + if checker.is_rule_enabled(Rule::MultipleImportsOnOneLine) { pycodestyle::rules::multiple_imports_on_one_line(checker, stmt, names); } - if checker.enabled(Rule::ModuleImportNotAtTopOfFile) { + if checker.is_rule_enabled(Rule::ModuleImportNotAtTopOfFile) { pycodestyle::rules::module_import_not_at_top_of_file(checker, stmt); } - if checker.enabled(Rule::ImportOutsideTopLevel) { + if checker.is_rule_enabled(Rule::ImportOutsideTopLevel) { pylint::rules::import_outside_top_level(checker, stmt); } - if checker.enabled(Rule::GlobalStatement) { + 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); @@ -577,13 +577,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } - if checker.enabled(Rule::DeprecatedCElementTree) { + if checker.is_rule_enabled(Rule::DeprecatedCElementTree) { pyupgrade::rules::deprecated_c_element_tree(checker, stmt); } - if checker.enabled(Rule::DeprecatedMockImport) { + if checker.is_rule_enabled(Rule::DeprecatedMockImport) { pyupgrade::rules::deprecated_mock_import(checker, stmt); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SuspiciousTelnetlibImport, Rule::SuspiciousFtplibImport, Rule::SuspiciousPickleImport, @@ -602,19 +602,19 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { flake8_bandit::rules::suspicious_imports(checker, stmt); } - if checker.enabled(Rule::BannedModuleLevelImports) { + if checker.is_rule_enabled(Rule::BannedModuleLevelImports) { flake8_tidy_imports::rules::banned_module_level_imports(checker, stmt); } for alias in names { - if checker.enabled(Rule::NonAsciiImportName) { + if checker.is_rule_enabled(Rule::NonAsciiImportName) { pylint::rules::non_ascii_module_import(checker, alias); } - if checker.enabled(Rule::Debugger) { + if checker.is_rule_enabled(Rule::Debugger) { flake8_debugger::rules::debugger_import(checker, stmt, None, &alias.name); } - if checker.enabled(Rule::BannedApi) { + if checker.is_rule_enabled(Rule::BannedApi) { flake8_tidy_imports::rules::banned_api( checker, &flake8_tidy_imports::matchers::NameMatchPolicy::MatchNameOrParent( @@ -627,19 +627,19 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } if !checker.source_type.is_stub() { - if checker.enabled(Rule::UselessImportAlias) { + if checker.is_rule_enabled(Rule::UselessImportAlias) { pylint::rules::useless_import_alias(checker, alias); } } - if checker.enabled(Rule::ManualFromImport) { + if checker.is_rule_enabled(Rule::ManualFromImport) { pylint::rules::manual_from_import(checker, stmt, alias, names); } - if checker.enabled(Rule::ImportSelf) { + 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.enabled(Rule::ConstantImportedAsNonConstant) { + if checker.is_rule_enabled(Rule::ConstantImportedAsNonConstant) { pep8_naming::rules::constant_imported_as_non_constant( checker, name, @@ -649,7 +649,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::LowercaseImportedAsNonLowercase) { + if checker.is_rule_enabled(Rule::LowercaseImportedAsNonLowercase) { pep8_naming::rules::lowercase_imported_as_non_lowercase( checker, name, @@ -659,7 +659,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::CamelcaseImportedAsLowercase) { + if checker.is_rule_enabled(Rule::CamelcaseImportedAsLowercase) { pep8_naming::rules::camelcase_imported_as_lowercase( checker, name, @@ -669,7 +669,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::CamelcaseImportedAsConstant) { + if checker.is_rule_enabled(Rule::CamelcaseImportedAsConstant) { pep8_naming::rules::camelcase_imported_as_constant( checker, name, @@ -679,13 +679,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::CamelcaseImportedAsAcronym) { + if checker.is_rule_enabled(Rule::CamelcaseImportedAsAcronym) { pep8_naming::rules::camelcase_imported_as_acronym( name, asname, alias, stmt, checker, ); } } - if checker.enabled(Rule::BannedImportAlias) { + if checker.is_rule_enabled(Rule::BannedImportAlias) { if let Some(asname) = &alias.asname { flake8_import_conventions::rules::banned_import_alias( checker, @@ -696,7 +696,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } } - if checker.enabled(Rule::PytestIncorrectPytestImport) { + if checker.is_rule_enabled(Rule::PytestIncorrectPytestImport) { flake8_pytest_style::rules::import( checker, stmt, @@ -704,7 +704,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { alias.asname.as_deref(), ); } - if checker.enabled(Rule::BuiltinImportShadowing) { + if checker.is_rule_enabled(Rule::BuiltinImportShadowing) { flake8_builtins::rules::builtin_import_shadowing(checker, alias); } } @@ -720,13 +720,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ) => { let level = *level; let module = module.as_deref(); - if checker.enabled(Rule::ModuleImportNotAtTopOfFile) { + if checker.is_rule_enabled(Rule::ModuleImportNotAtTopOfFile) { pycodestyle::rules::module_import_not_at_top_of_file(checker, stmt); } - if checker.enabled(Rule::ImportOutsideTopLevel) { + if checker.is_rule_enabled(Rule::ImportOutsideTopLevel) { pylint::rules::import_outside_top_level(checker, stmt); } - if checker.enabled(Rule::GlobalStatement) { + 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); @@ -735,33 +735,33 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } - if checker.enabled(Rule::NonAsciiImportName) { + if checker.is_rule_enabled(Rule::NonAsciiImportName) { for alias in names { pylint::rules::non_ascii_module_import(checker, alias); } } - if checker.enabled(Rule::UnnecessaryFutureImport) { + if checker.is_rule_enabled(Rule::UnnecessaryFutureImport) { if checker.target_version() >= PythonVersion::PY37 { if let Some("__future__") = module { pyupgrade::rules::unnecessary_future_import(checker, stmt, names); } } } - if checker.enabled(Rule::DeprecatedMockImport) { + if checker.is_rule_enabled(Rule::DeprecatedMockImport) { pyupgrade::rules::deprecated_mock_import(checker, stmt); } - if checker.enabled(Rule::DeprecatedCElementTree) { + if checker.is_rule_enabled(Rule::DeprecatedCElementTree) { pyupgrade::rules::deprecated_c_element_tree(checker, stmt); } - if checker.enabled(Rule::DeprecatedImport) { + if checker.is_rule_enabled(Rule::DeprecatedImport) { pyupgrade::rules::deprecated_import(checker, import_from); } - if checker.enabled(Rule::UnnecessaryBuiltinImport) { + if checker.is_rule_enabled(Rule::UnnecessaryBuiltinImport) { if let Some(module) = module { pyupgrade::rules::unnecessary_builtin_import(checker, stmt, module, names); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SuspiciousTelnetlibImport, Rule::SuspiciousFtplibImport, Rule::SuspiciousPickleImport, @@ -779,7 +779,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ]) { flake8_bandit::rules::suspicious_imports(checker, stmt); } - if checker.enabled(Rule::BannedApi) { + if checker.is_rule_enabled(Rule::BannedApi) { if let Some(module) = helpers::resolve_imported_module_path( level, module, @@ -810,25 +810,25 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } - if checker.enabled(Rule::BannedModuleLevelImports) { + if checker.is_rule_enabled(Rule::BannedModuleLevelImports) { flake8_tidy_imports::rules::banned_module_level_imports(checker, stmt); } - if checker.enabled(Rule::PytestIncorrectPytestImport) { + if checker.is_rule_enabled(Rule::PytestIncorrectPytestImport) { flake8_pytest_style::rules::import_from(checker, stmt, module, level); } if checker.source_type.is_stub() { - if checker.enabled(Rule::FutureAnnotationsInStub) { + if checker.is_rule_enabled(Rule::FutureAnnotationsInStub) { flake8_pyi::rules::from_future_import(checker, import_from); } } for alias in names { if let Some("__future__") = module { - if checker.enabled(Rule::FutureFeatureNotDefined) { + if checker.is_rule_enabled(Rule::FutureFeatureNotDefined) { pyflakes::rules::future_feature_not_defined(checker, alias); } } else if &alias.name == "*" { - if checker.enabled(Rule::UndefinedLocalWithNestedImportStarUsage) { + if checker.is_rule_enabled(Rule::UndefinedLocalWithNestedImportStarUsage) { if !matches!(checker.semantic.current_scope().kind, ScopeKind::Module) { checker.report_diagnostic( pyflakes::rules::UndefinedLocalWithNestedImportStarUsage { @@ -838,7 +838,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } } - if checker.enabled(Rule::UndefinedLocalWithImportStar) { + if checker.is_rule_enabled(Rule::UndefinedLocalWithImportStar) { checker.report_diagnostic( pyflakes::rules::UndefinedLocalWithImportStar { name: helpers::format_import_from(level, module).to_string(), @@ -847,7 +847,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } } - if checker.enabled(Rule::RelativeImports) { + if checker.is_rule_enabled(Rule::RelativeImports) { flake8_tidy_imports::rules::banned_relative_import( checker, stmt, @@ -857,10 +857,10 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { checker.settings.flake8_tidy_imports.ban_relative_imports, ); } - if checker.enabled(Rule::Debugger) { + if checker.is_rule_enabled(Rule::Debugger) { flake8_debugger::rules::debugger_import(checker, stmt, module, &alias.name); } - if checker.enabled(Rule::BannedImportAlias) { + if checker.is_rule_enabled(Rule::BannedImportAlias) { if let Some(asname) = &alias.asname { let qualified_name = helpers::format_import_from_member(level, module, &alias.name); @@ -874,7 +874,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } if let Some(asname) = &alias.asname { - if checker.enabled(Rule::ConstantImportedAsNonConstant) { + if checker.is_rule_enabled(Rule::ConstantImportedAsNonConstant) { pep8_naming::rules::constant_imported_as_non_constant( checker, &alias.name, @@ -884,7 +884,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::LowercaseImportedAsNonLowercase) { + if checker.is_rule_enabled(Rule::LowercaseImportedAsNonLowercase) { pep8_naming::rules::lowercase_imported_as_non_lowercase( checker, &alias.name, @@ -894,7 +894,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::CamelcaseImportedAsLowercase) { + if checker.is_rule_enabled(Rule::CamelcaseImportedAsLowercase) { pep8_naming::rules::camelcase_imported_as_lowercase( checker, &alias.name, @@ -904,7 +904,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::CamelcaseImportedAsConstant) { + if checker.is_rule_enabled(Rule::CamelcaseImportedAsConstant) { pep8_naming::rules::camelcase_imported_as_constant( checker, &alias.name, @@ -914,7 +914,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.pep8_naming.ignore_names, ); } - if checker.enabled(Rule::CamelcaseImportedAsAcronym) { + if checker.is_rule_enabled(Rule::CamelcaseImportedAsAcronym) { pep8_naming::rules::camelcase_imported_as_acronym( &alias.name, asname, @@ -924,16 +924,16 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } if !checker.source_type.is_stub() { - if checker.enabled(Rule::UselessImportAlias) { + if checker.is_rule_enabled(Rule::UselessImportAlias) { pylint::rules::useless_import_from_alias(checker, alias, module, level); } } } - if checker.enabled(Rule::BuiltinImportShadowing) { + if checker.is_rule_enabled(Rule::BuiltinImportShadowing) { flake8_builtins::rules::builtin_import_shadowing(checker, alias); } } - if checker.enabled(Rule::ImportSelf) { + if checker.is_rule_enabled(Rule::ImportSelf) { pylint::rules::import_from_self( checker, level, @@ -942,7 +942,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { checker.module.qualified_name(), ); } - if checker.enabled(Rule::BannedImportFrom) { + if checker.is_rule_enabled(Rule::BannedImportFrom) { flake8_import_conventions::rules::banned_import_from( checker, stmt, @@ -950,22 +950,22 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { &checker.settings.flake8_import_conventions.banned_from, ); } - if checker.enabled(Rule::ByteStringUsage) { + if checker.is_rule_enabled(Rule::ByteStringUsage) { flake8_pyi::rules::bytestring_import(checker, import_from); } } Stmt::Raise(raise @ ast::StmtRaise { exc, .. }) => { - if checker.enabled(Rule::RaiseNotImplemented) { + if checker.is_rule_enabled(Rule::RaiseNotImplemented) { if let Some(expr) = exc { pyflakes::rules::raise_not_implemented(checker, expr); } } - if checker.enabled(Rule::RaiseLiteral) { + if checker.is_rule_enabled(Rule::RaiseLiteral) { if let Some(exc) = exc { flake8_bugbear::rules::raise_literal(checker, exc); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::RawStringInException, Rule::FStringInException, Rule::DotFormatInException, @@ -974,44 +974,44 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { flake8_errmsg::rules::string_in_exception(checker, stmt, exc); } } - if checker.enabled(Rule::OSErrorAlias) { + if checker.is_rule_enabled(Rule::OSErrorAlias) { if let Some(item) = exc { pyupgrade::rules::os_error_alias_raise(checker, item); } } - if checker.enabled(Rule::TimeoutErrorAlias) { + if checker.is_rule_enabled(Rule::TimeoutErrorAlias) { if checker.target_version() >= PythonVersion::PY310 { if let Some(item) = exc { pyupgrade::rules::timeout_error_alias_raise(checker, item); } } } - if checker.enabled(Rule::RaiseVanillaClass) { + if checker.is_rule_enabled(Rule::RaiseVanillaClass) { if let Some(expr) = exc { tryceratops::rules::raise_vanilla_class(checker, expr); } } - if checker.enabled(Rule::RaiseVanillaArgs) { + if checker.is_rule_enabled(Rule::RaiseVanillaArgs) { if let Some(expr) = exc { tryceratops::rules::raise_vanilla_args(checker, expr); } } - if checker.enabled(Rule::UnnecessaryParenOnRaiseException) { + if checker.is_rule_enabled(Rule::UnnecessaryParenOnRaiseException) { if let Some(expr) = exc { flake8_raise::rules::unnecessary_paren_on_raise_exception(checker, expr); } } - if checker.enabled(Rule::MisplacedBareRaise) { + if checker.is_rule_enabled(Rule::MisplacedBareRaise) { pylint::rules::misplaced_bare_raise(checker, raise); } } Stmt::AugAssign(aug_assign @ ast::StmtAugAssign { target, .. }) => { - if checker.enabled(Rule::GlobalStatement) { + if checker.is_rule_enabled(Rule::GlobalStatement) { if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() { pylint::rules::global_statement(checker, id); } } - if checker.enabled(Rule::UnsortedDunderAll) { + if checker.is_rule_enabled(Rule::UnsortedDunderAll) { ruff::rules::sort_dunder_all_aug_assign(checker, aug_assign); } } @@ -1022,64 +1022,64 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { .. }, ) => { - if checker.enabled(Rule::TooManyNestedBlocks) { + if checker.is_rule_enabled(Rule::TooManyNestedBlocks) { pylint::rules::too_many_nested_blocks(checker, stmt); } - if checker.enabled(Rule::EmptyTypeCheckingBlock) { + if checker.is_rule_enabled(Rule::EmptyTypeCheckingBlock) { flake8_type_checking::rules::empty_type_checking_block(checker, if_); } - if checker.enabled(Rule::IfTuple) { + if checker.is_rule_enabled(Rule::IfTuple) { pyflakes::rules::if_tuple(checker, if_); } - if checker.enabled(Rule::CollapsibleIf) { + if checker.is_rule_enabled(Rule::CollapsibleIf) { flake8_simplify::rules::nested_if_statements( checker, if_, checker.semantic.current_statement_parent(), ); } - if checker.enabled(Rule::IfWithSameArms) { + if checker.is_rule_enabled(Rule::IfWithSameArms) { flake8_simplify::rules::if_with_same_arms(checker, if_); } - if checker.enabled(Rule::NeedlessBool) { + if checker.is_rule_enabled(Rule::NeedlessBool) { flake8_simplify::rules::needless_bool(checker, stmt); } - if checker.enabled(Rule::IfElseBlockInsteadOfDictLookup) { + if checker.is_rule_enabled(Rule::IfElseBlockInsteadOfDictLookup) { flake8_simplify::rules::if_else_block_instead_of_dict_lookup(checker, if_); } - if checker.enabled(Rule::IfElseBlockInsteadOfIfExp) { + if checker.is_rule_enabled(Rule::IfElseBlockInsteadOfIfExp) { flake8_simplify::rules::if_else_block_instead_of_if_exp(checker, if_); } - if checker.enabled(Rule::IfElseBlockInsteadOfDictGet) { + if checker.is_rule_enabled(Rule::IfElseBlockInsteadOfDictGet) { flake8_simplify::rules::if_else_block_instead_of_dict_get(checker, if_); } - if checker.enabled(Rule::TypeCheckWithoutTypeError) { + if checker.is_rule_enabled(Rule::TypeCheckWithoutTypeError) { tryceratops::rules::type_check_without_type_error( checker, if_, checker.semantic.current_statement_parent(), ); } - if checker.enabled(Rule::OutdatedVersionBlock) { + if checker.is_rule_enabled(Rule::OutdatedVersionBlock) { pyupgrade::rules::outdated_version_block(checker, if_); } - if checker.enabled(Rule::CollapsibleElseIf) { + if checker.is_rule_enabled(Rule::CollapsibleElseIf) { pylint::rules::collapsible_else_if(checker, stmt); } - if checker.enabled(Rule::CheckAndRemoveFromSet) { + if checker.is_rule_enabled(Rule::CheckAndRemoveFromSet) { refurb::rules::check_and_remove_from_set(checker, if_); } - if checker.enabled(Rule::SliceToRemovePrefixOrSuffix) { + if checker.is_rule_enabled(Rule::SliceToRemovePrefixOrSuffix) { refurb::rules::slice_to_remove_affix_stmt(checker, if_); } - if checker.enabled(Rule::TooManyBooleanExpressions) { + if checker.is_rule_enabled(Rule::TooManyBooleanExpressions) { pylint::rules::too_many_boolean_expressions(checker, if_); } - if checker.enabled(Rule::IfStmtMinMax) { + if checker.is_rule_enabled(Rule::IfStmtMinMax) { pylint::rules::if_stmt_min_max(checker, if_); } if checker.source_type.is_stub() { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::UnrecognizedVersionInfoCheck, Rule::PatchVersionComparison, Rule::WrongTupleLengthVersionComparison, @@ -1092,7 +1092,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { flake8_pyi::rules::unrecognized_version_info(checker, test); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::UnrecognizedPlatformCheck, Rule::UnrecognizedPlatformName, ]) { @@ -1104,7 +1104,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { flake8_pyi::rules::unrecognized_platform(checker, test); } } - if checker.enabled(Rule::ComplexIfStatementInStub) { + if checker.is_rule_enabled(Rule::ComplexIfStatementInStub) { if let Expr::BoolOp(ast::ExprBoolOp { values, .. }) = test.as_ref() { for value in values { flake8_pyi::rules::complex_if_statement_in_stub(checker, value); @@ -1114,7 +1114,9 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } - if checker.any_enabled(&[Rule::BadVersionInfoComparison, Rule::BadVersionInfoOrder]) { + if checker + .any_rule_enabled(&[Rule::BadVersionInfoComparison, Rule::BadVersionInfoOrder]) + { fn bad_version_info_comparison( checker: &Checker, test: &Expr, @@ -1147,10 +1149,10 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } - if checker.enabled(Rule::IfKeyInDictDel) { + if checker.is_rule_enabled(Rule::IfKeyInDictDel) { ruff::rules::if_key_in_dict_del(checker, if_); } - if checker.enabled(Rule::NeedlessElse) { + if checker.is_rule_enabled(Rule::NeedlessElse) { ruff::rules::needless_else(checker, if_.into()); } } @@ -1163,20 +1165,20 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { }, ) => { if !checker.semantic.in_type_checking_block() { - if checker.enabled(Rule::Assert) { + if checker.is_rule_enabled(Rule::Assert) { flake8_bandit::rules::assert_used(checker, stmt); } } - if checker.enabled(Rule::AssertTuple) { + if checker.is_rule_enabled(Rule::AssertTuple) { pyflakes::rules::assert_tuple(checker, stmt, test); } - if checker.enabled(Rule::AssertFalse) { + if checker.is_rule_enabled(Rule::AssertFalse) { flake8_bugbear::rules::assert_false(checker, stmt, test, msg.as_deref()); } - if checker.enabled(Rule::PytestAssertAlwaysFalse) { + if checker.is_rule_enabled(Rule::PytestAssertAlwaysFalse) { flake8_pytest_style::rules::assert_falsy(checker, stmt, test); } - if checker.enabled(Rule::PytestCompositeAssertion) { + if checker.is_rule_enabled(Rule::PytestCompositeAssertion) { flake8_pytest_style::rules::composite_condition( checker, stmt, @@ -1184,72 +1186,72 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { msg.as_deref(), ); } - if checker.enabled(Rule::AssertOnStringLiteral) { + if checker.is_rule_enabled(Rule::AssertOnStringLiteral) { pylint::rules::assert_on_string_literal(checker, test); } - if checker.enabled(Rule::InvalidMockAccess) { + if checker.is_rule_enabled(Rule::InvalidMockAccess) { pygrep_hooks::rules::non_existent_mock_method(checker, test); } - if checker.enabled(Rule::AssertWithPrintMessage) { + if checker.is_rule_enabled(Rule::AssertWithPrintMessage) { ruff::rules::assert_with_print_message(checker, assert_stmt); } - if checker.enabled(Rule::InvalidAssertMessageLiteralArgument) { + if checker.is_rule_enabled(Rule::InvalidAssertMessageLiteralArgument) { ruff::rules::invalid_assert_message_literal_argument(checker, assert_stmt); } } Stmt::With(with_stmt @ ast::StmtWith { items, body, .. }) => { - if checker.enabled(Rule::TooManyNestedBlocks) { + if checker.is_rule_enabled(Rule::TooManyNestedBlocks) { pylint::rules::too_many_nested_blocks(checker, stmt); } - if checker.enabled(Rule::AssertRaisesException) { + if checker.is_rule_enabled(Rule::AssertRaisesException) { flake8_bugbear::rules::assert_raises_exception(checker, items); } - if checker.enabled(Rule::PytestRaisesWithMultipleStatements) { + if checker.is_rule_enabled(Rule::PytestRaisesWithMultipleStatements) { flake8_pytest_style::rules::complex_raises(checker, stmt, items, body); } - if checker.enabled(Rule::PytestWarnsWithMultipleStatements) { + if checker.is_rule_enabled(Rule::PytestWarnsWithMultipleStatements) { flake8_pytest_style::rules::complex_warns(checker, stmt, items, body); } - if checker.enabled(Rule::MultipleWithStatements) { + if checker.is_rule_enabled(Rule::MultipleWithStatements) { flake8_simplify::rules::multiple_with_statements( checker, with_stmt, checker.semantic.current_statement_parent(), ); } - if checker.enabled(Rule::RedefinedLoopName) { + if checker.is_rule_enabled(Rule::RedefinedLoopName) { pylint::rules::redefined_loop_name(checker, stmt); } - if checker.enabled(Rule::ReadWholeFile) { + if checker.is_rule_enabled(Rule::ReadWholeFile) { refurb::rules::read_whole_file(checker, with_stmt); } - if checker.enabled(Rule::WriteWholeFile) { + if checker.is_rule_enabled(Rule::WriteWholeFile) { refurb::rules::write_whole_file(checker, with_stmt); } - if checker.enabled(Rule::UselessWithLock) { + if checker.is_rule_enabled(Rule::UselessWithLock) { pylint::rules::useless_with_lock(checker, with_stmt); } - if checker.enabled(Rule::CancelScopeNoCheckpoint) { + if checker.is_rule_enabled(Rule::CancelScopeNoCheckpoint) { flake8_async::rules::cancel_scope_no_checkpoint(checker, with_stmt, items); } } Stmt::While(while_stmt @ ast::StmtWhile { body, orelse, .. }) => { - if checker.enabled(Rule::TooManyNestedBlocks) { + if checker.is_rule_enabled(Rule::TooManyNestedBlocks) { pylint::rules::too_many_nested_blocks(checker, stmt); } - if checker.enabled(Rule::FunctionUsesLoopVariable) { + if checker.is_rule_enabled(Rule::FunctionUsesLoopVariable) { flake8_bugbear::rules::function_uses_loop_variable(checker, &Node::Stmt(stmt)); } - if checker.enabled(Rule::UselessElseOnLoop) { + if checker.is_rule_enabled(Rule::UselessElseOnLoop) { pylint::rules::useless_else_on_loop(checker, stmt, body, orelse); } - if checker.enabled(Rule::TryExceptInLoop) { + if checker.is_rule_enabled(Rule::TryExceptInLoop) { perflint::rules::try_except_in_loop(checker, body); } - if checker.enabled(Rule::AsyncBusyWait) { + if checker.is_rule_enabled(Rule::AsyncBusyWait) { flake8_async::rules::async_busy_wait(checker, while_stmt); } - if checker.enabled(Rule::NeedlessElse) { + if checker.is_rule_enabled(Rule::NeedlessElse) { ruff::rules::needless_else(checker, while_stmt.into()); } } @@ -1264,10 +1266,10 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::TooManyNestedBlocks) { + if checker.is_rule_enabled(Rule::TooManyNestedBlocks) { pylint::rules::too_many_nested_blocks(checker, stmt); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::DictIndexMissingItems, Rule::EnumerateForLoop, Rule::IncorrectDictIterator, @@ -1280,64 +1282,64 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ]) { checker.analyze.for_loops.push(checker.semantic.snapshot()); } - if checker.enabled(Rule::LoopVariableOverridesIterator) { + if checker.is_rule_enabled(Rule::LoopVariableOverridesIterator) { flake8_bugbear::rules::loop_variable_overrides_iterator(checker, target, iter); } - if checker.enabled(Rule::FunctionUsesLoopVariable) { + if checker.is_rule_enabled(Rule::FunctionUsesLoopVariable) { flake8_bugbear::rules::function_uses_loop_variable(checker, &Node::Stmt(stmt)); } - if checker.enabled(Rule::ReuseOfGroupbyGenerator) { + if checker.is_rule_enabled(Rule::ReuseOfGroupbyGenerator) { flake8_bugbear::rules::reuse_of_groupby_generator(checker, target, body, iter); } - if checker.enabled(Rule::UselessElseOnLoop) { + if checker.is_rule_enabled(Rule::UselessElseOnLoop) { pylint::rules::useless_else_on_loop(checker, stmt, body, orelse); } - if checker.enabled(Rule::RedefinedLoopName) { + if checker.is_rule_enabled(Rule::RedefinedLoopName) { pylint::rules::redefined_loop_name(checker, stmt); } - if checker.enabled(Rule::IterationOverSet) { + if checker.is_rule_enabled(Rule::IterationOverSet) { pylint::rules::iteration_over_set(checker, iter); } - if checker.enabled(Rule::DictIterMissingItems) { + if checker.is_rule_enabled(Rule::DictIterMissingItems) { pylint::rules::dict_iter_missing_items(checker, target, iter); } - if checker.enabled(Rule::ManualListCopy) { + if checker.is_rule_enabled(Rule::ManualListCopy) { perflint::rules::manual_list_copy(checker, for_stmt); } - if checker.enabled(Rule::ModifiedIteratingSet) { + if checker.is_rule_enabled(Rule::ModifiedIteratingSet) { pylint::rules::modified_iterating_set(checker, for_stmt); } - if checker.enabled(Rule::UnnecessaryListCast) { + if checker.is_rule_enabled(Rule::UnnecessaryListCast) { perflint::rules::unnecessary_list_cast(checker, iter, body); } - if checker.enabled(Rule::UnnecessaryListIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryListIndexLookup) { pylint::rules::unnecessary_list_index_lookup(checker, for_stmt); } - if checker.enabled(Rule::UnnecessaryDictIndexLookup) { + if checker.is_rule_enabled(Rule::UnnecessaryDictIndexLookup) { pylint::rules::unnecessary_dict_index_lookup(checker, for_stmt); } - if checker.enabled(Rule::ReadlinesInFor) { + if checker.is_rule_enabled(Rule::ReadlinesInFor) { refurb::rules::readlines_in_for(checker, for_stmt); } if !*is_async { - if checker.enabled(Rule::ReimplementedBuiltin) { + if checker.is_rule_enabled(Rule::ReimplementedBuiltin) { flake8_simplify::rules::convert_for_loop_to_any_all(checker, stmt); } - if checker.enabled(Rule::InDictKeys) { + if checker.is_rule_enabled(Rule::InDictKeys) { flake8_simplify::rules::key_in_dict_for(checker, for_stmt); } - if checker.enabled(Rule::TryExceptInLoop) { + if checker.is_rule_enabled(Rule::TryExceptInLoop) { perflint::rules::try_except_in_loop(checker, body); } - if checker.enabled(Rule::ForLoopSetMutations) { + if checker.is_rule_enabled(Rule::ForLoopSetMutations) { refurb::rules::for_loop_set_mutations(checker, for_stmt); } - if checker.enabled(Rule::ForLoopWrites) { + if checker.is_rule_enabled(Rule::ForLoopWrites) { refurb::rules::for_loop_writes_stmt(checker, for_stmt); } } - if checker.enabled(Rule::NeedlessElse) { + if checker.is_rule_enabled(Rule::NeedlessElse) { ruff::rules::needless_else(checker, for_stmt.into()); } } @@ -1350,146 +1352,138 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { .. }, ) => { - if checker.enabled(Rule::TooManyNestedBlocks) { + if checker.is_rule_enabled(Rule::TooManyNestedBlocks) { pylint::rules::too_many_nested_blocks(checker, stmt); } - if checker.enabled(Rule::JumpStatementInFinally) { + if checker.is_rule_enabled(Rule::JumpStatementInFinally) { flake8_bugbear::rules::jump_statement_in_finally(checker, finalbody); } - if checker.enabled(Rule::ContinueInFinally) { + if checker.is_rule_enabled(Rule::ContinueInFinally) { if checker.target_version() <= PythonVersion::PY38 { pylint::rules::continue_in_finally(checker, finalbody); } } - if checker.enabled(Rule::DefaultExceptNotLast) { + if checker.is_rule_enabled(Rule::DefaultExceptNotLast) { pyflakes::rules::default_except_not_last(checker, handlers, checker.locator); } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::DuplicateHandlerException, Rule::DuplicateTryBlockException, ]) { flake8_bugbear::rules::duplicate_exceptions(checker, handlers); } - if checker.enabled(Rule::RedundantTupleInExceptionHandler) { + if checker.is_rule_enabled(Rule::RedundantTupleInExceptionHandler) { flake8_bugbear::rules::redundant_tuple_in_exception_handler(checker, handlers); } - if checker.enabled(Rule::OSErrorAlias) { + if checker.is_rule_enabled(Rule::OSErrorAlias) { pyupgrade::rules::os_error_alias_handlers(checker, handlers); } - if checker.enabled(Rule::TimeoutErrorAlias) { + if checker.is_rule_enabled(Rule::TimeoutErrorAlias) { if checker.target_version() >= PythonVersion::PY310 { pyupgrade::rules::timeout_error_alias_handlers(checker, handlers); } } - if checker.enabled(Rule::PytestAssertInExcept) { + if checker.is_rule_enabled(Rule::PytestAssertInExcept) { flake8_pytest_style::rules::assert_in_exception_handler(checker, handlers); } - if checker.enabled(Rule::SuppressibleException) { + if checker.is_rule_enabled(Rule::SuppressibleException) { flake8_simplify::rules::suppressible_exception( checker, stmt, body, handlers, orelse, finalbody, ); } - if checker.enabled(Rule::ReturnInTryExceptFinally) { + if checker.is_rule_enabled(Rule::ReturnInTryExceptFinally) { flake8_simplify::rules::return_in_try_except_finally( checker, body, handlers, finalbody, ); } - if checker.enabled(Rule::TryConsiderElse) { + if checker.is_rule_enabled(Rule::TryConsiderElse) { tryceratops::rules::try_consider_else(checker, body, orelse, handlers); } - if checker.enabled(Rule::VerboseRaise) { + if checker.is_rule_enabled(Rule::VerboseRaise) { tryceratops::rules::verbose_raise(checker, handlers); } - if checker.enabled(Rule::VerboseLogMessage) { + if checker.is_rule_enabled(Rule::VerboseLogMessage) { tryceratops::rules::verbose_log_message(checker, handlers); } - if checker.enabled(Rule::RaiseWithinTry) { + if checker.is_rule_enabled(Rule::RaiseWithinTry) { tryceratops::rules::raise_within_try(checker, body, handlers); } - if checker.enabled(Rule::UselessTryExcept) { + if checker.is_rule_enabled(Rule::UselessTryExcept) { tryceratops::rules::useless_try_except(checker, handlers); } - if checker.enabled(Rule::ErrorInsteadOfException) { + if checker.is_rule_enabled(Rule::ErrorInsteadOfException) { tryceratops::rules::error_instead_of_exception(checker, handlers); } - if checker.enabled(Rule::NeedlessElse) { + if checker.is_rule_enabled(Rule::NeedlessElse) { ruff::rules::needless_else(checker, try_stmt.into()); } } Stmt::Assign(assign @ ast::StmtAssign { targets, value, .. }) => { - if checker.enabled(Rule::SelfOrClsAssignment) { + if checker.is_rule_enabled(Rule::SelfOrClsAssignment) { for target in targets { pylint::rules::self_or_cls_assignment(checker, target); } } - if checker.enabled(Rule::RedeclaredAssignedName) { + if checker.is_rule_enabled(Rule::RedeclaredAssignedName) { pylint::rules::redeclared_assigned_name(checker, targets); } - if checker.enabled(Rule::LambdaAssignment) { + if checker.is_rule_enabled(Rule::LambdaAssignment) { if let [target] = &targets[..] { pycodestyle::rules::lambda_assignment(checker, target, value, None, stmt); } } - if checker.enabled(Rule::AssignmentToOsEnviron) { + if checker.is_rule_enabled(Rule::AssignmentToOsEnviron) { flake8_bugbear::rules::assignment_to_os_environ(checker, targets); } - if checker.enabled(Rule::HardcodedPasswordString) { + if checker.is_rule_enabled(Rule::HardcodedPasswordString) { flake8_bandit::rules::assign_hardcoded_password_string(checker, value, targets); } - if checker.enabled(Rule::GlobalStatement) { + if checker.is_rule_enabled(Rule::GlobalStatement) { for target in targets { if let Expr::Name(ast::ExprName { id, .. }) = target { pylint::rules::global_statement(checker, id); } } } - if checker.enabled(Rule::UselessMetaclassType) { + if checker.is_rule_enabled(Rule::UselessMetaclassType) { pyupgrade::rules::useless_metaclass_type(checker, stmt, value, targets); } - if checker.enabled(Rule::ConvertTypedDictFunctionalToClass) { + if checker.is_rule_enabled(Rule::ConvertTypedDictFunctionalToClass) { pyupgrade::rules::convert_typed_dict_functional_to_class( checker, stmt, targets, value, ); } - if checker.enabled(Rule::ConvertNamedTupleFunctionalToClass) { + if checker.is_rule_enabled(Rule::ConvertNamedTupleFunctionalToClass) { pyupgrade::rules::convert_named_tuple_functional_to_class( checker, stmt, targets, value, ); } - if checker.enabled(Rule::PandasDfVariableName) { + if checker.is_rule_enabled(Rule::PandasDfVariableName) { pandas_vet::rules::assignment_to_df(checker, targets); } - if checker - .settings - .rules - .enabled(Rule::AirflowVariableNameTaskIdMismatch) - { + if checker.is_rule_enabled(Rule::AirflowVariableNameTaskIdMismatch) { airflow::rules::variable_name_task_id(checker, targets, value); } - if checker.settings.rules.enabled(Rule::SelfAssigningVariable) { + if checker.is_rule_enabled(Rule::SelfAssigningVariable) { pylint::rules::self_assignment(checker, assign); } - if checker.settings.rules.enabled(Rule::TypeParamNameMismatch) { + if checker.is_rule_enabled(Rule::TypeParamNameMismatch) { pylint::rules::type_param_name_mismatch(checker, value, targets); } - if checker - .settings - .rules - .enabled(Rule::TypeNameIncorrectVariance) - { + if checker.is_rule_enabled(Rule::TypeNameIncorrectVariance) { pylint::rules::type_name_incorrect_variance(checker, value); } - if checker.settings.rules.enabled(Rule::TypeBivariance) { + if checker.is_rule_enabled(Rule::TypeBivariance) { pylint::rules::type_bivariance(checker, value); } - if checker.enabled(Rule::NonAugmentedAssignment) { + if checker.is_rule_enabled(Rule::NonAugmentedAssignment) { pylint::rules::non_augmented_assignment(checker, assign); } - if checker.settings.rules.enabled(Rule::UnsortedDunderAll) { + if checker.is_rule_enabled(Rule::UnsortedDunderAll) { ruff::rules::sort_dunder_all_assign(checker, assign); } if checker.source_type.is_stub() { - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::UnprefixedTypeParam, Rule::AssignmentDefaultInStub, Rule::UnannotatedAssignmentInStub, @@ -1502,21 +1496,21 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { .current_scopes() .any(|scope| scope.kind.is_function()) { - if checker.enabled(Rule::UnprefixedTypeParam) { + if checker.is_rule_enabled(Rule::UnprefixedTypeParam) { flake8_pyi::rules::prefix_type_params(checker, value, targets); } - if checker.enabled(Rule::AssignmentDefaultInStub) { + if checker.is_rule_enabled(Rule::AssignmentDefaultInStub) { flake8_pyi::rules::assignment_default_in_stub(checker, targets, value); } - if checker.enabled(Rule::UnannotatedAssignmentInStub) { + if checker.is_rule_enabled(Rule::UnannotatedAssignmentInStub) { flake8_pyi::rules::unannotated_assignment_in_stub( checker, targets, value, ); } - if checker.enabled(Rule::ComplexAssignmentInStub) { + if checker.is_rule_enabled(Rule::ComplexAssignmentInStub) { flake8_pyi::rules::complex_assignment_in_stub(checker, assign); } - if checker.enabled(Rule::TypeAliasWithoutAnnotation) { + if checker.is_rule_enabled(Rule::TypeAliasWithoutAnnotation) { flake8_pyi::rules::type_alias_without_annotation( checker, value, targets, ); @@ -1524,10 +1518,10 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } - if checker.enabled(Rule::ListReverseCopy) { + if checker.is_rule_enabled(Rule::ListReverseCopy) { refurb::rules::list_assign_reversed(checker, assign); } - if checker.enabled(Rule::NonPEP695TypeAlias) { + if checker.is_rule_enabled(Rule::NonPEP695TypeAlias) { pyupgrade::rules::non_pep695_type_alias_type(checker, assign); } } @@ -1540,7 +1534,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { }, ) => { if let Some(value) = value { - if checker.enabled(Rule::LambdaAssignment) { + if checker.is_rule_enabled(Rule::LambdaAssignment) { pycodestyle::rules::lambda_assignment( checker, target, @@ -1550,13 +1544,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } } - if checker.enabled(Rule::SelfOrClsAssignment) { + if checker.is_rule_enabled(Rule::SelfOrClsAssignment) { pylint::rules::self_or_cls_assignment(checker, target); } - if checker.enabled(Rule::SelfAssigningVariable) { + if checker.is_rule_enabled(Rule::SelfAssigningVariable) { pylint::rules::self_annotated_assignment(checker, assign_stmt); } - if checker.enabled(Rule::UnintentionalTypeAnnotation) { + if checker.is_rule_enabled(Rule::UnintentionalTypeAnnotation) { flake8_bugbear::rules::unintentional_type_annotation( checker, target, @@ -1564,10 +1558,10 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { stmt, ); } - if checker.enabled(Rule::NonPEP695TypeAlias) { + if checker.is_rule_enabled(Rule::NonPEP695TypeAlias) { pyupgrade::rules::non_pep695_type_alias(checker, assign_stmt); } - if checker.enabled(Rule::HardcodedPasswordString) { + if checker.is_rule_enabled(Rule::HardcodedPasswordString) { if let Some(value) = value.as_deref() { flake8_bandit::rules::assign_hardcoded_password_string( checker, @@ -1576,12 +1570,12 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { ); } } - if checker.settings.rules.enabled(Rule::UnsortedDunderAll) { + if checker.is_rule_enabled(Rule::UnsortedDunderAll) { ruff::rules::sort_dunder_all_ann_assign(checker, assign_stmt); } if checker.source_type.is_stub() { if let Some(value) = value { - if checker.enabled(Rule::AssignmentDefaultInStub) { + if checker.is_rule_enabled(Rule::AssignmentDefaultInStub) { // Ignore assignments in function bodies; those are covered by other rules. if !checker .semantic @@ -1594,7 +1588,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } } else { - if checker.enabled(Rule::UnassignedSpecialVariableInStub) { + if checker.is_rule_enabled(Rule::UnassignedSpecialVariableInStub) { flake8_pyi::rules::unassigned_special_variable_in_stub( checker, target, stmt, ); @@ -1602,26 +1596,26 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { } } if checker.semantic.match_typing_expr(annotation, "TypeAlias") { - if checker.enabled(Rule::SnakeCaseTypeAlias) { + if checker.is_rule_enabled(Rule::SnakeCaseTypeAlias) { flake8_pyi::rules::snake_case_type_alias(checker, target); } - if checker.enabled(Rule::TSuffixedTypeAlias) { + if checker.is_rule_enabled(Rule::TSuffixedTypeAlias) { flake8_pyi::rules::t_suffixed_type_alias(checker, target); } } else if checker .semantic .match_typing_expr(helpers::map_subscript(annotation), "Final") { - if checker.enabled(Rule::RedundantFinalLiteral) { + if checker.is_rule_enabled(Rule::RedundantFinalLiteral) { flake8_pyi::rules::redundant_final_literal(checker, assign_stmt); } } } Stmt::TypeAlias(ast::StmtTypeAlias { name, .. }) => { - if checker.enabled(Rule::SnakeCaseTypeAlias) { + if checker.is_rule_enabled(Rule::SnakeCaseTypeAlias) { flake8_pyi::rules::snake_case_type_alias(checker, name); } - if checker.enabled(Rule::TSuffixedTypeAlias) { + if checker.is_rule_enabled(Rule::TSuffixedTypeAlias) { flake8_pyi::rules::t_suffixed_type_alias(checker, name); } } @@ -1632,14 +1626,14 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::GlobalStatement) { + if checker.is_rule_enabled(Rule::GlobalStatement) { for target in targets { if let Expr::Name(ast::ExprName { id, .. }) = target { pylint::rules::global_statement(checker, id); } } } - if checker.enabled(Rule::DeleteFullSlice) { + if checker.is_rule_enabled(Rule::DeleteFullSlice) { refurb::rules::delete_full_slice(checker, delete); } } @@ -1650,25 +1644,25 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { node_index: _, }, ) => { - if checker.enabled(Rule::UselessComparison) { + if checker.is_rule_enabled(Rule::UselessComparison) { flake8_bugbear::rules::useless_comparison(checker, value); } - if checker.enabled(Rule::UselessExpression) { + if checker.is_rule_enabled(Rule::UselessExpression) { flake8_bugbear::rules::useless_expression(checker, value); } - if checker.enabled(Rule::InvalidMockAccess) { + if checker.is_rule_enabled(Rule::InvalidMockAccess) { pygrep_hooks::rules::uncalled_mock_method(checker, value); } - if checker.enabled(Rule::NamedExprWithoutContext) { + if checker.is_rule_enabled(Rule::NamedExprWithoutContext) { pylint::rules::named_expr_without_context(checker, value); } - if checker.enabled(Rule::AsyncioDanglingTask) { + if checker.is_rule_enabled(Rule::AsyncioDanglingTask) { ruff::rules::asyncio_dangling_task(checker, value, checker.semantic()); } - if checker.enabled(Rule::RepeatedAppend) { + if checker.is_rule_enabled(Rule::RepeatedAppend) { refurb::rules::repeated_append(checker, stmt); } - if checker.enabled(Rule::UselessExceptionStatement) { + if checker.is_rule_enabled(Rule::UselessExceptionStatement) { pylint::rules::useless_exception_statement(checker, expr); } } @@ -1678,7 +1672,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) { range: _, node_index: _, }) => { - if checker.enabled(Rule::NanComparison) { + if checker.is_rule_enabled(Rule::NanComparison) { pylint::rules::nan_comparison_match(checker, cases); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/string_like.rs b/crates/ruff_linter/src/checkers/ast/analyze/string_like.rs index acd25d9fc7..25c37bcd01 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/string_like.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/string_like.rs @@ -6,37 +6,39 @@ 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_enabled(&[ + if checker.any_rule_enabled(&[ Rule::AmbiguousUnicodeCharacterString, Rule::AmbiguousUnicodeCharacterDocstring, ]) { ruff::rules::ambiguous_unicode_character_string(checker, string_like); } - if checker.enabled(Rule::HardcodedBindAllInterfaces) { + if checker.is_rule_enabled(Rule::HardcodedBindAllInterfaces) { flake8_bandit::rules::hardcoded_bind_all_interfaces(checker, string_like); } - if checker.enabled(Rule::HardcodedTempFile) { + if checker.is_rule_enabled(Rule::HardcodedTempFile) { flake8_bandit::rules::hardcoded_tmp_directory(checker, string_like); } if checker.source_type.is_stub() { - if checker.enabled(Rule::StringOrBytesTooLong) { + if checker.is_rule_enabled(Rule::StringOrBytesTooLong) { flake8_pyi::rules::string_or_bytes_too_long(checker, string_like); } } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::BadQuotesInlineString, Rule::BadQuotesMultilineString, Rule::BadQuotesDocstring, ]) { flake8_quotes::rules::check_string_quotes(checker, string_like); } - if checker.enabled(Rule::UnnecessaryEscapedQuote) { + if checker.is_rule_enabled(Rule::UnnecessaryEscapedQuote) { flake8_quotes::rules::unnecessary_escaped_quote(checker, string_like); } - if checker.enabled(Rule::AvoidableEscapedQuote) && checker.settings.flake8_quotes.avoid_escape { + if checker.is_rule_enabled(Rule::AvoidableEscapedQuote) + && checker.settings.flake8_quotes.avoid_escape + { flake8_quotes::rules::avoidable_escaped_quote(checker, string_like); } - if checker.enabled(Rule::InvalidEscapeSequence) { + if checker.is_rule_enabled(Rule::InvalidEscapeSequence) { pycodestyle::rules::invalid_escape_sequence(checker, string_like); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/suite.rs b/crates/ruff_linter/src/checkers/ast/analyze/suite.rs index f5b56f1081..503a864259 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/suite.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/suite.rs @@ -7,10 +7,10 @@ use crate::rules::refurb; /// Run lint rules over a suite of [`Stmt`] syntax nodes. pub(crate) fn suite(suite: &[Stmt], checker: &Checker) { - if checker.enabled(Rule::UnnecessaryPlaceholder) { + if checker.is_rule_enabled(Rule::UnnecessaryPlaceholder) { flake8_pie::rules::unnecessary_placeholder(checker, suite); } - if checker.enabled(Rule::RepeatedGlobal) { + if checker.is_rule_enabled(Rule::RepeatedGlobal) { refurb::rules::repeated_global(checker, suite); } } diff --git a/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs b/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs index 3060e07f63..021cfd7d1f 100644 --- a/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs +++ b/crates/ruff_linter/src/checkers/ast/analyze/unresolved_references.rs @@ -7,13 +7,13 @@ use crate::rules::pyflakes; /// Run lint rules over all [`UnresolvedReference`] entities in the [`SemanticModel`]. pub(crate) fn unresolved_references(checker: &Checker) { - if !checker.any_enabled(&[Rule::UndefinedLocalWithImportStarUsage, Rule::UndefinedName]) { + if !checker.any_rule_enabled(&[Rule::UndefinedLocalWithImportStarUsage, Rule::UndefinedName]) { return; } for reference in checker.semantic.unresolved_references() { if reference.is_wildcard_import() { - if checker.enabled(Rule::UndefinedLocalWithImportStarUsage) { + if checker.is_rule_enabled(Rule::UndefinedLocalWithImportStarUsage) { checker.report_diagnostic( pyflakes::rules::UndefinedLocalWithImportStarUsage { name: reference.name(checker.source()).to_string(), @@ -22,7 +22,7 @@ pub(crate) fn unresolved_references(checker: &Checker) { ); } } else { - if checker.enabled(Rule::UndefinedName) { + if checker.is_rule_enabled(Rule::UndefinedName) { if checker.semantic.in_no_type_check() { continue; } diff --git a/crates/ruff_linter/src/checkers/ast/mod.rs b/crates/ruff_linter/src/checkers/ast/mod.rs index 9dc7c6fa7b..e1e86c40e3 100644 --- a/crates/ruff_linter/src/checkers/ast/mod.rs +++ b/crates/ruff_linter/src/checkers/ast/mod.rs @@ -57,7 +57,7 @@ use ruff_python_semantic::{ }; use ruff_python_stdlib::builtins::{MAGIC_GLOBALS, python_builtins}; use ruff_python_trivia::CommentRanges; -use ruff_source_file::{OneIndexed, SourceFile, SourceRow}; +use ruff_source_file::{OneIndexed, SourceFile, SourceFileBuilder, SourceRow}; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::checkers::ast::annotation::AnnotationContext; @@ -72,6 +72,7 @@ use crate::rules::pyflakes::rules::{ }; use crate::rules::pylint::rules::{AwaitOutsideAsync, LoadBeforeGlobalDeclaration}; 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, OldDiagnostic, Violation}; use crate::{Locator, docstrings, noqa}; @@ -480,14 +481,14 @@ impl<'a> Checker<'a> { /// Returns whether the given rule should be checked. #[inline] - pub(crate) const fn enabled(&self, rule: Rule) -> bool { - self.settings.rules.enabled(rule) + 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_enabled(&self, rules: &[Rule]) -> bool { - self.settings.rules.any_enabled(rules) + 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. @@ -622,16 +623,12 @@ impl SemanticSyntaxContext for Checker<'_> { fn report_semantic_error(&self, error: SemanticSyntaxError) { match error.kind { SemanticSyntaxErrorKind::LateFutureImport => { - if self.settings.rules.enabled(Rule::LateFutureImport) { + if self.is_rule_enabled(Rule::LateFutureImport) { self.report_diagnostic(LateFutureImport, error.range); } } SemanticSyntaxErrorKind::LoadBeforeGlobalDeclaration { name, start } => { - if self - .settings - .rules - .enabled(Rule::LoadBeforeGlobalDeclaration) - { + if self.is_rule_enabled(Rule::LoadBeforeGlobalDeclaration) { self.report_diagnostic( LoadBeforeGlobalDeclaration { name, @@ -642,17 +639,17 @@ impl SemanticSyntaxContext for Checker<'_> { } } SemanticSyntaxErrorKind::YieldOutsideFunction(kind) => { - if self.settings.rules.enabled(Rule::YieldOutsideFunction) { + if self.is_rule_enabled(Rule::YieldOutsideFunction) { self.report_diagnostic(YieldOutsideFunction::new(kind), error.range); } } SemanticSyntaxErrorKind::ReturnOutsideFunction => { - if self.settings.rules.enabled(Rule::ReturnOutsideFunction) { + if self.is_rule_enabled(Rule::ReturnOutsideFunction) { self.report_diagnostic(ReturnOutsideFunction, error.range); } } SemanticSyntaxErrorKind::AwaitOutsideAsyncFunction(_) => { - if self.settings.rules.enabled(Rule::AwaitOutsideAsync) { + if self.is_rule_enabled(Rule::AwaitOutsideAsync) { self.report_diagnostic(AwaitOutsideAsync, error.range); } } @@ -2364,7 +2361,7 @@ impl<'a> Checker<'a> { fn visit_cast_type_argument(&mut self, arg: &'a Expr) { self.visit_type_definition(arg); - if !self.source_type.is_stub() && self.enabled(Rule::RuntimeCastValue) { + if !self.source_type.is_stub() && self.is_rule_enabled(Rule::RuntimeCastValue) { flake8_type_checking::rules::runtime_cast_value(self, arg); } } @@ -2766,12 +2763,12 @@ impl<'a> Checker<'a> { if self.semantic.in_annotation() && self.semantic.in_typing_only_annotation() { - if self.enabled(Rule::QuotedAnnotation) { + if self.is_rule_enabled(Rule::QuotedAnnotation) { pyupgrade::rules::quoted_annotation(self, annotation, range); } } if self.source_type.is_stub() { - if self.enabled(Rule::QuotedAnnotationInStub) { + if self.is_rule_enabled(Rule::QuotedAnnotationInStub) { flake8_pyi::rules::quoted_annotation_in_stub( self, annotation, range, ); @@ -2793,7 +2790,9 @@ impl<'a> Checker<'a> { self.visit_expr(parsed_expr); if self.semantic.in_type_alias_value() { // stub files are covered by PYI020 - if !self.source_type.is_stub() && self.enabled(Rule::QuotedTypeAlias) { + if !self.source_type.is_stub() + && self.is_rule_enabled(Rule::QuotedTypeAlias) + { flake8_type_checking::rules::quoted_type_alias( self, parsed_expr, @@ -2806,7 +2805,7 @@ impl<'a> Checker<'a> { Err(parse_error) => { self.semantic.restore(snapshot); - if self.enabled(Rule::ForwardAnnotationSyntaxError) { + if self.is_rule_enabled(Rule::ForwardAnnotationSyntaxError) { self.report_type_diagnostic( pyflakes::rules::ForwardAnnotationSyntaxError { parse_error: parse_error.error.to_string(), @@ -2953,7 +2952,7 @@ impl<'a> Checker<'a> { self.semantic.flags -= SemanticModelFlags::DUNDER_ALL_DEFINITION; } else { if self.semantic.global_scope().uses_star_imports() { - if self.enabled(Rule::UndefinedLocalWithImportStarUsage) { + if self.is_rule_enabled(Rule::UndefinedLocalWithImportStarUsage) { self.report_diagnostic( pyflakes::rules::UndefinedLocalWithImportStarUsage { name: name.to_string(), @@ -2963,7 +2962,7 @@ impl<'a> Checker<'a> { .set_parent(definition.start()); } } else { - if self.enabled(Rule::UndefinedExport) { + if self.is_rule_enabled(Rule::UndefinedExport) { if is_undefined_export_in_dunder_init_enabled(self.settings) || !self.path.ends_with("__init__.py") { @@ -3114,17 +3113,29 @@ pub(crate) fn check_ast( /// a [`Violation`] to the contained [`OldDiagnostic`] collection on `Drop`. pub(crate) struct LintContext<'a> { diagnostics: RefCell>, - source_file: &'a SourceFile, + source_file: SourceFile, + rules: RuleTable, + #[expect(unused, reason = "TODO(brent) use this instead of Checker::settings")] settings: &'a LinterSettings, } impl<'a> LintContext<'a> { /// Create a new collector with the given `source_file` and an empty collection of /// `OldDiagnostic`s. - pub(crate) fn new(source_file: &'a SourceFile, settings: &'a LinterSettings) -> Self { + pub(crate) fn new(path: &Path, contents: &str, settings: &'a LinterSettings) -> Self { + let source_file = + SourceFileBuilder::new(path.to_string_lossy().as_ref(), contents).finish(); + + // Ignore diagnostics based on per-file-ignores. + let mut rules = settings.rules.clone(); + for ignore in crate::fs::ignores_from_path(path, &settings.per_file_ignores) { + rules.disable(ignore); + } + Self { diagnostics: RefCell::default(), source_file, + rules, settings, } } @@ -3140,7 +3151,7 @@ impl<'a> LintContext<'a> { ) -> DiagnosticGuard<'chk, 'a> { DiagnosticGuard { context: self, - diagnostic: Some(OldDiagnostic::new(kind, range, self.source_file)), + diagnostic: Some(OldDiagnostic::new(kind, range, &self.source_file)), } } @@ -3154,28 +3165,42 @@ impl<'a> LintContext<'a> { kind: T, range: TextRange, ) -> Option> { - if self.settings.rules.enabled(T::rule()) { + if self.is_rule_enabled(T::rule()) { Some(DiagnosticGuard { context: self, - diagnostic: Some(OldDiagnostic::new(kind, range, self.source_file)), + diagnostic: Some(OldDiagnostic::new(kind, range, &self.source_file)), }) } else { None } } - pub(crate) fn into_diagnostics(self) -> Vec { - self.diagnostics.into_inner() + #[inline] + pub(crate) const fn is_rule_enabled(&self, rule: Rule) -> bool { + self.rules.enabled(rule) } - pub(crate) fn is_empty(&self) -> bool { - self.diagnostics.borrow().is_empty() + #[inline] + pub(crate) const fn any_rule_enabled(&self, rules: &[Rule]) -> bool { + self.rules.any_enabled(rules) } + #[inline] + pub(crate) fn iter_enabled_rules(&self) -> impl Iterator + '_ { + self.rules.iter_enabled() + } + + #[inline] + pub(crate) fn into_parts(self) -> (Vec, SourceFile) { + (self.diagnostics.into_inner(), self.source_file) + } + + #[inline] pub(crate) fn as_mut_vec(&mut self) -> &mut Vec { self.diagnostics.get_mut() } + #[inline] pub(crate) fn iter(&mut self) -> impl Iterator { self.diagnostics.get_mut().iter() } diff --git a/crates/ruff_linter/src/checkers/filesystem.rs b/crates/ruff_linter/src/checkers/filesystem.rs index 69c95a1dec..f7fbff280f 100644 --- a/crates/ruff_linter/src/checkers/filesystem.rs +++ b/crates/ruff_linter/src/checkers/filesystem.rs @@ -23,7 +23,7 @@ pub(crate) fn check_file_path( context: &LintContext, ) { // flake8-no-pep420 - if settings.rules.enabled(Rule::ImplicitNamespacePackage) { + if context.is_rule_enabled(Rule::ImplicitNamespacePackage) { let allow_nested_roots = is_allow_nested_roots_enabled(settings); implicit_namespace_package( path, @@ -38,12 +38,12 @@ pub(crate) fn check_file_path( } // pep8-naming - if settings.rules.enabled(Rule::InvalidModuleName) { + if context.is_rule_enabled(Rule::InvalidModuleName) { invalid_module_name(path, package, &settings.pep8_naming.ignore_names, context); } // flake8-builtins - if settings.rules.enabled(Rule::StdlibModuleShadowing) { + if context.is_rule_enabled(Rule::StdlibModuleShadowing) { stdlib_module_shadowing(path, settings, target_version, context); } } diff --git a/crates/ruff_linter/src/checkers/imports.rs b/crates/ruff_linter/src/checkers/imports.rs index d01249bcd4..dd24614dd6 100644 --- a/crates/ruff_linter/src/checkers/imports.rs +++ b/crates/ruff_linter/src/checkers/imports.rs @@ -42,7 +42,7 @@ pub(crate) fn check_imports( let blocks: Vec<&Block> = tracker.iter().collect(); // Enforce import rules. - if settings.rules.enabled(Rule::UnsortedImports) { + if context.is_rule_enabled(Rule::UnsortedImports) { for block in &blocks { if !block.imports.is_empty() { isort::rules::organize_imports( @@ -60,7 +60,7 @@ pub(crate) fn check_imports( } } } - if settings.rules.enabled(Rule::MissingRequiredImport) { + if context.is_rule_enabled(Rule::MissingRequiredImport) { isort::rules::add_required_imports( parsed, locator, diff --git a/crates/ruff_linter/src/checkers/logical_lines.rs b/crates/ruff_linter/src/checkers/logical_lines.rs index e99981f0cd..5c60a3171a 100644 --- a/crates/ruff_linter/src/checkers/logical_lines.rs +++ b/crates/ruff_linter/src/checkers/logical_lines.rs @@ -47,49 +47,48 @@ pub(crate) fn check_logical_lines( let mut prev_indent_level = None; let indent_char = stylist.indentation().as_char(); - let enforce_space_around_operator = settings.rules.any_enabled(&[ + let enforce_space_around_operator = context.any_rule_enabled(&[ Rule::MultipleSpacesBeforeOperator, Rule::MultipleSpacesAfterOperator, Rule::TabBeforeOperator, Rule::TabAfterOperator, ]); - let enforce_whitespace_around_named_parameter_equals = settings.rules.any_enabled(&[ + let enforce_whitespace_around_named_parameter_equals = context.any_rule_enabled(&[ Rule::UnexpectedSpacesAroundKeywordParameterEquals, Rule::MissingWhitespaceAroundParameterEquals, ]); - let enforce_missing_whitespace_around_operator = settings.rules.any_enabled(&[ + let enforce_missing_whitespace_around_operator = context.any_rule_enabled(&[ Rule::MissingWhitespaceAroundOperator, Rule::MissingWhitespaceAroundArithmeticOperator, Rule::MissingWhitespaceAroundBitwiseOrShiftOperator, Rule::MissingWhitespaceAroundModuloOperator, ]); - let enforce_missing_whitespace = settings.rules.enabled(Rule::MissingWhitespace); - let enforce_space_after_comma = settings - .rules - .any_enabled(&[Rule::MultipleSpacesAfterComma, Rule::TabAfterComma]); - let enforce_extraneous_whitespace = settings.rules.any_enabled(&[ + 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 = settings.rules.any_enabled(&[ + let enforce_whitespace_around_keywords = context.any_rule_enabled(&[ Rule::MultipleSpacesAfterKeyword, Rule::MultipleSpacesBeforeKeyword, Rule::TabAfterKeyword, Rule::TabBeforeKeyword, ]); let enforce_missing_whitespace_after_keyword = - settings.rules.enabled(Rule::MissingWhitespaceAfterKeyword); - let enforce_whitespace_before_comment = settings.rules.any_enabled(&[ + 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 = - settings.rules.enabled(Rule::WhitespaceBeforeParameters); - let enforce_redundant_backslash = settings.rules.enabled(Rule::RedundantBackslash); - let enforce_indentation = settings.rules.any_enabled(&[ + 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, diff --git a/crates/ruff_linter/src/checkers/noqa.rs b/crates/ruff_linter/src/checkers/noqa.rs index 0b88cc7158..ac553b21e5 100644 --- a/crates/ruff_linter/src/checkers/noqa.rs +++ b/crates/ruff_linter/src/checkers/noqa.rs @@ -12,7 +12,7 @@ use crate::fix::edits::delete_comment; use crate::noqa::{ Code, Directive, FileExemption, FileNoqaDirectives, NoqaDirectives, NoqaMapping, }; -use crate::registry::{Rule, RuleSet}; +use crate::registry::Rule; use crate::rule_redirects::get_redirect_target; use crate::rules::pygrep_hooks; use crate::rules::ruff; @@ -22,7 +22,6 @@ use crate::{Edit, Fix, Locator}; use super::ast::LintContext; -#[expect(clippy::too_many_arguments)] pub(crate) fn check_noqa( context: &mut LintContext, path: &Path, @@ -30,7 +29,6 @@ pub(crate) fn check_noqa( comment_ranges: &CommentRanges, noqa_line_for: &NoqaMapping, analyze_directives: bool, - per_file_ignores: &RuleSet, settings: &LinterSettings, ) -> Vec { // Identify any codes that are globally exempted (within the current file). @@ -107,10 +105,9 @@ pub(crate) fn check_noqa( // Enforce that the noqa directive was actually used (RUF100), unless RUF100 was itself // suppressed. - if settings.rules.enabled(Rule::UnusedNOQA) + if context.is_rule_enabled(Rule::UnusedNOQA) && analyze_directives && !exemption.includes(Rule::UnusedNOQA) - && !per_file_ignores.contains(Rule::UnusedNOQA) { let directives = noqa_directives .lines() @@ -162,7 +159,7 @@ pub(crate) fn check_noqa( if is_code_used { valid_codes.push(original_code); } else if let Ok(rule) = Rule::from_code(code) { - if settings.rules.enabled(rule) { + if context.is_rule_enabled(rule) { unmatched_codes.push(original_code); } else { disabled_codes.push(original_code); @@ -232,18 +229,12 @@ pub(crate) fn check_noqa( } } - if settings.rules.enabled(Rule::RedirectedNOQA) - && !per_file_ignores.contains(Rule::RedirectedNOQA) - && !exemption.includes(Rule::RedirectedNOQA) - { + 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 settings.rules.enabled(Rule::BlanketNOQA) - && !per_file_ignores.contains(Rule::BlanketNOQA) - && !exemption.enumerates(Rule::BlanketNOQA) - { + if context.is_rule_enabled(Rule::BlanketNOQA) && !exemption.enumerates(Rule::BlanketNOQA) { pygrep_hooks::rules::blanket_noqa( context, &noqa_directives, @@ -252,8 +243,7 @@ pub(crate) fn check_noqa( ); } - if settings.rules.enabled(Rule::InvalidRuleCode) - && !per_file_ignores.contains(Rule::InvalidRuleCode) + if context.is_rule_enabled(Rule::InvalidRuleCode) && !exemption.enumerates(Rule::InvalidRuleCode) { ruff::rules::invalid_noqa_code(context, &noqa_directives, locator, &settings.external); diff --git a/crates/ruff_linter/src/checkers/physical_lines.rs b/crates/ruff_linter/src/checkers/physical_lines.rs index 3d3fbfd4da..5cc8f7a908 100644 --- a/crates/ruff_linter/src/checkers/physical_lines.rs +++ b/crates/ruff_linter/src/checkers/physical_lines.rs @@ -26,15 +26,16 @@ pub(crate) fn check_physical_lines( settings: &LinterSettings, context: &LintContext, ) { - let enforce_doc_line_too_long = settings.rules.enabled(Rule::DocLineTooLong); - let enforce_line_too_long = settings.rules.enabled(Rule::LineTooLong); - let enforce_no_newline_at_end_of_file = settings.rules.enabled(Rule::MissingNewlineAtEndOfFile); - let enforce_mixed_spaces_and_tabs = settings.rules.enabled(Rule::MixedSpacesAndTabs); - let enforce_bidirectional_unicode = settings.rules.enabled(Rule::BidirectionalUnicode); - let enforce_trailing_whitespace = settings.rules.enabled(Rule::TrailingWhitespace); + 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 = - settings.rules.enabled(Rule::BlankLineWithWhitespace); - let enforce_copyright_notice = settings.rules.enabled(Rule::MissingCopyrightNotice); + 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(); @@ -62,10 +63,10 @@ pub(crate) fn check_physical_lines( } if enforce_trailing_whitespace || enforce_blank_line_contains_whitespace { - trailing_whitespace(&line, locator, indexer, settings, context); + trailing_whitespace(&line, locator, indexer, context); } - if settings.rules.enabled(Rule::IndentedFormFeed) { + if context.is_rule_enabled(Rule::IndentedFormFeed) { indented_form_feed(&line, context); } } @@ -81,10 +82,11 @@ pub(crate) fn check_physical_lines( #[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 ruff_source_file::SourceFileBuilder; use crate::Locator; use crate::checkers::ast::LintContext; @@ -104,7 +106,6 @@ mod tests { let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); let check_with_max_line_length = |line_length: LineLength| { - let source_file = SourceFileBuilder::new("", line).finish(); let settings = LinterSettings { pycodestyle: pycodestyle::settings::Settings { max_line_length: line_length, @@ -112,9 +113,9 @@ mod tests { }, ..LinterSettings::for_rule(Rule::LineTooLong) }; - let diagnostics = LintContext::new(&source_file, &settings); + let diagnostics = LintContext::new(Path::new(""), line, &settings); check_physical_lines(&locator, &stylist, &indexer, &[], &settings, &diagnostics); - diagnostics.into_diagnostics() + diagnostics.into_parts().0 }; let line_length = LineLength::try_from(8).unwrap(); assert_eq!(check_with_max_line_length(line_length), vec![]); diff --git a/crates/ruff_linter/src/checkers/tokens.rs b/crates/ruff_linter/src/checkers/tokens.rs index 0b16cf78a3..388bbfea8d 100644 --- a/crates/ruff_linter/src/checkers/tokens.rs +++ b/crates/ruff_linter/src/checkers/tokens.rs @@ -34,7 +34,7 @@ pub(crate) fn check_tokens( ) { let comment_ranges = indexer.comment_ranges(); - if settings.rules.any_enabled(&[ + if context.any_rule_enabled(&[ Rule::BlankLineBetweenMethods, Rule::BlankLinesTopLevel, Rule::TooManyBlankLines, @@ -53,36 +53,33 @@ pub(crate) fn check_tokens( .check_lines(tokens); } - if settings.rules.enabled(Rule::BlanketTypeIgnore) { + if context.is_rule_enabled(Rule::BlanketTypeIgnore) { pygrep_hooks::rules::blanket_type_ignore(context, comment_ranges, locator); } - if settings.rules.enabled(Rule::EmptyComment) { + if context.is_rule_enabled(Rule::EmptyComment) { pylint::rules::empty_comments(context, comment_ranges, locator); } - if settings - .rules - .enabled(Rule::AmbiguousUnicodeCharacterComment) - { + if context.is_rule_enabled(Rule::AmbiguousUnicodeCharacterComment) { for range in comment_ranges { ruff::rules::ambiguous_unicode_character_comment(context, locator, range, settings); } } - if settings.rules.enabled(Rule::CommentedOutCode) { + if context.is_rule_enabled(Rule::CommentedOutCode) { eradicate::rules::commented_out_code(context, locator, comment_ranges, settings); } - if settings.rules.enabled(Rule::UTF8EncodingDeclaration) { + if context.is_rule_enabled(Rule::UTF8EncodingDeclaration) { pyupgrade::rules::unnecessary_coding_comment(context, locator, comment_ranges); } - if settings.rules.enabled(Rule::TabIndentation) { + if context.is_rule_enabled(Rule::TabIndentation) { pycodestyle::rules::tab_indentation(context, locator, indexer); } - if settings.rules.any_enabled(&[ + if context.any_rule_enabled(&[ Rule::InvalidCharacterBackspace, Rule::InvalidCharacterSub, Rule::InvalidCharacterEsc, @@ -94,7 +91,7 @@ pub(crate) fn check_tokens( } } - if settings.rules.any_enabled(&[ + if context.any_rule_enabled(&[ Rule::MultipleStatementsOnOneLineColon, Rule::MultipleStatementsOnOneLineSemicolon, Rule::UselessSemicolon, @@ -109,14 +106,14 @@ pub(crate) fn check_tokens( ); } - if settings.rules.any_enabled(&[ + if context.any_rule_enabled(&[ Rule::SingleLineImplicitStringConcatenation, Rule::MultiLineImplicitStringConcatenation, ]) { flake8_implicit_str_concat::rules::implicit(context, tokens, locator, indexer, settings); } - if settings.rules.any_enabled(&[ + if context.any_rule_enabled(&[ Rule::MissingTrailingComma, Rule::TrailingCommaOnBareTuple, Rule::ProhibitedTrailingComma, @@ -124,25 +121,25 @@ pub(crate) fn check_tokens( flake8_commas::rules::trailing_commas(context, tokens, locator, indexer); } - if settings.rules.enabled(Rule::ExtraneousParentheses) { + if context.is_rule_enabled(Rule::ExtraneousParentheses) { pyupgrade::rules::extraneous_parentheses(context, tokens, locator); } - if source_type.is_stub() && settings.rules.enabled(Rule::TypeCommentInStub) { + if source_type.is_stub() && context.is_rule_enabled(Rule::TypeCommentInStub) { flake8_pyi::rules::type_comment_in_stub(context, locator, comment_ranges); } - if settings.rules.any_enabled(&[ + 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, settings); + flake8_executable::rules::from_tokens(context, path, locator, comment_ranges); } - if settings.rules.any_enabled(&[ + if context.any_rule_enabled(&[ Rule::InvalidTodoTag, Rule::MissingTodoAuthor, Rule::MissingTodoLink, @@ -167,7 +164,7 @@ pub(crate) fn check_tokens( flake8_fixme::rules::todos(context, &todo_comments); } - if settings.rules.enabled(Rule::TooManyNewlinesAtEndOfFile) { + if context.is_rule_enabled(Rule::TooManyNewlinesAtEndOfFile) { pycodestyle::rules::too_many_newlines_at_end_of_file(context, tokens, cell_offsets); } } diff --git a/crates/ruff_linter/src/fs.rs b/crates/ruff_linter/src/fs.rs index 983651121a..37fbf36bc6 100644 --- a/crates/ruff_linter/src/fs.rs +++ b/crates/ruff_linter/src/fs.rs @@ -20,6 +20,9 @@ pub fn get_cwd() -> &'static Path { /// Create a set with codes matching the pattern/code pairs. pub(crate) fn ignores_from_path(path: &Path, ignore_list: &CompiledPerFileIgnoreList) -> RuleSet { + if ignore_list.is_empty() { + return RuleSet::empty(); + } ignore_list .iter_matches(path, "Adding per-file ignores") .flatten() diff --git a/crates/ruff_linter/src/linter.rs b/crates/ruff_linter/src/linter.rs index e46eaedc53..cf1852b032 100644 --- a/crates/ruff_linter/src/linter.rs +++ b/crates/ruff_linter/src/linter.rs @@ -13,7 +13,7 @@ use ruff_python_ast::{ModModule, PySourceType, PythonVersion}; use ruff_python_codegen::Stylist; use ruff_python_index::Indexer; use ruff_python_parser::{ParseError, ParseOptions, Parsed, UnsupportedSyntaxError}; -use ruff_source_file::{SourceFile, SourceFileBuilder}; +use ruff_source_file::SourceFile; use ruff_text_size::Ranged; use crate::OldDiagnostic; @@ -30,7 +30,7 @@ use crate::fix::{FixResult, fix_file}; use crate::noqa::add_noqa; use crate::package::PackageRoot; use crate::preview::is_py314_support_enabled; -use crate::registry::{Rule, RuleSet}; +use crate::registry::Rule; #[cfg(any(feature = "test-rules", test))] use crate::rules::ruff::rules::test_rules::{self, TEST_RULES, TestRule}; use crate::settings::types::UnsafeFixes; @@ -160,11 +160,8 @@ pub fn check_path( parsed: &Parsed, target_version: TargetVersion, ) -> Vec { - let source_file = - SourceFileBuilder::new(path.to_string_lossy().as_ref(), locator.contents()).finish(); - // Aggregate all diagnostics. - let mut diagnostics = LintContext::new(&source_file, settings); + let mut context = LintContext::new(path, locator.contents(), settings); // Aggregate all semantic syntax errors. let mut semantic_syntax_errors = vec![]; @@ -174,16 +171,15 @@ pub fn check_path( // Collect doc lines. This requires a rare mix of tokens (for comments) and AST // (for docstrings), which demands special-casing at this level. - let use_doc_lines = settings.rules.enabled(Rule::DocLineTooLong); + let use_doc_lines = context.is_rule_enabled(Rule::DocLineTooLong); let mut doc_lines = vec![]; if use_doc_lines { doc_lines.extend(doc_lines_from_tokens(tokens)); } // Run the token-based rules. - if settings - .rules - .iter_enabled() + if context + .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_tokens()) { check_tokens( @@ -195,14 +191,13 @@ pub fn check_path( settings, source_type, source_kind.as_ipy_notebook().map(Notebook::cell_offsets), - &mut diagnostics, + &mut context, ); } // Run the filesystem-based rules. - if settings - .rules - .iter_enabled() + if context + .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_filesystem()) { check_file_path( @@ -212,23 +207,17 @@ pub fn check_path( comment_ranges, settings, target_version.linter_version(), - &diagnostics, + &context, ); } // Run the logical line-based rules. - if settings - .rules - .iter_enabled() + if context + .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_logical_lines()) { crate::checkers::logical_lines::check_logical_lines( - tokens, - locator, - indexer, - stylist, - settings, - &diagnostics, + tokens, locator, indexer, stylist, settings, &context, ); } @@ -251,13 +240,12 @@ pub fn check_path( cell_offsets, notebook_index, target_version, - &diagnostics, + &context, )); let use_imports = !directives.isort.skip_file - && settings - .rules - .iter_enabled() + && context + .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_imports()); if use_imports || use_doc_lines { if use_imports { @@ -272,7 +260,7 @@ pub fn check_path( source_type, cell_offsets, target_version.linter_version(), - &diagnostics, + &context, ); } if use_doc_lines { @@ -288,89 +276,77 @@ pub fn check_path( } // Run the lines-based rules. - if settings - .rules - .iter_enabled() + if context + .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_physical_lines()) { - check_physical_lines( - locator, - stylist, - indexer, - &doc_lines, - settings, - &diagnostics, - ); + check_physical_lines(locator, stylist, indexer, &doc_lines, settings, &context); } // Raise violations for internal test rules #[cfg(any(feature = "test-rules", test))] { for test_rule in TEST_RULES { - if !settings.rules.enabled(*test_rule) { + if !context.is_rule_enabled(*test_rule) { continue; } match test_rule { Rule::StableTestRule => { - test_rules::StableTestRule::diagnostic(locator, comment_ranges, &diagnostics); + test_rules::StableTestRule::diagnostic(locator, comment_ranges, &context); + } + Rule::StableTestRuleSafeFix => { + test_rules::StableTestRuleSafeFix::diagnostic( + locator, + comment_ranges, + &context, + ); } - Rule::StableTestRuleSafeFix => test_rules::StableTestRuleSafeFix::diagnostic( - locator, - comment_ranges, - &diagnostics, - ), Rule::StableTestRuleUnsafeFix => test_rules::StableTestRuleUnsafeFix::diagnostic( locator, comment_ranges, - &diagnostics, + &context, ), Rule::StableTestRuleDisplayOnlyFix => { test_rules::StableTestRuleDisplayOnlyFix::diagnostic( locator, comment_ranges, - &diagnostics, + &context, ); } Rule::PreviewTestRule => { - test_rules::PreviewTestRule::diagnostic(locator, comment_ranges, &diagnostics); + test_rules::PreviewTestRule::diagnostic(locator, comment_ranges, &context); } Rule::DeprecatedTestRule => { - test_rules::DeprecatedTestRule::diagnostic( - locator, - comment_ranges, - &diagnostics, - ); + test_rules::DeprecatedTestRule::diagnostic(locator, comment_ranges, &context); } Rule::AnotherDeprecatedTestRule => { test_rules::AnotherDeprecatedTestRule::diagnostic( locator, comment_ranges, - &diagnostics, + &context, ); } Rule::RemovedTestRule => { - test_rules::RemovedTestRule::diagnostic(locator, comment_ranges, &diagnostics); + test_rules::RemovedTestRule::diagnostic(locator, comment_ranges, &context); } Rule::AnotherRemovedTestRule => test_rules::AnotherRemovedTestRule::diagnostic( locator, comment_ranges, - &diagnostics, - ), - Rule::RedirectedToTestRule => test_rules::RedirectedToTestRule::diagnostic( - locator, - comment_ranges, - &diagnostics, + &context, ), + Rule::RedirectedToTestRule => { + test_rules::RedirectedToTestRule::diagnostic(locator, comment_ranges, &context); + } Rule::RedirectedFromTestRule => test_rules::RedirectedFromTestRule::diagnostic( locator, comment_ranges, - &diagnostics, + &context, ), Rule::RedirectedFromPrefixTestRule => { test_rules::RedirectedFromPrefixTestRule::diagnostic( locator, comment_ranges, - &diagnostics, + &context, ); } _ => unreachable!("All test rules must have an implementation"), @@ -378,52 +354,29 @@ pub fn check_path( } } - // Ignore diagnostics based on per-file-ignores. - let per_file_ignores = if (!diagnostics.is_empty() - || settings - .rules - .iter_enabled() - .any(|rule_code| rule_code.lint_source().is_noqa())) - && !settings.per_file_ignores.is_empty() - { - fs::ignores_from_path(path, &settings.per_file_ignores) - } else { - RuleSet::empty() - }; - if !per_file_ignores.is_empty() { - diagnostics.as_mut_vec().retain(|diagnostic| { - diagnostic - .noqa_code() - .and_then(|code| code.rule()) - .is_none_or(|rule| !per_file_ignores.contains(rule)) - }); - } - // Enforce `noqa` directives. if noqa.is_enabled() - || settings - .rules - .iter_enabled() + || context + .iter_enabled_rules() .any(|rule_code| rule_code.lint_source().is_noqa()) { let ignored = check_noqa( - &mut diagnostics, + &mut context, path, locator, comment_ranges, &directives.noqa_line_for, parsed.has_valid_syntax(), - &per_file_ignores, settings, ); if noqa.is_enabled() { for index in ignored.iter().rev() { - diagnostics.as_mut_vec().swap_remove(*index); + context.as_mut_vec().swap_remove(*index); } } } - let mut diagnostics = diagnostics.into_diagnostics(); + let (mut diagnostics, source_file) = context.into_parts(); if parsed.has_valid_syntax() { // Remove fixes for any rules marked as unfixable. diff --git a/crates/ruff_linter/src/rules/flake8_2020/rules/compare.rs b/crates/ruff_linter/src/rules/flake8_2020/rules/compare.rs index 902223ac10..1effc87e47 100644 --- a/crates/ruff_linter/src/rules/flake8_2020/rules/compare.rs +++ b/crates/ruff_linter/src/rules/flake8_2020/rules/compare.rs @@ -253,7 +253,7 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ], ) = (ops, comparators) { - if *n == 3 && checker.enabled(Rule::SysVersionInfo0Eq3) { + if *n == 3 && checker.is_rule_enabled(Rule::SysVersionInfo0Eq3) { checker.report_diagnostic( SysVersionInfo0Eq3 { eq: matches!(*operator, CmpOp::Eq), @@ -273,7 +273,7 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ], ) = (ops, comparators) { - if checker.enabled(Rule::SysVersionInfo1CmpInt) { + if checker.is_rule_enabled(Rule::SysVersionInfo1CmpInt) { checker.report_diagnostic(SysVersionInfo1CmpInt, left.range()); } } @@ -294,7 +294,7 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ], ) = (ops, comparators) { - if checker.enabled(Rule::SysVersionInfoMinorCmpInt) { + if checker.is_rule_enabled(Rule::SysVersionInfoMinorCmpInt) { checker.report_diagnostic(SysVersionInfoMinorCmpInt, left.range()); } } @@ -310,10 +310,10 @@ pub(crate) fn compare(checker: &Checker, left: &Expr, ops: &[CmpOp], comparators ) = (ops, comparators) { if value.len() == 1 { - if checker.enabled(Rule::SysVersionCmpStr10) { + if checker.is_rule_enabled(Rule::SysVersionCmpStr10) { checker.report_diagnostic(SysVersionCmpStr10, left.range()); } - } else if checker.enabled(Rule::SysVersionCmpStr3) { + } else if checker.is_rule_enabled(Rule::SysVersionCmpStr3) { checker.report_diagnostic(SysVersionCmpStr3, left.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_2020/rules/subscript.rs b/crates/ruff_linter/src/rules/flake8_2020/rules/subscript.rs index e594c4ffc0..5b5d4d6e00 100644 --- a/crates/ruff_linter/src/rules/flake8_2020/rules/subscript.rs +++ b/crates/ruff_linter/src/rules/flake8_2020/rules/subscript.rs @@ -183,9 +183,9 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, slice: &Expr) { .. }) = upper.as_ref() { - if *i == 1 && checker.enabled(Rule::SysVersionSlice1) { + if *i == 1 && checker.is_rule_enabled(Rule::SysVersionSlice1) { checker.report_diagnostic(SysVersionSlice1, value.range()); - } else if *i == 3 && checker.enabled(Rule::SysVersionSlice3) { + } else if *i == 3 && checker.is_rule_enabled(Rule::SysVersionSlice3) { checker.report_diagnostic(SysVersionSlice3, value.range()); } } @@ -195,9 +195,9 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, slice: &Expr) { value: ast::Number::Int(i), .. }) => { - if *i == 2 && checker.enabled(Rule::SysVersion2) { + if *i == 2 && checker.is_rule_enabled(Rule::SysVersion2) { checker.report_diagnostic(SysVersion2, value.range()); - } else if *i == 0 && checker.enabled(Rule::SysVersion0) { + } else if *i == 0 && checker.is_rule_enabled(Rule::SysVersion0) { checker.report_diagnostic(SysVersion0, value.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_annotations/rules/definition.rs b/crates/ruff_linter/src/rules/flake8_annotations/rules/definition.rs index 60886c0034..72d95137e0 100644 --- a/crates/ruff_linter/src/rules/flake8_annotations/rules/definition.rs +++ b/crates/ruff_linter/src/rules/flake8_annotations/rules/definition.rs @@ -639,7 +639,7 @@ pub(crate) fn definition( // ANN401 for dynamically typed parameters if let Some(annotation) = parameter.annotation() { has_any_typed_arg = true; - if checker.enabled(Rule::AnyType) && !is_overridden { + if checker.is_rule_enabled(Rule::AnyType) && !is_overridden { check_dynamically_typed( checker, annotation, @@ -654,7 +654,7 @@ pub(crate) fn definition( .dummy_variable_rgx .is_match(parameter.name())) { - if checker.enabled(Rule::MissingTypeFunctionArgument) { + if checker.is_rule_enabled(Rule::MissingTypeFunctionArgument) { diagnostics.push(checker.report_diagnostic( MissingTypeFunctionArgument { name: parameter.name().to_string(), @@ -671,7 +671,7 @@ pub(crate) fn definition( if let Some(expr) = &arg.annotation { has_any_typed_arg = true; if !checker.settings.flake8_annotations.allow_star_arg_any { - if checker.enabled(Rule::AnyType) && !is_overridden { + if checker.is_rule_enabled(Rule::AnyType) && !is_overridden { let name = &arg.name; check_dynamically_typed(checker, expr, || format!("*{name}"), &mut diagnostics); } @@ -680,7 +680,7 @@ pub(crate) fn definition( if !(checker.settings.flake8_annotations.suppress_dummy_args && checker.settings.dummy_variable_rgx.is_match(&arg.name)) { - if checker.enabled(Rule::MissingTypeArgs) { + if checker.is_rule_enabled(Rule::MissingTypeArgs) { diagnostics.push(checker.report_diagnostic( MissingTypeArgs { name: arg.name.to_string(), @@ -697,7 +697,7 @@ pub(crate) fn definition( if let Some(expr) = &arg.annotation { has_any_typed_arg = true; if !checker.settings.flake8_annotations.allow_star_arg_any { - if checker.enabled(Rule::AnyType) && !is_overridden { + if checker.is_rule_enabled(Rule::AnyType) && !is_overridden { let name = &arg.name; check_dynamically_typed( checker, @@ -711,7 +711,7 @@ pub(crate) fn definition( if !(checker.settings.flake8_annotations.suppress_dummy_args && checker.settings.dummy_variable_rgx.is_match(&arg.name)) { - if checker.enabled(Rule::MissingTypeKwargs) { + if checker.is_rule_enabled(Rule::MissingTypeKwargs) { diagnostics.push(checker.report_diagnostic( MissingTypeKwargs { name: arg.name.to_string(), @@ -726,7 +726,7 @@ pub(crate) fn definition( // ANN201, ANN202, ANN401 if let Some(expr) = &returns { has_typed_return = true; - if checker.enabled(Rule::AnyType) && !is_overridden { + if checker.is_rule_enabled(Rule::AnyType) && !is_overridden { check_dynamically_typed(checker, expr, || name.to_string(), &mut diagnostics); } } else if !( @@ -735,7 +735,7 @@ pub(crate) fn definition( checker.settings.flake8_annotations.suppress_none_returning && is_none_returning(body) ) { if is_method && visibility::is_classmethod(decorator_list, checker.semantic()) { - if checker.enabled(Rule::MissingReturnTypeClassMethod) { + if checker.is_rule_enabled(Rule::MissingReturnTypeClassMethod) { let return_type = if is_stub_function(function, checker) { None } else { @@ -761,7 +761,7 @@ pub(crate) fn definition( diagnostics.push(diagnostic); } } else if is_method && visibility::is_staticmethod(decorator_list, checker.semantic()) { - if checker.enabled(Rule::MissingReturnTypeStaticMethod) { + if checker.is_rule_enabled(Rule::MissingReturnTypeStaticMethod) { let return_type = if is_stub_function(function, checker) { None } else { @@ -789,7 +789,7 @@ pub(crate) fn definition( } else if is_method && visibility::is_init(name) { // Allow omission of return annotation in `__init__` functions, as long as at // least one argument is typed. - if checker.enabled(Rule::MissingReturnTypeSpecialMethod) { + if checker.is_rule_enabled(Rule::MissingReturnTypeSpecialMethod) { if !(checker.settings.flake8_annotations.mypy_init_return && has_any_typed_arg) { let mut diagnostic = checker.report_diagnostic( MissingReturnTypeSpecialMethod { @@ -806,7 +806,7 @@ pub(crate) fn definition( } } } else if is_method && visibility::is_magic(name) { - if checker.enabled(Rule::MissingReturnTypeSpecialMethod) { + if checker.is_rule_enabled(Rule::MissingReturnTypeSpecialMethod) { let return_type = simple_magic_return_type(name); let mut diagnostic = checker.report_diagnostic( MissingReturnTypeSpecialMethod { @@ -826,7 +826,7 @@ pub(crate) fn definition( } else { match visibility { visibility::Visibility::Public => { - if checker.enabled(Rule::MissingReturnTypeUndocumentedPublicFunction) { + if checker.is_rule_enabled(Rule::MissingReturnTypeUndocumentedPublicFunction) { let return_type = if is_stub_function(function, checker) { None } else { @@ -861,7 +861,7 @@ pub(crate) fn definition( } } visibility::Visibility::Private => { - if checker.enabled(Rule::MissingReturnTypePrivateFunction) { + if checker.is_rule_enabled(Rule::MissingReturnTypePrivateFunction) { let return_type = if is_stub_function(function, checker) { None } else { diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/shell_injection.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/shell_injection.rs index 6a423ea5b8..6d0515ac99 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/shell_injection.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/shell_injection.rs @@ -312,7 +312,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { Some(ShellKeyword { truthiness: truthiness @ (Truthiness::True | Truthiness::Truthy), }) => { - if checker.enabled(Rule::SubprocessPopenWithShellEqualsTrue) { + if checker.is_rule_enabled(Rule::SubprocessPopenWithShellEqualsTrue) { checker.report_diagnostic( SubprocessPopenWithShellEqualsTrue { safety: Safety::from(arg), @@ -325,7 +325,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { // S603 _ => { if !is_trusted_input(arg) { - if checker.enabled(Rule::SubprocessWithoutShellEqualsTrue) { + if checker.is_rule_enabled(Rule::SubprocessWithoutShellEqualsTrue) { checker.report_diagnostic( SubprocessWithoutShellEqualsTrue, call.func.range(), @@ -340,7 +340,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { }) = shell_keyword { // S604 - if checker.enabled(Rule::CallWithShellEqualsTrue) { + if checker.is_rule_enabled(Rule::CallWithShellEqualsTrue) { checker.report_diagnostic( CallWithShellEqualsTrue { is_exact: matches!(truthiness, Truthiness::True), @@ -351,7 +351,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { } // S605 - if checker.enabled(Rule::StartProcessWithAShell) { + if checker.is_rule_enabled(Rule::StartProcessWithAShell) { if matches!(call_kind, Some(CallKind::Shell)) { if let Some(arg) = call.arguments.args.first() { checker.report_diagnostic( @@ -365,14 +365,14 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { } // S606 - if checker.enabled(Rule::StartProcessWithNoShell) { + if checker.is_rule_enabled(Rule::StartProcessWithNoShell) { if matches!(call_kind, Some(CallKind::NoShell)) { checker.report_diagnostic(StartProcessWithNoShell, call.func.range()); } } // S607 - if checker.enabled(Rule::StartProcessWithPartialPath) { + if checker.is_rule_enabled(Rule::StartProcessWithPartialPath) { if call_kind.is_some() { if let Some(arg) = call.arguments.args.first() { if is_partial_path(arg) { @@ -383,7 +383,7 @@ pub(crate) fn shell_injection(checker: &Checker, call: &ast::ExprCall) { } // S609 - if checker.enabled(Rule::UnixCommandWildcardInjection) { + if checker.is_rule_enabled(Rule::UnixCommandWildcardInjection) { if matches!(call_kind, Some(CallKind::Shell)) || matches!( (call_kind, shell_keyword), diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/abstract_base_class.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/abstract_base_class.rs index b84c909303..2d14a917e7 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/abstract_base_class.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/abstract_base_class.rs @@ -192,7 +192,7 @@ pub(crate) fn abstract_base_class( let has_abstract_decorator = is_abstract(decorator_list, checker.semantic()); has_abstract_method |= has_abstract_decorator; - if !checker.enabled(Rule::EmptyMethodWithoutAbstractDecorator) { + if !checker.is_rule_enabled(Rule::EmptyMethodWithoutAbstractDecorator) { continue; } @@ -208,7 +208,7 @@ pub(crate) fn abstract_base_class( ); } } - if checker.enabled(Rule::AbstractBaseClassWithoutAbstractMethod) { + if checker.is_rule_enabled(Rule::AbstractBaseClassWithoutAbstractMethod) { if !has_abstract_method { checker.report_diagnostic( AbstractBaseClassWithoutAbstractMethod { diff --git a/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs b/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs index 6516a92390..f753152e4d 100644 --- a/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs +++ b/crates/ruff_linter/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs @@ -139,7 +139,7 @@ fn duplicate_handler_exceptions<'a>( } } - if checker.enabled(Rule::DuplicateHandlerException) { + if checker.is_rule_enabled(Rule::DuplicateHandlerException) { // TODO(charlie): Handle "BaseException" and redundant exception aliases. if !duplicates.is_empty() { let mut diagnostic = checker.report_diagnostic( @@ -209,7 +209,7 @@ pub(crate) fn duplicate_exceptions(checker: &Checker, handlers: &[ExceptHandler] } } - if checker.enabled(Rule::DuplicateTryBlockException) { + if checker.is_rule_enabled(Rule::DuplicateTryBlockException) { for (name, exprs) in duplicates { for expr in exprs { let is_star = checker diff --git a/crates/ruff_linter/src/rules/flake8_errmsg/rules/string_in_exception.rs b/crates/ruff_linter/src/rules/flake8_errmsg/rules/string_in_exception.rs index 85f1a4afeb..9e4b5b9e91 100644 --- a/crates/ruff_linter/src/rules/flake8_errmsg/rules/string_in_exception.rs +++ b/crates/ruff_linter/src/rules/flake8_errmsg/rules/string_in_exception.rs @@ -185,7 +185,7 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { match first { // Check for string literals. Expr::StringLiteral(ast::ExprStringLiteral { value: string, .. }) => { - if checker.enabled(Rule::RawStringInException) { + 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()); @@ -205,7 +205,7 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { } // Check for f-strings. Expr::FString(_) => { - if checker.enabled(Rule::FStringInException) { + 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) { @@ -221,7 +221,7 @@ pub(crate) fn string_in_exception(checker: &Checker, stmt: &Stmt, exc: &Expr) { } // Check for .format() calls. Expr::Call(ast::ExprCall { func, .. }) => { - if checker.enabled(Rule::DotFormatInException) { + if checker.is_rule_enabled(Rule::DotFormatInException) { if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() { diff --git a/crates/ruff_linter/src/rules/flake8_executable/rules/mod.rs b/crates/ruff_linter/src/rules/flake8_executable/rules/mod.rs index 82065b8af0..99d1ff31f4 100644 --- a/crates/ruff_linter/src/rules/flake8_executable/rules/mod.rs +++ b/crates/ruff_linter/src/rules/flake8_executable/rules/mod.rs @@ -11,7 +11,6 @@ use crate::Locator; use crate::checkers::ast::LintContext; use crate::codes::Rule; use crate::comments::shebang::ShebangDirective; -use crate::settings::LinterSettings; mod shebang_leading_whitespace; mod shebang_missing_executable_file; @@ -24,7 +23,6 @@ pub(crate) fn from_tokens( path: &Path, locator: &Locator, comment_ranges: &CommentRanges, - settings: &LinterSettings, ) { let mut has_any_shebang = false; for range in comment_ranges { @@ -34,7 +32,7 @@ pub(crate) fn from_tokens( shebang_missing_python(range, &shebang, context); - if settings.rules.enabled(Rule::ShebangNotExecutable) { + if context.is_rule_enabled(Rule::ShebangNotExecutable) { shebang_not_executable(path, range, context); } @@ -45,7 +43,7 @@ pub(crate) fn from_tokens( } if !has_any_shebang { - if settings.rules.enabled(Rule::ShebangMissingExecutableFile) { + if context.is_rule_enabled(Rule::ShebangMissingExecutableFile) { shebang_missing_executable_file(path, context); } } diff --git a/crates/ruff_linter/src/rules/flake8_logging_format/rules/logging_call.rs b/crates/ruff_linter/src/rules/flake8_logging_format/rules/logging_call.rs index 4d0f2fc221..05a70d9fc8 100644 --- a/crates/ruff_linter/src/rules/flake8_logging_format/rules/logging_call.rs +++ b/crates/ruff_linter/src/rules/flake8_logging_format/rules/logging_call.rs @@ -47,12 +47,12 @@ fn check_msg(checker: &Checker, msg: &Expr) { // Check for string concatenation and percent format. Expr::BinOp(ast::ExprBinOp { op, .. }) => match op { Operator::Add => { - if checker.enabled(Rule::LoggingStringConcat) { + if checker.is_rule_enabled(Rule::LoggingStringConcat) { checker.report_diagnostic(LoggingStringConcat, msg.range()); } } Operator::Mod => { - if checker.enabled(Rule::LoggingPercentFormat) { + if checker.is_rule_enabled(Rule::LoggingPercentFormat) { checker.report_diagnostic(LoggingPercentFormat, msg.range()); } } @@ -60,13 +60,13 @@ fn check_msg(checker: &Checker, msg: &Expr) { }, // Check for f-strings. Expr::FString(_) => { - if checker.enabled(Rule::LoggingFString) { + if checker.is_rule_enabled(Rule::LoggingFString) { checker.report_diagnostic(LoggingFString, msg.range()); } } // Check for .format() calls. Expr::Call(ast::ExprCall { func, .. }) => { - if checker.enabled(Rule::LoggingStringFormat) { + if checker.is_rule_enabled(Rule::LoggingStringFormat) { if let Expr::Attribute(ast::ExprAttribute { value, attr, .. }) = func.as_ref() { if attr == "format" && value.is_literal_expr() { checker.report_diagnostic(LoggingStringFormat, msg.range()); @@ -178,7 +178,7 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { } // G010 - if checker.enabled(Rule::LoggingWarn) { + if checker.is_rule_enabled(Rule::LoggingWarn) { if matches!( logging_call_type, LoggingCallType::LevelCall(LoggingLevel::Warn) @@ -192,14 +192,14 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { } // G101 - if checker.enabled(Rule::LoggingExtraAttrClash) { + if checker.is_rule_enabled(Rule::LoggingExtraAttrClash) { if let Some(extra) = call.arguments.find_keyword("extra") { check_log_record_attr_clash(checker, extra); } } // G201, G202 - if checker.any_enabled(&[Rule::LoggingExcInfo, Rule::LoggingRedundantExcInfo]) { + if checker.any_rule_enabled(&[Rule::LoggingExcInfo, Rule::LoggingRedundantExcInfo]) { if !checker.semantic().in_exception_handler() { return; } @@ -209,12 +209,12 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { if let LoggingCallType::LevelCall(logging_level) = logging_call_type { match logging_level { LoggingLevel::Error => { - if checker.enabled(Rule::LoggingExcInfo) { + if checker.is_rule_enabled(Rule::LoggingExcInfo) { checker.report_diagnostic(LoggingExcInfo, range); } } LoggingLevel::Exception => { - if checker.enabled(Rule::LoggingRedundantExcInfo) { + if checker.is_rule_enabled(Rule::LoggingRedundantExcInfo) { checker.report_diagnostic(LoggingRedundantExcInfo, exc_info.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs index edd8ac1cb7..deaaa7af4b 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs @@ -139,7 +139,7 @@ pub(crate) fn bad_version_info_comparison(checker: &Checker, test: &Expr, has_el } if matches!(op, CmpOp::Lt) { - if checker.enabled(Rule::BadVersionInfoOrder) + if checker.is_rule_enabled(Rule::BadVersionInfoOrder) // See https://github.com/astral-sh/ruff/issues/15347 && (checker.source_type.is_stub() || is_bad_version_info_in_non_stub_enabled(checker.settings)) { @@ -148,7 +148,7 @@ pub(crate) fn bad_version_info_comparison(checker: &Checker, test: &Expr, has_el } } } else { - if checker.enabled(Rule::BadVersionInfoComparison) { + if checker.is_rule_enabled(Rule::BadVersionInfoComparison) { checker.report_diagnostic(BadVersionInfoComparison, test.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_platform.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_platform.rs index 4cf4730471..bec447456e 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_platform.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_platform.rs @@ -114,7 +114,7 @@ pub(crate) fn unrecognized_platform(checker: &Checker, test: &Expr) { // "in" might also make sense but we don't currently have one. if !matches!(op, CmpOp::Eq | CmpOp::NotEq) { - if checker.enabled(Rule::UnrecognizedPlatformCheck) { + if checker.is_rule_enabled(Rule::UnrecognizedPlatformCheck) { checker.report_diagnostic(UnrecognizedPlatformCheck, test.range()); } return; @@ -123,7 +123,7 @@ pub(crate) fn unrecognized_platform(checker: &Checker, test: &Expr) { if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = right { // Other values are possible but we don't need them right now. // This protects against typos. - if checker.enabled(Rule::UnrecognizedPlatformName) { + if checker.is_rule_enabled(Rule::UnrecognizedPlatformName) { if !matches!(value.to_str(), "linux" | "win32" | "cygwin" | "darwin") { checker.report_diagnostic( UnrecognizedPlatformName { @@ -134,7 +134,7 @@ pub(crate) fn unrecognized_platform(checker: &Checker, test: &Expr) { } } } else { - if checker.enabled(Rule::UnrecognizedPlatformCheck) { + if checker.is_rule_enabled(Rule::UnrecognizedPlatformCheck) { checker.report_diagnostic(UnrecognizedPlatformCheck, test.range()); } } diff --git a/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_version_info.rs b/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_version_info.rs index e01b18613f..57eb058ba7 100644 --- a/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_version_info.rs +++ b/crates/ruff_linter/src/rules/flake8_pyi/rules/unrecognized_version_info.rs @@ -147,7 +147,7 @@ pub(crate) fn unrecognized_version_info(checker: &Checker, test: &Expr) { if let Some(expected) = ExpectedComparator::try_from(left) { version_check(checker, expected, test, *op, comparator); } else { - if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { + if checker.is_rule_enabled(Rule::UnrecognizedVersionInfoCheck) { checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } } @@ -163,7 +163,7 @@ fn version_check( // Single digit comparison, e.g., `sys.version_info[0] == 2`. if expected == ExpectedComparator::MajorDigit { if !is_int_constant(comparator) { - if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { + if checker.is_rule_enabled(Rule::UnrecognizedVersionInfoCheck) { checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } } @@ -172,7 +172,7 @@ fn version_check( // Tuple comparison, e.g., `sys.version_info == (3, 4)`. let Expr::Tuple(tuple) = comparator else { - if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { + if checker.is_rule_enabled(Rule::UnrecognizedVersionInfoCheck) { checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } return; @@ -181,18 +181,18 @@ fn version_check( if !tuple.iter().all(is_int_constant) { // All tuple elements must be integers, e.g., `sys.version_info == (3, 4)` instead of // `sys.version_info == (3.0, 4)`. - if checker.enabled(Rule::UnrecognizedVersionInfoCheck) { + if checker.is_rule_enabled(Rule::UnrecognizedVersionInfoCheck) { checker.report_diagnostic(UnrecognizedVersionInfoCheck, test.range()); } } else if tuple.len() > 2 { // Must compare against major and minor version only, e.g., `sys.version_info == (3, 4)` // instead of `sys.version_info == (3, 4, 0)`. - if checker.enabled(Rule::PatchVersionComparison) { + if checker.is_rule_enabled(Rule::PatchVersionComparison) { checker.report_diagnostic(PatchVersionComparison, test.range()); } } - if checker.enabled(Rule::WrongTupleLengthVersionComparison) { + if checker.is_rule_enabled(Rule::WrongTupleLengthVersionComparison) { if op == CmpOp::Eq || op == CmpOp::NotEq { let expected_length = match expected { ExpectedComparator::MajorTuple => 1, diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fixture.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fixture.rs index 6c5f84706d..7c31ef375d 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fixture.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/fixture.rs @@ -713,7 +713,7 @@ fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decor range: _, node_index: _, }) => { - if checker.enabled(Rule::PytestFixtureIncorrectParenthesesStyle) { + if checker.is_rule_enabled(Rule::PytestFixtureIncorrectParenthesesStyle) { if !checker.settings.flake8_pytest_style.fixture_parentheses && arguments.args.is_empty() && arguments.keywords.is_empty() @@ -739,7 +739,7 @@ fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decor } } - if checker.enabled(Rule::PytestFixturePositionalArgs) { + if checker.is_rule_enabled(Rule::PytestFixturePositionalArgs) { if !arguments.args.is_empty() { checker.report_diagnostic( PytestFixturePositionalArgs { @@ -750,7 +750,7 @@ fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decor } } - if checker.enabled(Rule::PytestExtraneousScopeFunction) { + if checker.is_rule_enabled(Rule::PytestExtraneousScopeFunction) { if let Some(keyword) = arguments.find_keyword("scope") { if keyword_is_literal(keyword, "function") { let mut diagnostic = checker @@ -769,7 +769,7 @@ fn check_fixture_decorator(checker: &Checker, func_name: &str, decorator: &Decor } } _ => { - if checker.enabled(Rule::PytestFixtureIncorrectParenthesesStyle) { + if checker.is_rule_enabled(Rule::PytestFixtureIncorrectParenthesesStyle) { if checker.settings.flake8_pytest_style.fixture_parentheses { let fix = Fix::safe_edit(Edit::insertion( Parentheses::Empty.to_string(), @@ -796,7 +796,7 @@ fn check_fixture_returns(checker: &Checker, name: &str, body: &[Stmt], returns: visitor.visit_stmt(stmt); } - if checker.enabled(Rule::PytestUselessYieldFixture) { + if checker.is_rule_enabled(Rule::PytestUselessYieldFixture) { let Some(stmt) = body.last() else { return; }; @@ -924,7 +924,7 @@ fn check_fixture_addfinalizer(checker: &Checker, parameters: &Parameters, body: /// PT024, PT025 fn check_fixture_marks(checker: &Checker, decorators: &[Decorator]) { for (expr, marker) in get_mark_decorators(decorators, checker.semantic()) { - if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) { + if checker.is_rule_enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) { if marker == "asyncio" { let mut diagnostic = checker.report_diagnostic(PytestUnnecessaryAsyncioMarkOnFixture, expr.range()); @@ -933,7 +933,7 @@ fn check_fixture_marks(checker: &Checker, decorators: &[Decorator]) { } } - if checker.enabled(Rule::PytestErroneousUseFixturesOnFixture) { + if checker.is_rule_enabled(Rule::PytestErroneousUseFixturesOnFixture) { if marker == "usefixtures" { let mut diagnostic = checker.report_diagnostic(PytestErroneousUseFixturesOnFixture, expr.range()); @@ -954,35 +954,35 @@ pub(crate) fn fixture( ) { let decorator = fixture_decorator(decorators, checker.semantic()); if let Some(decorator) = decorator { - if checker.enabled(Rule::PytestFixtureIncorrectParenthesesStyle) - || checker.enabled(Rule::PytestFixturePositionalArgs) - || checker.enabled(Rule::PytestExtraneousScopeFunction) + if checker.is_rule_enabled(Rule::PytestFixtureIncorrectParenthesesStyle) + || checker.is_rule_enabled(Rule::PytestFixturePositionalArgs) + || checker.is_rule_enabled(Rule::PytestExtraneousScopeFunction) { check_fixture_decorator(checker, name, decorator); } - if checker.enabled(Rule::PytestDeprecatedYieldFixture) { + if checker.is_rule_enabled(Rule::PytestDeprecatedYieldFixture) { check_fixture_decorator_name(checker, decorator); } - if checker.enabled(Rule::PytestUselessYieldFixture) + if checker.is_rule_enabled(Rule::PytestUselessYieldFixture) && !is_abstract(decorators, checker.semantic()) { check_fixture_returns(checker, name, body, returns); } - if checker.enabled(Rule::PytestFixtureFinalizerCallback) { + if checker.is_rule_enabled(Rule::PytestFixtureFinalizerCallback) { check_fixture_addfinalizer(checker, parameters, body); } - if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) - || checker.enabled(Rule::PytestErroneousUseFixturesOnFixture) + if checker.is_rule_enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) + || checker.is_rule_enabled(Rule::PytestErroneousUseFixturesOnFixture) { check_fixture_marks(checker, decorators); } } - if checker.enabled(Rule::PytestFixtureParamWithoutValue) && name.starts_with("test_") { + if checker.is_rule_enabled(Rule::PytestFixtureParamWithoutValue) && name.starts_with("test_") { check_test_function_args(checker, parameters, decorators); } } diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/marks.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/marks.rs index 75e64da73e..65a68d095d 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/marks.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/marks.rs @@ -235,8 +235,9 @@ fn check_useless_usefixtures(checker: &Checker, decorator: &Decorator, marker: & } pub(crate) fn marks(checker: &Checker, decorators: &[Decorator]) { - let enforce_parentheses = checker.enabled(Rule::PytestIncorrectMarkParenthesesStyle); - let enforce_useless_usefixtures = checker.enabled(Rule::PytestUseFixturesWithoutParameters); + let enforce_parentheses = checker.is_rule_enabled(Rule::PytestIncorrectMarkParenthesesStyle); + let enforce_useless_usefixtures = + checker.is_rule_enabled(Rule::PytestUseFixturesWithoutParameters); for (decorator, marker) in get_mark_decorators(decorators, checker.semantic()) { if enforce_parentheses { diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/parametrize.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/parametrize.rs index 66590cc684..a1de3178f5 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/parametrize.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/parametrize.rs @@ -865,7 +865,7 @@ pub(crate) fn parametrize(checker: &Checker, call: &ExprCall) { return; } - if checker.enabled(Rule::PytestParametrizeNamesWrongType) { + if checker.is_rule_enabled(Rule::PytestParametrizeNamesWrongType) { let names = call.arguments.find_argument_value("argnames", 0); let values = call.arguments.find_argument_value("argvalues", 1); @@ -873,7 +873,7 @@ pub(crate) fn parametrize(checker: &Checker, call: &ExprCall) { check_names(checker, call, names, values); } } - if checker.enabled(Rule::PytestParametrizeValuesWrongType) { + if checker.is_rule_enabled(Rule::PytestParametrizeValuesWrongType) { let names = call.arguments.find_argument_value("argnames", 0); let values = call.arguments.find_argument_value("argvalues", 1); @@ -881,7 +881,7 @@ pub(crate) fn parametrize(checker: &Checker, call: &ExprCall) { check_values(checker, names, values); } } - if checker.enabled(Rule::PytestDuplicateParametrizeTestCases) { + if checker.is_rule_enabled(Rule::PytestDuplicateParametrizeTestCases) { if let Some(values) = call.arguments.find_argument_value("argvalues", 1) { check_duplicates(checker, values); } diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs index ce4763e83b..0b429919c8 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/raises.rs @@ -172,7 +172,7 @@ const fn is_non_trivial_with_body(body: &[Stmt]) -> bool { pub(crate) fn raises_call(checker: &Checker, call: &ast::ExprCall) { if is_pytest_raises(&call.func, checker.semantic()) { - if checker.enabled(Rule::PytestRaisesWithoutException) { + if checker.is_rule_enabled(Rule::PytestRaisesWithoutException) { if call .arguments .find_argument("expected_exception", 0) @@ -182,7 +182,7 @@ pub(crate) fn raises_call(checker: &Checker, call: &ast::ExprCall) { } } - if checker.enabled(Rule::PytestRaisesTooBroad) { + if checker.is_rule_enabled(Rule::PytestRaisesTooBroad) { // Pytest.raises has two overloads // ```py // with raises(expected_exception: type[E] | tuple[type[E], ...], *, match: str | Pattern[str] | None = ...) → RaisesContext[E] as excinfo diff --git a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/warns.rs b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/warns.rs index 9b3d6e0796..4d6497cbae 100644 --- a/crates/ruff_linter/src/rules/flake8_pytest_style/rules/warns.rs +++ b/crates/ruff_linter/src/rules/flake8_pytest_style/rules/warns.rs @@ -172,13 +172,13 @@ const fn is_non_trivial_with_body(body: &[Stmt]) -> bool { /// PT029, PT030 pub(crate) fn warns_call(checker: &Checker, call: &ast::ExprCall) { if is_pytest_warns(&call.func, checker.semantic()) { - if checker.enabled(Rule::PytestWarnsWithoutWarning) { + if checker.is_rule_enabled(Rule::PytestWarnsWithoutWarning) { if call.arguments.is_empty() { checker.report_diagnostic(PytestWarnsWithoutWarning, call.func.range()); } } - if checker.enabled(Rule::PytestWarnsTooBroad) { + if checker.is_rule_enabled(Rule::PytestWarnsTooBroad) { if let Some(warning) = call.arguments.find_argument_value("expected_warning", 0) { if call .arguments diff --git a/crates/ruff_linter/src/rules/flake8_quotes/rules/check_string_quotes.rs b/crates/ruff_linter/src/rules/flake8_quotes/rules/check_string_quotes.rs index 2607d3d2d1..aedce054a2 100644 --- a/crates/ruff_linter/src/rules/flake8_quotes/rules/check_string_quotes.rs +++ b/crates/ruff_linter/src/rules/flake8_quotes/rules/check_string_quotes.rs @@ -332,7 +332,7 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { for (range, trivia) in sequence.iter().zip(trivia) { if trivia.is_multiline { // If multiline strings aren't enforced, ignore it. - if !checker.enabled(Rule::BadQuotesMultilineString) { + if !checker.is_rule_enabled(Rule::BadQuotesMultilineString) { continue; } @@ -377,7 +377,7 @@ fn strings(checker: &Checker, sequence: &[TextRange]) { && !relax_quote { // If inline strings aren't enforced, ignore it. - if !checker.enabled(Rule::BadQuotesInlineString) { + if !checker.is_rule_enabled(Rule::BadQuotesInlineString) { continue; } @@ -454,13 +454,14 @@ pub(crate) fn check_string_quotes(checker: &Checker, string_like: StringLike) { let ranges: Vec<_> = string_like.parts().map(|part| part.range()).collect(); if checker.semantic().in_pep_257_docstring() { - if checker.enabled(Rule::BadQuotesDocstring) { + if checker.is_rule_enabled(Rule::BadQuotesDocstring) { for range in ranges { docstring(checker, range); } } } else { - if checker.any_enabled(&[Rule::BadQuotesInlineString, Rule::BadQuotesMultilineString]) { + if checker.any_rule_enabled(&[Rule::BadQuotesInlineString, Rule::BadQuotesMultilineString]) + { strings(checker, &ranges); } } diff --git a/crates/ruff_linter/src/rules/flake8_return/rules/function.rs b/crates/ruff_linter/src/rules/flake8_return/rules/function.rs index d74cc58c33..51cbbe439f 100644 --- a/crates/ruff_linter/src/rules/flake8_return/rules/function.rs +++ b/crates/ruff_linter/src/rules/flake8_return/rules/function.rs @@ -700,7 +700,7 @@ pub(crate) fn function(checker: &Checker, function_def: &ast::StmtFunctionDef) { return; } - if checker.any_enabled(&[ + if checker.any_rule_enabled(&[ Rule::SuperfluousElseReturn, Rule::SuperfluousElseRaise, Rule::SuperfluousElseContinue, @@ -716,18 +716,18 @@ pub(crate) fn function(checker: &Checker, function_def: &ast::StmtFunctionDef) { // If we have at least one non-`None` return... if result_exists(&stack.returns) { - if checker.enabled(Rule::ImplicitReturnValue) { + if checker.is_rule_enabled(Rule::ImplicitReturnValue) { implicit_return_value(checker, &stack); } - if checker.enabled(Rule::ImplicitReturn) { + if checker.is_rule_enabled(Rule::ImplicitReturn) { implicit_return(checker, function_def, last_stmt); } - if checker.enabled(Rule::UnnecessaryAssign) { + if checker.is_rule_enabled(Rule::UnnecessaryAssign) { unnecessary_assign(checker, &stack); } } else { - if checker.enabled(Rule::UnnecessaryReturnNone) { + if checker.is_rule_enabled(Rule::UnnecessaryReturnNone) { // Skip functions that have a return annotation that is not `None`. if returns.as_deref().is_none_or(Expr::is_none_literal_expr) { unnecessary_return_none(checker, decorator_list, &stack); diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/rules/type_alias_quotes.rs b/crates/ruff_linter/src/rules/flake8_type_checking/rules/type_alias_quotes.rs index cf47b80d93..1a4e250e0f 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/rules/type_alias_quotes.rs +++ b/crates/ruff_linter/src/rules/flake8_type_checking/rules/type_alias_quotes.rs @@ -246,7 +246,7 @@ fn collect_typing_references<'a>( // if TC004 is enabled we shouldn't emit a TC007 for a reference to // a binding that would emit a TC004, otherwise the fixes will never // stabilize and keep going in circles - if checker.enabled(Rule::RuntimeImportInTypeCheckingBlock) + if checker.is_rule_enabled(Rule::RuntimeImportInTypeCheckingBlock) && checker .semantic() .binding(binding_id) @@ -267,7 +267,7 @@ pub(crate) fn quoted_type_alias( expr: &Expr, annotation_expr: &ast::ExprStringLiteral, ) { - if checker.enabled(Rule::RuntimeStringUnion) { + if checker.is_rule_enabled(Rule::RuntimeStringUnion) { // this should return a TC010 error instead if let Some(Expr::BinOp(ast::ExprBinOp { op: Operator::BitOr, diff --git a/crates/ruff_linter/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs b/crates/ruff_linter/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs index e91d00409d..872a079f86 100644 --- a/crates/ruff_linter/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs +++ b/crates/ruff_linter/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs @@ -347,7 +347,7 @@ pub(crate) fn typing_only_runtime_import( } }; - if !checker.enabled(rule_for(import_type)) { + if !checker.is_rule_enabled(rule_for(import_type)) { continue; } diff --git a/crates/ruff_linter/src/rules/flake8_unused_arguments/rules/unused_arguments.rs b/crates/ruff_linter/src/rules/flake8_unused_arguments/rules/unused_arguments.rs index 774f689ed0..62d083d107 100644 --- a/crates/ruff_linter/src/rules/flake8_unused_arguments/rules/unused_arguments.rs +++ b/crates/ruff_linter/src/rules/flake8_unused_arguments/rules/unused_arguments.rs @@ -412,7 +412,7 @@ pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) { &checker.settings.pep8_naming.staticmethod_decorators, ) { function_type::FunctionType::Function => { - if checker.enabled(Argumentable::Function.rule_code()) + if checker.is_rule_enabled(Argumentable::Function.rule_code()) && !function_type::is_stub(function_def, checker.semantic()) && !is_not_implemented_stub_with_variable(function_def, checker.semantic()) && !visibility::is_overload(decorator_list, checker.semantic()) @@ -421,7 +421,7 @@ pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) { } } function_type::FunctionType::Method => { - if checker.enabled(Argumentable::Method.rule_code()) + if checker.is_rule_enabled(Argumentable::Method.rule_code()) && !function_type::is_stub(function_def, checker.semantic()) && !is_not_implemented_stub_with_variable(function_def, checker.semantic()) && (!visibility::is_magic(name) @@ -435,7 +435,7 @@ pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) { } } function_type::FunctionType::ClassMethod => { - if checker.enabled(Argumentable::ClassMethod.rule_code()) + if checker.is_rule_enabled(Argumentable::ClassMethod.rule_code()) && !function_type::is_stub(function_def, checker.semantic()) && !is_not_implemented_stub_with_variable(function_def, checker.semantic()) && (!visibility::is_magic(name) @@ -449,7 +449,7 @@ pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) { } } function_type::FunctionType::StaticMethod => { - if checker.enabled(Argumentable::StaticMethod.rule_code()) + if checker.is_rule_enabled(Argumentable::StaticMethod.rule_code()) && !function_type::is_stub(function_def, checker.semantic()) && !is_not_implemented_stub_with_variable(function_def, checker.semantic()) && (!visibility::is_magic(name) @@ -463,7 +463,7 @@ pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) { } } function_type::FunctionType::NewMethod => { - if checker.enabled(Argumentable::StaticMethod.rule_code()) + if checker.is_rule_enabled(Argumentable::StaticMethod.rule_code()) && !function_type::is_stub(function_def, checker.semantic()) && !is_not_implemented_stub_with_variable(function_def, checker.semantic()) && !visibility::is_abstract(decorator_list, checker.semantic()) @@ -479,7 +479,7 @@ pub(crate) fn unused_arguments(checker: &Checker, scope: &Scope) { } ScopeKind::Lambda(ast::ExprLambda { parameters, .. }) => { if let Some(parameters) = parameters { - if checker.enabled(Argumentable::Lambda.rule_code()) { + if checker.is_rule_enabled(Argumentable::Lambda.rule_code()) { function(Argumentable::Lambda, parameters, scope, checker); } } diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/call.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/call.rs index df8e47a861..0ed5cdfc28 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/call.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/call.rs @@ -181,21 +181,16 @@ pub(crate) fn call(checker: &Checker, func: &Expr) { let range = func.range(); match attr.as_str() { - "isnull" if checker.settings.rules.enabled(Rule::PandasUseOfDotIsNull) => { + "isnull" if checker.is_rule_enabled(Rule::PandasUseOfDotIsNull) => { checker.report_diagnostic(PandasUseOfDotIsNull, range); } - "notnull" if checker.settings.rules.enabled(Rule::PandasUseOfDotNotNull) => { + "notnull" if checker.is_rule_enabled(Rule::PandasUseOfDotNotNull) => { checker.report_diagnostic(PandasUseOfDotNotNull, range); } - "pivot" | "unstack" - if checker - .settings - .rules - .enabled(Rule::PandasUseOfDotPivotOrUnstack) => - { + "pivot" | "unstack" if checker.is_rule_enabled(Rule::PandasUseOfDotPivotOrUnstack) => { checker.report_diagnostic(PandasUseOfDotPivotOrUnstack, range); } - "stack" if checker.settings.rules.enabled(Rule::PandasUseOfDotStack) => { + "stack" if checker.is_rule_enabled(Rule::PandasUseOfDotStack) => { checker.report_diagnostic(PandasUseOfDotStack, range); } _ => {} diff --git a/crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs b/crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs index ce1ff5bcc4..bf4f9ea31a 100644 --- a/crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs +++ b/crates/ruff_linter/src/rules/pandas_vet/rules/subscript.rs @@ -163,13 +163,13 @@ pub(crate) fn subscript(checker: &Checker, value: &Expr, expr: &Expr) { let range = expr.range(); match attr.as_str() { - "ix" if checker.settings.rules.enabled(Rule::PandasUseOfDotIx) => { + "ix" if checker.is_rule_enabled(Rule::PandasUseOfDotIx) => { checker.report_diagnostic(PandasUseOfDotIx, range) } - "at" if checker.settings.rules.enabled(Rule::PandasUseOfDotAt) => { + "at" if checker.is_rule_enabled(Rule::PandasUseOfDotAt) => { checker.report_diagnostic(PandasUseOfDotAt, range) } - "iat" if checker.settings.rules.enabled(Rule::PandasUseOfDotIat) => { + "iat" if checker.is_rule_enabled(Rule::PandasUseOfDotIat) => { checker.report_diagnostic(PandasUseOfDotIat, range) } _ => return, diff --git a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_first_argument_name.rs b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_first_argument_name.rs index 93f06cdea1..f326f16f2b 100644 --- a/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_first_argument_name.rs +++ b/crates/ruff_linter/src/rules/pep8_naming/rules/invalid_first_argument_name.rs @@ -243,7 +243,7 @@ pub(crate) fn invalid_first_argument_name(checker: &Checker, scope: &Scope) { return; } }; - if !checker.enabled(function_type.rule()) { + if !checker.is_rule_enabled(function_type.rule()) { return; } diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/literal_comparisons.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/literal_comparisons.rs index 837dc70731..baf229ada8 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/literal_comparisons.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/literal_comparisons.rs @@ -222,7 +222,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) if !helpers::is_constant_non_singleton(next) { if let Some(op) = EqCmpOp::try_from(*op) { - if checker.enabled(Rule::NoneComparison) && comparator.is_none_literal_expr() { + if checker.is_rule_enabled(Rule::NoneComparison) && comparator.is_none_literal_expr() { match op { EqCmpOp::Eq => { let diagnostic = @@ -239,7 +239,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } } - if checker.enabled(Rule::TrueFalseComparison) { + if checker.is_rule_enabled(Rule::TrueFalseComparison) { if let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = comparator { match op { EqCmpOp::Eq => { @@ -290,7 +290,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } if let Some(op) = EqCmpOp::try_from(*op) { - if checker.enabled(Rule::NoneComparison) && next.is_none_literal_expr() { + if checker.is_rule_enabled(Rule::NoneComparison) && next.is_none_literal_expr() { match op { EqCmpOp::Eq => { let diagnostic = @@ -307,7 +307,7 @@ pub(crate) fn literal_comparisons(checker: &Checker, compare: &ast::ExprCompare) } } - if checker.enabled(Rule::TrueFalseComparison) { + if checker.is_rule_enabled(Rule::TrueFalseComparison) { if let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = next { match op { EqCmpOp::Eq => { diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/not_tests.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/not_tests.rs index 30460c1b7c..a431cb0368 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/not_tests.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/not_tests.rs @@ -96,7 +96,7 @@ pub(crate) fn not_tests(checker: &Checker, unary_op: &ast::ExprUnaryOp) { match &**ops { [CmpOp::In] => { - if checker.enabled(Rule::NotInTest) { + if checker.is_rule_enabled(Rule::NotInTest) { let mut diagnostic = checker.report_diagnostic(NotInTest, unary_op.operand.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( pad( @@ -116,7 +116,7 @@ pub(crate) fn not_tests(checker: &Checker, unary_op: &ast::ExprUnaryOp) { } } [CmpOp::Is] => { - if checker.enabled(Rule::NotIsTest) { + if checker.is_rule_enabled(Rule::NotIsTest) { let mut diagnostic = checker.report_diagnostic(NotIsTest, unary_op.operand.range()); diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( pad( diff --git a/crates/ruff_linter/src/rules/pycodestyle/rules/trailing_whitespace.rs b/crates/ruff_linter/src/rules/pycodestyle/rules/trailing_whitespace.rs index 1f2b8f94b5..6f077fd18c 100644 --- a/crates/ruff_linter/src/rules/pycodestyle/rules/trailing_whitespace.rs +++ b/crates/ruff_linter/src/rules/pycodestyle/rules/trailing_whitespace.rs @@ -6,7 +6,6 @@ use ruff_text_size::{TextLen, TextRange, TextSize}; use crate::Locator; use crate::checkers::ast::LintContext; use crate::registry::Rule; -use crate::settings::LinterSettings; use crate::{AlwaysFixableViolation, Applicability, Edit, Fix}; /// ## What it does @@ -88,7 +87,6 @@ pub(crate) fn trailing_whitespace( line: &Line, locator: &Locator, indexer: &Indexer, - settings: &LinterSettings, context: &LintContext, ) { let whitespace_len: TextSize = line @@ -106,7 +104,7 @@ pub(crate) fn trailing_whitespace( Applicability::Safe }; if range == line.range() { - if settings.rules.enabled(Rule::BlankLineWithWhitespace) { + if context.is_rule_enabled(Rule::BlankLineWithWhitespace) { let mut diagnostic = context.report_diagnostic(BlankLineWithWhitespace, range); // Remove any preceding continuations, to avoid introducing a potential // syntax error. @@ -120,7 +118,7 @@ pub(crate) fn trailing_whitespace( applicability, )); } - } else if settings.rules.enabled(Rule::TrailingWhitespace) { + } else if context.is_rule_enabled(Rule::TrailingWhitespace) { let mut diagnostic = context.report_diagnostic(TrailingWhitespace, range); diagnostic.set_fix(Fix::applicable_edit( Edit::range_deletion(range), diff --git a/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs b/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs index 5c392ae93a..26305caf81 100644 --- a/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs +++ b/crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs @@ -915,7 +915,7 @@ pub(crate) fn check_docstring( }; // DOC201 - if checker.enabled(Rule::DocstringMissingReturns) { + if checker.is_rule_enabled(Rule::DocstringMissingReturns) { if should_document_returns(function_def) && !returns_documented(docstring, &docstring_sections, convention) { @@ -953,7 +953,7 @@ pub(crate) fn check_docstring( } // DOC402 - if checker.enabled(Rule::DocstringMissingYields) { + if checker.is_rule_enabled(Rule::DocstringMissingYields) { if !yields_documented(docstring, &docstring_sections, convention) { if !body_entries.yields.is_empty() { match function_def.returns.as_deref() { @@ -974,7 +974,7 @@ pub(crate) fn check_docstring( } // DOC501 - if checker.enabled(Rule::DocstringMissingException) { + if checker.is_rule_enabled(Rule::DocstringMissingException) { for body_raise in &body_entries.raised_exceptions { let Some(name) = body_raise.qualified_name.segments().last() else { continue; @@ -1006,7 +1006,7 @@ pub(crate) fn check_docstring( // document that it raises an exception without including the exception in the implementation. if !visibility::is_abstract(&function_def.decorator_list, semantic) { // DOC202 - if checker.enabled(Rule::DocstringExtraneousReturns) { + if checker.is_rule_enabled(Rule::DocstringExtraneousReturns) { if docstring_sections.returns.is_some() { if body_entries.returns.is_empty() || body_entries.returns.iter().all(ReturnEntry::is_implicit) @@ -1017,7 +1017,7 @@ pub(crate) fn check_docstring( } // DOC403 - if checker.enabled(Rule::DocstringExtraneousYields) { + if checker.is_rule_enabled(Rule::DocstringExtraneousYields) { if docstring_sections.yields.is_some() { if body_entries.yields.is_empty() { checker.report_diagnostic(DocstringExtraneousYields, docstring.range()); @@ -1026,7 +1026,7 @@ pub(crate) fn check_docstring( } // DOC502 - if checker.enabled(Rule::DocstringExtraneousException) { + if checker.is_rule_enabled(Rule::DocstringExtraneousException) { if let Some(docstring_raises) = docstring_sections.raises { let mut extraneous_exceptions = Vec::new(); for docstring_raise in &docstring_raises.raised_exceptions { diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_class.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_class.rs index 05c6cdf1aa..1196a42a75 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_class.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_class.rs @@ -170,8 +170,8 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) return; } - if checker.enabled(Rule::IncorrectBlankLineBeforeClass) - || checker.enabled(Rule::BlankLineBeforeClass) + if checker.is_rule_enabled(Rule::IncorrectBlankLineBeforeClass) + || checker.is_rule_enabled(Rule::BlankLineBeforeClass) { let mut lines = UniversalNewlineIterator::with_offset( checker.locator().slice(between_range), @@ -191,7 +191,7 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) } } - if checker.enabled(Rule::BlankLineBeforeClass) { + if checker.is_rule_enabled(Rule::BlankLineBeforeClass) { if blank_lines_before != 0 { let mut diagnostic = checker.report_diagnostic(BlankLineBeforeClass, docstring.range()); @@ -202,7 +202,7 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) ))); } } - if checker.enabled(Rule::IncorrectBlankLineBeforeClass) { + if checker.is_rule_enabled(Rule::IncorrectBlankLineBeforeClass) { if blank_lines_before != 1 { let mut diagnostic = checker.report_diagnostic(IncorrectBlankLineBeforeClass, docstring.range()); @@ -216,7 +216,7 @@ pub(crate) fn blank_before_after_class(checker: &Checker, docstring: &Docstring) } } - if checker.enabled(Rule::IncorrectBlankLineAfterClass) { + if checker.is_rule_enabled(Rule::IncorrectBlankLineAfterClass) { let class_after_docstring_range = TextRange::new(docstring.end(), class.end()); let class_after_docstring = checker.locator().slice(class_after_docstring_range); let mut lines = UniversalNewlineIterator::with_offset( diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_function.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_function.rs index 82ff085979..a3f1ab0efd 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_function.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/blank_before_after_function.rs @@ -107,7 +107,7 @@ pub(crate) fn blank_before_after_function(checker: &Checker, docstring: &Docstri return; }; - if checker.enabled(Rule::BlankLineBeforeFunction) { + if checker.is_rule_enabled(Rule::BlankLineBeforeFunction) { let before = checker .locator() .slice(TextRange::new(function.start(), docstring.start())); @@ -140,7 +140,7 @@ pub(crate) fn blank_before_after_function(checker: &Checker, docstring: &Docstri } } - if checker.enabled(Rule::BlankLineAfterFunction) { + if checker.is_rule_enabled(Rule::BlankLineAfterFunction) { let after = checker .locator() .slice(TextRange::new(docstring.end(), function.end())); diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs index 4e9256f0de..2a8f9b721f 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/indent.rs @@ -220,7 +220,7 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { // yet. has_seen_tab = has_seen_tab || line_indent.contains('\t'); - if checker.enabled(Rule::UnderIndentation) { + if checker.is_rule_enabled(Rule::UnderIndentation) { // We report under-indentation on every line. This isn't great, but enables // fix. if (is_last || !is_blank) && line_indent_size < docstring_indent_size { @@ -264,13 +264,13 @@ pub(crate) fn indent(checker: &Checker, docstring: &Docstring) { current = lines.next(); } - if checker.enabled(Rule::DocstringTabIndentation) { + if checker.is_rule_enabled(Rule::DocstringTabIndentation) { if has_seen_tab { checker.report_diagnostic(DocstringTabIndentation, docstring.range()); } } - if checker.enabled(Rule::OverIndentation) { + if checker.is_rule_enabled(Rule::OverIndentation) { // If every line (except the last) is over-indented... if let Some(smallest_over_indent_size) = smallest_over_indent_size { for line in over_indented_lines { diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/multi_line_summary_start.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/multi_line_summary_start.rs index 12bbc25d31..f9e1348e7c 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/multi_line_summary_start.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/multi_line_summary_start.rs @@ -155,7 +155,7 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring) }; if is_triple_quote(&first_line) { - if checker.enabled(Rule::MultiLineSummaryFirstLine) { + if checker.is_rule_enabled(Rule::MultiLineSummaryFirstLine) { let mut diagnostic = checker.report_diagnostic(MultiLineSummaryFirstLine, docstring.range()); // Delete until first non-whitespace char. @@ -179,7 +179,7 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring) // ``` return; } else { - if checker.enabled(Rule::MultiLineSummarySecondLine) { + if checker.is_rule_enabled(Rule::MultiLineSummarySecondLine) { let mut diagnostic = checker.report_diagnostic(MultiLineSummarySecondLine, docstring.range()); let mut indentation = Cow::Borrowed(docstring.compute_indentation()); diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/not_empty.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/not_empty.rs index c23e33a85b..2df678639d 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/not_empty.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/not_empty.rs @@ -45,7 +45,7 @@ pub(crate) fn not_empty(checker: &Checker, docstring: &Docstring) -> bool { return true; } - if checker.enabled(Rule::EmptyDocstring) { + if checker.is_rule_enabled(Rule::EmptyDocstring) { checker.report_diagnostic(EmptyDocstring, docstring.range()); } false diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/not_missing.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/not_missing.rs index 1052b80f0a..087916b25c 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/not_missing.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/not_missing.rs @@ -551,7 +551,7 @@ pub(crate) fn not_missing( if checker.source_type.is_ipynb() { return true; } - if checker.enabled(Rule::UndocumentedPublicModule) { + if checker.is_rule_enabled(Rule::UndocumentedPublicModule) { checker.report_diagnostic(UndocumentedPublicModule, TextRange::default()); } false @@ -560,7 +560,7 @@ pub(crate) fn not_missing( kind: ModuleKind::Package, .. }) => { - if checker.enabled(Rule::UndocumentedPublicPackage) { + if checker.is_rule_enabled(Rule::UndocumentedPublicPackage) { checker.report_diagnostic(UndocumentedPublicPackage, TextRange::default()); } false @@ -569,7 +569,7 @@ pub(crate) fn not_missing( kind: MemberKind::Class(class), .. }) => { - if checker.enabled(Rule::UndocumentedPublicClass) { + if checker.is_rule_enabled(Rule::UndocumentedPublicClass) { checker.report_diagnostic(UndocumentedPublicClass, class.identifier()); } false @@ -578,7 +578,7 @@ pub(crate) fn not_missing( kind: MemberKind::NestedClass(function), .. }) => { - if checker.enabled(Rule::UndocumentedPublicNestedClass) { + if checker.is_rule_enabled(Rule::UndocumentedPublicNestedClass) { checker.report_diagnostic(UndocumentedPublicNestedClass, function.identifier()); } false @@ -590,7 +590,7 @@ pub(crate) fn not_missing( if is_overload(&function.decorator_list, checker.semantic()) { true } else { - if checker.enabled(Rule::UndocumentedPublicFunction) { + if checker.is_rule_enabled(Rule::UndocumentedPublicFunction) { checker.report_diagnostic(UndocumentedPublicFunction, function.identifier()); } false @@ -605,22 +605,22 @@ pub(crate) fn not_missing( { true } else if is_init(&function.name) { - if checker.enabled(Rule::UndocumentedPublicInit) { + if checker.is_rule_enabled(Rule::UndocumentedPublicInit) { checker.report_diagnostic(UndocumentedPublicInit, function.identifier()); } true } else if is_new(&function.name) || is_call(&function.name) { - if checker.enabled(Rule::UndocumentedPublicMethod) { + if checker.is_rule_enabled(Rule::UndocumentedPublicMethod) { checker.report_diagnostic(UndocumentedPublicMethod, function.identifier()); } true } else if is_magic(&function.name) { - if checker.enabled(Rule::UndocumentedMagicMethod) { + if checker.is_rule_enabled(Rule::UndocumentedMagicMethod) { checker.report_diagnostic(UndocumentedMagicMethod, function.identifier()); } true } else { - if checker.enabled(Rule::UndocumentedPublicMethod) { + if checker.is_rule_enabled(Rule::UndocumentedPublicMethod) { checker.report_diagnostic(UndocumentedPublicMethod, function.identifier()); } true diff --git a/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs b/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs index d7da286b16..d09fb9a8cd 100644 --- a/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs +++ b/crates/ruff_linter/src/rules/pydocstyle/rules/sections.rs @@ -1361,7 +1361,7 @@ fn blanks_and_section_underline( if let Some(non_blank_line) = following_lines.next() { if let Some(dashed_line) = find_underline(&non_blank_line, '-') { if num_blank_lines_after_header > 0 { - if checker.enabled(Rule::MissingSectionUnderlineAfterName) { + if checker.is_rule_enabled(Rule::MissingSectionUnderlineAfterName) { let mut diagnostic = checker.report_diagnostic( MissingSectionUnderlineAfterName { name: context.section_name().to_string(), @@ -1378,7 +1378,7 @@ fn blanks_and_section_underline( } if dashed_line.len().to_usize() != context.section_name().len() { - if checker.enabled(Rule::MismatchedSectionUnderlineLength) { + if checker.is_rule_enabled(Rule::MismatchedSectionUnderlineLength) { let mut diagnostic = checker.report_diagnostic( MismatchedSectionUnderlineLength { name: context.section_name().to_string(), @@ -1394,7 +1394,7 @@ fn blanks_and_section_underline( } } - if checker.enabled(Rule::OverindentedSectionUnderline) { + if checker.is_rule_enabled(Rule::OverindentedSectionUnderline) { let leading_space = leading_space(&non_blank_line); let docstring_indentation = docstring.compute_indentation(); if leading_space.len() > docstring_indentation.len() { @@ -1434,7 +1434,7 @@ fn blanks_and_section_underline( } if following_lines.peek().is_none() { - if checker.enabled(Rule::EmptyDocstringSection) { + if checker.is_rule_enabled(Rule::EmptyDocstringSection) { checker.report_diagnostic( EmptyDocstringSection { name: context.section_name().to_string(), @@ -1442,7 +1442,7 @@ fn blanks_and_section_underline( context.section_name_range(), ); } - } else if checker.enabled(Rule::BlankLinesBetweenHeaderAndContent) { + } else if checker.is_rule_enabled(Rule::BlankLinesBetweenHeaderAndContent) { // If the section is followed by exactly one line, and then a // reStructuredText directive, the blank lines should be preserved, as in: // @@ -1495,7 +1495,7 @@ fn blanks_and_section_underline( } } } else { - if checker.enabled(Rule::EmptyDocstringSection) { + if checker.is_rule_enabled(Rule::EmptyDocstringSection) { checker.report_diagnostic( EmptyDocstringSection { name: context.section_name().to_string(), @@ -1505,7 +1505,8 @@ fn blanks_and_section_underline( } } } else { - if style.is_numpy() && checker.enabled(Rule::MissingDashedUnderlineAfterSection) { + if style.is_numpy() && checker.is_rule_enabled(Rule::MissingDashedUnderlineAfterSection) + { if let Some(equal_line) = find_underline(&non_blank_line, '=') { let mut diagnostic = checker.report_diagnostic( MissingDashedUnderlineAfterSection { @@ -1542,7 +1543,7 @@ fn blanks_and_section_underline( } } if num_blank_lines_after_header > 0 { - if checker.enabled(Rule::BlankLinesBetweenHeaderAndContent) { + if checker.is_rule_enabled(Rule::BlankLinesBetweenHeaderAndContent) { // If the section is followed by exactly one line, and then a // reStructuredText directive, the blank lines should be preserved, as in: // @@ -1597,7 +1598,7 @@ fn blanks_and_section_underline( } } else { // Nothing but blank lines after the section header. - if style.is_numpy() && checker.enabled(Rule::MissingDashedUnderlineAfterSection) { + if style.is_numpy() && checker.is_rule_enabled(Rule::MissingDashedUnderlineAfterSection) { let mut diagnostic = checker.report_diagnostic( MissingDashedUnderlineAfterSection { name: context.section_name().to_string(), @@ -1617,7 +1618,7 @@ fn blanks_and_section_underline( context.summary_range().end(), ))); } - if checker.enabled(Rule::EmptyDocstringSection) { + if checker.is_rule_enabled(Rule::EmptyDocstringSection) { checker.report_diagnostic( EmptyDocstringSection { name: context.section_name().to_string(), @@ -1635,7 +1636,7 @@ fn common_section( next: Option<&SectionContext>, style: SectionStyle, ) { - if checker.enabled(Rule::NonCapitalizedSectionName) { + if checker.is_rule_enabled(Rule::NonCapitalizedSectionName) { let capitalized_section_name = context.kind().as_str(); if context.section_name() != capitalized_section_name { let section_range = context.section_name_range(); @@ -1654,7 +1655,7 @@ fn common_section( } } - if checker.enabled(Rule::OverindentedSection) { + if checker.is_rule_enabled(Rule::OverindentedSection) { let leading_space = leading_space(context.summary_line()); let docstring_indentation = docstring.compute_indentation(); if leading_space.len() > docstring_indentation.len() { @@ -1680,7 +1681,7 @@ fn common_section( let line_end = checker.stylist().line_ending().as_str(); if let Some(next) = next { - if checker.enabled(Rule::NoBlankLineAfterSection) { + if checker.is_rule_enabled(Rule::NoBlankLineAfterSection) { let num_blank_lines = context .following_lines() .rev() @@ -1704,7 +1705,7 @@ fn common_section( } else { // The first blank line is the line containing the closing triple quotes, so we need at // least two. - if checker.enabled(Rule::MissingBlankLineAfterLastSection) { + if checker.is_rule_enabled(Rule::MissingBlankLineAfterLastSection) { let num_blank_lines = context .following_lines() .rev() @@ -1740,7 +1741,7 @@ fn common_section( } } - if checker.enabled(Rule::NoBlankLineBeforeSection) { + if checker.is_rule_enabled(Rule::NoBlankLineBeforeSection) { if !context .previous_line() .is_some_and(|line| line.trim().is_empty()) @@ -1930,7 +1931,7 @@ fn numpy_section( ) { common_section(checker, docstring, context, next, SectionStyle::Numpy); - if checker.enabled(Rule::MissingNewLineAfterSectionName) { + if checker.is_rule_enabled(Rule::MissingNewLineAfterSectionName) { let suffix = context.summary_after_section_name(); if !suffix.is_empty() { @@ -1948,7 +1949,7 @@ fn numpy_section( } } - if checker.enabled(Rule::UndocumentedParam) { + if checker.is_rule_enabled(Rule::UndocumentedParam) { if matches!(context.kind(), SectionKind::Parameters) { parameters_section(checker, docstring, context); } @@ -1963,7 +1964,7 @@ fn google_section( ) { common_section(checker, docstring, context, next, SectionStyle::Google); - if checker.enabled(Rule::MissingSectionNameColon) { + if checker.is_rule_enabled(Rule::MissingSectionNameColon) { let suffix = context.summary_after_section_name(); if suffix != ":" { let mut diagnostic = checker.report_diagnostic( @@ -2003,7 +2004,7 @@ fn parse_google_sections( google_section(checker, docstring, &context, iterator.peek()); } - if checker.enabled(Rule::UndocumentedParam) { + if checker.is_rule_enabled(Rule::UndocumentedParam) { let mut has_args = false; let mut documented_args: FxHashSet = FxHashSet::default(); for section_context in section_contexts { diff --git a/crates/ruff_linter/src/rules/pyflakes/rules/repeated_keys.rs b/crates/ruff_linter/src/rules/pyflakes/rules/repeated_keys.rs index e769f1747c..0771b2ec72 100644 --- a/crates/ruff_linter/src/rules/pyflakes/rules/repeated_keys.rs +++ b/crates/ruff_linter/src/rules/pyflakes/rules/repeated_keys.rs @@ -176,7 +176,7 @@ pub(crate) fn repeated_keys(checker: &Checker, dict: &ast::ExprDict) { | Expr::EllipsisLiteral(_) | Expr::Tuple(_) | Expr::FString(_) => { - if checker.enabled(Rule::MultiValueRepeatedKeyLiteral) { + if checker.is_rule_enabled(Rule::MultiValueRepeatedKeyLiteral) { let mut diagnostic = checker.report_diagnostic( MultiValueRepeatedKeyLiteral { name: SourceCodeSnippet::from_str(checker.locator().slice(key)), @@ -209,7 +209,7 @@ pub(crate) fn repeated_keys(checker: &Checker, dict: &ast::ExprDict) { } } Expr::Name(_) => { - if checker.enabled(Rule::MultiValueRepeatedKeyVariable) { + if checker.is_rule_enabled(Rule::MultiValueRepeatedKeyVariable) { let mut diagnostic = checker.report_diagnostic( MultiValueRepeatedKeyVariable { name: SourceCodeSnippet::from_str(checker.locator().slice(key)), diff --git a/crates/ruff_linter/src/rules/pylint/rules/import_outside_top_level.rs b/crates/ruff_linter/src/rules/pylint/rules/import_outside_top_level.rs index 3464c26315..2bf244d273 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/import_outside_top_level.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/import_outside_top_level.rs @@ -64,7 +64,7 @@ pub(crate) fn import_outside_top_level(checker: &Checker, stmt: &Stmt) { // Check if any of the non-top-level imports are banned by TID253 // before emitting the diagnostic to avoid conflicts. - if checker.enabled(Rule::BannedModuleLevelImports) { + if checker.is_rule_enabled(Rule::BannedModuleLevelImports) { let mut all_aliases_banned = true; let mut has_alias = false; for (policy, node) in &BannedModuleImportPolicies::new(stmt, checker) { diff --git a/crates/ruff_linter/src/rules/pylint/rules/logging.rs b/crates/ruff_linter/src/rules/pylint/rules/logging.rs index 62eb28d7cc..f5a194d231 100644 --- a/crates/ruff_linter/src/rules/pylint/rules/logging.rs +++ b/crates/ruff_linter/src/rules/pylint/rules/logging.rs @@ -152,13 +152,13 @@ pub(crate) fn logging_call(checker: &Checker, call: &ast::ExprCall) { let num_message_args = call.arguments.args.len() - 1; let num_keywords = call.arguments.keywords.len(); - if checker.enabled(Rule::LoggingTooManyArgs) { + if checker.is_rule_enabled(Rule::LoggingTooManyArgs) { if summary.num_positional < num_message_args { checker.report_diagnostic(LoggingTooManyArgs, call.func.range()); } } - if checker.enabled(Rule::LoggingTooFewArgs) { + if checker.is_rule_enabled(Rule::LoggingTooFewArgs) { if num_message_args > 0 && num_keywords == 0 && summary.num_positional > num_message_args { checker.report_diagnostic(LoggingTooFewArgs, call.func.range()); } diff --git a/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_annotation.rs b/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_annotation.rs index 4cf3979775..54c923e768 100644 --- a/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_annotation.rs +++ b/crates/ruff_linter/src/rules/pyupgrade/rules/use_pep604_annotation.rs @@ -176,7 +176,7 @@ pub(crate) fn non_pep604_annotation( } } Pep604Operator::Union => { - if !checker.enabled(Rule::NonPEP604AnnotationUnion) { + if !checker.is_rule_enabled(Rule::NonPEP604AnnotationUnion) { return; } diff --git a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap index d4ea19a5df..b698180305 100644 --- a/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap +++ b/crates/ruff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__ruf100_2.snap @@ -1,8 +1,7 @@ --- source: crates/ruff_linter/src/rules/ruff/mod.rs -snapshot_kind: text --- -RUF100_2.py:1:19: RUF100 [*] Unused `noqa` directive (unused: `F401`) +RUF100_2.py:1:19: RUF100 [*] Unused `noqa` directive (non-enabled: `F401`) | 1 | import itertools # noqa: F401 | ^^^^^^^^^^^^ RUF100